Bluetooth: vhci: Fix race at creating hci device
[linux/fpc-iii.git] / fs / btrfs / inode.c
blobc8d287fff7bcaee9df2ddae8405ff466a2c72ead
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 "ctree.h"
47 #include "disk-io.h"
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
52 #include "xattr.h"
53 #include "tree-log.h"
54 #include "volumes.h"
55 #include "compression.h"
56 #include "locking.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
59 #include "backref.h"
60 #include "hash.h"
61 #include "props.h"
63 struct btrfs_iget_args {
64 struct btrfs_key *location;
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 int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_path *path, int extent_inserted,
130 struct btrfs_root *root, struct inode *inode,
131 u64 start, size_t size, size_t compressed_size,
132 int compress_type,
133 struct page **compressed_pages)
135 struct extent_buffer *leaf;
136 struct page *page = NULL;
137 char *kaddr;
138 unsigned long ptr;
139 struct btrfs_file_extent_item *ei;
140 int err = 0;
141 int ret;
142 size_t cur_size = size;
143 unsigned long offset;
145 if (compressed_size && compressed_pages)
146 cur_size = compressed_size;
148 inode_add_bytes(inode, size);
150 if (!extent_inserted) {
151 struct btrfs_key key;
152 size_t datasize;
154 key.objectid = btrfs_ino(inode);
155 key.offset = start;
156 key.type = BTRFS_EXTENT_DATA_KEY;
158 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159 path->leave_spinning = 1;
160 ret = btrfs_insert_empty_item(trans, root, path, &key,
161 datasize);
162 if (ret) {
163 err = ret;
164 goto fail;
167 leaf = path->nodes[0];
168 ei = btrfs_item_ptr(leaf, path->slots[0],
169 struct btrfs_file_extent_item);
170 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172 btrfs_set_file_extent_encryption(leaf, ei, 0);
173 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175 ptr = btrfs_file_extent_inline_start(ei);
177 if (compress_type != BTRFS_COMPRESS_NONE) {
178 struct page *cpage;
179 int i = 0;
180 while (compressed_size > 0) {
181 cpage = compressed_pages[i];
182 cur_size = min_t(unsigned long, compressed_size,
183 PAGE_CACHE_SIZE);
185 kaddr = kmap_atomic(cpage);
186 write_extent_buffer(leaf, kaddr, ptr, cur_size);
187 kunmap_atomic(kaddr);
189 i++;
190 ptr += cur_size;
191 compressed_size -= cur_size;
193 btrfs_set_file_extent_compression(leaf, ei,
194 compress_type);
195 } else {
196 page = find_get_page(inode->i_mapping,
197 start >> PAGE_CACHE_SHIFT);
198 btrfs_set_file_extent_compression(leaf, ei, 0);
199 kaddr = kmap_atomic(page);
200 offset = start & (PAGE_CACHE_SIZE - 1);
201 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202 kunmap_atomic(kaddr);
203 page_cache_release(page);
205 btrfs_mark_buffer_dirty(leaf);
206 btrfs_release_path(path);
209 * we're an inline extent, so nobody can
210 * extend the file past i_size without locking
211 * a page we already have locked.
213 * We must do any isize and inode updates
214 * before we unlock the pages. Otherwise we
215 * could end up racing with unlink.
217 BTRFS_I(inode)->disk_i_size = inode->i_size;
218 ret = btrfs_update_inode(trans, root, inode);
220 return ret;
221 fail:
222 return err;
227 * conditionally insert an inline extent into the file. This
228 * does the checks required to make sure the data is small enough
229 * to fit as an inline extent.
231 static noinline int cow_file_range_inline(struct btrfs_root *root,
232 struct inode *inode, u64 start,
233 u64 end, size_t compressed_size,
234 int compress_type,
235 struct page **compressed_pages)
237 struct btrfs_trans_handle *trans;
238 u64 isize = i_size_read(inode);
239 u64 actual_end = min(end + 1, isize);
240 u64 inline_len = actual_end - start;
241 u64 aligned_end = ALIGN(end, root->sectorsize);
242 u64 data_len = inline_len;
243 int ret;
244 struct btrfs_path *path;
245 int extent_inserted = 0;
246 u32 extent_item_size;
248 if (compressed_size)
249 data_len = compressed_size;
251 if (start > 0 ||
252 actual_end > PAGE_CACHE_SIZE ||
253 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
254 (!compressed_size &&
255 (actual_end & (root->sectorsize - 1)) == 0) ||
256 end + 1 < isize ||
257 data_len > root->fs_info->max_inline) {
258 return 1;
261 path = btrfs_alloc_path();
262 if (!path)
263 return -ENOMEM;
265 trans = btrfs_join_transaction(root);
266 if (IS_ERR(trans)) {
267 btrfs_free_path(path);
268 return PTR_ERR(trans);
270 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
272 if (compressed_size && compressed_pages)
273 extent_item_size = btrfs_file_extent_calc_inline_size(
274 compressed_size);
275 else
276 extent_item_size = btrfs_file_extent_calc_inline_size(
277 inline_len);
279 ret = __btrfs_drop_extents(trans, root, inode, path,
280 start, aligned_end, NULL,
281 1, 1, extent_item_size, &extent_inserted);
282 if (ret) {
283 btrfs_abort_transaction(trans, root, ret);
284 goto out;
287 if (isize > actual_end)
288 inline_len = min_t(u64, isize, actual_end);
289 ret = insert_inline_extent(trans, path, extent_inserted,
290 root, inode, start,
291 inline_len, compressed_size,
292 compress_type, compressed_pages);
293 if (ret && ret != -ENOSPC) {
294 btrfs_abort_transaction(trans, root, ret);
295 goto out;
296 } else if (ret == -ENOSPC) {
297 ret = 1;
298 goto out;
301 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
302 btrfs_delalloc_release_metadata(inode, end + 1 - start);
303 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
304 out:
305 btrfs_free_path(path);
306 btrfs_end_transaction(trans, root);
307 return ret;
310 struct async_extent {
311 u64 start;
312 u64 ram_size;
313 u64 compressed_size;
314 struct page **pages;
315 unsigned long nr_pages;
316 int compress_type;
317 struct list_head list;
320 struct async_cow {
321 struct inode *inode;
322 struct btrfs_root *root;
323 struct page *locked_page;
324 u64 start;
325 u64 end;
326 struct list_head extents;
327 struct btrfs_work work;
330 static noinline int add_async_extent(struct async_cow *cow,
331 u64 start, u64 ram_size,
332 u64 compressed_size,
333 struct page **pages,
334 unsigned long nr_pages,
335 int compress_type)
337 struct async_extent *async_extent;
339 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
340 BUG_ON(!async_extent); /* -ENOMEM */
341 async_extent->start = start;
342 async_extent->ram_size = ram_size;
343 async_extent->compressed_size = compressed_size;
344 async_extent->pages = pages;
345 async_extent->nr_pages = nr_pages;
346 async_extent->compress_type = compress_type;
347 list_add_tail(&async_extent->list, &cow->extents);
348 return 0;
351 static inline int inode_need_compress(struct inode *inode)
353 struct btrfs_root *root = BTRFS_I(inode)->root;
355 /* force compress */
356 if (btrfs_test_opt(root, FORCE_COMPRESS))
357 return 1;
358 /* bad compression ratios */
359 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
360 return 0;
361 if (btrfs_test_opt(root, COMPRESS) ||
362 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
363 BTRFS_I(inode)->force_compress)
364 return 1;
365 return 0;
369 * we create compressed extents in two phases. The first
370 * phase compresses a range of pages that have already been
371 * locked (both pages and state bits are locked).
373 * This is done inside an ordered work queue, and the compression
374 * is spread across many cpus. The actual IO submission is step
375 * two, and the ordered work queue takes care of making sure that
376 * happens in the same order things were put onto the queue by
377 * writepages and friends.
379 * If this code finds it can't get good compression, it puts an
380 * entry onto the work queue to write the uncompressed bytes. This
381 * makes sure that both compressed inodes and uncompressed inodes
382 * are written in the same order that the flusher thread sent them
383 * down.
385 static noinline int compress_file_range(struct inode *inode,
386 struct page *locked_page,
387 u64 start, u64 end,
388 struct async_cow *async_cow,
389 int *num_added)
391 struct btrfs_root *root = BTRFS_I(inode)->root;
392 u64 num_bytes;
393 u64 blocksize = root->sectorsize;
394 u64 actual_end;
395 u64 isize = i_size_read(inode);
396 int ret = 0;
397 struct page **pages = NULL;
398 unsigned long nr_pages;
399 unsigned long nr_pages_ret = 0;
400 unsigned long total_compressed = 0;
401 unsigned long total_in = 0;
402 unsigned long max_compressed = 128 * 1024;
403 unsigned long max_uncompressed = 128 * 1024;
404 int i;
405 int will_compress;
406 int compress_type = root->fs_info->compress_type;
407 int redirty = 0;
409 /* if this is a small write inside eof, kick off a defrag */
410 if ((end - start + 1) < 16 * 1024 &&
411 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
412 btrfs_add_inode_defrag(NULL, inode);
415 * skip compression for a small file range(<=blocksize) that
416 * isn't an inline extent, since it dosen't save disk space at all.
418 if ((end - start + 1) <= blocksize &&
419 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
420 goto cleanup_and_bail_uncompressed;
422 actual_end = min_t(u64, isize, end + 1);
423 again:
424 will_compress = 0;
425 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
426 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
429 * we don't want to send crud past the end of i_size through
430 * compression, that's just a waste of CPU time. So, if the
431 * end of the file is before the start of our current
432 * requested range of bytes, we bail out to the uncompressed
433 * cleanup code that can deal with all of this.
435 * It isn't really the fastest way to fix things, but this is a
436 * very uncommon corner.
438 if (actual_end <= start)
439 goto cleanup_and_bail_uncompressed;
441 total_compressed = actual_end - start;
443 /* we want to make sure that amount of ram required to uncompress
444 * an extent is reasonable, so we limit the total size in ram
445 * of a compressed extent to 128k. This is a crucial number
446 * because it also controls how easily we can spread reads across
447 * cpus for decompression.
449 * We also want to make sure the amount of IO required to do
450 * a random read is reasonably small, so we limit the size of
451 * a compressed extent to 128k.
453 total_compressed = min(total_compressed, max_uncompressed);
454 num_bytes = ALIGN(end - start + 1, blocksize);
455 num_bytes = max(blocksize, num_bytes);
456 total_in = 0;
457 ret = 0;
460 * we do compression for mount -o compress and when the
461 * inode has not been flagged as nocompress. This flag can
462 * change at any time if we discover bad compression ratios.
464 if (inode_need_compress(inode)) {
465 WARN_ON(pages);
466 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
467 if (!pages) {
468 /* just bail out to the uncompressed code */
469 goto cont;
472 if (BTRFS_I(inode)->force_compress)
473 compress_type = BTRFS_I(inode)->force_compress;
476 * we need to call clear_page_dirty_for_io on each
477 * page in the range. Otherwise applications with the file
478 * mmap'd can wander in and change the page contents while
479 * we are compressing them.
481 * If the compression fails for any reason, we set the pages
482 * dirty again later on.
484 extent_range_clear_dirty_for_io(inode, start, end);
485 redirty = 1;
486 ret = btrfs_compress_pages(compress_type,
487 inode->i_mapping, start,
488 total_compressed, pages,
489 nr_pages, &nr_pages_ret,
490 &total_in,
491 &total_compressed,
492 max_compressed);
494 if (!ret) {
495 unsigned long offset = total_compressed &
496 (PAGE_CACHE_SIZE - 1);
497 struct page *page = pages[nr_pages_ret - 1];
498 char *kaddr;
500 /* zero the tail end of the last page, we might be
501 * sending it down to disk
503 if (offset) {
504 kaddr = kmap_atomic(page);
505 memset(kaddr + offset, 0,
506 PAGE_CACHE_SIZE - offset);
507 kunmap_atomic(kaddr);
509 will_compress = 1;
512 cont:
513 if (start == 0) {
514 /* lets try to make an inline extent */
515 if (ret || total_in < (actual_end - start)) {
516 /* we didn't compress the entire range, try
517 * to make an uncompressed inline extent.
519 ret = cow_file_range_inline(root, inode, start, end,
520 0, 0, NULL);
521 } else {
522 /* try making a compressed inline extent */
523 ret = cow_file_range_inline(root, inode, start, end,
524 total_compressed,
525 compress_type, pages);
527 if (ret <= 0) {
528 unsigned long clear_flags = EXTENT_DELALLOC |
529 EXTENT_DEFRAG;
530 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
533 * inline extent creation worked or returned error,
534 * we don't need to create any more async work items.
535 * Unlock and free up our temp pages.
537 extent_clear_unlock_delalloc(inode, start, end, NULL,
538 clear_flags, PAGE_UNLOCK |
539 PAGE_CLEAR_DIRTY |
540 PAGE_SET_WRITEBACK |
541 PAGE_END_WRITEBACK);
542 goto free_pages_out;
546 if (will_compress) {
548 * we aren't doing an inline extent round the compressed size
549 * up to a block size boundary so the allocator does sane
550 * things
552 total_compressed = ALIGN(total_compressed, blocksize);
555 * one last check to make sure the compression is really a
556 * win, compare the page count read with the blocks on disk
558 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
559 if (total_compressed >= total_in) {
560 will_compress = 0;
561 } else {
562 num_bytes = total_in;
565 if (!will_compress && pages) {
567 * the compression code ran but failed to make things smaller,
568 * free any pages it allocated and our page pointer array
570 for (i = 0; i < nr_pages_ret; i++) {
571 WARN_ON(pages[i]->mapping);
572 page_cache_release(pages[i]);
574 kfree(pages);
575 pages = NULL;
576 total_compressed = 0;
577 nr_pages_ret = 0;
579 /* flag the file so we don't compress in the future */
580 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
581 !(BTRFS_I(inode)->force_compress)) {
582 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
585 if (will_compress) {
586 *num_added += 1;
588 /* the async work queues will take care of doing actual
589 * allocation on disk for these compressed pages,
590 * and will submit them to the elevator.
592 add_async_extent(async_cow, start, num_bytes,
593 total_compressed, pages, nr_pages_ret,
594 compress_type);
596 if (start + num_bytes < end) {
597 start += num_bytes;
598 pages = NULL;
599 cond_resched();
600 goto again;
602 } else {
603 cleanup_and_bail_uncompressed:
605 * No compression, but we still need to write the pages in
606 * the file we've been given so far. redirty the locked
607 * page if it corresponds to our extent and set things up
608 * for the async work queue to run cow_file_range to do
609 * the normal delalloc dance
611 if (page_offset(locked_page) >= start &&
612 page_offset(locked_page) <= end) {
613 __set_page_dirty_nobuffers(locked_page);
614 /* unlocked later on in the async handlers */
616 if (redirty)
617 extent_range_redirty_for_io(inode, start, end);
618 add_async_extent(async_cow, start, end - start + 1,
619 0, NULL, 0, BTRFS_COMPRESS_NONE);
620 *num_added += 1;
623 out:
624 return ret;
626 free_pages_out:
627 for (i = 0; i < nr_pages_ret; i++) {
628 WARN_ON(pages[i]->mapping);
629 page_cache_release(pages[i]);
631 kfree(pages);
633 goto out;
637 * phase two of compressed writeback. This is the ordered portion
638 * of the code, which only gets called in the order the work was
639 * queued. We walk all the async extents created by compress_file_range
640 * and send them down to the disk.
642 static noinline int submit_compressed_extents(struct inode *inode,
643 struct async_cow *async_cow)
645 struct async_extent *async_extent;
646 u64 alloc_hint = 0;
647 struct btrfs_key ins;
648 struct extent_map *em;
649 struct btrfs_root *root = BTRFS_I(inode)->root;
650 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
651 struct extent_io_tree *io_tree;
652 int ret = 0;
654 if (list_empty(&async_cow->extents))
655 return 0;
657 again:
658 while (!list_empty(&async_cow->extents)) {
659 async_extent = list_entry(async_cow->extents.next,
660 struct async_extent, list);
661 list_del(&async_extent->list);
663 io_tree = &BTRFS_I(inode)->io_tree;
665 retry:
666 /* did the compression code fall back to uncompressed IO? */
667 if (!async_extent->pages) {
668 int page_started = 0;
669 unsigned long nr_written = 0;
671 lock_extent(io_tree, async_extent->start,
672 async_extent->start +
673 async_extent->ram_size - 1);
675 /* allocate blocks */
676 ret = cow_file_range(inode, async_cow->locked_page,
677 async_extent->start,
678 async_extent->start +
679 async_extent->ram_size - 1,
680 &page_started, &nr_written, 0);
682 /* JDM XXX */
685 * if page_started, cow_file_range inserted an
686 * inline extent and took care of all the unlocking
687 * and IO for us. Otherwise, we need to submit
688 * all those pages down to the drive.
690 if (!page_started && !ret)
691 extent_write_locked_range(io_tree,
692 inode, async_extent->start,
693 async_extent->start +
694 async_extent->ram_size - 1,
695 btrfs_get_extent,
696 WB_SYNC_ALL);
697 else if (ret)
698 unlock_page(async_cow->locked_page);
699 kfree(async_extent);
700 cond_resched();
701 continue;
704 lock_extent(io_tree, async_extent->start,
705 async_extent->start + async_extent->ram_size - 1);
707 ret = btrfs_reserve_extent(root,
708 async_extent->compressed_size,
709 async_extent->compressed_size,
710 0, alloc_hint, &ins, 1, 1);
711 if (ret) {
712 int i;
714 for (i = 0; i < async_extent->nr_pages; i++) {
715 WARN_ON(async_extent->pages[i]->mapping);
716 page_cache_release(async_extent->pages[i]);
718 kfree(async_extent->pages);
719 async_extent->nr_pages = 0;
720 async_extent->pages = NULL;
722 if (ret == -ENOSPC) {
723 unlock_extent(io_tree, async_extent->start,
724 async_extent->start +
725 async_extent->ram_size - 1);
728 * we need to redirty the pages if we decide to
729 * fallback to uncompressed IO, otherwise we
730 * will not submit these pages down to lower
731 * layers.
733 extent_range_redirty_for_io(inode,
734 async_extent->start,
735 async_extent->start +
736 async_extent->ram_size - 1);
738 goto retry;
740 goto out_free;
744 * here we're doing allocation and writeback of the
745 * compressed pages
747 btrfs_drop_extent_cache(inode, async_extent->start,
748 async_extent->start +
749 async_extent->ram_size - 1, 0);
751 em = alloc_extent_map();
752 if (!em) {
753 ret = -ENOMEM;
754 goto out_free_reserve;
756 em->start = async_extent->start;
757 em->len = async_extent->ram_size;
758 em->orig_start = em->start;
759 em->mod_start = em->start;
760 em->mod_len = em->len;
762 em->block_start = ins.objectid;
763 em->block_len = ins.offset;
764 em->orig_block_len = ins.offset;
765 em->ram_bytes = async_extent->ram_size;
766 em->bdev = root->fs_info->fs_devices->latest_bdev;
767 em->compress_type = async_extent->compress_type;
768 set_bit(EXTENT_FLAG_PINNED, &em->flags);
769 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
770 em->generation = -1;
772 while (1) {
773 write_lock(&em_tree->lock);
774 ret = add_extent_mapping(em_tree, em, 1);
775 write_unlock(&em_tree->lock);
776 if (ret != -EEXIST) {
777 free_extent_map(em);
778 break;
780 btrfs_drop_extent_cache(inode, async_extent->start,
781 async_extent->start +
782 async_extent->ram_size - 1, 0);
785 if (ret)
786 goto out_free_reserve;
788 ret = btrfs_add_ordered_extent_compress(inode,
789 async_extent->start,
790 ins.objectid,
791 async_extent->ram_size,
792 ins.offset,
793 BTRFS_ORDERED_COMPRESSED,
794 async_extent->compress_type);
795 if (ret) {
796 btrfs_drop_extent_cache(inode, async_extent->start,
797 async_extent->start +
798 async_extent->ram_size - 1, 0);
799 goto out_free_reserve;
803 * clear dirty, set writeback and unlock the pages.
805 extent_clear_unlock_delalloc(inode, async_extent->start,
806 async_extent->start +
807 async_extent->ram_size - 1,
808 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
809 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
810 PAGE_SET_WRITEBACK);
811 ret = btrfs_submit_compressed_write(inode,
812 async_extent->start,
813 async_extent->ram_size,
814 ins.objectid,
815 ins.offset, async_extent->pages,
816 async_extent->nr_pages);
817 alloc_hint = ins.objectid + ins.offset;
818 kfree(async_extent);
819 if (ret)
820 goto out;
821 cond_resched();
823 ret = 0;
824 out:
825 return ret;
826 out_free_reserve:
827 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
828 out_free:
829 extent_clear_unlock_delalloc(inode, async_extent->start,
830 async_extent->start +
831 async_extent->ram_size - 1,
832 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
833 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
834 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
835 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
836 kfree(async_extent);
837 goto again;
840 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
841 u64 num_bytes)
843 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
844 struct extent_map *em;
845 u64 alloc_hint = 0;
847 read_lock(&em_tree->lock);
848 em = search_extent_mapping(em_tree, start, num_bytes);
849 if (em) {
851 * if block start isn't an actual block number then find the
852 * first block in this inode and use that as a hint. If that
853 * block is also bogus then just don't worry about it.
855 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
856 free_extent_map(em);
857 em = search_extent_mapping(em_tree, 0, 0);
858 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
859 alloc_hint = em->block_start;
860 if (em)
861 free_extent_map(em);
862 } else {
863 alloc_hint = em->block_start;
864 free_extent_map(em);
867 read_unlock(&em_tree->lock);
869 return alloc_hint;
873 * when extent_io.c finds a delayed allocation range in the file,
874 * the call backs end up in this code. The basic idea is to
875 * allocate extents on disk for the range, and create ordered data structs
876 * in ram to track those extents.
878 * locked_page is the page that writepage had locked already. We use
879 * it to make sure we don't do extra locks or unlocks.
881 * *page_started is set to one if we unlock locked_page and do everything
882 * required to start IO on it. It may be clean and already done with
883 * IO when we return.
885 static noinline int cow_file_range(struct inode *inode,
886 struct page *locked_page,
887 u64 start, u64 end, int *page_started,
888 unsigned long *nr_written,
889 int unlock)
891 struct btrfs_root *root = BTRFS_I(inode)->root;
892 u64 alloc_hint = 0;
893 u64 num_bytes;
894 unsigned long ram_size;
895 u64 disk_num_bytes;
896 u64 cur_alloc_size;
897 u64 blocksize = root->sectorsize;
898 struct btrfs_key ins;
899 struct extent_map *em;
900 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
901 int ret = 0;
903 if (btrfs_is_free_space_inode(inode)) {
904 WARN_ON_ONCE(1);
905 ret = -EINVAL;
906 goto out_unlock;
909 num_bytes = ALIGN(end - start + 1, blocksize);
910 num_bytes = max(blocksize, num_bytes);
911 disk_num_bytes = num_bytes;
913 /* if this is a small write inside eof, kick off defrag */
914 if (num_bytes < 64 * 1024 &&
915 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
916 btrfs_add_inode_defrag(NULL, inode);
918 if (start == 0) {
919 /* lets try to make an inline extent */
920 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
921 NULL);
922 if (ret == 0) {
923 extent_clear_unlock_delalloc(inode, start, end, NULL,
924 EXTENT_LOCKED | EXTENT_DELALLOC |
925 EXTENT_DEFRAG, PAGE_UNLOCK |
926 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
927 PAGE_END_WRITEBACK);
929 *nr_written = *nr_written +
930 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
931 *page_started = 1;
932 goto out;
933 } else if (ret < 0) {
934 goto out_unlock;
938 BUG_ON(disk_num_bytes >
939 btrfs_super_total_bytes(root->fs_info->super_copy));
941 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
942 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
944 while (disk_num_bytes > 0) {
945 unsigned long op;
947 cur_alloc_size = disk_num_bytes;
948 ret = btrfs_reserve_extent(root, cur_alloc_size,
949 root->sectorsize, 0, alloc_hint,
950 &ins, 1, 1);
951 if (ret < 0)
952 goto out_unlock;
954 em = alloc_extent_map();
955 if (!em) {
956 ret = -ENOMEM;
957 goto out_reserve;
959 em->start = start;
960 em->orig_start = em->start;
961 ram_size = ins.offset;
962 em->len = ins.offset;
963 em->mod_start = em->start;
964 em->mod_len = em->len;
966 em->block_start = ins.objectid;
967 em->block_len = ins.offset;
968 em->orig_block_len = ins.offset;
969 em->ram_bytes = ram_size;
970 em->bdev = root->fs_info->fs_devices->latest_bdev;
971 set_bit(EXTENT_FLAG_PINNED, &em->flags);
972 em->generation = -1;
974 while (1) {
975 write_lock(&em_tree->lock);
976 ret = add_extent_mapping(em_tree, em, 1);
977 write_unlock(&em_tree->lock);
978 if (ret != -EEXIST) {
979 free_extent_map(em);
980 break;
982 btrfs_drop_extent_cache(inode, start,
983 start + ram_size - 1, 0);
985 if (ret)
986 goto out_reserve;
988 cur_alloc_size = ins.offset;
989 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
990 ram_size, cur_alloc_size, 0);
991 if (ret)
992 goto out_drop_extent_cache;
994 if (root->root_key.objectid ==
995 BTRFS_DATA_RELOC_TREE_OBJECTID) {
996 ret = btrfs_reloc_clone_csums(inode, start,
997 cur_alloc_size);
998 if (ret)
999 goto out_drop_extent_cache;
1002 if (disk_num_bytes < cur_alloc_size)
1003 break;
1005 /* we're not doing compressed IO, don't unlock the first
1006 * page (which the caller expects to stay locked), don't
1007 * clear any dirty bits and don't set any writeback bits
1009 * Do set the Private2 bit so we know this page was properly
1010 * setup for writepage
1012 op = unlock ? PAGE_UNLOCK : 0;
1013 op |= PAGE_SET_PRIVATE2;
1015 extent_clear_unlock_delalloc(inode, start,
1016 start + ram_size - 1, locked_page,
1017 EXTENT_LOCKED | EXTENT_DELALLOC,
1018 op);
1019 disk_num_bytes -= cur_alloc_size;
1020 num_bytes -= cur_alloc_size;
1021 alloc_hint = ins.objectid + ins.offset;
1022 start += cur_alloc_size;
1024 out:
1025 return ret;
1027 out_drop_extent_cache:
1028 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1029 out_reserve:
1030 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1031 out_unlock:
1032 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1033 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1034 EXTENT_DELALLOC | EXTENT_DEFRAG,
1035 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1036 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1037 goto out;
1041 * work queue call back to started compression on a file and pages
1043 static noinline void async_cow_start(struct btrfs_work *work)
1045 struct async_cow *async_cow;
1046 int num_added = 0;
1047 async_cow = container_of(work, struct async_cow, work);
1049 compress_file_range(async_cow->inode, async_cow->locked_page,
1050 async_cow->start, async_cow->end, async_cow,
1051 &num_added);
1052 if (num_added == 0) {
1053 btrfs_add_delayed_iput(async_cow->inode);
1054 async_cow->inode = NULL;
1059 * work queue call back to submit previously compressed pages
1061 static noinline void async_cow_submit(struct btrfs_work *work)
1063 struct async_cow *async_cow;
1064 struct btrfs_root *root;
1065 unsigned long nr_pages;
1067 async_cow = container_of(work, struct async_cow, work);
1069 root = async_cow->root;
1070 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1071 PAGE_CACHE_SHIFT;
1073 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1074 5 * 1024 * 1024 &&
1075 waitqueue_active(&root->fs_info->async_submit_wait))
1076 wake_up(&root->fs_info->async_submit_wait);
1078 if (async_cow->inode)
1079 submit_compressed_extents(async_cow->inode, async_cow);
1082 static noinline void async_cow_free(struct btrfs_work *work)
1084 struct async_cow *async_cow;
1085 async_cow = container_of(work, struct async_cow, work);
1086 if (async_cow->inode)
1087 btrfs_add_delayed_iput(async_cow->inode);
1088 kfree(async_cow);
1091 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1092 u64 start, u64 end, int *page_started,
1093 unsigned long *nr_written)
1095 struct async_cow *async_cow;
1096 struct btrfs_root *root = BTRFS_I(inode)->root;
1097 unsigned long nr_pages;
1098 u64 cur_end;
1099 int limit = 10 * 1024 * 1024;
1101 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1102 1, 0, NULL, GFP_NOFS);
1103 while (start < end) {
1104 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1105 BUG_ON(!async_cow); /* -ENOMEM */
1106 async_cow->inode = igrab(inode);
1107 async_cow->root = root;
1108 async_cow->locked_page = locked_page;
1109 async_cow->start = start;
1111 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1112 !btrfs_test_opt(root, FORCE_COMPRESS))
1113 cur_end = end;
1114 else
1115 cur_end = min(end, start + 512 * 1024 - 1);
1117 async_cow->end = cur_end;
1118 INIT_LIST_HEAD(&async_cow->extents);
1120 btrfs_init_work(&async_cow->work,
1121 btrfs_delalloc_helper,
1122 async_cow_start, async_cow_submit,
1123 async_cow_free);
1125 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1126 PAGE_CACHE_SHIFT;
1127 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1129 btrfs_queue_work(root->fs_info->delalloc_workers,
1130 &async_cow->work);
1132 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1133 wait_event(root->fs_info->async_submit_wait,
1134 (atomic_read(&root->fs_info->async_delalloc_pages) <
1135 limit));
1138 while (atomic_read(&root->fs_info->async_submit_draining) &&
1139 atomic_read(&root->fs_info->async_delalloc_pages)) {
1140 wait_event(root->fs_info->async_submit_wait,
1141 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1142 0));
1145 *nr_written += nr_pages;
1146 start = cur_end + 1;
1148 *page_started = 1;
1149 return 0;
1152 static noinline int csum_exist_in_range(struct btrfs_root *root,
1153 u64 bytenr, u64 num_bytes)
1155 int ret;
1156 struct btrfs_ordered_sum *sums;
1157 LIST_HEAD(list);
1159 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1160 bytenr + num_bytes - 1, &list, 0);
1161 if (ret == 0 && list_empty(&list))
1162 return 0;
1164 while (!list_empty(&list)) {
1165 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1166 list_del(&sums->list);
1167 kfree(sums);
1169 return 1;
1173 * when nowcow writeback call back. This checks for snapshots or COW copies
1174 * of the extents that exist in the file, and COWs the file as required.
1176 * If no cow copies or snapshots exist, we write directly to the existing
1177 * blocks on disk
1179 static noinline int run_delalloc_nocow(struct inode *inode,
1180 struct page *locked_page,
1181 u64 start, u64 end, int *page_started, int force,
1182 unsigned long *nr_written)
1184 struct btrfs_root *root = BTRFS_I(inode)->root;
1185 struct btrfs_trans_handle *trans;
1186 struct extent_buffer *leaf;
1187 struct btrfs_path *path;
1188 struct btrfs_file_extent_item *fi;
1189 struct btrfs_key found_key;
1190 u64 cow_start;
1191 u64 cur_offset;
1192 u64 extent_end;
1193 u64 extent_offset;
1194 u64 disk_bytenr;
1195 u64 num_bytes;
1196 u64 disk_num_bytes;
1197 u64 ram_bytes;
1198 int extent_type;
1199 int ret, err;
1200 int type;
1201 int nocow;
1202 int check_prev = 1;
1203 bool nolock;
1204 u64 ino = btrfs_ino(inode);
1206 path = btrfs_alloc_path();
1207 if (!path) {
1208 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1209 EXTENT_LOCKED | EXTENT_DELALLOC |
1210 EXTENT_DO_ACCOUNTING |
1211 EXTENT_DEFRAG, PAGE_UNLOCK |
1212 PAGE_CLEAR_DIRTY |
1213 PAGE_SET_WRITEBACK |
1214 PAGE_END_WRITEBACK);
1215 return -ENOMEM;
1218 nolock = btrfs_is_free_space_inode(inode);
1220 if (nolock)
1221 trans = btrfs_join_transaction_nolock(root);
1222 else
1223 trans = btrfs_join_transaction(root);
1225 if (IS_ERR(trans)) {
1226 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1227 EXTENT_LOCKED | EXTENT_DELALLOC |
1228 EXTENT_DO_ACCOUNTING |
1229 EXTENT_DEFRAG, PAGE_UNLOCK |
1230 PAGE_CLEAR_DIRTY |
1231 PAGE_SET_WRITEBACK |
1232 PAGE_END_WRITEBACK);
1233 btrfs_free_path(path);
1234 return PTR_ERR(trans);
1237 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1239 cow_start = (u64)-1;
1240 cur_offset = start;
1241 while (1) {
1242 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1243 cur_offset, 0);
1244 if (ret < 0)
1245 goto error;
1246 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1247 leaf = path->nodes[0];
1248 btrfs_item_key_to_cpu(leaf, &found_key,
1249 path->slots[0] - 1);
1250 if (found_key.objectid == ino &&
1251 found_key.type == BTRFS_EXTENT_DATA_KEY)
1252 path->slots[0]--;
1254 check_prev = 0;
1255 next_slot:
1256 leaf = path->nodes[0];
1257 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1258 ret = btrfs_next_leaf(root, path);
1259 if (ret < 0)
1260 goto error;
1261 if (ret > 0)
1262 break;
1263 leaf = path->nodes[0];
1266 nocow = 0;
1267 disk_bytenr = 0;
1268 num_bytes = 0;
1269 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1271 if (found_key.objectid > ino)
1272 break;
1273 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1274 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1275 path->slots[0]++;
1276 goto next_slot;
1278 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1279 found_key.offset > end)
1280 break;
1282 if (found_key.offset > cur_offset) {
1283 extent_end = found_key.offset;
1284 extent_type = 0;
1285 goto out_check;
1288 fi = btrfs_item_ptr(leaf, path->slots[0],
1289 struct btrfs_file_extent_item);
1290 extent_type = btrfs_file_extent_type(leaf, fi);
1292 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1293 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1294 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1295 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1296 extent_offset = btrfs_file_extent_offset(leaf, fi);
1297 extent_end = found_key.offset +
1298 btrfs_file_extent_num_bytes(leaf, fi);
1299 disk_num_bytes =
1300 btrfs_file_extent_disk_num_bytes(leaf, fi);
1301 if (extent_end <= start) {
1302 path->slots[0]++;
1303 goto next_slot;
1305 if (disk_bytenr == 0)
1306 goto out_check;
1307 if (btrfs_file_extent_compression(leaf, fi) ||
1308 btrfs_file_extent_encryption(leaf, fi) ||
1309 btrfs_file_extent_other_encoding(leaf, fi))
1310 goto out_check;
1311 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1312 goto out_check;
1313 if (btrfs_extent_readonly(root, disk_bytenr))
1314 goto out_check;
1315 if (btrfs_cross_ref_exist(trans, root, ino,
1316 found_key.offset -
1317 extent_offset, disk_bytenr))
1318 goto out_check;
1319 disk_bytenr += extent_offset;
1320 disk_bytenr += cur_offset - found_key.offset;
1321 num_bytes = min(end + 1, extent_end) - cur_offset;
1323 * if there are pending snapshots for this root,
1324 * we fall into common COW way.
1326 if (!nolock) {
1327 err = btrfs_start_nocow_write(root);
1328 if (!err)
1329 goto out_check;
1332 * force cow if csum exists in the range.
1333 * this ensure that csum for a given extent are
1334 * either valid or do not exist.
1336 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1337 goto out_check;
1338 nocow = 1;
1339 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1340 extent_end = found_key.offset +
1341 btrfs_file_extent_inline_len(leaf,
1342 path->slots[0], fi);
1343 extent_end = ALIGN(extent_end, root->sectorsize);
1344 } else {
1345 BUG_ON(1);
1347 out_check:
1348 if (extent_end <= start) {
1349 path->slots[0]++;
1350 if (!nolock && nocow)
1351 btrfs_end_nocow_write(root);
1352 goto next_slot;
1354 if (!nocow) {
1355 if (cow_start == (u64)-1)
1356 cow_start = cur_offset;
1357 cur_offset = extent_end;
1358 if (cur_offset > end)
1359 break;
1360 path->slots[0]++;
1361 goto next_slot;
1364 btrfs_release_path(path);
1365 if (cow_start != (u64)-1) {
1366 ret = cow_file_range(inode, locked_page,
1367 cow_start, found_key.offset - 1,
1368 page_started, nr_written, 1);
1369 if (ret) {
1370 if (!nolock && nocow)
1371 btrfs_end_nocow_write(root);
1372 goto error;
1374 cow_start = (u64)-1;
1377 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1378 struct extent_map *em;
1379 struct extent_map_tree *em_tree;
1380 em_tree = &BTRFS_I(inode)->extent_tree;
1381 em = alloc_extent_map();
1382 BUG_ON(!em); /* -ENOMEM */
1383 em->start = cur_offset;
1384 em->orig_start = found_key.offset - extent_offset;
1385 em->len = num_bytes;
1386 em->block_len = num_bytes;
1387 em->block_start = disk_bytenr;
1388 em->orig_block_len = disk_num_bytes;
1389 em->ram_bytes = ram_bytes;
1390 em->bdev = root->fs_info->fs_devices->latest_bdev;
1391 em->mod_start = em->start;
1392 em->mod_len = em->len;
1393 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1394 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1395 em->generation = -1;
1396 while (1) {
1397 write_lock(&em_tree->lock);
1398 ret = add_extent_mapping(em_tree, em, 1);
1399 write_unlock(&em_tree->lock);
1400 if (ret != -EEXIST) {
1401 free_extent_map(em);
1402 break;
1404 btrfs_drop_extent_cache(inode, em->start,
1405 em->start + em->len - 1, 0);
1407 type = BTRFS_ORDERED_PREALLOC;
1408 } else {
1409 type = BTRFS_ORDERED_NOCOW;
1412 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1413 num_bytes, num_bytes, type);
1414 BUG_ON(ret); /* -ENOMEM */
1416 if (root->root_key.objectid ==
1417 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1418 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1419 num_bytes);
1420 if (ret) {
1421 if (!nolock && nocow)
1422 btrfs_end_nocow_write(root);
1423 goto error;
1427 extent_clear_unlock_delalloc(inode, cur_offset,
1428 cur_offset + num_bytes - 1,
1429 locked_page, EXTENT_LOCKED |
1430 EXTENT_DELALLOC, PAGE_UNLOCK |
1431 PAGE_SET_PRIVATE2);
1432 if (!nolock && nocow)
1433 btrfs_end_nocow_write(root);
1434 cur_offset = extent_end;
1435 if (cur_offset > end)
1436 break;
1438 btrfs_release_path(path);
1440 if (cur_offset <= end && cow_start == (u64)-1) {
1441 cow_start = cur_offset;
1442 cur_offset = end;
1445 if (cow_start != (u64)-1) {
1446 ret = cow_file_range(inode, locked_page, cow_start, end,
1447 page_started, nr_written, 1);
1448 if (ret)
1449 goto error;
1452 error:
1453 err = btrfs_end_transaction(trans, root);
1454 if (!ret)
1455 ret = err;
1457 if (ret && cur_offset < end)
1458 extent_clear_unlock_delalloc(inode, cur_offset, end,
1459 locked_page, EXTENT_LOCKED |
1460 EXTENT_DELALLOC | EXTENT_DEFRAG |
1461 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1462 PAGE_CLEAR_DIRTY |
1463 PAGE_SET_WRITEBACK |
1464 PAGE_END_WRITEBACK);
1465 btrfs_free_path(path);
1466 return ret;
1469 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1472 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1473 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1474 return 0;
1477 * @defrag_bytes is a hint value, no spinlock held here,
1478 * if is not zero, it means the file is defragging.
1479 * Force cow if given extent needs to be defragged.
1481 if (BTRFS_I(inode)->defrag_bytes &&
1482 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1483 EXTENT_DEFRAG, 0, NULL))
1484 return 1;
1486 return 0;
1490 * extent_io.c call back to do delayed allocation processing
1492 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1493 u64 start, u64 end, int *page_started,
1494 unsigned long *nr_written)
1496 int ret;
1497 int force_cow = need_force_cow(inode, start, end);
1499 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1500 ret = run_delalloc_nocow(inode, locked_page, start, end,
1501 page_started, 1, nr_written);
1502 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1503 ret = run_delalloc_nocow(inode, locked_page, start, end,
1504 page_started, 0, nr_written);
1505 } else if (!inode_need_compress(inode)) {
1506 ret = cow_file_range(inode, locked_page, start, end,
1507 page_started, nr_written, 1);
1508 } else {
1509 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1510 &BTRFS_I(inode)->runtime_flags);
1511 ret = cow_file_range_async(inode, locked_page, start, end,
1512 page_started, nr_written);
1514 return ret;
1517 static void btrfs_split_extent_hook(struct inode *inode,
1518 struct extent_state *orig, u64 split)
1520 /* not delalloc, ignore it */
1521 if (!(orig->state & EXTENT_DELALLOC))
1522 return;
1524 spin_lock(&BTRFS_I(inode)->lock);
1525 BTRFS_I(inode)->outstanding_extents++;
1526 spin_unlock(&BTRFS_I(inode)->lock);
1530 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1531 * extents so we can keep track of new extents that are just merged onto old
1532 * extents, such as when we are doing sequential writes, so we can properly
1533 * account for the metadata space we'll need.
1535 static void btrfs_merge_extent_hook(struct inode *inode,
1536 struct extent_state *new,
1537 struct extent_state *other)
1539 /* not delalloc, ignore it */
1540 if (!(other->state & EXTENT_DELALLOC))
1541 return;
1543 spin_lock(&BTRFS_I(inode)->lock);
1544 BTRFS_I(inode)->outstanding_extents--;
1545 spin_unlock(&BTRFS_I(inode)->lock);
1548 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1549 struct inode *inode)
1551 spin_lock(&root->delalloc_lock);
1552 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1553 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1554 &root->delalloc_inodes);
1555 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1556 &BTRFS_I(inode)->runtime_flags);
1557 root->nr_delalloc_inodes++;
1558 if (root->nr_delalloc_inodes == 1) {
1559 spin_lock(&root->fs_info->delalloc_root_lock);
1560 BUG_ON(!list_empty(&root->delalloc_root));
1561 list_add_tail(&root->delalloc_root,
1562 &root->fs_info->delalloc_roots);
1563 spin_unlock(&root->fs_info->delalloc_root_lock);
1566 spin_unlock(&root->delalloc_lock);
1569 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1570 struct inode *inode)
1572 spin_lock(&root->delalloc_lock);
1573 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1574 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1575 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1576 &BTRFS_I(inode)->runtime_flags);
1577 root->nr_delalloc_inodes--;
1578 if (!root->nr_delalloc_inodes) {
1579 spin_lock(&root->fs_info->delalloc_root_lock);
1580 BUG_ON(list_empty(&root->delalloc_root));
1581 list_del_init(&root->delalloc_root);
1582 spin_unlock(&root->fs_info->delalloc_root_lock);
1585 spin_unlock(&root->delalloc_lock);
1589 * extent_io.c set_bit_hook, used to track delayed allocation
1590 * bytes in this file, and to maintain the list of inodes that
1591 * have pending delalloc work to be done.
1593 static void btrfs_set_bit_hook(struct inode *inode,
1594 struct extent_state *state, unsigned long *bits)
1597 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1598 WARN_ON(1);
1600 * set_bit and clear bit hooks normally require _irqsave/restore
1601 * but in this case, we are only testing for the DELALLOC
1602 * bit, which is only set or cleared with irqs on
1604 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1605 struct btrfs_root *root = BTRFS_I(inode)->root;
1606 u64 len = state->end + 1 - state->start;
1607 bool do_list = !btrfs_is_free_space_inode(inode);
1609 if (*bits & EXTENT_FIRST_DELALLOC) {
1610 *bits &= ~EXTENT_FIRST_DELALLOC;
1611 } else {
1612 spin_lock(&BTRFS_I(inode)->lock);
1613 BTRFS_I(inode)->outstanding_extents++;
1614 spin_unlock(&BTRFS_I(inode)->lock);
1617 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1618 root->fs_info->delalloc_batch);
1619 spin_lock(&BTRFS_I(inode)->lock);
1620 BTRFS_I(inode)->delalloc_bytes += len;
1621 if (*bits & EXTENT_DEFRAG)
1622 BTRFS_I(inode)->defrag_bytes += len;
1623 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1624 &BTRFS_I(inode)->runtime_flags))
1625 btrfs_add_delalloc_inodes(root, inode);
1626 spin_unlock(&BTRFS_I(inode)->lock);
1631 * extent_io.c clear_bit_hook, see set_bit_hook for why
1633 static void btrfs_clear_bit_hook(struct inode *inode,
1634 struct extent_state *state,
1635 unsigned long *bits)
1637 u64 len = state->end + 1 - state->start;
1639 spin_lock(&BTRFS_I(inode)->lock);
1640 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1641 BTRFS_I(inode)->defrag_bytes -= len;
1642 spin_unlock(&BTRFS_I(inode)->lock);
1645 * set_bit and clear bit hooks normally require _irqsave/restore
1646 * but in this case, we are only testing for the DELALLOC
1647 * bit, which is only set or cleared with irqs on
1649 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1650 struct btrfs_root *root = BTRFS_I(inode)->root;
1651 bool do_list = !btrfs_is_free_space_inode(inode);
1653 if (*bits & EXTENT_FIRST_DELALLOC) {
1654 *bits &= ~EXTENT_FIRST_DELALLOC;
1655 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1656 spin_lock(&BTRFS_I(inode)->lock);
1657 BTRFS_I(inode)->outstanding_extents--;
1658 spin_unlock(&BTRFS_I(inode)->lock);
1662 * We don't reserve metadata space for space cache inodes so we
1663 * don't need to call dellalloc_release_metadata if there is an
1664 * error.
1666 if (*bits & EXTENT_DO_ACCOUNTING &&
1667 root != root->fs_info->tree_root)
1668 btrfs_delalloc_release_metadata(inode, len);
1670 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1671 && do_list && !(state->state & EXTENT_NORESERVE))
1672 btrfs_free_reserved_data_space(inode, len);
1674 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1675 root->fs_info->delalloc_batch);
1676 spin_lock(&BTRFS_I(inode)->lock);
1677 BTRFS_I(inode)->delalloc_bytes -= len;
1678 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1679 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1680 &BTRFS_I(inode)->runtime_flags))
1681 btrfs_del_delalloc_inode(root, inode);
1682 spin_unlock(&BTRFS_I(inode)->lock);
1687 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1688 * we don't create bios that span stripes or chunks
1690 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1691 size_t size, struct bio *bio,
1692 unsigned long bio_flags)
1694 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1695 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1696 u64 length = 0;
1697 u64 map_length;
1698 int ret;
1700 if (bio_flags & EXTENT_BIO_COMPRESSED)
1701 return 0;
1703 length = bio->bi_iter.bi_size;
1704 map_length = length;
1705 ret = btrfs_map_block(root->fs_info, rw, logical,
1706 &map_length, NULL, 0);
1707 /* Will always return 0 with map_multi == NULL */
1708 BUG_ON(ret < 0);
1709 if (map_length < length + size)
1710 return 1;
1711 return 0;
1715 * in order to insert checksums into the metadata in large chunks,
1716 * we wait until bio submission time. All the pages in the bio are
1717 * checksummed and sums are attached onto the ordered extent record.
1719 * At IO completion time the cums attached on the ordered extent record
1720 * are inserted into the btree
1722 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1723 struct bio *bio, int mirror_num,
1724 unsigned long bio_flags,
1725 u64 bio_offset)
1727 struct btrfs_root *root = BTRFS_I(inode)->root;
1728 int ret = 0;
1730 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1731 BUG_ON(ret); /* -ENOMEM */
1732 return 0;
1736 * in order to insert checksums into the metadata in large chunks,
1737 * we wait until bio submission time. All the pages in the bio are
1738 * checksummed and sums are attached onto the ordered extent record.
1740 * At IO completion time the cums attached on the ordered extent record
1741 * are inserted into the btree
1743 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1744 int mirror_num, unsigned long bio_flags,
1745 u64 bio_offset)
1747 struct btrfs_root *root = BTRFS_I(inode)->root;
1748 int ret;
1750 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1751 if (ret)
1752 bio_endio(bio, ret);
1753 return ret;
1757 * extent_io.c submission hook. This does the right thing for csum calculation
1758 * on write, or reading the csums from the tree before a read
1760 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1761 int mirror_num, unsigned long bio_flags,
1762 u64 bio_offset)
1764 struct btrfs_root *root = BTRFS_I(inode)->root;
1765 int ret = 0;
1766 int skip_sum;
1767 int metadata = 0;
1768 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1770 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1772 if (btrfs_is_free_space_inode(inode))
1773 metadata = 2;
1775 if (!(rw & REQ_WRITE)) {
1776 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1777 if (ret)
1778 goto out;
1780 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1781 ret = btrfs_submit_compressed_read(inode, bio,
1782 mirror_num,
1783 bio_flags);
1784 goto out;
1785 } else if (!skip_sum) {
1786 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1787 if (ret)
1788 goto out;
1790 goto mapit;
1791 } else if (async && !skip_sum) {
1792 /* csum items have already been cloned */
1793 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1794 goto mapit;
1795 /* we're doing a write, do the async checksumming */
1796 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1797 inode, rw, bio, mirror_num,
1798 bio_flags, bio_offset,
1799 __btrfs_submit_bio_start,
1800 __btrfs_submit_bio_done);
1801 goto out;
1802 } else if (!skip_sum) {
1803 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1804 if (ret)
1805 goto out;
1808 mapit:
1809 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1811 out:
1812 if (ret < 0)
1813 bio_endio(bio, ret);
1814 return ret;
1818 * given a list of ordered sums record them in the inode. This happens
1819 * at IO completion time based on sums calculated at bio submission time.
1821 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1822 struct inode *inode, u64 file_offset,
1823 struct list_head *list)
1825 struct btrfs_ordered_sum *sum;
1827 list_for_each_entry(sum, list, list) {
1828 trans->adding_csums = 1;
1829 btrfs_csum_file_blocks(trans,
1830 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1831 trans->adding_csums = 0;
1833 return 0;
1836 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1837 struct extent_state **cached_state)
1839 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1840 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1841 cached_state, GFP_NOFS);
1844 /* see btrfs_writepage_start_hook for details on why this is required */
1845 struct btrfs_writepage_fixup {
1846 struct page *page;
1847 struct btrfs_work work;
1850 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1852 struct btrfs_writepage_fixup *fixup;
1853 struct btrfs_ordered_extent *ordered;
1854 struct extent_state *cached_state = NULL;
1855 struct page *page;
1856 struct inode *inode;
1857 u64 page_start;
1858 u64 page_end;
1859 int ret;
1861 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1862 page = fixup->page;
1863 again:
1864 lock_page(page);
1865 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1866 ClearPageChecked(page);
1867 goto out_page;
1870 inode = page->mapping->host;
1871 page_start = page_offset(page);
1872 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1874 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1875 &cached_state);
1877 /* already ordered? We're done */
1878 if (PagePrivate2(page))
1879 goto out;
1881 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1882 if (ordered) {
1883 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1884 page_end, &cached_state, GFP_NOFS);
1885 unlock_page(page);
1886 btrfs_start_ordered_extent(inode, ordered, 1);
1887 btrfs_put_ordered_extent(ordered);
1888 goto again;
1891 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1892 if (ret) {
1893 mapping_set_error(page->mapping, ret);
1894 end_extent_writepage(page, ret, page_start, page_end);
1895 ClearPageChecked(page);
1896 goto out;
1899 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1900 ClearPageChecked(page);
1901 set_page_dirty(page);
1902 out:
1903 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1904 &cached_state, GFP_NOFS);
1905 out_page:
1906 unlock_page(page);
1907 page_cache_release(page);
1908 kfree(fixup);
1912 * There are a few paths in the higher layers of the kernel that directly
1913 * set the page dirty bit without asking the filesystem if it is a
1914 * good idea. This causes problems because we want to make sure COW
1915 * properly happens and the data=ordered rules are followed.
1917 * In our case any range that doesn't have the ORDERED bit set
1918 * hasn't been properly setup for IO. We kick off an async process
1919 * to fix it up. The async helper will wait for ordered extents, set
1920 * the delalloc bit and make it safe to write the page.
1922 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1924 struct inode *inode = page->mapping->host;
1925 struct btrfs_writepage_fixup *fixup;
1926 struct btrfs_root *root = BTRFS_I(inode)->root;
1928 /* this page is properly in the ordered list */
1929 if (TestClearPagePrivate2(page))
1930 return 0;
1932 if (PageChecked(page))
1933 return -EAGAIN;
1935 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1936 if (!fixup)
1937 return -EAGAIN;
1939 SetPageChecked(page);
1940 page_cache_get(page);
1941 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
1942 btrfs_writepage_fixup_worker, NULL, NULL);
1943 fixup->page = page;
1944 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1945 return -EBUSY;
1948 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1949 struct inode *inode, u64 file_pos,
1950 u64 disk_bytenr, u64 disk_num_bytes,
1951 u64 num_bytes, u64 ram_bytes,
1952 u8 compression, u8 encryption,
1953 u16 other_encoding, int extent_type)
1955 struct btrfs_root *root = BTRFS_I(inode)->root;
1956 struct btrfs_file_extent_item *fi;
1957 struct btrfs_path *path;
1958 struct extent_buffer *leaf;
1959 struct btrfs_key ins;
1960 int extent_inserted = 0;
1961 int ret;
1963 path = btrfs_alloc_path();
1964 if (!path)
1965 return -ENOMEM;
1968 * we may be replacing one extent in the tree with another.
1969 * The new extent is pinned in the extent map, and we don't want
1970 * to drop it from the cache until it is completely in the btree.
1972 * So, tell btrfs_drop_extents to leave this extent in the cache.
1973 * the caller is expected to unpin it and allow it to be merged
1974 * with the others.
1976 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1977 file_pos + num_bytes, NULL, 0,
1978 1, sizeof(*fi), &extent_inserted);
1979 if (ret)
1980 goto out;
1982 if (!extent_inserted) {
1983 ins.objectid = btrfs_ino(inode);
1984 ins.offset = file_pos;
1985 ins.type = BTRFS_EXTENT_DATA_KEY;
1987 path->leave_spinning = 1;
1988 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1989 sizeof(*fi));
1990 if (ret)
1991 goto out;
1993 leaf = path->nodes[0];
1994 fi = btrfs_item_ptr(leaf, path->slots[0],
1995 struct btrfs_file_extent_item);
1996 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1997 btrfs_set_file_extent_type(leaf, fi, extent_type);
1998 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1999 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2000 btrfs_set_file_extent_offset(leaf, fi, 0);
2001 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2002 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2003 btrfs_set_file_extent_compression(leaf, fi, compression);
2004 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2005 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2007 btrfs_mark_buffer_dirty(leaf);
2008 btrfs_release_path(path);
2010 inode_add_bytes(inode, num_bytes);
2012 ins.objectid = disk_bytenr;
2013 ins.offset = disk_num_bytes;
2014 ins.type = BTRFS_EXTENT_ITEM_KEY;
2015 ret = btrfs_alloc_reserved_file_extent(trans, root,
2016 root->root_key.objectid,
2017 btrfs_ino(inode), file_pos, &ins);
2018 out:
2019 btrfs_free_path(path);
2021 return ret;
2024 /* snapshot-aware defrag */
2025 struct sa_defrag_extent_backref {
2026 struct rb_node node;
2027 struct old_sa_defrag_extent *old;
2028 u64 root_id;
2029 u64 inum;
2030 u64 file_pos;
2031 u64 extent_offset;
2032 u64 num_bytes;
2033 u64 generation;
2036 struct old_sa_defrag_extent {
2037 struct list_head list;
2038 struct new_sa_defrag_extent *new;
2040 u64 extent_offset;
2041 u64 bytenr;
2042 u64 offset;
2043 u64 len;
2044 int count;
2047 struct new_sa_defrag_extent {
2048 struct rb_root root;
2049 struct list_head head;
2050 struct btrfs_path *path;
2051 struct inode *inode;
2052 u64 file_pos;
2053 u64 len;
2054 u64 bytenr;
2055 u64 disk_len;
2056 u8 compress_type;
2059 static int backref_comp(struct sa_defrag_extent_backref *b1,
2060 struct sa_defrag_extent_backref *b2)
2062 if (b1->root_id < b2->root_id)
2063 return -1;
2064 else if (b1->root_id > b2->root_id)
2065 return 1;
2067 if (b1->inum < b2->inum)
2068 return -1;
2069 else if (b1->inum > b2->inum)
2070 return 1;
2072 if (b1->file_pos < b2->file_pos)
2073 return -1;
2074 else if (b1->file_pos > b2->file_pos)
2075 return 1;
2078 * [------------------------------] ===> (a range of space)
2079 * |<--->| |<---->| =============> (fs/file tree A)
2080 * |<---------------------------->| ===> (fs/file tree B)
2082 * A range of space can refer to two file extents in one tree while
2083 * refer to only one file extent in another tree.
2085 * So we may process a disk offset more than one time(two extents in A)
2086 * and locate at the same extent(one extent in B), then insert two same
2087 * backrefs(both refer to the extent in B).
2089 return 0;
2092 static void backref_insert(struct rb_root *root,
2093 struct sa_defrag_extent_backref *backref)
2095 struct rb_node **p = &root->rb_node;
2096 struct rb_node *parent = NULL;
2097 struct sa_defrag_extent_backref *entry;
2098 int ret;
2100 while (*p) {
2101 parent = *p;
2102 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2104 ret = backref_comp(backref, entry);
2105 if (ret < 0)
2106 p = &(*p)->rb_left;
2107 else
2108 p = &(*p)->rb_right;
2111 rb_link_node(&backref->node, parent, p);
2112 rb_insert_color(&backref->node, root);
2116 * Note the backref might has changed, and in this case we just return 0.
2118 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2119 void *ctx)
2121 struct btrfs_file_extent_item *extent;
2122 struct btrfs_fs_info *fs_info;
2123 struct old_sa_defrag_extent *old = ctx;
2124 struct new_sa_defrag_extent *new = old->new;
2125 struct btrfs_path *path = new->path;
2126 struct btrfs_key key;
2127 struct btrfs_root *root;
2128 struct sa_defrag_extent_backref *backref;
2129 struct extent_buffer *leaf;
2130 struct inode *inode = new->inode;
2131 int slot;
2132 int ret;
2133 u64 extent_offset;
2134 u64 num_bytes;
2136 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2137 inum == btrfs_ino(inode))
2138 return 0;
2140 key.objectid = root_id;
2141 key.type = BTRFS_ROOT_ITEM_KEY;
2142 key.offset = (u64)-1;
2144 fs_info = BTRFS_I(inode)->root->fs_info;
2145 root = btrfs_read_fs_root_no_name(fs_info, &key);
2146 if (IS_ERR(root)) {
2147 if (PTR_ERR(root) == -ENOENT)
2148 return 0;
2149 WARN_ON(1);
2150 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2151 inum, offset, root_id);
2152 return PTR_ERR(root);
2155 key.objectid = inum;
2156 key.type = BTRFS_EXTENT_DATA_KEY;
2157 if (offset > (u64)-1 << 32)
2158 key.offset = 0;
2159 else
2160 key.offset = offset;
2162 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2163 if (WARN_ON(ret < 0))
2164 return ret;
2165 ret = 0;
2167 while (1) {
2168 cond_resched();
2170 leaf = path->nodes[0];
2171 slot = path->slots[0];
2173 if (slot >= btrfs_header_nritems(leaf)) {
2174 ret = btrfs_next_leaf(root, path);
2175 if (ret < 0) {
2176 goto out;
2177 } else if (ret > 0) {
2178 ret = 0;
2179 goto out;
2181 continue;
2184 path->slots[0]++;
2186 btrfs_item_key_to_cpu(leaf, &key, slot);
2188 if (key.objectid > inum)
2189 goto out;
2191 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2192 continue;
2194 extent = btrfs_item_ptr(leaf, slot,
2195 struct btrfs_file_extent_item);
2197 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2198 continue;
2201 * 'offset' refers to the exact key.offset,
2202 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2203 * (key.offset - extent_offset).
2205 if (key.offset != offset)
2206 continue;
2208 extent_offset = btrfs_file_extent_offset(leaf, extent);
2209 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2211 if (extent_offset >= old->extent_offset + old->offset +
2212 old->len || extent_offset + num_bytes <=
2213 old->extent_offset + old->offset)
2214 continue;
2215 break;
2218 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2219 if (!backref) {
2220 ret = -ENOENT;
2221 goto out;
2224 backref->root_id = root_id;
2225 backref->inum = inum;
2226 backref->file_pos = offset;
2227 backref->num_bytes = num_bytes;
2228 backref->extent_offset = extent_offset;
2229 backref->generation = btrfs_file_extent_generation(leaf, extent);
2230 backref->old = old;
2231 backref_insert(&new->root, backref);
2232 old->count++;
2233 out:
2234 btrfs_release_path(path);
2235 WARN_ON(ret);
2236 return ret;
2239 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2240 struct new_sa_defrag_extent *new)
2242 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2243 struct old_sa_defrag_extent *old, *tmp;
2244 int ret;
2246 new->path = path;
2248 list_for_each_entry_safe(old, tmp, &new->head, list) {
2249 ret = iterate_inodes_from_logical(old->bytenr +
2250 old->extent_offset, fs_info,
2251 path, record_one_backref,
2252 old);
2253 if (ret < 0 && ret != -ENOENT)
2254 return false;
2256 /* no backref to be processed for this extent */
2257 if (!old->count) {
2258 list_del(&old->list);
2259 kfree(old);
2263 if (list_empty(&new->head))
2264 return false;
2266 return true;
2269 static int relink_is_mergable(struct extent_buffer *leaf,
2270 struct btrfs_file_extent_item *fi,
2271 struct new_sa_defrag_extent *new)
2273 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2274 return 0;
2276 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2277 return 0;
2279 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2280 return 0;
2282 if (btrfs_file_extent_encryption(leaf, fi) ||
2283 btrfs_file_extent_other_encoding(leaf, fi))
2284 return 0;
2286 return 1;
2290 * Note the backref might has changed, and in this case we just return 0.
2292 static noinline int relink_extent_backref(struct btrfs_path *path,
2293 struct sa_defrag_extent_backref *prev,
2294 struct sa_defrag_extent_backref *backref)
2296 struct btrfs_file_extent_item *extent;
2297 struct btrfs_file_extent_item *item;
2298 struct btrfs_ordered_extent *ordered;
2299 struct btrfs_trans_handle *trans;
2300 struct btrfs_fs_info *fs_info;
2301 struct btrfs_root *root;
2302 struct btrfs_key key;
2303 struct extent_buffer *leaf;
2304 struct old_sa_defrag_extent *old = backref->old;
2305 struct new_sa_defrag_extent *new = old->new;
2306 struct inode *src_inode = new->inode;
2307 struct inode *inode;
2308 struct extent_state *cached = NULL;
2309 int ret = 0;
2310 u64 start;
2311 u64 len;
2312 u64 lock_start;
2313 u64 lock_end;
2314 bool merge = false;
2315 int index;
2317 if (prev && prev->root_id == backref->root_id &&
2318 prev->inum == backref->inum &&
2319 prev->file_pos + prev->num_bytes == backref->file_pos)
2320 merge = true;
2322 /* step 1: get root */
2323 key.objectid = backref->root_id;
2324 key.type = BTRFS_ROOT_ITEM_KEY;
2325 key.offset = (u64)-1;
2327 fs_info = BTRFS_I(src_inode)->root->fs_info;
2328 index = srcu_read_lock(&fs_info->subvol_srcu);
2330 root = btrfs_read_fs_root_no_name(fs_info, &key);
2331 if (IS_ERR(root)) {
2332 srcu_read_unlock(&fs_info->subvol_srcu, index);
2333 if (PTR_ERR(root) == -ENOENT)
2334 return 0;
2335 return PTR_ERR(root);
2338 if (btrfs_root_readonly(root)) {
2339 srcu_read_unlock(&fs_info->subvol_srcu, index);
2340 return 0;
2343 /* step 2: get inode */
2344 key.objectid = backref->inum;
2345 key.type = BTRFS_INODE_ITEM_KEY;
2346 key.offset = 0;
2348 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2349 if (IS_ERR(inode)) {
2350 srcu_read_unlock(&fs_info->subvol_srcu, index);
2351 return 0;
2354 srcu_read_unlock(&fs_info->subvol_srcu, index);
2356 /* step 3: relink backref */
2357 lock_start = backref->file_pos;
2358 lock_end = backref->file_pos + backref->num_bytes - 1;
2359 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2360 0, &cached);
2362 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2363 if (ordered) {
2364 btrfs_put_ordered_extent(ordered);
2365 goto out_unlock;
2368 trans = btrfs_join_transaction(root);
2369 if (IS_ERR(trans)) {
2370 ret = PTR_ERR(trans);
2371 goto out_unlock;
2374 key.objectid = backref->inum;
2375 key.type = BTRFS_EXTENT_DATA_KEY;
2376 key.offset = backref->file_pos;
2378 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2379 if (ret < 0) {
2380 goto out_free_path;
2381 } else if (ret > 0) {
2382 ret = 0;
2383 goto out_free_path;
2386 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2387 struct btrfs_file_extent_item);
2389 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2390 backref->generation)
2391 goto out_free_path;
2393 btrfs_release_path(path);
2395 start = backref->file_pos;
2396 if (backref->extent_offset < old->extent_offset + old->offset)
2397 start += old->extent_offset + old->offset -
2398 backref->extent_offset;
2400 len = min(backref->extent_offset + backref->num_bytes,
2401 old->extent_offset + old->offset + old->len);
2402 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2404 ret = btrfs_drop_extents(trans, root, inode, start,
2405 start + len, 1);
2406 if (ret)
2407 goto out_free_path;
2408 again:
2409 key.objectid = btrfs_ino(inode);
2410 key.type = BTRFS_EXTENT_DATA_KEY;
2411 key.offset = start;
2413 path->leave_spinning = 1;
2414 if (merge) {
2415 struct btrfs_file_extent_item *fi;
2416 u64 extent_len;
2417 struct btrfs_key found_key;
2419 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2420 if (ret < 0)
2421 goto out_free_path;
2423 path->slots[0]--;
2424 leaf = path->nodes[0];
2425 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2427 fi = btrfs_item_ptr(leaf, path->slots[0],
2428 struct btrfs_file_extent_item);
2429 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2431 if (extent_len + found_key.offset == start &&
2432 relink_is_mergable(leaf, fi, new)) {
2433 btrfs_set_file_extent_num_bytes(leaf, fi,
2434 extent_len + len);
2435 btrfs_mark_buffer_dirty(leaf);
2436 inode_add_bytes(inode, len);
2438 ret = 1;
2439 goto out_free_path;
2440 } else {
2441 merge = false;
2442 btrfs_release_path(path);
2443 goto again;
2447 ret = btrfs_insert_empty_item(trans, root, path, &key,
2448 sizeof(*extent));
2449 if (ret) {
2450 btrfs_abort_transaction(trans, root, ret);
2451 goto out_free_path;
2454 leaf = path->nodes[0];
2455 item = btrfs_item_ptr(leaf, path->slots[0],
2456 struct btrfs_file_extent_item);
2457 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2458 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2459 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2460 btrfs_set_file_extent_num_bytes(leaf, item, len);
2461 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2462 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2463 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2464 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2465 btrfs_set_file_extent_encryption(leaf, item, 0);
2466 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2468 btrfs_mark_buffer_dirty(leaf);
2469 inode_add_bytes(inode, len);
2470 btrfs_release_path(path);
2472 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2473 new->disk_len, 0,
2474 backref->root_id, backref->inum,
2475 new->file_pos, 0); /* start - extent_offset */
2476 if (ret) {
2477 btrfs_abort_transaction(trans, root, ret);
2478 goto out_free_path;
2481 ret = 1;
2482 out_free_path:
2483 btrfs_release_path(path);
2484 path->leave_spinning = 0;
2485 btrfs_end_transaction(trans, root);
2486 out_unlock:
2487 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2488 &cached, GFP_NOFS);
2489 iput(inode);
2490 return ret;
2493 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2495 struct old_sa_defrag_extent *old, *tmp;
2497 if (!new)
2498 return;
2500 list_for_each_entry_safe(old, tmp, &new->head, list) {
2501 list_del(&old->list);
2502 kfree(old);
2504 kfree(new);
2507 static void relink_file_extents(struct new_sa_defrag_extent *new)
2509 struct btrfs_path *path;
2510 struct sa_defrag_extent_backref *backref;
2511 struct sa_defrag_extent_backref *prev = NULL;
2512 struct inode *inode;
2513 struct btrfs_root *root;
2514 struct rb_node *node;
2515 int ret;
2517 inode = new->inode;
2518 root = BTRFS_I(inode)->root;
2520 path = btrfs_alloc_path();
2521 if (!path)
2522 return;
2524 if (!record_extent_backrefs(path, new)) {
2525 btrfs_free_path(path);
2526 goto out;
2528 btrfs_release_path(path);
2530 while (1) {
2531 node = rb_first(&new->root);
2532 if (!node)
2533 break;
2534 rb_erase(node, &new->root);
2536 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2538 ret = relink_extent_backref(path, prev, backref);
2539 WARN_ON(ret < 0);
2541 kfree(prev);
2543 if (ret == 1)
2544 prev = backref;
2545 else
2546 prev = NULL;
2547 cond_resched();
2549 kfree(prev);
2551 btrfs_free_path(path);
2552 out:
2553 free_sa_defrag_extent(new);
2555 atomic_dec(&root->fs_info->defrag_running);
2556 wake_up(&root->fs_info->transaction_wait);
2559 static struct new_sa_defrag_extent *
2560 record_old_file_extents(struct inode *inode,
2561 struct btrfs_ordered_extent *ordered)
2563 struct btrfs_root *root = BTRFS_I(inode)->root;
2564 struct btrfs_path *path;
2565 struct btrfs_key key;
2566 struct old_sa_defrag_extent *old;
2567 struct new_sa_defrag_extent *new;
2568 int ret;
2570 new = kmalloc(sizeof(*new), GFP_NOFS);
2571 if (!new)
2572 return NULL;
2574 new->inode = inode;
2575 new->file_pos = ordered->file_offset;
2576 new->len = ordered->len;
2577 new->bytenr = ordered->start;
2578 new->disk_len = ordered->disk_len;
2579 new->compress_type = ordered->compress_type;
2580 new->root = RB_ROOT;
2581 INIT_LIST_HEAD(&new->head);
2583 path = btrfs_alloc_path();
2584 if (!path)
2585 goto out_kfree;
2587 key.objectid = btrfs_ino(inode);
2588 key.type = BTRFS_EXTENT_DATA_KEY;
2589 key.offset = new->file_pos;
2591 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2592 if (ret < 0)
2593 goto out_free_path;
2594 if (ret > 0 && path->slots[0] > 0)
2595 path->slots[0]--;
2597 /* find out all the old extents for the file range */
2598 while (1) {
2599 struct btrfs_file_extent_item *extent;
2600 struct extent_buffer *l;
2601 int slot;
2602 u64 num_bytes;
2603 u64 offset;
2604 u64 end;
2605 u64 disk_bytenr;
2606 u64 extent_offset;
2608 l = path->nodes[0];
2609 slot = path->slots[0];
2611 if (slot >= btrfs_header_nritems(l)) {
2612 ret = btrfs_next_leaf(root, path);
2613 if (ret < 0)
2614 goto out_free_path;
2615 else if (ret > 0)
2616 break;
2617 continue;
2620 btrfs_item_key_to_cpu(l, &key, slot);
2622 if (key.objectid != btrfs_ino(inode))
2623 break;
2624 if (key.type != BTRFS_EXTENT_DATA_KEY)
2625 break;
2626 if (key.offset >= new->file_pos + new->len)
2627 break;
2629 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2631 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2632 if (key.offset + num_bytes < new->file_pos)
2633 goto next;
2635 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2636 if (!disk_bytenr)
2637 goto next;
2639 extent_offset = btrfs_file_extent_offset(l, extent);
2641 old = kmalloc(sizeof(*old), GFP_NOFS);
2642 if (!old)
2643 goto out_free_path;
2645 offset = max(new->file_pos, key.offset);
2646 end = min(new->file_pos + new->len, key.offset + num_bytes);
2648 old->bytenr = disk_bytenr;
2649 old->extent_offset = extent_offset;
2650 old->offset = offset - key.offset;
2651 old->len = end - offset;
2652 old->new = new;
2653 old->count = 0;
2654 list_add_tail(&old->list, &new->head);
2655 next:
2656 path->slots[0]++;
2657 cond_resched();
2660 btrfs_free_path(path);
2661 atomic_inc(&root->fs_info->defrag_running);
2663 return new;
2665 out_free_path:
2666 btrfs_free_path(path);
2667 out_kfree:
2668 free_sa_defrag_extent(new);
2669 return NULL;
2672 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2673 u64 start, u64 len)
2675 struct btrfs_block_group_cache *cache;
2677 cache = btrfs_lookup_block_group(root->fs_info, start);
2678 ASSERT(cache);
2680 spin_lock(&cache->lock);
2681 cache->delalloc_bytes -= len;
2682 spin_unlock(&cache->lock);
2684 btrfs_put_block_group(cache);
2687 /* as ordered data IO finishes, this gets called so we can finish
2688 * an ordered extent if the range of bytes in the file it covers are
2689 * fully written.
2691 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2693 struct inode *inode = ordered_extent->inode;
2694 struct btrfs_root *root = BTRFS_I(inode)->root;
2695 struct btrfs_trans_handle *trans = NULL;
2696 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2697 struct extent_state *cached_state = NULL;
2698 struct new_sa_defrag_extent *new = NULL;
2699 int compress_type = 0;
2700 int ret = 0;
2701 u64 logical_len = ordered_extent->len;
2702 bool nolock;
2703 bool truncated = false;
2705 nolock = btrfs_is_free_space_inode(inode);
2707 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2708 ret = -EIO;
2709 goto out;
2712 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2713 ordered_extent->file_offset +
2714 ordered_extent->len - 1);
2716 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2717 truncated = true;
2718 logical_len = ordered_extent->truncated_len;
2719 /* Truncated the entire extent, don't bother adding */
2720 if (!logical_len)
2721 goto out;
2724 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2725 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2726 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2727 if (nolock)
2728 trans = btrfs_join_transaction_nolock(root);
2729 else
2730 trans = btrfs_join_transaction(root);
2731 if (IS_ERR(trans)) {
2732 ret = PTR_ERR(trans);
2733 trans = NULL;
2734 goto out;
2736 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2737 ret = btrfs_update_inode_fallback(trans, root, inode);
2738 if (ret) /* -ENOMEM or corruption */
2739 btrfs_abort_transaction(trans, root, ret);
2740 goto out;
2743 lock_extent_bits(io_tree, ordered_extent->file_offset,
2744 ordered_extent->file_offset + ordered_extent->len - 1,
2745 0, &cached_state);
2747 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2748 ordered_extent->file_offset + ordered_extent->len - 1,
2749 EXTENT_DEFRAG, 1, cached_state);
2750 if (ret) {
2751 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2752 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2753 /* the inode is shared */
2754 new = record_old_file_extents(inode, ordered_extent);
2756 clear_extent_bit(io_tree, ordered_extent->file_offset,
2757 ordered_extent->file_offset + ordered_extent->len - 1,
2758 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2761 if (nolock)
2762 trans = btrfs_join_transaction_nolock(root);
2763 else
2764 trans = btrfs_join_transaction(root);
2765 if (IS_ERR(trans)) {
2766 ret = PTR_ERR(trans);
2767 trans = NULL;
2768 goto out_unlock;
2771 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2773 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2774 compress_type = ordered_extent->compress_type;
2775 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2776 BUG_ON(compress_type);
2777 ret = btrfs_mark_extent_written(trans, inode,
2778 ordered_extent->file_offset,
2779 ordered_extent->file_offset +
2780 logical_len);
2781 } else {
2782 BUG_ON(root == root->fs_info->tree_root);
2783 ret = insert_reserved_file_extent(trans, inode,
2784 ordered_extent->file_offset,
2785 ordered_extent->start,
2786 ordered_extent->disk_len,
2787 logical_len, logical_len,
2788 compress_type, 0, 0,
2789 BTRFS_FILE_EXTENT_REG);
2790 if (!ret)
2791 btrfs_release_delalloc_bytes(root,
2792 ordered_extent->start,
2793 ordered_extent->disk_len);
2795 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2796 ordered_extent->file_offset, ordered_extent->len,
2797 trans->transid);
2798 if (ret < 0) {
2799 btrfs_abort_transaction(trans, root, ret);
2800 goto out_unlock;
2803 add_pending_csums(trans, inode, ordered_extent->file_offset,
2804 &ordered_extent->list);
2806 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2807 ret = btrfs_update_inode_fallback(trans, root, inode);
2808 if (ret) { /* -ENOMEM or corruption */
2809 btrfs_abort_transaction(trans, root, ret);
2810 goto out_unlock;
2812 ret = 0;
2813 out_unlock:
2814 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2815 ordered_extent->file_offset +
2816 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2817 out:
2818 if (root != root->fs_info->tree_root)
2819 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2820 if (trans)
2821 btrfs_end_transaction(trans, root);
2823 if (ret || truncated) {
2824 u64 start, end;
2826 if (truncated)
2827 start = ordered_extent->file_offset + logical_len;
2828 else
2829 start = ordered_extent->file_offset;
2830 end = ordered_extent->file_offset + ordered_extent->len - 1;
2831 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2833 /* Drop the cache for the part of the extent we didn't write. */
2834 btrfs_drop_extent_cache(inode, start, end, 0);
2837 * If the ordered extent had an IOERR or something else went
2838 * wrong we need to return the space for this ordered extent
2839 * back to the allocator. We only free the extent in the
2840 * truncated case if we didn't write out the extent at all.
2842 if ((ret || !logical_len) &&
2843 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2844 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2845 btrfs_free_reserved_extent(root, ordered_extent->start,
2846 ordered_extent->disk_len, 1);
2851 * This needs to be done to make sure anybody waiting knows we are done
2852 * updating everything for this ordered extent.
2854 btrfs_remove_ordered_extent(inode, ordered_extent);
2856 /* for snapshot-aware defrag */
2857 if (new) {
2858 if (ret) {
2859 free_sa_defrag_extent(new);
2860 atomic_dec(&root->fs_info->defrag_running);
2861 } else {
2862 relink_file_extents(new);
2866 /* once for us */
2867 btrfs_put_ordered_extent(ordered_extent);
2868 /* once for the tree */
2869 btrfs_put_ordered_extent(ordered_extent);
2871 return ret;
2874 static void finish_ordered_fn(struct btrfs_work *work)
2876 struct btrfs_ordered_extent *ordered_extent;
2877 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2878 btrfs_finish_ordered_io(ordered_extent);
2881 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2882 struct extent_state *state, int uptodate)
2884 struct inode *inode = page->mapping->host;
2885 struct btrfs_root *root = BTRFS_I(inode)->root;
2886 struct btrfs_ordered_extent *ordered_extent = NULL;
2887 struct btrfs_workqueue *wq;
2888 btrfs_work_func_t func;
2890 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2892 ClearPagePrivate2(page);
2893 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2894 end - start + 1, uptodate))
2895 return 0;
2897 if (btrfs_is_free_space_inode(inode)) {
2898 wq = root->fs_info->endio_freespace_worker;
2899 func = btrfs_freespace_write_helper;
2900 } else {
2901 wq = root->fs_info->endio_write_workers;
2902 func = btrfs_endio_write_helper;
2905 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2906 NULL);
2907 btrfs_queue_work(wq, &ordered_extent->work);
2909 return 0;
2912 static int __readpage_endio_check(struct inode *inode,
2913 struct btrfs_io_bio *io_bio,
2914 int icsum, struct page *page,
2915 int pgoff, u64 start, size_t len)
2917 char *kaddr;
2918 u32 csum_expected;
2919 u32 csum = ~(u32)0;
2920 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2921 DEFAULT_RATELIMIT_BURST);
2923 csum_expected = *(((u32 *)io_bio->csum) + icsum);
2925 kaddr = kmap_atomic(page);
2926 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
2927 btrfs_csum_final(csum, (char *)&csum);
2928 if (csum != csum_expected)
2929 goto zeroit;
2931 kunmap_atomic(kaddr);
2932 return 0;
2933 zeroit:
2934 if (__ratelimit(&_rs))
2935 btrfs_info(BTRFS_I(inode)->root->fs_info,
2936 "csum failed ino %llu off %llu csum %u expected csum %u",
2937 btrfs_ino(inode), start, csum, csum_expected);
2938 memset(kaddr + pgoff, 1, len);
2939 flush_dcache_page(page);
2940 kunmap_atomic(kaddr);
2941 if (csum_expected == 0)
2942 return 0;
2943 return -EIO;
2947 * when reads are done, we need to check csums to verify the data is correct
2948 * if there's a match, we allow the bio to finish. If not, the code in
2949 * extent_io.c will try to find good copies for us.
2951 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2952 u64 phy_offset, struct page *page,
2953 u64 start, u64 end, int mirror)
2955 size_t offset = start - page_offset(page);
2956 struct inode *inode = page->mapping->host;
2957 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2958 struct btrfs_root *root = BTRFS_I(inode)->root;
2960 if (PageChecked(page)) {
2961 ClearPageChecked(page);
2962 return 0;
2965 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2966 return 0;
2968 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2969 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2970 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2971 GFP_NOFS);
2972 return 0;
2975 phy_offset >>= inode->i_sb->s_blocksize_bits;
2976 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
2977 start, (size_t)(end - start + 1));
2980 struct delayed_iput {
2981 struct list_head list;
2982 struct inode *inode;
2985 /* JDM: If this is fs-wide, why can't we add a pointer to
2986 * btrfs_inode instead and avoid the allocation? */
2987 void btrfs_add_delayed_iput(struct inode *inode)
2989 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2990 struct delayed_iput *delayed;
2992 if (atomic_add_unless(&inode->i_count, -1, 1))
2993 return;
2995 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2996 delayed->inode = inode;
2998 spin_lock(&fs_info->delayed_iput_lock);
2999 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3000 spin_unlock(&fs_info->delayed_iput_lock);
3003 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3005 LIST_HEAD(list);
3006 struct btrfs_fs_info *fs_info = root->fs_info;
3007 struct delayed_iput *delayed;
3008 int empty;
3010 spin_lock(&fs_info->delayed_iput_lock);
3011 empty = list_empty(&fs_info->delayed_iputs);
3012 spin_unlock(&fs_info->delayed_iput_lock);
3013 if (empty)
3014 return;
3016 spin_lock(&fs_info->delayed_iput_lock);
3017 list_splice_init(&fs_info->delayed_iputs, &list);
3018 spin_unlock(&fs_info->delayed_iput_lock);
3020 while (!list_empty(&list)) {
3021 delayed = list_entry(list.next, struct delayed_iput, list);
3022 list_del(&delayed->list);
3023 iput(delayed->inode);
3024 kfree(delayed);
3029 * This is called in transaction commit time. If there are no orphan
3030 * files in the subvolume, it removes orphan item and frees block_rsv
3031 * structure.
3033 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3034 struct btrfs_root *root)
3036 struct btrfs_block_rsv *block_rsv;
3037 int ret;
3039 if (atomic_read(&root->orphan_inodes) ||
3040 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3041 return;
3043 spin_lock(&root->orphan_lock);
3044 if (atomic_read(&root->orphan_inodes)) {
3045 spin_unlock(&root->orphan_lock);
3046 return;
3049 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3050 spin_unlock(&root->orphan_lock);
3051 return;
3054 block_rsv = root->orphan_block_rsv;
3055 root->orphan_block_rsv = NULL;
3056 spin_unlock(&root->orphan_lock);
3058 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3059 btrfs_root_refs(&root->root_item) > 0) {
3060 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3061 root->root_key.objectid);
3062 if (ret)
3063 btrfs_abort_transaction(trans, root, ret);
3064 else
3065 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3066 &root->state);
3069 if (block_rsv) {
3070 WARN_ON(block_rsv->size > 0);
3071 btrfs_free_block_rsv(root, block_rsv);
3076 * This creates an orphan entry for the given inode in case something goes
3077 * wrong in the middle of an unlink/truncate.
3079 * NOTE: caller of this function should reserve 5 units of metadata for
3080 * this function.
3082 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3084 struct btrfs_root *root = BTRFS_I(inode)->root;
3085 struct btrfs_block_rsv *block_rsv = NULL;
3086 int reserve = 0;
3087 int insert = 0;
3088 int ret;
3090 if (!root->orphan_block_rsv) {
3091 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3092 if (!block_rsv)
3093 return -ENOMEM;
3096 spin_lock(&root->orphan_lock);
3097 if (!root->orphan_block_rsv) {
3098 root->orphan_block_rsv = block_rsv;
3099 } else if (block_rsv) {
3100 btrfs_free_block_rsv(root, block_rsv);
3101 block_rsv = NULL;
3104 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3105 &BTRFS_I(inode)->runtime_flags)) {
3106 #if 0
3108 * For proper ENOSPC handling, we should do orphan
3109 * cleanup when mounting. But this introduces backward
3110 * compatibility issue.
3112 if (!xchg(&root->orphan_item_inserted, 1))
3113 insert = 2;
3114 else
3115 insert = 1;
3116 #endif
3117 insert = 1;
3118 atomic_inc(&root->orphan_inodes);
3121 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3122 &BTRFS_I(inode)->runtime_flags))
3123 reserve = 1;
3124 spin_unlock(&root->orphan_lock);
3126 /* grab metadata reservation from transaction handle */
3127 if (reserve) {
3128 ret = btrfs_orphan_reserve_metadata(trans, inode);
3129 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3132 /* insert an orphan item to track this unlinked/truncated file */
3133 if (insert >= 1) {
3134 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3135 if (ret) {
3136 atomic_dec(&root->orphan_inodes);
3137 if (reserve) {
3138 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3139 &BTRFS_I(inode)->runtime_flags);
3140 btrfs_orphan_release_metadata(inode);
3142 if (ret != -EEXIST) {
3143 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3144 &BTRFS_I(inode)->runtime_flags);
3145 btrfs_abort_transaction(trans, root, ret);
3146 return ret;
3149 ret = 0;
3152 /* insert an orphan item to track subvolume contains orphan files */
3153 if (insert >= 2) {
3154 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3155 root->root_key.objectid);
3156 if (ret && ret != -EEXIST) {
3157 btrfs_abort_transaction(trans, root, ret);
3158 return ret;
3161 return 0;
3165 * We have done the truncate/delete so we can go ahead and remove the orphan
3166 * item for this particular inode.
3168 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3169 struct inode *inode)
3171 struct btrfs_root *root = BTRFS_I(inode)->root;
3172 int delete_item = 0;
3173 int release_rsv = 0;
3174 int ret = 0;
3176 spin_lock(&root->orphan_lock);
3177 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3178 &BTRFS_I(inode)->runtime_flags))
3179 delete_item = 1;
3181 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3182 &BTRFS_I(inode)->runtime_flags))
3183 release_rsv = 1;
3184 spin_unlock(&root->orphan_lock);
3186 if (delete_item) {
3187 atomic_dec(&root->orphan_inodes);
3188 if (trans)
3189 ret = btrfs_del_orphan_item(trans, root,
3190 btrfs_ino(inode));
3193 if (release_rsv)
3194 btrfs_orphan_release_metadata(inode);
3196 return ret;
3200 * this cleans up any orphans that may be left on the list from the last use
3201 * of this root.
3203 int btrfs_orphan_cleanup(struct btrfs_root *root)
3205 struct btrfs_path *path;
3206 struct extent_buffer *leaf;
3207 struct btrfs_key key, found_key;
3208 struct btrfs_trans_handle *trans;
3209 struct inode *inode;
3210 u64 last_objectid = 0;
3211 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3213 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3214 return 0;
3216 path = btrfs_alloc_path();
3217 if (!path) {
3218 ret = -ENOMEM;
3219 goto out;
3221 path->reada = -1;
3223 key.objectid = BTRFS_ORPHAN_OBJECTID;
3224 key.type = BTRFS_ORPHAN_ITEM_KEY;
3225 key.offset = (u64)-1;
3227 while (1) {
3228 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3229 if (ret < 0)
3230 goto out;
3233 * if ret == 0 means we found what we were searching for, which
3234 * is weird, but possible, so only screw with path if we didn't
3235 * find the key and see if we have stuff that matches
3237 if (ret > 0) {
3238 ret = 0;
3239 if (path->slots[0] == 0)
3240 break;
3241 path->slots[0]--;
3244 /* pull out the item */
3245 leaf = path->nodes[0];
3246 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3248 /* make sure the item matches what we want */
3249 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3250 break;
3251 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3252 break;
3254 /* release the path since we're done with it */
3255 btrfs_release_path(path);
3258 * this is where we are basically btrfs_lookup, without the
3259 * crossing root thing. we store the inode number in the
3260 * offset of the orphan item.
3263 if (found_key.offset == last_objectid) {
3264 btrfs_err(root->fs_info,
3265 "Error removing orphan entry, stopping orphan cleanup");
3266 ret = -EINVAL;
3267 goto out;
3270 last_objectid = found_key.offset;
3272 found_key.objectid = found_key.offset;
3273 found_key.type = BTRFS_INODE_ITEM_KEY;
3274 found_key.offset = 0;
3275 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3276 ret = PTR_ERR_OR_ZERO(inode);
3277 if (ret && ret != -ESTALE)
3278 goto out;
3280 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3281 struct btrfs_root *dead_root;
3282 struct btrfs_fs_info *fs_info = root->fs_info;
3283 int is_dead_root = 0;
3286 * this is an orphan in the tree root. Currently these
3287 * could come from 2 sources:
3288 * a) a snapshot deletion in progress
3289 * b) a free space cache inode
3290 * We need to distinguish those two, as the snapshot
3291 * orphan must not get deleted.
3292 * find_dead_roots already ran before us, so if this
3293 * is a snapshot deletion, we should find the root
3294 * in the dead_roots list
3296 spin_lock(&fs_info->trans_lock);
3297 list_for_each_entry(dead_root, &fs_info->dead_roots,
3298 root_list) {
3299 if (dead_root->root_key.objectid ==
3300 found_key.objectid) {
3301 is_dead_root = 1;
3302 break;
3305 spin_unlock(&fs_info->trans_lock);
3306 if (is_dead_root) {
3307 /* prevent this orphan from being found again */
3308 key.offset = found_key.objectid - 1;
3309 continue;
3313 * Inode is already gone but the orphan item is still there,
3314 * kill the orphan item.
3316 if (ret == -ESTALE) {
3317 trans = btrfs_start_transaction(root, 1);
3318 if (IS_ERR(trans)) {
3319 ret = PTR_ERR(trans);
3320 goto out;
3322 btrfs_debug(root->fs_info, "auto deleting %Lu",
3323 found_key.objectid);
3324 ret = btrfs_del_orphan_item(trans, root,
3325 found_key.objectid);
3326 btrfs_end_transaction(trans, root);
3327 if (ret)
3328 goto out;
3329 continue;
3333 * add this inode to the orphan list so btrfs_orphan_del does
3334 * the proper thing when we hit it
3336 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3337 &BTRFS_I(inode)->runtime_flags);
3338 atomic_inc(&root->orphan_inodes);
3340 /* if we have links, this was a truncate, lets do that */
3341 if (inode->i_nlink) {
3342 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3343 iput(inode);
3344 continue;
3346 nr_truncate++;
3348 /* 1 for the orphan item deletion. */
3349 trans = btrfs_start_transaction(root, 1);
3350 if (IS_ERR(trans)) {
3351 iput(inode);
3352 ret = PTR_ERR(trans);
3353 goto out;
3355 ret = btrfs_orphan_add(trans, inode);
3356 btrfs_end_transaction(trans, root);
3357 if (ret) {
3358 iput(inode);
3359 goto out;
3362 ret = btrfs_truncate(inode);
3363 if (ret)
3364 btrfs_orphan_del(NULL, inode);
3365 } else {
3366 nr_unlink++;
3369 /* this will do delete_inode and everything for us */
3370 iput(inode);
3371 if (ret)
3372 goto out;
3374 /* release the path since we're done with it */
3375 btrfs_release_path(path);
3377 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3379 if (root->orphan_block_rsv)
3380 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3381 (u64)-1);
3383 if (root->orphan_block_rsv ||
3384 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3385 trans = btrfs_join_transaction(root);
3386 if (!IS_ERR(trans))
3387 btrfs_end_transaction(trans, root);
3390 if (nr_unlink)
3391 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3392 if (nr_truncate)
3393 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3395 out:
3396 if (ret)
3397 btrfs_crit(root->fs_info,
3398 "could not do orphan cleanup %d", ret);
3399 btrfs_free_path(path);
3400 return ret;
3404 * very simple check to peek ahead in the leaf looking for xattrs. If we
3405 * don't find any xattrs, we know there can't be any acls.
3407 * slot is the slot the inode is in, objectid is the objectid of the inode
3409 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3410 int slot, u64 objectid,
3411 int *first_xattr_slot)
3413 u32 nritems = btrfs_header_nritems(leaf);
3414 struct btrfs_key found_key;
3415 static u64 xattr_access = 0;
3416 static u64 xattr_default = 0;
3417 int scanned = 0;
3419 if (!xattr_access) {
3420 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3421 strlen(POSIX_ACL_XATTR_ACCESS));
3422 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3423 strlen(POSIX_ACL_XATTR_DEFAULT));
3426 slot++;
3427 *first_xattr_slot = -1;
3428 while (slot < nritems) {
3429 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3431 /* we found a different objectid, there must not be acls */
3432 if (found_key.objectid != objectid)
3433 return 0;
3435 /* we found an xattr, assume we've got an acl */
3436 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3437 if (*first_xattr_slot == -1)
3438 *first_xattr_slot = slot;
3439 if (found_key.offset == xattr_access ||
3440 found_key.offset == xattr_default)
3441 return 1;
3445 * we found a key greater than an xattr key, there can't
3446 * be any acls later on
3448 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3449 return 0;
3451 slot++;
3452 scanned++;
3455 * it goes inode, inode backrefs, xattrs, extents,
3456 * so if there are a ton of hard links to an inode there can
3457 * be a lot of backrefs. Don't waste time searching too hard,
3458 * this is just an optimization
3460 if (scanned >= 8)
3461 break;
3463 /* we hit the end of the leaf before we found an xattr or
3464 * something larger than an xattr. We have to assume the inode
3465 * has acls
3467 if (*first_xattr_slot == -1)
3468 *first_xattr_slot = slot;
3469 return 1;
3473 * read an inode from the btree into the in-memory inode
3475 static void btrfs_read_locked_inode(struct inode *inode)
3477 struct btrfs_path *path;
3478 struct extent_buffer *leaf;
3479 struct btrfs_inode_item *inode_item;
3480 struct btrfs_timespec *tspec;
3481 struct btrfs_root *root = BTRFS_I(inode)->root;
3482 struct btrfs_key location;
3483 unsigned long ptr;
3484 int maybe_acls;
3485 u32 rdev;
3486 int ret;
3487 bool filled = false;
3488 int first_xattr_slot;
3490 ret = btrfs_fill_inode(inode, &rdev);
3491 if (!ret)
3492 filled = true;
3494 path = btrfs_alloc_path();
3495 if (!path)
3496 goto make_bad;
3498 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3500 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3501 if (ret)
3502 goto make_bad;
3504 leaf = path->nodes[0];
3506 if (filled)
3507 goto cache_index;
3509 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3510 struct btrfs_inode_item);
3511 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3512 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3513 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3514 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3515 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3517 tspec = btrfs_inode_atime(inode_item);
3518 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3519 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3521 tspec = btrfs_inode_mtime(inode_item);
3522 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3523 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3525 tspec = btrfs_inode_ctime(inode_item);
3526 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3527 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3529 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3530 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3531 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3534 * If we were modified in the current generation and evicted from memory
3535 * and then re-read we need to do a full sync since we don't have any
3536 * idea about which extents were modified before we were evicted from
3537 * cache.
3539 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3540 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3541 &BTRFS_I(inode)->runtime_flags);
3543 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3544 inode->i_generation = BTRFS_I(inode)->generation;
3545 inode->i_rdev = 0;
3546 rdev = btrfs_inode_rdev(leaf, inode_item);
3548 BTRFS_I(inode)->index_cnt = (u64)-1;
3549 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3551 cache_index:
3552 path->slots[0]++;
3553 if (inode->i_nlink != 1 ||
3554 path->slots[0] >= btrfs_header_nritems(leaf))
3555 goto cache_acl;
3557 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3558 if (location.objectid != btrfs_ino(inode))
3559 goto cache_acl;
3561 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3562 if (location.type == BTRFS_INODE_REF_KEY) {
3563 struct btrfs_inode_ref *ref;
3565 ref = (struct btrfs_inode_ref *)ptr;
3566 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3567 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3568 struct btrfs_inode_extref *extref;
3570 extref = (struct btrfs_inode_extref *)ptr;
3571 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3572 extref);
3574 cache_acl:
3576 * try to precache a NULL acl entry for files that don't have
3577 * any xattrs or acls
3579 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3580 btrfs_ino(inode), &first_xattr_slot);
3581 if (first_xattr_slot != -1) {
3582 path->slots[0] = first_xattr_slot;
3583 ret = btrfs_load_inode_props(inode, path);
3584 if (ret)
3585 btrfs_err(root->fs_info,
3586 "error loading props for ino %llu (root %llu): %d",
3587 btrfs_ino(inode),
3588 root->root_key.objectid, ret);
3590 btrfs_free_path(path);
3592 if (!maybe_acls)
3593 cache_no_acl(inode);
3595 switch (inode->i_mode & S_IFMT) {
3596 case S_IFREG:
3597 inode->i_mapping->a_ops = &btrfs_aops;
3598 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3599 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3600 inode->i_fop = &btrfs_file_operations;
3601 inode->i_op = &btrfs_file_inode_operations;
3602 break;
3603 case S_IFDIR:
3604 inode->i_fop = &btrfs_dir_file_operations;
3605 if (root == root->fs_info->tree_root)
3606 inode->i_op = &btrfs_dir_ro_inode_operations;
3607 else
3608 inode->i_op = &btrfs_dir_inode_operations;
3609 break;
3610 case S_IFLNK:
3611 inode->i_op = &btrfs_symlink_inode_operations;
3612 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3613 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3614 break;
3615 default:
3616 inode->i_op = &btrfs_special_inode_operations;
3617 init_special_inode(inode, inode->i_mode, rdev);
3618 break;
3621 btrfs_update_iflags(inode);
3622 return;
3624 make_bad:
3625 btrfs_free_path(path);
3626 make_bad_inode(inode);
3630 * given a leaf and an inode, copy the inode fields into the leaf
3632 static void fill_inode_item(struct btrfs_trans_handle *trans,
3633 struct extent_buffer *leaf,
3634 struct btrfs_inode_item *item,
3635 struct inode *inode)
3637 struct btrfs_map_token token;
3639 btrfs_init_map_token(&token);
3641 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3642 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3643 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3644 &token);
3645 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3646 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3648 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3649 inode->i_atime.tv_sec, &token);
3650 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3651 inode->i_atime.tv_nsec, &token);
3653 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3654 inode->i_mtime.tv_sec, &token);
3655 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3656 inode->i_mtime.tv_nsec, &token);
3658 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3659 inode->i_ctime.tv_sec, &token);
3660 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3661 inode->i_ctime.tv_nsec, &token);
3663 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3664 &token);
3665 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3666 &token);
3667 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3668 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3669 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3670 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3671 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3675 * copy everything in the in-memory inode into the btree.
3677 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3678 struct btrfs_root *root, struct inode *inode)
3680 struct btrfs_inode_item *inode_item;
3681 struct btrfs_path *path;
3682 struct extent_buffer *leaf;
3683 int ret;
3685 path = btrfs_alloc_path();
3686 if (!path)
3687 return -ENOMEM;
3689 path->leave_spinning = 1;
3690 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3692 if (ret) {
3693 if (ret > 0)
3694 ret = -ENOENT;
3695 goto failed;
3698 leaf = path->nodes[0];
3699 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3700 struct btrfs_inode_item);
3702 fill_inode_item(trans, leaf, inode_item, inode);
3703 btrfs_mark_buffer_dirty(leaf);
3704 btrfs_set_inode_last_trans(trans, inode);
3705 ret = 0;
3706 failed:
3707 btrfs_free_path(path);
3708 return ret;
3712 * copy everything in the in-memory inode into the btree.
3714 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3715 struct btrfs_root *root, struct inode *inode)
3717 int ret;
3720 * If the inode is a free space inode, we can deadlock during commit
3721 * if we put it into the delayed code.
3723 * The data relocation inode should also be directly updated
3724 * without delay
3726 if (!btrfs_is_free_space_inode(inode)
3727 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3728 && !root->fs_info->log_root_recovering) {
3729 btrfs_update_root_times(trans, root);
3731 ret = btrfs_delayed_update_inode(trans, root, inode);
3732 if (!ret)
3733 btrfs_set_inode_last_trans(trans, inode);
3734 return ret;
3737 return btrfs_update_inode_item(trans, root, inode);
3740 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3741 struct btrfs_root *root,
3742 struct inode *inode)
3744 int ret;
3746 ret = btrfs_update_inode(trans, root, inode);
3747 if (ret == -ENOSPC)
3748 return btrfs_update_inode_item(trans, root, inode);
3749 return ret;
3753 * unlink helper that gets used here in inode.c and in the tree logging
3754 * recovery code. It remove a link in a directory with a given name, and
3755 * also drops the back refs in the inode to the directory
3757 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3758 struct btrfs_root *root,
3759 struct inode *dir, struct inode *inode,
3760 const char *name, int name_len)
3762 struct btrfs_path *path;
3763 int ret = 0;
3764 struct extent_buffer *leaf;
3765 struct btrfs_dir_item *di;
3766 struct btrfs_key key;
3767 u64 index;
3768 u64 ino = btrfs_ino(inode);
3769 u64 dir_ino = btrfs_ino(dir);
3771 path = btrfs_alloc_path();
3772 if (!path) {
3773 ret = -ENOMEM;
3774 goto out;
3777 path->leave_spinning = 1;
3778 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3779 name, name_len, -1);
3780 if (IS_ERR(di)) {
3781 ret = PTR_ERR(di);
3782 goto err;
3784 if (!di) {
3785 ret = -ENOENT;
3786 goto err;
3788 leaf = path->nodes[0];
3789 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3790 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3791 if (ret)
3792 goto err;
3793 btrfs_release_path(path);
3796 * If we don't have dir index, we have to get it by looking up
3797 * the inode ref, since we get the inode ref, remove it directly,
3798 * it is unnecessary to do delayed deletion.
3800 * But if we have dir index, needn't search inode ref to get it.
3801 * Since the inode ref is close to the inode item, it is better
3802 * that we delay to delete it, and just do this deletion when
3803 * we update the inode item.
3805 if (BTRFS_I(inode)->dir_index) {
3806 ret = btrfs_delayed_delete_inode_ref(inode);
3807 if (!ret) {
3808 index = BTRFS_I(inode)->dir_index;
3809 goto skip_backref;
3813 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3814 dir_ino, &index);
3815 if (ret) {
3816 btrfs_info(root->fs_info,
3817 "failed to delete reference to %.*s, inode %llu parent %llu",
3818 name_len, name, ino, dir_ino);
3819 btrfs_abort_transaction(trans, root, ret);
3820 goto err;
3822 skip_backref:
3823 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3824 if (ret) {
3825 btrfs_abort_transaction(trans, root, ret);
3826 goto err;
3829 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3830 inode, dir_ino);
3831 if (ret != 0 && ret != -ENOENT) {
3832 btrfs_abort_transaction(trans, root, ret);
3833 goto err;
3836 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3837 dir, index);
3838 if (ret == -ENOENT)
3839 ret = 0;
3840 else if (ret)
3841 btrfs_abort_transaction(trans, root, ret);
3842 err:
3843 btrfs_free_path(path);
3844 if (ret)
3845 goto out;
3847 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3848 inode_inc_iversion(inode);
3849 inode_inc_iversion(dir);
3850 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3851 ret = btrfs_update_inode(trans, root, dir);
3852 out:
3853 return ret;
3856 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3857 struct btrfs_root *root,
3858 struct inode *dir, struct inode *inode,
3859 const char *name, int name_len)
3861 int ret;
3862 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3863 if (!ret) {
3864 drop_nlink(inode);
3865 ret = btrfs_update_inode(trans, root, inode);
3867 return ret;
3871 * helper to start transaction for unlink and rmdir.
3873 * unlink and rmdir are special in btrfs, they do not always free space, so
3874 * if we cannot make our reservations the normal way try and see if there is
3875 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3876 * allow the unlink to occur.
3878 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3880 struct btrfs_trans_handle *trans;
3881 struct btrfs_root *root = BTRFS_I(dir)->root;
3882 int ret;
3885 * 1 for the possible orphan item
3886 * 1 for the dir item
3887 * 1 for the dir index
3888 * 1 for the inode ref
3889 * 1 for the inode
3891 trans = btrfs_start_transaction(root, 5);
3892 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3893 return trans;
3895 if (PTR_ERR(trans) == -ENOSPC) {
3896 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3898 trans = btrfs_start_transaction(root, 0);
3899 if (IS_ERR(trans))
3900 return trans;
3901 ret = btrfs_cond_migrate_bytes(root->fs_info,
3902 &root->fs_info->trans_block_rsv,
3903 num_bytes, 5);
3904 if (ret) {
3905 btrfs_end_transaction(trans, root);
3906 return ERR_PTR(ret);
3908 trans->block_rsv = &root->fs_info->trans_block_rsv;
3909 trans->bytes_reserved = num_bytes;
3911 return trans;
3914 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3916 struct btrfs_root *root = BTRFS_I(dir)->root;
3917 struct btrfs_trans_handle *trans;
3918 struct inode *inode = dentry->d_inode;
3919 int ret;
3921 trans = __unlink_start_trans(dir);
3922 if (IS_ERR(trans))
3923 return PTR_ERR(trans);
3925 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3927 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3928 dentry->d_name.name, dentry->d_name.len);
3929 if (ret)
3930 goto out;
3932 if (inode->i_nlink == 0) {
3933 ret = btrfs_orphan_add(trans, inode);
3934 if (ret)
3935 goto out;
3938 out:
3939 btrfs_end_transaction(trans, root);
3940 btrfs_btree_balance_dirty(root);
3941 return ret;
3944 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3945 struct btrfs_root *root,
3946 struct inode *dir, u64 objectid,
3947 const char *name, int name_len)
3949 struct btrfs_path *path;
3950 struct extent_buffer *leaf;
3951 struct btrfs_dir_item *di;
3952 struct btrfs_key key;
3953 u64 index;
3954 int ret;
3955 u64 dir_ino = btrfs_ino(dir);
3957 path = btrfs_alloc_path();
3958 if (!path)
3959 return -ENOMEM;
3961 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3962 name, name_len, -1);
3963 if (IS_ERR_OR_NULL(di)) {
3964 if (!di)
3965 ret = -ENOENT;
3966 else
3967 ret = PTR_ERR(di);
3968 goto out;
3971 leaf = path->nodes[0];
3972 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3973 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3974 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3975 if (ret) {
3976 btrfs_abort_transaction(trans, root, ret);
3977 goto out;
3979 btrfs_release_path(path);
3981 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3982 objectid, root->root_key.objectid,
3983 dir_ino, &index, name, name_len);
3984 if (ret < 0) {
3985 if (ret != -ENOENT) {
3986 btrfs_abort_transaction(trans, root, ret);
3987 goto out;
3989 di = btrfs_search_dir_index_item(root, path, dir_ino,
3990 name, name_len);
3991 if (IS_ERR_OR_NULL(di)) {
3992 if (!di)
3993 ret = -ENOENT;
3994 else
3995 ret = PTR_ERR(di);
3996 btrfs_abort_transaction(trans, root, ret);
3997 goto out;
4000 leaf = path->nodes[0];
4001 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4002 btrfs_release_path(path);
4003 index = key.offset;
4005 btrfs_release_path(path);
4007 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4008 if (ret) {
4009 btrfs_abort_transaction(trans, root, ret);
4010 goto out;
4013 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4014 inode_inc_iversion(dir);
4015 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4016 ret = btrfs_update_inode_fallback(trans, root, dir);
4017 if (ret)
4018 btrfs_abort_transaction(trans, root, ret);
4019 out:
4020 btrfs_free_path(path);
4021 return ret;
4024 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4026 struct inode *inode = dentry->d_inode;
4027 int err = 0;
4028 struct btrfs_root *root = BTRFS_I(dir)->root;
4029 struct btrfs_trans_handle *trans;
4031 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4032 return -ENOTEMPTY;
4033 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4034 return -EPERM;
4036 trans = __unlink_start_trans(dir);
4037 if (IS_ERR(trans))
4038 return PTR_ERR(trans);
4040 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4041 err = btrfs_unlink_subvol(trans, root, dir,
4042 BTRFS_I(inode)->location.objectid,
4043 dentry->d_name.name,
4044 dentry->d_name.len);
4045 goto out;
4048 err = btrfs_orphan_add(trans, inode);
4049 if (err)
4050 goto out;
4052 /* now the directory is empty */
4053 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4054 dentry->d_name.name, dentry->d_name.len);
4055 if (!err)
4056 btrfs_i_size_write(inode, 0);
4057 out:
4058 btrfs_end_transaction(trans, root);
4059 btrfs_btree_balance_dirty(root);
4061 return err;
4065 * this can truncate away extent items, csum items and directory items.
4066 * It starts at a high offset and removes keys until it can't find
4067 * any higher than new_size
4069 * csum items that cross the new i_size are truncated to the new size
4070 * as well.
4072 * min_type is the minimum key type to truncate down to. If set to 0, this
4073 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4075 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4076 struct btrfs_root *root,
4077 struct inode *inode,
4078 u64 new_size, u32 min_type)
4080 struct btrfs_path *path;
4081 struct extent_buffer *leaf;
4082 struct btrfs_file_extent_item *fi;
4083 struct btrfs_key key;
4084 struct btrfs_key found_key;
4085 u64 extent_start = 0;
4086 u64 extent_num_bytes = 0;
4087 u64 extent_offset = 0;
4088 u64 item_end = 0;
4089 u64 last_size = (u64)-1;
4090 u32 found_type = (u8)-1;
4091 int found_extent;
4092 int del_item;
4093 int pending_del_nr = 0;
4094 int pending_del_slot = 0;
4095 int extent_type = -1;
4096 int ret;
4097 int err = 0;
4098 u64 ino = btrfs_ino(inode);
4100 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4102 path = btrfs_alloc_path();
4103 if (!path)
4104 return -ENOMEM;
4105 path->reada = -1;
4108 * We want to drop from the next block forward in case this new size is
4109 * not block aligned since we will be keeping the last block of the
4110 * extent just the way it is.
4112 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4113 root == root->fs_info->tree_root)
4114 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4115 root->sectorsize), (u64)-1, 0);
4118 * This function is also used to drop the items in the log tree before
4119 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4120 * it is used to drop the loged items. So we shouldn't kill the delayed
4121 * items.
4123 if (min_type == 0 && root == BTRFS_I(inode)->root)
4124 btrfs_kill_delayed_inode_items(inode);
4126 key.objectid = ino;
4127 key.offset = (u64)-1;
4128 key.type = (u8)-1;
4130 search_again:
4131 path->leave_spinning = 1;
4132 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4133 if (ret < 0) {
4134 err = ret;
4135 goto out;
4138 if (ret > 0) {
4139 /* there are no items in the tree for us to truncate, we're
4140 * done
4142 if (path->slots[0] == 0)
4143 goto out;
4144 path->slots[0]--;
4147 while (1) {
4148 fi = NULL;
4149 leaf = path->nodes[0];
4150 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4151 found_type = found_key.type;
4153 if (found_key.objectid != ino)
4154 break;
4156 if (found_type < min_type)
4157 break;
4159 item_end = found_key.offset;
4160 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4161 fi = btrfs_item_ptr(leaf, path->slots[0],
4162 struct btrfs_file_extent_item);
4163 extent_type = btrfs_file_extent_type(leaf, fi);
4164 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4165 item_end +=
4166 btrfs_file_extent_num_bytes(leaf, fi);
4167 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4168 item_end += btrfs_file_extent_inline_len(leaf,
4169 path->slots[0], fi);
4171 item_end--;
4173 if (found_type > min_type) {
4174 del_item = 1;
4175 } else {
4176 if (item_end < new_size)
4177 break;
4178 if (found_key.offset >= new_size)
4179 del_item = 1;
4180 else
4181 del_item = 0;
4183 found_extent = 0;
4184 /* FIXME, shrink the extent if the ref count is only 1 */
4185 if (found_type != BTRFS_EXTENT_DATA_KEY)
4186 goto delete;
4188 if (del_item)
4189 last_size = found_key.offset;
4190 else
4191 last_size = new_size;
4193 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4194 u64 num_dec;
4195 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4196 if (!del_item) {
4197 u64 orig_num_bytes =
4198 btrfs_file_extent_num_bytes(leaf, fi);
4199 extent_num_bytes = ALIGN(new_size -
4200 found_key.offset,
4201 root->sectorsize);
4202 btrfs_set_file_extent_num_bytes(leaf, fi,
4203 extent_num_bytes);
4204 num_dec = (orig_num_bytes -
4205 extent_num_bytes);
4206 if (test_bit(BTRFS_ROOT_REF_COWS,
4207 &root->state) &&
4208 extent_start != 0)
4209 inode_sub_bytes(inode, num_dec);
4210 btrfs_mark_buffer_dirty(leaf);
4211 } else {
4212 extent_num_bytes =
4213 btrfs_file_extent_disk_num_bytes(leaf,
4214 fi);
4215 extent_offset = found_key.offset -
4216 btrfs_file_extent_offset(leaf, fi);
4218 /* FIXME blocksize != 4096 */
4219 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4220 if (extent_start != 0) {
4221 found_extent = 1;
4222 if (test_bit(BTRFS_ROOT_REF_COWS,
4223 &root->state))
4224 inode_sub_bytes(inode, num_dec);
4227 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4229 * we can't truncate inline items that have had
4230 * special encodings
4232 if (!del_item &&
4233 btrfs_file_extent_compression(leaf, fi) == 0 &&
4234 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4235 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4236 u32 size = new_size - found_key.offset;
4238 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4239 inode_sub_bytes(inode, item_end + 1 -
4240 new_size);
4243 * update the ram bytes to properly reflect
4244 * the new size of our item
4246 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4247 size =
4248 btrfs_file_extent_calc_inline_size(size);
4249 btrfs_truncate_item(root, path, size, 1);
4250 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4251 &root->state)) {
4252 inode_sub_bytes(inode, item_end + 1 -
4253 found_key.offset);
4256 delete:
4257 if (del_item) {
4258 if (!pending_del_nr) {
4259 /* no pending yet, add ourselves */
4260 pending_del_slot = path->slots[0];
4261 pending_del_nr = 1;
4262 } else if (pending_del_nr &&
4263 path->slots[0] + 1 == pending_del_slot) {
4264 /* hop on the pending chunk */
4265 pending_del_nr++;
4266 pending_del_slot = path->slots[0];
4267 } else {
4268 BUG();
4270 } else {
4271 break;
4273 if (found_extent &&
4274 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4275 root == root->fs_info->tree_root)) {
4276 btrfs_set_path_blocking(path);
4277 ret = btrfs_free_extent(trans, root, extent_start,
4278 extent_num_bytes, 0,
4279 btrfs_header_owner(leaf),
4280 ino, extent_offset, 0);
4281 BUG_ON(ret);
4284 if (found_type == BTRFS_INODE_ITEM_KEY)
4285 break;
4287 if (path->slots[0] == 0 ||
4288 path->slots[0] != pending_del_slot) {
4289 if (pending_del_nr) {
4290 ret = btrfs_del_items(trans, root, path,
4291 pending_del_slot,
4292 pending_del_nr);
4293 if (ret) {
4294 btrfs_abort_transaction(trans,
4295 root, ret);
4296 goto error;
4298 pending_del_nr = 0;
4300 btrfs_release_path(path);
4301 goto search_again;
4302 } else {
4303 path->slots[0]--;
4306 out:
4307 if (pending_del_nr) {
4308 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4309 pending_del_nr);
4310 if (ret)
4311 btrfs_abort_transaction(trans, root, ret);
4313 error:
4314 if (last_size != (u64)-1 &&
4315 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4316 btrfs_ordered_update_i_size(inode, last_size, NULL);
4317 btrfs_free_path(path);
4318 return err;
4322 * btrfs_truncate_page - read, zero a chunk and write a page
4323 * @inode - inode that we're zeroing
4324 * @from - the offset to start zeroing
4325 * @len - the length to zero, 0 to zero the entire range respective to the
4326 * offset
4327 * @front - zero up to the offset instead of from the offset on
4329 * This will find the page for the "from" offset and cow the page and zero the
4330 * part we want to zero. This is used with truncate and hole punching.
4332 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4333 int front)
4335 struct address_space *mapping = inode->i_mapping;
4336 struct btrfs_root *root = BTRFS_I(inode)->root;
4337 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4338 struct btrfs_ordered_extent *ordered;
4339 struct extent_state *cached_state = NULL;
4340 char *kaddr;
4341 u32 blocksize = root->sectorsize;
4342 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4343 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4344 struct page *page;
4345 gfp_t mask = btrfs_alloc_write_mask(mapping);
4346 int ret = 0;
4347 u64 page_start;
4348 u64 page_end;
4350 if ((offset & (blocksize - 1)) == 0 &&
4351 (!len || ((len & (blocksize - 1)) == 0)))
4352 goto out;
4353 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4354 if (ret)
4355 goto out;
4357 again:
4358 page = find_or_create_page(mapping, index, mask);
4359 if (!page) {
4360 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4361 ret = -ENOMEM;
4362 goto out;
4365 page_start = page_offset(page);
4366 page_end = page_start + PAGE_CACHE_SIZE - 1;
4368 if (!PageUptodate(page)) {
4369 ret = btrfs_readpage(NULL, page);
4370 lock_page(page);
4371 if (page->mapping != mapping) {
4372 unlock_page(page);
4373 page_cache_release(page);
4374 goto again;
4376 if (!PageUptodate(page)) {
4377 ret = -EIO;
4378 goto out_unlock;
4381 wait_on_page_writeback(page);
4383 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4384 set_page_extent_mapped(page);
4386 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4387 if (ordered) {
4388 unlock_extent_cached(io_tree, page_start, page_end,
4389 &cached_state, GFP_NOFS);
4390 unlock_page(page);
4391 page_cache_release(page);
4392 btrfs_start_ordered_extent(inode, ordered, 1);
4393 btrfs_put_ordered_extent(ordered);
4394 goto again;
4397 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4398 EXTENT_DIRTY | EXTENT_DELALLOC |
4399 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4400 0, 0, &cached_state, GFP_NOFS);
4402 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4403 &cached_state);
4404 if (ret) {
4405 unlock_extent_cached(io_tree, page_start, page_end,
4406 &cached_state, GFP_NOFS);
4407 goto out_unlock;
4410 if (offset != PAGE_CACHE_SIZE) {
4411 if (!len)
4412 len = PAGE_CACHE_SIZE - offset;
4413 kaddr = kmap(page);
4414 if (front)
4415 memset(kaddr, 0, offset);
4416 else
4417 memset(kaddr + offset, 0, len);
4418 flush_dcache_page(page);
4419 kunmap(page);
4421 ClearPageChecked(page);
4422 set_page_dirty(page);
4423 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4424 GFP_NOFS);
4426 out_unlock:
4427 if (ret)
4428 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4429 unlock_page(page);
4430 page_cache_release(page);
4431 out:
4432 return ret;
4435 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4436 u64 offset, u64 len)
4438 struct btrfs_trans_handle *trans;
4439 int ret;
4442 * Still need to make sure the inode looks like it's been updated so
4443 * that any holes get logged if we fsync.
4445 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4446 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4447 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4448 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4449 return 0;
4453 * 1 - for the one we're dropping
4454 * 1 - for the one we're adding
4455 * 1 - for updating the inode.
4457 trans = btrfs_start_transaction(root, 3);
4458 if (IS_ERR(trans))
4459 return PTR_ERR(trans);
4461 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4462 if (ret) {
4463 btrfs_abort_transaction(trans, root, ret);
4464 btrfs_end_transaction(trans, root);
4465 return ret;
4468 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4469 0, 0, len, 0, len, 0, 0, 0);
4470 if (ret)
4471 btrfs_abort_transaction(trans, root, ret);
4472 else
4473 btrfs_update_inode(trans, root, inode);
4474 btrfs_end_transaction(trans, root);
4475 return ret;
4479 * This function puts in dummy file extents for the area we're creating a hole
4480 * for. So if we are truncating this file to a larger size we need to insert
4481 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4482 * the range between oldsize and size
4484 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4486 struct btrfs_root *root = BTRFS_I(inode)->root;
4487 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4488 struct extent_map *em = NULL;
4489 struct extent_state *cached_state = NULL;
4490 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4491 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4492 u64 block_end = ALIGN(size, root->sectorsize);
4493 u64 last_byte;
4494 u64 cur_offset;
4495 u64 hole_size;
4496 int err = 0;
4499 * If our size started in the middle of a page we need to zero out the
4500 * rest of the page before we expand the i_size, otherwise we could
4501 * expose stale data.
4503 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4504 if (err)
4505 return err;
4507 if (size <= hole_start)
4508 return 0;
4510 while (1) {
4511 struct btrfs_ordered_extent *ordered;
4513 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4514 &cached_state);
4515 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4516 block_end - hole_start);
4517 if (!ordered)
4518 break;
4519 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4520 &cached_state, GFP_NOFS);
4521 btrfs_start_ordered_extent(inode, ordered, 1);
4522 btrfs_put_ordered_extent(ordered);
4525 cur_offset = hole_start;
4526 while (1) {
4527 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4528 block_end - cur_offset, 0);
4529 if (IS_ERR(em)) {
4530 err = PTR_ERR(em);
4531 em = NULL;
4532 break;
4534 last_byte = min(extent_map_end(em), block_end);
4535 last_byte = ALIGN(last_byte , root->sectorsize);
4536 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4537 struct extent_map *hole_em;
4538 hole_size = last_byte - cur_offset;
4540 err = maybe_insert_hole(root, inode, cur_offset,
4541 hole_size);
4542 if (err)
4543 break;
4544 btrfs_drop_extent_cache(inode, cur_offset,
4545 cur_offset + hole_size - 1, 0);
4546 hole_em = alloc_extent_map();
4547 if (!hole_em) {
4548 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4549 &BTRFS_I(inode)->runtime_flags);
4550 goto next;
4552 hole_em->start = cur_offset;
4553 hole_em->len = hole_size;
4554 hole_em->orig_start = cur_offset;
4556 hole_em->block_start = EXTENT_MAP_HOLE;
4557 hole_em->block_len = 0;
4558 hole_em->orig_block_len = 0;
4559 hole_em->ram_bytes = hole_size;
4560 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4561 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4562 hole_em->generation = root->fs_info->generation;
4564 while (1) {
4565 write_lock(&em_tree->lock);
4566 err = add_extent_mapping(em_tree, hole_em, 1);
4567 write_unlock(&em_tree->lock);
4568 if (err != -EEXIST)
4569 break;
4570 btrfs_drop_extent_cache(inode, cur_offset,
4571 cur_offset +
4572 hole_size - 1, 0);
4574 free_extent_map(hole_em);
4576 next:
4577 free_extent_map(em);
4578 em = NULL;
4579 cur_offset = last_byte;
4580 if (cur_offset >= block_end)
4581 break;
4583 free_extent_map(em);
4584 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4585 GFP_NOFS);
4586 return err;
4589 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4591 struct btrfs_root *root = BTRFS_I(inode)->root;
4592 struct btrfs_trans_handle *trans;
4593 loff_t oldsize = i_size_read(inode);
4594 loff_t newsize = attr->ia_size;
4595 int mask = attr->ia_valid;
4596 int ret;
4599 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4600 * special case where we need to update the times despite not having
4601 * these flags set. For all other operations the VFS set these flags
4602 * explicitly if it wants a timestamp update.
4604 if (newsize != oldsize) {
4605 inode_inc_iversion(inode);
4606 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4607 inode->i_ctime = inode->i_mtime =
4608 current_fs_time(inode->i_sb);
4611 if (newsize > oldsize) {
4612 truncate_pagecache(inode, newsize);
4613 ret = btrfs_cont_expand(inode, oldsize, newsize);
4614 if (ret)
4615 return ret;
4617 trans = btrfs_start_transaction(root, 1);
4618 if (IS_ERR(trans))
4619 return PTR_ERR(trans);
4621 i_size_write(inode, newsize);
4622 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4623 ret = btrfs_update_inode(trans, root, inode);
4624 btrfs_end_transaction(trans, root);
4625 } else {
4628 * We're truncating a file that used to have good data down to
4629 * zero. Make sure it gets into the ordered flush list so that
4630 * any new writes get down to disk quickly.
4632 if (newsize == 0)
4633 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4634 &BTRFS_I(inode)->runtime_flags);
4637 * 1 for the orphan item we're going to add
4638 * 1 for the orphan item deletion.
4640 trans = btrfs_start_transaction(root, 2);
4641 if (IS_ERR(trans))
4642 return PTR_ERR(trans);
4645 * We need to do this in case we fail at _any_ point during the
4646 * actual truncate. Once we do the truncate_setsize we could
4647 * invalidate pages which forces any outstanding ordered io to
4648 * be instantly completed which will give us extents that need
4649 * to be truncated. If we fail to get an orphan inode down we
4650 * could have left over extents that were never meant to live,
4651 * so we need to garuntee from this point on that everything
4652 * will be consistent.
4654 ret = btrfs_orphan_add(trans, inode);
4655 btrfs_end_transaction(trans, root);
4656 if (ret)
4657 return ret;
4659 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4660 truncate_setsize(inode, newsize);
4662 /* Disable nonlocked read DIO to avoid the end less truncate */
4663 btrfs_inode_block_unlocked_dio(inode);
4664 inode_dio_wait(inode);
4665 btrfs_inode_resume_unlocked_dio(inode);
4667 ret = btrfs_truncate(inode);
4668 if (ret && inode->i_nlink) {
4669 int err;
4672 * failed to truncate, disk_i_size is only adjusted down
4673 * as we remove extents, so it should represent the true
4674 * size of the inode, so reset the in memory size and
4675 * delete our orphan entry.
4677 trans = btrfs_join_transaction(root);
4678 if (IS_ERR(trans)) {
4679 btrfs_orphan_del(NULL, inode);
4680 return ret;
4682 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4683 err = btrfs_orphan_del(trans, inode);
4684 if (err)
4685 btrfs_abort_transaction(trans, root, err);
4686 btrfs_end_transaction(trans, root);
4690 return ret;
4693 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4695 struct inode *inode = dentry->d_inode;
4696 struct btrfs_root *root = BTRFS_I(inode)->root;
4697 int err;
4699 if (btrfs_root_readonly(root))
4700 return -EROFS;
4702 err = inode_change_ok(inode, attr);
4703 if (err)
4704 return err;
4706 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4707 err = btrfs_setsize(inode, attr);
4708 if (err)
4709 return err;
4712 if (attr->ia_valid) {
4713 setattr_copy(inode, attr);
4714 inode_inc_iversion(inode);
4715 err = btrfs_dirty_inode(inode);
4717 if (!err && attr->ia_valid & ATTR_MODE)
4718 err = posix_acl_chmod(inode, inode->i_mode);
4721 return err;
4725 * While truncating the inode pages during eviction, we get the VFS calling
4726 * btrfs_invalidatepage() against each page of the inode. This is slow because
4727 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4728 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4729 * extent_state structures over and over, wasting lots of time.
4731 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4732 * those expensive operations on a per page basis and do only the ordered io
4733 * finishing, while we release here the extent_map and extent_state structures,
4734 * without the excessive merging and splitting.
4736 static void evict_inode_truncate_pages(struct inode *inode)
4738 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4739 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4740 struct rb_node *node;
4742 ASSERT(inode->i_state & I_FREEING);
4743 truncate_inode_pages_final(&inode->i_data);
4745 write_lock(&map_tree->lock);
4746 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4747 struct extent_map *em;
4749 node = rb_first(&map_tree->map);
4750 em = rb_entry(node, struct extent_map, rb_node);
4751 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4752 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4753 remove_extent_mapping(map_tree, em);
4754 free_extent_map(em);
4755 if (need_resched()) {
4756 write_unlock(&map_tree->lock);
4757 cond_resched();
4758 write_lock(&map_tree->lock);
4761 write_unlock(&map_tree->lock);
4763 spin_lock(&io_tree->lock);
4764 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4765 struct extent_state *state;
4766 struct extent_state *cached_state = NULL;
4768 node = rb_first(&io_tree->state);
4769 state = rb_entry(node, struct extent_state, rb_node);
4770 atomic_inc(&state->refs);
4771 spin_unlock(&io_tree->lock);
4773 lock_extent_bits(io_tree, state->start, state->end,
4774 0, &cached_state);
4775 clear_extent_bit(io_tree, state->start, state->end,
4776 EXTENT_LOCKED | EXTENT_DIRTY |
4777 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4778 EXTENT_DEFRAG, 1, 1,
4779 &cached_state, GFP_NOFS);
4780 free_extent_state(state);
4782 cond_resched();
4783 spin_lock(&io_tree->lock);
4785 spin_unlock(&io_tree->lock);
4788 void btrfs_evict_inode(struct inode *inode)
4790 struct btrfs_trans_handle *trans;
4791 struct btrfs_root *root = BTRFS_I(inode)->root;
4792 struct btrfs_block_rsv *rsv, *global_rsv;
4793 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4794 int ret;
4796 trace_btrfs_inode_evict(inode);
4798 evict_inode_truncate_pages(inode);
4800 if (inode->i_nlink &&
4801 ((btrfs_root_refs(&root->root_item) != 0 &&
4802 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4803 btrfs_is_free_space_inode(inode)))
4804 goto no_delete;
4806 if (is_bad_inode(inode)) {
4807 btrfs_orphan_del(NULL, inode);
4808 goto no_delete;
4810 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4811 if (!special_file(inode->i_mode))
4812 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4814 btrfs_free_io_failure_record(inode, 0, (u64)-1);
4816 if (root->fs_info->log_root_recovering) {
4817 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4818 &BTRFS_I(inode)->runtime_flags));
4819 goto no_delete;
4822 if (inode->i_nlink > 0) {
4823 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4824 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4825 goto no_delete;
4828 ret = btrfs_commit_inode_delayed_inode(inode);
4829 if (ret) {
4830 btrfs_orphan_del(NULL, inode);
4831 goto no_delete;
4834 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4835 if (!rsv) {
4836 btrfs_orphan_del(NULL, inode);
4837 goto no_delete;
4839 rsv->size = min_size;
4840 rsv->failfast = 1;
4841 global_rsv = &root->fs_info->global_block_rsv;
4843 btrfs_i_size_write(inode, 0);
4846 * This is a bit simpler than btrfs_truncate since we've already
4847 * reserved our space for our orphan item in the unlink, so we just
4848 * need to reserve some slack space in case we add bytes and update
4849 * inode item when doing the truncate.
4851 while (1) {
4852 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4853 BTRFS_RESERVE_FLUSH_LIMIT);
4856 * Try and steal from the global reserve since we will
4857 * likely not use this space anyway, we want to try as
4858 * hard as possible to get this to work.
4860 if (ret)
4861 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4863 if (ret) {
4864 btrfs_warn(root->fs_info,
4865 "Could not get space for a delete, will truncate on mount %d",
4866 ret);
4867 btrfs_orphan_del(NULL, inode);
4868 btrfs_free_block_rsv(root, rsv);
4869 goto no_delete;
4872 trans = btrfs_join_transaction(root);
4873 if (IS_ERR(trans)) {
4874 btrfs_orphan_del(NULL, inode);
4875 btrfs_free_block_rsv(root, rsv);
4876 goto no_delete;
4879 trans->block_rsv = rsv;
4881 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4882 if (ret != -ENOSPC)
4883 break;
4885 trans->block_rsv = &root->fs_info->trans_block_rsv;
4886 btrfs_end_transaction(trans, root);
4887 trans = NULL;
4888 btrfs_btree_balance_dirty(root);
4891 btrfs_free_block_rsv(root, rsv);
4894 * Errors here aren't a big deal, it just means we leave orphan items
4895 * in the tree. They will be cleaned up on the next mount.
4897 if (ret == 0) {
4898 trans->block_rsv = root->orphan_block_rsv;
4899 btrfs_orphan_del(trans, inode);
4900 } else {
4901 btrfs_orphan_del(NULL, inode);
4904 trans->block_rsv = &root->fs_info->trans_block_rsv;
4905 if (!(root == root->fs_info->tree_root ||
4906 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4907 btrfs_return_ino(root, btrfs_ino(inode));
4909 btrfs_end_transaction(trans, root);
4910 btrfs_btree_balance_dirty(root);
4911 no_delete:
4912 btrfs_remove_delayed_node(inode);
4913 clear_inode(inode);
4914 return;
4918 * this returns the key found in the dir entry in the location pointer.
4919 * If no dir entries were found, location->objectid is 0.
4921 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4922 struct btrfs_key *location)
4924 const char *name = dentry->d_name.name;
4925 int namelen = dentry->d_name.len;
4926 struct btrfs_dir_item *di;
4927 struct btrfs_path *path;
4928 struct btrfs_root *root = BTRFS_I(dir)->root;
4929 int ret = 0;
4931 path = btrfs_alloc_path();
4932 if (!path)
4933 return -ENOMEM;
4935 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4936 namelen, 0);
4937 if (IS_ERR(di))
4938 ret = PTR_ERR(di);
4940 if (IS_ERR_OR_NULL(di))
4941 goto out_err;
4943 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4944 out:
4945 btrfs_free_path(path);
4946 return ret;
4947 out_err:
4948 location->objectid = 0;
4949 goto out;
4953 * when we hit a tree root in a directory, the btrfs part of the inode
4954 * needs to be changed to reflect the root directory of the tree root. This
4955 * is kind of like crossing a mount point.
4957 static int fixup_tree_root_location(struct btrfs_root *root,
4958 struct inode *dir,
4959 struct dentry *dentry,
4960 struct btrfs_key *location,
4961 struct btrfs_root **sub_root)
4963 struct btrfs_path *path;
4964 struct btrfs_root *new_root;
4965 struct btrfs_root_ref *ref;
4966 struct extent_buffer *leaf;
4967 int ret;
4968 int err = 0;
4970 path = btrfs_alloc_path();
4971 if (!path) {
4972 err = -ENOMEM;
4973 goto out;
4976 err = -ENOENT;
4977 ret = btrfs_find_item(root->fs_info->tree_root, path,
4978 BTRFS_I(dir)->root->root_key.objectid,
4979 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4980 if (ret) {
4981 if (ret < 0)
4982 err = ret;
4983 goto out;
4986 leaf = path->nodes[0];
4987 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4988 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4989 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4990 goto out;
4992 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4993 (unsigned long)(ref + 1),
4994 dentry->d_name.len);
4995 if (ret)
4996 goto out;
4998 btrfs_release_path(path);
5000 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5001 if (IS_ERR(new_root)) {
5002 err = PTR_ERR(new_root);
5003 goto out;
5006 *sub_root = new_root;
5007 location->objectid = btrfs_root_dirid(&new_root->root_item);
5008 location->type = BTRFS_INODE_ITEM_KEY;
5009 location->offset = 0;
5010 err = 0;
5011 out:
5012 btrfs_free_path(path);
5013 return err;
5016 static void inode_tree_add(struct inode *inode)
5018 struct btrfs_root *root = BTRFS_I(inode)->root;
5019 struct btrfs_inode *entry;
5020 struct rb_node **p;
5021 struct rb_node *parent;
5022 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5023 u64 ino = btrfs_ino(inode);
5025 if (inode_unhashed(inode))
5026 return;
5027 parent = NULL;
5028 spin_lock(&root->inode_lock);
5029 p = &root->inode_tree.rb_node;
5030 while (*p) {
5031 parent = *p;
5032 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5034 if (ino < btrfs_ino(&entry->vfs_inode))
5035 p = &parent->rb_left;
5036 else if (ino > btrfs_ino(&entry->vfs_inode))
5037 p = &parent->rb_right;
5038 else {
5039 WARN_ON(!(entry->vfs_inode.i_state &
5040 (I_WILL_FREE | I_FREEING)));
5041 rb_replace_node(parent, new, &root->inode_tree);
5042 RB_CLEAR_NODE(parent);
5043 spin_unlock(&root->inode_lock);
5044 return;
5047 rb_link_node(new, parent, p);
5048 rb_insert_color(new, &root->inode_tree);
5049 spin_unlock(&root->inode_lock);
5052 static void inode_tree_del(struct inode *inode)
5054 struct btrfs_root *root = BTRFS_I(inode)->root;
5055 int empty = 0;
5057 spin_lock(&root->inode_lock);
5058 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5059 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5060 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5061 empty = RB_EMPTY_ROOT(&root->inode_tree);
5063 spin_unlock(&root->inode_lock);
5065 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5066 synchronize_srcu(&root->fs_info->subvol_srcu);
5067 spin_lock(&root->inode_lock);
5068 empty = RB_EMPTY_ROOT(&root->inode_tree);
5069 spin_unlock(&root->inode_lock);
5070 if (empty)
5071 btrfs_add_dead_root(root);
5075 void btrfs_invalidate_inodes(struct btrfs_root *root)
5077 struct rb_node *node;
5078 struct rb_node *prev;
5079 struct btrfs_inode *entry;
5080 struct inode *inode;
5081 u64 objectid = 0;
5083 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5084 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5086 spin_lock(&root->inode_lock);
5087 again:
5088 node = root->inode_tree.rb_node;
5089 prev = NULL;
5090 while (node) {
5091 prev = node;
5092 entry = rb_entry(node, struct btrfs_inode, rb_node);
5094 if (objectid < btrfs_ino(&entry->vfs_inode))
5095 node = node->rb_left;
5096 else if (objectid > btrfs_ino(&entry->vfs_inode))
5097 node = node->rb_right;
5098 else
5099 break;
5101 if (!node) {
5102 while (prev) {
5103 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5104 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5105 node = prev;
5106 break;
5108 prev = rb_next(prev);
5111 while (node) {
5112 entry = rb_entry(node, struct btrfs_inode, rb_node);
5113 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5114 inode = igrab(&entry->vfs_inode);
5115 if (inode) {
5116 spin_unlock(&root->inode_lock);
5117 if (atomic_read(&inode->i_count) > 1)
5118 d_prune_aliases(inode);
5120 * btrfs_drop_inode will have it removed from
5121 * the inode cache when its usage count
5122 * hits zero.
5124 iput(inode);
5125 cond_resched();
5126 spin_lock(&root->inode_lock);
5127 goto again;
5130 if (cond_resched_lock(&root->inode_lock))
5131 goto again;
5133 node = rb_next(node);
5135 spin_unlock(&root->inode_lock);
5138 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5140 struct btrfs_iget_args *args = p;
5141 inode->i_ino = args->location->objectid;
5142 memcpy(&BTRFS_I(inode)->location, args->location,
5143 sizeof(*args->location));
5144 BTRFS_I(inode)->root = args->root;
5145 return 0;
5148 static int btrfs_find_actor(struct inode *inode, void *opaque)
5150 struct btrfs_iget_args *args = opaque;
5151 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5152 args->root == BTRFS_I(inode)->root;
5155 static struct inode *btrfs_iget_locked(struct super_block *s,
5156 struct btrfs_key *location,
5157 struct btrfs_root *root)
5159 struct inode *inode;
5160 struct btrfs_iget_args args;
5161 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5163 args.location = location;
5164 args.root = root;
5166 inode = iget5_locked(s, hashval, btrfs_find_actor,
5167 btrfs_init_locked_inode,
5168 (void *)&args);
5169 return inode;
5172 /* Get an inode object given its location and corresponding root.
5173 * Returns in *is_new if the inode was read from disk
5175 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5176 struct btrfs_root *root, int *new)
5178 struct inode *inode;
5180 inode = btrfs_iget_locked(s, location, root);
5181 if (!inode)
5182 return ERR_PTR(-ENOMEM);
5184 if (inode->i_state & I_NEW) {
5185 btrfs_read_locked_inode(inode);
5186 if (!is_bad_inode(inode)) {
5187 inode_tree_add(inode);
5188 unlock_new_inode(inode);
5189 if (new)
5190 *new = 1;
5191 } else {
5192 unlock_new_inode(inode);
5193 iput(inode);
5194 inode = ERR_PTR(-ESTALE);
5198 return inode;
5201 static struct inode *new_simple_dir(struct super_block *s,
5202 struct btrfs_key *key,
5203 struct btrfs_root *root)
5205 struct inode *inode = new_inode(s);
5207 if (!inode)
5208 return ERR_PTR(-ENOMEM);
5210 BTRFS_I(inode)->root = root;
5211 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5212 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5214 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5215 inode->i_op = &btrfs_dir_ro_inode_operations;
5216 inode->i_fop = &simple_dir_operations;
5217 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5218 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5220 return inode;
5223 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5225 struct inode *inode;
5226 struct btrfs_root *root = BTRFS_I(dir)->root;
5227 struct btrfs_root *sub_root = root;
5228 struct btrfs_key location;
5229 int index;
5230 int ret = 0;
5232 if (dentry->d_name.len > BTRFS_NAME_LEN)
5233 return ERR_PTR(-ENAMETOOLONG);
5235 ret = btrfs_inode_by_name(dir, dentry, &location);
5236 if (ret < 0)
5237 return ERR_PTR(ret);
5239 if (location.objectid == 0)
5240 return ERR_PTR(-ENOENT);
5242 if (location.type == BTRFS_INODE_ITEM_KEY) {
5243 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5244 return inode;
5247 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5249 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5250 ret = fixup_tree_root_location(root, dir, dentry,
5251 &location, &sub_root);
5252 if (ret < 0) {
5253 if (ret != -ENOENT)
5254 inode = ERR_PTR(ret);
5255 else
5256 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5257 } else {
5258 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5260 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5262 if (!IS_ERR(inode) && root != sub_root) {
5263 down_read(&root->fs_info->cleanup_work_sem);
5264 if (!(inode->i_sb->s_flags & MS_RDONLY))
5265 ret = btrfs_orphan_cleanup(sub_root);
5266 up_read(&root->fs_info->cleanup_work_sem);
5267 if (ret) {
5268 iput(inode);
5269 inode = ERR_PTR(ret);
5273 return inode;
5276 static int btrfs_dentry_delete(const struct dentry *dentry)
5278 struct btrfs_root *root;
5279 struct inode *inode = dentry->d_inode;
5281 if (!inode && !IS_ROOT(dentry))
5282 inode = dentry->d_parent->d_inode;
5284 if (inode) {
5285 root = BTRFS_I(inode)->root;
5286 if (btrfs_root_refs(&root->root_item) == 0)
5287 return 1;
5289 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5290 return 1;
5292 return 0;
5295 static void btrfs_dentry_release(struct dentry *dentry)
5297 kfree(dentry->d_fsdata);
5300 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5301 unsigned int flags)
5303 struct inode *inode;
5305 inode = btrfs_lookup_dentry(dir, dentry);
5306 if (IS_ERR(inode)) {
5307 if (PTR_ERR(inode) == -ENOENT)
5308 inode = NULL;
5309 else
5310 return ERR_CAST(inode);
5313 return d_materialise_unique(dentry, inode);
5316 unsigned char btrfs_filetype_table[] = {
5317 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5320 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5322 struct inode *inode = file_inode(file);
5323 struct btrfs_root *root = BTRFS_I(inode)->root;
5324 struct btrfs_item *item;
5325 struct btrfs_dir_item *di;
5326 struct btrfs_key key;
5327 struct btrfs_key found_key;
5328 struct btrfs_path *path;
5329 struct list_head ins_list;
5330 struct list_head del_list;
5331 int ret;
5332 struct extent_buffer *leaf;
5333 int slot;
5334 unsigned char d_type;
5335 int over = 0;
5336 u32 di_cur;
5337 u32 di_total;
5338 u32 di_len;
5339 int key_type = BTRFS_DIR_INDEX_KEY;
5340 char tmp_name[32];
5341 char *name_ptr;
5342 int name_len;
5343 int is_curr = 0; /* ctx->pos points to the current index? */
5344 bool emitted;
5346 /* FIXME, use a real flag for deciding about the key type */
5347 if (root->fs_info->tree_root == root)
5348 key_type = BTRFS_DIR_ITEM_KEY;
5350 if (!dir_emit_dots(file, ctx))
5351 return 0;
5353 path = btrfs_alloc_path();
5354 if (!path)
5355 return -ENOMEM;
5357 path->reada = 1;
5359 if (key_type == BTRFS_DIR_INDEX_KEY) {
5360 INIT_LIST_HEAD(&ins_list);
5361 INIT_LIST_HEAD(&del_list);
5362 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5365 key.type = key_type;
5366 key.offset = ctx->pos;
5367 key.objectid = btrfs_ino(inode);
5369 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5370 if (ret < 0)
5371 goto err;
5373 emitted = false;
5374 while (1) {
5375 leaf = path->nodes[0];
5376 slot = path->slots[0];
5377 if (slot >= btrfs_header_nritems(leaf)) {
5378 ret = btrfs_next_leaf(root, path);
5379 if (ret < 0)
5380 goto err;
5381 else if (ret > 0)
5382 break;
5383 continue;
5386 item = btrfs_item_nr(slot);
5387 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5389 if (found_key.objectid != key.objectid)
5390 break;
5391 if (found_key.type != key_type)
5392 break;
5393 if (found_key.offset < ctx->pos)
5394 goto next;
5395 if (key_type == BTRFS_DIR_INDEX_KEY &&
5396 btrfs_should_delete_dir_index(&del_list,
5397 found_key.offset))
5398 goto next;
5400 ctx->pos = found_key.offset;
5401 is_curr = 1;
5403 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5404 di_cur = 0;
5405 di_total = btrfs_item_size(leaf, item);
5407 while (di_cur < di_total) {
5408 struct btrfs_key location;
5410 if (verify_dir_item(root, leaf, di))
5411 break;
5413 name_len = btrfs_dir_name_len(leaf, di);
5414 if (name_len <= sizeof(tmp_name)) {
5415 name_ptr = tmp_name;
5416 } else {
5417 name_ptr = kmalloc(name_len, GFP_NOFS);
5418 if (!name_ptr) {
5419 ret = -ENOMEM;
5420 goto err;
5423 read_extent_buffer(leaf, name_ptr,
5424 (unsigned long)(di + 1), name_len);
5426 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5427 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5430 /* is this a reference to our own snapshot? If so
5431 * skip it.
5433 * In contrast to old kernels, we insert the snapshot's
5434 * dir item and dir index after it has been created, so
5435 * we won't find a reference to our own snapshot. We
5436 * still keep the following code for backward
5437 * compatibility.
5439 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5440 location.objectid == root->root_key.objectid) {
5441 over = 0;
5442 goto skip;
5444 over = !dir_emit(ctx, name_ptr, name_len,
5445 location.objectid, d_type);
5447 skip:
5448 if (name_ptr != tmp_name)
5449 kfree(name_ptr);
5451 if (over)
5452 goto nopos;
5453 emitted = true;
5454 di_len = btrfs_dir_name_len(leaf, di) +
5455 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5456 di_cur += di_len;
5457 di = (struct btrfs_dir_item *)((char *)di + di_len);
5459 next:
5460 path->slots[0]++;
5463 if (key_type == BTRFS_DIR_INDEX_KEY) {
5464 if (is_curr)
5465 ctx->pos++;
5466 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list, &emitted);
5467 if (ret)
5468 goto nopos;
5472 * If we haven't emitted any dir entry, we must not touch ctx->pos as
5473 * it was was set to the termination value in previous call. We assume
5474 * that "." and ".." were emitted if we reach this point and set the
5475 * termination value as well for an empty directory.
5477 if (ctx->pos > 2 && !emitted)
5478 goto nopos;
5480 /* Reached end of directory/root. Bump pos past the last item. */
5481 ctx->pos++;
5484 * Stop new entries from being returned after we return the last
5485 * entry.
5487 * New directory entries are assigned a strictly increasing
5488 * offset. This means that new entries created during readdir
5489 * are *guaranteed* to be seen in the future by that readdir.
5490 * This has broken buggy programs which operate on names as
5491 * they're returned by readdir. Until we re-use freed offsets
5492 * we have this hack to stop new entries from being returned
5493 * under the assumption that they'll never reach this huge
5494 * offset.
5496 * This is being careful not to overflow 32bit loff_t unless the
5497 * last entry requires it because doing so has broken 32bit apps
5498 * in the past.
5500 if (key_type == BTRFS_DIR_INDEX_KEY) {
5501 if (ctx->pos >= INT_MAX)
5502 ctx->pos = LLONG_MAX;
5503 else
5504 ctx->pos = INT_MAX;
5506 nopos:
5507 ret = 0;
5508 err:
5509 if (key_type == BTRFS_DIR_INDEX_KEY)
5510 btrfs_put_delayed_items(&ins_list, &del_list);
5511 btrfs_free_path(path);
5512 return ret;
5515 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5517 struct btrfs_root *root = BTRFS_I(inode)->root;
5518 struct btrfs_trans_handle *trans;
5519 int ret = 0;
5520 bool nolock = false;
5522 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5523 return 0;
5525 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5526 nolock = true;
5528 if (wbc->sync_mode == WB_SYNC_ALL) {
5529 if (nolock)
5530 trans = btrfs_join_transaction_nolock(root);
5531 else
5532 trans = btrfs_join_transaction(root);
5533 if (IS_ERR(trans))
5534 return PTR_ERR(trans);
5535 ret = btrfs_commit_transaction(trans, root);
5537 return ret;
5541 * This is somewhat expensive, updating the tree every time the
5542 * inode changes. But, it is most likely to find the inode in cache.
5543 * FIXME, needs more benchmarking...there are no reasons other than performance
5544 * to keep or drop this code.
5546 static int btrfs_dirty_inode(struct inode *inode)
5548 struct btrfs_root *root = BTRFS_I(inode)->root;
5549 struct btrfs_trans_handle *trans;
5550 int ret;
5552 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5553 return 0;
5555 trans = btrfs_join_transaction(root);
5556 if (IS_ERR(trans))
5557 return PTR_ERR(trans);
5559 ret = btrfs_update_inode(trans, root, inode);
5560 if (ret && ret == -ENOSPC) {
5561 /* whoops, lets try again with the full transaction */
5562 btrfs_end_transaction(trans, root);
5563 trans = btrfs_start_transaction(root, 1);
5564 if (IS_ERR(trans))
5565 return PTR_ERR(trans);
5567 ret = btrfs_update_inode(trans, root, inode);
5569 btrfs_end_transaction(trans, root);
5570 if (BTRFS_I(inode)->delayed_node)
5571 btrfs_balance_delayed_items(root);
5573 return ret;
5577 * This is a copy of file_update_time. We need this so we can return error on
5578 * ENOSPC for updating the inode in the case of file write and mmap writes.
5580 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5581 int flags)
5583 struct btrfs_root *root = BTRFS_I(inode)->root;
5585 if (btrfs_root_readonly(root))
5586 return -EROFS;
5588 if (flags & S_VERSION)
5589 inode_inc_iversion(inode);
5590 if (flags & S_CTIME)
5591 inode->i_ctime = *now;
5592 if (flags & S_MTIME)
5593 inode->i_mtime = *now;
5594 if (flags & S_ATIME)
5595 inode->i_atime = *now;
5596 return btrfs_dirty_inode(inode);
5600 * find the highest existing sequence number in a directory
5601 * and then set the in-memory index_cnt variable to reflect
5602 * free sequence numbers
5604 static int btrfs_set_inode_index_count(struct inode *inode)
5606 struct btrfs_root *root = BTRFS_I(inode)->root;
5607 struct btrfs_key key, found_key;
5608 struct btrfs_path *path;
5609 struct extent_buffer *leaf;
5610 int ret;
5612 key.objectid = btrfs_ino(inode);
5613 key.type = BTRFS_DIR_INDEX_KEY;
5614 key.offset = (u64)-1;
5616 path = btrfs_alloc_path();
5617 if (!path)
5618 return -ENOMEM;
5620 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5621 if (ret < 0)
5622 goto out;
5623 /* FIXME: we should be able to handle this */
5624 if (ret == 0)
5625 goto out;
5626 ret = 0;
5629 * MAGIC NUMBER EXPLANATION:
5630 * since we search a directory based on f_pos we have to start at 2
5631 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5632 * else has to start at 2
5634 if (path->slots[0] == 0) {
5635 BTRFS_I(inode)->index_cnt = 2;
5636 goto out;
5639 path->slots[0]--;
5641 leaf = path->nodes[0];
5642 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5644 if (found_key.objectid != btrfs_ino(inode) ||
5645 found_key.type != BTRFS_DIR_INDEX_KEY) {
5646 BTRFS_I(inode)->index_cnt = 2;
5647 goto out;
5650 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5651 out:
5652 btrfs_free_path(path);
5653 return ret;
5657 * helper to find a free sequence number in a given directory. This current
5658 * code is very simple, later versions will do smarter things in the btree
5660 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5662 int ret = 0;
5664 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5665 ret = btrfs_inode_delayed_dir_index_count(dir);
5666 if (ret) {
5667 ret = btrfs_set_inode_index_count(dir);
5668 if (ret)
5669 return ret;
5673 *index = BTRFS_I(dir)->index_cnt;
5674 BTRFS_I(dir)->index_cnt++;
5676 return ret;
5679 static int btrfs_insert_inode_locked(struct inode *inode)
5681 struct btrfs_iget_args args;
5682 args.location = &BTRFS_I(inode)->location;
5683 args.root = BTRFS_I(inode)->root;
5685 return insert_inode_locked4(inode,
5686 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5687 btrfs_find_actor, &args);
5690 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5691 struct btrfs_root *root,
5692 struct inode *dir,
5693 const char *name, int name_len,
5694 u64 ref_objectid, u64 objectid,
5695 umode_t mode, u64 *index)
5697 struct inode *inode;
5698 struct btrfs_inode_item *inode_item;
5699 struct btrfs_key *location;
5700 struct btrfs_path *path;
5701 struct btrfs_inode_ref *ref;
5702 struct btrfs_key key[2];
5703 u32 sizes[2];
5704 int nitems = name ? 2 : 1;
5705 unsigned long ptr;
5706 int ret;
5708 path = btrfs_alloc_path();
5709 if (!path)
5710 return ERR_PTR(-ENOMEM);
5712 inode = new_inode(root->fs_info->sb);
5713 if (!inode) {
5714 btrfs_free_path(path);
5715 return ERR_PTR(-ENOMEM);
5719 * O_TMPFILE, set link count to 0, so that after this point,
5720 * we fill in an inode item with the correct link count.
5722 if (!name)
5723 set_nlink(inode, 0);
5726 * we have to initialize this early, so we can reclaim the inode
5727 * number if we fail afterwards in this function.
5729 inode->i_ino = objectid;
5731 if (dir && name) {
5732 trace_btrfs_inode_request(dir);
5734 ret = btrfs_set_inode_index(dir, index);
5735 if (ret) {
5736 btrfs_free_path(path);
5737 iput(inode);
5738 return ERR_PTR(ret);
5740 } else if (dir) {
5741 *index = 0;
5744 * index_cnt is ignored for everything but a dir,
5745 * btrfs_get_inode_index_count has an explanation for the magic
5746 * number
5748 BTRFS_I(inode)->index_cnt = 2;
5749 BTRFS_I(inode)->dir_index = *index;
5750 BTRFS_I(inode)->root = root;
5751 BTRFS_I(inode)->generation = trans->transid;
5752 inode->i_generation = BTRFS_I(inode)->generation;
5755 * We could have gotten an inode number from somebody who was fsynced
5756 * and then removed in this same transaction, so let's just set full
5757 * sync since it will be a full sync anyway and this will blow away the
5758 * old info in the log.
5760 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5762 key[0].objectid = objectid;
5763 key[0].type = BTRFS_INODE_ITEM_KEY;
5764 key[0].offset = 0;
5766 sizes[0] = sizeof(struct btrfs_inode_item);
5768 if (name) {
5770 * Start new inodes with an inode_ref. This is slightly more
5771 * efficient for small numbers of hard links since they will
5772 * be packed into one item. Extended refs will kick in if we
5773 * add more hard links than can fit in the ref item.
5775 key[1].objectid = objectid;
5776 key[1].type = BTRFS_INODE_REF_KEY;
5777 key[1].offset = ref_objectid;
5779 sizes[1] = name_len + sizeof(*ref);
5782 location = &BTRFS_I(inode)->location;
5783 location->objectid = objectid;
5784 location->offset = 0;
5785 location->type = BTRFS_INODE_ITEM_KEY;
5787 ret = btrfs_insert_inode_locked(inode);
5788 if (ret < 0)
5789 goto fail;
5791 path->leave_spinning = 1;
5792 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5793 if (ret != 0)
5794 goto fail_unlock;
5796 inode_init_owner(inode, dir, mode);
5797 inode_set_bytes(inode, 0);
5798 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5799 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5800 struct btrfs_inode_item);
5801 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5802 sizeof(*inode_item));
5803 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5805 if (name) {
5806 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5807 struct btrfs_inode_ref);
5808 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5809 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5810 ptr = (unsigned long)(ref + 1);
5811 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5814 btrfs_mark_buffer_dirty(path->nodes[0]);
5815 btrfs_free_path(path);
5817 btrfs_inherit_iflags(inode, dir);
5819 if (S_ISREG(mode)) {
5820 if (btrfs_test_opt(root, NODATASUM))
5821 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5822 if (btrfs_test_opt(root, NODATACOW))
5823 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5824 BTRFS_INODE_NODATASUM;
5827 inode_tree_add(inode);
5829 trace_btrfs_inode_new(inode);
5830 btrfs_set_inode_last_trans(trans, inode);
5832 btrfs_update_root_times(trans, root);
5834 ret = btrfs_inode_inherit_props(trans, inode, dir);
5835 if (ret)
5836 btrfs_err(root->fs_info,
5837 "error inheriting props for ino %llu (root %llu): %d",
5838 btrfs_ino(inode), root->root_key.objectid, ret);
5840 return inode;
5842 fail_unlock:
5843 unlock_new_inode(inode);
5844 fail:
5845 if (dir && name)
5846 BTRFS_I(dir)->index_cnt--;
5847 btrfs_free_path(path);
5848 iput(inode);
5849 return ERR_PTR(ret);
5852 static inline u8 btrfs_inode_type(struct inode *inode)
5854 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5858 * utility function to add 'inode' into 'parent_inode' with
5859 * a give name and a given sequence number.
5860 * if 'add_backref' is true, also insert a backref from the
5861 * inode to the parent directory.
5863 int btrfs_add_link(struct btrfs_trans_handle *trans,
5864 struct inode *parent_inode, struct inode *inode,
5865 const char *name, int name_len, int add_backref, u64 index)
5867 int ret = 0;
5868 struct btrfs_key key;
5869 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5870 u64 ino = btrfs_ino(inode);
5871 u64 parent_ino = btrfs_ino(parent_inode);
5873 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5874 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5875 } else {
5876 key.objectid = ino;
5877 key.type = BTRFS_INODE_ITEM_KEY;
5878 key.offset = 0;
5881 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5882 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5883 key.objectid, root->root_key.objectid,
5884 parent_ino, index, name, name_len);
5885 } else if (add_backref) {
5886 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5887 parent_ino, index);
5890 /* Nothing to clean up yet */
5891 if (ret)
5892 return ret;
5894 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5895 parent_inode, &key,
5896 btrfs_inode_type(inode), index);
5897 if (ret == -EEXIST || ret == -EOVERFLOW)
5898 goto fail_dir_item;
5899 else if (ret) {
5900 btrfs_abort_transaction(trans, root, ret);
5901 return ret;
5904 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5905 name_len * 2);
5906 inode_inc_iversion(parent_inode);
5907 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5908 ret = btrfs_update_inode(trans, root, parent_inode);
5909 if (ret)
5910 btrfs_abort_transaction(trans, root, ret);
5911 return ret;
5913 fail_dir_item:
5914 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5915 u64 local_index;
5916 int err;
5917 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5918 key.objectid, root->root_key.objectid,
5919 parent_ino, &local_index, name, name_len);
5921 } else if (add_backref) {
5922 u64 local_index;
5923 int err;
5925 err = btrfs_del_inode_ref(trans, root, name, name_len,
5926 ino, parent_ino, &local_index);
5928 return ret;
5931 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5932 struct inode *dir, struct dentry *dentry,
5933 struct inode *inode, int backref, u64 index)
5935 int err = btrfs_add_link(trans, dir, inode,
5936 dentry->d_name.name, dentry->d_name.len,
5937 backref, index);
5938 if (err > 0)
5939 err = -EEXIST;
5940 return err;
5943 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5944 umode_t mode, dev_t rdev)
5946 struct btrfs_trans_handle *trans;
5947 struct btrfs_root *root = BTRFS_I(dir)->root;
5948 struct inode *inode = NULL;
5949 int err;
5950 int drop_inode = 0;
5951 u64 objectid;
5952 u64 index = 0;
5954 if (!new_valid_dev(rdev))
5955 return -EINVAL;
5958 * 2 for inode item and ref
5959 * 2 for dir items
5960 * 1 for xattr if selinux is on
5962 trans = btrfs_start_transaction(root, 5);
5963 if (IS_ERR(trans))
5964 return PTR_ERR(trans);
5966 err = btrfs_find_free_ino(root, &objectid);
5967 if (err)
5968 goto out_unlock;
5970 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5971 dentry->d_name.len, btrfs_ino(dir), objectid,
5972 mode, &index);
5973 if (IS_ERR(inode)) {
5974 err = PTR_ERR(inode);
5975 goto out_unlock;
5979 * If the active LSM wants to access the inode during
5980 * d_instantiate it needs these. Smack checks to see
5981 * if the filesystem supports xattrs by looking at the
5982 * ops vector.
5984 inode->i_op = &btrfs_special_inode_operations;
5985 init_special_inode(inode, inode->i_mode, rdev);
5987 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5988 if (err)
5989 goto out_unlock_inode;
5991 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5992 if (err) {
5993 goto out_unlock_inode;
5994 } else {
5995 btrfs_update_inode(trans, root, inode);
5996 unlock_new_inode(inode);
5997 d_instantiate(dentry, inode);
6000 out_unlock:
6001 btrfs_end_transaction(trans, root);
6002 btrfs_balance_delayed_items(root);
6003 btrfs_btree_balance_dirty(root);
6004 if (drop_inode) {
6005 inode_dec_link_count(inode);
6006 iput(inode);
6008 return err;
6010 out_unlock_inode:
6011 drop_inode = 1;
6012 unlock_new_inode(inode);
6013 goto out_unlock;
6017 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6018 umode_t mode, bool excl)
6020 struct btrfs_trans_handle *trans;
6021 struct btrfs_root *root = BTRFS_I(dir)->root;
6022 struct inode *inode = NULL;
6023 int drop_inode_on_err = 0;
6024 int err;
6025 u64 objectid;
6026 u64 index = 0;
6029 * 2 for inode item and ref
6030 * 2 for dir items
6031 * 1 for xattr if selinux is on
6033 trans = btrfs_start_transaction(root, 5);
6034 if (IS_ERR(trans))
6035 return PTR_ERR(trans);
6037 err = btrfs_find_free_ino(root, &objectid);
6038 if (err)
6039 goto out_unlock;
6041 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6042 dentry->d_name.len, btrfs_ino(dir), objectid,
6043 mode, &index);
6044 if (IS_ERR(inode)) {
6045 err = PTR_ERR(inode);
6046 goto out_unlock;
6048 drop_inode_on_err = 1;
6050 * If the active LSM wants to access the inode during
6051 * d_instantiate it needs these. Smack checks to see
6052 * if the filesystem supports xattrs by looking at the
6053 * ops vector.
6055 inode->i_fop = &btrfs_file_operations;
6056 inode->i_op = &btrfs_file_inode_operations;
6057 inode->i_mapping->a_ops = &btrfs_aops;
6058 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6060 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6061 if (err)
6062 goto out_unlock_inode;
6064 err = btrfs_update_inode(trans, root, inode);
6065 if (err)
6066 goto out_unlock_inode;
6068 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6069 if (err)
6070 goto out_unlock_inode;
6072 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6073 unlock_new_inode(inode);
6074 d_instantiate(dentry, inode);
6076 out_unlock:
6077 btrfs_end_transaction(trans, root);
6078 if (err && drop_inode_on_err) {
6079 inode_dec_link_count(inode);
6080 iput(inode);
6082 btrfs_balance_delayed_items(root);
6083 btrfs_btree_balance_dirty(root);
6084 return err;
6086 out_unlock_inode:
6087 unlock_new_inode(inode);
6088 goto out_unlock;
6092 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6093 struct dentry *dentry)
6095 struct btrfs_trans_handle *trans = NULL;
6096 struct btrfs_root *root = BTRFS_I(dir)->root;
6097 struct inode *inode = old_dentry->d_inode;
6098 u64 index;
6099 int err;
6100 int drop_inode = 0;
6102 /* do not allow sys_link's with other subvols of the same device */
6103 if (root->objectid != BTRFS_I(inode)->root->objectid)
6104 return -EXDEV;
6106 if (inode->i_nlink >= BTRFS_LINK_MAX)
6107 return -EMLINK;
6109 err = btrfs_set_inode_index(dir, &index);
6110 if (err)
6111 goto fail;
6114 * 2 items for inode and inode ref
6115 * 2 items for dir items
6116 * 1 item for parent inode
6118 trans = btrfs_start_transaction(root, 5);
6119 if (IS_ERR(trans)) {
6120 err = PTR_ERR(trans);
6121 trans = NULL;
6122 goto fail;
6125 /* There are several dir indexes for this inode, clear the cache. */
6126 BTRFS_I(inode)->dir_index = 0ULL;
6127 inc_nlink(inode);
6128 inode_inc_iversion(inode);
6129 inode->i_ctime = CURRENT_TIME;
6130 ihold(inode);
6131 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6133 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6135 if (err) {
6136 drop_inode = 1;
6137 } else {
6138 struct dentry *parent = dentry->d_parent;
6139 err = btrfs_update_inode(trans, root, inode);
6140 if (err)
6141 goto fail;
6142 if (inode->i_nlink == 1) {
6144 * If new hard link count is 1, it's a file created
6145 * with open(2) O_TMPFILE flag.
6147 err = btrfs_orphan_del(trans, inode);
6148 if (err)
6149 goto fail;
6151 d_instantiate(dentry, inode);
6152 btrfs_log_new_name(trans, inode, NULL, parent);
6155 btrfs_balance_delayed_items(root);
6156 fail:
6157 if (trans)
6158 btrfs_end_transaction(trans, root);
6159 if (drop_inode) {
6160 inode_dec_link_count(inode);
6161 iput(inode);
6163 btrfs_btree_balance_dirty(root);
6164 return err;
6167 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6169 struct inode *inode = NULL;
6170 struct btrfs_trans_handle *trans;
6171 struct btrfs_root *root = BTRFS_I(dir)->root;
6172 int err = 0;
6173 int drop_on_err = 0;
6174 u64 objectid = 0;
6175 u64 index = 0;
6178 * 2 items for inode and ref
6179 * 2 items for dir items
6180 * 1 for xattr if selinux is on
6182 trans = btrfs_start_transaction(root, 5);
6183 if (IS_ERR(trans))
6184 return PTR_ERR(trans);
6186 err = btrfs_find_free_ino(root, &objectid);
6187 if (err)
6188 goto out_fail;
6190 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6191 dentry->d_name.len, btrfs_ino(dir), objectid,
6192 S_IFDIR | mode, &index);
6193 if (IS_ERR(inode)) {
6194 err = PTR_ERR(inode);
6195 goto out_fail;
6198 drop_on_err = 1;
6199 /* these must be set before we unlock the inode */
6200 inode->i_op = &btrfs_dir_inode_operations;
6201 inode->i_fop = &btrfs_dir_file_operations;
6203 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6204 if (err)
6205 goto out_fail_inode;
6207 btrfs_i_size_write(inode, 0);
6208 err = btrfs_update_inode(trans, root, inode);
6209 if (err)
6210 goto out_fail_inode;
6212 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6213 dentry->d_name.len, 0, index);
6214 if (err)
6215 goto out_fail_inode;
6217 d_instantiate(dentry, inode);
6219 * mkdir is special. We're unlocking after we call d_instantiate
6220 * to avoid a race with nfsd calling d_instantiate.
6222 unlock_new_inode(inode);
6223 drop_on_err = 0;
6225 out_fail:
6226 btrfs_end_transaction(trans, root);
6227 if (drop_on_err)
6228 iput(inode);
6229 btrfs_balance_delayed_items(root);
6230 btrfs_btree_balance_dirty(root);
6231 return err;
6233 out_fail_inode:
6234 unlock_new_inode(inode);
6235 goto out_fail;
6238 /* Find next extent map of a given extent map, caller needs to ensure locks */
6239 static struct extent_map *next_extent_map(struct extent_map *em)
6241 struct rb_node *next;
6243 next = rb_next(&em->rb_node);
6244 if (!next)
6245 return NULL;
6246 return container_of(next, struct extent_map, rb_node);
6249 static struct extent_map *prev_extent_map(struct extent_map *em)
6251 struct rb_node *prev;
6253 prev = rb_prev(&em->rb_node);
6254 if (!prev)
6255 return NULL;
6256 return container_of(prev, struct extent_map, rb_node);
6259 /* helper for btfs_get_extent. Given an existing extent in the tree,
6260 * the existing extent is the nearest extent to map_start,
6261 * and an extent that you want to insert, deal with overlap and insert
6262 * the best fitted new extent into the tree.
6264 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6265 struct extent_map *existing,
6266 struct extent_map *em,
6267 u64 map_start)
6269 struct extent_map *prev;
6270 struct extent_map *next;
6271 u64 start;
6272 u64 end;
6273 u64 start_diff;
6275 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6277 if (existing->start > map_start) {
6278 next = existing;
6279 prev = prev_extent_map(next);
6280 } else {
6281 prev = existing;
6282 next = next_extent_map(prev);
6285 start = prev ? extent_map_end(prev) : em->start;
6286 start = max_t(u64, start, em->start);
6287 end = next ? next->start : extent_map_end(em);
6288 end = min_t(u64, end, extent_map_end(em));
6289 start_diff = start - em->start;
6290 em->start = start;
6291 em->len = end - start;
6292 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6293 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6294 em->block_start += start_diff;
6295 em->block_len -= start_diff;
6297 return add_extent_mapping(em_tree, em, 0);
6300 static noinline int uncompress_inline(struct btrfs_path *path,
6301 struct inode *inode, struct page *page,
6302 size_t pg_offset, u64 extent_offset,
6303 struct btrfs_file_extent_item *item)
6305 int ret;
6306 struct extent_buffer *leaf = path->nodes[0];
6307 char *tmp;
6308 size_t max_size;
6309 unsigned long inline_size;
6310 unsigned long ptr;
6311 int compress_type;
6313 WARN_ON(pg_offset != 0);
6314 compress_type = btrfs_file_extent_compression(leaf, item);
6315 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6316 inline_size = btrfs_file_extent_inline_item_len(leaf,
6317 btrfs_item_nr(path->slots[0]));
6318 tmp = kmalloc(inline_size, GFP_NOFS);
6319 if (!tmp)
6320 return -ENOMEM;
6321 ptr = btrfs_file_extent_inline_start(item);
6323 read_extent_buffer(leaf, tmp, ptr, inline_size);
6325 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6326 ret = btrfs_decompress(compress_type, tmp, page,
6327 extent_offset, inline_size, max_size);
6328 kfree(tmp);
6329 return ret;
6333 * a bit scary, this does extent mapping from logical file offset to the disk.
6334 * the ugly parts come from merging extents from the disk with the in-ram
6335 * representation. This gets more complex because of the data=ordered code,
6336 * where the in-ram extents might be locked pending data=ordered completion.
6338 * This also copies inline extents directly into the page.
6341 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6342 size_t pg_offset, u64 start, u64 len,
6343 int create)
6345 int ret;
6346 int err = 0;
6347 u64 extent_start = 0;
6348 u64 extent_end = 0;
6349 u64 objectid = btrfs_ino(inode);
6350 u32 found_type;
6351 struct btrfs_path *path = NULL;
6352 struct btrfs_root *root = BTRFS_I(inode)->root;
6353 struct btrfs_file_extent_item *item;
6354 struct extent_buffer *leaf;
6355 struct btrfs_key found_key;
6356 struct extent_map *em = NULL;
6357 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6358 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6359 struct btrfs_trans_handle *trans = NULL;
6360 const bool new_inline = !page || create;
6362 again:
6363 read_lock(&em_tree->lock);
6364 em = lookup_extent_mapping(em_tree, start, len);
6365 if (em)
6366 em->bdev = root->fs_info->fs_devices->latest_bdev;
6367 read_unlock(&em_tree->lock);
6369 if (em) {
6370 if (em->start > start || em->start + em->len <= start)
6371 free_extent_map(em);
6372 else if (em->block_start == EXTENT_MAP_INLINE && page)
6373 free_extent_map(em);
6374 else
6375 goto out;
6377 em = alloc_extent_map();
6378 if (!em) {
6379 err = -ENOMEM;
6380 goto out;
6382 em->bdev = root->fs_info->fs_devices->latest_bdev;
6383 em->start = EXTENT_MAP_HOLE;
6384 em->orig_start = EXTENT_MAP_HOLE;
6385 em->len = (u64)-1;
6386 em->block_len = (u64)-1;
6388 if (!path) {
6389 path = btrfs_alloc_path();
6390 if (!path) {
6391 err = -ENOMEM;
6392 goto out;
6395 * Chances are we'll be called again, so go ahead and do
6396 * readahead
6398 path->reada = 1;
6401 ret = btrfs_lookup_file_extent(trans, root, path,
6402 objectid, start, trans != NULL);
6403 if (ret < 0) {
6404 err = ret;
6405 goto out;
6408 if (ret != 0) {
6409 if (path->slots[0] == 0)
6410 goto not_found;
6411 path->slots[0]--;
6414 leaf = path->nodes[0];
6415 item = btrfs_item_ptr(leaf, path->slots[0],
6416 struct btrfs_file_extent_item);
6417 /* are we inside the extent that was found? */
6418 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6419 found_type = found_key.type;
6420 if (found_key.objectid != objectid ||
6421 found_type != BTRFS_EXTENT_DATA_KEY) {
6423 * If we backup past the first extent we want to move forward
6424 * and see if there is an extent in front of us, otherwise we'll
6425 * say there is a hole for our whole search range which can
6426 * cause problems.
6428 extent_end = start;
6429 goto next;
6432 found_type = btrfs_file_extent_type(leaf, item);
6433 extent_start = found_key.offset;
6434 if (found_type == BTRFS_FILE_EXTENT_REG ||
6435 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6436 extent_end = extent_start +
6437 btrfs_file_extent_num_bytes(leaf, item);
6438 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6439 size_t size;
6440 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6441 extent_end = ALIGN(extent_start + size, root->sectorsize);
6443 next:
6444 if (start >= extent_end) {
6445 path->slots[0]++;
6446 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6447 ret = btrfs_next_leaf(root, path);
6448 if (ret < 0) {
6449 err = ret;
6450 goto out;
6452 if (ret > 0)
6453 goto not_found;
6454 leaf = path->nodes[0];
6456 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6457 if (found_key.objectid != objectid ||
6458 found_key.type != BTRFS_EXTENT_DATA_KEY)
6459 goto not_found;
6460 if (start + len <= found_key.offset)
6461 goto not_found;
6462 if (start > found_key.offset)
6463 goto next;
6464 em->start = start;
6465 em->orig_start = start;
6466 em->len = found_key.offset - start;
6467 goto not_found_em;
6470 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6472 if (found_type == BTRFS_FILE_EXTENT_REG ||
6473 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6474 goto insert;
6475 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6476 unsigned long ptr;
6477 char *map;
6478 size_t size;
6479 size_t extent_offset;
6480 size_t copy_size;
6482 if (new_inline)
6483 goto out;
6485 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6486 extent_offset = page_offset(page) + pg_offset - extent_start;
6487 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6488 size - extent_offset);
6489 em->start = extent_start + extent_offset;
6490 em->len = ALIGN(copy_size, root->sectorsize);
6491 em->orig_block_len = em->len;
6492 em->orig_start = em->start;
6493 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6494 if (create == 0 && !PageUptodate(page)) {
6495 if (btrfs_file_extent_compression(leaf, item) !=
6496 BTRFS_COMPRESS_NONE) {
6497 ret = uncompress_inline(path, inode, page,
6498 pg_offset,
6499 extent_offset, item);
6500 if (ret) {
6501 err = ret;
6502 goto out;
6504 } else {
6505 map = kmap(page);
6506 read_extent_buffer(leaf, map + pg_offset, ptr,
6507 copy_size);
6508 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6509 memset(map + pg_offset + copy_size, 0,
6510 PAGE_CACHE_SIZE - pg_offset -
6511 copy_size);
6513 kunmap(page);
6515 flush_dcache_page(page);
6516 } else if (create && PageUptodate(page)) {
6517 BUG();
6518 if (!trans) {
6519 kunmap(page);
6520 free_extent_map(em);
6521 em = NULL;
6523 btrfs_release_path(path);
6524 trans = btrfs_join_transaction(root);
6526 if (IS_ERR(trans))
6527 return ERR_CAST(trans);
6528 goto again;
6530 map = kmap(page);
6531 write_extent_buffer(leaf, map + pg_offset, ptr,
6532 copy_size);
6533 kunmap(page);
6534 btrfs_mark_buffer_dirty(leaf);
6536 set_extent_uptodate(io_tree, em->start,
6537 extent_map_end(em) - 1, NULL, GFP_NOFS);
6538 goto insert;
6540 not_found:
6541 em->start = start;
6542 em->orig_start = start;
6543 em->len = len;
6544 not_found_em:
6545 em->block_start = EXTENT_MAP_HOLE;
6546 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6547 insert:
6548 btrfs_release_path(path);
6549 if (em->start > start || extent_map_end(em) <= start) {
6550 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6551 em->start, em->len, start, len);
6552 err = -EIO;
6553 goto out;
6556 err = 0;
6557 write_lock(&em_tree->lock);
6558 ret = add_extent_mapping(em_tree, em, 0);
6559 /* it is possible that someone inserted the extent into the tree
6560 * while we had the lock dropped. It is also possible that
6561 * an overlapping map exists in the tree
6563 if (ret == -EEXIST) {
6564 struct extent_map *existing;
6566 ret = 0;
6568 existing = search_extent_mapping(em_tree, start, len);
6570 * existing will always be non-NULL, since there must be
6571 * extent causing the -EEXIST.
6573 if (start >= extent_map_end(existing) ||
6574 start <= existing->start) {
6576 * The existing extent map is the one nearest to
6577 * the [start, start + len) range which overlaps
6579 err = merge_extent_mapping(em_tree, existing,
6580 em, start);
6581 free_extent_map(existing);
6582 if (err) {
6583 free_extent_map(em);
6584 em = NULL;
6586 } else {
6587 free_extent_map(em);
6588 em = existing;
6589 err = 0;
6592 write_unlock(&em_tree->lock);
6593 out:
6595 trace_btrfs_get_extent(root, em);
6597 if (path)
6598 btrfs_free_path(path);
6599 if (trans) {
6600 ret = btrfs_end_transaction(trans, root);
6601 if (!err)
6602 err = ret;
6604 if (err) {
6605 free_extent_map(em);
6606 return ERR_PTR(err);
6608 BUG_ON(!em); /* Error is always set */
6609 return em;
6612 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6613 size_t pg_offset, u64 start, u64 len,
6614 int create)
6616 struct extent_map *em;
6617 struct extent_map *hole_em = NULL;
6618 u64 range_start = start;
6619 u64 end;
6620 u64 found;
6621 u64 found_end;
6622 int err = 0;
6624 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6625 if (IS_ERR(em))
6626 return em;
6627 if (em) {
6629 * if our em maps to
6630 * - a hole or
6631 * - a pre-alloc extent,
6632 * there might actually be delalloc bytes behind it.
6634 if (em->block_start != EXTENT_MAP_HOLE &&
6635 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6636 return em;
6637 else
6638 hole_em = em;
6641 /* check to see if we've wrapped (len == -1 or similar) */
6642 end = start + len;
6643 if (end < start)
6644 end = (u64)-1;
6645 else
6646 end -= 1;
6648 em = NULL;
6650 /* ok, we didn't find anything, lets look for delalloc */
6651 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6652 end, len, EXTENT_DELALLOC, 1);
6653 found_end = range_start + found;
6654 if (found_end < range_start)
6655 found_end = (u64)-1;
6658 * we didn't find anything useful, return
6659 * the original results from get_extent()
6661 if (range_start > end || found_end <= start) {
6662 em = hole_em;
6663 hole_em = NULL;
6664 goto out;
6667 /* adjust the range_start to make sure it doesn't
6668 * go backwards from the start they passed in
6670 range_start = max(start, range_start);
6671 found = found_end - range_start;
6673 if (found > 0) {
6674 u64 hole_start = start;
6675 u64 hole_len = len;
6677 em = alloc_extent_map();
6678 if (!em) {
6679 err = -ENOMEM;
6680 goto out;
6683 * when btrfs_get_extent can't find anything it
6684 * returns one huge hole
6686 * make sure what it found really fits our range, and
6687 * adjust to make sure it is based on the start from
6688 * the caller
6690 if (hole_em) {
6691 u64 calc_end = extent_map_end(hole_em);
6693 if (calc_end <= start || (hole_em->start > end)) {
6694 free_extent_map(hole_em);
6695 hole_em = NULL;
6696 } else {
6697 hole_start = max(hole_em->start, start);
6698 hole_len = calc_end - hole_start;
6701 em->bdev = NULL;
6702 if (hole_em && range_start > hole_start) {
6703 /* our hole starts before our delalloc, so we
6704 * have to return just the parts of the hole
6705 * that go until the delalloc starts
6707 em->len = min(hole_len,
6708 range_start - hole_start);
6709 em->start = hole_start;
6710 em->orig_start = hole_start;
6712 * don't adjust block start at all,
6713 * it is fixed at EXTENT_MAP_HOLE
6715 em->block_start = hole_em->block_start;
6716 em->block_len = hole_len;
6717 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6718 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6719 } else {
6720 em->start = range_start;
6721 em->len = found;
6722 em->orig_start = range_start;
6723 em->block_start = EXTENT_MAP_DELALLOC;
6724 em->block_len = found;
6726 } else if (hole_em) {
6727 return hole_em;
6729 out:
6731 free_extent_map(hole_em);
6732 if (err) {
6733 free_extent_map(em);
6734 return ERR_PTR(err);
6736 return em;
6739 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6740 u64 start, u64 len)
6742 struct btrfs_root *root = BTRFS_I(inode)->root;
6743 struct extent_map *em;
6744 struct btrfs_key ins;
6745 u64 alloc_hint;
6746 int ret;
6748 alloc_hint = get_extent_allocation_hint(inode, start, len);
6749 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6750 alloc_hint, &ins, 1, 1);
6751 if (ret)
6752 return ERR_PTR(ret);
6754 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6755 ins.offset, ins.offset, ins.offset, 0);
6756 if (IS_ERR(em)) {
6757 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6758 return em;
6761 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6762 ins.offset, ins.offset, 0);
6763 if (ret) {
6764 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6765 free_extent_map(em);
6766 return ERR_PTR(ret);
6769 return em;
6773 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6774 * block must be cow'd
6776 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6777 u64 *orig_start, u64 *orig_block_len,
6778 u64 *ram_bytes)
6780 struct btrfs_trans_handle *trans;
6781 struct btrfs_path *path;
6782 int ret;
6783 struct extent_buffer *leaf;
6784 struct btrfs_root *root = BTRFS_I(inode)->root;
6785 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6786 struct btrfs_file_extent_item *fi;
6787 struct btrfs_key key;
6788 u64 disk_bytenr;
6789 u64 backref_offset;
6790 u64 extent_end;
6791 u64 num_bytes;
6792 int slot;
6793 int found_type;
6794 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6796 path = btrfs_alloc_path();
6797 if (!path)
6798 return -ENOMEM;
6800 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6801 offset, 0);
6802 if (ret < 0)
6803 goto out;
6805 slot = path->slots[0];
6806 if (ret == 1) {
6807 if (slot == 0) {
6808 /* can't find the item, must cow */
6809 ret = 0;
6810 goto out;
6812 slot--;
6814 ret = 0;
6815 leaf = path->nodes[0];
6816 btrfs_item_key_to_cpu(leaf, &key, slot);
6817 if (key.objectid != btrfs_ino(inode) ||
6818 key.type != BTRFS_EXTENT_DATA_KEY) {
6819 /* not our file or wrong item type, must cow */
6820 goto out;
6823 if (key.offset > offset) {
6824 /* Wrong offset, must cow */
6825 goto out;
6828 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6829 found_type = btrfs_file_extent_type(leaf, fi);
6830 if (found_type != BTRFS_FILE_EXTENT_REG &&
6831 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6832 /* not a regular extent, must cow */
6833 goto out;
6836 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6837 goto out;
6839 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6840 if (extent_end <= offset)
6841 goto out;
6843 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6844 if (disk_bytenr == 0)
6845 goto out;
6847 if (btrfs_file_extent_compression(leaf, fi) ||
6848 btrfs_file_extent_encryption(leaf, fi) ||
6849 btrfs_file_extent_other_encoding(leaf, fi))
6850 goto out;
6852 backref_offset = btrfs_file_extent_offset(leaf, fi);
6854 if (orig_start) {
6855 *orig_start = key.offset - backref_offset;
6856 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6857 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6860 if (btrfs_extent_readonly(root, disk_bytenr))
6861 goto out;
6863 num_bytes = min(offset + *len, extent_end) - offset;
6864 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6865 u64 range_end;
6867 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6868 ret = test_range_bit(io_tree, offset, range_end,
6869 EXTENT_DELALLOC, 0, NULL);
6870 if (ret) {
6871 ret = -EAGAIN;
6872 goto out;
6876 btrfs_release_path(path);
6879 * look for other files referencing this extent, if we
6880 * find any we must cow
6882 trans = btrfs_join_transaction(root);
6883 if (IS_ERR(trans)) {
6884 ret = 0;
6885 goto out;
6888 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6889 key.offset - backref_offset, disk_bytenr);
6890 btrfs_end_transaction(trans, root);
6891 if (ret) {
6892 ret = 0;
6893 goto out;
6897 * adjust disk_bytenr and num_bytes to cover just the bytes
6898 * in this extent we are about to write. If there
6899 * are any csums in that range we have to cow in order
6900 * to keep the csums correct
6902 disk_bytenr += backref_offset;
6903 disk_bytenr += offset - key.offset;
6904 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6905 goto out;
6907 * all of the above have passed, it is safe to overwrite this extent
6908 * without cow
6910 *len = num_bytes;
6911 ret = 1;
6912 out:
6913 btrfs_free_path(path);
6914 return ret;
6917 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
6919 struct radix_tree_root *root = &inode->i_mapping->page_tree;
6920 int found = false;
6921 void **pagep = NULL;
6922 struct page *page = NULL;
6923 int start_idx;
6924 int end_idx;
6926 start_idx = start >> PAGE_CACHE_SHIFT;
6929 * end is the last byte in the last page. end == start is legal
6931 end_idx = end >> PAGE_CACHE_SHIFT;
6933 rcu_read_lock();
6935 /* Most of the code in this while loop is lifted from
6936 * find_get_page. It's been modified to begin searching from a
6937 * page and return just the first page found in that range. If the
6938 * found idx is less than or equal to the end idx then we know that
6939 * a page exists. If no pages are found or if those pages are
6940 * outside of the range then we're fine (yay!) */
6941 while (page == NULL &&
6942 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
6943 page = radix_tree_deref_slot(pagep);
6944 if (unlikely(!page))
6945 break;
6947 if (radix_tree_exception(page)) {
6948 if (radix_tree_deref_retry(page)) {
6949 page = NULL;
6950 continue;
6953 * Otherwise, shmem/tmpfs must be storing a swap entry
6954 * here as an exceptional entry: so return it without
6955 * attempting to raise page count.
6957 page = NULL;
6958 break; /* TODO: Is this relevant for this use case? */
6961 if (!page_cache_get_speculative(page)) {
6962 page = NULL;
6963 continue;
6967 * Has the page moved?
6968 * This is part of the lockless pagecache protocol. See
6969 * include/linux/pagemap.h for details.
6971 if (unlikely(page != *pagep)) {
6972 page_cache_release(page);
6973 page = NULL;
6977 if (page) {
6978 if (page->index <= end_idx)
6979 found = true;
6980 page_cache_release(page);
6983 rcu_read_unlock();
6984 return found;
6987 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6988 struct extent_state **cached_state, int writing)
6990 struct btrfs_ordered_extent *ordered;
6991 int ret = 0;
6993 while (1) {
6994 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6995 0, cached_state);
6997 * We're concerned with the entire range that we're going to be
6998 * doing DIO to, so we need to make sure theres no ordered
6999 * extents in this range.
7001 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7002 lockend - lockstart + 1);
7005 * We need to make sure there are no buffered pages in this
7006 * range either, we could have raced between the invalidate in
7007 * generic_file_direct_write and locking the extent. The
7008 * invalidate needs to happen so that reads after a write do not
7009 * get stale data.
7011 if (!ordered &&
7012 (!writing ||
7013 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7014 break;
7016 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7017 cached_state, GFP_NOFS);
7019 if (ordered) {
7020 btrfs_start_ordered_extent(inode, ordered, 1);
7021 btrfs_put_ordered_extent(ordered);
7022 } else {
7023 /* Screw you mmap */
7024 ret = filemap_write_and_wait_range(inode->i_mapping,
7025 lockstart,
7026 lockend);
7027 if (ret)
7028 break;
7031 * If we found a page that couldn't be invalidated just
7032 * fall back to buffered.
7034 ret = invalidate_inode_pages2_range(inode->i_mapping,
7035 lockstart >> PAGE_CACHE_SHIFT,
7036 lockend >> PAGE_CACHE_SHIFT);
7037 if (ret)
7038 break;
7041 cond_resched();
7044 return ret;
7047 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7048 u64 len, u64 orig_start,
7049 u64 block_start, u64 block_len,
7050 u64 orig_block_len, u64 ram_bytes,
7051 int type)
7053 struct extent_map_tree *em_tree;
7054 struct extent_map *em;
7055 struct btrfs_root *root = BTRFS_I(inode)->root;
7056 int ret;
7058 em_tree = &BTRFS_I(inode)->extent_tree;
7059 em = alloc_extent_map();
7060 if (!em)
7061 return ERR_PTR(-ENOMEM);
7063 em->start = start;
7064 em->orig_start = orig_start;
7065 em->mod_start = start;
7066 em->mod_len = len;
7067 em->len = len;
7068 em->block_len = block_len;
7069 em->block_start = block_start;
7070 em->bdev = root->fs_info->fs_devices->latest_bdev;
7071 em->orig_block_len = orig_block_len;
7072 em->ram_bytes = ram_bytes;
7073 em->generation = -1;
7074 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7075 if (type == BTRFS_ORDERED_PREALLOC)
7076 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7078 do {
7079 btrfs_drop_extent_cache(inode, em->start,
7080 em->start + em->len - 1, 0);
7081 write_lock(&em_tree->lock);
7082 ret = add_extent_mapping(em_tree, em, 1);
7083 write_unlock(&em_tree->lock);
7084 } while (ret == -EEXIST);
7086 if (ret) {
7087 free_extent_map(em);
7088 return ERR_PTR(ret);
7091 return em;
7095 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7096 struct buffer_head *bh_result, int create)
7098 struct extent_map *em;
7099 struct btrfs_root *root = BTRFS_I(inode)->root;
7100 struct extent_state *cached_state = NULL;
7101 u64 start = iblock << inode->i_blkbits;
7102 u64 lockstart, lockend;
7103 u64 len = bh_result->b_size;
7104 int unlock_bits = EXTENT_LOCKED;
7105 int ret = 0;
7107 if (create)
7108 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
7109 else
7110 len = min_t(u64, len, root->sectorsize);
7112 lockstart = start;
7113 lockend = start + len - 1;
7116 * If this errors out it's because we couldn't invalidate pagecache for
7117 * this range and we need to fallback to buffered.
7119 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7120 return -ENOTBLK;
7122 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7123 if (IS_ERR(em)) {
7124 ret = PTR_ERR(em);
7125 goto unlock_err;
7129 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7130 * io. INLINE is special, and we could probably kludge it in here, but
7131 * it's still buffered so for safety lets just fall back to the generic
7132 * buffered path.
7134 * For COMPRESSED we _have_ to read the entire extent in so we can
7135 * decompress it, so there will be buffering required no matter what we
7136 * do, so go ahead and fallback to buffered.
7138 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7139 * to buffered IO. Don't blame me, this is the price we pay for using
7140 * the generic code.
7142 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7143 em->block_start == EXTENT_MAP_INLINE) {
7144 free_extent_map(em);
7145 ret = -ENOTBLK;
7146 goto unlock_err;
7149 /* Just a good old fashioned hole, return */
7150 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7151 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7152 free_extent_map(em);
7153 goto unlock_err;
7157 * We don't allocate a new extent in the following cases
7159 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7160 * existing extent.
7161 * 2) The extent is marked as PREALLOC. We're good to go here and can
7162 * just use the extent.
7165 if (!create) {
7166 len = min(len, em->len - (start - em->start));
7167 lockstart = start + len;
7168 goto unlock;
7171 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7172 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7173 em->block_start != EXTENT_MAP_HOLE)) {
7174 int type;
7175 u64 block_start, orig_start, orig_block_len, ram_bytes;
7177 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7178 type = BTRFS_ORDERED_PREALLOC;
7179 else
7180 type = BTRFS_ORDERED_NOCOW;
7181 len = min(len, em->len - (start - em->start));
7182 block_start = em->block_start + (start - em->start);
7184 if (can_nocow_extent(inode, start, &len, &orig_start,
7185 &orig_block_len, &ram_bytes) == 1) {
7186 if (type == BTRFS_ORDERED_PREALLOC) {
7187 free_extent_map(em);
7188 em = create_pinned_em(inode, start, len,
7189 orig_start,
7190 block_start, len,
7191 orig_block_len,
7192 ram_bytes, type);
7193 if (IS_ERR(em)) {
7194 ret = PTR_ERR(em);
7195 goto unlock_err;
7199 ret = btrfs_add_ordered_extent_dio(inode, start,
7200 block_start, len, len, type);
7201 if (ret) {
7202 free_extent_map(em);
7203 goto unlock_err;
7205 goto unlock;
7210 * this will cow the extent, reset the len in case we changed
7211 * it above
7213 len = bh_result->b_size;
7214 free_extent_map(em);
7215 em = btrfs_new_extent_direct(inode, start, len);
7216 if (IS_ERR(em)) {
7217 ret = PTR_ERR(em);
7218 goto unlock_err;
7220 len = min(len, em->len - (start - em->start));
7221 unlock:
7222 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7223 inode->i_blkbits;
7224 bh_result->b_size = len;
7225 bh_result->b_bdev = em->bdev;
7226 set_buffer_mapped(bh_result);
7227 if (create) {
7228 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7229 set_buffer_new(bh_result);
7232 * Need to update the i_size under the extent lock so buffered
7233 * readers will get the updated i_size when we unlock.
7235 if (start + len > i_size_read(inode))
7236 i_size_write(inode, start + len);
7238 spin_lock(&BTRFS_I(inode)->lock);
7239 BTRFS_I(inode)->outstanding_extents++;
7240 spin_unlock(&BTRFS_I(inode)->lock);
7242 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7243 lockstart + len - 1, EXTENT_DELALLOC, NULL,
7244 &cached_state, GFP_NOFS);
7245 BUG_ON(ret);
7249 * In the case of write we need to clear and unlock the entire range,
7250 * in the case of read we need to unlock only the end area that we
7251 * aren't using if there is any left over space.
7253 if (lockstart < lockend) {
7254 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7255 lockend, unlock_bits, 1, 0,
7256 &cached_state, GFP_NOFS);
7257 } else {
7258 free_extent_state(cached_state);
7261 free_extent_map(em);
7263 return 0;
7265 unlock_err:
7266 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7267 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7268 return ret;
7271 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7272 int rw, int mirror_num)
7274 struct btrfs_root *root = BTRFS_I(inode)->root;
7275 int ret;
7277 BUG_ON(rw & REQ_WRITE);
7279 bio_get(bio);
7281 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7282 BTRFS_WQ_ENDIO_DIO_REPAIR);
7283 if (ret)
7284 goto err;
7286 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7287 err:
7288 bio_put(bio);
7289 return ret;
7292 static int btrfs_check_dio_repairable(struct inode *inode,
7293 struct bio *failed_bio,
7294 struct io_failure_record *failrec,
7295 int failed_mirror)
7297 int num_copies;
7299 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7300 failrec->logical, failrec->len);
7301 if (num_copies == 1) {
7303 * we only have a single copy of the data, so don't bother with
7304 * all the retry and error correction code that follows. no
7305 * matter what the error is, it is very likely to persist.
7307 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7308 num_copies, failrec->this_mirror, failed_mirror);
7309 return 0;
7312 failrec->failed_mirror = failed_mirror;
7313 failrec->this_mirror++;
7314 if (failrec->this_mirror == failed_mirror)
7315 failrec->this_mirror++;
7317 if (failrec->this_mirror > num_copies) {
7318 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7319 num_copies, failrec->this_mirror, failed_mirror);
7320 return 0;
7323 return 1;
7326 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7327 struct page *page, u64 start, u64 end,
7328 int failed_mirror, bio_end_io_t *repair_endio,
7329 void *repair_arg)
7331 struct io_failure_record *failrec;
7332 struct bio *bio;
7333 int isector;
7334 int read_mode;
7335 int ret;
7337 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7339 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7340 if (ret)
7341 return ret;
7343 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7344 failed_mirror);
7345 if (!ret) {
7346 free_io_failure(inode, failrec);
7347 return -EIO;
7350 if (failed_bio->bi_vcnt > 1)
7351 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7352 else
7353 read_mode = READ_SYNC;
7355 isector = start - btrfs_io_bio(failed_bio)->logical;
7356 isector >>= inode->i_sb->s_blocksize_bits;
7357 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7358 0, isector, repair_endio, repair_arg);
7359 if (!bio) {
7360 free_io_failure(inode, failrec);
7361 return -EIO;
7364 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7365 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7366 read_mode, failrec->this_mirror, failrec->in_validation);
7368 ret = submit_dio_repair_bio(inode, bio, read_mode,
7369 failrec->this_mirror);
7370 if (ret) {
7371 free_io_failure(inode, failrec);
7372 bio_put(bio);
7375 return ret;
7378 struct btrfs_retry_complete {
7379 struct completion done;
7380 struct inode *inode;
7381 u64 start;
7382 int uptodate;
7385 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7387 struct btrfs_retry_complete *done = bio->bi_private;
7388 struct bio_vec *bvec;
7389 int i;
7391 if (err)
7392 goto end;
7394 done->uptodate = 1;
7395 bio_for_each_segment_all(bvec, bio, i)
7396 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7397 end:
7398 complete(&done->done);
7399 bio_put(bio);
7402 static int __btrfs_correct_data_nocsum(struct inode *inode,
7403 struct btrfs_io_bio *io_bio)
7405 struct bio_vec *bvec;
7406 struct btrfs_retry_complete done;
7407 u64 start;
7408 int i;
7409 int ret;
7411 start = io_bio->logical;
7412 done.inode = inode;
7414 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7415 try_again:
7416 done.uptodate = 0;
7417 done.start = start;
7418 init_completion(&done.done);
7420 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7421 start + bvec->bv_len - 1,
7422 io_bio->mirror_num,
7423 btrfs_retry_endio_nocsum, &done);
7424 if (ret)
7425 return ret;
7427 wait_for_completion(&done.done);
7429 if (!done.uptodate) {
7430 /* We might have another mirror, so try again */
7431 goto try_again;
7434 start += bvec->bv_len;
7437 return 0;
7440 static void btrfs_retry_endio(struct bio *bio, int err)
7442 struct btrfs_retry_complete *done = bio->bi_private;
7443 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7444 struct bio_vec *bvec;
7445 int uptodate;
7446 int ret;
7447 int i;
7449 if (err)
7450 goto end;
7452 uptodate = 1;
7453 bio_for_each_segment_all(bvec, bio, i) {
7454 ret = __readpage_endio_check(done->inode, io_bio, i,
7455 bvec->bv_page, 0,
7456 done->start, bvec->bv_len);
7457 if (!ret)
7458 clean_io_failure(done->inode, done->start,
7459 bvec->bv_page, 0);
7460 else
7461 uptodate = 0;
7464 done->uptodate = uptodate;
7465 end:
7466 complete(&done->done);
7467 bio_put(bio);
7470 static int __btrfs_subio_endio_read(struct inode *inode,
7471 struct btrfs_io_bio *io_bio, int err)
7473 struct bio_vec *bvec;
7474 struct btrfs_retry_complete done;
7475 u64 start;
7476 u64 offset = 0;
7477 int i;
7478 int ret;
7480 err = 0;
7481 start = io_bio->logical;
7482 done.inode = inode;
7484 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7485 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7486 0, start, bvec->bv_len);
7487 if (likely(!ret))
7488 goto next;
7489 try_again:
7490 done.uptodate = 0;
7491 done.start = start;
7492 init_completion(&done.done);
7494 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7495 start + bvec->bv_len - 1,
7496 io_bio->mirror_num,
7497 btrfs_retry_endio, &done);
7498 if (ret) {
7499 err = ret;
7500 goto next;
7503 wait_for_completion(&done.done);
7505 if (!done.uptodate) {
7506 /* We might have another mirror, so try again */
7507 goto try_again;
7509 next:
7510 offset += bvec->bv_len;
7511 start += bvec->bv_len;
7514 return err;
7517 static int btrfs_subio_endio_read(struct inode *inode,
7518 struct btrfs_io_bio *io_bio, int err)
7520 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7522 if (skip_csum) {
7523 if (unlikely(err))
7524 return __btrfs_correct_data_nocsum(inode, io_bio);
7525 else
7526 return 0;
7527 } else {
7528 return __btrfs_subio_endio_read(inode, io_bio, err);
7532 static void btrfs_endio_direct_read(struct bio *bio, int err)
7534 struct btrfs_dio_private *dip = bio->bi_private;
7535 struct inode *inode = dip->inode;
7536 struct bio *dio_bio;
7537 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7539 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7540 err = btrfs_subio_endio_read(inode, io_bio, err);
7542 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7543 dip->logical_offset + dip->bytes - 1);
7544 dio_bio = dip->dio_bio;
7546 kfree(dip);
7548 /* If we had a csum failure make sure to clear the uptodate flag */
7549 if (err)
7550 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7551 dio_end_io(dio_bio, err);
7553 if (io_bio->end_io)
7554 io_bio->end_io(io_bio, err);
7555 bio_put(bio);
7558 static void btrfs_endio_direct_write(struct bio *bio, int err)
7560 struct btrfs_dio_private *dip = bio->bi_private;
7561 struct inode *inode = dip->inode;
7562 struct btrfs_root *root = BTRFS_I(inode)->root;
7563 struct btrfs_ordered_extent *ordered = NULL;
7564 u64 ordered_offset = dip->logical_offset;
7565 u64 ordered_bytes = dip->bytes;
7566 struct bio *dio_bio;
7567 int ret;
7569 if (err)
7570 goto out_done;
7571 again:
7572 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7573 &ordered_offset,
7574 ordered_bytes, !err);
7575 if (!ret)
7576 goto out_test;
7578 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7579 finish_ordered_fn, NULL, NULL);
7580 btrfs_queue_work(root->fs_info->endio_write_workers,
7581 &ordered->work);
7582 out_test:
7584 * our bio might span multiple ordered extents. If we haven't
7585 * completed the accounting for the whole dio, go back and try again
7587 if (ordered_offset < dip->logical_offset + dip->bytes) {
7588 ordered_bytes = dip->logical_offset + dip->bytes -
7589 ordered_offset;
7590 ordered = NULL;
7591 goto again;
7593 out_done:
7594 dio_bio = dip->dio_bio;
7596 kfree(dip);
7598 /* If we had an error make sure to clear the uptodate flag */
7599 if (err)
7600 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7601 dio_end_io(dio_bio, err);
7602 bio_put(bio);
7605 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7606 struct bio *bio, int mirror_num,
7607 unsigned long bio_flags, u64 offset)
7609 int ret;
7610 struct btrfs_root *root = BTRFS_I(inode)->root;
7611 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7612 BUG_ON(ret); /* -ENOMEM */
7613 return 0;
7616 static void btrfs_end_dio_bio(struct bio *bio, int err)
7618 struct btrfs_dio_private *dip = bio->bi_private;
7620 if (err)
7621 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7622 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7623 btrfs_ino(dip->inode), bio->bi_rw,
7624 (unsigned long long)bio->bi_iter.bi_sector,
7625 bio->bi_iter.bi_size, err);
7627 if (dip->subio_endio)
7628 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7630 if (err) {
7631 dip->errors = 1;
7634 * before atomic variable goto zero, we must make sure
7635 * dip->errors is perceived to be set.
7637 smp_mb__before_atomic();
7640 /* if there are more bios still pending for this dio, just exit */
7641 if (!atomic_dec_and_test(&dip->pending_bios))
7642 goto out;
7644 if (dip->errors) {
7645 bio_io_error(dip->orig_bio);
7646 } else {
7647 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7648 bio_endio(dip->orig_bio, 0);
7650 out:
7651 bio_put(bio);
7654 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7655 u64 first_sector, gfp_t gfp_flags)
7657 int nr_vecs = bio_get_nr_vecs(bdev);
7658 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7661 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7662 struct inode *inode,
7663 struct btrfs_dio_private *dip,
7664 struct bio *bio,
7665 u64 file_offset)
7667 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7668 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7669 int ret;
7672 * We load all the csum data we need when we submit
7673 * the first bio to reduce the csum tree search and
7674 * contention.
7676 if (dip->logical_offset == file_offset) {
7677 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7678 file_offset);
7679 if (ret)
7680 return ret;
7683 if (bio == dip->orig_bio)
7684 return 0;
7686 file_offset -= dip->logical_offset;
7687 file_offset >>= inode->i_sb->s_blocksize_bits;
7688 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7690 return 0;
7693 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7694 int rw, u64 file_offset, int skip_sum,
7695 int async_submit)
7697 struct btrfs_dio_private *dip = bio->bi_private;
7698 int write = rw & REQ_WRITE;
7699 struct btrfs_root *root = BTRFS_I(inode)->root;
7700 int ret;
7702 if (async_submit)
7703 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7705 bio_get(bio);
7707 if (!write) {
7708 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7709 BTRFS_WQ_ENDIO_DATA);
7710 if (ret)
7711 goto err;
7714 if (skip_sum)
7715 goto map;
7717 if (write && async_submit) {
7718 ret = btrfs_wq_submit_bio(root->fs_info,
7719 inode, rw, bio, 0, 0,
7720 file_offset,
7721 __btrfs_submit_bio_start_direct_io,
7722 __btrfs_submit_bio_done);
7723 goto err;
7724 } else if (write) {
7726 * If we aren't doing async submit, calculate the csum of the
7727 * bio now.
7729 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7730 if (ret)
7731 goto err;
7732 } else {
7733 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
7734 file_offset);
7735 if (ret)
7736 goto err;
7738 map:
7739 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7740 err:
7741 bio_put(bio);
7742 return ret;
7745 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7746 int skip_sum)
7748 struct inode *inode = dip->inode;
7749 struct btrfs_root *root = BTRFS_I(inode)->root;
7750 struct bio *bio;
7751 struct bio *orig_bio = dip->orig_bio;
7752 struct bio_vec *bvec = orig_bio->bi_io_vec;
7753 u64 start_sector = orig_bio->bi_iter.bi_sector;
7754 u64 file_offset = dip->logical_offset;
7755 u64 submit_len = 0;
7756 u64 map_length;
7757 int nr_pages = 0;
7758 int ret;
7759 int async_submit = 0;
7761 map_length = orig_bio->bi_iter.bi_size;
7762 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7763 &map_length, NULL, 0);
7764 if (ret)
7765 return -EIO;
7767 if (map_length >= orig_bio->bi_iter.bi_size) {
7768 bio = orig_bio;
7769 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7770 goto submit;
7773 /* async crcs make it difficult to collect full stripe writes. */
7774 if (btrfs_get_alloc_profile(root, 1) &
7775 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7776 async_submit = 0;
7777 else
7778 async_submit = 1;
7780 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7781 if (!bio)
7782 return -ENOMEM;
7784 bio->bi_private = dip;
7785 bio->bi_end_io = btrfs_end_dio_bio;
7786 btrfs_io_bio(bio)->logical = file_offset;
7787 atomic_inc(&dip->pending_bios);
7789 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7790 if (map_length < submit_len + bvec->bv_len ||
7791 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7792 bvec->bv_offset) < bvec->bv_len) {
7794 * inc the count before we submit the bio so
7795 * we know the end IO handler won't happen before
7796 * we inc the count. Otherwise, the dip might get freed
7797 * before we're done setting it up
7799 atomic_inc(&dip->pending_bios);
7800 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7801 file_offset, skip_sum,
7802 async_submit);
7803 if (ret) {
7804 bio_put(bio);
7805 atomic_dec(&dip->pending_bios);
7806 goto out_err;
7809 start_sector += submit_len >> 9;
7810 file_offset += submit_len;
7812 submit_len = 0;
7813 nr_pages = 0;
7815 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7816 start_sector, GFP_NOFS);
7817 if (!bio)
7818 goto out_err;
7819 bio->bi_private = dip;
7820 bio->bi_end_io = btrfs_end_dio_bio;
7821 btrfs_io_bio(bio)->logical = file_offset;
7823 map_length = orig_bio->bi_iter.bi_size;
7824 ret = btrfs_map_block(root->fs_info, rw,
7825 start_sector << 9,
7826 &map_length, NULL, 0);
7827 if (ret) {
7828 bio_put(bio);
7829 goto out_err;
7831 } else {
7832 submit_len += bvec->bv_len;
7833 nr_pages++;
7834 bvec++;
7838 submit:
7839 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7840 async_submit);
7841 if (!ret)
7842 return 0;
7844 bio_put(bio);
7845 out_err:
7846 dip->errors = 1;
7848 * before atomic variable goto zero, we must
7849 * make sure dip->errors is perceived to be set.
7851 smp_mb__before_atomic();
7852 if (atomic_dec_and_test(&dip->pending_bios))
7853 bio_io_error(dip->orig_bio);
7855 /* bio_end_io() will handle error, so we needn't return it */
7856 return 0;
7859 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7860 struct inode *inode, loff_t file_offset)
7862 struct btrfs_root *root = BTRFS_I(inode)->root;
7863 struct btrfs_dio_private *dip;
7864 struct bio *io_bio;
7865 struct btrfs_io_bio *btrfs_bio;
7866 int skip_sum;
7867 int write = rw & REQ_WRITE;
7868 int ret = 0;
7870 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7872 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7873 if (!io_bio) {
7874 ret = -ENOMEM;
7875 goto free_ordered;
7878 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7879 if (!dip) {
7880 ret = -ENOMEM;
7881 goto free_io_bio;
7884 dip->private = dio_bio->bi_private;
7885 dip->inode = inode;
7886 dip->logical_offset = file_offset;
7887 dip->bytes = dio_bio->bi_iter.bi_size;
7888 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7889 io_bio->bi_private = dip;
7890 dip->orig_bio = io_bio;
7891 dip->dio_bio = dio_bio;
7892 atomic_set(&dip->pending_bios, 0);
7893 btrfs_bio = btrfs_io_bio(io_bio);
7894 btrfs_bio->logical = file_offset;
7896 if (write) {
7897 io_bio->bi_end_io = btrfs_endio_direct_write;
7898 } else {
7899 io_bio->bi_end_io = btrfs_endio_direct_read;
7900 dip->subio_endio = btrfs_subio_endio_read;
7903 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7904 if (!ret)
7905 return;
7907 if (btrfs_bio->end_io)
7908 btrfs_bio->end_io(btrfs_bio, ret);
7909 free_io_bio:
7910 bio_put(io_bio);
7912 free_ordered:
7914 * If this is a write, we need to clean up the reserved space and kill
7915 * the ordered extent.
7917 if (write) {
7918 struct btrfs_ordered_extent *ordered;
7919 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7920 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7921 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7922 btrfs_free_reserved_extent(root, ordered->start,
7923 ordered->disk_len, 1);
7924 btrfs_put_ordered_extent(ordered);
7925 btrfs_put_ordered_extent(ordered);
7927 bio_endio(dio_bio, ret);
7930 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7931 const struct iov_iter *iter, loff_t offset)
7933 int seg;
7934 int i;
7935 unsigned blocksize_mask = root->sectorsize - 1;
7936 ssize_t retval = -EINVAL;
7938 if (offset & blocksize_mask)
7939 goto out;
7941 if (iov_iter_alignment(iter) & blocksize_mask)
7942 goto out;
7944 /* If this is a write we don't need to check anymore */
7945 if (rw & WRITE)
7946 return 0;
7948 * Check to make sure we don't have duplicate iov_base's in this
7949 * iovec, if so return EINVAL, otherwise we'll get csum errors
7950 * when reading back.
7952 for (seg = 0; seg < iter->nr_segs; seg++) {
7953 for (i = seg + 1; i < iter->nr_segs; i++) {
7954 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7955 goto out;
7958 retval = 0;
7959 out:
7960 return retval;
7963 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7964 struct iov_iter *iter, loff_t offset)
7966 struct file *file = iocb->ki_filp;
7967 struct inode *inode = file->f_mapping->host;
7968 size_t count = 0;
7969 int flags = 0;
7970 bool wakeup = true;
7971 bool relock = false;
7972 ssize_t ret;
7974 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
7975 return 0;
7977 atomic_inc(&inode->i_dio_count);
7978 smp_mb__after_atomic();
7981 * The generic stuff only does filemap_write_and_wait_range, which
7982 * isn't enough if we've written compressed pages to this area, so
7983 * we need to flush the dirty pages again to make absolutely sure
7984 * that any outstanding dirty pages are on disk.
7986 count = iov_iter_count(iter);
7987 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7988 &BTRFS_I(inode)->runtime_flags))
7989 filemap_fdatawrite_range(inode->i_mapping, offset,
7990 offset + count - 1);
7992 if (rw & WRITE) {
7994 * If the write DIO is beyond the EOF, we need update
7995 * the isize, but it is protected by i_mutex. So we can
7996 * not unlock the i_mutex at this case.
7998 if (offset + count <= inode->i_size) {
7999 mutex_unlock(&inode->i_mutex);
8000 relock = true;
8002 ret = btrfs_delalloc_reserve_space(inode, count);
8003 if (ret)
8004 goto out;
8005 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8006 &BTRFS_I(inode)->runtime_flags)) {
8007 inode_dio_done(inode);
8008 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8009 wakeup = false;
8012 ret = __blockdev_direct_IO(rw, iocb, inode,
8013 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8014 iter, offset, btrfs_get_blocks_direct, NULL,
8015 btrfs_submit_direct, flags);
8016 if (rw & WRITE) {
8017 if (ret < 0 && ret != -EIOCBQUEUED)
8018 btrfs_delalloc_release_space(inode, count);
8019 else if (ret >= 0 && (size_t)ret < count)
8020 btrfs_delalloc_release_space(inode,
8021 count - (size_t)ret);
8022 else
8023 btrfs_delalloc_release_metadata(inode, 0);
8025 out:
8026 if (wakeup)
8027 inode_dio_done(inode);
8028 if (relock)
8029 mutex_lock(&inode->i_mutex);
8031 return ret;
8034 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8036 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8037 __u64 start, __u64 len)
8039 int ret;
8041 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8042 if (ret)
8043 return ret;
8045 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8048 int btrfs_readpage(struct file *file, struct page *page)
8050 struct extent_io_tree *tree;
8051 tree = &BTRFS_I(page->mapping->host)->io_tree;
8052 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8055 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8057 struct extent_io_tree *tree;
8058 struct inode *inode = page->mapping->host;
8059 int ret;
8061 if (current->flags & PF_MEMALLOC) {
8062 redirty_page_for_writepage(wbc, page);
8063 unlock_page(page);
8064 return 0;
8068 * If we are under memory pressure we will call this directly from the
8069 * VM, we need to make sure we have the inode referenced for the ordered
8070 * extent. If not just return like we didn't do anything.
8072 if (!igrab(inode)) {
8073 redirty_page_for_writepage(wbc, page);
8074 return AOP_WRITEPAGE_ACTIVATE;
8076 tree = &BTRFS_I(page->mapping->host)->io_tree;
8077 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8078 btrfs_add_delayed_iput(inode);
8079 return ret;
8082 static int btrfs_writepages(struct address_space *mapping,
8083 struct writeback_control *wbc)
8085 struct extent_io_tree *tree;
8087 tree = &BTRFS_I(mapping->host)->io_tree;
8088 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8091 static int
8092 btrfs_readpages(struct file *file, struct address_space *mapping,
8093 struct list_head *pages, unsigned nr_pages)
8095 struct extent_io_tree *tree;
8096 tree = &BTRFS_I(mapping->host)->io_tree;
8097 return extent_readpages(tree, mapping, pages, nr_pages,
8098 btrfs_get_extent);
8100 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8102 struct extent_io_tree *tree;
8103 struct extent_map_tree *map;
8104 int ret;
8106 tree = &BTRFS_I(page->mapping->host)->io_tree;
8107 map = &BTRFS_I(page->mapping->host)->extent_tree;
8108 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8109 if (ret == 1) {
8110 ClearPagePrivate(page);
8111 set_page_private(page, 0);
8112 page_cache_release(page);
8114 return ret;
8117 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8119 if (PageWriteback(page) || PageDirty(page))
8120 return 0;
8121 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8124 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8125 unsigned int length)
8127 struct inode *inode = page->mapping->host;
8128 struct extent_io_tree *tree;
8129 struct btrfs_ordered_extent *ordered;
8130 struct extent_state *cached_state = NULL;
8131 u64 page_start = page_offset(page);
8132 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8133 int inode_evicting = inode->i_state & I_FREEING;
8136 * we have the page locked, so new writeback can't start,
8137 * and the dirty bit won't be cleared while we are here.
8139 * Wait for IO on this page so that we can safely clear
8140 * the PagePrivate2 bit and do ordered accounting
8142 wait_on_page_writeback(page);
8144 tree = &BTRFS_I(inode)->io_tree;
8145 if (offset) {
8146 btrfs_releasepage(page, GFP_NOFS);
8147 return;
8150 if (!inode_evicting)
8151 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8152 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8153 if (ordered) {
8155 * IO on this page will never be started, so we need
8156 * to account for any ordered extents now
8158 if (!inode_evicting)
8159 clear_extent_bit(tree, page_start, page_end,
8160 EXTENT_DIRTY | EXTENT_DELALLOC |
8161 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8162 EXTENT_DEFRAG, 1, 0, &cached_state,
8163 GFP_NOFS);
8165 * whoever cleared the private bit is responsible
8166 * for the finish_ordered_io
8168 if (TestClearPagePrivate2(page)) {
8169 struct btrfs_ordered_inode_tree *tree;
8170 u64 new_len;
8172 tree = &BTRFS_I(inode)->ordered_tree;
8174 spin_lock_irq(&tree->lock);
8175 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8176 new_len = page_start - ordered->file_offset;
8177 if (new_len < ordered->truncated_len)
8178 ordered->truncated_len = new_len;
8179 spin_unlock_irq(&tree->lock);
8181 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8182 page_start,
8183 PAGE_CACHE_SIZE, 1))
8184 btrfs_finish_ordered_io(ordered);
8186 btrfs_put_ordered_extent(ordered);
8187 if (!inode_evicting) {
8188 cached_state = NULL;
8189 lock_extent_bits(tree, page_start, page_end, 0,
8190 &cached_state);
8194 if (!inode_evicting) {
8195 clear_extent_bit(tree, page_start, page_end,
8196 EXTENT_LOCKED | EXTENT_DIRTY |
8197 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8198 EXTENT_DEFRAG, 1, 1,
8199 &cached_state, GFP_NOFS);
8201 __btrfs_releasepage(page, GFP_NOFS);
8204 ClearPageChecked(page);
8205 if (PagePrivate(page)) {
8206 ClearPagePrivate(page);
8207 set_page_private(page, 0);
8208 page_cache_release(page);
8213 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8214 * called from a page fault handler when a page is first dirtied. Hence we must
8215 * be careful to check for EOF conditions here. We set the page up correctly
8216 * for a written page which means we get ENOSPC checking when writing into
8217 * holes and correct delalloc and unwritten extent mapping on filesystems that
8218 * support these features.
8220 * We are not allowed to take the i_mutex here so we have to play games to
8221 * protect against truncate races as the page could now be beyond EOF. Because
8222 * vmtruncate() writes the inode size before removing pages, once we have the
8223 * page lock we can determine safely if the page is beyond EOF. If it is not
8224 * beyond EOF, then the page is guaranteed safe against truncation until we
8225 * unlock the page.
8227 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8229 struct page *page = vmf->page;
8230 struct inode *inode = file_inode(vma->vm_file);
8231 struct btrfs_root *root = BTRFS_I(inode)->root;
8232 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8233 struct btrfs_ordered_extent *ordered;
8234 struct extent_state *cached_state = NULL;
8235 char *kaddr;
8236 unsigned long zero_start;
8237 loff_t size;
8238 int ret;
8239 int reserved = 0;
8240 u64 page_start;
8241 u64 page_end;
8243 sb_start_pagefault(inode->i_sb);
8244 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8245 if (!ret) {
8246 ret = file_update_time(vma->vm_file);
8247 reserved = 1;
8249 if (ret) {
8250 if (ret == -ENOMEM)
8251 ret = VM_FAULT_OOM;
8252 else /* -ENOSPC, -EIO, etc */
8253 ret = VM_FAULT_SIGBUS;
8254 if (reserved)
8255 goto out;
8256 goto out_noreserve;
8259 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8260 again:
8261 lock_page(page);
8262 size = i_size_read(inode);
8263 page_start = page_offset(page);
8264 page_end = page_start + PAGE_CACHE_SIZE - 1;
8266 if ((page->mapping != inode->i_mapping) ||
8267 (page_start >= size)) {
8268 /* page got truncated out from underneath us */
8269 goto out_unlock;
8271 wait_on_page_writeback(page);
8273 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8274 set_page_extent_mapped(page);
8277 * we can't set the delalloc bits if there are pending ordered
8278 * extents. Drop our locks and wait for them to finish
8280 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8281 if (ordered) {
8282 unlock_extent_cached(io_tree, page_start, page_end,
8283 &cached_state, GFP_NOFS);
8284 unlock_page(page);
8285 btrfs_start_ordered_extent(inode, ordered, 1);
8286 btrfs_put_ordered_extent(ordered);
8287 goto again;
8291 * XXX - page_mkwrite gets called every time the page is dirtied, even
8292 * if it was already dirty, so for space accounting reasons we need to
8293 * clear any delalloc bits for the range we are fixing to save. There
8294 * is probably a better way to do this, but for now keep consistent with
8295 * prepare_pages in the normal write path.
8297 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8298 EXTENT_DIRTY | EXTENT_DELALLOC |
8299 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8300 0, 0, &cached_state, GFP_NOFS);
8302 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8303 &cached_state);
8304 if (ret) {
8305 unlock_extent_cached(io_tree, page_start, page_end,
8306 &cached_state, GFP_NOFS);
8307 ret = VM_FAULT_SIGBUS;
8308 goto out_unlock;
8310 ret = 0;
8312 /* page is wholly or partially inside EOF */
8313 if (page_start + PAGE_CACHE_SIZE > size)
8314 zero_start = size & ~PAGE_CACHE_MASK;
8315 else
8316 zero_start = PAGE_CACHE_SIZE;
8318 if (zero_start != PAGE_CACHE_SIZE) {
8319 kaddr = kmap(page);
8320 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8321 flush_dcache_page(page);
8322 kunmap(page);
8324 ClearPageChecked(page);
8325 set_page_dirty(page);
8326 SetPageUptodate(page);
8328 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8329 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8330 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8332 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8334 out_unlock:
8335 if (!ret) {
8336 sb_end_pagefault(inode->i_sb);
8337 return VM_FAULT_LOCKED;
8339 unlock_page(page);
8340 out:
8341 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8342 out_noreserve:
8343 sb_end_pagefault(inode->i_sb);
8344 return ret;
8347 static int btrfs_truncate(struct inode *inode)
8349 struct btrfs_root *root = BTRFS_I(inode)->root;
8350 struct btrfs_block_rsv *rsv;
8351 int ret = 0;
8352 int err = 0;
8353 struct btrfs_trans_handle *trans;
8354 u64 mask = root->sectorsize - 1;
8355 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8357 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8358 (u64)-1);
8359 if (ret)
8360 return ret;
8363 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8364 * 3 things going on here
8366 * 1) We need to reserve space for our orphan item and the space to
8367 * delete our orphan item. Lord knows we don't want to have a dangling
8368 * orphan item because we didn't reserve space to remove it.
8370 * 2) We need to reserve space to update our inode.
8372 * 3) We need to have something to cache all the space that is going to
8373 * be free'd up by the truncate operation, but also have some slack
8374 * space reserved in case it uses space during the truncate (thank you
8375 * very much snapshotting).
8377 * And we need these to all be seperate. The fact is we can use alot of
8378 * space doing the truncate, and we have no earthly idea how much space
8379 * we will use, so we need the truncate reservation to be seperate so it
8380 * doesn't end up using space reserved for updating the inode or
8381 * removing the orphan item. We also need to be able to stop the
8382 * transaction and start a new one, which means we need to be able to
8383 * update the inode several times, and we have no idea of knowing how
8384 * many times that will be, so we can't just reserve 1 item for the
8385 * entirety of the opration, so that has to be done seperately as well.
8386 * Then there is the orphan item, which does indeed need to be held on
8387 * to for the whole operation, and we need nobody to touch this reserved
8388 * space except the orphan code.
8390 * So that leaves us with
8392 * 1) root->orphan_block_rsv - for the orphan deletion.
8393 * 2) rsv - for the truncate reservation, which we will steal from the
8394 * transaction reservation.
8395 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8396 * updating the inode.
8398 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8399 if (!rsv)
8400 return -ENOMEM;
8401 rsv->size = min_size;
8402 rsv->failfast = 1;
8405 * 1 for the truncate slack space
8406 * 1 for updating the inode.
8408 trans = btrfs_start_transaction(root, 2);
8409 if (IS_ERR(trans)) {
8410 err = PTR_ERR(trans);
8411 goto out;
8414 /* Migrate the slack space for the truncate to our reserve */
8415 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8416 min_size);
8417 BUG_ON(ret);
8420 * So if we truncate and then write and fsync we normally would just
8421 * write the extents that changed, which is a problem if we need to
8422 * first truncate that entire inode. So set this flag so we write out
8423 * all of the extents in the inode to the sync log so we're completely
8424 * safe.
8426 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8427 trans->block_rsv = rsv;
8429 while (1) {
8430 ret = btrfs_truncate_inode_items(trans, root, inode,
8431 inode->i_size,
8432 BTRFS_EXTENT_DATA_KEY);
8433 if (ret != -ENOSPC) {
8434 err = ret;
8435 break;
8438 trans->block_rsv = &root->fs_info->trans_block_rsv;
8439 ret = btrfs_update_inode(trans, root, inode);
8440 if (ret) {
8441 err = ret;
8442 break;
8445 btrfs_end_transaction(trans, root);
8446 btrfs_btree_balance_dirty(root);
8448 trans = btrfs_start_transaction(root, 2);
8449 if (IS_ERR(trans)) {
8450 ret = err = PTR_ERR(trans);
8451 trans = NULL;
8452 break;
8455 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8456 rsv, min_size);
8457 BUG_ON(ret); /* shouldn't happen */
8458 trans->block_rsv = rsv;
8461 if (ret == 0 && inode->i_nlink > 0) {
8462 trans->block_rsv = root->orphan_block_rsv;
8463 ret = btrfs_orphan_del(trans, inode);
8464 if (ret)
8465 err = ret;
8468 if (trans) {
8469 trans->block_rsv = &root->fs_info->trans_block_rsv;
8470 ret = btrfs_update_inode(trans, root, inode);
8471 if (ret && !err)
8472 err = ret;
8474 ret = btrfs_end_transaction(trans, root);
8475 btrfs_btree_balance_dirty(root);
8478 out:
8479 btrfs_free_block_rsv(root, rsv);
8481 if (ret && !err)
8482 err = ret;
8484 return err;
8488 * create a new subvolume directory/inode (helper for the ioctl).
8490 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8491 struct btrfs_root *new_root,
8492 struct btrfs_root *parent_root,
8493 u64 new_dirid)
8495 struct inode *inode;
8496 int err;
8497 u64 index = 0;
8499 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8500 new_dirid, new_dirid,
8501 S_IFDIR | (~current_umask() & S_IRWXUGO),
8502 &index);
8503 if (IS_ERR(inode))
8504 return PTR_ERR(inode);
8505 inode->i_op = &btrfs_dir_inode_operations;
8506 inode->i_fop = &btrfs_dir_file_operations;
8508 set_nlink(inode, 1);
8509 btrfs_i_size_write(inode, 0);
8510 unlock_new_inode(inode);
8512 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8513 if (err)
8514 btrfs_err(new_root->fs_info,
8515 "error inheriting subvolume %llu properties: %d",
8516 new_root->root_key.objectid, err);
8518 err = btrfs_update_inode(trans, new_root, inode);
8520 iput(inode);
8521 return err;
8524 struct inode *btrfs_alloc_inode(struct super_block *sb)
8526 struct btrfs_inode *ei;
8527 struct inode *inode;
8529 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8530 if (!ei)
8531 return NULL;
8533 ei->root = NULL;
8534 ei->generation = 0;
8535 ei->last_trans = 0;
8536 ei->last_sub_trans = 0;
8537 ei->logged_trans = 0;
8538 ei->delalloc_bytes = 0;
8539 ei->defrag_bytes = 0;
8540 ei->disk_i_size = 0;
8541 ei->flags = 0;
8542 ei->csum_bytes = 0;
8543 ei->index_cnt = (u64)-1;
8544 ei->dir_index = 0;
8545 ei->last_unlink_trans = 0;
8546 ei->last_log_commit = 0;
8548 spin_lock_init(&ei->lock);
8549 ei->outstanding_extents = 0;
8550 ei->reserved_extents = 0;
8552 ei->runtime_flags = 0;
8553 ei->force_compress = BTRFS_COMPRESS_NONE;
8555 ei->delayed_node = NULL;
8557 inode = &ei->vfs_inode;
8558 extent_map_tree_init(&ei->extent_tree);
8559 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8560 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8561 ei->io_tree.track_uptodate = 1;
8562 ei->io_failure_tree.track_uptodate = 1;
8563 atomic_set(&ei->sync_writers, 0);
8564 mutex_init(&ei->log_mutex);
8565 mutex_init(&ei->delalloc_mutex);
8566 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8567 INIT_LIST_HEAD(&ei->delalloc_inodes);
8568 RB_CLEAR_NODE(&ei->rb_node);
8570 return inode;
8573 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8574 void btrfs_test_destroy_inode(struct inode *inode)
8576 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8577 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8579 #endif
8581 static void btrfs_i_callback(struct rcu_head *head)
8583 struct inode *inode = container_of(head, struct inode, i_rcu);
8584 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8587 void btrfs_destroy_inode(struct inode *inode)
8589 struct btrfs_ordered_extent *ordered;
8590 struct btrfs_root *root = BTRFS_I(inode)->root;
8592 WARN_ON(!hlist_empty(&inode->i_dentry));
8593 WARN_ON(inode->i_data.nrpages);
8594 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8595 WARN_ON(BTRFS_I(inode)->reserved_extents);
8596 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8597 WARN_ON(BTRFS_I(inode)->csum_bytes);
8598 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8601 * This can happen where we create an inode, but somebody else also
8602 * created the same inode and we need to destroy the one we already
8603 * created.
8605 if (!root)
8606 goto free;
8608 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8609 &BTRFS_I(inode)->runtime_flags)) {
8610 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8611 btrfs_ino(inode));
8612 atomic_dec(&root->orphan_inodes);
8615 while (1) {
8616 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8617 if (!ordered)
8618 break;
8619 else {
8620 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8621 ordered->file_offset, ordered->len);
8622 btrfs_remove_ordered_extent(inode, ordered);
8623 btrfs_put_ordered_extent(ordered);
8624 btrfs_put_ordered_extent(ordered);
8627 inode_tree_del(inode);
8628 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8629 free:
8630 call_rcu(&inode->i_rcu, btrfs_i_callback);
8633 int btrfs_drop_inode(struct inode *inode)
8635 struct btrfs_root *root = BTRFS_I(inode)->root;
8637 if (root == NULL)
8638 return 1;
8640 /* the snap/subvol tree is on deleting */
8641 if (btrfs_root_refs(&root->root_item) == 0)
8642 return 1;
8643 else
8644 return generic_drop_inode(inode);
8647 static void init_once(void *foo)
8649 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8651 inode_init_once(&ei->vfs_inode);
8654 void btrfs_destroy_cachep(void)
8657 * Make sure all delayed rcu free inodes are flushed before we
8658 * destroy cache.
8660 rcu_barrier();
8661 if (btrfs_inode_cachep)
8662 kmem_cache_destroy(btrfs_inode_cachep);
8663 if (btrfs_trans_handle_cachep)
8664 kmem_cache_destroy(btrfs_trans_handle_cachep);
8665 if (btrfs_transaction_cachep)
8666 kmem_cache_destroy(btrfs_transaction_cachep);
8667 if (btrfs_path_cachep)
8668 kmem_cache_destroy(btrfs_path_cachep);
8669 if (btrfs_free_space_cachep)
8670 kmem_cache_destroy(btrfs_free_space_cachep);
8671 if (btrfs_delalloc_work_cachep)
8672 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8675 int btrfs_init_cachep(void)
8677 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8678 sizeof(struct btrfs_inode), 0,
8679 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8680 if (!btrfs_inode_cachep)
8681 goto fail;
8683 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8684 sizeof(struct btrfs_trans_handle), 0,
8685 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8686 if (!btrfs_trans_handle_cachep)
8687 goto fail;
8689 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8690 sizeof(struct btrfs_transaction), 0,
8691 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8692 if (!btrfs_transaction_cachep)
8693 goto fail;
8695 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8696 sizeof(struct btrfs_path), 0,
8697 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8698 if (!btrfs_path_cachep)
8699 goto fail;
8701 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8702 sizeof(struct btrfs_free_space), 0,
8703 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8704 if (!btrfs_free_space_cachep)
8705 goto fail;
8707 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8708 sizeof(struct btrfs_delalloc_work), 0,
8709 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8710 NULL);
8711 if (!btrfs_delalloc_work_cachep)
8712 goto fail;
8714 return 0;
8715 fail:
8716 btrfs_destroy_cachep();
8717 return -ENOMEM;
8720 static int btrfs_getattr(struct vfsmount *mnt,
8721 struct dentry *dentry, struct kstat *stat)
8723 u64 delalloc_bytes;
8724 struct inode *inode = dentry->d_inode;
8725 u32 blocksize = inode->i_sb->s_blocksize;
8727 generic_fillattr(inode, stat);
8728 stat->dev = BTRFS_I(inode)->root->anon_dev;
8729 stat->blksize = PAGE_CACHE_SIZE;
8731 spin_lock(&BTRFS_I(inode)->lock);
8732 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8733 spin_unlock(&BTRFS_I(inode)->lock);
8734 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8735 ALIGN(delalloc_bytes, blocksize)) >> 9;
8736 return 0;
8739 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8740 struct inode *new_dir, struct dentry *new_dentry)
8742 struct btrfs_trans_handle *trans;
8743 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8744 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8745 struct inode *new_inode = new_dentry->d_inode;
8746 struct inode *old_inode = old_dentry->d_inode;
8747 struct timespec ctime = CURRENT_TIME;
8748 u64 index = 0;
8749 u64 root_objectid;
8750 int ret;
8751 u64 old_ino = btrfs_ino(old_inode);
8753 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8754 return -EPERM;
8756 /* we only allow rename subvolume link between subvolumes */
8757 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8758 return -EXDEV;
8760 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8761 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8762 return -ENOTEMPTY;
8764 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8765 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8766 return -ENOTEMPTY;
8769 /* check for collisions, even if the name isn't there */
8770 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8771 new_dentry->d_name.name,
8772 new_dentry->d_name.len);
8774 if (ret) {
8775 if (ret == -EEXIST) {
8776 /* we shouldn't get
8777 * eexist without a new_inode */
8778 if (WARN_ON(!new_inode)) {
8779 return ret;
8781 } else {
8782 /* maybe -EOVERFLOW */
8783 return ret;
8786 ret = 0;
8789 * we're using rename to replace one file with another. Start IO on it
8790 * now so we don't add too much work to the end of the transaction
8792 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8793 filemap_flush(old_inode->i_mapping);
8795 /* close the racy window with snapshot create/destroy ioctl */
8796 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8797 down_read(&root->fs_info->subvol_sem);
8799 * We want to reserve the absolute worst case amount of items. So if
8800 * both inodes are subvols and we need to unlink them then that would
8801 * require 4 item modifications, but if they are both normal inodes it
8802 * would require 5 item modifications, so we'll assume their normal
8803 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8804 * should cover the worst case number of items we'll modify.
8806 trans = btrfs_start_transaction(root, 11);
8807 if (IS_ERR(trans)) {
8808 ret = PTR_ERR(trans);
8809 goto out_notrans;
8812 if (dest != root)
8813 btrfs_record_root_in_trans(trans, dest);
8815 ret = btrfs_set_inode_index(new_dir, &index);
8816 if (ret)
8817 goto out_fail;
8819 BTRFS_I(old_inode)->dir_index = 0ULL;
8820 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8821 /* force full log commit if subvolume involved. */
8822 btrfs_set_log_full_commit(root->fs_info, trans);
8823 } else {
8824 ret = btrfs_insert_inode_ref(trans, dest,
8825 new_dentry->d_name.name,
8826 new_dentry->d_name.len,
8827 old_ino,
8828 btrfs_ino(new_dir), index);
8829 if (ret)
8830 goto out_fail;
8832 * this is an ugly little race, but the rename is required
8833 * to make sure that if we crash, the inode is either at the
8834 * old name or the new one. pinning the log transaction lets
8835 * us make sure we don't allow a log commit to come in after
8836 * we unlink the name but before we add the new name back in.
8838 btrfs_pin_log_trans(root);
8841 inode_inc_iversion(old_dir);
8842 inode_inc_iversion(new_dir);
8843 inode_inc_iversion(old_inode);
8844 old_dir->i_ctime = old_dir->i_mtime = ctime;
8845 new_dir->i_ctime = new_dir->i_mtime = ctime;
8846 old_inode->i_ctime = ctime;
8848 if (old_dentry->d_parent != new_dentry->d_parent)
8849 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8851 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8852 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8853 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8854 old_dentry->d_name.name,
8855 old_dentry->d_name.len);
8856 } else {
8857 ret = __btrfs_unlink_inode(trans, root, old_dir,
8858 old_dentry->d_inode,
8859 old_dentry->d_name.name,
8860 old_dentry->d_name.len);
8861 if (!ret)
8862 ret = btrfs_update_inode(trans, root, old_inode);
8864 if (ret) {
8865 btrfs_abort_transaction(trans, root, ret);
8866 goto out_fail;
8869 if (new_inode) {
8870 inode_inc_iversion(new_inode);
8871 new_inode->i_ctime = CURRENT_TIME;
8872 if (unlikely(btrfs_ino(new_inode) ==
8873 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8874 root_objectid = BTRFS_I(new_inode)->location.objectid;
8875 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8876 root_objectid,
8877 new_dentry->d_name.name,
8878 new_dentry->d_name.len);
8879 BUG_ON(new_inode->i_nlink == 0);
8880 } else {
8881 ret = btrfs_unlink_inode(trans, dest, new_dir,
8882 new_dentry->d_inode,
8883 new_dentry->d_name.name,
8884 new_dentry->d_name.len);
8886 if (!ret && new_inode->i_nlink == 0)
8887 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8888 if (ret) {
8889 btrfs_abort_transaction(trans, root, ret);
8890 goto out_fail;
8894 ret = btrfs_add_link(trans, new_dir, old_inode,
8895 new_dentry->d_name.name,
8896 new_dentry->d_name.len, 0, index);
8897 if (ret) {
8898 btrfs_abort_transaction(trans, root, ret);
8899 goto out_fail;
8902 if (old_inode->i_nlink == 1)
8903 BTRFS_I(old_inode)->dir_index = index;
8905 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8906 struct dentry *parent = new_dentry->d_parent;
8907 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8908 btrfs_end_log_trans(root);
8910 out_fail:
8911 btrfs_end_transaction(trans, root);
8912 out_notrans:
8913 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8914 up_read(&root->fs_info->subvol_sem);
8916 return ret;
8919 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
8920 struct inode *new_dir, struct dentry *new_dentry,
8921 unsigned int flags)
8923 if (flags & ~RENAME_NOREPLACE)
8924 return -EINVAL;
8926 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
8929 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8931 struct btrfs_delalloc_work *delalloc_work;
8932 struct inode *inode;
8934 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8935 work);
8936 inode = delalloc_work->inode;
8937 if (delalloc_work->wait) {
8938 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8939 } else {
8940 filemap_flush(inode->i_mapping);
8941 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8942 &BTRFS_I(inode)->runtime_flags))
8943 filemap_flush(inode->i_mapping);
8946 if (delalloc_work->delay_iput)
8947 btrfs_add_delayed_iput(inode);
8948 else
8949 iput(inode);
8950 complete(&delalloc_work->completion);
8953 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8954 int wait, int delay_iput)
8956 struct btrfs_delalloc_work *work;
8958 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8959 if (!work)
8960 return NULL;
8962 init_completion(&work->completion);
8963 INIT_LIST_HEAD(&work->list);
8964 work->inode = inode;
8965 work->wait = wait;
8966 work->delay_iput = delay_iput;
8967 WARN_ON_ONCE(!inode);
8968 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
8969 btrfs_run_delalloc_work, NULL, NULL);
8971 return work;
8974 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8976 wait_for_completion(&work->completion);
8977 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8981 * some fairly slow code that needs optimization. This walks the list
8982 * of all the inodes with pending delalloc and forces them to disk.
8984 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8985 int nr)
8987 struct btrfs_inode *binode;
8988 struct inode *inode;
8989 struct btrfs_delalloc_work *work, *next;
8990 struct list_head works;
8991 struct list_head splice;
8992 int ret = 0;
8994 INIT_LIST_HEAD(&works);
8995 INIT_LIST_HEAD(&splice);
8997 mutex_lock(&root->delalloc_mutex);
8998 spin_lock(&root->delalloc_lock);
8999 list_splice_init(&root->delalloc_inodes, &splice);
9000 while (!list_empty(&splice)) {
9001 binode = list_entry(splice.next, struct btrfs_inode,
9002 delalloc_inodes);
9004 list_move_tail(&binode->delalloc_inodes,
9005 &root->delalloc_inodes);
9006 inode = igrab(&binode->vfs_inode);
9007 if (!inode) {
9008 cond_resched_lock(&root->delalloc_lock);
9009 continue;
9011 spin_unlock(&root->delalloc_lock);
9013 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9014 if (!work) {
9015 if (delay_iput)
9016 btrfs_add_delayed_iput(inode);
9017 else
9018 iput(inode);
9019 ret = -ENOMEM;
9020 goto out;
9022 list_add_tail(&work->list, &works);
9023 btrfs_queue_work(root->fs_info->flush_workers,
9024 &work->work);
9025 ret++;
9026 if (nr != -1 && ret >= nr)
9027 goto out;
9028 cond_resched();
9029 spin_lock(&root->delalloc_lock);
9031 spin_unlock(&root->delalloc_lock);
9033 out:
9034 list_for_each_entry_safe(work, next, &works, list) {
9035 list_del_init(&work->list);
9036 btrfs_wait_and_free_delalloc_work(work);
9039 if (!list_empty_careful(&splice)) {
9040 spin_lock(&root->delalloc_lock);
9041 list_splice_tail(&splice, &root->delalloc_inodes);
9042 spin_unlock(&root->delalloc_lock);
9044 mutex_unlock(&root->delalloc_mutex);
9045 return ret;
9048 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9050 int ret;
9052 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9053 return -EROFS;
9055 ret = __start_delalloc_inodes(root, delay_iput, -1);
9056 if (ret > 0)
9057 ret = 0;
9059 * the filemap_flush will queue IO into the worker threads, but
9060 * we have to make sure the IO is actually started and that
9061 * ordered extents get created before we return
9063 atomic_inc(&root->fs_info->async_submit_draining);
9064 while (atomic_read(&root->fs_info->nr_async_submits) ||
9065 atomic_read(&root->fs_info->async_delalloc_pages)) {
9066 wait_event(root->fs_info->async_submit_wait,
9067 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9068 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9070 atomic_dec(&root->fs_info->async_submit_draining);
9071 return ret;
9074 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9075 int nr)
9077 struct btrfs_root *root;
9078 struct list_head splice;
9079 int ret;
9081 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9082 return -EROFS;
9084 INIT_LIST_HEAD(&splice);
9086 mutex_lock(&fs_info->delalloc_root_mutex);
9087 spin_lock(&fs_info->delalloc_root_lock);
9088 list_splice_init(&fs_info->delalloc_roots, &splice);
9089 while (!list_empty(&splice) && nr) {
9090 root = list_first_entry(&splice, struct btrfs_root,
9091 delalloc_root);
9092 root = btrfs_grab_fs_root(root);
9093 BUG_ON(!root);
9094 list_move_tail(&root->delalloc_root,
9095 &fs_info->delalloc_roots);
9096 spin_unlock(&fs_info->delalloc_root_lock);
9098 ret = __start_delalloc_inodes(root, delay_iput, nr);
9099 btrfs_put_fs_root(root);
9100 if (ret < 0)
9101 goto out;
9103 if (nr != -1) {
9104 nr -= ret;
9105 WARN_ON(nr < 0);
9107 spin_lock(&fs_info->delalloc_root_lock);
9109 spin_unlock(&fs_info->delalloc_root_lock);
9111 ret = 0;
9112 atomic_inc(&fs_info->async_submit_draining);
9113 while (atomic_read(&fs_info->nr_async_submits) ||
9114 atomic_read(&fs_info->async_delalloc_pages)) {
9115 wait_event(fs_info->async_submit_wait,
9116 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9117 atomic_read(&fs_info->async_delalloc_pages) == 0));
9119 atomic_dec(&fs_info->async_submit_draining);
9120 out:
9121 if (!list_empty_careful(&splice)) {
9122 spin_lock(&fs_info->delalloc_root_lock);
9123 list_splice_tail(&splice, &fs_info->delalloc_roots);
9124 spin_unlock(&fs_info->delalloc_root_lock);
9126 mutex_unlock(&fs_info->delalloc_root_mutex);
9127 return ret;
9130 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9131 const char *symname)
9133 struct btrfs_trans_handle *trans;
9134 struct btrfs_root *root = BTRFS_I(dir)->root;
9135 struct btrfs_path *path;
9136 struct btrfs_key key;
9137 struct inode *inode = NULL;
9138 int err;
9139 int drop_inode = 0;
9140 u64 objectid;
9141 u64 index = 0;
9142 int name_len;
9143 int datasize;
9144 unsigned long ptr;
9145 struct btrfs_file_extent_item *ei;
9146 struct extent_buffer *leaf;
9148 name_len = strlen(symname);
9149 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9150 return -ENAMETOOLONG;
9153 * 2 items for inode item and ref
9154 * 2 items for dir items
9155 * 1 item for updating parent inode item
9156 * 1 item for the inline extent item
9157 * 1 item for xattr if selinux is on
9159 trans = btrfs_start_transaction(root, 7);
9160 if (IS_ERR(trans))
9161 return PTR_ERR(trans);
9163 err = btrfs_find_free_ino(root, &objectid);
9164 if (err)
9165 goto out_unlock;
9167 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9168 dentry->d_name.len, btrfs_ino(dir), objectid,
9169 S_IFLNK|S_IRWXUGO, &index);
9170 if (IS_ERR(inode)) {
9171 err = PTR_ERR(inode);
9172 goto out_unlock;
9176 * If the active LSM wants to access the inode during
9177 * d_instantiate it needs these. Smack checks to see
9178 * if the filesystem supports xattrs by looking at the
9179 * ops vector.
9181 inode->i_fop = &btrfs_file_operations;
9182 inode->i_op = &btrfs_file_inode_operations;
9183 inode->i_mapping->a_ops = &btrfs_aops;
9184 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9185 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9187 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9188 if (err)
9189 goto out_unlock_inode;
9191 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9192 if (err)
9193 goto out_unlock_inode;
9195 path = btrfs_alloc_path();
9196 if (!path) {
9197 err = -ENOMEM;
9198 goto out_unlock_inode;
9200 key.objectid = btrfs_ino(inode);
9201 key.offset = 0;
9202 key.type = BTRFS_EXTENT_DATA_KEY;
9203 datasize = btrfs_file_extent_calc_inline_size(name_len);
9204 err = btrfs_insert_empty_item(trans, root, path, &key,
9205 datasize);
9206 if (err) {
9207 btrfs_free_path(path);
9208 goto out_unlock_inode;
9210 leaf = path->nodes[0];
9211 ei = btrfs_item_ptr(leaf, path->slots[0],
9212 struct btrfs_file_extent_item);
9213 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9214 btrfs_set_file_extent_type(leaf, ei,
9215 BTRFS_FILE_EXTENT_INLINE);
9216 btrfs_set_file_extent_encryption(leaf, ei, 0);
9217 btrfs_set_file_extent_compression(leaf, ei, 0);
9218 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9219 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9221 ptr = btrfs_file_extent_inline_start(ei);
9222 write_extent_buffer(leaf, symname, ptr, name_len);
9223 btrfs_mark_buffer_dirty(leaf);
9224 btrfs_free_path(path);
9226 inode->i_op = &btrfs_symlink_inode_operations;
9227 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9228 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9229 inode_set_bytes(inode, name_len);
9230 btrfs_i_size_write(inode, name_len);
9231 err = btrfs_update_inode(trans, root, inode);
9232 if (err) {
9233 drop_inode = 1;
9234 goto out_unlock_inode;
9237 unlock_new_inode(inode);
9238 d_instantiate(dentry, inode);
9240 out_unlock:
9241 btrfs_end_transaction(trans, root);
9242 if (drop_inode) {
9243 inode_dec_link_count(inode);
9244 iput(inode);
9246 btrfs_btree_balance_dirty(root);
9247 return err;
9249 out_unlock_inode:
9250 drop_inode = 1;
9251 unlock_new_inode(inode);
9252 goto out_unlock;
9255 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9256 u64 start, u64 num_bytes, u64 min_size,
9257 loff_t actual_len, u64 *alloc_hint,
9258 struct btrfs_trans_handle *trans)
9260 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9261 struct extent_map *em;
9262 struct btrfs_root *root = BTRFS_I(inode)->root;
9263 struct btrfs_key ins;
9264 u64 cur_offset = start;
9265 u64 i_size;
9266 u64 cur_bytes;
9267 int ret = 0;
9268 bool own_trans = true;
9270 if (trans)
9271 own_trans = false;
9272 while (num_bytes > 0) {
9273 if (own_trans) {
9274 trans = btrfs_start_transaction(root, 3);
9275 if (IS_ERR(trans)) {
9276 ret = PTR_ERR(trans);
9277 break;
9281 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9282 cur_bytes = max(cur_bytes, min_size);
9283 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9284 *alloc_hint, &ins, 1, 0);
9285 if (ret) {
9286 if (own_trans)
9287 btrfs_end_transaction(trans, root);
9288 break;
9291 ret = insert_reserved_file_extent(trans, inode,
9292 cur_offset, ins.objectid,
9293 ins.offset, ins.offset,
9294 ins.offset, 0, 0, 0,
9295 BTRFS_FILE_EXTENT_PREALLOC);
9296 if (ret) {
9297 btrfs_free_reserved_extent(root, ins.objectid,
9298 ins.offset, 0);
9299 btrfs_abort_transaction(trans, root, ret);
9300 if (own_trans)
9301 btrfs_end_transaction(trans, root);
9302 break;
9304 btrfs_drop_extent_cache(inode, cur_offset,
9305 cur_offset + ins.offset -1, 0);
9307 em = alloc_extent_map();
9308 if (!em) {
9309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9310 &BTRFS_I(inode)->runtime_flags);
9311 goto next;
9314 em->start = cur_offset;
9315 em->orig_start = cur_offset;
9316 em->len = ins.offset;
9317 em->block_start = ins.objectid;
9318 em->block_len = ins.offset;
9319 em->orig_block_len = ins.offset;
9320 em->ram_bytes = ins.offset;
9321 em->bdev = root->fs_info->fs_devices->latest_bdev;
9322 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9323 em->generation = trans->transid;
9325 while (1) {
9326 write_lock(&em_tree->lock);
9327 ret = add_extent_mapping(em_tree, em, 1);
9328 write_unlock(&em_tree->lock);
9329 if (ret != -EEXIST)
9330 break;
9331 btrfs_drop_extent_cache(inode, cur_offset,
9332 cur_offset + ins.offset - 1,
9335 free_extent_map(em);
9336 next:
9337 num_bytes -= ins.offset;
9338 cur_offset += ins.offset;
9339 *alloc_hint = ins.objectid + ins.offset;
9341 inode_inc_iversion(inode);
9342 inode->i_ctime = CURRENT_TIME;
9343 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9344 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9345 (actual_len > inode->i_size) &&
9346 (cur_offset > inode->i_size)) {
9347 if (cur_offset > actual_len)
9348 i_size = actual_len;
9349 else
9350 i_size = cur_offset;
9351 i_size_write(inode, i_size);
9352 btrfs_ordered_update_i_size(inode, i_size, NULL);
9355 ret = btrfs_update_inode(trans, root, inode);
9357 if (ret) {
9358 btrfs_abort_transaction(trans, root, ret);
9359 if (own_trans)
9360 btrfs_end_transaction(trans, root);
9361 break;
9364 if (own_trans)
9365 btrfs_end_transaction(trans, root);
9367 return ret;
9370 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9371 u64 start, u64 num_bytes, u64 min_size,
9372 loff_t actual_len, u64 *alloc_hint)
9374 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9375 min_size, actual_len, alloc_hint,
9376 NULL);
9379 int btrfs_prealloc_file_range_trans(struct inode *inode,
9380 struct btrfs_trans_handle *trans, int mode,
9381 u64 start, u64 num_bytes, u64 min_size,
9382 loff_t actual_len, u64 *alloc_hint)
9384 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9385 min_size, actual_len, alloc_hint, trans);
9388 static int btrfs_set_page_dirty(struct page *page)
9390 return __set_page_dirty_nobuffers(page);
9393 static int btrfs_permission(struct inode *inode, int mask)
9395 struct btrfs_root *root = BTRFS_I(inode)->root;
9396 umode_t mode = inode->i_mode;
9398 if (mask & MAY_WRITE &&
9399 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9400 if (btrfs_root_readonly(root))
9401 return -EROFS;
9402 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9403 return -EACCES;
9405 return generic_permission(inode, mask);
9408 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9410 struct btrfs_trans_handle *trans;
9411 struct btrfs_root *root = BTRFS_I(dir)->root;
9412 struct inode *inode = NULL;
9413 u64 objectid;
9414 u64 index;
9415 int ret = 0;
9418 * 5 units required for adding orphan entry
9420 trans = btrfs_start_transaction(root, 5);
9421 if (IS_ERR(trans))
9422 return PTR_ERR(trans);
9424 ret = btrfs_find_free_ino(root, &objectid);
9425 if (ret)
9426 goto out;
9428 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9429 btrfs_ino(dir), objectid, mode, &index);
9430 if (IS_ERR(inode)) {
9431 ret = PTR_ERR(inode);
9432 inode = NULL;
9433 goto out;
9436 inode->i_fop = &btrfs_file_operations;
9437 inode->i_op = &btrfs_file_inode_operations;
9439 inode->i_mapping->a_ops = &btrfs_aops;
9440 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9441 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9443 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9444 if (ret)
9445 goto out_inode;
9447 ret = btrfs_update_inode(trans, root, inode);
9448 if (ret)
9449 goto out_inode;
9450 ret = btrfs_orphan_add(trans, inode);
9451 if (ret)
9452 goto out_inode;
9455 * We set number of links to 0 in btrfs_new_inode(), and here we set
9456 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9457 * through:
9459 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9461 set_nlink(inode, 1);
9462 unlock_new_inode(inode);
9463 d_tmpfile(dentry, inode);
9464 mark_inode_dirty(inode);
9466 out:
9467 btrfs_end_transaction(trans, root);
9468 if (ret)
9469 iput(inode);
9470 btrfs_balance_delayed_items(root);
9471 btrfs_btree_balance_dirty(root);
9472 return ret;
9474 out_inode:
9475 unlock_new_inode(inode);
9476 goto out;
9480 static const struct inode_operations btrfs_dir_inode_operations = {
9481 .getattr = btrfs_getattr,
9482 .lookup = btrfs_lookup,
9483 .create = btrfs_create,
9484 .unlink = btrfs_unlink,
9485 .link = btrfs_link,
9486 .mkdir = btrfs_mkdir,
9487 .rmdir = btrfs_rmdir,
9488 .rename2 = btrfs_rename2,
9489 .symlink = btrfs_symlink,
9490 .setattr = btrfs_setattr,
9491 .mknod = btrfs_mknod,
9492 .setxattr = btrfs_setxattr,
9493 .getxattr = btrfs_getxattr,
9494 .listxattr = btrfs_listxattr,
9495 .removexattr = btrfs_removexattr,
9496 .permission = btrfs_permission,
9497 .get_acl = btrfs_get_acl,
9498 .set_acl = btrfs_set_acl,
9499 .update_time = btrfs_update_time,
9500 .tmpfile = btrfs_tmpfile,
9502 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9503 .lookup = btrfs_lookup,
9504 .permission = btrfs_permission,
9505 .get_acl = btrfs_get_acl,
9506 .set_acl = btrfs_set_acl,
9507 .update_time = btrfs_update_time,
9510 static const struct file_operations btrfs_dir_file_operations = {
9511 .llseek = generic_file_llseek,
9512 .read = generic_read_dir,
9513 .iterate = btrfs_real_readdir,
9514 .unlocked_ioctl = btrfs_ioctl,
9515 #ifdef CONFIG_COMPAT
9516 .compat_ioctl = btrfs_ioctl,
9517 #endif
9518 .release = btrfs_release_file,
9519 .fsync = btrfs_sync_file,
9522 static struct extent_io_ops btrfs_extent_io_ops = {
9523 .fill_delalloc = run_delalloc_range,
9524 .submit_bio_hook = btrfs_submit_bio_hook,
9525 .merge_bio_hook = btrfs_merge_bio_hook,
9526 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9527 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9528 .writepage_start_hook = btrfs_writepage_start_hook,
9529 .set_bit_hook = btrfs_set_bit_hook,
9530 .clear_bit_hook = btrfs_clear_bit_hook,
9531 .merge_extent_hook = btrfs_merge_extent_hook,
9532 .split_extent_hook = btrfs_split_extent_hook,
9536 * btrfs doesn't support the bmap operation because swapfiles
9537 * use bmap to make a mapping of extents in the file. They assume
9538 * these extents won't change over the life of the file and they
9539 * use the bmap result to do IO directly to the drive.
9541 * the btrfs bmap call would return logical addresses that aren't
9542 * suitable for IO and they also will change frequently as COW
9543 * operations happen. So, swapfile + btrfs == corruption.
9545 * For now we're avoiding this by dropping bmap.
9547 static const struct address_space_operations btrfs_aops = {
9548 .readpage = btrfs_readpage,
9549 .writepage = btrfs_writepage,
9550 .writepages = btrfs_writepages,
9551 .readpages = btrfs_readpages,
9552 .direct_IO = btrfs_direct_IO,
9553 .invalidatepage = btrfs_invalidatepage,
9554 .releasepage = btrfs_releasepage,
9555 .set_page_dirty = btrfs_set_page_dirty,
9556 .error_remove_page = generic_error_remove_page,
9559 static const struct address_space_operations btrfs_symlink_aops = {
9560 .readpage = btrfs_readpage,
9561 .writepage = btrfs_writepage,
9562 .invalidatepage = btrfs_invalidatepage,
9563 .releasepage = btrfs_releasepage,
9566 static const struct inode_operations btrfs_file_inode_operations = {
9567 .getattr = btrfs_getattr,
9568 .setattr = btrfs_setattr,
9569 .setxattr = btrfs_setxattr,
9570 .getxattr = btrfs_getxattr,
9571 .listxattr = btrfs_listxattr,
9572 .removexattr = btrfs_removexattr,
9573 .permission = btrfs_permission,
9574 .fiemap = btrfs_fiemap,
9575 .get_acl = btrfs_get_acl,
9576 .set_acl = btrfs_set_acl,
9577 .update_time = btrfs_update_time,
9579 static const struct inode_operations btrfs_special_inode_operations = {
9580 .getattr = btrfs_getattr,
9581 .setattr = btrfs_setattr,
9582 .permission = btrfs_permission,
9583 .setxattr = btrfs_setxattr,
9584 .getxattr = btrfs_getxattr,
9585 .listxattr = btrfs_listxattr,
9586 .removexattr = btrfs_removexattr,
9587 .get_acl = btrfs_get_acl,
9588 .set_acl = btrfs_set_acl,
9589 .update_time = btrfs_update_time,
9591 static const struct inode_operations btrfs_symlink_inode_operations = {
9592 .readlink = generic_readlink,
9593 .follow_link = page_follow_link_light,
9594 .put_link = page_put_link,
9595 .getattr = btrfs_getattr,
9596 .setattr = btrfs_setattr,
9597 .permission = btrfs_permission,
9598 .setxattr = btrfs_setxattr,
9599 .getxattr = btrfs_getxattr,
9600 .listxattr = btrfs_listxattr,
9601 .removexattr = btrfs_removexattr,
9602 .update_time = btrfs_update_time,
9605 const struct dentry_operations btrfs_dentry_operations = {
9606 .d_delete = btrfs_dentry_delete,
9607 .d_release = btrfs_dentry_release,