Linux 3.12.28
[linux/fpc-iii.git] / fs / btrfs / inode.c
blobfa8010c1b628f2aa33ea5e817294f8c412eb4c4e
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/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
46 #include "compat.h"
47 #include "ctree.h"
48 #include "disk-io.h"
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "ordered-data.h"
53 #include "xattr.h"
54 #include "tree-log.h"
55 #include "volumes.h"
56 #include "compression.h"
57 #include "locking.h"
58 #include "free-space-cache.h"
59 #include "inode-map.h"
60 #include "backref.h"
61 #include "hash.h"
63 struct btrfs_iget_args {
64 u64 ino;
65 struct btrfs_root *root;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
85 #define S_SHIFT 12
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
88 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
89 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
90 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
91 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
92 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
93 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100 struct page *locked_page,
101 u64 start, u64 end, int *page_started,
102 unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104 u64 len, u64 orig_start,
105 u64 block_start, u64 block_len,
106 u64 orig_block_len, u64 ram_bytes,
107 int type);
109 static int btrfs_dirty_inode(struct inode *inode);
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112 struct inode *inode, struct inode *dir,
113 const struct qstr *qstr)
115 int err;
117 err = btrfs_init_acl(trans, inode, dir);
118 if (!err)
119 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
120 return err;
124 * this does all the hard work for inserting an inline extent into
125 * the btree. The caller should have done a btrfs_drop_extents so that
126 * no overlapping inline items exist in the btree
128 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_root *root, struct inode *inode,
130 u64 start, size_t size, size_t compressed_size,
131 int compress_type,
132 struct page **compressed_pages)
134 struct btrfs_key key;
135 struct btrfs_path *path;
136 struct extent_buffer *leaf;
137 struct page *page = NULL;
138 char *kaddr;
139 unsigned long ptr;
140 struct btrfs_file_extent_item *ei;
141 int err = 0;
142 int ret;
143 size_t cur_size = size;
144 size_t datasize;
145 unsigned long offset;
147 if (compressed_size && compressed_pages)
148 cur_size = compressed_size;
150 path = btrfs_alloc_path();
151 if (!path)
152 return -ENOMEM;
154 path->leave_spinning = 1;
156 key.objectid = btrfs_ino(inode);
157 key.offset = start;
158 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
159 datasize = btrfs_file_extent_calc_inline_size(cur_size);
161 inode_add_bytes(inode, size);
162 ret = btrfs_insert_empty_item(trans, root, path, &key,
163 datasize);
164 if (ret) {
165 err = ret;
166 goto fail;
168 leaf = path->nodes[0];
169 ei = btrfs_item_ptr(leaf, path->slots[0],
170 struct btrfs_file_extent_item);
171 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
172 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
173 btrfs_set_file_extent_encryption(leaf, ei, 0);
174 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
175 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
176 ptr = btrfs_file_extent_inline_start(ei);
178 if (compress_type != BTRFS_COMPRESS_NONE) {
179 struct page *cpage;
180 int i = 0;
181 while (compressed_size > 0) {
182 cpage = compressed_pages[i];
183 cur_size = min_t(unsigned long, compressed_size,
184 PAGE_CACHE_SIZE);
186 kaddr = kmap_atomic(cpage);
187 write_extent_buffer(leaf, kaddr, ptr, cur_size);
188 kunmap_atomic(kaddr);
190 i++;
191 ptr += cur_size;
192 compressed_size -= cur_size;
194 btrfs_set_file_extent_compression(leaf, ei,
195 compress_type);
196 } else {
197 page = find_get_page(inode->i_mapping,
198 start >> PAGE_CACHE_SHIFT);
199 btrfs_set_file_extent_compression(leaf, ei, 0);
200 kaddr = kmap_atomic(page);
201 offset = start & (PAGE_CACHE_SIZE - 1);
202 write_extent_buffer(leaf, kaddr + offset, ptr, size);
203 kunmap_atomic(kaddr);
204 page_cache_release(page);
206 btrfs_mark_buffer_dirty(leaf);
207 btrfs_free_path(path);
210 * we're an inline extent, so nobody can
211 * extend the file past i_size without locking
212 * a page we already have locked.
214 * We must do any isize and inode updates
215 * before we unlock the pages. Otherwise we
216 * could end up racing with unlink.
218 BTRFS_I(inode)->disk_i_size = inode->i_size;
219 ret = btrfs_update_inode(trans, root, inode);
221 return ret;
222 fail:
223 btrfs_free_path(path);
224 return err;
229 * conditionally insert an inline extent into the file. This
230 * does the checks required to make sure the data is small enough
231 * to fit as an inline extent.
233 static noinline int cow_file_range_inline(struct btrfs_root *root,
234 struct inode *inode, u64 start,
235 u64 end, size_t compressed_size,
236 int compress_type,
237 struct page **compressed_pages)
239 struct btrfs_trans_handle *trans;
240 u64 isize = i_size_read(inode);
241 u64 actual_end = min(end + 1, isize);
242 u64 inline_len = actual_end - start;
243 u64 aligned_end = ALIGN(end, root->sectorsize);
244 u64 data_len = inline_len;
245 int ret;
247 if (compressed_size)
248 data_len = compressed_size;
250 if (start > 0 ||
251 actual_end >= PAGE_CACHE_SIZE ||
252 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
253 (!compressed_size &&
254 (actual_end & (root->sectorsize - 1)) == 0) ||
255 end + 1 < isize ||
256 data_len > root->fs_info->max_inline) {
257 return 1;
260 trans = btrfs_join_transaction(root);
261 if (IS_ERR(trans))
262 return PTR_ERR(trans);
263 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
265 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
266 if (ret) {
267 btrfs_abort_transaction(trans, root, ret);
268 goto out;
271 if (isize > actual_end)
272 inline_len = min_t(u64, isize, actual_end);
273 ret = insert_inline_extent(trans, root, inode, start,
274 inline_len, compressed_size,
275 compress_type, compressed_pages);
276 if (ret && ret != -ENOSPC) {
277 btrfs_abort_transaction(trans, root, ret);
278 goto out;
279 } else if (ret == -ENOSPC) {
280 ret = 1;
281 goto out;
284 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
285 btrfs_delalloc_release_metadata(inode, end + 1 - start);
286 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
287 out:
288 btrfs_end_transaction(trans, root);
289 return ret;
292 struct async_extent {
293 u64 start;
294 u64 ram_size;
295 u64 compressed_size;
296 struct page **pages;
297 unsigned long nr_pages;
298 int compress_type;
299 struct list_head list;
302 struct async_cow {
303 struct inode *inode;
304 struct btrfs_root *root;
305 struct page *locked_page;
306 u64 start;
307 u64 end;
308 struct list_head extents;
309 struct btrfs_work work;
312 static noinline int add_async_extent(struct async_cow *cow,
313 u64 start, u64 ram_size,
314 u64 compressed_size,
315 struct page **pages,
316 unsigned long nr_pages,
317 int compress_type)
319 struct async_extent *async_extent;
321 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
322 BUG_ON(!async_extent); /* -ENOMEM */
323 async_extent->start = start;
324 async_extent->ram_size = ram_size;
325 async_extent->compressed_size = compressed_size;
326 async_extent->pages = pages;
327 async_extent->nr_pages = nr_pages;
328 async_extent->compress_type = compress_type;
329 list_add_tail(&async_extent->list, &cow->extents);
330 return 0;
334 * we create compressed extents in two phases. The first
335 * phase compresses a range of pages that have already been
336 * locked (both pages and state bits are locked).
338 * This is done inside an ordered work queue, and the compression
339 * is spread across many cpus. The actual IO submission is step
340 * two, and the ordered work queue takes care of making sure that
341 * happens in the same order things were put onto the queue by
342 * writepages and friends.
344 * If this code finds it can't get good compression, it puts an
345 * entry onto the work queue to write the uncompressed bytes. This
346 * makes sure that both compressed inodes and uncompressed inodes
347 * are written in the same order that the flusher thread sent them
348 * down.
350 static noinline int compress_file_range(struct inode *inode,
351 struct page *locked_page,
352 u64 start, u64 end,
353 struct async_cow *async_cow,
354 int *num_added)
356 struct btrfs_root *root = BTRFS_I(inode)->root;
357 u64 num_bytes;
358 u64 blocksize = root->sectorsize;
359 u64 actual_end;
360 u64 isize = i_size_read(inode);
361 int ret = 0;
362 struct page **pages = NULL;
363 unsigned long nr_pages;
364 unsigned long nr_pages_ret = 0;
365 unsigned long total_compressed = 0;
366 unsigned long total_in = 0;
367 unsigned long max_compressed = 128 * 1024;
368 unsigned long max_uncompressed = 128 * 1024;
369 int i;
370 int will_compress;
371 int compress_type = root->fs_info->compress_type;
372 int redirty = 0;
374 /* if this is a small write inside eof, kick off a defrag */
375 if ((end - start + 1) < 16 * 1024 &&
376 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
377 btrfs_add_inode_defrag(NULL, inode);
379 actual_end = min_t(u64, isize, end + 1);
380 again:
381 will_compress = 0;
382 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
383 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
386 * we don't want to send crud past the end of i_size through
387 * compression, that's just a waste of CPU time. So, if the
388 * end of the file is before the start of our current
389 * requested range of bytes, we bail out to the uncompressed
390 * cleanup code that can deal with all of this.
392 * It isn't really the fastest way to fix things, but this is a
393 * very uncommon corner.
395 if (actual_end <= start)
396 goto cleanup_and_bail_uncompressed;
398 total_compressed = actual_end - start;
400 /* we want to make sure that amount of ram required to uncompress
401 * an extent is reasonable, so we limit the total size in ram
402 * of a compressed extent to 128k. This is a crucial number
403 * because it also controls how easily we can spread reads across
404 * cpus for decompression.
406 * We also want to make sure the amount of IO required to do
407 * a random read is reasonably small, so we limit the size of
408 * a compressed extent to 128k.
410 total_compressed = min(total_compressed, max_uncompressed);
411 num_bytes = ALIGN(end - start + 1, blocksize);
412 num_bytes = max(blocksize, num_bytes);
413 total_in = 0;
414 ret = 0;
417 * we do compression for mount -o compress and when the
418 * inode has not been flagged as nocompress. This flag can
419 * change at any time if we discover bad compression ratios.
421 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
422 (btrfs_test_opt(root, COMPRESS) ||
423 (BTRFS_I(inode)->force_compress) ||
424 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
425 WARN_ON(pages);
426 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
427 if (!pages) {
428 /* just bail out to the uncompressed code */
429 goto cont;
432 if (BTRFS_I(inode)->force_compress)
433 compress_type = BTRFS_I(inode)->force_compress;
436 * we need to call clear_page_dirty_for_io on each
437 * page in the range. Otherwise applications with the file
438 * mmap'd can wander in and change the page contents while
439 * we are compressing them.
441 * If the compression fails for any reason, we set the pages
442 * dirty again later on.
444 extent_range_clear_dirty_for_io(inode, start, end);
445 redirty = 1;
446 ret = btrfs_compress_pages(compress_type,
447 inode->i_mapping, start,
448 total_compressed, pages,
449 nr_pages, &nr_pages_ret,
450 &total_in,
451 &total_compressed,
452 max_compressed);
454 if (!ret) {
455 unsigned long offset = total_compressed &
456 (PAGE_CACHE_SIZE - 1);
457 struct page *page = pages[nr_pages_ret - 1];
458 char *kaddr;
460 /* zero the tail end of the last page, we might be
461 * sending it down to disk
463 if (offset) {
464 kaddr = kmap_atomic(page);
465 memset(kaddr + offset, 0,
466 PAGE_CACHE_SIZE - offset);
467 kunmap_atomic(kaddr);
469 will_compress = 1;
472 cont:
473 if (start == 0) {
474 /* lets try to make an inline extent */
475 if (ret || total_in < (actual_end - start)) {
476 /* we didn't compress the entire range, try
477 * to make an uncompressed inline extent.
479 ret = cow_file_range_inline(root, inode, start, end,
480 0, 0, NULL);
481 } else {
482 /* try making a compressed inline extent */
483 ret = cow_file_range_inline(root, inode, start, end,
484 total_compressed,
485 compress_type, pages);
487 if (ret <= 0) {
488 unsigned long clear_flags = EXTENT_DELALLOC |
489 EXTENT_DEFRAG;
490 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
493 * inline extent creation worked or returned error,
494 * we don't need to create any more async work items.
495 * Unlock and free up our temp pages.
497 extent_clear_unlock_delalloc(inode, start, end, NULL,
498 clear_flags, PAGE_UNLOCK |
499 PAGE_CLEAR_DIRTY |
500 PAGE_SET_WRITEBACK |
501 PAGE_END_WRITEBACK);
502 goto free_pages_out;
506 if (will_compress) {
508 * we aren't doing an inline extent round the compressed size
509 * up to a block size boundary so the allocator does sane
510 * things
512 total_compressed = ALIGN(total_compressed, blocksize);
515 * one last check to make sure the compression is really a
516 * win, compare the page count read with the blocks on disk
518 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
519 if (total_compressed >= total_in) {
520 will_compress = 0;
521 } else {
522 num_bytes = total_in;
525 if (!will_compress && pages) {
527 * the compression code ran but failed to make things smaller,
528 * free any pages it allocated and our page pointer array
530 for (i = 0; i < nr_pages_ret; i++) {
531 WARN_ON(pages[i]->mapping);
532 page_cache_release(pages[i]);
534 kfree(pages);
535 pages = NULL;
536 total_compressed = 0;
537 nr_pages_ret = 0;
539 /* flag the file so we don't compress in the future */
540 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
541 !(BTRFS_I(inode)->force_compress)) {
542 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
545 if (will_compress) {
546 *num_added += 1;
548 /* the async work queues will take care of doing actual
549 * allocation on disk for these compressed pages,
550 * and will submit them to the elevator.
552 add_async_extent(async_cow, start, num_bytes,
553 total_compressed, pages, nr_pages_ret,
554 compress_type);
556 if (start + num_bytes < end) {
557 start += num_bytes;
558 pages = NULL;
559 cond_resched();
560 goto again;
562 } else {
563 cleanup_and_bail_uncompressed:
565 * No compression, but we still need to write the pages in
566 * the file we've been given so far. redirty the locked
567 * page if it corresponds to our extent and set things up
568 * for the async work queue to run cow_file_range to do
569 * the normal delalloc dance
571 if (page_offset(locked_page) >= start &&
572 page_offset(locked_page) <= end) {
573 __set_page_dirty_nobuffers(locked_page);
574 /* unlocked later on in the async handlers */
576 if (redirty)
577 extent_range_redirty_for_io(inode, start, end);
578 add_async_extent(async_cow, start, end - start + 1,
579 0, NULL, 0, BTRFS_COMPRESS_NONE);
580 *num_added += 1;
583 out:
584 return ret;
586 free_pages_out:
587 for (i = 0; i < nr_pages_ret; i++) {
588 WARN_ON(pages[i]->mapping);
589 page_cache_release(pages[i]);
591 kfree(pages);
593 goto out;
597 * phase two of compressed writeback. This is the ordered portion
598 * of the code, which only gets called in the order the work was
599 * queued. We walk all the async extents created by compress_file_range
600 * and send them down to the disk.
602 static noinline int submit_compressed_extents(struct inode *inode,
603 struct async_cow *async_cow)
605 struct async_extent *async_extent;
606 u64 alloc_hint = 0;
607 struct btrfs_key ins;
608 struct extent_map *em;
609 struct btrfs_root *root = BTRFS_I(inode)->root;
610 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
611 struct extent_io_tree *io_tree;
612 int ret = 0;
614 if (list_empty(&async_cow->extents))
615 return 0;
617 again:
618 while (!list_empty(&async_cow->extents)) {
619 async_extent = list_entry(async_cow->extents.next,
620 struct async_extent, list);
621 list_del(&async_extent->list);
623 io_tree = &BTRFS_I(inode)->io_tree;
625 retry:
626 /* did the compression code fall back to uncompressed IO? */
627 if (!async_extent->pages) {
628 int page_started = 0;
629 unsigned long nr_written = 0;
631 lock_extent(io_tree, async_extent->start,
632 async_extent->start +
633 async_extent->ram_size - 1);
635 /* allocate blocks */
636 ret = cow_file_range(inode, async_cow->locked_page,
637 async_extent->start,
638 async_extent->start +
639 async_extent->ram_size - 1,
640 &page_started, &nr_written, 0);
642 /* JDM XXX */
645 * if page_started, cow_file_range inserted an
646 * inline extent and took care of all the unlocking
647 * and IO for us. Otherwise, we need to submit
648 * all those pages down to the drive.
650 if (!page_started && !ret)
651 extent_write_locked_range(io_tree,
652 inode, async_extent->start,
653 async_extent->start +
654 async_extent->ram_size - 1,
655 btrfs_get_extent,
656 WB_SYNC_ALL);
657 else if (ret)
658 unlock_page(async_cow->locked_page);
659 kfree(async_extent);
660 cond_resched();
661 continue;
664 lock_extent(io_tree, async_extent->start,
665 async_extent->start + async_extent->ram_size - 1);
667 ret = btrfs_reserve_extent(root,
668 async_extent->compressed_size,
669 async_extent->compressed_size,
670 0, alloc_hint, &ins, 1);
671 if (ret) {
672 int i;
674 for (i = 0; i < async_extent->nr_pages; i++) {
675 WARN_ON(async_extent->pages[i]->mapping);
676 page_cache_release(async_extent->pages[i]);
678 kfree(async_extent->pages);
679 async_extent->nr_pages = 0;
680 async_extent->pages = NULL;
682 if (ret == -ENOSPC) {
683 unlock_extent(io_tree, async_extent->start,
684 async_extent->start +
685 async_extent->ram_size - 1);
686 goto retry;
688 goto out_free;
692 * here we're doing allocation and writeback of the
693 * compressed pages
695 btrfs_drop_extent_cache(inode, async_extent->start,
696 async_extent->start +
697 async_extent->ram_size - 1, 0);
699 em = alloc_extent_map();
700 if (!em) {
701 ret = -ENOMEM;
702 goto out_free_reserve;
704 em->start = async_extent->start;
705 em->len = async_extent->ram_size;
706 em->orig_start = em->start;
707 em->mod_start = em->start;
708 em->mod_len = em->len;
710 em->block_start = ins.objectid;
711 em->block_len = ins.offset;
712 em->orig_block_len = ins.offset;
713 em->ram_bytes = async_extent->ram_size;
714 em->bdev = root->fs_info->fs_devices->latest_bdev;
715 em->compress_type = async_extent->compress_type;
716 set_bit(EXTENT_FLAG_PINNED, &em->flags);
717 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
718 em->generation = -1;
720 while (1) {
721 write_lock(&em_tree->lock);
722 ret = add_extent_mapping(em_tree, em, 1);
723 write_unlock(&em_tree->lock);
724 if (ret != -EEXIST) {
725 free_extent_map(em);
726 break;
728 btrfs_drop_extent_cache(inode, async_extent->start,
729 async_extent->start +
730 async_extent->ram_size - 1, 0);
733 if (ret)
734 goto out_free_reserve;
736 ret = btrfs_add_ordered_extent_compress(inode,
737 async_extent->start,
738 ins.objectid,
739 async_extent->ram_size,
740 ins.offset,
741 BTRFS_ORDERED_COMPRESSED,
742 async_extent->compress_type);
743 if (ret)
744 goto out_free_reserve;
747 * clear dirty, set writeback and unlock the pages.
749 extent_clear_unlock_delalloc(inode, async_extent->start,
750 async_extent->start +
751 async_extent->ram_size - 1,
752 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
753 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
754 PAGE_SET_WRITEBACK);
755 ret = btrfs_submit_compressed_write(inode,
756 async_extent->start,
757 async_extent->ram_size,
758 ins.objectid,
759 ins.offset, async_extent->pages,
760 async_extent->nr_pages);
761 alloc_hint = ins.objectid + ins.offset;
762 kfree(async_extent);
763 if (ret)
764 goto out;
765 cond_resched();
767 ret = 0;
768 out:
769 return ret;
770 out_free_reserve:
771 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
772 out_free:
773 extent_clear_unlock_delalloc(inode, async_extent->start,
774 async_extent->start +
775 async_extent->ram_size - 1,
776 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
777 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
778 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
779 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
780 kfree(async_extent);
781 goto again;
784 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
785 u64 num_bytes)
787 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
788 struct extent_map *em;
789 u64 alloc_hint = 0;
791 read_lock(&em_tree->lock);
792 em = search_extent_mapping(em_tree, start, num_bytes);
793 if (em) {
795 * if block start isn't an actual block number then find the
796 * first block in this inode and use that as a hint. If that
797 * block is also bogus then just don't worry about it.
799 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
800 free_extent_map(em);
801 em = search_extent_mapping(em_tree, 0, 0);
802 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
803 alloc_hint = em->block_start;
804 if (em)
805 free_extent_map(em);
806 } else {
807 alloc_hint = em->block_start;
808 free_extent_map(em);
811 read_unlock(&em_tree->lock);
813 return alloc_hint;
817 * when extent_io.c finds a delayed allocation range in the file,
818 * the call backs end up in this code. The basic idea is to
819 * allocate extents on disk for the range, and create ordered data structs
820 * in ram to track those extents.
822 * locked_page is the page that writepage had locked already. We use
823 * it to make sure we don't do extra locks or unlocks.
825 * *page_started is set to one if we unlock locked_page and do everything
826 * required to start IO on it. It may be clean and already done with
827 * IO when we return.
829 static noinline int cow_file_range(struct inode *inode,
830 struct page *locked_page,
831 u64 start, u64 end, int *page_started,
832 unsigned long *nr_written,
833 int unlock)
835 struct btrfs_root *root = BTRFS_I(inode)->root;
836 u64 alloc_hint = 0;
837 u64 num_bytes;
838 unsigned long ram_size;
839 u64 disk_num_bytes;
840 u64 cur_alloc_size;
841 u64 blocksize = root->sectorsize;
842 struct btrfs_key ins;
843 struct extent_map *em;
844 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
845 int ret = 0;
847 BUG_ON(btrfs_is_free_space_inode(inode));
849 num_bytes = ALIGN(end - start + 1, blocksize);
850 num_bytes = max(blocksize, num_bytes);
851 disk_num_bytes = num_bytes;
853 /* if this is a small write inside eof, kick off defrag */
854 if (num_bytes < 64 * 1024 &&
855 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
856 btrfs_add_inode_defrag(NULL, inode);
858 if (start == 0) {
859 /* lets try to make an inline extent */
860 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
861 NULL);
862 if (ret == 0) {
863 extent_clear_unlock_delalloc(inode, start, end, NULL,
864 EXTENT_LOCKED | EXTENT_DELALLOC |
865 EXTENT_DEFRAG, PAGE_UNLOCK |
866 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
867 PAGE_END_WRITEBACK);
869 *nr_written = *nr_written +
870 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
871 *page_started = 1;
872 goto out;
873 } else if (ret < 0) {
874 goto out_unlock;
878 BUG_ON(disk_num_bytes >
879 btrfs_super_total_bytes(root->fs_info->super_copy));
881 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
882 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
884 while (disk_num_bytes > 0) {
885 unsigned long op;
887 cur_alloc_size = disk_num_bytes;
888 ret = btrfs_reserve_extent(root, cur_alloc_size,
889 root->sectorsize, 0, alloc_hint,
890 &ins, 1);
891 if (ret < 0)
892 goto out_unlock;
894 em = alloc_extent_map();
895 if (!em) {
896 ret = -ENOMEM;
897 goto out_reserve;
899 em->start = start;
900 em->orig_start = em->start;
901 ram_size = ins.offset;
902 em->len = ins.offset;
903 em->mod_start = em->start;
904 em->mod_len = em->len;
906 em->block_start = ins.objectid;
907 em->block_len = ins.offset;
908 em->orig_block_len = ins.offset;
909 em->ram_bytes = ram_size;
910 em->bdev = root->fs_info->fs_devices->latest_bdev;
911 set_bit(EXTENT_FLAG_PINNED, &em->flags);
912 em->generation = -1;
914 while (1) {
915 write_lock(&em_tree->lock);
916 ret = add_extent_mapping(em_tree, em, 1);
917 write_unlock(&em_tree->lock);
918 if (ret != -EEXIST) {
919 free_extent_map(em);
920 break;
922 btrfs_drop_extent_cache(inode, start,
923 start + ram_size - 1, 0);
925 if (ret)
926 goto out_reserve;
928 cur_alloc_size = ins.offset;
929 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
930 ram_size, cur_alloc_size, 0);
931 if (ret)
932 goto out_reserve;
934 if (root->root_key.objectid ==
935 BTRFS_DATA_RELOC_TREE_OBJECTID) {
936 ret = btrfs_reloc_clone_csums(inode, start,
937 cur_alloc_size);
938 if (ret)
939 goto out_reserve;
942 if (disk_num_bytes < cur_alloc_size)
943 break;
945 /* we're not doing compressed IO, don't unlock the first
946 * page (which the caller expects to stay locked), don't
947 * clear any dirty bits and don't set any writeback bits
949 * Do set the Private2 bit so we know this page was properly
950 * setup for writepage
952 op = unlock ? PAGE_UNLOCK : 0;
953 op |= PAGE_SET_PRIVATE2;
955 extent_clear_unlock_delalloc(inode, start,
956 start + ram_size - 1, locked_page,
957 EXTENT_LOCKED | EXTENT_DELALLOC,
958 op);
959 disk_num_bytes -= cur_alloc_size;
960 num_bytes -= cur_alloc_size;
961 alloc_hint = ins.objectid + ins.offset;
962 start += cur_alloc_size;
964 out:
965 return ret;
967 out_reserve:
968 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
969 out_unlock:
970 extent_clear_unlock_delalloc(inode, start, end, locked_page,
971 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
972 EXTENT_DELALLOC | EXTENT_DEFRAG,
973 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
974 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
975 goto out;
979 * work queue call back to started compression on a file and pages
981 static noinline void async_cow_start(struct btrfs_work *work)
983 struct async_cow *async_cow;
984 int num_added = 0;
985 async_cow = container_of(work, struct async_cow, work);
987 compress_file_range(async_cow->inode, async_cow->locked_page,
988 async_cow->start, async_cow->end, async_cow,
989 &num_added);
990 if (num_added == 0) {
991 btrfs_add_delayed_iput(async_cow->inode);
992 async_cow->inode = NULL;
997 * work queue call back to submit previously compressed pages
999 static noinline void async_cow_submit(struct btrfs_work *work)
1001 struct async_cow *async_cow;
1002 struct btrfs_root *root;
1003 unsigned long nr_pages;
1005 async_cow = container_of(work, struct async_cow, work);
1007 root = async_cow->root;
1008 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1009 PAGE_CACHE_SHIFT;
1011 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1012 5 * 1024 * 1024 &&
1013 waitqueue_active(&root->fs_info->async_submit_wait))
1014 wake_up(&root->fs_info->async_submit_wait);
1016 if (async_cow->inode)
1017 submit_compressed_extents(async_cow->inode, async_cow);
1020 static noinline void async_cow_free(struct btrfs_work *work)
1022 struct async_cow *async_cow;
1023 async_cow = container_of(work, struct async_cow, work);
1024 if (async_cow->inode)
1025 btrfs_add_delayed_iput(async_cow->inode);
1026 kfree(async_cow);
1029 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1030 u64 start, u64 end, int *page_started,
1031 unsigned long *nr_written)
1033 struct async_cow *async_cow;
1034 struct btrfs_root *root = BTRFS_I(inode)->root;
1035 unsigned long nr_pages;
1036 u64 cur_end;
1037 int limit = 10 * 1024 * 1024;
1039 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1040 1, 0, NULL, GFP_NOFS);
1041 while (start < end) {
1042 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1043 BUG_ON(!async_cow); /* -ENOMEM */
1044 async_cow->inode = igrab(inode);
1045 async_cow->root = root;
1046 async_cow->locked_page = locked_page;
1047 async_cow->start = start;
1049 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1050 cur_end = end;
1051 else
1052 cur_end = min(end, start + 512 * 1024 - 1);
1054 async_cow->end = cur_end;
1055 INIT_LIST_HEAD(&async_cow->extents);
1057 async_cow->work.func = async_cow_start;
1058 async_cow->work.ordered_func = async_cow_submit;
1059 async_cow->work.ordered_free = async_cow_free;
1060 async_cow->work.flags = 0;
1062 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1063 PAGE_CACHE_SHIFT;
1064 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1066 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1067 &async_cow->work);
1069 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1070 wait_event(root->fs_info->async_submit_wait,
1071 (atomic_read(&root->fs_info->async_delalloc_pages) <
1072 limit));
1075 while (atomic_read(&root->fs_info->async_submit_draining) &&
1076 atomic_read(&root->fs_info->async_delalloc_pages)) {
1077 wait_event(root->fs_info->async_submit_wait,
1078 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1079 0));
1082 *nr_written += nr_pages;
1083 start = cur_end + 1;
1085 *page_started = 1;
1086 return 0;
1089 static noinline int csum_exist_in_range(struct btrfs_root *root,
1090 u64 bytenr, u64 num_bytes)
1092 int ret;
1093 struct btrfs_ordered_sum *sums;
1094 LIST_HEAD(list);
1096 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1097 bytenr + num_bytes - 1, &list, 0);
1098 if (ret == 0 && list_empty(&list))
1099 return 0;
1101 while (!list_empty(&list)) {
1102 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1103 list_del(&sums->list);
1104 kfree(sums);
1106 return 1;
1110 * when nowcow writeback call back. This checks for snapshots or COW copies
1111 * of the extents that exist in the file, and COWs the file as required.
1113 * If no cow copies or snapshots exist, we write directly to the existing
1114 * blocks on disk
1116 static noinline int run_delalloc_nocow(struct inode *inode,
1117 struct page *locked_page,
1118 u64 start, u64 end, int *page_started, int force,
1119 unsigned long *nr_written)
1121 struct btrfs_root *root = BTRFS_I(inode)->root;
1122 struct btrfs_trans_handle *trans;
1123 struct extent_buffer *leaf;
1124 struct btrfs_path *path;
1125 struct btrfs_file_extent_item *fi;
1126 struct btrfs_key found_key;
1127 u64 cow_start;
1128 u64 cur_offset;
1129 u64 extent_end;
1130 u64 extent_offset;
1131 u64 disk_bytenr;
1132 u64 num_bytes;
1133 u64 disk_num_bytes;
1134 u64 ram_bytes;
1135 int extent_type;
1136 int ret, err;
1137 int type;
1138 int nocow;
1139 int check_prev = 1;
1140 bool nolock;
1141 u64 ino = btrfs_ino(inode);
1143 path = btrfs_alloc_path();
1144 if (!path) {
1145 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1146 EXTENT_LOCKED | EXTENT_DELALLOC |
1147 EXTENT_DO_ACCOUNTING |
1148 EXTENT_DEFRAG, PAGE_UNLOCK |
1149 PAGE_CLEAR_DIRTY |
1150 PAGE_SET_WRITEBACK |
1151 PAGE_END_WRITEBACK);
1152 return -ENOMEM;
1155 nolock = btrfs_is_free_space_inode(inode);
1157 if (nolock)
1158 trans = btrfs_join_transaction_nolock(root);
1159 else
1160 trans = btrfs_join_transaction(root);
1162 if (IS_ERR(trans)) {
1163 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1164 EXTENT_LOCKED | EXTENT_DELALLOC |
1165 EXTENT_DO_ACCOUNTING |
1166 EXTENT_DEFRAG, PAGE_UNLOCK |
1167 PAGE_CLEAR_DIRTY |
1168 PAGE_SET_WRITEBACK |
1169 PAGE_END_WRITEBACK);
1170 btrfs_free_path(path);
1171 return PTR_ERR(trans);
1174 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1176 cow_start = (u64)-1;
1177 cur_offset = start;
1178 while (1) {
1179 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1180 cur_offset, 0);
1181 if (ret < 0) {
1182 btrfs_abort_transaction(trans, root, ret);
1183 goto error;
1185 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1186 leaf = path->nodes[0];
1187 btrfs_item_key_to_cpu(leaf, &found_key,
1188 path->slots[0] - 1);
1189 if (found_key.objectid == ino &&
1190 found_key.type == BTRFS_EXTENT_DATA_KEY)
1191 path->slots[0]--;
1193 check_prev = 0;
1194 next_slot:
1195 leaf = path->nodes[0];
1196 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1197 ret = btrfs_next_leaf(root, path);
1198 if (ret < 0) {
1199 btrfs_abort_transaction(trans, root, ret);
1200 goto error;
1202 if (ret > 0)
1203 break;
1204 leaf = path->nodes[0];
1207 nocow = 0;
1208 disk_bytenr = 0;
1209 num_bytes = 0;
1210 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1212 if (found_key.objectid > ino ||
1213 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1214 found_key.offset > end)
1215 break;
1217 if (found_key.offset > cur_offset) {
1218 extent_end = found_key.offset;
1219 extent_type = 0;
1220 goto out_check;
1223 fi = btrfs_item_ptr(leaf, path->slots[0],
1224 struct btrfs_file_extent_item);
1225 extent_type = btrfs_file_extent_type(leaf, fi);
1227 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1228 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1229 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1230 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1231 extent_offset = btrfs_file_extent_offset(leaf, fi);
1232 extent_end = found_key.offset +
1233 btrfs_file_extent_num_bytes(leaf, fi);
1234 disk_num_bytes =
1235 btrfs_file_extent_disk_num_bytes(leaf, fi);
1236 if (extent_end <= start) {
1237 path->slots[0]++;
1238 goto next_slot;
1240 if (disk_bytenr == 0)
1241 goto out_check;
1242 if (btrfs_file_extent_compression(leaf, fi) ||
1243 btrfs_file_extent_encryption(leaf, fi) ||
1244 btrfs_file_extent_other_encoding(leaf, fi))
1245 goto out_check;
1246 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1247 goto out_check;
1248 if (btrfs_extent_readonly(root, disk_bytenr))
1249 goto out_check;
1250 if (btrfs_cross_ref_exist(trans, root, ino,
1251 found_key.offset -
1252 extent_offset, disk_bytenr))
1253 goto out_check;
1254 disk_bytenr += extent_offset;
1255 disk_bytenr += cur_offset - found_key.offset;
1256 num_bytes = min(end + 1, extent_end) - cur_offset;
1258 * force cow if csum exists in the range.
1259 * this ensure that csum for a given extent are
1260 * either valid or do not exist.
1262 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1263 goto out_check;
1264 nocow = 1;
1265 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1266 extent_end = found_key.offset +
1267 btrfs_file_extent_inline_len(leaf, fi);
1268 extent_end = ALIGN(extent_end, root->sectorsize);
1269 } else {
1270 BUG_ON(1);
1272 out_check:
1273 if (extent_end <= start) {
1274 path->slots[0]++;
1275 goto next_slot;
1277 if (!nocow) {
1278 if (cow_start == (u64)-1)
1279 cow_start = cur_offset;
1280 cur_offset = extent_end;
1281 if (cur_offset > end)
1282 break;
1283 path->slots[0]++;
1284 goto next_slot;
1287 btrfs_release_path(path);
1288 if (cow_start != (u64)-1) {
1289 ret = cow_file_range(inode, locked_page,
1290 cow_start, found_key.offset - 1,
1291 page_started, nr_written, 1);
1292 if (ret) {
1293 btrfs_abort_transaction(trans, root, ret);
1294 goto error;
1296 cow_start = (u64)-1;
1299 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1300 struct extent_map *em;
1301 struct extent_map_tree *em_tree;
1302 em_tree = &BTRFS_I(inode)->extent_tree;
1303 em = alloc_extent_map();
1304 BUG_ON(!em); /* -ENOMEM */
1305 em->start = cur_offset;
1306 em->orig_start = found_key.offset - extent_offset;
1307 em->len = num_bytes;
1308 em->block_len = num_bytes;
1309 em->block_start = disk_bytenr;
1310 em->orig_block_len = disk_num_bytes;
1311 em->ram_bytes = ram_bytes;
1312 em->bdev = root->fs_info->fs_devices->latest_bdev;
1313 em->mod_start = em->start;
1314 em->mod_len = em->len;
1315 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1316 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1317 em->generation = -1;
1318 while (1) {
1319 write_lock(&em_tree->lock);
1320 ret = add_extent_mapping(em_tree, em, 1);
1321 write_unlock(&em_tree->lock);
1322 if (ret != -EEXIST) {
1323 free_extent_map(em);
1324 break;
1326 btrfs_drop_extent_cache(inode, em->start,
1327 em->start + em->len - 1, 0);
1329 type = BTRFS_ORDERED_PREALLOC;
1330 } else {
1331 type = BTRFS_ORDERED_NOCOW;
1334 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1335 num_bytes, num_bytes, type);
1336 BUG_ON(ret); /* -ENOMEM */
1338 if (root->root_key.objectid ==
1339 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1340 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1341 num_bytes);
1342 if (ret) {
1343 btrfs_abort_transaction(trans, root, ret);
1344 goto error;
1348 extent_clear_unlock_delalloc(inode, cur_offset,
1349 cur_offset + num_bytes - 1,
1350 locked_page, EXTENT_LOCKED |
1351 EXTENT_DELALLOC, PAGE_UNLOCK |
1352 PAGE_SET_PRIVATE2);
1353 cur_offset = extent_end;
1354 if (cur_offset > end)
1355 break;
1357 btrfs_release_path(path);
1359 if (cur_offset <= end && cow_start == (u64)-1) {
1360 cow_start = cur_offset;
1361 cur_offset = end;
1364 if (cow_start != (u64)-1) {
1365 ret = cow_file_range(inode, locked_page, cow_start, end,
1366 page_started, nr_written, 1);
1367 if (ret) {
1368 btrfs_abort_transaction(trans, root, ret);
1369 goto error;
1373 error:
1374 err = btrfs_end_transaction(trans, root);
1375 if (!ret)
1376 ret = err;
1378 if (ret && cur_offset < end)
1379 extent_clear_unlock_delalloc(inode, cur_offset, end,
1380 locked_page, EXTENT_LOCKED |
1381 EXTENT_DELALLOC | EXTENT_DEFRAG |
1382 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1383 PAGE_CLEAR_DIRTY |
1384 PAGE_SET_WRITEBACK |
1385 PAGE_END_WRITEBACK);
1386 btrfs_free_path(path);
1387 return ret;
1391 * extent_io.c call back to do delayed allocation processing
1393 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1394 u64 start, u64 end, int *page_started,
1395 unsigned long *nr_written)
1397 int ret;
1398 struct btrfs_root *root = BTRFS_I(inode)->root;
1400 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1401 ret = run_delalloc_nocow(inode, locked_page, start, end,
1402 page_started, 1, nr_written);
1403 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1404 ret = run_delalloc_nocow(inode, locked_page, start, end,
1405 page_started, 0, nr_written);
1406 } else if (!btrfs_test_opt(root, COMPRESS) &&
1407 !(BTRFS_I(inode)->force_compress) &&
1408 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1409 ret = cow_file_range(inode, locked_page, start, end,
1410 page_started, nr_written, 1);
1411 } else {
1412 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1413 &BTRFS_I(inode)->runtime_flags);
1414 ret = cow_file_range_async(inode, locked_page, start, end,
1415 page_started, nr_written);
1417 return ret;
1420 static void btrfs_split_extent_hook(struct inode *inode,
1421 struct extent_state *orig, u64 split)
1423 /* not delalloc, ignore it */
1424 if (!(orig->state & EXTENT_DELALLOC))
1425 return;
1427 spin_lock(&BTRFS_I(inode)->lock);
1428 BTRFS_I(inode)->outstanding_extents++;
1429 spin_unlock(&BTRFS_I(inode)->lock);
1433 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1434 * extents so we can keep track of new extents that are just merged onto old
1435 * extents, such as when we are doing sequential writes, so we can properly
1436 * account for the metadata space we'll need.
1438 static void btrfs_merge_extent_hook(struct inode *inode,
1439 struct extent_state *new,
1440 struct extent_state *other)
1442 /* not delalloc, ignore it */
1443 if (!(other->state & EXTENT_DELALLOC))
1444 return;
1446 spin_lock(&BTRFS_I(inode)->lock);
1447 BTRFS_I(inode)->outstanding_extents--;
1448 spin_unlock(&BTRFS_I(inode)->lock);
1451 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1452 struct inode *inode)
1454 spin_lock(&root->delalloc_lock);
1455 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1456 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1457 &root->delalloc_inodes);
1458 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1459 &BTRFS_I(inode)->runtime_flags);
1460 root->nr_delalloc_inodes++;
1461 if (root->nr_delalloc_inodes == 1) {
1462 spin_lock(&root->fs_info->delalloc_root_lock);
1463 BUG_ON(!list_empty(&root->delalloc_root));
1464 list_add_tail(&root->delalloc_root,
1465 &root->fs_info->delalloc_roots);
1466 spin_unlock(&root->fs_info->delalloc_root_lock);
1469 spin_unlock(&root->delalloc_lock);
1472 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1473 struct inode *inode)
1475 spin_lock(&root->delalloc_lock);
1476 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1477 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1478 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1479 &BTRFS_I(inode)->runtime_flags);
1480 root->nr_delalloc_inodes--;
1481 if (!root->nr_delalloc_inodes) {
1482 spin_lock(&root->fs_info->delalloc_root_lock);
1483 BUG_ON(list_empty(&root->delalloc_root));
1484 list_del_init(&root->delalloc_root);
1485 spin_unlock(&root->fs_info->delalloc_root_lock);
1488 spin_unlock(&root->delalloc_lock);
1492 * extent_io.c set_bit_hook, used to track delayed allocation
1493 * bytes in this file, and to maintain the list of inodes that
1494 * have pending delalloc work to be done.
1496 static void btrfs_set_bit_hook(struct inode *inode,
1497 struct extent_state *state, unsigned long *bits)
1501 * set_bit and clear bit hooks normally require _irqsave/restore
1502 * but in this case, we are only testing for the DELALLOC
1503 * bit, which is only set or cleared with irqs on
1505 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1506 struct btrfs_root *root = BTRFS_I(inode)->root;
1507 u64 len = state->end + 1 - state->start;
1508 bool do_list = !btrfs_is_free_space_inode(inode);
1510 if (*bits & EXTENT_FIRST_DELALLOC) {
1511 *bits &= ~EXTENT_FIRST_DELALLOC;
1512 } else {
1513 spin_lock(&BTRFS_I(inode)->lock);
1514 BTRFS_I(inode)->outstanding_extents++;
1515 spin_unlock(&BTRFS_I(inode)->lock);
1518 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1519 root->fs_info->delalloc_batch);
1520 spin_lock(&BTRFS_I(inode)->lock);
1521 BTRFS_I(inode)->delalloc_bytes += len;
1522 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1523 &BTRFS_I(inode)->runtime_flags))
1524 btrfs_add_delalloc_inodes(root, inode);
1525 spin_unlock(&BTRFS_I(inode)->lock);
1530 * extent_io.c clear_bit_hook, see set_bit_hook for why
1532 static void btrfs_clear_bit_hook(struct inode *inode,
1533 struct extent_state *state,
1534 unsigned long *bits)
1537 * set_bit and clear bit hooks normally require _irqsave/restore
1538 * but in this case, we are only testing for the DELALLOC
1539 * bit, which is only set or cleared with irqs on
1541 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1542 struct btrfs_root *root = BTRFS_I(inode)->root;
1543 u64 len = state->end + 1 - state->start;
1544 bool do_list = !btrfs_is_free_space_inode(inode);
1546 if (*bits & EXTENT_FIRST_DELALLOC) {
1547 *bits &= ~EXTENT_FIRST_DELALLOC;
1548 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1549 spin_lock(&BTRFS_I(inode)->lock);
1550 BTRFS_I(inode)->outstanding_extents--;
1551 spin_unlock(&BTRFS_I(inode)->lock);
1555 * We don't reserve metadata space for space cache inodes so we
1556 * don't need to call dellalloc_release_metadata if there is an
1557 * error.
1559 if (*bits & EXTENT_DO_ACCOUNTING &&
1560 root != root->fs_info->tree_root)
1561 btrfs_delalloc_release_metadata(inode, len);
1563 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1564 && do_list && !(state->state & EXTENT_NORESERVE))
1565 btrfs_free_reserved_data_space(inode, len);
1567 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1568 root->fs_info->delalloc_batch);
1569 spin_lock(&BTRFS_I(inode)->lock);
1570 BTRFS_I(inode)->delalloc_bytes -= len;
1571 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1572 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1573 &BTRFS_I(inode)->runtime_flags))
1574 btrfs_del_delalloc_inode(root, inode);
1575 spin_unlock(&BTRFS_I(inode)->lock);
1580 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1581 * we don't create bios that span stripes or chunks
1583 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1584 size_t size, struct bio *bio,
1585 unsigned long bio_flags)
1587 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1588 u64 logical = (u64)bio->bi_sector << 9;
1589 u64 length = 0;
1590 u64 map_length;
1591 int ret;
1593 if (bio_flags & EXTENT_BIO_COMPRESSED)
1594 return 0;
1596 length = bio->bi_size;
1597 map_length = length;
1598 ret = btrfs_map_block(root->fs_info, rw, logical,
1599 &map_length, NULL, 0);
1600 /* Will always return 0 with map_multi == NULL */
1601 BUG_ON(ret < 0);
1602 if (map_length < length + size)
1603 return 1;
1604 return 0;
1608 * in order to insert checksums into the metadata in large chunks,
1609 * we wait until bio submission time. All the pages in the bio are
1610 * checksummed and sums are attached onto the ordered extent record.
1612 * At IO completion time the cums attached on the ordered extent record
1613 * are inserted into the btree
1615 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1616 struct bio *bio, int mirror_num,
1617 unsigned long bio_flags,
1618 u64 bio_offset)
1620 struct btrfs_root *root = BTRFS_I(inode)->root;
1621 int ret = 0;
1623 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1624 BUG_ON(ret); /* -ENOMEM */
1625 return 0;
1629 * in order to insert checksums into the metadata in large chunks,
1630 * we wait until bio submission time. All the pages in the bio are
1631 * checksummed and sums are attached onto the ordered extent record.
1633 * At IO completion time the cums attached on the ordered extent record
1634 * are inserted into the btree
1636 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1637 int mirror_num, unsigned long bio_flags,
1638 u64 bio_offset)
1640 struct btrfs_root *root = BTRFS_I(inode)->root;
1641 int ret;
1643 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1644 if (ret)
1645 bio_endio(bio, ret);
1646 return ret;
1650 * extent_io.c submission hook. This does the right thing for csum calculation
1651 * on write, or reading the csums from the tree before a read
1653 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1654 int mirror_num, unsigned long bio_flags,
1655 u64 bio_offset)
1657 struct btrfs_root *root = BTRFS_I(inode)->root;
1658 int ret = 0;
1659 int skip_sum;
1660 int metadata = 0;
1661 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1663 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1665 if (btrfs_is_free_space_inode(inode))
1666 metadata = 2;
1668 if (!(rw & REQ_WRITE)) {
1669 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1670 if (ret)
1671 goto out;
1673 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1674 ret = btrfs_submit_compressed_read(inode, bio,
1675 mirror_num,
1676 bio_flags);
1677 goto out;
1678 } else if (!skip_sum) {
1679 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1680 if (ret)
1681 goto out;
1683 goto mapit;
1684 } else if (async && !skip_sum) {
1685 /* csum items have already been cloned */
1686 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1687 goto mapit;
1688 /* we're doing a write, do the async checksumming */
1689 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1690 inode, rw, bio, mirror_num,
1691 bio_flags, bio_offset,
1692 __btrfs_submit_bio_start,
1693 __btrfs_submit_bio_done);
1694 goto out;
1695 } else if (!skip_sum) {
1696 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1697 if (ret)
1698 goto out;
1701 mapit:
1702 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1704 out:
1705 if (ret < 0)
1706 bio_endio(bio, ret);
1707 return ret;
1711 * given a list of ordered sums record them in the inode. This happens
1712 * at IO completion time based on sums calculated at bio submission time.
1714 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1715 struct inode *inode, u64 file_offset,
1716 struct list_head *list)
1718 struct btrfs_ordered_sum *sum;
1720 list_for_each_entry(sum, list, list) {
1721 trans->adding_csums = 1;
1722 btrfs_csum_file_blocks(trans,
1723 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1724 trans->adding_csums = 0;
1726 return 0;
1729 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1730 struct extent_state **cached_state)
1732 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1733 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1734 cached_state, GFP_NOFS);
1737 /* see btrfs_writepage_start_hook for details on why this is required */
1738 struct btrfs_writepage_fixup {
1739 struct page *page;
1740 struct btrfs_work work;
1743 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1745 struct btrfs_writepage_fixup *fixup;
1746 struct btrfs_ordered_extent *ordered;
1747 struct extent_state *cached_state = NULL;
1748 struct page *page;
1749 struct inode *inode;
1750 u64 page_start;
1751 u64 page_end;
1752 int ret;
1754 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1755 page = fixup->page;
1756 again:
1757 lock_page(page);
1758 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1759 ClearPageChecked(page);
1760 goto out_page;
1763 inode = page->mapping->host;
1764 page_start = page_offset(page);
1765 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1767 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1768 &cached_state);
1770 /* already ordered? We're done */
1771 if (PagePrivate2(page))
1772 goto out;
1774 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1775 if (ordered) {
1776 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1777 page_end, &cached_state, GFP_NOFS);
1778 unlock_page(page);
1779 btrfs_start_ordered_extent(inode, ordered, 1);
1780 btrfs_put_ordered_extent(ordered);
1781 goto again;
1784 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1785 if (ret) {
1786 mapping_set_error(page->mapping, ret);
1787 end_extent_writepage(page, ret, page_start, page_end);
1788 ClearPageChecked(page);
1789 goto out;
1792 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1793 ClearPageChecked(page);
1794 set_page_dirty(page);
1795 out:
1796 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1797 &cached_state, GFP_NOFS);
1798 out_page:
1799 unlock_page(page);
1800 page_cache_release(page);
1801 kfree(fixup);
1805 * There are a few paths in the higher layers of the kernel that directly
1806 * set the page dirty bit without asking the filesystem if it is a
1807 * good idea. This causes problems because we want to make sure COW
1808 * properly happens and the data=ordered rules are followed.
1810 * In our case any range that doesn't have the ORDERED bit set
1811 * hasn't been properly setup for IO. We kick off an async process
1812 * to fix it up. The async helper will wait for ordered extents, set
1813 * the delalloc bit and make it safe to write the page.
1815 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1817 struct inode *inode = page->mapping->host;
1818 struct btrfs_writepage_fixup *fixup;
1819 struct btrfs_root *root = BTRFS_I(inode)->root;
1821 /* this page is properly in the ordered list */
1822 if (TestClearPagePrivate2(page))
1823 return 0;
1825 if (PageChecked(page))
1826 return -EAGAIN;
1828 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1829 if (!fixup)
1830 return -EAGAIN;
1832 SetPageChecked(page);
1833 page_cache_get(page);
1834 fixup->work.func = btrfs_writepage_fixup_worker;
1835 fixup->page = page;
1836 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1837 return -EBUSY;
1840 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1841 struct inode *inode, u64 file_pos,
1842 u64 disk_bytenr, u64 disk_num_bytes,
1843 u64 num_bytes, u64 ram_bytes,
1844 u8 compression, u8 encryption,
1845 u16 other_encoding, int extent_type)
1847 struct btrfs_root *root = BTRFS_I(inode)->root;
1848 struct btrfs_file_extent_item *fi;
1849 struct btrfs_path *path;
1850 struct extent_buffer *leaf;
1851 struct btrfs_key ins;
1852 int ret;
1854 path = btrfs_alloc_path();
1855 if (!path)
1856 return -ENOMEM;
1858 path->leave_spinning = 1;
1861 * we may be replacing one extent in the tree with another.
1862 * The new extent is pinned in the extent map, and we don't want
1863 * to drop it from the cache until it is completely in the btree.
1865 * So, tell btrfs_drop_extents to leave this extent in the cache.
1866 * the caller is expected to unpin it and allow it to be merged
1867 * with the others.
1869 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1870 file_pos + num_bytes, 0);
1871 if (ret)
1872 goto out;
1874 ins.objectid = btrfs_ino(inode);
1875 ins.offset = file_pos;
1876 ins.type = BTRFS_EXTENT_DATA_KEY;
1877 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1878 if (ret)
1879 goto out;
1880 leaf = path->nodes[0];
1881 fi = btrfs_item_ptr(leaf, path->slots[0],
1882 struct btrfs_file_extent_item);
1883 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1884 btrfs_set_file_extent_type(leaf, fi, extent_type);
1885 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1886 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1887 btrfs_set_file_extent_offset(leaf, fi, 0);
1888 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1889 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1890 btrfs_set_file_extent_compression(leaf, fi, compression);
1891 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1892 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1894 btrfs_mark_buffer_dirty(leaf);
1895 btrfs_release_path(path);
1897 inode_add_bytes(inode, num_bytes);
1899 ins.objectid = disk_bytenr;
1900 ins.offset = disk_num_bytes;
1901 ins.type = BTRFS_EXTENT_ITEM_KEY;
1902 ret = btrfs_alloc_reserved_file_extent(trans, root,
1903 root->root_key.objectid,
1904 btrfs_ino(inode), file_pos, &ins);
1905 out:
1906 btrfs_free_path(path);
1908 return ret;
1911 /* snapshot-aware defrag */
1912 struct sa_defrag_extent_backref {
1913 struct rb_node node;
1914 struct old_sa_defrag_extent *old;
1915 u64 root_id;
1916 u64 inum;
1917 u64 file_pos;
1918 u64 extent_offset;
1919 u64 num_bytes;
1920 u64 generation;
1923 struct old_sa_defrag_extent {
1924 struct list_head list;
1925 struct new_sa_defrag_extent *new;
1927 u64 extent_offset;
1928 u64 bytenr;
1929 u64 offset;
1930 u64 len;
1931 int count;
1934 struct new_sa_defrag_extent {
1935 struct rb_root root;
1936 struct list_head head;
1937 struct btrfs_path *path;
1938 struct inode *inode;
1939 u64 file_pos;
1940 u64 len;
1941 u64 bytenr;
1942 u64 disk_len;
1943 u8 compress_type;
1946 static int backref_comp(struct sa_defrag_extent_backref *b1,
1947 struct sa_defrag_extent_backref *b2)
1949 if (b1->root_id < b2->root_id)
1950 return -1;
1951 else if (b1->root_id > b2->root_id)
1952 return 1;
1954 if (b1->inum < b2->inum)
1955 return -1;
1956 else if (b1->inum > b2->inum)
1957 return 1;
1959 if (b1->file_pos < b2->file_pos)
1960 return -1;
1961 else if (b1->file_pos > b2->file_pos)
1962 return 1;
1965 * [------------------------------] ===> (a range of space)
1966 * |<--->| |<---->| =============> (fs/file tree A)
1967 * |<---------------------------->| ===> (fs/file tree B)
1969 * A range of space can refer to two file extents in one tree while
1970 * refer to only one file extent in another tree.
1972 * So we may process a disk offset more than one time(two extents in A)
1973 * and locate at the same extent(one extent in B), then insert two same
1974 * backrefs(both refer to the extent in B).
1976 return 0;
1979 static void backref_insert(struct rb_root *root,
1980 struct sa_defrag_extent_backref *backref)
1982 struct rb_node **p = &root->rb_node;
1983 struct rb_node *parent = NULL;
1984 struct sa_defrag_extent_backref *entry;
1985 int ret;
1987 while (*p) {
1988 parent = *p;
1989 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
1991 ret = backref_comp(backref, entry);
1992 if (ret < 0)
1993 p = &(*p)->rb_left;
1994 else
1995 p = &(*p)->rb_right;
1998 rb_link_node(&backref->node, parent, p);
1999 rb_insert_color(&backref->node, root);
2003 * Note the backref might has changed, and in this case we just return 0.
2005 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2006 void *ctx)
2008 struct btrfs_file_extent_item *extent;
2009 struct btrfs_fs_info *fs_info;
2010 struct old_sa_defrag_extent *old = ctx;
2011 struct new_sa_defrag_extent *new = old->new;
2012 struct btrfs_path *path = new->path;
2013 struct btrfs_key key;
2014 struct btrfs_root *root;
2015 struct sa_defrag_extent_backref *backref;
2016 struct extent_buffer *leaf;
2017 struct inode *inode = new->inode;
2018 int slot;
2019 int ret;
2020 u64 extent_offset;
2021 u64 num_bytes;
2023 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2024 inum == btrfs_ino(inode))
2025 return 0;
2027 key.objectid = root_id;
2028 key.type = BTRFS_ROOT_ITEM_KEY;
2029 key.offset = (u64)-1;
2031 fs_info = BTRFS_I(inode)->root->fs_info;
2032 root = btrfs_read_fs_root_no_name(fs_info, &key);
2033 if (IS_ERR(root)) {
2034 if (PTR_ERR(root) == -ENOENT)
2035 return 0;
2036 WARN_ON(1);
2037 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2038 inum, offset, root_id);
2039 return PTR_ERR(root);
2042 key.objectid = inum;
2043 key.type = BTRFS_EXTENT_DATA_KEY;
2044 if (offset > (u64)-1 << 32)
2045 key.offset = 0;
2046 else
2047 key.offset = offset;
2049 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2050 if (ret < 0) {
2051 WARN_ON(1);
2052 return ret;
2054 ret = 0;
2056 while (1) {
2057 cond_resched();
2059 leaf = path->nodes[0];
2060 slot = path->slots[0];
2062 if (slot >= btrfs_header_nritems(leaf)) {
2063 ret = btrfs_next_leaf(root, path);
2064 if (ret < 0) {
2065 goto out;
2066 } else if (ret > 0) {
2067 ret = 0;
2068 goto out;
2070 continue;
2073 path->slots[0]++;
2075 btrfs_item_key_to_cpu(leaf, &key, slot);
2077 if (key.objectid > inum)
2078 goto out;
2080 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2081 continue;
2083 extent = btrfs_item_ptr(leaf, slot,
2084 struct btrfs_file_extent_item);
2086 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2087 continue;
2090 * 'offset' refers to the exact key.offset,
2091 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2092 * (key.offset - extent_offset).
2094 if (key.offset != offset)
2095 continue;
2097 extent_offset = btrfs_file_extent_offset(leaf, extent);
2098 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2100 if (extent_offset >= old->extent_offset + old->offset +
2101 old->len || extent_offset + num_bytes <=
2102 old->extent_offset + old->offset)
2103 continue;
2104 break;
2107 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2108 if (!backref) {
2109 ret = -ENOENT;
2110 goto out;
2113 backref->root_id = root_id;
2114 backref->inum = inum;
2115 backref->file_pos = offset;
2116 backref->num_bytes = num_bytes;
2117 backref->extent_offset = extent_offset;
2118 backref->generation = btrfs_file_extent_generation(leaf, extent);
2119 backref->old = old;
2120 backref_insert(&new->root, backref);
2121 old->count++;
2122 out:
2123 btrfs_release_path(path);
2124 WARN_ON(ret);
2125 return ret;
2128 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2129 struct new_sa_defrag_extent *new)
2131 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2132 struct old_sa_defrag_extent *old, *tmp;
2133 int ret;
2135 new->path = path;
2137 list_for_each_entry_safe(old, tmp, &new->head, list) {
2138 ret = iterate_inodes_from_logical(old->bytenr +
2139 old->extent_offset, fs_info,
2140 path, record_one_backref,
2141 old);
2142 BUG_ON(ret < 0 && ret != -ENOENT);
2144 /* no backref to be processed for this extent */
2145 if (!old->count) {
2146 list_del(&old->list);
2147 kfree(old);
2151 if (list_empty(&new->head))
2152 return false;
2154 return true;
2157 static int relink_is_mergable(struct extent_buffer *leaf,
2158 struct btrfs_file_extent_item *fi,
2159 struct new_sa_defrag_extent *new)
2161 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2162 return 0;
2164 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2165 return 0;
2167 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2168 return 0;
2170 if (btrfs_file_extent_encryption(leaf, fi) ||
2171 btrfs_file_extent_other_encoding(leaf, fi))
2172 return 0;
2174 return 1;
2178 * Note the backref might has changed, and in this case we just return 0.
2180 static noinline int relink_extent_backref(struct btrfs_path *path,
2181 struct sa_defrag_extent_backref *prev,
2182 struct sa_defrag_extent_backref *backref)
2184 struct btrfs_file_extent_item *extent;
2185 struct btrfs_file_extent_item *item;
2186 struct btrfs_ordered_extent *ordered;
2187 struct btrfs_trans_handle *trans;
2188 struct btrfs_fs_info *fs_info;
2189 struct btrfs_root *root;
2190 struct btrfs_key key;
2191 struct extent_buffer *leaf;
2192 struct old_sa_defrag_extent *old = backref->old;
2193 struct new_sa_defrag_extent *new = old->new;
2194 struct inode *src_inode = new->inode;
2195 struct inode *inode;
2196 struct extent_state *cached = NULL;
2197 int ret = 0;
2198 u64 start;
2199 u64 len;
2200 u64 lock_start;
2201 u64 lock_end;
2202 bool merge = false;
2203 int index;
2205 if (prev && prev->root_id == backref->root_id &&
2206 prev->inum == backref->inum &&
2207 prev->file_pos + prev->num_bytes == backref->file_pos)
2208 merge = true;
2210 /* step 1: get root */
2211 key.objectid = backref->root_id;
2212 key.type = BTRFS_ROOT_ITEM_KEY;
2213 key.offset = (u64)-1;
2215 fs_info = BTRFS_I(src_inode)->root->fs_info;
2216 index = srcu_read_lock(&fs_info->subvol_srcu);
2218 root = btrfs_read_fs_root_no_name(fs_info, &key);
2219 if (IS_ERR(root)) {
2220 srcu_read_unlock(&fs_info->subvol_srcu, index);
2221 if (PTR_ERR(root) == -ENOENT)
2222 return 0;
2223 return PTR_ERR(root);
2226 /* step 2: get inode */
2227 key.objectid = backref->inum;
2228 key.type = BTRFS_INODE_ITEM_KEY;
2229 key.offset = 0;
2231 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2232 if (IS_ERR(inode)) {
2233 srcu_read_unlock(&fs_info->subvol_srcu, index);
2234 return 0;
2237 srcu_read_unlock(&fs_info->subvol_srcu, index);
2239 /* step 3: relink backref */
2240 lock_start = backref->file_pos;
2241 lock_end = backref->file_pos + backref->num_bytes - 1;
2242 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2243 0, &cached);
2245 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2246 if (ordered) {
2247 btrfs_put_ordered_extent(ordered);
2248 goto out_unlock;
2251 trans = btrfs_join_transaction(root);
2252 if (IS_ERR(trans)) {
2253 ret = PTR_ERR(trans);
2254 goto out_unlock;
2257 key.objectid = backref->inum;
2258 key.type = BTRFS_EXTENT_DATA_KEY;
2259 key.offset = backref->file_pos;
2261 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2262 if (ret < 0) {
2263 goto out_free_path;
2264 } else if (ret > 0) {
2265 ret = 0;
2266 goto out_free_path;
2269 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2270 struct btrfs_file_extent_item);
2272 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2273 backref->generation)
2274 goto out_free_path;
2276 btrfs_release_path(path);
2278 start = backref->file_pos;
2279 if (backref->extent_offset < old->extent_offset + old->offset)
2280 start += old->extent_offset + old->offset -
2281 backref->extent_offset;
2283 len = min(backref->extent_offset + backref->num_bytes,
2284 old->extent_offset + old->offset + old->len);
2285 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2287 ret = btrfs_drop_extents(trans, root, inode, start,
2288 start + len, 1);
2289 if (ret)
2290 goto out_free_path;
2291 again:
2292 key.objectid = btrfs_ino(inode);
2293 key.type = BTRFS_EXTENT_DATA_KEY;
2294 key.offset = start;
2296 path->leave_spinning = 1;
2297 if (merge) {
2298 struct btrfs_file_extent_item *fi;
2299 u64 extent_len;
2300 struct btrfs_key found_key;
2302 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2303 if (ret < 0)
2304 goto out_free_path;
2306 path->slots[0]--;
2307 leaf = path->nodes[0];
2308 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2310 fi = btrfs_item_ptr(leaf, path->slots[0],
2311 struct btrfs_file_extent_item);
2312 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2314 if (extent_len + found_key.offset == start &&
2315 relink_is_mergable(leaf, fi, new)) {
2316 btrfs_set_file_extent_num_bytes(leaf, fi,
2317 extent_len + len);
2318 btrfs_mark_buffer_dirty(leaf);
2319 inode_add_bytes(inode, len);
2321 ret = 1;
2322 goto out_free_path;
2323 } else {
2324 merge = false;
2325 btrfs_release_path(path);
2326 goto again;
2330 ret = btrfs_insert_empty_item(trans, root, path, &key,
2331 sizeof(*extent));
2332 if (ret) {
2333 btrfs_abort_transaction(trans, root, ret);
2334 goto out_free_path;
2337 leaf = path->nodes[0];
2338 item = btrfs_item_ptr(leaf, path->slots[0],
2339 struct btrfs_file_extent_item);
2340 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2341 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2342 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2343 btrfs_set_file_extent_num_bytes(leaf, item, len);
2344 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2345 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2346 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2347 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2348 btrfs_set_file_extent_encryption(leaf, item, 0);
2349 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2351 btrfs_mark_buffer_dirty(leaf);
2352 inode_add_bytes(inode, len);
2353 btrfs_release_path(path);
2355 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2356 new->disk_len, 0,
2357 backref->root_id, backref->inum,
2358 new->file_pos, 0); /* start - extent_offset */
2359 if (ret) {
2360 btrfs_abort_transaction(trans, root, ret);
2361 goto out_free_path;
2364 ret = 1;
2365 out_free_path:
2366 btrfs_release_path(path);
2367 path->leave_spinning = 0;
2368 btrfs_end_transaction(trans, root);
2369 out_unlock:
2370 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2371 &cached, GFP_NOFS);
2372 iput(inode);
2373 return ret;
2376 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2378 struct old_sa_defrag_extent *old, *tmp;
2380 if (!new)
2381 return;
2383 list_for_each_entry_safe(old, tmp, &new->head, list) {
2384 list_del(&old->list);
2385 kfree(old);
2387 kfree(new);
2390 static void relink_file_extents(struct new_sa_defrag_extent *new)
2392 struct btrfs_path *path;
2393 struct sa_defrag_extent_backref *backref;
2394 struct sa_defrag_extent_backref *prev = NULL;
2395 struct inode *inode;
2396 struct btrfs_root *root;
2397 struct rb_node *node;
2398 int ret;
2400 inode = new->inode;
2401 root = BTRFS_I(inode)->root;
2403 path = btrfs_alloc_path();
2404 if (!path)
2405 return;
2407 if (!record_extent_backrefs(path, new)) {
2408 btrfs_free_path(path);
2409 goto out;
2411 btrfs_release_path(path);
2413 while (1) {
2414 node = rb_first(&new->root);
2415 if (!node)
2416 break;
2417 rb_erase(node, &new->root);
2419 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2421 ret = relink_extent_backref(path, prev, backref);
2422 WARN_ON(ret < 0);
2424 kfree(prev);
2426 if (ret == 1)
2427 prev = backref;
2428 else
2429 prev = NULL;
2430 cond_resched();
2432 kfree(prev);
2434 btrfs_free_path(path);
2435 out:
2436 free_sa_defrag_extent(new);
2438 atomic_dec(&root->fs_info->defrag_running);
2439 wake_up(&root->fs_info->transaction_wait);
2442 static struct new_sa_defrag_extent *
2443 record_old_file_extents(struct inode *inode,
2444 struct btrfs_ordered_extent *ordered)
2446 struct btrfs_root *root = BTRFS_I(inode)->root;
2447 struct btrfs_path *path;
2448 struct btrfs_key key;
2449 struct old_sa_defrag_extent *old;
2450 struct new_sa_defrag_extent *new;
2451 int ret;
2453 new = kmalloc(sizeof(*new), GFP_NOFS);
2454 if (!new)
2455 return NULL;
2457 new->inode = inode;
2458 new->file_pos = ordered->file_offset;
2459 new->len = ordered->len;
2460 new->bytenr = ordered->start;
2461 new->disk_len = ordered->disk_len;
2462 new->compress_type = ordered->compress_type;
2463 new->root = RB_ROOT;
2464 INIT_LIST_HEAD(&new->head);
2466 path = btrfs_alloc_path();
2467 if (!path)
2468 goto out_kfree;
2470 key.objectid = btrfs_ino(inode);
2471 key.type = BTRFS_EXTENT_DATA_KEY;
2472 key.offset = new->file_pos;
2474 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2475 if (ret < 0)
2476 goto out_free_path;
2477 if (ret > 0 && path->slots[0] > 0)
2478 path->slots[0]--;
2480 /* find out all the old extents for the file range */
2481 while (1) {
2482 struct btrfs_file_extent_item *extent;
2483 struct extent_buffer *l;
2484 int slot;
2485 u64 num_bytes;
2486 u64 offset;
2487 u64 end;
2488 u64 disk_bytenr;
2489 u64 extent_offset;
2491 l = path->nodes[0];
2492 slot = path->slots[0];
2494 if (slot >= btrfs_header_nritems(l)) {
2495 ret = btrfs_next_leaf(root, path);
2496 if (ret < 0)
2497 goto out_free_path;
2498 else if (ret > 0)
2499 break;
2500 continue;
2503 btrfs_item_key_to_cpu(l, &key, slot);
2505 if (key.objectid != btrfs_ino(inode))
2506 break;
2507 if (key.type != BTRFS_EXTENT_DATA_KEY)
2508 break;
2509 if (key.offset >= new->file_pos + new->len)
2510 break;
2512 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2514 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2515 if (key.offset + num_bytes < new->file_pos)
2516 goto next;
2518 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2519 if (!disk_bytenr)
2520 goto next;
2522 extent_offset = btrfs_file_extent_offset(l, extent);
2524 old = kmalloc(sizeof(*old), GFP_NOFS);
2525 if (!old)
2526 goto out_free_path;
2528 offset = max(new->file_pos, key.offset);
2529 end = min(new->file_pos + new->len, key.offset + num_bytes);
2531 old->bytenr = disk_bytenr;
2532 old->extent_offset = extent_offset;
2533 old->offset = offset - key.offset;
2534 old->len = end - offset;
2535 old->new = new;
2536 old->count = 0;
2537 list_add_tail(&old->list, &new->head);
2538 next:
2539 path->slots[0]++;
2540 cond_resched();
2543 btrfs_free_path(path);
2544 atomic_inc(&root->fs_info->defrag_running);
2546 return new;
2548 out_free_path:
2549 btrfs_free_path(path);
2550 out_kfree:
2551 free_sa_defrag_extent(new);
2552 return NULL;
2556 * helper function for btrfs_finish_ordered_io, this
2557 * just reads in some of the csum leaves to prime them into ram
2558 * before we start the transaction. It limits the amount of btree
2559 * reads required while inside the transaction.
2561 /* as ordered data IO finishes, this gets called so we can finish
2562 * an ordered extent if the range of bytes in the file it covers are
2563 * fully written.
2565 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2567 struct inode *inode = ordered_extent->inode;
2568 struct btrfs_root *root = BTRFS_I(inode)->root;
2569 struct btrfs_trans_handle *trans = NULL;
2570 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2571 struct extent_state *cached_state = NULL;
2572 struct new_sa_defrag_extent *new = NULL;
2573 int compress_type = 0;
2574 int ret = 0;
2575 u64 logical_len = ordered_extent->len;
2576 bool nolock;
2577 bool truncated = false;
2579 nolock = btrfs_is_free_space_inode(inode);
2581 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2582 ret = -EIO;
2583 goto out;
2586 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2587 truncated = true;
2588 logical_len = ordered_extent->truncated_len;
2589 /* Truncated the entire extent, don't bother adding */
2590 if (!logical_len)
2591 goto out;
2594 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2595 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2596 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2597 if (nolock)
2598 trans = btrfs_join_transaction_nolock(root);
2599 else
2600 trans = btrfs_join_transaction(root);
2601 if (IS_ERR(trans)) {
2602 ret = PTR_ERR(trans);
2603 trans = NULL;
2604 goto out;
2606 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2607 ret = btrfs_update_inode_fallback(trans, root, inode);
2608 if (ret) /* -ENOMEM or corruption */
2609 btrfs_abort_transaction(trans, root, ret);
2610 goto out;
2613 lock_extent_bits(io_tree, ordered_extent->file_offset,
2614 ordered_extent->file_offset + ordered_extent->len - 1,
2615 0, &cached_state);
2617 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2618 ordered_extent->file_offset + ordered_extent->len - 1,
2619 EXTENT_DEFRAG, 1, cached_state);
2620 if (ret) {
2621 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2622 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2623 /* the inode is shared */
2624 new = record_old_file_extents(inode, ordered_extent);
2626 clear_extent_bit(io_tree, ordered_extent->file_offset,
2627 ordered_extent->file_offset + ordered_extent->len - 1,
2628 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2631 if (nolock)
2632 trans = btrfs_join_transaction_nolock(root);
2633 else
2634 trans = btrfs_join_transaction(root);
2635 if (IS_ERR(trans)) {
2636 ret = PTR_ERR(trans);
2637 trans = NULL;
2638 goto out_unlock;
2640 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2642 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2643 compress_type = ordered_extent->compress_type;
2644 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2645 BUG_ON(compress_type);
2646 ret = btrfs_mark_extent_written(trans, inode,
2647 ordered_extent->file_offset,
2648 ordered_extent->file_offset +
2649 logical_len);
2650 } else {
2651 BUG_ON(root == root->fs_info->tree_root);
2652 ret = insert_reserved_file_extent(trans, inode,
2653 ordered_extent->file_offset,
2654 ordered_extent->start,
2655 ordered_extent->disk_len,
2656 logical_len, logical_len,
2657 compress_type, 0, 0,
2658 BTRFS_FILE_EXTENT_REG);
2660 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2661 ordered_extent->file_offset, ordered_extent->len,
2662 trans->transid);
2663 if (ret < 0) {
2664 btrfs_abort_transaction(trans, root, ret);
2665 goto out_unlock;
2668 add_pending_csums(trans, inode, ordered_extent->file_offset,
2669 &ordered_extent->list);
2671 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2672 ret = btrfs_update_inode_fallback(trans, root, inode);
2673 if (ret) { /* -ENOMEM or corruption */
2674 btrfs_abort_transaction(trans, root, ret);
2675 goto out_unlock;
2677 ret = 0;
2678 out_unlock:
2679 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2680 ordered_extent->file_offset +
2681 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2682 out:
2683 if (root != root->fs_info->tree_root)
2684 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2685 if (trans)
2686 btrfs_end_transaction(trans, root);
2688 if (ret || truncated) {
2689 u64 start, end;
2691 if (truncated)
2692 start = ordered_extent->file_offset + logical_len;
2693 else
2694 start = ordered_extent->file_offset;
2695 end = ordered_extent->file_offset + ordered_extent->len - 1;
2696 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2698 /* Drop the cache for the part of the extent we didn't write. */
2699 btrfs_drop_extent_cache(inode, start, end, 0);
2702 * If the ordered extent had an IOERR or something else went
2703 * wrong we need to return the space for this ordered extent
2704 * back to the allocator. We only free the extent in the
2705 * truncated case if we didn't write out the extent at all.
2707 if ((ret || !logical_len) &&
2708 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2709 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2710 btrfs_free_reserved_extent(root, ordered_extent->start,
2711 ordered_extent->disk_len);
2716 * This needs to be done to make sure anybody waiting knows we are done
2717 * updating everything for this ordered extent.
2719 btrfs_remove_ordered_extent(inode, ordered_extent);
2721 /* for snapshot-aware defrag */
2722 if (new) {
2723 if (ret) {
2724 free_sa_defrag_extent(new);
2725 atomic_dec(&root->fs_info->defrag_running);
2726 } else {
2727 relink_file_extents(new);
2731 /* once for us */
2732 btrfs_put_ordered_extent(ordered_extent);
2733 /* once for the tree */
2734 btrfs_put_ordered_extent(ordered_extent);
2736 return ret;
2739 static void finish_ordered_fn(struct btrfs_work *work)
2741 struct btrfs_ordered_extent *ordered_extent;
2742 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2743 btrfs_finish_ordered_io(ordered_extent);
2746 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2747 struct extent_state *state, int uptodate)
2749 struct inode *inode = page->mapping->host;
2750 struct btrfs_root *root = BTRFS_I(inode)->root;
2751 struct btrfs_ordered_extent *ordered_extent = NULL;
2752 struct btrfs_workers *workers;
2754 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2756 ClearPagePrivate2(page);
2757 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2758 end - start + 1, uptodate))
2759 return 0;
2761 ordered_extent->work.func = finish_ordered_fn;
2762 ordered_extent->work.flags = 0;
2764 if (btrfs_is_free_space_inode(inode))
2765 workers = &root->fs_info->endio_freespace_worker;
2766 else
2767 workers = &root->fs_info->endio_write_workers;
2768 btrfs_queue_worker(workers, &ordered_extent->work);
2770 return 0;
2774 * when reads are done, we need to check csums to verify the data is correct
2775 * if there's a match, we allow the bio to finish. If not, the code in
2776 * extent_io.c will try to find good copies for us.
2778 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2779 u64 phy_offset, struct page *page,
2780 u64 start, u64 end, int mirror)
2782 size_t offset = start - page_offset(page);
2783 struct inode *inode = page->mapping->host;
2784 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2785 char *kaddr;
2786 struct btrfs_root *root = BTRFS_I(inode)->root;
2787 u32 csum_expected;
2788 u32 csum = ~(u32)0;
2789 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2790 DEFAULT_RATELIMIT_BURST);
2792 if (PageChecked(page)) {
2793 ClearPageChecked(page);
2794 goto good;
2797 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2798 goto good;
2800 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2801 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2802 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2803 GFP_NOFS);
2804 return 0;
2807 phy_offset >>= inode->i_sb->s_blocksize_bits;
2808 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2810 kaddr = kmap_atomic(page);
2811 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2812 btrfs_csum_final(csum, (char *)&csum);
2813 if (csum != csum_expected)
2814 goto zeroit;
2816 kunmap_atomic(kaddr);
2817 good:
2818 return 0;
2820 zeroit:
2821 if (__ratelimit(&_rs))
2822 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2823 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2824 memset(kaddr + offset, 1, end - start + 1);
2825 flush_dcache_page(page);
2826 kunmap_atomic(kaddr);
2827 if (csum_expected == 0)
2828 return 0;
2829 return -EIO;
2832 struct delayed_iput {
2833 struct list_head list;
2834 struct inode *inode;
2837 /* JDM: If this is fs-wide, why can't we add a pointer to
2838 * btrfs_inode instead and avoid the allocation? */
2839 void btrfs_add_delayed_iput(struct inode *inode)
2841 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2842 struct delayed_iput *delayed;
2844 if (atomic_add_unless(&inode->i_count, -1, 1))
2845 return;
2847 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2848 delayed->inode = inode;
2850 spin_lock(&fs_info->delayed_iput_lock);
2851 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2852 spin_unlock(&fs_info->delayed_iput_lock);
2855 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2857 LIST_HEAD(list);
2858 struct btrfs_fs_info *fs_info = root->fs_info;
2859 struct delayed_iput *delayed;
2860 int empty;
2862 spin_lock(&fs_info->delayed_iput_lock);
2863 empty = list_empty(&fs_info->delayed_iputs);
2864 spin_unlock(&fs_info->delayed_iput_lock);
2865 if (empty)
2866 return;
2868 spin_lock(&fs_info->delayed_iput_lock);
2869 list_splice_init(&fs_info->delayed_iputs, &list);
2870 spin_unlock(&fs_info->delayed_iput_lock);
2872 while (!list_empty(&list)) {
2873 delayed = list_entry(list.next, struct delayed_iput, list);
2874 list_del(&delayed->list);
2875 iput(delayed->inode);
2876 kfree(delayed);
2881 * This is called in transaction commit time. If there are no orphan
2882 * files in the subvolume, it removes orphan item and frees block_rsv
2883 * structure.
2885 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2886 struct btrfs_root *root)
2888 struct btrfs_block_rsv *block_rsv;
2889 int ret;
2891 if (atomic_read(&root->orphan_inodes) ||
2892 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2893 return;
2895 spin_lock(&root->orphan_lock);
2896 if (atomic_read(&root->orphan_inodes)) {
2897 spin_unlock(&root->orphan_lock);
2898 return;
2901 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2902 spin_unlock(&root->orphan_lock);
2903 return;
2906 block_rsv = root->orphan_block_rsv;
2907 root->orphan_block_rsv = NULL;
2908 spin_unlock(&root->orphan_lock);
2910 if (root->orphan_item_inserted &&
2911 btrfs_root_refs(&root->root_item) > 0) {
2912 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2913 root->root_key.objectid);
2914 if (ret)
2915 btrfs_abort_transaction(trans, root, ret);
2916 else
2917 root->orphan_item_inserted = 0;
2920 if (block_rsv) {
2921 WARN_ON(block_rsv->size > 0);
2922 btrfs_free_block_rsv(root, block_rsv);
2927 * This creates an orphan entry for the given inode in case something goes
2928 * wrong in the middle of an unlink/truncate.
2930 * NOTE: caller of this function should reserve 5 units of metadata for
2931 * this function.
2933 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2935 struct btrfs_root *root = BTRFS_I(inode)->root;
2936 struct btrfs_block_rsv *block_rsv = NULL;
2937 int reserve = 0;
2938 int insert = 0;
2939 int ret;
2941 if (!root->orphan_block_rsv) {
2942 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2943 if (!block_rsv)
2944 return -ENOMEM;
2947 spin_lock(&root->orphan_lock);
2948 if (!root->orphan_block_rsv) {
2949 root->orphan_block_rsv = block_rsv;
2950 } else if (block_rsv) {
2951 btrfs_free_block_rsv(root, block_rsv);
2952 block_rsv = NULL;
2955 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2956 &BTRFS_I(inode)->runtime_flags)) {
2957 #if 0
2959 * For proper ENOSPC handling, we should do orphan
2960 * cleanup when mounting. But this introduces backward
2961 * compatibility issue.
2963 if (!xchg(&root->orphan_item_inserted, 1))
2964 insert = 2;
2965 else
2966 insert = 1;
2967 #endif
2968 insert = 1;
2969 atomic_inc(&root->orphan_inodes);
2972 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2973 &BTRFS_I(inode)->runtime_flags))
2974 reserve = 1;
2975 spin_unlock(&root->orphan_lock);
2977 /* grab metadata reservation from transaction handle */
2978 if (reserve) {
2979 ret = btrfs_orphan_reserve_metadata(trans, inode);
2980 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2983 /* insert an orphan item to track this unlinked/truncated file */
2984 if (insert >= 1) {
2985 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2986 if (ret) {
2987 atomic_dec(&root->orphan_inodes);
2988 if (reserve) {
2989 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2990 &BTRFS_I(inode)->runtime_flags);
2991 btrfs_orphan_release_metadata(inode);
2993 if (ret != -EEXIST) {
2994 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2995 &BTRFS_I(inode)->runtime_flags);
2996 btrfs_abort_transaction(trans, root, ret);
2997 return ret;
3000 ret = 0;
3003 /* insert an orphan item to track subvolume contains orphan files */
3004 if (insert >= 2) {
3005 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3006 root->root_key.objectid);
3007 if (ret && ret != -EEXIST) {
3008 btrfs_abort_transaction(trans, root, ret);
3009 return ret;
3012 return 0;
3016 * We have done the truncate/delete so we can go ahead and remove the orphan
3017 * item for this particular inode.
3019 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3020 struct inode *inode)
3022 struct btrfs_root *root = BTRFS_I(inode)->root;
3023 int delete_item = 0;
3024 int release_rsv = 0;
3025 int ret = 0;
3027 spin_lock(&root->orphan_lock);
3028 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3029 &BTRFS_I(inode)->runtime_flags))
3030 delete_item = 1;
3032 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3033 &BTRFS_I(inode)->runtime_flags))
3034 release_rsv = 1;
3035 spin_unlock(&root->orphan_lock);
3037 if (delete_item) {
3038 atomic_dec(&root->orphan_inodes);
3039 if (trans)
3040 ret = btrfs_del_orphan_item(trans, root,
3041 btrfs_ino(inode));
3044 if (release_rsv)
3045 btrfs_orphan_release_metadata(inode);
3047 return ret;
3051 * this cleans up any orphans that may be left on the list from the last use
3052 * of this root.
3054 int btrfs_orphan_cleanup(struct btrfs_root *root)
3056 struct btrfs_path *path;
3057 struct extent_buffer *leaf;
3058 struct btrfs_key key, found_key;
3059 struct btrfs_trans_handle *trans;
3060 struct inode *inode;
3061 u64 last_objectid = 0;
3062 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3064 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3065 return 0;
3067 path = btrfs_alloc_path();
3068 if (!path) {
3069 ret = -ENOMEM;
3070 goto out;
3072 path->reada = -1;
3074 key.objectid = BTRFS_ORPHAN_OBJECTID;
3075 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3076 key.offset = (u64)-1;
3078 while (1) {
3079 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3080 if (ret < 0)
3081 goto out;
3084 * if ret == 0 means we found what we were searching for, which
3085 * is weird, but possible, so only screw with path if we didn't
3086 * find the key and see if we have stuff that matches
3088 if (ret > 0) {
3089 ret = 0;
3090 if (path->slots[0] == 0)
3091 break;
3092 path->slots[0]--;
3095 /* pull out the item */
3096 leaf = path->nodes[0];
3097 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3099 /* make sure the item matches what we want */
3100 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3101 break;
3102 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3103 break;
3105 /* release the path since we're done with it */
3106 btrfs_release_path(path);
3109 * this is where we are basically btrfs_lookup, without the
3110 * crossing root thing. we store the inode number in the
3111 * offset of the orphan item.
3114 if (found_key.offset == last_objectid) {
3115 btrfs_err(root->fs_info,
3116 "Error removing orphan entry, stopping orphan cleanup");
3117 ret = -EINVAL;
3118 goto out;
3121 last_objectid = found_key.offset;
3123 found_key.objectid = found_key.offset;
3124 found_key.type = BTRFS_INODE_ITEM_KEY;
3125 found_key.offset = 0;
3126 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3127 ret = PTR_ERR_OR_ZERO(inode);
3128 if (ret && ret != -ESTALE)
3129 goto out;
3131 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3132 struct btrfs_root *dead_root;
3133 struct btrfs_fs_info *fs_info = root->fs_info;
3134 int is_dead_root = 0;
3137 * this is an orphan in the tree root. Currently these
3138 * could come from 2 sources:
3139 * a) a snapshot deletion in progress
3140 * b) a free space cache inode
3141 * We need to distinguish those two, as the snapshot
3142 * orphan must not get deleted.
3143 * find_dead_roots already ran before us, so if this
3144 * is a snapshot deletion, we should find the root
3145 * in the dead_roots list
3147 spin_lock(&fs_info->trans_lock);
3148 list_for_each_entry(dead_root, &fs_info->dead_roots,
3149 root_list) {
3150 if (dead_root->root_key.objectid ==
3151 found_key.objectid) {
3152 is_dead_root = 1;
3153 break;
3156 spin_unlock(&fs_info->trans_lock);
3157 if (is_dead_root) {
3158 /* prevent this orphan from being found again */
3159 key.offset = found_key.objectid - 1;
3160 continue;
3164 * Inode is already gone but the orphan item is still there,
3165 * kill the orphan item.
3167 if (ret == -ESTALE) {
3168 trans = btrfs_start_transaction(root, 1);
3169 if (IS_ERR(trans)) {
3170 ret = PTR_ERR(trans);
3171 goto out;
3173 btrfs_debug(root->fs_info, "auto deleting %Lu",
3174 found_key.objectid);
3175 ret = btrfs_del_orphan_item(trans, root,
3176 found_key.objectid);
3177 btrfs_end_transaction(trans, root);
3178 if (ret)
3179 goto out;
3180 continue;
3184 * add this inode to the orphan list so btrfs_orphan_del does
3185 * the proper thing when we hit it
3187 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3188 &BTRFS_I(inode)->runtime_flags);
3189 atomic_inc(&root->orphan_inodes);
3191 /* if we have links, this was a truncate, lets do that */
3192 if (inode->i_nlink) {
3193 if (!S_ISREG(inode->i_mode)) {
3194 WARN_ON(1);
3195 iput(inode);
3196 continue;
3198 nr_truncate++;
3200 /* 1 for the orphan item deletion. */
3201 trans = btrfs_start_transaction(root, 1);
3202 if (IS_ERR(trans)) {
3203 iput(inode);
3204 ret = PTR_ERR(trans);
3205 goto out;
3207 ret = btrfs_orphan_add(trans, inode);
3208 btrfs_end_transaction(trans, root);
3209 if (ret) {
3210 iput(inode);
3211 goto out;
3214 ret = btrfs_truncate(inode);
3215 if (ret)
3216 btrfs_orphan_del(NULL, inode);
3217 } else {
3218 nr_unlink++;
3221 /* this will do delete_inode and everything for us */
3222 iput(inode);
3223 if (ret)
3224 goto out;
3226 /* release the path since we're done with it */
3227 btrfs_release_path(path);
3229 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3231 if (root->orphan_block_rsv)
3232 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3233 (u64)-1);
3235 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3236 trans = btrfs_join_transaction(root);
3237 if (!IS_ERR(trans))
3238 btrfs_end_transaction(trans, root);
3241 if (nr_unlink)
3242 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3243 if (nr_truncate)
3244 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3246 out:
3247 if (ret)
3248 btrfs_crit(root->fs_info,
3249 "could not do orphan cleanup %d", ret);
3250 btrfs_free_path(path);
3251 return ret;
3255 * very simple check to peek ahead in the leaf looking for xattrs. If we
3256 * don't find any xattrs, we know there can't be any acls.
3258 * slot is the slot the inode is in, objectid is the objectid of the inode
3260 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3261 int slot, u64 objectid)
3263 u32 nritems = btrfs_header_nritems(leaf);
3264 struct btrfs_key found_key;
3265 static u64 xattr_access = 0;
3266 static u64 xattr_default = 0;
3267 int scanned = 0;
3269 if (!xattr_access) {
3270 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3271 strlen(POSIX_ACL_XATTR_ACCESS));
3272 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3273 strlen(POSIX_ACL_XATTR_DEFAULT));
3276 slot++;
3277 while (slot < nritems) {
3278 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3280 /* we found a different objectid, there must not be acls */
3281 if (found_key.objectid != objectid)
3282 return 0;
3284 /* we found an xattr, assume we've got an acl */
3285 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3286 if (found_key.offset == xattr_access ||
3287 found_key.offset == xattr_default)
3288 return 1;
3292 * we found a key greater than an xattr key, there can't
3293 * be any acls later on
3295 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3296 return 0;
3298 slot++;
3299 scanned++;
3302 * it goes inode, inode backrefs, xattrs, extents,
3303 * so if there are a ton of hard links to an inode there can
3304 * be a lot of backrefs. Don't waste time searching too hard,
3305 * this is just an optimization
3307 if (scanned >= 8)
3308 break;
3310 /* we hit the end of the leaf before we found an xattr or
3311 * something larger than an xattr. We have to assume the inode
3312 * has acls
3314 return 1;
3318 * read an inode from the btree into the in-memory inode
3320 static void btrfs_read_locked_inode(struct inode *inode)
3322 struct btrfs_path *path;
3323 struct extent_buffer *leaf;
3324 struct btrfs_inode_item *inode_item;
3325 struct btrfs_timespec *tspec;
3326 struct btrfs_root *root = BTRFS_I(inode)->root;
3327 struct btrfs_key location;
3328 int maybe_acls;
3329 u32 rdev;
3330 int ret;
3331 bool filled = false;
3333 ret = btrfs_fill_inode(inode, &rdev);
3334 if (!ret)
3335 filled = true;
3337 path = btrfs_alloc_path();
3338 if (!path)
3339 goto make_bad;
3341 path->leave_spinning = 1;
3342 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3344 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3345 if (ret)
3346 goto make_bad;
3348 leaf = path->nodes[0];
3350 if (filled)
3351 goto cache_acl;
3353 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3354 struct btrfs_inode_item);
3355 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3356 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3357 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3358 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3359 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3361 tspec = btrfs_inode_atime(inode_item);
3362 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3363 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3365 tspec = btrfs_inode_mtime(inode_item);
3366 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3367 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3369 tspec = btrfs_inode_ctime(inode_item);
3370 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3371 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3373 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3374 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3375 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3378 * If we were modified in the current generation and evicted from memory
3379 * and then re-read we need to do a full sync since we don't have any
3380 * idea about which extents were modified before we were evicted from
3381 * cache.
3383 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3384 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3385 &BTRFS_I(inode)->runtime_flags);
3387 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3388 inode->i_generation = BTRFS_I(inode)->generation;
3389 inode->i_rdev = 0;
3390 rdev = btrfs_inode_rdev(leaf, inode_item);
3392 BTRFS_I(inode)->index_cnt = (u64)-1;
3393 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3394 cache_acl:
3396 * try to precache a NULL acl entry for files that don't have
3397 * any xattrs or acls
3399 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3400 btrfs_ino(inode));
3401 if (!maybe_acls)
3402 cache_no_acl(inode);
3404 btrfs_free_path(path);
3406 switch (inode->i_mode & S_IFMT) {
3407 case S_IFREG:
3408 inode->i_mapping->a_ops = &btrfs_aops;
3409 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3410 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3411 inode->i_fop = &btrfs_file_operations;
3412 inode->i_op = &btrfs_file_inode_operations;
3413 break;
3414 case S_IFDIR:
3415 inode->i_fop = &btrfs_dir_file_operations;
3416 if (root == root->fs_info->tree_root)
3417 inode->i_op = &btrfs_dir_ro_inode_operations;
3418 else
3419 inode->i_op = &btrfs_dir_inode_operations;
3420 break;
3421 case S_IFLNK:
3422 inode->i_op = &btrfs_symlink_inode_operations;
3423 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3424 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3425 break;
3426 default:
3427 inode->i_op = &btrfs_special_inode_operations;
3428 init_special_inode(inode, inode->i_mode, rdev);
3429 break;
3432 btrfs_update_iflags(inode);
3433 return;
3435 make_bad:
3436 btrfs_free_path(path);
3437 make_bad_inode(inode);
3441 * given a leaf and an inode, copy the inode fields into the leaf
3443 static void fill_inode_item(struct btrfs_trans_handle *trans,
3444 struct extent_buffer *leaf,
3445 struct btrfs_inode_item *item,
3446 struct inode *inode)
3448 struct btrfs_map_token token;
3450 btrfs_init_map_token(&token);
3452 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3453 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3454 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3455 &token);
3456 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3457 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3459 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3460 inode->i_atime.tv_sec, &token);
3461 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3462 inode->i_atime.tv_nsec, &token);
3464 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3465 inode->i_mtime.tv_sec, &token);
3466 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3467 inode->i_mtime.tv_nsec, &token);
3469 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3470 inode->i_ctime.tv_sec, &token);
3471 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3472 inode->i_ctime.tv_nsec, &token);
3474 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3475 &token);
3476 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3477 &token);
3478 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3479 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3480 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3481 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3482 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3486 * copy everything in the in-memory inode into the btree.
3488 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3489 struct btrfs_root *root, struct inode *inode)
3491 struct btrfs_inode_item *inode_item;
3492 struct btrfs_path *path;
3493 struct extent_buffer *leaf;
3494 int ret;
3496 path = btrfs_alloc_path();
3497 if (!path)
3498 return -ENOMEM;
3500 path->leave_spinning = 1;
3501 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3503 if (ret) {
3504 if (ret > 0)
3505 ret = -ENOENT;
3506 goto failed;
3509 btrfs_unlock_up_safe(path, 1);
3510 leaf = path->nodes[0];
3511 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3512 struct btrfs_inode_item);
3514 fill_inode_item(trans, leaf, inode_item, inode);
3515 btrfs_mark_buffer_dirty(leaf);
3516 btrfs_set_inode_last_trans(trans, inode);
3517 ret = 0;
3518 failed:
3519 btrfs_free_path(path);
3520 return ret;
3524 * copy everything in the in-memory inode into the btree.
3526 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3527 struct btrfs_root *root, struct inode *inode)
3529 int ret;
3532 * If the inode is a free space inode, we can deadlock during commit
3533 * if we put it into the delayed code.
3535 * The data relocation inode should also be directly updated
3536 * without delay
3538 if (!btrfs_is_free_space_inode(inode)
3539 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3540 btrfs_update_root_times(trans, root);
3542 ret = btrfs_delayed_update_inode(trans, root, inode);
3543 if (!ret)
3544 btrfs_set_inode_last_trans(trans, inode);
3545 return ret;
3548 return btrfs_update_inode_item(trans, root, inode);
3551 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3552 struct btrfs_root *root,
3553 struct inode *inode)
3555 int ret;
3557 ret = btrfs_update_inode(trans, root, inode);
3558 if (ret == -ENOSPC)
3559 return btrfs_update_inode_item(trans, root, inode);
3560 return ret;
3564 * unlink helper that gets used here in inode.c and in the tree logging
3565 * recovery code. It remove a link in a directory with a given name, and
3566 * also drops the back refs in the inode to the directory
3568 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3569 struct btrfs_root *root,
3570 struct inode *dir, struct inode *inode,
3571 const char *name, int name_len)
3573 struct btrfs_path *path;
3574 int ret = 0;
3575 struct extent_buffer *leaf;
3576 struct btrfs_dir_item *di;
3577 struct btrfs_key key;
3578 u64 index;
3579 u64 ino = btrfs_ino(inode);
3580 u64 dir_ino = btrfs_ino(dir);
3582 path = btrfs_alloc_path();
3583 if (!path) {
3584 ret = -ENOMEM;
3585 goto out;
3588 path->leave_spinning = 1;
3589 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3590 name, name_len, -1);
3591 if (IS_ERR(di)) {
3592 ret = PTR_ERR(di);
3593 goto err;
3595 if (!di) {
3596 ret = -ENOENT;
3597 goto err;
3599 leaf = path->nodes[0];
3600 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3601 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3602 if (ret)
3603 goto err;
3604 btrfs_release_path(path);
3606 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3607 dir_ino, &index);
3608 if (ret) {
3609 btrfs_info(root->fs_info,
3610 "failed to delete reference to %.*s, inode %llu parent %llu",
3611 name_len, name, ino, dir_ino);
3612 btrfs_abort_transaction(trans, root, ret);
3613 goto err;
3616 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3617 if (ret) {
3618 btrfs_abort_transaction(trans, root, ret);
3619 goto err;
3622 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3623 inode, dir_ino);
3624 if (ret != 0 && ret != -ENOENT) {
3625 btrfs_abort_transaction(trans, root, ret);
3626 goto err;
3629 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3630 dir, index);
3631 if (ret == -ENOENT)
3632 ret = 0;
3633 else if (ret)
3634 btrfs_abort_transaction(trans, root, ret);
3635 err:
3636 btrfs_free_path(path);
3637 if (ret)
3638 goto out;
3640 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3641 inode_inc_iversion(inode);
3642 inode_inc_iversion(dir);
3643 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3644 ret = btrfs_update_inode(trans, root, dir);
3645 out:
3646 return ret;
3649 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3650 struct btrfs_root *root,
3651 struct inode *dir, struct inode *inode,
3652 const char *name, int name_len)
3654 int ret;
3655 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3656 if (!ret) {
3657 btrfs_drop_nlink(inode);
3658 ret = btrfs_update_inode(trans, root, inode);
3660 return ret;
3664 * helper to start transaction for unlink and rmdir.
3666 * unlink and rmdir are special in btrfs, they do not always free space, so
3667 * if we cannot make our reservations the normal way try and see if there is
3668 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3669 * allow the unlink to occur.
3671 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3673 struct btrfs_trans_handle *trans;
3674 struct btrfs_root *root = BTRFS_I(dir)->root;
3675 int ret;
3678 * 1 for the possible orphan item
3679 * 1 for the dir item
3680 * 1 for the dir index
3681 * 1 for the inode ref
3682 * 1 for the inode
3684 trans = btrfs_start_transaction(root, 5);
3685 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3686 return trans;
3688 if (PTR_ERR(trans) == -ENOSPC) {
3689 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3691 trans = btrfs_start_transaction(root, 0);
3692 if (IS_ERR(trans))
3693 return trans;
3694 ret = btrfs_cond_migrate_bytes(root->fs_info,
3695 &root->fs_info->trans_block_rsv,
3696 num_bytes, 5);
3697 if (ret) {
3698 btrfs_end_transaction(trans, root);
3699 return ERR_PTR(ret);
3701 trans->block_rsv = &root->fs_info->trans_block_rsv;
3702 trans->bytes_reserved = num_bytes;
3704 return trans;
3707 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3709 struct btrfs_root *root = BTRFS_I(dir)->root;
3710 struct btrfs_trans_handle *trans;
3711 struct inode *inode = dentry->d_inode;
3712 int ret;
3714 trans = __unlink_start_trans(dir);
3715 if (IS_ERR(trans))
3716 return PTR_ERR(trans);
3718 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3720 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3721 dentry->d_name.name, dentry->d_name.len);
3722 if (ret)
3723 goto out;
3725 if (inode->i_nlink == 0) {
3726 ret = btrfs_orphan_add(trans, inode);
3727 if (ret)
3728 goto out;
3731 out:
3732 btrfs_end_transaction(trans, root);
3733 btrfs_btree_balance_dirty(root);
3734 return ret;
3737 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3738 struct btrfs_root *root,
3739 struct inode *dir, u64 objectid,
3740 const char *name, int name_len)
3742 struct btrfs_path *path;
3743 struct extent_buffer *leaf;
3744 struct btrfs_dir_item *di;
3745 struct btrfs_key key;
3746 u64 index;
3747 int ret;
3748 u64 dir_ino = btrfs_ino(dir);
3750 path = btrfs_alloc_path();
3751 if (!path)
3752 return -ENOMEM;
3754 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3755 name, name_len, -1);
3756 if (IS_ERR_OR_NULL(di)) {
3757 if (!di)
3758 ret = -ENOENT;
3759 else
3760 ret = PTR_ERR(di);
3761 goto out;
3764 leaf = path->nodes[0];
3765 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3766 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3767 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3768 if (ret) {
3769 btrfs_abort_transaction(trans, root, ret);
3770 goto out;
3772 btrfs_release_path(path);
3774 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3775 objectid, root->root_key.objectid,
3776 dir_ino, &index, name, name_len);
3777 if (ret < 0) {
3778 if (ret != -ENOENT) {
3779 btrfs_abort_transaction(trans, root, ret);
3780 goto out;
3782 di = btrfs_search_dir_index_item(root, path, dir_ino,
3783 name, name_len);
3784 if (IS_ERR_OR_NULL(di)) {
3785 if (!di)
3786 ret = -ENOENT;
3787 else
3788 ret = PTR_ERR(di);
3789 btrfs_abort_transaction(trans, root, ret);
3790 goto out;
3793 leaf = path->nodes[0];
3794 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3795 btrfs_release_path(path);
3796 index = key.offset;
3798 btrfs_release_path(path);
3800 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3801 if (ret) {
3802 btrfs_abort_transaction(trans, root, ret);
3803 goto out;
3806 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3807 inode_inc_iversion(dir);
3808 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3809 ret = btrfs_update_inode_fallback(trans, root, dir);
3810 if (ret)
3811 btrfs_abort_transaction(trans, root, ret);
3812 out:
3813 btrfs_free_path(path);
3814 return ret;
3817 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3819 struct inode *inode = dentry->d_inode;
3820 int err = 0;
3821 struct btrfs_root *root = BTRFS_I(dir)->root;
3822 struct btrfs_trans_handle *trans;
3824 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3825 return -ENOTEMPTY;
3826 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3827 return -EPERM;
3829 trans = __unlink_start_trans(dir);
3830 if (IS_ERR(trans))
3831 return PTR_ERR(trans);
3833 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3834 err = btrfs_unlink_subvol(trans, root, dir,
3835 BTRFS_I(inode)->location.objectid,
3836 dentry->d_name.name,
3837 dentry->d_name.len);
3838 goto out;
3841 err = btrfs_orphan_add(trans, inode);
3842 if (err)
3843 goto out;
3845 /* now the directory is empty */
3846 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3847 dentry->d_name.name, dentry->d_name.len);
3848 if (!err)
3849 btrfs_i_size_write(inode, 0);
3850 out:
3851 btrfs_end_transaction(trans, root);
3852 btrfs_btree_balance_dirty(root);
3854 return err;
3858 * this can truncate away extent items, csum items and directory items.
3859 * It starts at a high offset and removes keys until it can't find
3860 * any higher than new_size
3862 * csum items that cross the new i_size are truncated to the new size
3863 * as well.
3865 * min_type is the minimum key type to truncate down to. If set to 0, this
3866 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3868 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3869 struct btrfs_root *root,
3870 struct inode *inode,
3871 u64 new_size, u32 min_type)
3873 struct btrfs_path *path;
3874 struct extent_buffer *leaf;
3875 struct btrfs_file_extent_item *fi;
3876 struct btrfs_key key;
3877 struct btrfs_key found_key;
3878 u64 extent_start = 0;
3879 u64 extent_num_bytes = 0;
3880 u64 extent_offset = 0;
3881 u64 item_end = 0;
3882 u64 last_size = (u64)-1;
3883 u32 found_type = (u8)-1;
3884 int found_extent;
3885 int del_item;
3886 int pending_del_nr = 0;
3887 int pending_del_slot = 0;
3888 int extent_type = -1;
3889 int ret;
3890 int err = 0;
3891 u64 ino = btrfs_ino(inode);
3893 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3895 path = btrfs_alloc_path();
3896 if (!path)
3897 return -ENOMEM;
3898 path->reada = -1;
3901 * We want to drop from the next block forward in case this new size is
3902 * not block aligned since we will be keeping the last block of the
3903 * extent just the way it is.
3905 if (root->ref_cows || root == root->fs_info->tree_root)
3906 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3907 root->sectorsize), (u64)-1, 0);
3910 * This function is also used to drop the items in the log tree before
3911 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3912 * it is used to drop the loged items. So we shouldn't kill the delayed
3913 * items.
3915 if (min_type == 0 && root == BTRFS_I(inode)->root)
3916 btrfs_kill_delayed_inode_items(inode);
3918 key.objectid = ino;
3919 key.offset = (u64)-1;
3920 key.type = (u8)-1;
3922 search_again:
3923 path->leave_spinning = 1;
3924 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3925 if (ret < 0) {
3926 err = ret;
3927 goto out;
3930 if (ret > 0) {
3931 /* there are no items in the tree for us to truncate, we're
3932 * done
3934 if (path->slots[0] == 0)
3935 goto out;
3936 path->slots[0]--;
3939 while (1) {
3940 fi = NULL;
3941 leaf = path->nodes[0];
3942 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3943 found_type = btrfs_key_type(&found_key);
3945 if (found_key.objectid != ino)
3946 break;
3948 if (found_type < min_type)
3949 break;
3951 item_end = found_key.offset;
3952 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3953 fi = btrfs_item_ptr(leaf, path->slots[0],
3954 struct btrfs_file_extent_item);
3955 extent_type = btrfs_file_extent_type(leaf, fi);
3956 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3957 item_end +=
3958 btrfs_file_extent_num_bytes(leaf, fi);
3959 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3960 item_end += btrfs_file_extent_inline_len(leaf,
3961 fi);
3963 item_end--;
3965 if (found_type > min_type) {
3966 del_item = 1;
3967 } else {
3968 if (item_end < new_size)
3969 break;
3970 if (found_key.offset >= new_size)
3971 del_item = 1;
3972 else
3973 del_item = 0;
3975 found_extent = 0;
3976 /* FIXME, shrink the extent if the ref count is only 1 */
3977 if (found_type != BTRFS_EXTENT_DATA_KEY)
3978 goto delete;
3980 if (del_item)
3981 last_size = found_key.offset;
3982 else
3983 last_size = new_size;
3985 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3986 u64 num_dec;
3987 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3988 if (!del_item) {
3989 u64 orig_num_bytes =
3990 btrfs_file_extent_num_bytes(leaf, fi);
3991 extent_num_bytes = ALIGN(new_size -
3992 found_key.offset,
3993 root->sectorsize);
3994 btrfs_set_file_extent_num_bytes(leaf, fi,
3995 extent_num_bytes);
3996 num_dec = (orig_num_bytes -
3997 extent_num_bytes);
3998 if (root->ref_cows && extent_start != 0)
3999 inode_sub_bytes(inode, num_dec);
4000 btrfs_mark_buffer_dirty(leaf);
4001 } else {
4002 extent_num_bytes =
4003 btrfs_file_extent_disk_num_bytes(leaf,
4004 fi);
4005 extent_offset = found_key.offset -
4006 btrfs_file_extent_offset(leaf, fi);
4008 /* FIXME blocksize != 4096 */
4009 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4010 if (extent_start != 0) {
4011 found_extent = 1;
4012 if (root->ref_cows)
4013 inode_sub_bytes(inode, num_dec);
4016 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4018 * we can't truncate inline items that have had
4019 * special encodings
4021 if (!del_item &&
4022 btrfs_file_extent_compression(leaf, fi) == 0 &&
4023 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4024 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4025 u32 size = new_size - found_key.offset;
4027 if (root->ref_cows) {
4028 inode_sub_bytes(inode, item_end + 1 -
4029 new_size);
4031 size =
4032 btrfs_file_extent_calc_inline_size(size);
4033 btrfs_truncate_item(root, path, size, 1);
4034 } else if (root->ref_cows) {
4035 inode_sub_bytes(inode, item_end + 1 -
4036 found_key.offset);
4039 delete:
4040 if (del_item) {
4041 if (!pending_del_nr) {
4042 /* no pending yet, add ourselves */
4043 pending_del_slot = path->slots[0];
4044 pending_del_nr = 1;
4045 } else if (pending_del_nr &&
4046 path->slots[0] + 1 == pending_del_slot) {
4047 /* hop on the pending chunk */
4048 pending_del_nr++;
4049 pending_del_slot = path->slots[0];
4050 } else {
4051 BUG();
4053 } else {
4054 break;
4056 if (found_extent && (root->ref_cows ||
4057 root == root->fs_info->tree_root)) {
4058 btrfs_set_path_blocking(path);
4059 ret = btrfs_free_extent(trans, root, extent_start,
4060 extent_num_bytes, 0,
4061 btrfs_header_owner(leaf),
4062 ino, extent_offset, 0);
4063 BUG_ON(ret);
4066 if (found_type == BTRFS_INODE_ITEM_KEY)
4067 break;
4069 if (path->slots[0] == 0 ||
4070 path->slots[0] != pending_del_slot) {
4071 if (pending_del_nr) {
4072 ret = btrfs_del_items(trans, root, path,
4073 pending_del_slot,
4074 pending_del_nr);
4075 if (ret) {
4076 btrfs_abort_transaction(trans,
4077 root, ret);
4078 goto error;
4080 pending_del_nr = 0;
4082 btrfs_release_path(path);
4083 goto search_again;
4084 } else {
4085 path->slots[0]--;
4088 out:
4089 if (pending_del_nr) {
4090 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4091 pending_del_nr);
4092 if (ret)
4093 btrfs_abort_transaction(trans, root, ret);
4095 error:
4096 if (last_size != (u64)-1)
4097 btrfs_ordered_update_i_size(inode, last_size, NULL);
4098 btrfs_free_path(path);
4099 return err;
4103 * btrfs_truncate_page - read, zero a chunk and write a page
4104 * @inode - inode that we're zeroing
4105 * @from - the offset to start zeroing
4106 * @len - the length to zero, 0 to zero the entire range respective to the
4107 * offset
4108 * @front - zero up to the offset instead of from the offset on
4110 * This will find the page for the "from" offset and cow the page and zero the
4111 * part we want to zero. This is used with truncate and hole punching.
4113 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4114 int front)
4116 struct address_space *mapping = inode->i_mapping;
4117 struct btrfs_root *root = BTRFS_I(inode)->root;
4118 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4119 struct btrfs_ordered_extent *ordered;
4120 struct extent_state *cached_state = NULL;
4121 char *kaddr;
4122 u32 blocksize = root->sectorsize;
4123 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4124 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4125 struct page *page;
4126 gfp_t mask = btrfs_alloc_write_mask(mapping);
4127 int ret = 0;
4128 u64 page_start;
4129 u64 page_end;
4131 if ((offset & (blocksize - 1)) == 0 &&
4132 (!len || ((len & (blocksize - 1)) == 0)))
4133 goto out;
4134 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4135 if (ret)
4136 goto out;
4138 again:
4139 page = find_or_create_page(mapping, index, mask);
4140 if (!page) {
4141 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4142 ret = -ENOMEM;
4143 goto out;
4146 page_start = page_offset(page);
4147 page_end = page_start + PAGE_CACHE_SIZE - 1;
4149 if (!PageUptodate(page)) {
4150 ret = btrfs_readpage(NULL, page);
4151 lock_page(page);
4152 if (page->mapping != mapping) {
4153 unlock_page(page);
4154 page_cache_release(page);
4155 goto again;
4157 if (!PageUptodate(page)) {
4158 ret = -EIO;
4159 goto out_unlock;
4162 wait_on_page_writeback(page);
4164 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4165 set_page_extent_mapped(page);
4167 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4168 if (ordered) {
4169 unlock_extent_cached(io_tree, page_start, page_end,
4170 &cached_state, GFP_NOFS);
4171 unlock_page(page);
4172 page_cache_release(page);
4173 btrfs_start_ordered_extent(inode, ordered, 1);
4174 btrfs_put_ordered_extent(ordered);
4175 goto again;
4178 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4179 EXTENT_DIRTY | EXTENT_DELALLOC |
4180 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4181 0, 0, &cached_state, GFP_NOFS);
4183 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4184 &cached_state);
4185 if (ret) {
4186 unlock_extent_cached(io_tree, page_start, page_end,
4187 &cached_state, GFP_NOFS);
4188 goto out_unlock;
4191 if (offset != PAGE_CACHE_SIZE) {
4192 if (!len)
4193 len = PAGE_CACHE_SIZE - offset;
4194 kaddr = kmap(page);
4195 if (front)
4196 memset(kaddr, 0, offset);
4197 else
4198 memset(kaddr + offset, 0, len);
4199 flush_dcache_page(page);
4200 kunmap(page);
4202 ClearPageChecked(page);
4203 set_page_dirty(page);
4204 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4205 GFP_NOFS);
4207 out_unlock:
4208 if (ret)
4209 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4210 unlock_page(page);
4211 page_cache_release(page);
4212 out:
4213 return ret;
4217 * This function puts in dummy file extents for the area we're creating a hole
4218 * for. So if we are truncating this file to a larger size we need to insert
4219 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4220 * the range between oldsize and size
4222 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4224 struct btrfs_trans_handle *trans;
4225 struct btrfs_root *root = BTRFS_I(inode)->root;
4226 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4227 struct extent_map *em = NULL;
4228 struct extent_state *cached_state = NULL;
4229 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4230 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4231 u64 block_end = ALIGN(size, root->sectorsize);
4232 u64 last_byte;
4233 u64 cur_offset;
4234 u64 hole_size;
4235 int err = 0;
4238 * If our size started in the middle of a page we need to zero out the
4239 * rest of the page before we expand the i_size, otherwise we could
4240 * expose stale data.
4242 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4243 if (err)
4244 return err;
4246 if (size <= hole_start)
4247 return 0;
4249 while (1) {
4250 struct btrfs_ordered_extent *ordered;
4251 btrfs_wait_ordered_range(inode, hole_start,
4252 block_end - hole_start);
4253 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4254 &cached_state);
4255 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4256 if (!ordered)
4257 break;
4258 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4259 &cached_state, GFP_NOFS);
4260 btrfs_put_ordered_extent(ordered);
4263 cur_offset = hole_start;
4264 while (1) {
4265 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4266 block_end - cur_offset, 0);
4267 if (IS_ERR(em)) {
4268 err = PTR_ERR(em);
4269 em = NULL;
4270 break;
4272 last_byte = min(extent_map_end(em), block_end);
4273 last_byte = ALIGN(last_byte , root->sectorsize);
4274 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4275 struct extent_map *hole_em;
4276 hole_size = last_byte - cur_offset;
4278 trans = btrfs_start_transaction(root, 3);
4279 if (IS_ERR(trans)) {
4280 err = PTR_ERR(trans);
4281 break;
4284 err = btrfs_drop_extents(trans, root, inode,
4285 cur_offset,
4286 cur_offset + hole_size, 1);
4287 if (err) {
4288 btrfs_abort_transaction(trans, root, err);
4289 btrfs_end_transaction(trans, root);
4290 break;
4293 err = btrfs_insert_file_extent(trans, root,
4294 btrfs_ino(inode), cur_offset, 0,
4295 0, hole_size, 0, hole_size,
4296 0, 0, 0);
4297 if (err) {
4298 btrfs_abort_transaction(trans, root, err);
4299 btrfs_end_transaction(trans, root);
4300 break;
4303 btrfs_drop_extent_cache(inode, cur_offset,
4304 cur_offset + hole_size - 1, 0);
4305 hole_em = alloc_extent_map();
4306 if (!hole_em) {
4307 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4308 &BTRFS_I(inode)->runtime_flags);
4309 goto next;
4311 hole_em->start = cur_offset;
4312 hole_em->len = hole_size;
4313 hole_em->orig_start = cur_offset;
4315 hole_em->block_start = EXTENT_MAP_HOLE;
4316 hole_em->block_len = 0;
4317 hole_em->orig_block_len = 0;
4318 hole_em->ram_bytes = hole_size;
4319 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4320 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4321 hole_em->generation = trans->transid;
4323 while (1) {
4324 write_lock(&em_tree->lock);
4325 err = add_extent_mapping(em_tree, hole_em, 1);
4326 write_unlock(&em_tree->lock);
4327 if (err != -EEXIST)
4328 break;
4329 btrfs_drop_extent_cache(inode, cur_offset,
4330 cur_offset +
4331 hole_size - 1, 0);
4333 free_extent_map(hole_em);
4334 next:
4335 btrfs_update_inode(trans, root, inode);
4336 btrfs_end_transaction(trans, root);
4338 free_extent_map(em);
4339 em = NULL;
4340 cur_offset = last_byte;
4341 if (cur_offset >= block_end)
4342 break;
4345 free_extent_map(em);
4346 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4347 GFP_NOFS);
4348 return err;
4351 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4353 struct btrfs_root *root = BTRFS_I(inode)->root;
4354 struct btrfs_trans_handle *trans;
4355 loff_t oldsize = i_size_read(inode);
4356 loff_t newsize = attr->ia_size;
4357 int mask = attr->ia_valid;
4358 int ret;
4361 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4362 * special case where we need to update the times despite not having
4363 * these flags set. For all other operations the VFS set these flags
4364 * explicitly if it wants a timestamp update.
4366 if (newsize != oldsize) {
4367 inode_inc_iversion(inode);
4368 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4369 inode->i_ctime = inode->i_mtime =
4370 current_fs_time(inode->i_sb);
4373 if (newsize > oldsize) {
4374 truncate_pagecache(inode, newsize);
4375 ret = btrfs_cont_expand(inode, oldsize, newsize);
4376 if (ret)
4377 return ret;
4379 trans = btrfs_start_transaction(root, 1);
4380 if (IS_ERR(trans))
4381 return PTR_ERR(trans);
4383 i_size_write(inode, newsize);
4384 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4385 ret = btrfs_update_inode(trans, root, inode);
4386 btrfs_end_transaction(trans, root);
4387 } else {
4390 * We're truncating a file that used to have good data down to
4391 * zero. Make sure it gets into the ordered flush list so that
4392 * any new writes get down to disk quickly.
4394 if (newsize == 0)
4395 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4396 &BTRFS_I(inode)->runtime_flags);
4399 * 1 for the orphan item we're going to add
4400 * 1 for the orphan item deletion.
4402 trans = btrfs_start_transaction(root, 2);
4403 if (IS_ERR(trans))
4404 return PTR_ERR(trans);
4407 * We need to do this in case we fail at _any_ point during the
4408 * actual truncate. Once we do the truncate_setsize we could
4409 * invalidate pages which forces any outstanding ordered io to
4410 * be instantly completed which will give us extents that need
4411 * to be truncated. If we fail to get an orphan inode down we
4412 * could have left over extents that were never meant to live,
4413 * so we need to garuntee from this point on that everything
4414 * will be consistent.
4416 ret = btrfs_orphan_add(trans, inode);
4417 btrfs_end_transaction(trans, root);
4418 if (ret)
4419 return ret;
4421 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4422 truncate_setsize(inode, newsize);
4424 /* Disable nonlocked read DIO to avoid the end less truncate */
4425 btrfs_inode_block_unlocked_dio(inode);
4426 inode_dio_wait(inode);
4427 btrfs_inode_resume_unlocked_dio(inode);
4429 ret = btrfs_truncate(inode);
4430 if (ret && inode->i_nlink) {
4431 int err;
4434 * failed to truncate, disk_i_size is only adjusted down
4435 * as we remove extents, so it should represent the true
4436 * size of the inode, so reset the in memory size and
4437 * delete our orphan entry.
4439 trans = btrfs_join_transaction(root);
4440 if (IS_ERR(trans)) {
4441 btrfs_orphan_del(NULL, inode);
4442 return ret;
4444 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4445 err = btrfs_orphan_del(trans, inode);
4446 if (err)
4447 btrfs_abort_transaction(trans, root, err);
4448 btrfs_end_transaction(trans, root);
4452 return ret;
4455 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4457 struct inode *inode = dentry->d_inode;
4458 struct btrfs_root *root = BTRFS_I(inode)->root;
4459 int err;
4461 if (btrfs_root_readonly(root))
4462 return -EROFS;
4464 err = inode_change_ok(inode, attr);
4465 if (err)
4466 return err;
4468 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4469 err = btrfs_setsize(inode, attr);
4470 if (err)
4471 return err;
4474 if (attr->ia_valid) {
4475 setattr_copy(inode, attr);
4476 inode_inc_iversion(inode);
4477 err = btrfs_dirty_inode(inode);
4479 if (!err && attr->ia_valid & ATTR_MODE)
4480 err = btrfs_acl_chmod(inode);
4483 return err;
4486 void btrfs_evict_inode(struct inode *inode)
4488 struct btrfs_trans_handle *trans;
4489 struct btrfs_root *root = BTRFS_I(inode)->root;
4490 struct btrfs_block_rsv *rsv, *global_rsv;
4491 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4492 int ret;
4494 trace_btrfs_inode_evict(inode);
4496 truncate_inode_pages(&inode->i_data, 0);
4497 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4498 btrfs_is_free_space_inode(inode)))
4499 goto no_delete;
4501 if (is_bad_inode(inode)) {
4502 btrfs_orphan_del(NULL, inode);
4503 goto no_delete;
4505 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4506 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4508 if (root->fs_info->log_root_recovering) {
4509 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4510 &BTRFS_I(inode)->runtime_flags));
4511 goto no_delete;
4514 if (inode->i_nlink > 0) {
4515 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4516 goto no_delete;
4519 ret = btrfs_commit_inode_delayed_inode(inode);
4520 if (ret) {
4521 btrfs_orphan_del(NULL, inode);
4522 goto no_delete;
4525 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4526 if (!rsv) {
4527 btrfs_orphan_del(NULL, inode);
4528 goto no_delete;
4530 rsv->size = min_size;
4531 rsv->failfast = 1;
4532 global_rsv = &root->fs_info->global_block_rsv;
4534 btrfs_i_size_write(inode, 0);
4537 * This is a bit simpler than btrfs_truncate since we've already
4538 * reserved our space for our orphan item in the unlink, so we just
4539 * need to reserve some slack space in case we add bytes and update
4540 * inode item when doing the truncate.
4542 while (1) {
4543 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4544 BTRFS_RESERVE_FLUSH_LIMIT);
4547 * Try and steal from the global reserve since we will
4548 * likely not use this space anyway, we want to try as
4549 * hard as possible to get this to work.
4551 if (ret)
4552 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4554 if (ret) {
4555 btrfs_warn(root->fs_info,
4556 "Could not get space for a delete, will truncate on mount %d",
4557 ret);
4558 btrfs_orphan_del(NULL, inode);
4559 btrfs_free_block_rsv(root, rsv);
4560 goto no_delete;
4563 trans = btrfs_join_transaction(root);
4564 if (IS_ERR(trans)) {
4565 btrfs_orphan_del(NULL, inode);
4566 btrfs_free_block_rsv(root, rsv);
4567 goto no_delete;
4570 trans->block_rsv = rsv;
4572 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4573 if (ret != -ENOSPC)
4574 break;
4576 trans->block_rsv = &root->fs_info->trans_block_rsv;
4577 btrfs_end_transaction(trans, root);
4578 trans = NULL;
4579 btrfs_btree_balance_dirty(root);
4582 btrfs_free_block_rsv(root, rsv);
4585 * Errors here aren't a big deal, it just means we leave orphan items
4586 * in the tree. They will be cleaned up on the next mount.
4588 if (ret == 0) {
4589 trans->block_rsv = root->orphan_block_rsv;
4590 btrfs_orphan_del(trans, inode);
4591 } else {
4592 btrfs_orphan_del(NULL, inode);
4595 trans->block_rsv = &root->fs_info->trans_block_rsv;
4596 if (!(root == root->fs_info->tree_root ||
4597 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4598 btrfs_return_ino(root, btrfs_ino(inode));
4600 btrfs_end_transaction(trans, root);
4601 btrfs_btree_balance_dirty(root);
4602 no_delete:
4603 btrfs_remove_delayed_node(inode);
4604 clear_inode(inode);
4605 return;
4609 * this returns the key found in the dir entry in the location pointer.
4610 * If no dir entries were found, location->objectid is 0.
4612 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4613 struct btrfs_key *location)
4615 const char *name = dentry->d_name.name;
4616 int namelen = dentry->d_name.len;
4617 struct btrfs_dir_item *di;
4618 struct btrfs_path *path;
4619 struct btrfs_root *root = BTRFS_I(dir)->root;
4620 int ret = 0;
4622 path = btrfs_alloc_path();
4623 if (!path)
4624 return -ENOMEM;
4626 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4627 namelen, 0);
4628 if (IS_ERR(di))
4629 ret = PTR_ERR(di);
4631 if (IS_ERR_OR_NULL(di))
4632 goto out_err;
4634 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4635 out:
4636 btrfs_free_path(path);
4637 return ret;
4638 out_err:
4639 location->objectid = 0;
4640 goto out;
4644 * when we hit a tree root in a directory, the btrfs part of the inode
4645 * needs to be changed to reflect the root directory of the tree root. This
4646 * is kind of like crossing a mount point.
4648 static int fixup_tree_root_location(struct btrfs_root *root,
4649 struct inode *dir,
4650 struct dentry *dentry,
4651 struct btrfs_key *location,
4652 struct btrfs_root **sub_root)
4654 struct btrfs_path *path;
4655 struct btrfs_root *new_root;
4656 struct btrfs_root_ref *ref;
4657 struct extent_buffer *leaf;
4658 int ret;
4659 int err = 0;
4661 path = btrfs_alloc_path();
4662 if (!path) {
4663 err = -ENOMEM;
4664 goto out;
4667 err = -ENOENT;
4668 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4669 BTRFS_I(dir)->root->root_key.objectid,
4670 location->objectid);
4671 if (ret) {
4672 if (ret < 0)
4673 err = ret;
4674 goto out;
4677 leaf = path->nodes[0];
4678 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4679 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4680 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4681 goto out;
4683 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4684 (unsigned long)(ref + 1),
4685 dentry->d_name.len);
4686 if (ret)
4687 goto out;
4689 btrfs_release_path(path);
4691 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4692 if (IS_ERR(new_root)) {
4693 err = PTR_ERR(new_root);
4694 goto out;
4697 *sub_root = new_root;
4698 location->objectid = btrfs_root_dirid(&new_root->root_item);
4699 location->type = BTRFS_INODE_ITEM_KEY;
4700 location->offset = 0;
4701 err = 0;
4702 out:
4703 btrfs_free_path(path);
4704 return err;
4707 static void inode_tree_add(struct inode *inode)
4709 struct btrfs_root *root = BTRFS_I(inode)->root;
4710 struct btrfs_inode *entry;
4711 struct rb_node **p;
4712 struct rb_node *parent;
4713 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4714 u64 ino = btrfs_ino(inode);
4716 if (inode_unhashed(inode))
4717 return;
4718 parent = NULL;
4719 spin_lock(&root->inode_lock);
4720 p = &root->inode_tree.rb_node;
4721 while (*p) {
4722 parent = *p;
4723 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4725 if (ino < btrfs_ino(&entry->vfs_inode))
4726 p = &parent->rb_left;
4727 else if (ino > btrfs_ino(&entry->vfs_inode))
4728 p = &parent->rb_right;
4729 else {
4730 WARN_ON(!(entry->vfs_inode.i_state &
4731 (I_WILL_FREE | I_FREEING)));
4732 rb_replace_node(parent, new, &root->inode_tree);
4733 RB_CLEAR_NODE(parent);
4734 spin_unlock(&root->inode_lock);
4735 return;
4738 rb_link_node(new, parent, p);
4739 rb_insert_color(new, &root->inode_tree);
4740 spin_unlock(&root->inode_lock);
4743 static void inode_tree_del(struct inode *inode)
4745 struct btrfs_root *root = BTRFS_I(inode)->root;
4746 int empty = 0;
4748 spin_lock(&root->inode_lock);
4749 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4750 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4751 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4752 empty = RB_EMPTY_ROOT(&root->inode_tree);
4754 spin_unlock(&root->inode_lock);
4757 * Free space cache has inodes in the tree root, but the tree root has a
4758 * root_refs of 0, so this could end up dropping the tree root as a
4759 * snapshot, so we need the extra !root->fs_info->tree_root check to
4760 * make sure we don't drop it.
4762 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4763 root != root->fs_info->tree_root) {
4764 synchronize_srcu(&root->fs_info->subvol_srcu);
4765 spin_lock(&root->inode_lock);
4766 empty = RB_EMPTY_ROOT(&root->inode_tree);
4767 spin_unlock(&root->inode_lock);
4768 if (empty)
4769 btrfs_add_dead_root(root);
4773 void btrfs_invalidate_inodes(struct btrfs_root *root)
4775 struct rb_node *node;
4776 struct rb_node *prev;
4777 struct btrfs_inode *entry;
4778 struct inode *inode;
4779 u64 objectid = 0;
4781 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4783 spin_lock(&root->inode_lock);
4784 again:
4785 node = root->inode_tree.rb_node;
4786 prev = NULL;
4787 while (node) {
4788 prev = node;
4789 entry = rb_entry(node, struct btrfs_inode, rb_node);
4791 if (objectid < btrfs_ino(&entry->vfs_inode))
4792 node = node->rb_left;
4793 else if (objectid > btrfs_ino(&entry->vfs_inode))
4794 node = node->rb_right;
4795 else
4796 break;
4798 if (!node) {
4799 while (prev) {
4800 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4801 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4802 node = prev;
4803 break;
4805 prev = rb_next(prev);
4808 while (node) {
4809 entry = rb_entry(node, struct btrfs_inode, rb_node);
4810 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4811 inode = igrab(&entry->vfs_inode);
4812 if (inode) {
4813 spin_unlock(&root->inode_lock);
4814 if (atomic_read(&inode->i_count) > 1)
4815 d_prune_aliases(inode);
4817 * btrfs_drop_inode will have it removed from
4818 * the inode cache when its usage count
4819 * hits zero.
4821 iput(inode);
4822 cond_resched();
4823 spin_lock(&root->inode_lock);
4824 goto again;
4827 if (cond_resched_lock(&root->inode_lock))
4828 goto again;
4830 node = rb_next(node);
4832 spin_unlock(&root->inode_lock);
4835 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4837 struct btrfs_iget_args *args = p;
4838 inode->i_ino = args->ino;
4839 BTRFS_I(inode)->root = args->root;
4840 return 0;
4843 static int btrfs_find_actor(struct inode *inode, void *opaque)
4845 struct btrfs_iget_args *args = opaque;
4846 return args->ino == btrfs_ino(inode) &&
4847 args->root == BTRFS_I(inode)->root;
4850 static struct inode *btrfs_iget_locked(struct super_block *s,
4851 u64 objectid,
4852 struct btrfs_root *root)
4854 struct inode *inode;
4855 struct btrfs_iget_args args;
4856 args.ino = objectid;
4857 args.root = root;
4859 inode = iget5_locked(s, objectid, btrfs_find_actor,
4860 btrfs_init_locked_inode,
4861 (void *)&args);
4862 return inode;
4865 /* Get an inode object given its location and corresponding root.
4866 * Returns in *is_new if the inode was read from disk
4868 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4869 struct btrfs_root *root, int *new)
4871 struct inode *inode;
4873 inode = btrfs_iget_locked(s, location->objectid, root);
4874 if (!inode)
4875 return ERR_PTR(-ENOMEM);
4877 if (inode->i_state & I_NEW) {
4878 BTRFS_I(inode)->root = root;
4879 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4880 btrfs_read_locked_inode(inode);
4881 if (!is_bad_inode(inode)) {
4882 inode_tree_add(inode);
4883 unlock_new_inode(inode);
4884 if (new)
4885 *new = 1;
4886 } else {
4887 unlock_new_inode(inode);
4888 iput(inode);
4889 inode = ERR_PTR(-ESTALE);
4893 return inode;
4896 static struct inode *new_simple_dir(struct super_block *s,
4897 struct btrfs_key *key,
4898 struct btrfs_root *root)
4900 struct inode *inode = new_inode(s);
4902 if (!inode)
4903 return ERR_PTR(-ENOMEM);
4905 BTRFS_I(inode)->root = root;
4906 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4907 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4909 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4910 inode->i_op = &btrfs_dir_ro_inode_operations;
4911 inode->i_fop = &simple_dir_operations;
4912 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4913 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4915 return inode;
4918 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4920 struct inode *inode;
4921 struct btrfs_root *root = BTRFS_I(dir)->root;
4922 struct btrfs_root *sub_root = root;
4923 struct btrfs_key location;
4924 int index;
4925 int ret = 0;
4927 if (dentry->d_name.len > BTRFS_NAME_LEN)
4928 return ERR_PTR(-ENAMETOOLONG);
4930 ret = btrfs_inode_by_name(dir, dentry, &location);
4931 if (ret < 0)
4932 return ERR_PTR(ret);
4934 if (location.objectid == 0)
4935 return NULL;
4937 if (location.type == BTRFS_INODE_ITEM_KEY) {
4938 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4939 return inode;
4942 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4944 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4945 ret = fixup_tree_root_location(root, dir, dentry,
4946 &location, &sub_root);
4947 if (ret < 0) {
4948 if (ret != -ENOENT)
4949 inode = ERR_PTR(ret);
4950 else
4951 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4952 } else {
4953 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4955 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4957 if (!IS_ERR(inode) && root != sub_root) {
4958 down_read(&root->fs_info->cleanup_work_sem);
4959 if (!(inode->i_sb->s_flags & MS_RDONLY))
4960 ret = btrfs_orphan_cleanup(sub_root);
4961 up_read(&root->fs_info->cleanup_work_sem);
4962 if (ret) {
4963 iput(inode);
4964 inode = ERR_PTR(ret);
4968 return inode;
4971 static int btrfs_dentry_delete(const struct dentry *dentry)
4973 struct btrfs_root *root;
4974 struct inode *inode = dentry->d_inode;
4976 if (!inode && !IS_ROOT(dentry))
4977 inode = dentry->d_parent->d_inode;
4979 if (inode) {
4980 root = BTRFS_I(inode)->root;
4981 if (btrfs_root_refs(&root->root_item) == 0)
4982 return 1;
4984 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4985 return 1;
4987 return 0;
4990 static void btrfs_dentry_release(struct dentry *dentry)
4992 if (dentry->d_fsdata)
4993 kfree(dentry->d_fsdata);
4996 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4997 unsigned int flags)
4999 struct dentry *ret;
5001 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5002 return ret;
5005 unsigned char btrfs_filetype_table[] = {
5006 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5009 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5011 struct inode *inode = file_inode(file);
5012 struct btrfs_root *root = BTRFS_I(inode)->root;
5013 struct btrfs_item *item;
5014 struct btrfs_dir_item *di;
5015 struct btrfs_key key;
5016 struct btrfs_key found_key;
5017 struct btrfs_path *path;
5018 struct list_head ins_list;
5019 struct list_head del_list;
5020 int ret;
5021 struct extent_buffer *leaf;
5022 int slot;
5023 unsigned char d_type;
5024 int over = 0;
5025 u32 di_cur;
5026 u32 di_total;
5027 u32 di_len;
5028 int key_type = BTRFS_DIR_INDEX_KEY;
5029 char tmp_name[32];
5030 char *name_ptr;
5031 int name_len;
5032 int is_curr = 0; /* ctx->pos points to the current index? */
5034 /* FIXME, use a real flag for deciding about the key type */
5035 if (root->fs_info->tree_root == root)
5036 key_type = BTRFS_DIR_ITEM_KEY;
5038 if (!dir_emit_dots(file, ctx))
5039 return 0;
5041 path = btrfs_alloc_path();
5042 if (!path)
5043 return -ENOMEM;
5045 path->reada = 1;
5047 if (key_type == BTRFS_DIR_INDEX_KEY) {
5048 INIT_LIST_HEAD(&ins_list);
5049 INIT_LIST_HEAD(&del_list);
5050 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5053 btrfs_set_key_type(&key, key_type);
5054 key.offset = ctx->pos;
5055 key.objectid = btrfs_ino(inode);
5057 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5058 if (ret < 0)
5059 goto err;
5061 while (1) {
5062 leaf = path->nodes[0];
5063 slot = path->slots[0];
5064 if (slot >= btrfs_header_nritems(leaf)) {
5065 ret = btrfs_next_leaf(root, path);
5066 if (ret < 0)
5067 goto err;
5068 else if (ret > 0)
5069 break;
5070 continue;
5073 item = btrfs_item_nr(leaf, slot);
5074 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5076 if (found_key.objectid != key.objectid)
5077 break;
5078 if (btrfs_key_type(&found_key) != key_type)
5079 break;
5080 if (found_key.offset < ctx->pos)
5081 goto next;
5082 if (key_type == BTRFS_DIR_INDEX_KEY &&
5083 btrfs_should_delete_dir_index(&del_list,
5084 found_key.offset))
5085 goto next;
5087 ctx->pos = found_key.offset;
5088 is_curr = 1;
5090 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5091 di_cur = 0;
5092 di_total = btrfs_item_size(leaf, item);
5094 while (di_cur < di_total) {
5095 struct btrfs_key location;
5097 if (verify_dir_item(root, leaf, di))
5098 break;
5100 name_len = btrfs_dir_name_len(leaf, di);
5101 if (name_len <= sizeof(tmp_name)) {
5102 name_ptr = tmp_name;
5103 } else {
5104 name_ptr = kmalloc(name_len, GFP_NOFS);
5105 if (!name_ptr) {
5106 ret = -ENOMEM;
5107 goto err;
5110 read_extent_buffer(leaf, name_ptr,
5111 (unsigned long)(di + 1), name_len);
5113 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5114 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5117 /* is this a reference to our own snapshot? If so
5118 * skip it.
5120 * In contrast to old kernels, we insert the snapshot's
5121 * dir item and dir index after it has been created, so
5122 * we won't find a reference to our own snapshot. We
5123 * still keep the following code for backward
5124 * compatibility.
5126 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5127 location.objectid == root->root_key.objectid) {
5128 over = 0;
5129 goto skip;
5131 over = !dir_emit(ctx, name_ptr, name_len,
5132 location.objectid, d_type);
5134 skip:
5135 if (name_ptr != tmp_name)
5136 kfree(name_ptr);
5138 if (over)
5139 goto nopos;
5140 di_len = btrfs_dir_name_len(leaf, di) +
5141 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5142 di_cur += di_len;
5143 di = (struct btrfs_dir_item *)((char *)di + di_len);
5145 next:
5146 path->slots[0]++;
5149 if (key_type == BTRFS_DIR_INDEX_KEY) {
5150 if (is_curr)
5151 ctx->pos++;
5152 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5153 if (ret)
5154 goto nopos;
5157 /* Reached end of directory/root. Bump pos past the last item. */
5158 ctx->pos++;
5161 * Stop new entries from being returned after we return the last
5162 * entry.
5164 * New directory entries are assigned a strictly increasing
5165 * offset. This means that new entries created during readdir
5166 * are *guaranteed* to be seen in the future by that readdir.
5167 * This has broken buggy programs which operate on names as
5168 * they're returned by readdir. Until we re-use freed offsets
5169 * we have this hack to stop new entries from being returned
5170 * under the assumption that they'll never reach this huge
5171 * offset.
5173 * This is being careful not to overflow 32bit loff_t unless the
5174 * last entry requires it because doing so has broken 32bit apps
5175 * in the past.
5177 if (key_type == BTRFS_DIR_INDEX_KEY) {
5178 if (ctx->pos >= INT_MAX)
5179 ctx->pos = LLONG_MAX;
5180 else
5181 ctx->pos = INT_MAX;
5183 nopos:
5184 ret = 0;
5185 err:
5186 if (key_type == BTRFS_DIR_INDEX_KEY)
5187 btrfs_put_delayed_items(&ins_list, &del_list);
5188 btrfs_free_path(path);
5189 return ret;
5192 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5194 struct btrfs_root *root = BTRFS_I(inode)->root;
5195 struct btrfs_trans_handle *trans;
5196 int ret = 0;
5197 bool nolock = false;
5199 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5200 return 0;
5202 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5203 nolock = true;
5205 if (wbc->sync_mode == WB_SYNC_ALL) {
5206 if (nolock)
5207 trans = btrfs_join_transaction_nolock(root);
5208 else
5209 trans = btrfs_join_transaction(root);
5210 if (IS_ERR(trans))
5211 return PTR_ERR(trans);
5212 ret = btrfs_commit_transaction(trans, root);
5214 return ret;
5218 * This is somewhat expensive, updating the tree every time the
5219 * inode changes. But, it is most likely to find the inode in cache.
5220 * FIXME, needs more benchmarking...there are no reasons other than performance
5221 * to keep or drop this code.
5223 static int btrfs_dirty_inode(struct inode *inode)
5225 struct btrfs_root *root = BTRFS_I(inode)->root;
5226 struct btrfs_trans_handle *trans;
5227 int ret;
5229 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5230 return 0;
5232 trans = btrfs_join_transaction(root);
5233 if (IS_ERR(trans))
5234 return PTR_ERR(trans);
5236 ret = btrfs_update_inode(trans, root, inode);
5237 if (ret && ret == -ENOSPC) {
5238 /* whoops, lets try again with the full transaction */
5239 btrfs_end_transaction(trans, root);
5240 trans = btrfs_start_transaction(root, 1);
5241 if (IS_ERR(trans))
5242 return PTR_ERR(trans);
5244 ret = btrfs_update_inode(trans, root, inode);
5246 btrfs_end_transaction(trans, root);
5247 if (BTRFS_I(inode)->delayed_node)
5248 btrfs_balance_delayed_items(root);
5250 return ret;
5254 * This is a copy of file_update_time. We need this so we can return error on
5255 * ENOSPC for updating the inode in the case of file write and mmap writes.
5257 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5258 int flags)
5260 struct btrfs_root *root = BTRFS_I(inode)->root;
5262 if (btrfs_root_readonly(root))
5263 return -EROFS;
5265 if (flags & S_VERSION)
5266 inode_inc_iversion(inode);
5267 if (flags & S_CTIME)
5268 inode->i_ctime = *now;
5269 if (flags & S_MTIME)
5270 inode->i_mtime = *now;
5271 if (flags & S_ATIME)
5272 inode->i_atime = *now;
5273 return btrfs_dirty_inode(inode);
5277 * find the highest existing sequence number in a directory
5278 * and then set the in-memory index_cnt variable to reflect
5279 * free sequence numbers
5281 static int btrfs_set_inode_index_count(struct inode *inode)
5283 struct btrfs_root *root = BTRFS_I(inode)->root;
5284 struct btrfs_key key, found_key;
5285 struct btrfs_path *path;
5286 struct extent_buffer *leaf;
5287 int ret;
5289 key.objectid = btrfs_ino(inode);
5290 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5291 key.offset = (u64)-1;
5293 path = btrfs_alloc_path();
5294 if (!path)
5295 return -ENOMEM;
5297 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5298 if (ret < 0)
5299 goto out;
5300 /* FIXME: we should be able to handle this */
5301 if (ret == 0)
5302 goto out;
5303 ret = 0;
5306 * MAGIC NUMBER EXPLANATION:
5307 * since we search a directory based on f_pos we have to start at 2
5308 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5309 * else has to start at 2
5311 if (path->slots[0] == 0) {
5312 BTRFS_I(inode)->index_cnt = 2;
5313 goto out;
5316 path->slots[0]--;
5318 leaf = path->nodes[0];
5319 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5321 if (found_key.objectid != btrfs_ino(inode) ||
5322 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5323 BTRFS_I(inode)->index_cnt = 2;
5324 goto out;
5327 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5328 out:
5329 btrfs_free_path(path);
5330 return ret;
5334 * helper to find a free sequence number in a given directory. This current
5335 * code is very simple, later versions will do smarter things in the btree
5337 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5339 int ret = 0;
5341 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5342 ret = btrfs_inode_delayed_dir_index_count(dir);
5343 if (ret) {
5344 ret = btrfs_set_inode_index_count(dir);
5345 if (ret)
5346 return ret;
5350 *index = BTRFS_I(dir)->index_cnt;
5351 BTRFS_I(dir)->index_cnt++;
5353 return ret;
5356 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5357 struct btrfs_root *root,
5358 struct inode *dir,
5359 const char *name, int name_len,
5360 u64 ref_objectid, u64 objectid,
5361 umode_t mode, u64 *index)
5363 struct inode *inode;
5364 struct btrfs_inode_item *inode_item;
5365 struct btrfs_key *location;
5366 struct btrfs_path *path;
5367 struct btrfs_inode_ref *ref;
5368 struct btrfs_key key[2];
5369 u32 sizes[2];
5370 unsigned long ptr;
5371 int ret;
5372 int owner;
5374 path = btrfs_alloc_path();
5375 if (!path)
5376 return ERR_PTR(-ENOMEM);
5378 inode = new_inode(root->fs_info->sb);
5379 if (!inode) {
5380 btrfs_free_path(path);
5381 return ERR_PTR(-ENOMEM);
5385 * we have to initialize this early, so we can reclaim the inode
5386 * number if we fail afterwards in this function.
5388 inode->i_ino = objectid;
5390 if (dir) {
5391 trace_btrfs_inode_request(dir);
5393 ret = btrfs_set_inode_index(dir, index);
5394 if (ret) {
5395 btrfs_free_path(path);
5396 iput(inode);
5397 return ERR_PTR(ret);
5401 * index_cnt is ignored for everything but a dir,
5402 * btrfs_get_inode_index_count has an explanation for the magic
5403 * number
5405 BTRFS_I(inode)->index_cnt = 2;
5406 BTRFS_I(inode)->root = root;
5407 BTRFS_I(inode)->generation = trans->transid;
5408 inode->i_generation = BTRFS_I(inode)->generation;
5411 * We could have gotten an inode number from somebody who was fsynced
5412 * and then removed in this same transaction, so let's just set full
5413 * sync since it will be a full sync anyway and this will blow away the
5414 * old info in the log.
5416 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5418 if (S_ISDIR(mode))
5419 owner = 0;
5420 else
5421 owner = 1;
5423 key[0].objectid = objectid;
5424 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5425 key[0].offset = 0;
5428 * Start new inodes with an inode_ref. This is slightly more
5429 * efficient for small numbers of hard links since they will
5430 * be packed into one item. Extended refs will kick in if we
5431 * add more hard links than can fit in the ref item.
5433 key[1].objectid = objectid;
5434 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5435 key[1].offset = ref_objectid;
5437 sizes[0] = sizeof(struct btrfs_inode_item);
5438 sizes[1] = name_len + sizeof(*ref);
5440 path->leave_spinning = 1;
5441 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5442 if (ret != 0)
5443 goto fail;
5445 inode_init_owner(inode, dir, mode);
5446 inode_set_bytes(inode, 0);
5447 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5448 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5449 struct btrfs_inode_item);
5450 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5451 sizeof(*inode_item));
5452 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5454 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5455 struct btrfs_inode_ref);
5456 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5457 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5458 ptr = (unsigned long)(ref + 1);
5459 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5461 btrfs_mark_buffer_dirty(path->nodes[0]);
5462 btrfs_free_path(path);
5464 location = &BTRFS_I(inode)->location;
5465 location->objectid = objectid;
5466 location->offset = 0;
5467 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5469 btrfs_inherit_iflags(inode, dir);
5471 if (S_ISREG(mode)) {
5472 if (btrfs_test_opt(root, NODATASUM))
5473 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5474 if (btrfs_test_opt(root, NODATACOW))
5475 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5476 BTRFS_INODE_NODATASUM;
5479 insert_inode_hash(inode);
5480 inode_tree_add(inode);
5482 trace_btrfs_inode_new(inode);
5483 btrfs_set_inode_last_trans(trans, inode);
5485 btrfs_update_root_times(trans, root);
5487 return inode;
5488 fail:
5489 if (dir)
5490 BTRFS_I(dir)->index_cnt--;
5491 btrfs_free_path(path);
5492 iput(inode);
5493 return ERR_PTR(ret);
5496 static inline u8 btrfs_inode_type(struct inode *inode)
5498 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5502 * utility function to add 'inode' into 'parent_inode' with
5503 * a give name and a given sequence number.
5504 * if 'add_backref' is true, also insert a backref from the
5505 * inode to the parent directory.
5507 int btrfs_add_link(struct btrfs_trans_handle *trans,
5508 struct inode *parent_inode, struct inode *inode,
5509 const char *name, int name_len, int add_backref, u64 index)
5511 int ret = 0;
5512 struct btrfs_key key;
5513 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5514 u64 ino = btrfs_ino(inode);
5515 u64 parent_ino = btrfs_ino(parent_inode);
5517 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5518 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5519 } else {
5520 key.objectid = ino;
5521 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5522 key.offset = 0;
5525 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5526 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5527 key.objectid, root->root_key.objectid,
5528 parent_ino, index, name, name_len);
5529 } else if (add_backref) {
5530 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5531 parent_ino, index);
5534 /* Nothing to clean up yet */
5535 if (ret)
5536 return ret;
5538 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5539 parent_inode, &key,
5540 btrfs_inode_type(inode), index);
5541 if (ret == -EEXIST || ret == -EOVERFLOW)
5542 goto fail_dir_item;
5543 else if (ret) {
5544 btrfs_abort_transaction(trans, root, ret);
5545 return ret;
5548 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5549 name_len * 2);
5550 inode_inc_iversion(parent_inode);
5551 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5552 ret = btrfs_update_inode(trans, root, parent_inode);
5553 if (ret)
5554 btrfs_abort_transaction(trans, root, ret);
5555 return ret;
5557 fail_dir_item:
5558 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5559 u64 local_index;
5560 int err;
5561 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5562 key.objectid, root->root_key.objectid,
5563 parent_ino, &local_index, name, name_len);
5565 } else if (add_backref) {
5566 u64 local_index;
5567 int err;
5569 err = btrfs_del_inode_ref(trans, root, name, name_len,
5570 ino, parent_ino, &local_index);
5572 return ret;
5575 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5576 struct inode *dir, struct dentry *dentry,
5577 struct inode *inode, int backref, u64 index)
5579 int err = btrfs_add_link(trans, dir, inode,
5580 dentry->d_name.name, dentry->d_name.len,
5581 backref, index);
5582 if (err > 0)
5583 err = -EEXIST;
5584 return err;
5587 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5588 umode_t mode, dev_t rdev)
5590 struct btrfs_trans_handle *trans;
5591 struct btrfs_root *root = BTRFS_I(dir)->root;
5592 struct inode *inode = NULL;
5593 int err;
5594 int drop_inode = 0;
5595 u64 objectid;
5596 u64 index = 0;
5598 if (!new_valid_dev(rdev))
5599 return -EINVAL;
5602 * 2 for inode item and ref
5603 * 2 for dir items
5604 * 1 for xattr if selinux is on
5606 trans = btrfs_start_transaction(root, 5);
5607 if (IS_ERR(trans))
5608 return PTR_ERR(trans);
5610 err = btrfs_find_free_ino(root, &objectid);
5611 if (err)
5612 goto out_unlock;
5614 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5615 dentry->d_name.len, btrfs_ino(dir), objectid,
5616 mode, &index);
5617 if (IS_ERR(inode)) {
5618 err = PTR_ERR(inode);
5619 goto out_unlock;
5622 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5623 if (err) {
5624 drop_inode = 1;
5625 goto out_unlock;
5629 * If the active LSM wants to access the inode during
5630 * d_instantiate it needs these. Smack checks to see
5631 * if the filesystem supports xattrs by looking at the
5632 * ops vector.
5635 inode->i_op = &btrfs_special_inode_operations;
5636 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5637 if (err)
5638 drop_inode = 1;
5639 else {
5640 init_special_inode(inode, inode->i_mode, rdev);
5641 btrfs_update_inode(trans, root, inode);
5642 d_instantiate(dentry, inode);
5644 out_unlock:
5645 btrfs_end_transaction(trans, root);
5646 btrfs_btree_balance_dirty(root);
5647 if (drop_inode) {
5648 inode_dec_link_count(inode);
5649 iput(inode);
5651 return err;
5654 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5655 umode_t mode, bool excl)
5657 struct btrfs_trans_handle *trans;
5658 struct btrfs_root *root = BTRFS_I(dir)->root;
5659 struct inode *inode = NULL;
5660 int drop_inode_on_err = 0;
5661 int err;
5662 u64 objectid;
5663 u64 index = 0;
5666 * 2 for inode item and ref
5667 * 2 for dir items
5668 * 1 for xattr if selinux is on
5670 trans = btrfs_start_transaction(root, 5);
5671 if (IS_ERR(trans))
5672 return PTR_ERR(trans);
5674 err = btrfs_find_free_ino(root, &objectid);
5675 if (err)
5676 goto out_unlock;
5678 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5679 dentry->d_name.len, btrfs_ino(dir), objectid,
5680 mode, &index);
5681 if (IS_ERR(inode)) {
5682 err = PTR_ERR(inode);
5683 goto out_unlock;
5685 drop_inode_on_err = 1;
5687 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5688 if (err)
5689 goto out_unlock;
5691 err = btrfs_update_inode(trans, root, inode);
5692 if (err)
5693 goto out_unlock;
5696 * If the active LSM wants to access the inode during
5697 * d_instantiate it needs these. Smack checks to see
5698 * if the filesystem supports xattrs by looking at the
5699 * ops vector.
5701 inode->i_fop = &btrfs_file_operations;
5702 inode->i_op = &btrfs_file_inode_operations;
5704 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5705 if (err)
5706 goto out_unlock;
5708 inode->i_mapping->a_ops = &btrfs_aops;
5709 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5710 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5711 d_instantiate(dentry, inode);
5713 out_unlock:
5714 btrfs_end_transaction(trans, root);
5715 if (err && drop_inode_on_err) {
5716 inode_dec_link_count(inode);
5717 iput(inode);
5719 btrfs_btree_balance_dirty(root);
5720 return err;
5723 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5724 struct dentry *dentry)
5726 struct btrfs_trans_handle *trans;
5727 struct btrfs_root *root = BTRFS_I(dir)->root;
5728 struct inode *inode = old_dentry->d_inode;
5729 u64 index;
5730 int err;
5731 int drop_inode = 0;
5733 /* do not allow sys_link's with other subvols of the same device */
5734 if (root->objectid != BTRFS_I(inode)->root->objectid)
5735 return -EXDEV;
5737 if (inode->i_nlink >= BTRFS_LINK_MAX)
5738 return -EMLINK;
5740 err = btrfs_set_inode_index(dir, &index);
5741 if (err)
5742 goto fail;
5745 * 2 items for inode and inode ref
5746 * 2 items for dir items
5747 * 1 item for parent inode
5749 trans = btrfs_start_transaction(root, 5);
5750 if (IS_ERR(trans)) {
5751 err = PTR_ERR(trans);
5752 goto fail;
5755 btrfs_inc_nlink(inode);
5756 inode_inc_iversion(inode);
5757 inode->i_ctime = CURRENT_TIME;
5758 ihold(inode);
5759 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5761 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5763 if (err) {
5764 drop_inode = 1;
5765 } else {
5766 struct dentry *parent = dentry->d_parent;
5767 err = btrfs_update_inode(trans, root, inode);
5768 if (err)
5769 goto fail;
5770 d_instantiate(dentry, inode);
5771 btrfs_log_new_name(trans, inode, NULL, parent);
5774 btrfs_end_transaction(trans, root);
5775 fail:
5776 if (drop_inode) {
5777 inode_dec_link_count(inode);
5778 iput(inode);
5780 btrfs_btree_balance_dirty(root);
5781 return err;
5784 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5786 struct inode *inode = NULL;
5787 struct btrfs_trans_handle *trans;
5788 struct btrfs_root *root = BTRFS_I(dir)->root;
5789 int err = 0;
5790 int drop_on_err = 0;
5791 u64 objectid = 0;
5792 u64 index = 0;
5795 * 2 items for inode and ref
5796 * 2 items for dir items
5797 * 1 for xattr if selinux is on
5799 trans = btrfs_start_transaction(root, 5);
5800 if (IS_ERR(trans))
5801 return PTR_ERR(trans);
5803 err = btrfs_find_free_ino(root, &objectid);
5804 if (err)
5805 goto out_fail;
5807 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5808 dentry->d_name.len, btrfs_ino(dir), objectid,
5809 S_IFDIR | mode, &index);
5810 if (IS_ERR(inode)) {
5811 err = PTR_ERR(inode);
5812 goto out_fail;
5815 drop_on_err = 1;
5817 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5818 if (err)
5819 goto out_fail;
5821 inode->i_op = &btrfs_dir_inode_operations;
5822 inode->i_fop = &btrfs_dir_file_operations;
5824 btrfs_i_size_write(inode, 0);
5825 err = btrfs_update_inode(trans, root, inode);
5826 if (err)
5827 goto out_fail;
5829 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5830 dentry->d_name.len, 0, index);
5831 if (err)
5832 goto out_fail;
5834 d_instantiate(dentry, inode);
5835 drop_on_err = 0;
5837 out_fail:
5838 btrfs_end_transaction(trans, root);
5839 if (drop_on_err)
5840 iput(inode);
5841 btrfs_btree_balance_dirty(root);
5842 return err;
5845 /* helper for btfs_get_extent. Given an existing extent in the tree,
5846 * and an extent that you want to insert, deal with overlap and insert
5847 * the new extent into the tree.
5849 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5850 struct extent_map *existing,
5851 struct extent_map *em,
5852 u64 map_start, u64 map_len)
5854 u64 start_diff;
5856 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5857 start_diff = map_start - em->start;
5858 em->start = map_start;
5859 em->len = map_len;
5860 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5861 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5862 em->block_start += start_diff;
5863 em->block_len -= start_diff;
5865 return add_extent_mapping(em_tree, em, 0);
5868 static noinline int uncompress_inline(struct btrfs_path *path,
5869 struct inode *inode, struct page *page,
5870 size_t pg_offset, u64 extent_offset,
5871 struct btrfs_file_extent_item *item)
5873 int ret;
5874 struct extent_buffer *leaf = path->nodes[0];
5875 char *tmp;
5876 size_t max_size;
5877 unsigned long inline_size;
5878 unsigned long ptr;
5879 int compress_type;
5881 WARN_ON(pg_offset != 0);
5882 compress_type = btrfs_file_extent_compression(leaf, item);
5883 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5884 inline_size = btrfs_file_extent_inline_item_len(leaf,
5885 btrfs_item_nr(leaf, path->slots[0]));
5886 tmp = kmalloc(inline_size, GFP_NOFS);
5887 if (!tmp)
5888 return -ENOMEM;
5889 ptr = btrfs_file_extent_inline_start(item);
5891 read_extent_buffer(leaf, tmp, ptr, inline_size);
5893 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5894 ret = btrfs_decompress(compress_type, tmp, page,
5895 extent_offset, inline_size, max_size);
5896 if (ret) {
5897 char *kaddr = kmap_atomic(page);
5898 unsigned long copy_size = min_t(u64,
5899 PAGE_CACHE_SIZE - pg_offset,
5900 max_size - extent_offset);
5901 memset(kaddr + pg_offset, 0, copy_size);
5902 kunmap_atomic(kaddr);
5904 kfree(tmp);
5905 return 0;
5909 * a bit scary, this does extent mapping from logical file offset to the disk.
5910 * the ugly parts come from merging extents from the disk with the in-ram
5911 * representation. This gets more complex because of the data=ordered code,
5912 * where the in-ram extents might be locked pending data=ordered completion.
5914 * This also copies inline extents directly into the page.
5917 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5918 size_t pg_offset, u64 start, u64 len,
5919 int create)
5921 int ret;
5922 int err = 0;
5923 u64 bytenr;
5924 u64 extent_start = 0;
5925 u64 extent_end = 0;
5926 u64 objectid = btrfs_ino(inode);
5927 u32 found_type;
5928 struct btrfs_path *path = NULL;
5929 struct btrfs_root *root = BTRFS_I(inode)->root;
5930 struct btrfs_file_extent_item *item;
5931 struct extent_buffer *leaf;
5932 struct btrfs_key found_key;
5933 struct extent_map *em = NULL;
5934 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5935 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5936 struct btrfs_trans_handle *trans = NULL;
5937 int compress_type;
5939 again:
5940 read_lock(&em_tree->lock);
5941 em = lookup_extent_mapping(em_tree, start, len);
5942 if (em)
5943 em->bdev = root->fs_info->fs_devices->latest_bdev;
5944 read_unlock(&em_tree->lock);
5946 if (em) {
5947 if (em->start > start || em->start + em->len <= start)
5948 free_extent_map(em);
5949 else if (em->block_start == EXTENT_MAP_INLINE && page)
5950 free_extent_map(em);
5951 else
5952 goto out;
5954 em = alloc_extent_map();
5955 if (!em) {
5956 err = -ENOMEM;
5957 goto out;
5959 em->bdev = root->fs_info->fs_devices->latest_bdev;
5960 em->start = EXTENT_MAP_HOLE;
5961 em->orig_start = EXTENT_MAP_HOLE;
5962 em->len = (u64)-1;
5963 em->block_len = (u64)-1;
5965 if (!path) {
5966 path = btrfs_alloc_path();
5967 if (!path) {
5968 err = -ENOMEM;
5969 goto out;
5972 * Chances are we'll be called again, so go ahead and do
5973 * readahead
5975 path->reada = 1;
5978 ret = btrfs_lookup_file_extent(trans, root, path,
5979 objectid, start, trans != NULL);
5980 if (ret < 0) {
5981 err = ret;
5982 goto out;
5985 if (ret != 0) {
5986 if (path->slots[0] == 0)
5987 goto not_found;
5988 path->slots[0]--;
5991 leaf = path->nodes[0];
5992 item = btrfs_item_ptr(leaf, path->slots[0],
5993 struct btrfs_file_extent_item);
5994 /* are we inside the extent that was found? */
5995 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5996 found_type = btrfs_key_type(&found_key);
5997 if (found_key.objectid != objectid ||
5998 found_type != BTRFS_EXTENT_DATA_KEY) {
5999 goto not_found;
6002 found_type = btrfs_file_extent_type(leaf, item);
6003 extent_start = found_key.offset;
6004 compress_type = btrfs_file_extent_compression(leaf, item);
6005 if (found_type == BTRFS_FILE_EXTENT_REG ||
6006 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6007 extent_end = extent_start +
6008 btrfs_file_extent_num_bytes(leaf, item);
6009 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6010 size_t size;
6011 size = btrfs_file_extent_inline_len(leaf, item);
6012 extent_end = ALIGN(extent_start + size, root->sectorsize);
6015 if (start >= extent_end) {
6016 path->slots[0]++;
6017 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6018 ret = btrfs_next_leaf(root, path);
6019 if (ret < 0) {
6020 err = ret;
6021 goto out;
6023 if (ret > 0)
6024 goto not_found;
6025 leaf = path->nodes[0];
6027 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6028 if (found_key.objectid != objectid ||
6029 found_key.type != BTRFS_EXTENT_DATA_KEY)
6030 goto not_found;
6031 if (start + len <= found_key.offset)
6032 goto not_found;
6033 em->start = start;
6034 em->orig_start = start;
6035 em->len = found_key.offset - start;
6036 goto not_found_em;
6039 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6040 if (found_type == BTRFS_FILE_EXTENT_REG ||
6041 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6042 em->start = extent_start;
6043 em->len = extent_end - extent_start;
6044 em->orig_start = extent_start -
6045 btrfs_file_extent_offset(leaf, item);
6046 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6047 item);
6048 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6049 if (bytenr == 0) {
6050 em->block_start = EXTENT_MAP_HOLE;
6051 goto insert;
6053 if (compress_type != BTRFS_COMPRESS_NONE) {
6054 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6055 em->compress_type = compress_type;
6056 em->block_start = bytenr;
6057 em->block_len = em->orig_block_len;
6058 } else {
6059 bytenr += btrfs_file_extent_offset(leaf, item);
6060 em->block_start = bytenr;
6061 em->block_len = em->len;
6062 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6063 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6065 goto insert;
6066 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6067 unsigned long ptr;
6068 char *map;
6069 size_t size;
6070 size_t extent_offset;
6071 size_t copy_size;
6073 em->block_start = EXTENT_MAP_INLINE;
6074 if (!page || create) {
6075 em->start = extent_start;
6076 em->len = extent_end - extent_start;
6077 goto out;
6080 size = btrfs_file_extent_inline_len(leaf, item);
6081 extent_offset = page_offset(page) + pg_offset - extent_start;
6082 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6083 size - extent_offset);
6084 em->start = extent_start + extent_offset;
6085 em->len = ALIGN(copy_size, root->sectorsize);
6086 em->orig_block_len = em->len;
6087 em->orig_start = em->start;
6088 if (compress_type) {
6089 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6090 em->compress_type = compress_type;
6092 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6093 if (create == 0 && !PageUptodate(page)) {
6094 if (btrfs_file_extent_compression(leaf, item) !=
6095 BTRFS_COMPRESS_NONE) {
6096 ret = uncompress_inline(path, inode, page,
6097 pg_offset,
6098 extent_offset, item);
6099 BUG_ON(ret); /* -ENOMEM */
6100 } else {
6101 map = kmap(page);
6102 read_extent_buffer(leaf, map + pg_offset, ptr,
6103 copy_size);
6104 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6105 memset(map + pg_offset + copy_size, 0,
6106 PAGE_CACHE_SIZE - pg_offset -
6107 copy_size);
6109 kunmap(page);
6111 flush_dcache_page(page);
6112 } else if (create && PageUptodate(page)) {
6113 BUG();
6114 if (!trans) {
6115 kunmap(page);
6116 free_extent_map(em);
6117 em = NULL;
6119 btrfs_release_path(path);
6120 trans = btrfs_join_transaction(root);
6122 if (IS_ERR(trans))
6123 return ERR_CAST(trans);
6124 goto again;
6126 map = kmap(page);
6127 write_extent_buffer(leaf, map + pg_offset, ptr,
6128 copy_size);
6129 kunmap(page);
6130 btrfs_mark_buffer_dirty(leaf);
6132 set_extent_uptodate(io_tree, em->start,
6133 extent_map_end(em) - 1, NULL, GFP_NOFS);
6134 goto insert;
6135 } else {
6136 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6138 not_found:
6139 em->start = start;
6140 em->orig_start = start;
6141 em->len = len;
6142 not_found_em:
6143 em->block_start = EXTENT_MAP_HOLE;
6144 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6145 insert:
6146 btrfs_release_path(path);
6147 if (em->start > start || extent_map_end(em) <= start) {
6148 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6149 em->start, em->len, start, len);
6150 err = -EIO;
6151 goto out;
6154 err = 0;
6155 write_lock(&em_tree->lock);
6156 ret = add_extent_mapping(em_tree, em, 0);
6157 /* it is possible that someone inserted the extent into the tree
6158 * while we had the lock dropped. It is also possible that
6159 * an overlapping map exists in the tree
6161 if (ret == -EEXIST) {
6162 struct extent_map *existing;
6164 ret = 0;
6166 existing = lookup_extent_mapping(em_tree, start, len);
6167 if (existing && (existing->start > start ||
6168 existing->start + existing->len <= start)) {
6169 free_extent_map(existing);
6170 existing = NULL;
6172 if (!existing) {
6173 existing = lookup_extent_mapping(em_tree, em->start,
6174 em->len);
6175 if (existing) {
6176 err = merge_extent_mapping(em_tree, existing,
6177 em, start,
6178 root->sectorsize);
6179 free_extent_map(existing);
6180 if (err) {
6181 free_extent_map(em);
6182 em = NULL;
6184 } else {
6185 err = -EIO;
6186 free_extent_map(em);
6187 em = NULL;
6189 } else {
6190 free_extent_map(em);
6191 em = existing;
6192 err = 0;
6195 write_unlock(&em_tree->lock);
6196 out:
6198 if (em)
6199 trace_btrfs_get_extent(root, em);
6201 if (path)
6202 btrfs_free_path(path);
6203 if (trans) {
6204 ret = btrfs_end_transaction(trans, root);
6205 if (!err)
6206 err = ret;
6208 if (err) {
6209 free_extent_map(em);
6210 return ERR_PTR(err);
6212 BUG_ON(!em); /* Error is always set */
6213 return em;
6216 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6217 size_t pg_offset, u64 start, u64 len,
6218 int create)
6220 struct extent_map *em;
6221 struct extent_map *hole_em = NULL;
6222 u64 range_start = start;
6223 u64 end;
6224 u64 found;
6225 u64 found_end;
6226 int err = 0;
6228 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6229 if (IS_ERR(em))
6230 return em;
6231 if (em) {
6233 * if our em maps to
6234 * - a hole or
6235 * - a pre-alloc extent,
6236 * there might actually be delalloc bytes behind it.
6238 if (em->block_start != EXTENT_MAP_HOLE &&
6239 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6240 return em;
6241 else
6242 hole_em = em;
6245 /* check to see if we've wrapped (len == -1 or similar) */
6246 end = start + len;
6247 if (end < start)
6248 end = (u64)-1;
6249 else
6250 end -= 1;
6252 em = NULL;
6254 /* ok, we didn't find anything, lets look for delalloc */
6255 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6256 end, len, EXTENT_DELALLOC, 1);
6257 found_end = range_start + found;
6258 if (found_end < range_start)
6259 found_end = (u64)-1;
6262 * we didn't find anything useful, return
6263 * the original results from get_extent()
6265 if (range_start > end || found_end <= start) {
6266 em = hole_em;
6267 hole_em = NULL;
6268 goto out;
6271 /* adjust the range_start to make sure it doesn't
6272 * go backwards from the start they passed in
6274 range_start = max(start,range_start);
6275 found = found_end - range_start;
6277 if (found > 0) {
6278 u64 hole_start = start;
6279 u64 hole_len = len;
6281 em = alloc_extent_map();
6282 if (!em) {
6283 err = -ENOMEM;
6284 goto out;
6287 * when btrfs_get_extent can't find anything it
6288 * returns one huge hole
6290 * make sure what it found really fits our range, and
6291 * adjust to make sure it is based on the start from
6292 * the caller
6294 if (hole_em) {
6295 u64 calc_end = extent_map_end(hole_em);
6297 if (calc_end <= start || (hole_em->start > end)) {
6298 free_extent_map(hole_em);
6299 hole_em = NULL;
6300 } else {
6301 hole_start = max(hole_em->start, start);
6302 hole_len = calc_end - hole_start;
6305 em->bdev = NULL;
6306 if (hole_em && range_start > hole_start) {
6307 /* our hole starts before our delalloc, so we
6308 * have to return just the parts of the hole
6309 * that go until the delalloc starts
6311 em->len = min(hole_len,
6312 range_start - hole_start);
6313 em->start = hole_start;
6314 em->orig_start = hole_start;
6316 * don't adjust block start at all,
6317 * it is fixed at EXTENT_MAP_HOLE
6319 em->block_start = hole_em->block_start;
6320 em->block_len = hole_len;
6321 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6322 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6323 } else {
6324 em->start = range_start;
6325 em->len = found;
6326 em->orig_start = range_start;
6327 em->block_start = EXTENT_MAP_DELALLOC;
6328 em->block_len = found;
6330 } else if (hole_em) {
6331 return hole_em;
6333 out:
6335 free_extent_map(hole_em);
6336 if (err) {
6337 free_extent_map(em);
6338 return ERR_PTR(err);
6340 return em;
6343 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6344 u64 start, u64 len)
6346 struct btrfs_root *root = BTRFS_I(inode)->root;
6347 struct extent_map *em;
6348 struct btrfs_key ins;
6349 u64 alloc_hint;
6350 int ret;
6352 alloc_hint = get_extent_allocation_hint(inode, start, len);
6353 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6354 alloc_hint, &ins, 1);
6355 if (ret)
6356 return ERR_PTR(ret);
6358 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6359 ins.offset, ins.offset, ins.offset, 0);
6360 if (IS_ERR(em)) {
6361 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6362 return em;
6365 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6366 ins.offset, ins.offset, 0);
6367 if (ret) {
6368 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6369 free_extent_map(em);
6370 return ERR_PTR(ret);
6373 return em;
6377 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6378 * block must be cow'd
6380 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6381 u64 *orig_start, u64 *orig_block_len,
6382 u64 *ram_bytes)
6384 struct btrfs_trans_handle *trans;
6385 struct btrfs_path *path;
6386 int ret;
6387 struct extent_buffer *leaf;
6388 struct btrfs_root *root = BTRFS_I(inode)->root;
6389 struct btrfs_file_extent_item *fi;
6390 struct btrfs_key key;
6391 u64 disk_bytenr;
6392 u64 backref_offset;
6393 u64 extent_end;
6394 u64 num_bytes;
6395 int slot;
6396 int found_type;
6397 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6398 path = btrfs_alloc_path();
6399 if (!path)
6400 return -ENOMEM;
6402 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6403 offset, 0);
6404 if (ret < 0)
6405 goto out;
6407 slot = path->slots[0];
6408 if (ret == 1) {
6409 if (slot == 0) {
6410 /* can't find the item, must cow */
6411 ret = 0;
6412 goto out;
6414 slot--;
6416 ret = 0;
6417 leaf = path->nodes[0];
6418 btrfs_item_key_to_cpu(leaf, &key, slot);
6419 if (key.objectid != btrfs_ino(inode) ||
6420 key.type != BTRFS_EXTENT_DATA_KEY) {
6421 /* not our file or wrong item type, must cow */
6422 goto out;
6425 if (key.offset > offset) {
6426 /* Wrong offset, must cow */
6427 goto out;
6430 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6431 found_type = btrfs_file_extent_type(leaf, fi);
6432 if (found_type != BTRFS_FILE_EXTENT_REG &&
6433 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6434 /* not a regular extent, must cow */
6435 goto out;
6438 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6439 goto out;
6441 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6442 if (disk_bytenr == 0)
6443 goto out;
6445 if (btrfs_file_extent_compression(leaf, fi) ||
6446 btrfs_file_extent_encryption(leaf, fi) ||
6447 btrfs_file_extent_other_encoding(leaf, fi))
6448 goto out;
6450 backref_offset = btrfs_file_extent_offset(leaf, fi);
6452 if (orig_start) {
6453 *orig_start = key.offset - backref_offset;
6454 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6455 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6458 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6460 if (btrfs_extent_readonly(root, disk_bytenr))
6461 goto out;
6462 btrfs_release_path(path);
6465 * look for other files referencing this extent, if we
6466 * find any we must cow
6468 trans = btrfs_join_transaction(root);
6469 if (IS_ERR(trans)) {
6470 ret = 0;
6471 goto out;
6474 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6475 key.offset - backref_offset, disk_bytenr);
6476 btrfs_end_transaction(trans, root);
6477 if (ret) {
6478 ret = 0;
6479 goto out;
6483 * adjust disk_bytenr and num_bytes to cover just the bytes
6484 * in this extent we are about to write. If there
6485 * are any csums in that range we have to cow in order
6486 * to keep the csums correct
6488 disk_bytenr += backref_offset;
6489 disk_bytenr += offset - key.offset;
6490 num_bytes = min(offset + *len, extent_end) - offset;
6491 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6492 goto out;
6494 * all of the above have passed, it is safe to overwrite this extent
6495 * without cow
6497 *len = num_bytes;
6498 ret = 1;
6499 out:
6500 btrfs_free_path(path);
6501 return ret;
6504 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6505 struct extent_state **cached_state, int writing)
6507 struct btrfs_ordered_extent *ordered;
6508 int ret = 0;
6510 while (1) {
6511 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6512 0, cached_state);
6514 * We're concerned with the entire range that we're going to be
6515 * doing DIO to, so we need to make sure theres no ordered
6516 * extents in this range.
6518 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6519 lockend - lockstart + 1);
6522 * We need to make sure there are no buffered pages in this
6523 * range either, we could have raced between the invalidate in
6524 * generic_file_direct_write and locking the extent. The
6525 * invalidate needs to happen so that reads after a write do not
6526 * get stale data.
6528 if (!ordered && (!writing ||
6529 !test_range_bit(&BTRFS_I(inode)->io_tree,
6530 lockstart, lockend, EXTENT_UPTODATE, 0,
6531 *cached_state)))
6532 break;
6534 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6535 cached_state, GFP_NOFS);
6537 if (ordered) {
6538 btrfs_start_ordered_extent(inode, ordered, 1);
6539 btrfs_put_ordered_extent(ordered);
6540 } else {
6541 /* Screw you mmap */
6542 ret = filemap_write_and_wait_range(inode->i_mapping,
6543 lockstart,
6544 lockend);
6545 if (ret)
6546 break;
6549 * If we found a page that couldn't be invalidated just
6550 * fall back to buffered.
6552 ret = invalidate_inode_pages2_range(inode->i_mapping,
6553 lockstart >> PAGE_CACHE_SHIFT,
6554 lockend >> PAGE_CACHE_SHIFT);
6555 if (ret)
6556 break;
6559 cond_resched();
6562 return ret;
6565 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6566 u64 len, u64 orig_start,
6567 u64 block_start, u64 block_len,
6568 u64 orig_block_len, u64 ram_bytes,
6569 int type)
6571 struct extent_map_tree *em_tree;
6572 struct extent_map *em;
6573 struct btrfs_root *root = BTRFS_I(inode)->root;
6574 int ret;
6576 em_tree = &BTRFS_I(inode)->extent_tree;
6577 em = alloc_extent_map();
6578 if (!em)
6579 return ERR_PTR(-ENOMEM);
6581 em->start = start;
6582 em->orig_start = orig_start;
6583 em->mod_start = start;
6584 em->mod_len = len;
6585 em->len = len;
6586 em->block_len = block_len;
6587 em->block_start = block_start;
6588 em->bdev = root->fs_info->fs_devices->latest_bdev;
6589 em->orig_block_len = orig_block_len;
6590 em->ram_bytes = ram_bytes;
6591 em->generation = -1;
6592 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6593 if (type == BTRFS_ORDERED_PREALLOC)
6594 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6596 do {
6597 btrfs_drop_extent_cache(inode, em->start,
6598 em->start + em->len - 1, 0);
6599 write_lock(&em_tree->lock);
6600 ret = add_extent_mapping(em_tree, em, 1);
6601 write_unlock(&em_tree->lock);
6602 } while (ret == -EEXIST);
6604 if (ret) {
6605 free_extent_map(em);
6606 return ERR_PTR(ret);
6609 return em;
6613 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6614 struct buffer_head *bh_result, int create)
6616 struct extent_map *em;
6617 struct btrfs_root *root = BTRFS_I(inode)->root;
6618 struct extent_state *cached_state = NULL;
6619 u64 start = iblock << inode->i_blkbits;
6620 u64 lockstart, lockend;
6621 u64 len = bh_result->b_size;
6622 int unlock_bits = EXTENT_LOCKED;
6623 int ret = 0;
6625 if (create)
6626 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6627 else
6628 len = min_t(u64, len, root->sectorsize);
6630 lockstart = start;
6631 lockend = start + len - 1;
6634 * If this errors out it's because we couldn't invalidate pagecache for
6635 * this range and we need to fallback to buffered.
6637 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6638 return -ENOTBLK;
6640 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6641 if (IS_ERR(em)) {
6642 ret = PTR_ERR(em);
6643 goto unlock_err;
6647 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6648 * io. INLINE is special, and we could probably kludge it in here, but
6649 * it's still buffered so for safety lets just fall back to the generic
6650 * buffered path.
6652 * For COMPRESSED we _have_ to read the entire extent in so we can
6653 * decompress it, so there will be buffering required no matter what we
6654 * do, so go ahead and fallback to buffered.
6656 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6657 * to buffered IO. Don't blame me, this is the price we pay for using
6658 * the generic code.
6660 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6661 em->block_start == EXTENT_MAP_INLINE) {
6662 free_extent_map(em);
6663 ret = -ENOTBLK;
6664 goto unlock_err;
6667 /* Just a good old fashioned hole, return */
6668 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6669 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6670 free_extent_map(em);
6671 goto unlock_err;
6675 * We don't allocate a new extent in the following cases
6677 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6678 * existing extent.
6679 * 2) The extent is marked as PREALLOC. We're good to go here and can
6680 * just use the extent.
6683 if (!create) {
6684 len = min(len, em->len - (start - em->start));
6685 lockstart = start + len;
6686 goto unlock;
6689 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6690 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6691 em->block_start != EXTENT_MAP_HOLE)) {
6692 int type;
6693 int ret;
6694 u64 block_start, orig_start, orig_block_len, ram_bytes;
6696 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6697 type = BTRFS_ORDERED_PREALLOC;
6698 else
6699 type = BTRFS_ORDERED_NOCOW;
6700 len = min(len, em->len - (start - em->start));
6701 block_start = em->block_start + (start - em->start);
6703 if (can_nocow_extent(inode, start, &len, &orig_start,
6704 &orig_block_len, &ram_bytes) == 1) {
6705 if (type == BTRFS_ORDERED_PREALLOC) {
6706 free_extent_map(em);
6707 em = create_pinned_em(inode, start, len,
6708 orig_start,
6709 block_start, len,
6710 orig_block_len,
6711 ram_bytes, type);
6712 if (IS_ERR(em))
6713 goto unlock_err;
6716 ret = btrfs_add_ordered_extent_dio(inode, start,
6717 block_start, len, len, type);
6718 if (ret) {
6719 free_extent_map(em);
6720 goto unlock_err;
6722 goto unlock;
6727 * this will cow the extent, reset the len in case we changed
6728 * it above
6730 len = bh_result->b_size;
6731 free_extent_map(em);
6732 em = btrfs_new_extent_direct(inode, start, len);
6733 if (IS_ERR(em)) {
6734 ret = PTR_ERR(em);
6735 goto unlock_err;
6737 len = min(len, em->len - (start - em->start));
6738 unlock:
6739 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6740 inode->i_blkbits;
6741 bh_result->b_size = len;
6742 bh_result->b_bdev = em->bdev;
6743 set_buffer_mapped(bh_result);
6744 if (create) {
6745 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6746 set_buffer_new(bh_result);
6749 * Need to update the i_size under the extent lock so buffered
6750 * readers will get the updated i_size when we unlock.
6752 if (start + len > i_size_read(inode))
6753 i_size_write(inode, start + len);
6755 spin_lock(&BTRFS_I(inode)->lock);
6756 BTRFS_I(inode)->outstanding_extents++;
6757 spin_unlock(&BTRFS_I(inode)->lock);
6759 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6760 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6761 &cached_state, GFP_NOFS);
6762 BUG_ON(ret);
6766 * In the case of write we need to clear and unlock the entire range,
6767 * in the case of read we need to unlock only the end area that we
6768 * aren't using if there is any left over space.
6770 if (lockstart < lockend) {
6771 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6772 lockend, unlock_bits, 1, 0,
6773 &cached_state, GFP_NOFS);
6774 } else {
6775 free_extent_state(cached_state);
6778 free_extent_map(em);
6780 return 0;
6782 unlock_err:
6783 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6784 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6785 return ret;
6788 static void btrfs_endio_direct_read(struct bio *bio, int err)
6790 struct btrfs_dio_private *dip = bio->bi_private;
6791 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6792 struct bio_vec *bvec = bio->bi_io_vec;
6793 struct inode *inode = dip->inode;
6794 struct btrfs_root *root = BTRFS_I(inode)->root;
6795 struct bio *dio_bio;
6796 u32 *csums = (u32 *)dip->csum;
6797 int index = 0;
6798 u64 start;
6800 start = dip->logical_offset;
6801 do {
6802 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6803 struct page *page = bvec->bv_page;
6804 char *kaddr;
6805 u32 csum = ~(u32)0;
6806 unsigned long flags;
6808 local_irq_save(flags);
6809 kaddr = kmap_atomic(page);
6810 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6811 csum, bvec->bv_len);
6812 btrfs_csum_final(csum, (char *)&csum);
6813 kunmap_atomic(kaddr);
6814 local_irq_restore(flags);
6816 flush_dcache_page(bvec->bv_page);
6817 if (csum != csums[index]) {
6818 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6819 btrfs_ino(inode), start, csum,
6820 csums[index]);
6821 err = -EIO;
6825 start += bvec->bv_len;
6826 bvec++;
6827 index++;
6828 } while (bvec <= bvec_end);
6830 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6831 dip->logical_offset + dip->bytes - 1);
6832 dio_bio = dip->dio_bio;
6834 kfree(dip);
6836 /* If we had a csum failure make sure to clear the uptodate flag */
6837 if (err)
6838 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6839 dio_end_io(dio_bio, err);
6840 bio_put(bio);
6843 static void btrfs_endio_direct_write(struct bio *bio, int err)
6845 struct btrfs_dio_private *dip = bio->bi_private;
6846 struct inode *inode = dip->inode;
6847 struct btrfs_root *root = BTRFS_I(inode)->root;
6848 struct btrfs_ordered_extent *ordered = NULL;
6849 u64 ordered_offset = dip->logical_offset;
6850 u64 ordered_bytes = dip->bytes;
6851 struct bio *dio_bio;
6852 int ret;
6854 if (err)
6855 goto out_done;
6856 again:
6857 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6858 &ordered_offset,
6859 ordered_bytes, !err);
6860 if (!ret)
6861 goto out_test;
6863 ordered->work.func = finish_ordered_fn;
6864 ordered->work.flags = 0;
6865 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6866 &ordered->work);
6867 out_test:
6869 * our bio might span multiple ordered extents. If we haven't
6870 * completed the accounting for the whole dio, go back and try again
6872 if (ordered_offset < dip->logical_offset + dip->bytes) {
6873 ordered_bytes = dip->logical_offset + dip->bytes -
6874 ordered_offset;
6875 ordered = NULL;
6876 goto again;
6878 out_done:
6879 dio_bio = dip->dio_bio;
6881 kfree(dip);
6883 /* If we had an error make sure to clear the uptodate flag */
6884 if (err)
6885 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6886 dio_end_io(dio_bio, err);
6887 bio_put(bio);
6890 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6891 struct bio *bio, int mirror_num,
6892 unsigned long bio_flags, u64 offset)
6894 int ret;
6895 struct btrfs_root *root = BTRFS_I(inode)->root;
6896 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6897 BUG_ON(ret); /* -ENOMEM */
6898 return 0;
6901 static void btrfs_end_dio_bio(struct bio *bio, int err)
6903 struct btrfs_dio_private *dip = bio->bi_private;
6905 if (err) {
6906 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6907 "sector %#Lx len %u err no %d\n",
6908 btrfs_ino(dip->inode), bio->bi_rw,
6909 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6910 dip->errors = 1;
6913 * before atomic variable goto zero, we must make sure
6914 * dip->errors is perceived to be set.
6916 smp_mb__before_atomic_dec();
6919 /* if there are more bios still pending for this dio, just exit */
6920 if (!atomic_dec_and_test(&dip->pending_bios))
6921 goto out;
6923 if (dip->errors) {
6924 bio_io_error(dip->orig_bio);
6925 } else {
6926 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
6927 bio_endio(dip->orig_bio, 0);
6929 out:
6930 bio_put(bio);
6933 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6934 u64 first_sector, gfp_t gfp_flags)
6936 int nr_vecs = bio_get_nr_vecs(bdev);
6937 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6940 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6941 int rw, u64 file_offset, int skip_sum,
6942 int async_submit)
6944 struct btrfs_dio_private *dip = bio->bi_private;
6945 int write = rw & REQ_WRITE;
6946 struct btrfs_root *root = BTRFS_I(inode)->root;
6947 int ret;
6949 if (async_submit)
6950 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6952 bio_get(bio);
6954 if (!write) {
6955 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6956 if (ret)
6957 goto err;
6960 if (skip_sum)
6961 goto map;
6963 if (write && async_submit) {
6964 ret = btrfs_wq_submit_bio(root->fs_info,
6965 inode, rw, bio, 0, 0,
6966 file_offset,
6967 __btrfs_submit_bio_start_direct_io,
6968 __btrfs_submit_bio_done);
6969 goto err;
6970 } else if (write) {
6972 * If we aren't doing async submit, calculate the csum of the
6973 * bio now.
6975 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6976 if (ret)
6977 goto err;
6978 } else if (!skip_sum) {
6979 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
6980 file_offset);
6981 if (ret)
6982 goto err;
6985 map:
6986 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6987 err:
6988 bio_put(bio);
6989 return ret;
6992 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6993 int skip_sum)
6995 struct inode *inode = dip->inode;
6996 struct btrfs_root *root = BTRFS_I(inode)->root;
6997 struct bio *bio;
6998 struct bio *orig_bio = dip->orig_bio;
6999 struct bio_vec *bvec = orig_bio->bi_io_vec;
7000 u64 start_sector = orig_bio->bi_sector;
7001 u64 file_offset = dip->logical_offset;
7002 u64 submit_len = 0;
7003 u64 map_length;
7004 int nr_pages = 0;
7005 int ret = 0;
7006 int async_submit = 0;
7008 map_length = orig_bio->bi_size;
7009 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7010 &map_length, NULL, 0);
7011 if (ret) {
7012 bio_put(orig_bio);
7013 return -EIO;
7016 if (map_length >= orig_bio->bi_size) {
7017 bio = orig_bio;
7018 goto submit;
7021 /* async crcs make it difficult to collect full stripe writes. */
7022 if (btrfs_get_alloc_profile(root, 1) &
7023 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7024 async_submit = 0;
7025 else
7026 async_submit = 1;
7028 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7029 if (!bio)
7030 return -ENOMEM;
7031 bio->bi_private = dip;
7032 bio->bi_end_io = btrfs_end_dio_bio;
7033 atomic_inc(&dip->pending_bios);
7035 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7036 if (unlikely(map_length < submit_len + bvec->bv_len ||
7037 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7038 bvec->bv_offset) < bvec->bv_len)) {
7040 * inc the count before we submit the bio so
7041 * we know the end IO handler won't happen before
7042 * we inc the count. Otherwise, the dip might get freed
7043 * before we're done setting it up
7045 atomic_inc(&dip->pending_bios);
7046 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7047 file_offset, skip_sum,
7048 async_submit);
7049 if (ret) {
7050 bio_put(bio);
7051 atomic_dec(&dip->pending_bios);
7052 goto out_err;
7055 start_sector += submit_len >> 9;
7056 file_offset += submit_len;
7058 submit_len = 0;
7059 nr_pages = 0;
7061 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7062 start_sector, GFP_NOFS);
7063 if (!bio)
7064 goto out_err;
7065 bio->bi_private = dip;
7066 bio->bi_end_io = btrfs_end_dio_bio;
7068 map_length = orig_bio->bi_size;
7069 ret = btrfs_map_block(root->fs_info, rw,
7070 start_sector << 9,
7071 &map_length, NULL, 0);
7072 if (ret) {
7073 bio_put(bio);
7074 goto out_err;
7076 } else {
7077 submit_len += bvec->bv_len;
7078 nr_pages ++;
7079 bvec++;
7083 submit:
7084 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7085 async_submit);
7086 if (!ret)
7087 return 0;
7089 bio_put(bio);
7090 out_err:
7091 dip->errors = 1;
7093 * before atomic variable goto zero, we must
7094 * make sure dip->errors is perceived to be set.
7096 smp_mb__before_atomic_dec();
7097 if (atomic_dec_and_test(&dip->pending_bios))
7098 bio_io_error(dip->orig_bio);
7100 /* bio_end_io() will handle error, so we needn't return it */
7101 return 0;
7104 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7105 struct inode *inode, loff_t file_offset)
7107 struct btrfs_root *root = BTRFS_I(inode)->root;
7108 struct btrfs_dio_private *dip;
7109 struct bio *io_bio;
7110 int skip_sum;
7111 int sum_len;
7112 int write = rw & REQ_WRITE;
7113 int ret = 0;
7114 u16 csum_size;
7116 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7118 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7119 if (!io_bio) {
7120 ret = -ENOMEM;
7121 goto free_ordered;
7124 if (!skip_sum && !write) {
7125 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7126 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7127 sum_len *= csum_size;
7128 } else {
7129 sum_len = 0;
7132 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7133 if (!dip) {
7134 ret = -ENOMEM;
7135 goto free_io_bio;
7138 dip->private = dio_bio->bi_private;
7139 dip->inode = inode;
7140 dip->logical_offset = file_offset;
7141 dip->bytes = dio_bio->bi_size;
7142 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7143 io_bio->bi_private = dip;
7144 dip->errors = 0;
7145 dip->orig_bio = io_bio;
7146 dip->dio_bio = dio_bio;
7147 atomic_set(&dip->pending_bios, 0);
7149 if (write)
7150 io_bio->bi_end_io = btrfs_endio_direct_write;
7151 else
7152 io_bio->bi_end_io = btrfs_endio_direct_read;
7154 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7155 if (!ret)
7156 return;
7158 free_io_bio:
7159 bio_put(io_bio);
7161 free_ordered:
7163 * If this is a write, we need to clean up the reserved space and kill
7164 * the ordered extent.
7166 if (write) {
7167 struct btrfs_ordered_extent *ordered;
7168 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7169 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7170 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7171 btrfs_free_reserved_extent(root, ordered->start,
7172 ordered->disk_len);
7173 btrfs_put_ordered_extent(ordered);
7174 btrfs_put_ordered_extent(ordered);
7176 bio_endio(dio_bio, ret);
7179 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7180 const struct iovec *iov, loff_t offset,
7181 unsigned long nr_segs)
7183 int seg;
7184 int i;
7185 size_t size;
7186 unsigned long addr;
7187 unsigned blocksize_mask = root->sectorsize - 1;
7188 ssize_t retval = -EINVAL;
7189 loff_t end = offset;
7191 if (offset & blocksize_mask)
7192 goto out;
7194 /* Check the memory alignment. Blocks cannot straddle pages */
7195 for (seg = 0; seg < nr_segs; seg++) {
7196 addr = (unsigned long)iov[seg].iov_base;
7197 size = iov[seg].iov_len;
7198 end += size;
7199 if ((addr & blocksize_mask) || (size & blocksize_mask))
7200 goto out;
7202 /* If this is a write we don't need to check anymore */
7203 if (rw & WRITE)
7204 continue;
7207 * Check to make sure we don't have duplicate iov_base's in this
7208 * iovec, if so return EINVAL, otherwise we'll get csum errors
7209 * when reading back.
7211 for (i = seg + 1; i < nr_segs; i++) {
7212 if (iov[seg].iov_base == iov[i].iov_base)
7213 goto out;
7216 retval = 0;
7217 out:
7218 return retval;
7221 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7222 const struct iovec *iov, loff_t offset,
7223 unsigned long nr_segs)
7225 struct file *file = iocb->ki_filp;
7226 struct inode *inode = file->f_mapping->host;
7227 size_t count = 0;
7228 int flags = 0;
7229 bool wakeup = true;
7230 bool relock = false;
7231 ssize_t ret;
7233 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7234 offset, nr_segs))
7235 return 0;
7237 atomic_inc(&inode->i_dio_count);
7238 smp_mb__after_atomic_inc();
7241 * The generic stuff only does filemap_write_and_wait_range, which isn't
7242 * enough if we've written compressed pages to this area, so we need to
7243 * call btrfs_wait_ordered_range to make absolutely sure that any
7244 * outstanding dirty pages are on disk.
7246 count = iov_length(iov, nr_segs);
7247 btrfs_wait_ordered_range(inode, offset, count);
7249 if (rw & WRITE) {
7251 * If the write DIO is beyond the EOF, we need update
7252 * the isize, but it is protected by i_mutex. So we can
7253 * not unlock the i_mutex at this case.
7255 if (offset + count <= inode->i_size) {
7256 mutex_unlock(&inode->i_mutex);
7257 relock = true;
7259 ret = btrfs_delalloc_reserve_space(inode, count);
7260 if (ret)
7261 goto out;
7262 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7263 &BTRFS_I(inode)->runtime_flags))) {
7264 inode_dio_done(inode);
7265 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7266 wakeup = false;
7269 ret = __blockdev_direct_IO(rw, iocb, inode,
7270 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7271 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7272 btrfs_submit_direct, flags);
7273 if (rw & WRITE) {
7274 if (ret < 0 && ret != -EIOCBQUEUED)
7275 btrfs_delalloc_release_space(inode, count);
7276 else if (ret >= 0 && (size_t)ret < count)
7277 btrfs_delalloc_release_space(inode,
7278 count - (size_t)ret);
7279 else
7280 btrfs_delalloc_release_metadata(inode, 0);
7282 out:
7283 if (wakeup)
7284 inode_dio_done(inode);
7285 if (relock)
7286 mutex_lock(&inode->i_mutex);
7288 return ret;
7291 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7293 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7294 __u64 start, __u64 len)
7296 int ret;
7298 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7299 if (ret)
7300 return ret;
7302 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7305 int btrfs_readpage(struct file *file, struct page *page)
7307 struct extent_io_tree *tree;
7308 tree = &BTRFS_I(page->mapping->host)->io_tree;
7309 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7312 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7314 struct extent_io_tree *tree;
7317 if (current->flags & PF_MEMALLOC) {
7318 redirty_page_for_writepage(wbc, page);
7319 unlock_page(page);
7320 return 0;
7322 tree = &BTRFS_I(page->mapping->host)->io_tree;
7323 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7326 static int btrfs_writepages(struct address_space *mapping,
7327 struct writeback_control *wbc)
7329 struct extent_io_tree *tree;
7331 tree = &BTRFS_I(mapping->host)->io_tree;
7332 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7335 static int
7336 btrfs_readpages(struct file *file, struct address_space *mapping,
7337 struct list_head *pages, unsigned nr_pages)
7339 struct extent_io_tree *tree;
7340 tree = &BTRFS_I(mapping->host)->io_tree;
7341 return extent_readpages(tree, mapping, pages, nr_pages,
7342 btrfs_get_extent);
7344 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7346 struct extent_io_tree *tree;
7347 struct extent_map_tree *map;
7348 int ret;
7350 tree = &BTRFS_I(page->mapping->host)->io_tree;
7351 map = &BTRFS_I(page->mapping->host)->extent_tree;
7352 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7353 if (ret == 1) {
7354 ClearPagePrivate(page);
7355 set_page_private(page, 0);
7356 page_cache_release(page);
7358 return ret;
7361 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7363 if (PageWriteback(page) || PageDirty(page))
7364 return 0;
7365 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7368 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7369 unsigned int length)
7371 struct inode *inode = page->mapping->host;
7372 struct extent_io_tree *tree;
7373 struct btrfs_ordered_extent *ordered;
7374 struct extent_state *cached_state = NULL;
7375 u64 page_start = page_offset(page);
7376 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7379 * we have the page locked, so new writeback can't start,
7380 * and the dirty bit won't be cleared while we are here.
7382 * Wait for IO on this page so that we can safely clear
7383 * the PagePrivate2 bit and do ordered accounting
7385 wait_on_page_writeback(page);
7387 tree = &BTRFS_I(inode)->io_tree;
7388 if (offset) {
7389 btrfs_releasepage(page, GFP_NOFS);
7390 return;
7392 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7393 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7394 if (ordered) {
7396 * IO on this page will never be started, so we need
7397 * to account for any ordered extents now
7399 clear_extent_bit(tree, page_start, page_end,
7400 EXTENT_DIRTY | EXTENT_DELALLOC |
7401 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7402 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7404 * whoever cleared the private bit is responsible
7405 * for the finish_ordered_io
7407 if (TestClearPagePrivate2(page)) {
7408 struct btrfs_ordered_inode_tree *tree;
7409 u64 new_len;
7411 tree = &BTRFS_I(inode)->ordered_tree;
7413 spin_lock_irq(&tree->lock);
7414 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7415 new_len = page_start - ordered->file_offset;
7416 if (new_len < ordered->truncated_len)
7417 ordered->truncated_len = new_len;
7418 spin_unlock_irq(&tree->lock);
7420 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7421 page_start,
7422 PAGE_CACHE_SIZE, 1))
7423 btrfs_finish_ordered_io(ordered);
7425 btrfs_put_ordered_extent(ordered);
7426 cached_state = NULL;
7427 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7429 clear_extent_bit(tree, page_start, page_end,
7430 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7431 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7432 &cached_state, GFP_NOFS);
7433 __btrfs_releasepage(page, GFP_NOFS);
7435 ClearPageChecked(page);
7436 if (PagePrivate(page)) {
7437 ClearPagePrivate(page);
7438 set_page_private(page, 0);
7439 page_cache_release(page);
7444 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7445 * called from a page fault handler when a page is first dirtied. Hence we must
7446 * be careful to check for EOF conditions here. We set the page up correctly
7447 * for a written page which means we get ENOSPC checking when writing into
7448 * holes and correct delalloc and unwritten extent mapping on filesystems that
7449 * support these features.
7451 * We are not allowed to take the i_mutex here so we have to play games to
7452 * protect against truncate races as the page could now be beyond EOF. Because
7453 * vmtruncate() writes the inode size before removing pages, once we have the
7454 * page lock we can determine safely if the page is beyond EOF. If it is not
7455 * beyond EOF, then the page is guaranteed safe against truncation until we
7456 * unlock the page.
7458 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7460 struct page *page = vmf->page;
7461 struct inode *inode = file_inode(vma->vm_file);
7462 struct btrfs_root *root = BTRFS_I(inode)->root;
7463 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7464 struct btrfs_ordered_extent *ordered;
7465 struct extent_state *cached_state = NULL;
7466 char *kaddr;
7467 unsigned long zero_start;
7468 loff_t size;
7469 int ret;
7470 int reserved = 0;
7471 u64 page_start;
7472 u64 page_end;
7474 sb_start_pagefault(inode->i_sb);
7475 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7476 if (!ret) {
7477 ret = file_update_time(vma->vm_file);
7478 reserved = 1;
7480 if (ret) {
7481 if (ret == -ENOMEM)
7482 ret = VM_FAULT_OOM;
7483 else /* -ENOSPC, -EIO, etc */
7484 ret = VM_FAULT_SIGBUS;
7485 if (reserved)
7486 goto out;
7487 goto out_noreserve;
7490 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7491 again:
7492 lock_page(page);
7493 size = i_size_read(inode);
7494 page_start = page_offset(page);
7495 page_end = page_start + PAGE_CACHE_SIZE - 1;
7497 if ((page->mapping != inode->i_mapping) ||
7498 (page_start >= size)) {
7499 /* page got truncated out from underneath us */
7500 goto out_unlock;
7502 wait_on_page_writeback(page);
7504 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7505 set_page_extent_mapped(page);
7508 * we can't set the delalloc bits if there are pending ordered
7509 * extents. Drop our locks and wait for them to finish
7511 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7512 if (ordered) {
7513 unlock_extent_cached(io_tree, page_start, page_end,
7514 &cached_state, GFP_NOFS);
7515 unlock_page(page);
7516 btrfs_start_ordered_extent(inode, ordered, 1);
7517 btrfs_put_ordered_extent(ordered);
7518 goto again;
7522 * XXX - page_mkwrite gets called every time the page is dirtied, even
7523 * if it was already dirty, so for space accounting reasons we need to
7524 * clear any delalloc bits for the range we are fixing to save. There
7525 * is probably a better way to do this, but for now keep consistent with
7526 * prepare_pages in the normal write path.
7528 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7529 EXTENT_DIRTY | EXTENT_DELALLOC |
7530 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7531 0, 0, &cached_state, GFP_NOFS);
7533 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7534 &cached_state);
7535 if (ret) {
7536 unlock_extent_cached(io_tree, page_start, page_end,
7537 &cached_state, GFP_NOFS);
7538 ret = VM_FAULT_SIGBUS;
7539 goto out_unlock;
7541 ret = 0;
7543 /* page is wholly or partially inside EOF */
7544 if (page_start + PAGE_CACHE_SIZE > size)
7545 zero_start = size & ~PAGE_CACHE_MASK;
7546 else
7547 zero_start = PAGE_CACHE_SIZE;
7549 if (zero_start != PAGE_CACHE_SIZE) {
7550 kaddr = kmap(page);
7551 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7552 flush_dcache_page(page);
7553 kunmap(page);
7555 ClearPageChecked(page);
7556 set_page_dirty(page);
7557 SetPageUptodate(page);
7559 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7560 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7561 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7563 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7565 out_unlock:
7566 if (!ret) {
7567 sb_end_pagefault(inode->i_sb);
7568 return VM_FAULT_LOCKED;
7570 unlock_page(page);
7571 out:
7572 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7573 out_noreserve:
7574 sb_end_pagefault(inode->i_sb);
7575 return ret;
7578 static int btrfs_truncate(struct inode *inode)
7580 struct btrfs_root *root = BTRFS_I(inode)->root;
7581 struct btrfs_block_rsv *rsv;
7582 int ret = 0;
7583 int err = 0;
7584 struct btrfs_trans_handle *trans;
7585 u64 mask = root->sectorsize - 1;
7586 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7588 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7591 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7592 * 3 things going on here
7594 * 1) We need to reserve space for our orphan item and the space to
7595 * delete our orphan item. Lord knows we don't want to have a dangling
7596 * orphan item because we didn't reserve space to remove it.
7598 * 2) We need to reserve space to update our inode.
7600 * 3) We need to have something to cache all the space that is going to
7601 * be free'd up by the truncate operation, but also have some slack
7602 * space reserved in case it uses space during the truncate (thank you
7603 * very much snapshotting).
7605 * And we need these to all be seperate. The fact is we can use alot of
7606 * space doing the truncate, and we have no earthly idea how much space
7607 * we will use, so we need the truncate reservation to be seperate so it
7608 * doesn't end up using space reserved for updating the inode or
7609 * removing the orphan item. We also need to be able to stop the
7610 * transaction and start a new one, which means we need to be able to
7611 * update the inode several times, and we have no idea of knowing how
7612 * many times that will be, so we can't just reserve 1 item for the
7613 * entirety of the opration, so that has to be done seperately as well.
7614 * Then there is the orphan item, which does indeed need to be held on
7615 * to for the whole operation, and we need nobody to touch this reserved
7616 * space except the orphan code.
7618 * So that leaves us with
7620 * 1) root->orphan_block_rsv - for the orphan deletion.
7621 * 2) rsv - for the truncate reservation, which we will steal from the
7622 * transaction reservation.
7623 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7624 * updating the inode.
7626 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7627 if (!rsv)
7628 return -ENOMEM;
7629 rsv->size = min_size;
7630 rsv->failfast = 1;
7633 * 1 for the truncate slack space
7634 * 1 for updating the inode.
7636 trans = btrfs_start_transaction(root, 2);
7637 if (IS_ERR(trans)) {
7638 err = PTR_ERR(trans);
7639 goto out;
7642 /* Migrate the slack space for the truncate to our reserve */
7643 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7644 min_size);
7645 BUG_ON(ret);
7648 * setattr is responsible for setting the ordered_data_close flag,
7649 * but that is only tested during the last file release. That
7650 * could happen well after the next commit, leaving a great big
7651 * window where new writes may get lost if someone chooses to write
7652 * to this file after truncating to zero
7654 * The inode doesn't have any dirty data here, and so if we commit
7655 * this is a noop. If someone immediately starts writing to the inode
7656 * it is very likely we'll catch some of their writes in this
7657 * transaction, and the commit will find this file on the ordered
7658 * data list with good things to send down.
7660 * This is a best effort solution, there is still a window where
7661 * using truncate to replace the contents of the file will
7662 * end up with a zero length file after a crash.
7664 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7665 &BTRFS_I(inode)->runtime_flags))
7666 btrfs_add_ordered_operation(trans, root, inode);
7669 * So if we truncate and then write and fsync we normally would just
7670 * write the extents that changed, which is a problem if we need to
7671 * first truncate that entire inode. So set this flag so we write out
7672 * all of the extents in the inode to the sync log so we're completely
7673 * safe.
7675 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7676 trans->block_rsv = rsv;
7678 while (1) {
7679 ret = btrfs_truncate_inode_items(trans, root, inode,
7680 inode->i_size,
7681 BTRFS_EXTENT_DATA_KEY);
7682 if (ret != -ENOSPC) {
7683 err = ret;
7684 break;
7687 trans->block_rsv = &root->fs_info->trans_block_rsv;
7688 ret = btrfs_update_inode(trans, root, inode);
7689 if (ret) {
7690 err = ret;
7691 break;
7694 btrfs_end_transaction(trans, root);
7695 btrfs_btree_balance_dirty(root);
7697 trans = btrfs_start_transaction(root, 2);
7698 if (IS_ERR(trans)) {
7699 ret = err = PTR_ERR(trans);
7700 trans = NULL;
7701 break;
7704 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7705 rsv, min_size);
7706 BUG_ON(ret); /* shouldn't happen */
7707 trans->block_rsv = rsv;
7710 if (ret == 0 && inode->i_nlink > 0) {
7711 trans->block_rsv = root->orphan_block_rsv;
7712 ret = btrfs_orphan_del(trans, inode);
7713 if (ret)
7714 err = ret;
7717 if (trans) {
7718 trans->block_rsv = &root->fs_info->trans_block_rsv;
7719 ret = btrfs_update_inode(trans, root, inode);
7720 if (ret && !err)
7721 err = ret;
7723 ret = btrfs_end_transaction(trans, root);
7724 btrfs_btree_balance_dirty(root);
7727 out:
7728 btrfs_free_block_rsv(root, rsv);
7730 if (ret && !err)
7731 err = ret;
7733 return err;
7737 * create a new subvolume directory/inode (helper for the ioctl).
7739 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7740 struct btrfs_root *new_root, u64 new_dirid)
7742 struct inode *inode;
7743 int err;
7744 u64 index = 0;
7746 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7747 new_dirid, new_dirid,
7748 S_IFDIR | (~current_umask() & S_IRWXUGO),
7749 &index);
7750 if (IS_ERR(inode))
7751 return PTR_ERR(inode);
7752 inode->i_op = &btrfs_dir_inode_operations;
7753 inode->i_fop = &btrfs_dir_file_operations;
7755 set_nlink(inode, 1);
7756 btrfs_i_size_write(inode, 0);
7758 err = btrfs_update_inode(trans, new_root, inode);
7760 iput(inode);
7761 return err;
7764 struct inode *btrfs_alloc_inode(struct super_block *sb)
7766 struct btrfs_inode *ei;
7767 struct inode *inode;
7769 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7770 if (!ei)
7771 return NULL;
7773 ei->root = NULL;
7774 ei->generation = 0;
7775 ei->last_trans = 0;
7776 ei->last_sub_trans = 0;
7777 ei->logged_trans = 0;
7778 ei->delalloc_bytes = 0;
7779 ei->disk_i_size = 0;
7780 ei->flags = 0;
7781 ei->csum_bytes = 0;
7782 ei->index_cnt = (u64)-1;
7783 ei->last_unlink_trans = 0;
7784 ei->last_log_commit = 0;
7786 spin_lock_init(&ei->lock);
7787 ei->outstanding_extents = 0;
7788 ei->reserved_extents = 0;
7790 ei->runtime_flags = 0;
7791 ei->force_compress = BTRFS_COMPRESS_NONE;
7793 ei->delayed_node = NULL;
7795 inode = &ei->vfs_inode;
7796 extent_map_tree_init(&ei->extent_tree);
7797 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7798 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7799 ei->io_tree.track_uptodate = 1;
7800 ei->io_failure_tree.track_uptodate = 1;
7801 atomic_set(&ei->sync_writers, 0);
7802 mutex_init(&ei->log_mutex);
7803 mutex_init(&ei->delalloc_mutex);
7804 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7805 INIT_LIST_HEAD(&ei->delalloc_inodes);
7806 INIT_LIST_HEAD(&ei->ordered_operations);
7807 RB_CLEAR_NODE(&ei->rb_node);
7809 return inode;
7812 static void btrfs_i_callback(struct rcu_head *head)
7814 struct inode *inode = container_of(head, struct inode, i_rcu);
7815 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7818 void btrfs_destroy_inode(struct inode *inode)
7820 struct btrfs_ordered_extent *ordered;
7821 struct btrfs_root *root = BTRFS_I(inode)->root;
7823 WARN_ON(!hlist_empty(&inode->i_dentry));
7824 WARN_ON(inode->i_data.nrpages);
7825 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7826 WARN_ON(BTRFS_I(inode)->reserved_extents);
7827 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7828 WARN_ON(BTRFS_I(inode)->csum_bytes);
7831 * This can happen where we create an inode, but somebody else also
7832 * created the same inode and we need to destroy the one we already
7833 * created.
7835 if (!root)
7836 goto free;
7839 * Make sure we're properly removed from the ordered operation
7840 * lists.
7842 smp_mb();
7843 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7844 spin_lock(&root->fs_info->ordered_root_lock);
7845 list_del_init(&BTRFS_I(inode)->ordered_operations);
7846 spin_unlock(&root->fs_info->ordered_root_lock);
7849 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7850 &BTRFS_I(inode)->runtime_flags)) {
7851 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7852 btrfs_ino(inode));
7853 atomic_dec(&root->orphan_inodes);
7856 while (1) {
7857 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7858 if (!ordered)
7859 break;
7860 else {
7861 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7862 ordered->file_offset, ordered->len);
7863 btrfs_remove_ordered_extent(inode, ordered);
7864 btrfs_put_ordered_extent(ordered);
7865 btrfs_put_ordered_extent(ordered);
7868 inode_tree_del(inode);
7869 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7870 free:
7871 call_rcu(&inode->i_rcu, btrfs_i_callback);
7874 int btrfs_drop_inode(struct inode *inode)
7876 struct btrfs_root *root = BTRFS_I(inode)->root;
7878 if (root == NULL)
7879 return 1;
7881 /* the snap/subvol tree is on deleting */
7882 if (btrfs_root_refs(&root->root_item) == 0 &&
7883 root != root->fs_info->tree_root)
7884 return 1;
7885 else
7886 return generic_drop_inode(inode);
7889 static void init_once(void *foo)
7891 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7893 inode_init_once(&ei->vfs_inode);
7896 void btrfs_destroy_cachep(void)
7899 * Make sure all delayed rcu free inodes are flushed before we
7900 * destroy cache.
7902 rcu_barrier();
7903 if (btrfs_inode_cachep)
7904 kmem_cache_destroy(btrfs_inode_cachep);
7905 if (btrfs_trans_handle_cachep)
7906 kmem_cache_destroy(btrfs_trans_handle_cachep);
7907 if (btrfs_transaction_cachep)
7908 kmem_cache_destroy(btrfs_transaction_cachep);
7909 if (btrfs_path_cachep)
7910 kmem_cache_destroy(btrfs_path_cachep);
7911 if (btrfs_free_space_cachep)
7912 kmem_cache_destroy(btrfs_free_space_cachep);
7913 if (btrfs_delalloc_work_cachep)
7914 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7917 int btrfs_init_cachep(void)
7919 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7920 sizeof(struct btrfs_inode), 0,
7921 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7922 if (!btrfs_inode_cachep)
7923 goto fail;
7925 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7926 sizeof(struct btrfs_trans_handle), 0,
7927 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7928 if (!btrfs_trans_handle_cachep)
7929 goto fail;
7931 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7932 sizeof(struct btrfs_transaction), 0,
7933 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7934 if (!btrfs_transaction_cachep)
7935 goto fail;
7937 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7938 sizeof(struct btrfs_path), 0,
7939 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7940 if (!btrfs_path_cachep)
7941 goto fail;
7943 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7944 sizeof(struct btrfs_free_space), 0,
7945 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7946 if (!btrfs_free_space_cachep)
7947 goto fail;
7949 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7950 sizeof(struct btrfs_delalloc_work), 0,
7951 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7952 NULL);
7953 if (!btrfs_delalloc_work_cachep)
7954 goto fail;
7956 return 0;
7957 fail:
7958 btrfs_destroy_cachep();
7959 return -ENOMEM;
7962 static int btrfs_getattr(struct vfsmount *mnt,
7963 struct dentry *dentry, struct kstat *stat)
7965 u64 delalloc_bytes;
7966 struct inode *inode = dentry->d_inode;
7967 u32 blocksize = inode->i_sb->s_blocksize;
7969 generic_fillattr(inode, stat);
7970 stat->dev = BTRFS_I(inode)->root->anon_dev;
7971 stat->blksize = PAGE_CACHE_SIZE;
7973 spin_lock(&BTRFS_I(inode)->lock);
7974 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7975 spin_unlock(&BTRFS_I(inode)->lock);
7976 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7977 ALIGN(delalloc_bytes, blocksize)) >> 9;
7978 return 0;
7981 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7982 struct inode *new_dir, struct dentry *new_dentry)
7984 struct btrfs_trans_handle *trans;
7985 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7986 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7987 struct inode *new_inode = new_dentry->d_inode;
7988 struct inode *old_inode = old_dentry->d_inode;
7989 struct timespec ctime = CURRENT_TIME;
7990 u64 index = 0;
7991 u64 root_objectid;
7992 int ret;
7993 u64 old_ino = btrfs_ino(old_inode);
7995 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7996 return -EPERM;
7998 /* we only allow rename subvolume link between subvolumes */
7999 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8000 return -EXDEV;
8002 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8003 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8004 return -ENOTEMPTY;
8006 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8007 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8008 return -ENOTEMPTY;
8011 /* check for collisions, even if the name isn't there */
8012 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8013 new_dentry->d_name.name,
8014 new_dentry->d_name.len);
8016 if (ret) {
8017 if (ret == -EEXIST) {
8018 /* we shouldn't get
8019 * eexist without a new_inode */
8020 if (!new_inode) {
8021 WARN_ON(1);
8022 return ret;
8024 } else {
8025 /* maybe -EOVERFLOW */
8026 return ret;
8029 ret = 0;
8032 * we're using rename to replace one file with another.
8033 * and the replacement file is large. Start IO on it now so
8034 * we don't add too much work to the end of the transaction
8036 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8037 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8038 filemap_flush(old_inode->i_mapping);
8040 /* close the racy window with snapshot create/destroy ioctl */
8041 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8042 down_read(&root->fs_info->subvol_sem);
8044 * We want to reserve the absolute worst case amount of items. So if
8045 * both inodes are subvols and we need to unlink them then that would
8046 * require 4 item modifications, but if they are both normal inodes it
8047 * would require 5 item modifications, so we'll assume their normal
8048 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8049 * should cover the worst case number of items we'll modify.
8051 trans = btrfs_start_transaction(root, 11);
8052 if (IS_ERR(trans)) {
8053 ret = PTR_ERR(trans);
8054 goto out_notrans;
8057 if (dest != root)
8058 btrfs_record_root_in_trans(trans, dest);
8060 ret = btrfs_set_inode_index(new_dir, &index);
8061 if (ret)
8062 goto out_fail;
8064 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8065 /* force full log commit if subvolume involved. */
8066 root->fs_info->last_trans_log_full_commit = trans->transid;
8067 } else {
8068 ret = btrfs_insert_inode_ref(trans, dest,
8069 new_dentry->d_name.name,
8070 new_dentry->d_name.len,
8071 old_ino,
8072 btrfs_ino(new_dir), index);
8073 if (ret)
8074 goto out_fail;
8076 * this is an ugly little race, but the rename is required
8077 * to make sure that if we crash, the inode is either at the
8078 * old name or the new one. pinning the log transaction lets
8079 * us make sure we don't allow a log commit to come in after
8080 * we unlink the name but before we add the new name back in.
8082 btrfs_pin_log_trans(root);
8085 * make sure the inode gets flushed if it is replacing
8086 * something.
8088 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8089 btrfs_add_ordered_operation(trans, root, old_inode);
8091 inode_inc_iversion(old_dir);
8092 inode_inc_iversion(new_dir);
8093 inode_inc_iversion(old_inode);
8094 old_dir->i_ctime = old_dir->i_mtime = ctime;
8095 new_dir->i_ctime = new_dir->i_mtime = ctime;
8096 old_inode->i_ctime = ctime;
8098 if (old_dentry->d_parent != new_dentry->d_parent)
8099 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8101 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8102 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8103 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8104 old_dentry->d_name.name,
8105 old_dentry->d_name.len);
8106 } else {
8107 ret = __btrfs_unlink_inode(trans, root, old_dir,
8108 old_dentry->d_inode,
8109 old_dentry->d_name.name,
8110 old_dentry->d_name.len);
8111 if (!ret)
8112 ret = btrfs_update_inode(trans, root, old_inode);
8114 if (ret) {
8115 btrfs_abort_transaction(trans, root, ret);
8116 goto out_fail;
8119 if (new_inode) {
8120 inode_inc_iversion(new_inode);
8121 new_inode->i_ctime = CURRENT_TIME;
8122 if (unlikely(btrfs_ino(new_inode) ==
8123 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8124 root_objectid = BTRFS_I(new_inode)->location.objectid;
8125 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8126 root_objectid,
8127 new_dentry->d_name.name,
8128 new_dentry->d_name.len);
8129 BUG_ON(new_inode->i_nlink == 0);
8130 } else {
8131 ret = btrfs_unlink_inode(trans, dest, new_dir,
8132 new_dentry->d_inode,
8133 new_dentry->d_name.name,
8134 new_dentry->d_name.len);
8136 if (!ret && new_inode->i_nlink == 0)
8137 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8138 if (ret) {
8139 btrfs_abort_transaction(trans, root, ret);
8140 goto out_fail;
8144 ret = btrfs_add_link(trans, new_dir, old_inode,
8145 new_dentry->d_name.name,
8146 new_dentry->d_name.len, 0, index);
8147 if (ret) {
8148 btrfs_abort_transaction(trans, root, ret);
8149 goto out_fail;
8152 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8153 struct dentry *parent = new_dentry->d_parent;
8154 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8155 btrfs_end_log_trans(root);
8157 out_fail:
8158 btrfs_end_transaction(trans, root);
8159 out_notrans:
8160 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8161 up_read(&root->fs_info->subvol_sem);
8163 return ret;
8166 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8168 struct btrfs_delalloc_work *delalloc_work;
8170 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8171 work);
8172 if (delalloc_work->wait)
8173 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8174 else
8175 filemap_flush(delalloc_work->inode->i_mapping);
8177 if (delalloc_work->delay_iput)
8178 btrfs_add_delayed_iput(delalloc_work->inode);
8179 else
8180 iput(delalloc_work->inode);
8181 complete(&delalloc_work->completion);
8184 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8185 int wait, int delay_iput)
8187 struct btrfs_delalloc_work *work;
8189 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8190 if (!work)
8191 return NULL;
8193 init_completion(&work->completion);
8194 INIT_LIST_HEAD(&work->list);
8195 work->inode = inode;
8196 work->wait = wait;
8197 work->delay_iput = delay_iput;
8198 work->work.func = btrfs_run_delalloc_work;
8200 return work;
8203 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8205 wait_for_completion(&work->completion);
8206 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8210 * some fairly slow code that needs optimization. This walks the list
8211 * of all the inodes with pending delalloc and forces them to disk.
8213 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8215 struct btrfs_inode *binode;
8216 struct inode *inode;
8217 struct btrfs_delalloc_work *work, *next;
8218 struct list_head works;
8219 struct list_head splice;
8220 int ret = 0;
8222 INIT_LIST_HEAD(&works);
8223 INIT_LIST_HEAD(&splice);
8225 spin_lock(&root->delalloc_lock);
8226 list_splice_init(&root->delalloc_inodes, &splice);
8227 while (!list_empty(&splice)) {
8228 binode = list_entry(splice.next, struct btrfs_inode,
8229 delalloc_inodes);
8231 list_move_tail(&binode->delalloc_inodes,
8232 &root->delalloc_inodes);
8233 inode = igrab(&binode->vfs_inode);
8234 if (!inode) {
8235 cond_resched_lock(&root->delalloc_lock);
8236 continue;
8238 spin_unlock(&root->delalloc_lock);
8240 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8241 if (unlikely(!work)) {
8242 if (delay_iput)
8243 btrfs_add_delayed_iput(inode);
8244 else
8245 iput(inode);
8246 ret = -ENOMEM;
8247 goto out;
8249 list_add_tail(&work->list, &works);
8250 btrfs_queue_worker(&root->fs_info->flush_workers,
8251 &work->work);
8253 cond_resched();
8254 spin_lock(&root->delalloc_lock);
8256 spin_unlock(&root->delalloc_lock);
8258 list_for_each_entry_safe(work, next, &works, list) {
8259 list_del_init(&work->list);
8260 btrfs_wait_and_free_delalloc_work(work);
8262 return 0;
8263 out:
8264 list_for_each_entry_safe(work, next, &works, list) {
8265 list_del_init(&work->list);
8266 btrfs_wait_and_free_delalloc_work(work);
8269 if (!list_empty_careful(&splice)) {
8270 spin_lock(&root->delalloc_lock);
8271 list_splice_tail(&splice, &root->delalloc_inodes);
8272 spin_unlock(&root->delalloc_lock);
8274 return ret;
8277 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8279 int ret;
8281 if (root->fs_info->sb->s_flags & MS_RDONLY)
8282 return -EROFS;
8284 ret = __start_delalloc_inodes(root, delay_iput);
8286 * the filemap_flush will queue IO into the worker threads, but
8287 * we have to make sure the IO is actually started and that
8288 * ordered extents get created before we return
8290 atomic_inc(&root->fs_info->async_submit_draining);
8291 while (atomic_read(&root->fs_info->nr_async_submits) ||
8292 atomic_read(&root->fs_info->async_delalloc_pages)) {
8293 wait_event(root->fs_info->async_submit_wait,
8294 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8295 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8297 atomic_dec(&root->fs_info->async_submit_draining);
8298 return ret;
8301 int btrfs_start_all_delalloc_inodes(struct btrfs_fs_info *fs_info,
8302 int delay_iput)
8304 struct btrfs_root *root;
8305 struct list_head splice;
8306 int ret;
8308 if (fs_info->sb->s_flags & MS_RDONLY)
8309 return -EROFS;
8311 INIT_LIST_HEAD(&splice);
8313 spin_lock(&fs_info->delalloc_root_lock);
8314 list_splice_init(&fs_info->delalloc_roots, &splice);
8315 while (!list_empty(&splice)) {
8316 root = list_first_entry(&splice, struct btrfs_root,
8317 delalloc_root);
8318 root = btrfs_grab_fs_root(root);
8319 BUG_ON(!root);
8320 list_move_tail(&root->delalloc_root,
8321 &fs_info->delalloc_roots);
8322 spin_unlock(&fs_info->delalloc_root_lock);
8324 ret = __start_delalloc_inodes(root, delay_iput);
8325 btrfs_put_fs_root(root);
8326 if (ret)
8327 goto out;
8329 spin_lock(&fs_info->delalloc_root_lock);
8331 spin_unlock(&fs_info->delalloc_root_lock);
8333 atomic_inc(&fs_info->async_submit_draining);
8334 while (atomic_read(&fs_info->nr_async_submits) ||
8335 atomic_read(&fs_info->async_delalloc_pages)) {
8336 wait_event(fs_info->async_submit_wait,
8337 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8338 atomic_read(&fs_info->async_delalloc_pages) == 0));
8340 atomic_dec(&fs_info->async_submit_draining);
8341 return 0;
8342 out:
8343 if (!list_empty_careful(&splice)) {
8344 spin_lock(&fs_info->delalloc_root_lock);
8345 list_splice_tail(&splice, &fs_info->delalloc_roots);
8346 spin_unlock(&fs_info->delalloc_root_lock);
8348 return ret;
8351 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8352 const char *symname)
8354 struct btrfs_trans_handle *trans;
8355 struct btrfs_root *root = BTRFS_I(dir)->root;
8356 struct btrfs_path *path;
8357 struct btrfs_key key;
8358 struct inode *inode = NULL;
8359 int err;
8360 int drop_inode = 0;
8361 u64 objectid;
8362 u64 index = 0 ;
8363 int name_len;
8364 int datasize;
8365 unsigned long ptr;
8366 struct btrfs_file_extent_item *ei;
8367 struct extent_buffer *leaf;
8369 name_len = strlen(symname) + 1;
8370 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8371 return -ENAMETOOLONG;
8374 * 2 items for inode item and ref
8375 * 2 items for dir items
8376 * 1 item for xattr if selinux is on
8378 trans = btrfs_start_transaction(root, 5);
8379 if (IS_ERR(trans))
8380 return PTR_ERR(trans);
8382 err = btrfs_find_free_ino(root, &objectid);
8383 if (err)
8384 goto out_unlock;
8386 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8387 dentry->d_name.len, btrfs_ino(dir), objectid,
8388 S_IFLNK|S_IRWXUGO, &index);
8389 if (IS_ERR(inode)) {
8390 err = PTR_ERR(inode);
8391 goto out_unlock;
8394 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8395 if (err) {
8396 drop_inode = 1;
8397 goto out_unlock;
8401 * If the active LSM wants to access the inode during
8402 * d_instantiate it needs these. Smack checks to see
8403 * if the filesystem supports xattrs by looking at the
8404 * ops vector.
8406 inode->i_fop = &btrfs_file_operations;
8407 inode->i_op = &btrfs_file_inode_operations;
8409 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8410 if (err)
8411 drop_inode = 1;
8412 else {
8413 inode->i_mapping->a_ops = &btrfs_aops;
8414 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8415 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8417 if (drop_inode)
8418 goto out_unlock;
8420 path = btrfs_alloc_path();
8421 if (!path) {
8422 err = -ENOMEM;
8423 drop_inode = 1;
8424 goto out_unlock;
8426 key.objectid = btrfs_ino(inode);
8427 key.offset = 0;
8428 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8429 datasize = btrfs_file_extent_calc_inline_size(name_len);
8430 err = btrfs_insert_empty_item(trans, root, path, &key,
8431 datasize);
8432 if (err) {
8433 drop_inode = 1;
8434 btrfs_free_path(path);
8435 goto out_unlock;
8437 leaf = path->nodes[0];
8438 ei = btrfs_item_ptr(leaf, path->slots[0],
8439 struct btrfs_file_extent_item);
8440 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8441 btrfs_set_file_extent_type(leaf, ei,
8442 BTRFS_FILE_EXTENT_INLINE);
8443 btrfs_set_file_extent_encryption(leaf, ei, 0);
8444 btrfs_set_file_extent_compression(leaf, ei, 0);
8445 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8446 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8448 ptr = btrfs_file_extent_inline_start(ei);
8449 write_extent_buffer(leaf, symname, ptr, name_len);
8450 btrfs_mark_buffer_dirty(leaf);
8451 btrfs_free_path(path);
8453 inode->i_op = &btrfs_symlink_inode_operations;
8454 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8455 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8456 inode_set_bytes(inode, name_len);
8457 btrfs_i_size_write(inode, name_len - 1);
8458 err = btrfs_update_inode(trans, root, inode);
8459 if (err)
8460 drop_inode = 1;
8462 out_unlock:
8463 if (!err)
8464 d_instantiate(dentry, inode);
8465 btrfs_end_transaction(trans, root);
8466 if (drop_inode) {
8467 inode_dec_link_count(inode);
8468 iput(inode);
8470 btrfs_btree_balance_dirty(root);
8471 return err;
8474 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8475 u64 start, u64 num_bytes, u64 min_size,
8476 loff_t actual_len, u64 *alloc_hint,
8477 struct btrfs_trans_handle *trans)
8479 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8480 struct extent_map *em;
8481 struct btrfs_root *root = BTRFS_I(inode)->root;
8482 struct btrfs_key ins;
8483 u64 cur_offset = start;
8484 u64 i_size;
8485 u64 cur_bytes;
8486 int ret = 0;
8487 bool own_trans = true;
8489 if (trans)
8490 own_trans = false;
8491 while (num_bytes > 0) {
8492 if (own_trans) {
8493 trans = btrfs_start_transaction(root, 3);
8494 if (IS_ERR(trans)) {
8495 ret = PTR_ERR(trans);
8496 break;
8500 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8501 cur_bytes = max(cur_bytes, min_size);
8502 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8503 *alloc_hint, &ins, 1);
8504 if (ret) {
8505 if (own_trans)
8506 btrfs_end_transaction(trans, root);
8507 break;
8510 ret = insert_reserved_file_extent(trans, inode,
8511 cur_offset, ins.objectid,
8512 ins.offset, ins.offset,
8513 ins.offset, 0, 0, 0,
8514 BTRFS_FILE_EXTENT_PREALLOC);
8515 if (ret) {
8516 btrfs_abort_transaction(trans, root, ret);
8517 if (own_trans)
8518 btrfs_end_transaction(trans, root);
8519 break;
8521 btrfs_drop_extent_cache(inode, cur_offset,
8522 cur_offset + ins.offset -1, 0);
8524 em = alloc_extent_map();
8525 if (!em) {
8526 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8527 &BTRFS_I(inode)->runtime_flags);
8528 goto next;
8531 em->start = cur_offset;
8532 em->orig_start = cur_offset;
8533 em->len = ins.offset;
8534 em->block_start = ins.objectid;
8535 em->block_len = ins.offset;
8536 em->orig_block_len = ins.offset;
8537 em->ram_bytes = ins.offset;
8538 em->bdev = root->fs_info->fs_devices->latest_bdev;
8539 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8540 em->generation = trans->transid;
8542 while (1) {
8543 write_lock(&em_tree->lock);
8544 ret = add_extent_mapping(em_tree, em, 1);
8545 write_unlock(&em_tree->lock);
8546 if (ret != -EEXIST)
8547 break;
8548 btrfs_drop_extent_cache(inode, cur_offset,
8549 cur_offset + ins.offset - 1,
8552 free_extent_map(em);
8553 next:
8554 num_bytes -= ins.offset;
8555 cur_offset += ins.offset;
8556 *alloc_hint = ins.objectid + ins.offset;
8558 inode_inc_iversion(inode);
8559 inode->i_ctime = CURRENT_TIME;
8560 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8561 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8562 (actual_len > inode->i_size) &&
8563 (cur_offset > inode->i_size)) {
8564 if (cur_offset > actual_len)
8565 i_size = actual_len;
8566 else
8567 i_size = cur_offset;
8568 i_size_write(inode, i_size);
8569 btrfs_ordered_update_i_size(inode, i_size, NULL);
8572 ret = btrfs_update_inode(trans, root, inode);
8574 if (ret) {
8575 btrfs_abort_transaction(trans, root, ret);
8576 if (own_trans)
8577 btrfs_end_transaction(trans, root);
8578 break;
8581 if (own_trans)
8582 btrfs_end_transaction(trans, root);
8584 return ret;
8587 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8588 u64 start, u64 num_bytes, u64 min_size,
8589 loff_t actual_len, u64 *alloc_hint)
8591 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8592 min_size, actual_len, alloc_hint,
8593 NULL);
8596 int btrfs_prealloc_file_range_trans(struct inode *inode,
8597 struct btrfs_trans_handle *trans, int mode,
8598 u64 start, u64 num_bytes, u64 min_size,
8599 loff_t actual_len, u64 *alloc_hint)
8601 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8602 min_size, actual_len, alloc_hint, trans);
8605 static int btrfs_set_page_dirty(struct page *page)
8607 return __set_page_dirty_nobuffers(page);
8610 static int btrfs_permission(struct inode *inode, int mask)
8612 struct btrfs_root *root = BTRFS_I(inode)->root;
8613 umode_t mode = inode->i_mode;
8615 if (mask & MAY_WRITE &&
8616 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8617 if (btrfs_root_readonly(root))
8618 return -EROFS;
8619 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8620 return -EACCES;
8622 return generic_permission(inode, mask);
8625 static const struct inode_operations btrfs_dir_inode_operations = {
8626 .getattr = btrfs_getattr,
8627 .lookup = btrfs_lookup,
8628 .create = btrfs_create,
8629 .unlink = btrfs_unlink,
8630 .link = btrfs_link,
8631 .mkdir = btrfs_mkdir,
8632 .rmdir = btrfs_rmdir,
8633 .rename = btrfs_rename,
8634 .symlink = btrfs_symlink,
8635 .setattr = btrfs_setattr,
8636 .mknod = btrfs_mknod,
8637 .setxattr = btrfs_setxattr,
8638 .getxattr = btrfs_getxattr,
8639 .listxattr = btrfs_listxattr,
8640 .removexattr = btrfs_removexattr,
8641 .permission = btrfs_permission,
8642 .get_acl = btrfs_get_acl,
8643 .update_time = btrfs_update_time,
8645 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8646 .lookup = btrfs_lookup,
8647 .permission = btrfs_permission,
8648 .get_acl = btrfs_get_acl,
8649 .update_time = btrfs_update_time,
8652 static const struct file_operations btrfs_dir_file_operations = {
8653 .llseek = generic_file_llseek,
8654 .read = generic_read_dir,
8655 .iterate = btrfs_real_readdir,
8656 .unlocked_ioctl = btrfs_ioctl,
8657 #ifdef CONFIG_COMPAT
8658 .compat_ioctl = btrfs_ioctl,
8659 #endif
8660 .release = btrfs_release_file,
8661 .fsync = btrfs_sync_file,
8664 static struct extent_io_ops btrfs_extent_io_ops = {
8665 .fill_delalloc = run_delalloc_range,
8666 .submit_bio_hook = btrfs_submit_bio_hook,
8667 .merge_bio_hook = btrfs_merge_bio_hook,
8668 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8669 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8670 .writepage_start_hook = btrfs_writepage_start_hook,
8671 .set_bit_hook = btrfs_set_bit_hook,
8672 .clear_bit_hook = btrfs_clear_bit_hook,
8673 .merge_extent_hook = btrfs_merge_extent_hook,
8674 .split_extent_hook = btrfs_split_extent_hook,
8678 * btrfs doesn't support the bmap operation because swapfiles
8679 * use bmap to make a mapping of extents in the file. They assume
8680 * these extents won't change over the life of the file and they
8681 * use the bmap result to do IO directly to the drive.
8683 * the btrfs bmap call would return logical addresses that aren't
8684 * suitable for IO and they also will change frequently as COW
8685 * operations happen. So, swapfile + btrfs == corruption.
8687 * For now we're avoiding this by dropping bmap.
8689 static const struct address_space_operations btrfs_aops = {
8690 .readpage = btrfs_readpage,
8691 .writepage = btrfs_writepage,
8692 .writepages = btrfs_writepages,
8693 .readpages = btrfs_readpages,
8694 .direct_IO = btrfs_direct_IO,
8695 .invalidatepage = btrfs_invalidatepage,
8696 .releasepage = btrfs_releasepage,
8697 .set_page_dirty = btrfs_set_page_dirty,
8698 .error_remove_page = generic_error_remove_page,
8701 static const struct address_space_operations btrfs_symlink_aops = {
8702 .readpage = btrfs_readpage,
8703 .writepage = btrfs_writepage,
8704 .invalidatepage = btrfs_invalidatepage,
8705 .releasepage = btrfs_releasepage,
8708 static const struct inode_operations btrfs_file_inode_operations = {
8709 .getattr = btrfs_getattr,
8710 .setattr = btrfs_setattr,
8711 .setxattr = btrfs_setxattr,
8712 .getxattr = btrfs_getxattr,
8713 .listxattr = btrfs_listxattr,
8714 .removexattr = btrfs_removexattr,
8715 .permission = btrfs_permission,
8716 .fiemap = btrfs_fiemap,
8717 .get_acl = btrfs_get_acl,
8718 .update_time = btrfs_update_time,
8720 static const struct inode_operations btrfs_special_inode_operations = {
8721 .getattr = btrfs_getattr,
8722 .setattr = btrfs_setattr,
8723 .permission = btrfs_permission,
8724 .setxattr = btrfs_setxattr,
8725 .getxattr = btrfs_getxattr,
8726 .listxattr = btrfs_listxattr,
8727 .removexattr = btrfs_removexattr,
8728 .get_acl = btrfs_get_acl,
8729 .update_time = btrfs_update_time,
8731 static const struct inode_operations btrfs_symlink_inode_operations = {
8732 .readlink = generic_readlink,
8733 .follow_link = page_follow_link_light,
8734 .put_link = page_put_link,
8735 .getattr = btrfs_getattr,
8736 .setattr = btrfs_setattr,
8737 .permission = btrfs_permission,
8738 .setxattr = btrfs_setxattr,
8739 .getxattr = btrfs_getxattr,
8740 .listxattr = btrfs_listxattr,
8741 .removexattr = btrfs_removexattr,
8742 .get_acl = btrfs_get_acl,
8743 .update_time = btrfs_update_time,
8746 const struct dentry_operations btrfs_dentry_operations = {
8747 .d_delete = btrfs_dentry_delete,
8748 .d_release = btrfs_dentry_release,