Btrfs: add mount -o auto_defrag
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / fs / btrfs / inode.c
blobbb51bb1fa44f836ffaa519eaa3c49b96a6ebac03
1 /*
2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include "compat.h"
42 #include "ctree.h"
43 #include "disk-io.h"
44 #include "transaction.h"
45 #include "btrfs_inode.h"
46 #include "ioctl.h"
47 #include "print-tree.h"
48 #include "volumes.h"
49 #include "ordered-data.h"
50 #include "xattr.h"
51 #include "tree-log.h"
52 #include "compression.h"
53 #include "locking.h"
54 #include "free-space-cache.h"
55 #include "inode-map.h"
57 struct btrfs_iget_args {
58 u64 ino;
59 struct btrfs_root *root;
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct address_space_operations btrfs_symlink_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static struct extent_io_ops btrfs_extent_io_ops;
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_transaction_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
78 #define S_SHIFT 12
79 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
80 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
81 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
82 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
83 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
84 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
85 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
86 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
89 static int btrfs_setsize(struct inode *inode, loff_t newsize);
90 static int btrfs_truncate(struct inode *inode);
91 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
92 static noinline int cow_file_range(struct inode *inode,
93 struct page *locked_page,
94 u64 start, u64 end, int *page_started,
95 unsigned long *nr_written, int unlock);
97 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
98 struct inode *inode, struct inode *dir,
99 const struct qstr *qstr)
101 int err;
103 err = btrfs_init_acl(trans, inode, dir);
104 if (!err)
105 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
106 return err;
110 * this does all the hard work for inserting an inline extent into
111 * the btree. The caller should have done a btrfs_drop_extents so that
112 * no overlapping inline items exist in the btree
114 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
115 struct btrfs_root *root, struct inode *inode,
116 u64 start, size_t size, size_t compressed_size,
117 int compress_type,
118 struct page **compressed_pages)
120 struct btrfs_key key;
121 struct btrfs_path *path;
122 struct extent_buffer *leaf;
123 struct page *page = NULL;
124 char *kaddr;
125 unsigned long ptr;
126 struct btrfs_file_extent_item *ei;
127 int err = 0;
128 int ret;
129 size_t cur_size = size;
130 size_t datasize;
131 unsigned long offset;
133 if (compressed_size && compressed_pages)
134 cur_size = compressed_size;
136 path = btrfs_alloc_path();
137 if (!path)
138 return -ENOMEM;
140 path->leave_spinning = 1;
141 btrfs_set_trans_block_group(trans, inode);
143 key.objectid = btrfs_ino(inode);
144 key.offset = start;
145 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
146 datasize = btrfs_file_extent_calc_inline_size(cur_size);
148 inode_add_bytes(inode, size);
149 ret = btrfs_insert_empty_item(trans, root, path, &key,
150 datasize);
151 BUG_ON(ret);
152 if (ret) {
153 err = ret;
154 goto fail;
156 leaf = path->nodes[0];
157 ei = btrfs_item_ptr(leaf, path->slots[0],
158 struct btrfs_file_extent_item);
159 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
160 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
161 btrfs_set_file_extent_encryption(leaf, ei, 0);
162 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
163 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
164 ptr = btrfs_file_extent_inline_start(ei);
166 if (compress_type != BTRFS_COMPRESS_NONE) {
167 struct page *cpage;
168 int i = 0;
169 while (compressed_size > 0) {
170 cpage = compressed_pages[i];
171 cur_size = min_t(unsigned long, compressed_size,
172 PAGE_CACHE_SIZE);
174 kaddr = kmap_atomic(cpage, KM_USER0);
175 write_extent_buffer(leaf, kaddr, ptr, cur_size);
176 kunmap_atomic(kaddr, KM_USER0);
178 i++;
179 ptr += cur_size;
180 compressed_size -= cur_size;
182 btrfs_set_file_extent_compression(leaf, ei,
183 compress_type);
184 } else {
185 page = find_get_page(inode->i_mapping,
186 start >> PAGE_CACHE_SHIFT);
187 btrfs_set_file_extent_compression(leaf, ei, 0);
188 kaddr = kmap_atomic(page, KM_USER0);
189 offset = start & (PAGE_CACHE_SIZE - 1);
190 write_extent_buffer(leaf, kaddr + offset, ptr, size);
191 kunmap_atomic(kaddr, KM_USER0);
192 page_cache_release(page);
194 btrfs_mark_buffer_dirty(leaf);
195 btrfs_free_path(path);
198 * we're an inline extent, so nobody can
199 * extend the file past i_size without locking
200 * a page we already have locked.
202 * We must do any isize and inode updates
203 * before we unlock the pages. Otherwise we
204 * could end up racing with unlink.
206 BTRFS_I(inode)->disk_i_size = inode->i_size;
207 btrfs_update_inode(trans, root, inode);
209 return 0;
210 fail:
211 btrfs_free_path(path);
212 return err;
217 * conditionally insert an inline extent into the file. This
218 * does the checks required to make sure the data is small enough
219 * to fit as an inline extent.
221 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
222 struct btrfs_root *root,
223 struct inode *inode, u64 start, u64 end,
224 size_t compressed_size, int compress_type,
225 struct page **compressed_pages)
227 u64 isize = i_size_read(inode);
228 u64 actual_end = min(end + 1, isize);
229 u64 inline_len = actual_end - start;
230 u64 aligned_end = (end + root->sectorsize - 1) &
231 ~((u64)root->sectorsize - 1);
232 u64 hint_byte;
233 u64 data_len = inline_len;
234 int ret;
236 if (compressed_size)
237 data_len = compressed_size;
239 if (start > 0 ||
240 actual_end >= PAGE_CACHE_SIZE ||
241 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
242 (!compressed_size &&
243 (actual_end & (root->sectorsize - 1)) == 0) ||
244 end + 1 < isize ||
245 data_len > root->fs_info->max_inline) {
246 return 1;
249 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
250 &hint_byte, 1);
251 BUG_ON(ret);
253 if (isize > actual_end)
254 inline_len = min_t(u64, isize, actual_end);
255 ret = insert_inline_extent(trans, root, inode, start,
256 inline_len, compressed_size,
257 compress_type, compressed_pages);
258 BUG_ON(ret);
259 btrfs_delalloc_release_metadata(inode, end + 1 - start);
260 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
261 return 0;
264 struct async_extent {
265 u64 start;
266 u64 ram_size;
267 u64 compressed_size;
268 struct page **pages;
269 unsigned long nr_pages;
270 int compress_type;
271 struct list_head list;
274 struct async_cow {
275 struct inode *inode;
276 struct btrfs_root *root;
277 struct page *locked_page;
278 u64 start;
279 u64 end;
280 struct list_head extents;
281 struct btrfs_work work;
284 static noinline int add_async_extent(struct async_cow *cow,
285 u64 start, u64 ram_size,
286 u64 compressed_size,
287 struct page **pages,
288 unsigned long nr_pages,
289 int compress_type)
291 struct async_extent *async_extent;
293 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
294 BUG_ON(!async_extent);
295 async_extent->start = start;
296 async_extent->ram_size = ram_size;
297 async_extent->compressed_size = compressed_size;
298 async_extent->pages = pages;
299 async_extent->nr_pages = nr_pages;
300 async_extent->compress_type = compress_type;
301 list_add_tail(&async_extent->list, &cow->extents);
302 return 0;
306 * we create compressed extents in two phases. The first
307 * phase compresses a range of pages that have already been
308 * locked (both pages and state bits are locked).
310 * This is done inside an ordered work queue, and the compression
311 * is spread across many cpus. The actual IO submission is step
312 * two, and the ordered work queue takes care of making sure that
313 * happens in the same order things were put onto the queue by
314 * writepages and friends.
316 * If this code finds it can't get good compression, it puts an
317 * entry onto the work queue to write the uncompressed bytes. This
318 * makes sure that both compressed inodes and uncompressed inodes
319 * are written in the same order that pdflush sent them down.
321 static noinline int compress_file_range(struct inode *inode,
322 struct page *locked_page,
323 u64 start, u64 end,
324 struct async_cow *async_cow,
325 int *num_added)
327 struct btrfs_root *root = BTRFS_I(inode)->root;
328 struct btrfs_trans_handle *trans;
329 u64 num_bytes;
330 u64 blocksize = root->sectorsize;
331 u64 actual_end;
332 u64 isize = i_size_read(inode);
333 int ret = 0;
334 struct page **pages = NULL;
335 unsigned long nr_pages;
336 unsigned long nr_pages_ret = 0;
337 unsigned long total_compressed = 0;
338 unsigned long total_in = 0;
339 unsigned long max_compressed = 128 * 1024;
340 unsigned long max_uncompressed = 128 * 1024;
341 int i;
342 int will_compress;
343 int compress_type = root->fs_info->compress_type;
345 /* if this is a small write inside eof, kick off a defragbot */
346 if (end <= BTRFS_I(inode)->disk_i_size && (end - start + 1) < 16 * 1024)
347 btrfs_add_inode_defrag(NULL, inode);
349 actual_end = min_t(u64, isize, end + 1);
350 again:
351 will_compress = 0;
352 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
353 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
356 * we don't want to send crud past the end of i_size through
357 * compression, that's just a waste of CPU time. So, if the
358 * end of the file is before the start of our current
359 * requested range of bytes, we bail out to the uncompressed
360 * cleanup code that can deal with all of this.
362 * It isn't really the fastest way to fix things, but this is a
363 * very uncommon corner.
365 if (actual_end <= start)
366 goto cleanup_and_bail_uncompressed;
368 total_compressed = actual_end - start;
370 /* we want to make sure that amount of ram required to uncompress
371 * an extent is reasonable, so we limit the total size in ram
372 * of a compressed extent to 128k. This is a crucial number
373 * because it also controls how easily we can spread reads across
374 * cpus for decompression.
376 * We also want to make sure the amount of IO required to do
377 * a random read is reasonably small, so we limit the size of
378 * a compressed extent to 128k.
380 total_compressed = min(total_compressed, max_uncompressed);
381 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
382 num_bytes = max(blocksize, num_bytes);
383 total_in = 0;
384 ret = 0;
387 * we do compression for mount -o compress and when the
388 * inode has not been flagged as nocompress. This flag can
389 * change at any time if we discover bad compression ratios.
391 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
392 (btrfs_test_opt(root, COMPRESS) ||
393 (BTRFS_I(inode)->force_compress) ||
394 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
395 WARN_ON(pages);
396 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
397 BUG_ON(!pages);
399 if (BTRFS_I(inode)->force_compress)
400 compress_type = BTRFS_I(inode)->force_compress;
402 ret = btrfs_compress_pages(compress_type,
403 inode->i_mapping, start,
404 total_compressed, pages,
405 nr_pages, &nr_pages_ret,
406 &total_in,
407 &total_compressed,
408 max_compressed);
410 if (!ret) {
411 unsigned long offset = total_compressed &
412 (PAGE_CACHE_SIZE - 1);
413 struct page *page = pages[nr_pages_ret - 1];
414 char *kaddr;
416 /* zero the tail end of the last page, we might be
417 * sending it down to disk
419 if (offset) {
420 kaddr = kmap_atomic(page, KM_USER0);
421 memset(kaddr + offset, 0,
422 PAGE_CACHE_SIZE - offset);
423 kunmap_atomic(kaddr, KM_USER0);
425 will_compress = 1;
428 if (start == 0) {
429 trans = btrfs_join_transaction(root, 1);
430 BUG_ON(IS_ERR(trans));
431 btrfs_set_trans_block_group(trans, inode);
432 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
434 /* lets try to make an inline extent */
435 if (ret || total_in < (actual_end - start)) {
436 /* we didn't compress the entire range, try
437 * to make an uncompressed inline extent.
439 ret = cow_file_range_inline(trans, root, inode,
440 start, end, 0, 0, NULL);
441 } else {
442 /* try making a compressed inline extent */
443 ret = cow_file_range_inline(trans, root, inode,
444 start, end,
445 total_compressed,
446 compress_type, pages);
448 if (ret == 0) {
450 * inline extent creation worked, we don't need
451 * to create any more async work items. Unlock
452 * and free up our temp pages.
454 extent_clear_unlock_delalloc(inode,
455 &BTRFS_I(inode)->io_tree,
456 start, end, NULL,
457 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
458 EXTENT_CLEAR_DELALLOC |
459 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
461 btrfs_end_transaction(trans, root);
462 goto free_pages_out;
464 btrfs_end_transaction(trans, root);
467 if (will_compress) {
469 * we aren't doing an inline extent round the compressed size
470 * up to a block size boundary so the allocator does sane
471 * things
473 total_compressed = (total_compressed + blocksize - 1) &
474 ~(blocksize - 1);
477 * one last check to make sure the compression is really a
478 * win, compare the page count read with the blocks on disk
480 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
481 ~(PAGE_CACHE_SIZE - 1);
482 if (total_compressed >= total_in) {
483 will_compress = 0;
484 } else {
485 num_bytes = total_in;
488 if (!will_compress && pages) {
490 * the compression code ran but failed to make things smaller,
491 * free any pages it allocated and our page pointer array
493 for (i = 0; i < nr_pages_ret; i++) {
494 WARN_ON(pages[i]->mapping);
495 page_cache_release(pages[i]);
497 kfree(pages);
498 pages = NULL;
499 total_compressed = 0;
500 nr_pages_ret = 0;
502 /* flag the file so we don't compress in the future */
503 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
504 !(BTRFS_I(inode)->force_compress)) {
505 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
508 if (will_compress) {
509 *num_added += 1;
511 /* the async work queues will take care of doing actual
512 * allocation on disk for these compressed pages,
513 * and will submit them to the elevator.
515 add_async_extent(async_cow, start, num_bytes,
516 total_compressed, pages, nr_pages_ret,
517 compress_type);
519 if (start + num_bytes < end) {
520 start += num_bytes;
521 pages = NULL;
522 cond_resched();
523 goto again;
525 } else {
526 cleanup_and_bail_uncompressed:
528 * No compression, but we still need to write the pages in
529 * the file we've been given so far. redirty the locked
530 * page if it corresponds to our extent and set things up
531 * for the async work queue to run cow_file_range to do
532 * the normal delalloc dance
534 if (page_offset(locked_page) >= start &&
535 page_offset(locked_page) <= end) {
536 __set_page_dirty_nobuffers(locked_page);
537 /* unlocked later on in the async handlers */
539 add_async_extent(async_cow, start, end - start + 1,
540 0, NULL, 0, BTRFS_COMPRESS_NONE);
541 *num_added += 1;
544 out:
545 return 0;
547 free_pages_out:
548 for (i = 0; i < nr_pages_ret; i++) {
549 WARN_ON(pages[i]->mapping);
550 page_cache_release(pages[i]);
552 kfree(pages);
554 goto out;
558 * phase two of compressed writeback. This is the ordered portion
559 * of the code, which only gets called in the order the work was
560 * queued. We walk all the async extents created by compress_file_range
561 * and send them down to the disk.
563 static noinline int submit_compressed_extents(struct inode *inode,
564 struct async_cow *async_cow)
566 struct async_extent *async_extent;
567 u64 alloc_hint = 0;
568 struct btrfs_trans_handle *trans;
569 struct btrfs_key ins;
570 struct extent_map *em;
571 struct btrfs_root *root = BTRFS_I(inode)->root;
572 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
573 struct extent_io_tree *io_tree;
574 int ret = 0;
576 if (list_empty(&async_cow->extents))
577 return 0;
580 while (!list_empty(&async_cow->extents)) {
581 async_extent = list_entry(async_cow->extents.next,
582 struct async_extent, list);
583 list_del(&async_extent->list);
585 io_tree = &BTRFS_I(inode)->io_tree;
587 retry:
588 /* did the compression code fall back to uncompressed IO? */
589 if (!async_extent->pages) {
590 int page_started = 0;
591 unsigned long nr_written = 0;
593 lock_extent(io_tree, async_extent->start,
594 async_extent->start +
595 async_extent->ram_size - 1, GFP_NOFS);
597 /* allocate blocks */
598 ret = cow_file_range(inode, async_cow->locked_page,
599 async_extent->start,
600 async_extent->start +
601 async_extent->ram_size - 1,
602 &page_started, &nr_written, 0);
605 * if page_started, cow_file_range inserted an
606 * inline extent and took care of all the unlocking
607 * and IO for us. Otherwise, we need to submit
608 * all those pages down to the drive.
610 if (!page_started && !ret)
611 extent_write_locked_range(io_tree,
612 inode, async_extent->start,
613 async_extent->start +
614 async_extent->ram_size - 1,
615 btrfs_get_extent,
616 WB_SYNC_ALL);
617 kfree(async_extent);
618 cond_resched();
619 continue;
622 lock_extent(io_tree, async_extent->start,
623 async_extent->start + async_extent->ram_size - 1,
624 GFP_NOFS);
626 trans = btrfs_join_transaction(root, 1);
627 BUG_ON(IS_ERR(trans));
628 ret = btrfs_reserve_extent(trans, root,
629 async_extent->compressed_size,
630 async_extent->compressed_size,
631 0, alloc_hint,
632 (u64)-1, &ins, 1);
633 btrfs_end_transaction(trans, root);
635 if (ret) {
636 int i;
637 for (i = 0; i < async_extent->nr_pages; i++) {
638 WARN_ON(async_extent->pages[i]->mapping);
639 page_cache_release(async_extent->pages[i]);
641 kfree(async_extent->pages);
642 async_extent->nr_pages = 0;
643 async_extent->pages = NULL;
644 unlock_extent(io_tree, async_extent->start,
645 async_extent->start +
646 async_extent->ram_size - 1, GFP_NOFS);
647 goto retry;
651 * here we're doing allocation and writeback of the
652 * compressed pages
654 btrfs_drop_extent_cache(inode, async_extent->start,
655 async_extent->start +
656 async_extent->ram_size - 1, 0);
658 em = alloc_extent_map();
659 BUG_ON(!em);
660 em->start = async_extent->start;
661 em->len = async_extent->ram_size;
662 em->orig_start = em->start;
664 em->block_start = ins.objectid;
665 em->block_len = ins.offset;
666 em->bdev = root->fs_info->fs_devices->latest_bdev;
667 em->compress_type = async_extent->compress_type;
668 set_bit(EXTENT_FLAG_PINNED, &em->flags);
669 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
671 while (1) {
672 write_lock(&em_tree->lock);
673 ret = add_extent_mapping(em_tree, em);
674 write_unlock(&em_tree->lock);
675 if (ret != -EEXIST) {
676 free_extent_map(em);
677 break;
679 btrfs_drop_extent_cache(inode, async_extent->start,
680 async_extent->start +
681 async_extent->ram_size - 1, 0);
684 ret = btrfs_add_ordered_extent_compress(inode,
685 async_extent->start,
686 ins.objectid,
687 async_extent->ram_size,
688 ins.offset,
689 BTRFS_ORDERED_COMPRESSED,
690 async_extent->compress_type);
691 BUG_ON(ret);
694 * clear dirty, set writeback and unlock the pages.
696 extent_clear_unlock_delalloc(inode,
697 &BTRFS_I(inode)->io_tree,
698 async_extent->start,
699 async_extent->start +
700 async_extent->ram_size - 1,
701 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
702 EXTENT_CLEAR_UNLOCK |
703 EXTENT_CLEAR_DELALLOC |
704 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
706 ret = btrfs_submit_compressed_write(inode,
707 async_extent->start,
708 async_extent->ram_size,
709 ins.objectid,
710 ins.offset, async_extent->pages,
711 async_extent->nr_pages);
713 BUG_ON(ret);
714 alloc_hint = ins.objectid + ins.offset;
715 kfree(async_extent);
716 cond_resched();
719 return 0;
722 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
723 u64 num_bytes)
725 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
726 struct extent_map *em;
727 u64 alloc_hint = 0;
729 read_lock(&em_tree->lock);
730 em = search_extent_mapping(em_tree, start, num_bytes);
731 if (em) {
733 * if block start isn't an actual block number then find the
734 * first block in this inode and use that as a hint. If that
735 * block is also bogus then just don't worry about it.
737 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
738 free_extent_map(em);
739 em = search_extent_mapping(em_tree, 0, 0);
740 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
741 alloc_hint = em->block_start;
742 if (em)
743 free_extent_map(em);
744 } else {
745 alloc_hint = em->block_start;
746 free_extent_map(em);
749 read_unlock(&em_tree->lock);
751 return alloc_hint;
754 static inline bool is_free_space_inode(struct btrfs_root *root,
755 struct inode *inode)
757 if (root == root->fs_info->tree_root ||
758 BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID)
759 return true;
760 return false;
764 * when extent_io.c finds a delayed allocation range in the file,
765 * the call backs end up in this code. The basic idea is to
766 * allocate extents on disk for the range, and create ordered data structs
767 * in ram to track those extents.
769 * locked_page is the page that writepage had locked already. We use
770 * it to make sure we don't do extra locks or unlocks.
772 * *page_started is set to one if we unlock locked_page and do everything
773 * required to start IO on it. It may be clean and already done with
774 * IO when we return.
776 static noinline int cow_file_range(struct inode *inode,
777 struct page *locked_page,
778 u64 start, u64 end, int *page_started,
779 unsigned long *nr_written,
780 int unlock)
782 struct btrfs_root *root = BTRFS_I(inode)->root;
783 struct btrfs_trans_handle *trans;
784 u64 alloc_hint = 0;
785 u64 num_bytes;
786 unsigned long ram_size;
787 u64 disk_num_bytes;
788 u64 cur_alloc_size;
789 u64 blocksize = root->sectorsize;
790 struct btrfs_key ins;
791 struct extent_map *em;
792 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
793 int ret = 0;
795 BUG_ON(is_free_space_inode(root, inode));
796 trans = btrfs_join_transaction(root, 1);
797 BUG_ON(IS_ERR(trans));
798 btrfs_set_trans_block_group(trans, inode);
799 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
801 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
802 num_bytes = max(blocksize, num_bytes);
803 disk_num_bytes = num_bytes;
804 ret = 0;
806 /* if this is a small write inside eof, kick off defrag */
807 if (end <= BTRFS_I(inode)->disk_i_size && num_bytes < 64 * 1024)
808 btrfs_add_inode_defrag(trans, inode);
810 if (start == 0) {
811 /* lets try to make an inline extent */
812 ret = cow_file_range_inline(trans, root, inode,
813 start, end, 0, 0, NULL);
814 if (ret == 0) {
815 extent_clear_unlock_delalloc(inode,
816 &BTRFS_I(inode)->io_tree,
817 start, end, NULL,
818 EXTENT_CLEAR_UNLOCK_PAGE |
819 EXTENT_CLEAR_UNLOCK |
820 EXTENT_CLEAR_DELALLOC |
821 EXTENT_CLEAR_DIRTY |
822 EXTENT_SET_WRITEBACK |
823 EXTENT_END_WRITEBACK);
825 *nr_written = *nr_written +
826 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
827 *page_started = 1;
828 ret = 0;
829 goto out;
833 BUG_ON(disk_num_bytes >
834 btrfs_super_total_bytes(&root->fs_info->super_copy));
836 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
837 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
839 while (disk_num_bytes > 0) {
840 unsigned long op;
842 cur_alloc_size = disk_num_bytes;
843 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
844 root->sectorsize, 0, alloc_hint,
845 (u64)-1, &ins, 1);
846 BUG_ON(ret);
848 em = alloc_extent_map();
849 BUG_ON(!em);
850 em->start = start;
851 em->orig_start = em->start;
852 ram_size = ins.offset;
853 em->len = ins.offset;
855 em->block_start = ins.objectid;
856 em->block_len = ins.offset;
857 em->bdev = root->fs_info->fs_devices->latest_bdev;
858 set_bit(EXTENT_FLAG_PINNED, &em->flags);
860 while (1) {
861 write_lock(&em_tree->lock);
862 ret = add_extent_mapping(em_tree, em);
863 write_unlock(&em_tree->lock);
864 if (ret != -EEXIST) {
865 free_extent_map(em);
866 break;
868 btrfs_drop_extent_cache(inode, start,
869 start + ram_size - 1, 0);
872 cur_alloc_size = ins.offset;
873 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
874 ram_size, cur_alloc_size, 0);
875 BUG_ON(ret);
877 if (root->root_key.objectid ==
878 BTRFS_DATA_RELOC_TREE_OBJECTID) {
879 ret = btrfs_reloc_clone_csums(inode, start,
880 cur_alloc_size);
881 BUG_ON(ret);
884 if (disk_num_bytes < cur_alloc_size)
885 break;
887 /* we're not doing compressed IO, don't unlock the first
888 * page (which the caller expects to stay locked), don't
889 * clear any dirty bits and don't set any writeback bits
891 * Do set the Private2 bit so we know this page was properly
892 * setup for writepage
894 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
895 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
896 EXTENT_SET_PRIVATE2;
898 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
899 start, start + ram_size - 1,
900 locked_page, op);
901 disk_num_bytes -= cur_alloc_size;
902 num_bytes -= cur_alloc_size;
903 alloc_hint = ins.objectid + ins.offset;
904 start += cur_alloc_size;
906 out:
907 ret = 0;
908 btrfs_end_transaction(trans, root);
910 return ret;
914 * work queue call back to started compression on a file and pages
916 static noinline void async_cow_start(struct btrfs_work *work)
918 struct async_cow *async_cow;
919 int num_added = 0;
920 async_cow = container_of(work, struct async_cow, work);
922 compress_file_range(async_cow->inode, async_cow->locked_page,
923 async_cow->start, async_cow->end, async_cow,
924 &num_added);
925 if (num_added == 0)
926 async_cow->inode = NULL;
930 * work queue call back to submit previously compressed pages
932 static noinline void async_cow_submit(struct btrfs_work *work)
934 struct async_cow *async_cow;
935 struct btrfs_root *root;
936 unsigned long nr_pages;
938 async_cow = container_of(work, struct async_cow, work);
940 root = async_cow->root;
941 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
942 PAGE_CACHE_SHIFT;
944 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
946 if (atomic_read(&root->fs_info->async_delalloc_pages) <
947 5 * 1042 * 1024 &&
948 waitqueue_active(&root->fs_info->async_submit_wait))
949 wake_up(&root->fs_info->async_submit_wait);
951 if (async_cow->inode)
952 submit_compressed_extents(async_cow->inode, async_cow);
955 static noinline void async_cow_free(struct btrfs_work *work)
957 struct async_cow *async_cow;
958 async_cow = container_of(work, struct async_cow, work);
959 kfree(async_cow);
962 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
963 u64 start, u64 end, int *page_started,
964 unsigned long *nr_written)
966 struct async_cow *async_cow;
967 struct btrfs_root *root = BTRFS_I(inode)->root;
968 unsigned long nr_pages;
969 u64 cur_end;
970 int limit = 10 * 1024 * 1042;
972 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
973 1, 0, NULL, GFP_NOFS);
974 while (start < end) {
975 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
976 BUG_ON(!async_cow);
977 async_cow->inode = inode;
978 async_cow->root = root;
979 async_cow->locked_page = locked_page;
980 async_cow->start = start;
982 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
983 cur_end = end;
984 else
985 cur_end = min(end, start + 512 * 1024 - 1);
987 async_cow->end = cur_end;
988 INIT_LIST_HEAD(&async_cow->extents);
990 async_cow->work.func = async_cow_start;
991 async_cow->work.ordered_func = async_cow_submit;
992 async_cow->work.ordered_free = async_cow_free;
993 async_cow->work.flags = 0;
995 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
996 PAGE_CACHE_SHIFT;
997 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
999 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1000 &async_cow->work);
1002 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1003 wait_event(root->fs_info->async_submit_wait,
1004 (atomic_read(&root->fs_info->async_delalloc_pages) <
1005 limit));
1008 while (atomic_read(&root->fs_info->async_submit_draining) &&
1009 atomic_read(&root->fs_info->async_delalloc_pages)) {
1010 wait_event(root->fs_info->async_submit_wait,
1011 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1012 0));
1015 *nr_written += nr_pages;
1016 start = cur_end + 1;
1018 *page_started = 1;
1019 return 0;
1022 static noinline int csum_exist_in_range(struct btrfs_root *root,
1023 u64 bytenr, u64 num_bytes)
1025 int ret;
1026 struct btrfs_ordered_sum *sums;
1027 LIST_HEAD(list);
1029 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1030 bytenr + num_bytes - 1, &list, 0);
1031 if (ret == 0 && list_empty(&list))
1032 return 0;
1034 while (!list_empty(&list)) {
1035 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1036 list_del(&sums->list);
1037 kfree(sums);
1039 return 1;
1043 * when nowcow writeback call back. This checks for snapshots or COW copies
1044 * of the extents that exist in the file, and COWs the file as required.
1046 * If no cow copies or snapshots exist, we write directly to the existing
1047 * blocks on disk
1049 static noinline int run_delalloc_nocow(struct inode *inode,
1050 struct page *locked_page,
1051 u64 start, u64 end, int *page_started, int force,
1052 unsigned long *nr_written)
1054 struct btrfs_root *root = BTRFS_I(inode)->root;
1055 struct btrfs_trans_handle *trans;
1056 struct extent_buffer *leaf;
1057 struct btrfs_path *path;
1058 struct btrfs_file_extent_item *fi;
1059 struct btrfs_key found_key;
1060 u64 cow_start;
1061 u64 cur_offset;
1062 u64 extent_end;
1063 u64 extent_offset;
1064 u64 disk_bytenr;
1065 u64 num_bytes;
1066 int extent_type;
1067 int ret;
1068 int type;
1069 int nocow;
1070 int check_prev = 1;
1071 bool nolock;
1072 u64 ino = btrfs_ino(inode);
1074 path = btrfs_alloc_path();
1075 BUG_ON(!path);
1077 nolock = is_free_space_inode(root, inode);
1079 if (nolock)
1080 trans = btrfs_join_transaction_nolock(root, 1);
1081 else
1082 trans = btrfs_join_transaction(root, 1);
1083 BUG_ON(IS_ERR(trans));
1085 cow_start = (u64)-1;
1086 cur_offset = start;
1087 while (1) {
1088 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1089 cur_offset, 0);
1090 BUG_ON(ret < 0);
1091 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1092 leaf = path->nodes[0];
1093 btrfs_item_key_to_cpu(leaf, &found_key,
1094 path->slots[0] - 1);
1095 if (found_key.objectid == ino &&
1096 found_key.type == BTRFS_EXTENT_DATA_KEY)
1097 path->slots[0]--;
1099 check_prev = 0;
1100 next_slot:
1101 leaf = path->nodes[0];
1102 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1103 ret = btrfs_next_leaf(root, path);
1104 if (ret < 0)
1105 BUG_ON(1);
1106 if (ret > 0)
1107 break;
1108 leaf = path->nodes[0];
1111 nocow = 0;
1112 disk_bytenr = 0;
1113 num_bytes = 0;
1114 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1116 if (found_key.objectid > ino ||
1117 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1118 found_key.offset > end)
1119 break;
1121 if (found_key.offset > cur_offset) {
1122 extent_end = found_key.offset;
1123 extent_type = 0;
1124 goto out_check;
1127 fi = btrfs_item_ptr(leaf, path->slots[0],
1128 struct btrfs_file_extent_item);
1129 extent_type = btrfs_file_extent_type(leaf, fi);
1131 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1132 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1133 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1134 extent_offset = btrfs_file_extent_offset(leaf, fi);
1135 extent_end = found_key.offset +
1136 btrfs_file_extent_num_bytes(leaf, fi);
1137 if (extent_end <= start) {
1138 path->slots[0]++;
1139 goto next_slot;
1141 if (disk_bytenr == 0)
1142 goto out_check;
1143 if (btrfs_file_extent_compression(leaf, fi) ||
1144 btrfs_file_extent_encryption(leaf, fi) ||
1145 btrfs_file_extent_other_encoding(leaf, fi))
1146 goto out_check;
1147 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1148 goto out_check;
1149 if (btrfs_extent_readonly(root, disk_bytenr))
1150 goto out_check;
1151 if (btrfs_cross_ref_exist(trans, root, ino,
1152 found_key.offset -
1153 extent_offset, disk_bytenr))
1154 goto out_check;
1155 disk_bytenr += extent_offset;
1156 disk_bytenr += cur_offset - found_key.offset;
1157 num_bytes = min(end + 1, extent_end) - cur_offset;
1159 * force cow if csum exists in the range.
1160 * this ensure that csum for a given extent are
1161 * either valid or do not exist.
1163 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1164 goto out_check;
1165 nocow = 1;
1166 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1167 extent_end = found_key.offset +
1168 btrfs_file_extent_inline_len(leaf, fi);
1169 extent_end = ALIGN(extent_end, root->sectorsize);
1170 } else {
1171 BUG_ON(1);
1173 out_check:
1174 if (extent_end <= start) {
1175 path->slots[0]++;
1176 goto next_slot;
1178 if (!nocow) {
1179 if (cow_start == (u64)-1)
1180 cow_start = cur_offset;
1181 cur_offset = extent_end;
1182 if (cur_offset > end)
1183 break;
1184 path->slots[0]++;
1185 goto next_slot;
1188 btrfs_release_path(path);
1189 if (cow_start != (u64)-1) {
1190 ret = cow_file_range(inode, locked_page, cow_start,
1191 found_key.offset - 1, page_started,
1192 nr_written, 1);
1193 BUG_ON(ret);
1194 cow_start = (u64)-1;
1197 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1198 struct extent_map *em;
1199 struct extent_map_tree *em_tree;
1200 em_tree = &BTRFS_I(inode)->extent_tree;
1201 em = alloc_extent_map();
1202 BUG_ON(!em);
1203 em->start = cur_offset;
1204 em->orig_start = em->start;
1205 em->len = num_bytes;
1206 em->block_len = num_bytes;
1207 em->block_start = disk_bytenr;
1208 em->bdev = root->fs_info->fs_devices->latest_bdev;
1209 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1210 while (1) {
1211 write_lock(&em_tree->lock);
1212 ret = add_extent_mapping(em_tree, em);
1213 write_unlock(&em_tree->lock);
1214 if (ret != -EEXIST) {
1215 free_extent_map(em);
1216 break;
1218 btrfs_drop_extent_cache(inode, em->start,
1219 em->start + em->len - 1, 0);
1221 type = BTRFS_ORDERED_PREALLOC;
1222 } else {
1223 type = BTRFS_ORDERED_NOCOW;
1226 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1227 num_bytes, num_bytes, type);
1228 BUG_ON(ret);
1230 if (root->root_key.objectid ==
1231 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1232 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1233 num_bytes);
1234 BUG_ON(ret);
1237 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1238 cur_offset, cur_offset + num_bytes - 1,
1239 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1240 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1241 EXTENT_SET_PRIVATE2);
1242 cur_offset = extent_end;
1243 if (cur_offset > end)
1244 break;
1246 btrfs_release_path(path);
1248 if (cur_offset <= end && cow_start == (u64)-1)
1249 cow_start = cur_offset;
1250 if (cow_start != (u64)-1) {
1251 ret = cow_file_range(inode, locked_page, cow_start, end,
1252 page_started, nr_written, 1);
1253 BUG_ON(ret);
1256 if (nolock) {
1257 ret = btrfs_end_transaction_nolock(trans, root);
1258 BUG_ON(ret);
1259 } else {
1260 ret = btrfs_end_transaction(trans, root);
1261 BUG_ON(ret);
1263 btrfs_free_path(path);
1264 return 0;
1268 * extent_io.c call back to do delayed allocation processing
1270 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1271 u64 start, u64 end, int *page_started,
1272 unsigned long *nr_written)
1274 int ret;
1275 struct btrfs_root *root = BTRFS_I(inode)->root;
1277 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1278 ret = run_delalloc_nocow(inode, locked_page, start, end,
1279 page_started, 1, nr_written);
1280 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1281 ret = run_delalloc_nocow(inode, locked_page, start, end,
1282 page_started, 0, nr_written);
1283 else if (!btrfs_test_opt(root, COMPRESS) &&
1284 !(BTRFS_I(inode)->force_compress) &&
1285 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
1286 ret = cow_file_range(inode, locked_page, start, end,
1287 page_started, nr_written, 1);
1288 else
1289 ret = cow_file_range_async(inode, locked_page, start, end,
1290 page_started, nr_written);
1291 return ret;
1294 static int btrfs_split_extent_hook(struct inode *inode,
1295 struct extent_state *orig, u64 split)
1297 /* not delalloc, ignore it */
1298 if (!(orig->state & EXTENT_DELALLOC))
1299 return 0;
1301 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1302 return 0;
1306 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1307 * extents so we can keep track of new extents that are just merged onto old
1308 * extents, such as when we are doing sequential writes, so we can properly
1309 * account for the metadata space we'll need.
1311 static int btrfs_merge_extent_hook(struct inode *inode,
1312 struct extent_state *new,
1313 struct extent_state *other)
1315 /* not delalloc, ignore it */
1316 if (!(other->state & EXTENT_DELALLOC))
1317 return 0;
1319 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1320 return 0;
1324 * extent_io.c set_bit_hook, used to track delayed allocation
1325 * bytes in this file, and to maintain the list of inodes that
1326 * have pending delalloc work to be done.
1328 static int btrfs_set_bit_hook(struct inode *inode,
1329 struct extent_state *state, int *bits)
1333 * set_bit and clear bit hooks normally require _irqsave/restore
1334 * but in this case, we are only testing for the DELALLOC
1335 * bit, which is only set or cleared with irqs on
1337 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1338 struct btrfs_root *root = BTRFS_I(inode)->root;
1339 u64 len = state->end + 1 - state->start;
1340 bool do_list = !is_free_space_inode(root, inode);
1342 if (*bits & EXTENT_FIRST_DELALLOC)
1343 *bits &= ~EXTENT_FIRST_DELALLOC;
1344 else
1345 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1347 spin_lock(&root->fs_info->delalloc_lock);
1348 BTRFS_I(inode)->delalloc_bytes += len;
1349 root->fs_info->delalloc_bytes += len;
1350 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1351 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1352 &root->fs_info->delalloc_inodes);
1354 spin_unlock(&root->fs_info->delalloc_lock);
1356 return 0;
1360 * extent_io.c clear_bit_hook, see set_bit_hook for why
1362 static int btrfs_clear_bit_hook(struct inode *inode,
1363 struct extent_state *state, int *bits)
1366 * set_bit and clear bit hooks normally require _irqsave/restore
1367 * but in this case, we are only testing for the DELALLOC
1368 * bit, which is only set or cleared with irqs on
1370 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1371 struct btrfs_root *root = BTRFS_I(inode)->root;
1372 u64 len = state->end + 1 - state->start;
1373 bool do_list = !is_free_space_inode(root, inode);
1375 if (*bits & EXTENT_FIRST_DELALLOC)
1376 *bits &= ~EXTENT_FIRST_DELALLOC;
1377 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1378 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1380 if (*bits & EXTENT_DO_ACCOUNTING)
1381 btrfs_delalloc_release_metadata(inode, len);
1383 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1384 && do_list)
1385 btrfs_free_reserved_data_space(inode, len);
1387 spin_lock(&root->fs_info->delalloc_lock);
1388 root->fs_info->delalloc_bytes -= len;
1389 BTRFS_I(inode)->delalloc_bytes -= len;
1391 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1392 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1393 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1395 spin_unlock(&root->fs_info->delalloc_lock);
1397 return 0;
1401 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1402 * we don't create bios that span stripes or chunks
1404 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1405 size_t size, struct bio *bio,
1406 unsigned long bio_flags)
1408 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1409 struct btrfs_mapping_tree *map_tree;
1410 u64 logical = (u64)bio->bi_sector << 9;
1411 u64 length = 0;
1412 u64 map_length;
1413 int ret;
1415 if (bio_flags & EXTENT_BIO_COMPRESSED)
1416 return 0;
1418 length = bio->bi_size;
1419 map_tree = &root->fs_info->mapping_tree;
1420 map_length = length;
1421 ret = btrfs_map_block(map_tree, READ, logical,
1422 &map_length, NULL, 0);
1424 if (map_length < length + size)
1425 return 1;
1426 return ret;
1430 * in order to insert checksums into the metadata in large chunks,
1431 * we wait until bio submission time. All the pages in the bio are
1432 * checksummed and sums are attached onto the ordered extent record.
1434 * At IO completion time the cums attached on the ordered extent record
1435 * are inserted into the btree
1437 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1438 struct bio *bio, int mirror_num,
1439 unsigned long bio_flags,
1440 u64 bio_offset)
1442 struct btrfs_root *root = BTRFS_I(inode)->root;
1443 int ret = 0;
1445 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1446 BUG_ON(ret);
1447 return 0;
1451 * in order to insert checksums into the metadata in large chunks,
1452 * we wait until bio submission time. All the pages in the bio are
1453 * checksummed and sums are attached onto the ordered extent record.
1455 * At IO completion time the cums attached on the ordered extent record
1456 * are inserted into the btree
1458 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1459 int mirror_num, unsigned long bio_flags,
1460 u64 bio_offset)
1462 struct btrfs_root *root = BTRFS_I(inode)->root;
1463 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1467 * extent_io.c submission hook. This does the right thing for csum calculation
1468 * on write, or reading the csums from the tree before a read
1470 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1471 int mirror_num, unsigned long bio_flags,
1472 u64 bio_offset)
1474 struct btrfs_root *root = BTRFS_I(inode)->root;
1475 int ret = 0;
1476 int skip_sum;
1478 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1480 if (is_free_space_inode(root, inode))
1481 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1482 else
1483 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1484 BUG_ON(ret);
1486 if (!(rw & REQ_WRITE)) {
1487 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1488 return btrfs_submit_compressed_read(inode, bio,
1489 mirror_num, bio_flags);
1490 } else if (!skip_sum) {
1491 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1492 if (ret)
1493 return ret;
1495 goto mapit;
1496 } else if (!skip_sum) {
1497 /* csum items have already been cloned */
1498 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1499 goto mapit;
1500 /* we're doing a write, do the async checksumming */
1501 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1502 inode, rw, bio, mirror_num,
1503 bio_flags, bio_offset,
1504 __btrfs_submit_bio_start,
1505 __btrfs_submit_bio_done);
1508 mapit:
1509 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1513 * given a list of ordered sums record them in the inode. This happens
1514 * at IO completion time based on sums calculated at bio submission time.
1516 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1517 struct inode *inode, u64 file_offset,
1518 struct list_head *list)
1520 struct btrfs_ordered_sum *sum;
1522 btrfs_set_trans_block_group(trans, inode);
1524 list_for_each_entry(sum, list, list) {
1525 btrfs_csum_file_blocks(trans,
1526 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1528 return 0;
1531 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1532 struct extent_state **cached_state)
1534 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1535 WARN_ON(1);
1536 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1537 cached_state, GFP_NOFS);
1540 /* see btrfs_writepage_start_hook for details on why this is required */
1541 struct btrfs_writepage_fixup {
1542 struct page *page;
1543 struct btrfs_work work;
1546 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1548 struct btrfs_writepage_fixup *fixup;
1549 struct btrfs_ordered_extent *ordered;
1550 struct extent_state *cached_state = NULL;
1551 struct page *page;
1552 struct inode *inode;
1553 u64 page_start;
1554 u64 page_end;
1556 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1557 page = fixup->page;
1558 again:
1559 lock_page(page);
1560 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1561 ClearPageChecked(page);
1562 goto out_page;
1565 inode = page->mapping->host;
1566 page_start = page_offset(page);
1567 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1569 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1570 &cached_state, GFP_NOFS);
1572 /* already ordered? We're done */
1573 if (PagePrivate2(page))
1574 goto out;
1576 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1577 if (ordered) {
1578 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1579 page_end, &cached_state, GFP_NOFS);
1580 unlock_page(page);
1581 btrfs_start_ordered_extent(inode, ordered, 1);
1582 goto again;
1585 BUG();
1586 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1587 ClearPageChecked(page);
1588 out:
1589 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1590 &cached_state, GFP_NOFS);
1591 out_page:
1592 unlock_page(page);
1593 page_cache_release(page);
1594 kfree(fixup);
1598 * There are a few paths in the higher layers of the kernel that directly
1599 * set the page dirty bit without asking the filesystem if it is a
1600 * good idea. This causes problems because we want to make sure COW
1601 * properly happens and the data=ordered rules are followed.
1603 * In our case any range that doesn't have the ORDERED bit set
1604 * hasn't been properly setup for IO. We kick off an async process
1605 * to fix it up. The async helper will wait for ordered extents, set
1606 * the delalloc bit and make it safe to write the page.
1608 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1610 struct inode *inode = page->mapping->host;
1611 struct btrfs_writepage_fixup *fixup;
1612 struct btrfs_root *root = BTRFS_I(inode)->root;
1614 /* this page is properly in the ordered list */
1615 if (TestClearPagePrivate2(page))
1616 return 0;
1618 if (PageChecked(page))
1619 return -EAGAIN;
1621 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1622 if (!fixup)
1623 return -EAGAIN;
1625 SetPageChecked(page);
1626 page_cache_get(page);
1627 fixup->work.func = btrfs_writepage_fixup_worker;
1628 fixup->page = page;
1629 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1630 return -EAGAIN;
1633 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1634 struct inode *inode, u64 file_pos,
1635 u64 disk_bytenr, u64 disk_num_bytes,
1636 u64 num_bytes, u64 ram_bytes,
1637 u8 compression, u8 encryption,
1638 u16 other_encoding, int extent_type)
1640 struct btrfs_root *root = BTRFS_I(inode)->root;
1641 struct btrfs_file_extent_item *fi;
1642 struct btrfs_path *path;
1643 struct extent_buffer *leaf;
1644 struct btrfs_key ins;
1645 u64 hint;
1646 int ret;
1648 path = btrfs_alloc_path();
1649 BUG_ON(!path);
1651 path->leave_spinning = 1;
1654 * we may be replacing one extent in the tree with another.
1655 * The new extent is pinned in the extent map, and we don't want
1656 * to drop it from the cache until it is completely in the btree.
1658 * So, tell btrfs_drop_extents to leave this extent in the cache.
1659 * the caller is expected to unpin it and allow it to be merged
1660 * with the others.
1662 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1663 &hint, 0);
1664 BUG_ON(ret);
1666 ins.objectid = btrfs_ino(inode);
1667 ins.offset = file_pos;
1668 ins.type = BTRFS_EXTENT_DATA_KEY;
1669 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1670 BUG_ON(ret);
1671 leaf = path->nodes[0];
1672 fi = btrfs_item_ptr(leaf, path->slots[0],
1673 struct btrfs_file_extent_item);
1674 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1675 btrfs_set_file_extent_type(leaf, fi, extent_type);
1676 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1677 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1678 btrfs_set_file_extent_offset(leaf, fi, 0);
1679 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1680 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1681 btrfs_set_file_extent_compression(leaf, fi, compression);
1682 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1683 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1685 btrfs_unlock_up_safe(path, 1);
1686 btrfs_set_lock_blocking(leaf);
1688 btrfs_mark_buffer_dirty(leaf);
1690 inode_add_bytes(inode, num_bytes);
1692 ins.objectid = disk_bytenr;
1693 ins.offset = disk_num_bytes;
1694 ins.type = BTRFS_EXTENT_ITEM_KEY;
1695 ret = btrfs_alloc_reserved_file_extent(trans, root,
1696 root->root_key.objectid,
1697 btrfs_ino(inode), file_pos, &ins);
1698 BUG_ON(ret);
1699 btrfs_free_path(path);
1701 return 0;
1705 * helper function for btrfs_finish_ordered_io, this
1706 * just reads in some of the csum leaves to prime them into ram
1707 * before we start the transaction. It limits the amount of btree
1708 * reads required while inside the transaction.
1710 /* as ordered data IO finishes, this gets called so we can finish
1711 * an ordered extent if the range of bytes in the file it covers are
1712 * fully written.
1714 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1716 struct btrfs_root *root = BTRFS_I(inode)->root;
1717 struct btrfs_trans_handle *trans = NULL;
1718 struct btrfs_ordered_extent *ordered_extent = NULL;
1719 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1720 struct extent_state *cached_state = NULL;
1721 int compress_type = 0;
1722 int ret;
1723 bool nolock;
1725 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1726 end - start + 1);
1727 if (!ret)
1728 return 0;
1729 BUG_ON(!ordered_extent);
1731 nolock = is_free_space_inode(root, inode);
1733 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1734 BUG_ON(!list_empty(&ordered_extent->list));
1735 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1736 if (!ret) {
1737 if (nolock)
1738 trans = btrfs_join_transaction_nolock(root, 1);
1739 else
1740 trans = btrfs_join_transaction(root, 1);
1741 BUG_ON(IS_ERR(trans));
1742 btrfs_set_trans_block_group(trans, inode);
1743 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1744 ret = btrfs_update_inode(trans, root, inode);
1745 BUG_ON(ret);
1747 goto out;
1750 lock_extent_bits(io_tree, ordered_extent->file_offset,
1751 ordered_extent->file_offset + ordered_extent->len - 1,
1752 0, &cached_state, GFP_NOFS);
1754 if (nolock)
1755 trans = btrfs_join_transaction_nolock(root, 1);
1756 else
1757 trans = btrfs_join_transaction(root, 1);
1758 BUG_ON(IS_ERR(trans));
1759 btrfs_set_trans_block_group(trans, inode);
1760 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1762 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1763 compress_type = ordered_extent->compress_type;
1764 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1765 BUG_ON(compress_type);
1766 ret = btrfs_mark_extent_written(trans, inode,
1767 ordered_extent->file_offset,
1768 ordered_extent->file_offset +
1769 ordered_extent->len);
1770 BUG_ON(ret);
1771 } else {
1772 BUG_ON(root == root->fs_info->tree_root);
1773 ret = insert_reserved_file_extent(trans, inode,
1774 ordered_extent->file_offset,
1775 ordered_extent->start,
1776 ordered_extent->disk_len,
1777 ordered_extent->len,
1778 ordered_extent->len,
1779 compress_type, 0, 0,
1780 BTRFS_FILE_EXTENT_REG);
1781 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1782 ordered_extent->file_offset,
1783 ordered_extent->len);
1784 BUG_ON(ret);
1786 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1787 ordered_extent->file_offset +
1788 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1790 add_pending_csums(trans, inode, ordered_extent->file_offset,
1791 &ordered_extent->list);
1793 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1794 if (!ret) {
1795 ret = btrfs_update_inode(trans, root, inode);
1796 BUG_ON(ret);
1798 ret = 0;
1799 out:
1800 if (nolock) {
1801 if (trans)
1802 btrfs_end_transaction_nolock(trans, root);
1803 } else {
1804 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1805 if (trans)
1806 btrfs_end_transaction(trans, root);
1809 /* once for us */
1810 btrfs_put_ordered_extent(ordered_extent);
1811 /* once for the tree */
1812 btrfs_put_ordered_extent(ordered_extent);
1814 return 0;
1817 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1818 struct extent_state *state, int uptodate)
1820 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1822 ClearPagePrivate2(page);
1823 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1827 * When IO fails, either with EIO or csum verification fails, we
1828 * try other mirrors that might have a good copy of the data. This
1829 * io_failure_record is used to record state as we go through all the
1830 * mirrors. If another mirror has good data, the page is set up to date
1831 * and things continue. If a good mirror can't be found, the original
1832 * bio end_io callback is called to indicate things have failed.
1834 struct io_failure_record {
1835 struct page *page;
1836 u64 start;
1837 u64 len;
1838 u64 logical;
1839 unsigned long bio_flags;
1840 int last_mirror;
1843 static int btrfs_io_failed_hook(struct bio *failed_bio,
1844 struct page *page, u64 start, u64 end,
1845 struct extent_state *state)
1847 struct io_failure_record *failrec = NULL;
1848 u64 private;
1849 struct extent_map *em;
1850 struct inode *inode = page->mapping->host;
1851 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1852 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1853 struct bio *bio;
1854 int num_copies;
1855 int ret;
1856 int rw;
1857 u64 logical;
1859 ret = get_state_private(failure_tree, start, &private);
1860 if (ret) {
1861 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1862 if (!failrec)
1863 return -ENOMEM;
1864 failrec->start = start;
1865 failrec->len = end - start + 1;
1866 failrec->last_mirror = 0;
1867 failrec->bio_flags = 0;
1869 read_lock(&em_tree->lock);
1870 em = lookup_extent_mapping(em_tree, start, failrec->len);
1871 if (em->start > start || em->start + em->len < start) {
1872 free_extent_map(em);
1873 em = NULL;
1875 read_unlock(&em_tree->lock);
1877 if (IS_ERR_OR_NULL(em)) {
1878 kfree(failrec);
1879 return -EIO;
1881 logical = start - em->start;
1882 logical = em->block_start + logical;
1883 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1884 logical = em->block_start;
1885 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1886 extent_set_compress_type(&failrec->bio_flags,
1887 em->compress_type);
1889 failrec->logical = logical;
1890 free_extent_map(em);
1891 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1892 EXTENT_DIRTY, GFP_NOFS);
1893 set_state_private(failure_tree, start,
1894 (u64)(unsigned long)failrec);
1895 } else {
1896 failrec = (struct io_failure_record *)(unsigned long)private;
1898 num_copies = btrfs_num_copies(
1899 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1900 failrec->logical, failrec->len);
1901 failrec->last_mirror++;
1902 if (!state) {
1903 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1904 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1905 failrec->start,
1906 EXTENT_LOCKED);
1907 if (state && state->start != failrec->start)
1908 state = NULL;
1909 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1911 if (!state || failrec->last_mirror > num_copies) {
1912 set_state_private(failure_tree, failrec->start, 0);
1913 clear_extent_bits(failure_tree, failrec->start,
1914 failrec->start + failrec->len - 1,
1915 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1916 kfree(failrec);
1917 return -EIO;
1919 bio = bio_alloc(GFP_NOFS, 1);
1920 bio->bi_private = state;
1921 bio->bi_end_io = failed_bio->bi_end_io;
1922 bio->bi_sector = failrec->logical >> 9;
1923 bio->bi_bdev = failed_bio->bi_bdev;
1924 bio->bi_size = 0;
1926 bio_add_page(bio, page, failrec->len, start - page_offset(page));
1927 if (failed_bio->bi_rw & REQ_WRITE)
1928 rw = WRITE;
1929 else
1930 rw = READ;
1932 ret = BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1933 failrec->last_mirror,
1934 failrec->bio_flags, 0);
1935 return ret;
1939 * each time an IO finishes, we do a fast check in the IO failure tree
1940 * to see if we need to process or clean up an io_failure_record
1942 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1944 u64 private;
1945 u64 private_failure;
1946 struct io_failure_record *failure;
1947 int ret;
1949 private = 0;
1950 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1951 (u64)-1, 1, EXTENT_DIRTY, 0)) {
1952 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1953 start, &private_failure);
1954 if (ret == 0) {
1955 failure = (struct io_failure_record *)(unsigned long)
1956 private_failure;
1957 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1958 failure->start, 0);
1959 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1960 failure->start,
1961 failure->start + failure->len - 1,
1962 EXTENT_DIRTY | EXTENT_LOCKED,
1963 GFP_NOFS);
1964 kfree(failure);
1967 return 0;
1971 * when reads are done, we need to check csums to verify the data is correct
1972 * if there's a match, we allow the bio to finish. If not, we go through
1973 * the io_failure_record routines to find good copies
1975 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1976 struct extent_state *state)
1978 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1979 struct inode *inode = page->mapping->host;
1980 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1981 char *kaddr;
1982 u64 private = ~(u32)0;
1983 int ret;
1984 struct btrfs_root *root = BTRFS_I(inode)->root;
1985 u32 csum = ~(u32)0;
1987 if (PageChecked(page)) {
1988 ClearPageChecked(page);
1989 goto good;
1992 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1993 return 0;
1995 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1996 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1997 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1998 GFP_NOFS);
1999 return 0;
2002 if (state && state->start == start) {
2003 private = state->private;
2004 ret = 0;
2005 } else {
2006 ret = get_state_private(io_tree, start, &private);
2008 kaddr = kmap_atomic(page, KM_USER0);
2009 if (ret)
2010 goto zeroit;
2012 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2013 btrfs_csum_final(csum, (char *)&csum);
2014 if (csum != private)
2015 goto zeroit;
2017 kunmap_atomic(kaddr, KM_USER0);
2018 good:
2019 /* if the io failure tree for this inode is non-empty,
2020 * check to see if we've recovered from a failed IO
2022 btrfs_clean_io_failures(inode, start);
2023 return 0;
2025 zeroit:
2026 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2027 "private %llu\n",
2028 (unsigned long long)btrfs_ino(page->mapping->host),
2029 (unsigned long long)start, csum,
2030 (unsigned long long)private);
2031 memset(kaddr + offset, 1, end - start + 1);
2032 flush_dcache_page(page);
2033 kunmap_atomic(kaddr, KM_USER0);
2034 if (private == 0)
2035 return 0;
2036 return -EIO;
2039 struct delayed_iput {
2040 struct list_head list;
2041 struct inode *inode;
2044 void btrfs_add_delayed_iput(struct inode *inode)
2046 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2047 struct delayed_iput *delayed;
2049 if (atomic_add_unless(&inode->i_count, -1, 1))
2050 return;
2052 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2053 delayed->inode = inode;
2055 spin_lock(&fs_info->delayed_iput_lock);
2056 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2057 spin_unlock(&fs_info->delayed_iput_lock);
2060 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2062 LIST_HEAD(list);
2063 struct btrfs_fs_info *fs_info = root->fs_info;
2064 struct delayed_iput *delayed;
2065 int empty;
2067 spin_lock(&fs_info->delayed_iput_lock);
2068 empty = list_empty(&fs_info->delayed_iputs);
2069 spin_unlock(&fs_info->delayed_iput_lock);
2070 if (empty)
2071 return;
2073 down_read(&root->fs_info->cleanup_work_sem);
2074 spin_lock(&fs_info->delayed_iput_lock);
2075 list_splice_init(&fs_info->delayed_iputs, &list);
2076 spin_unlock(&fs_info->delayed_iput_lock);
2078 while (!list_empty(&list)) {
2079 delayed = list_entry(list.next, struct delayed_iput, list);
2080 list_del(&delayed->list);
2081 iput(delayed->inode);
2082 kfree(delayed);
2084 up_read(&root->fs_info->cleanup_work_sem);
2088 * calculate extra metadata reservation when snapshotting a subvolume
2089 * contains orphan files.
2091 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2092 struct btrfs_pending_snapshot *pending,
2093 u64 *bytes_to_reserve)
2095 struct btrfs_root *root;
2096 struct btrfs_block_rsv *block_rsv;
2097 u64 num_bytes;
2098 int index;
2100 root = pending->root;
2101 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2102 return;
2104 block_rsv = root->orphan_block_rsv;
2106 /* orphan block reservation for the snapshot */
2107 num_bytes = block_rsv->size;
2110 * after the snapshot is created, COWing tree blocks may use more
2111 * space than it frees. So we should make sure there is enough
2112 * reserved space.
2114 index = trans->transid & 0x1;
2115 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2116 num_bytes += block_rsv->size -
2117 (block_rsv->reserved + block_rsv->freed[index]);
2120 *bytes_to_reserve += num_bytes;
2123 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2124 struct btrfs_pending_snapshot *pending)
2126 struct btrfs_root *root = pending->root;
2127 struct btrfs_root *snap = pending->snap;
2128 struct btrfs_block_rsv *block_rsv;
2129 u64 num_bytes;
2130 int index;
2131 int ret;
2133 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2134 return;
2136 /* refill source subvolume's orphan block reservation */
2137 block_rsv = root->orphan_block_rsv;
2138 index = trans->transid & 0x1;
2139 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2140 num_bytes = block_rsv->size -
2141 (block_rsv->reserved + block_rsv->freed[index]);
2142 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2143 root->orphan_block_rsv,
2144 num_bytes);
2145 BUG_ON(ret);
2148 /* setup orphan block reservation for the snapshot */
2149 block_rsv = btrfs_alloc_block_rsv(snap);
2150 BUG_ON(!block_rsv);
2152 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2153 snap->orphan_block_rsv = block_rsv;
2155 num_bytes = root->orphan_block_rsv->size;
2156 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2157 block_rsv, num_bytes);
2158 BUG_ON(ret);
2160 #if 0
2161 /* insert orphan item for the snapshot */
2162 WARN_ON(!root->orphan_item_inserted);
2163 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2164 snap->root_key.objectid);
2165 BUG_ON(ret);
2166 snap->orphan_item_inserted = 1;
2167 #endif
2170 enum btrfs_orphan_cleanup_state {
2171 ORPHAN_CLEANUP_STARTED = 1,
2172 ORPHAN_CLEANUP_DONE = 2,
2176 * This is called in transaction commmit time. If there are no orphan
2177 * files in the subvolume, it removes orphan item and frees block_rsv
2178 * structure.
2180 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2181 struct btrfs_root *root)
2183 int ret;
2185 if (!list_empty(&root->orphan_list) ||
2186 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2187 return;
2189 if (root->orphan_item_inserted &&
2190 btrfs_root_refs(&root->root_item) > 0) {
2191 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2192 root->root_key.objectid);
2193 BUG_ON(ret);
2194 root->orphan_item_inserted = 0;
2197 if (root->orphan_block_rsv) {
2198 WARN_ON(root->orphan_block_rsv->size > 0);
2199 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2200 root->orphan_block_rsv = NULL;
2205 * This creates an orphan entry for the given inode in case something goes
2206 * wrong in the middle of an unlink/truncate.
2208 * NOTE: caller of this function should reserve 5 units of metadata for
2209 * this function.
2211 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2213 struct btrfs_root *root = BTRFS_I(inode)->root;
2214 struct btrfs_block_rsv *block_rsv = NULL;
2215 int reserve = 0;
2216 int insert = 0;
2217 int ret;
2219 if (!root->orphan_block_rsv) {
2220 block_rsv = btrfs_alloc_block_rsv(root);
2221 BUG_ON(!block_rsv);
2224 spin_lock(&root->orphan_lock);
2225 if (!root->orphan_block_rsv) {
2226 root->orphan_block_rsv = block_rsv;
2227 } else if (block_rsv) {
2228 btrfs_free_block_rsv(root, block_rsv);
2229 block_rsv = NULL;
2232 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2233 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2234 #if 0
2236 * For proper ENOSPC handling, we should do orphan
2237 * cleanup when mounting. But this introduces backward
2238 * compatibility issue.
2240 if (!xchg(&root->orphan_item_inserted, 1))
2241 insert = 2;
2242 else
2243 insert = 1;
2244 #endif
2245 insert = 1;
2248 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2249 BTRFS_I(inode)->orphan_meta_reserved = 1;
2250 reserve = 1;
2252 spin_unlock(&root->orphan_lock);
2254 if (block_rsv)
2255 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2257 /* grab metadata reservation from transaction handle */
2258 if (reserve) {
2259 ret = btrfs_orphan_reserve_metadata(trans, inode);
2260 BUG_ON(ret);
2263 /* insert an orphan item to track this unlinked/truncated file */
2264 if (insert >= 1) {
2265 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2266 BUG_ON(ret);
2269 /* insert an orphan item to track subvolume contains orphan files */
2270 if (insert >= 2) {
2271 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2272 root->root_key.objectid);
2273 BUG_ON(ret);
2275 return 0;
2279 * We have done the truncate/delete so we can go ahead and remove the orphan
2280 * item for this particular inode.
2282 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2284 struct btrfs_root *root = BTRFS_I(inode)->root;
2285 int delete_item = 0;
2286 int release_rsv = 0;
2287 int ret = 0;
2289 spin_lock(&root->orphan_lock);
2290 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2291 list_del_init(&BTRFS_I(inode)->i_orphan);
2292 delete_item = 1;
2295 if (BTRFS_I(inode)->orphan_meta_reserved) {
2296 BTRFS_I(inode)->orphan_meta_reserved = 0;
2297 release_rsv = 1;
2299 spin_unlock(&root->orphan_lock);
2301 if (trans && delete_item) {
2302 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2303 BUG_ON(ret);
2306 if (release_rsv)
2307 btrfs_orphan_release_metadata(inode);
2309 return 0;
2313 * this cleans up any orphans that may be left on the list from the last use
2314 * of this root.
2316 int btrfs_orphan_cleanup(struct btrfs_root *root)
2318 struct btrfs_path *path;
2319 struct extent_buffer *leaf;
2320 struct btrfs_key key, found_key;
2321 struct btrfs_trans_handle *trans;
2322 struct inode *inode;
2323 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2325 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2326 return 0;
2328 path = btrfs_alloc_path();
2329 if (!path) {
2330 ret = -ENOMEM;
2331 goto out;
2333 path->reada = -1;
2335 key.objectid = BTRFS_ORPHAN_OBJECTID;
2336 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2337 key.offset = (u64)-1;
2339 while (1) {
2340 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2341 if (ret < 0)
2342 goto out;
2345 * if ret == 0 means we found what we were searching for, which
2346 * is weird, but possible, so only screw with path if we didn't
2347 * find the key and see if we have stuff that matches
2349 if (ret > 0) {
2350 ret = 0;
2351 if (path->slots[0] == 0)
2352 break;
2353 path->slots[0]--;
2356 /* pull out the item */
2357 leaf = path->nodes[0];
2358 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2360 /* make sure the item matches what we want */
2361 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2362 break;
2363 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2364 break;
2366 /* release the path since we're done with it */
2367 btrfs_release_path(path);
2370 * this is where we are basically btrfs_lookup, without the
2371 * crossing root thing. we store the inode number in the
2372 * offset of the orphan item.
2374 found_key.objectid = found_key.offset;
2375 found_key.type = BTRFS_INODE_ITEM_KEY;
2376 found_key.offset = 0;
2377 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2378 if (IS_ERR(inode)) {
2379 ret = PTR_ERR(inode);
2380 goto out;
2384 * add this inode to the orphan list so btrfs_orphan_del does
2385 * the proper thing when we hit it
2387 spin_lock(&root->orphan_lock);
2388 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2389 spin_unlock(&root->orphan_lock);
2392 * if this is a bad inode, means we actually succeeded in
2393 * removing the inode, but not the orphan record, which means
2394 * we need to manually delete the orphan since iput will just
2395 * do a destroy_inode
2397 if (is_bad_inode(inode)) {
2398 trans = btrfs_start_transaction(root, 0);
2399 if (IS_ERR(trans)) {
2400 ret = PTR_ERR(trans);
2401 goto out;
2403 btrfs_orphan_del(trans, inode);
2404 btrfs_end_transaction(trans, root);
2405 iput(inode);
2406 continue;
2409 /* if we have links, this was a truncate, lets do that */
2410 if (inode->i_nlink) {
2411 if (!S_ISREG(inode->i_mode)) {
2412 WARN_ON(1);
2413 iput(inode);
2414 continue;
2416 nr_truncate++;
2417 ret = btrfs_truncate(inode);
2418 } else {
2419 nr_unlink++;
2422 /* this will do delete_inode and everything for us */
2423 iput(inode);
2424 if (ret)
2425 goto out;
2427 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2429 if (root->orphan_block_rsv)
2430 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2431 (u64)-1);
2433 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2434 trans = btrfs_join_transaction(root, 1);
2435 if (!IS_ERR(trans))
2436 btrfs_end_transaction(trans, root);
2439 if (nr_unlink)
2440 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2441 if (nr_truncate)
2442 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2444 out:
2445 if (ret)
2446 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2447 btrfs_free_path(path);
2448 return ret;
2452 * very simple check to peek ahead in the leaf looking for xattrs. If we
2453 * don't find any xattrs, we know there can't be any acls.
2455 * slot is the slot the inode is in, objectid is the objectid of the inode
2457 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2458 int slot, u64 objectid)
2460 u32 nritems = btrfs_header_nritems(leaf);
2461 struct btrfs_key found_key;
2462 int scanned = 0;
2464 slot++;
2465 while (slot < nritems) {
2466 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2468 /* we found a different objectid, there must not be acls */
2469 if (found_key.objectid != objectid)
2470 return 0;
2472 /* we found an xattr, assume we've got an acl */
2473 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2474 return 1;
2477 * we found a key greater than an xattr key, there can't
2478 * be any acls later on
2480 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2481 return 0;
2483 slot++;
2484 scanned++;
2487 * it goes inode, inode backrefs, xattrs, extents,
2488 * so if there are a ton of hard links to an inode there can
2489 * be a lot of backrefs. Don't waste time searching too hard,
2490 * this is just an optimization
2492 if (scanned >= 8)
2493 break;
2495 /* we hit the end of the leaf before we found an xattr or
2496 * something larger than an xattr. We have to assume the inode
2497 * has acls
2499 return 1;
2503 * read an inode from the btree into the in-memory inode
2505 static void btrfs_read_locked_inode(struct inode *inode)
2507 struct btrfs_path *path;
2508 struct extent_buffer *leaf;
2509 struct btrfs_inode_item *inode_item;
2510 struct btrfs_timespec *tspec;
2511 struct btrfs_root *root = BTRFS_I(inode)->root;
2512 struct btrfs_key location;
2513 int maybe_acls;
2514 u64 alloc_group_block;
2515 u32 rdev;
2516 int ret;
2518 path = btrfs_alloc_path();
2519 BUG_ON(!path);
2520 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2522 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2523 if (ret)
2524 goto make_bad;
2526 leaf = path->nodes[0];
2527 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2528 struct btrfs_inode_item);
2530 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2531 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2532 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2533 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2534 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2536 tspec = btrfs_inode_atime(inode_item);
2537 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2538 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2540 tspec = btrfs_inode_mtime(inode_item);
2541 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2542 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2544 tspec = btrfs_inode_ctime(inode_item);
2545 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2546 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2548 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2549 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2550 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2551 inode->i_generation = BTRFS_I(inode)->generation;
2552 inode->i_rdev = 0;
2553 rdev = btrfs_inode_rdev(leaf, inode_item);
2555 BTRFS_I(inode)->index_cnt = (u64)-1;
2556 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2558 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2561 * try to precache a NULL acl entry for files that don't have
2562 * any xattrs or acls
2564 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2565 btrfs_ino(inode));
2566 if (!maybe_acls)
2567 cache_no_acl(inode);
2569 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2570 alloc_group_block, 0);
2571 btrfs_free_path(path);
2572 inode_item = NULL;
2574 switch (inode->i_mode & S_IFMT) {
2575 case S_IFREG:
2576 inode->i_mapping->a_ops = &btrfs_aops;
2577 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2578 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2579 inode->i_fop = &btrfs_file_operations;
2580 inode->i_op = &btrfs_file_inode_operations;
2581 break;
2582 case S_IFDIR:
2583 inode->i_fop = &btrfs_dir_file_operations;
2584 if (root == root->fs_info->tree_root)
2585 inode->i_op = &btrfs_dir_ro_inode_operations;
2586 else
2587 inode->i_op = &btrfs_dir_inode_operations;
2588 break;
2589 case S_IFLNK:
2590 inode->i_op = &btrfs_symlink_inode_operations;
2591 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2592 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2593 break;
2594 default:
2595 inode->i_op = &btrfs_special_inode_operations;
2596 init_special_inode(inode, inode->i_mode, rdev);
2597 break;
2600 btrfs_update_iflags(inode);
2601 return;
2603 make_bad:
2604 btrfs_free_path(path);
2605 make_bad_inode(inode);
2609 * given a leaf and an inode, copy the inode fields into the leaf
2611 static void fill_inode_item(struct btrfs_trans_handle *trans,
2612 struct extent_buffer *leaf,
2613 struct btrfs_inode_item *item,
2614 struct inode *inode)
2616 if (!leaf->map_token)
2617 map_private_extent_buffer(leaf, (unsigned long)item,
2618 sizeof(struct btrfs_inode_item),
2619 &leaf->map_token, &leaf->kaddr,
2620 &leaf->map_start, &leaf->map_len,
2621 KM_USER1);
2623 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2624 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2625 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2626 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2627 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2629 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2630 inode->i_atime.tv_sec);
2631 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2632 inode->i_atime.tv_nsec);
2634 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2635 inode->i_mtime.tv_sec);
2636 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2637 inode->i_mtime.tv_nsec);
2639 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2640 inode->i_ctime.tv_sec);
2641 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2642 inode->i_ctime.tv_nsec);
2644 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2645 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2646 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2647 btrfs_set_inode_transid(leaf, item, trans->transid);
2648 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2649 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2650 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2652 if (leaf->map_token) {
2653 unmap_extent_buffer(leaf, leaf->map_token, KM_USER1);
2654 leaf->map_token = NULL;
2659 * copy everything in the in-memory inode into the btree.
2661 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2662 struct btrfs_root *root, struct inode *inode)
2664 struct btrfs_inode_item *inode_item;
2665 struct btrfs_path *path;
2666 struct extent_buffer *leaf;
2667 int ret;
2670 * If root is tree root, it means this inode is used to
2671 * store free space information. And these inodes are updated
2672 * when committing the transaction, so they needn't delaye to
2673 * be updated, or deadlock will occured.
2675 if (!is_free_space_inode(root, inode)) {
2676 ret = btrfs_delayed_update_inode(trans, root, inode);
2677 if (!ret)
2678 btrfs_set_inode_last_trans(trans, inode);
2679 return ret;
2682 path = btrfs_alloc_path();
2683 if (!path)
2684 return -ENOMEM;
2686 path->leave_spinning = 1;
2687 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2689 if (ret) {
2690 if (ret > 0)
2691 ret = -ENOENT;
2692 goto failed;
2695 btrfs_unlock_up_safe(path, 1);
2696 leaf = path->nodes[0];
2697 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2698 struct btrfs_inode_item);
2700 fill_inode_item(trans, leaf, inode_item, inode);
2701 btrfs_mark_buffer_dirty(leaf);
2702 btrfs_set_inode_last_trans(trans, inode);
2703 ret = 0;
2704 failed:
2705 btrfs_free_path(path);
2706 return ret;
2710 * unlink helper that gets used here in inode.c and in the tree logging
2711 * recovery code. It remove a link in a directory with a given name, and
2712 * also drops the back refs in the inode to the directory
2714 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2715 struct btrfs_root *root,
2716 struct inode *dir, struct inode *inode,
2717 const char *name, int name_len)
2719 struct btrfs_path *path;
2720 int ret = 0;
2721 struct extent_buffer *leaf;
2722 struct btrfs_dir_item *di;
2723 struct btrfs_key key;
2724 u64 index;
2725 u64 ino = btrfs_ino(inode);
2726 u64 dir_ino = btrfs_ino(dir);
2728 path = btrfs_alloc_path();
2729 if (!path) {
2730 ret = -ENOMEM;
2731 goto out;
2734 path->leave_spinning = 1;
2735 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2736 name, name_len, -1);
2737 if (IS_ERR(di)) {
2738 ret = PTR_ERR(di);
2739 goto err;
2741 if (!di) {
2742 ret = -ENOENT;
2743 goto err;
2745 leaf = path->nodes[0];
2746 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2747 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2748 if (ret)
2749 goto err;
2750 btrfs_release_path(path);
2752 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2753 dir_ino, &index);
2754 if (ret) {
2755 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2756 "inode %llu parent %llu\n", name_len, name,
2757 (unsigned long long)ino, (unsigned long long)dir_ino);
2758 goto err;
2761 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2762 if (ret)
2763 goto err;
2765 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2766 inode, dir_ino);
2767 BUG_ON(ret != 0 && ret != -ENOENT);
2769 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2770 dir, index);
2771 if (ret == -ENOENT)
2772 ret = 0;
2773 err:
2774 btrfs_free_path(path);
2775 if (ret)
2776 goto out;
2778 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2779 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2780 btrfs_update_inode(trans, root, dir);
2781 out:
2782 return ret;
2785 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2786 struct btrfs_root *root,
2787 struct inode *dir, struct inode *inode,
2788 const char *name, int name_len)
2790 int ret;
2791 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2792 if (!ret) {
2793 btrfs_drop_nlink(inode);
2794 ret = btrfs_update_inode(trans, root, inode);
2796 return ret;
2800 /* helper to check if there is any shared block in the path */
2801 static int check_path_shared(struct btrfs_root *root,
2802 struct btrfs_path *path)
2804 struct extent_buffer *eb;
2805 int level;
2806 u64 refs = 1;
2808 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2809 int ret;
2811 if (!path->nodes[level])
2812 break;
2813 eb = path->nodes[level];
2814 if (!btrfs_block_can_be_shared(root, eb))
2815 continue;
2816 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2817 &refs, NULL);
2818 if (refs > 1)
2819 return 1;
2821 return 0;
2825 * helper to start transaction for unlink and rmdir.
2827 * unlink and rmdir are special in btrfs, they do not always free space.
2828 * so in enospc case, we should make sure they will free space before
2829 * allowing them to use the global metadata reservation.
2831 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2832 struct dentry *dentry)
2834 struct btrfs_trans_handle *trans;
2835 struct btrfs_root *root = BTRFS_I(dir)->root;
2836 struct btrfs_path *path;
2837 struct btrfs_inode_ref *ref;
2838 struct btrfs_dir_item *di;
2839 struct inode *inode = dentry->d_inode;
2840 u64 index;
2841 int check_link = 1;
2842 int err = -ENOSPC;
2843 int ret;
2844 u64 ino = btrfs_ino(inode);
2845 u64 dir_ino = btrfs_ino(dir);
2847 trans = btrfs_start_transaction(root, 10);
2848 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2849 return trans;
2851 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2852 return ERR_PTR(-ENOSPC);
2854 /* check if there is someone else holds reference */
2855 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2856 return ERR_PTR(-ENOSPC);
2858 if (atomic_read(&inode->i_count) > 2)
2859 return ERR_PTR(-ENOSPC);
2861 if (xchg(&root->fs_info->enospc_unlink, 1))
2862 return ERR_PTR(-ENOSPC);
2864 path = btrfs_alloc_path();
2865 if (!path) {
2866 root->fs_info->enospc_unlink = 0;
2867 return ERR_PTR(-ENOMEM);
2870 trans = btrfs_start_transaction(root, 0);
2871 if (IS_ERR(trans)) {
2872 btrfs_free_path(path);
2873 root->fs_info->enospc_unlink = 0;
2874 return trans;
2877 path->skip_locking = 1;
2878 path->search_commit_root = 1;
2880 ret = btrfs_lookup_inode(trans, root, path,
2881 &BTRFS_I(dir)->location, 0);
2882 if (ret < 0) {
2883 err = ret;
2884 goto out;
2886 if (ret == 0) {
2887 if (check_path_shared(root, path))
2888 goto out;
2889 } else {
2890 check_link = 0;
2892 btrfs_release_path(path);
2894 ret = btrfs_lookup_inode(trans, root, path,
2895 &BTRFS_I(inode)->location, 0);
2896 if (ret < 0) {
2897 err = ret;
2898 goto out;
2900 if (ret == 0) {
2901 if (check_path_shared(root, path))
2902 goto out;
2903 } else {
2904 check_link = 0;
2906 btrfs_release_path(path);
2908 if (ret == 0 && S_ISREG(inode->i_mode)) {
2909 ret = btrfs_lookup_file_extent(trans, root, path,
2910 ino, (u64)-1, 0);
2911 if (ret < 0) {
2912 err = ret;
2913 goto out;
2915 BUG_ON(ret == 0);
2916 if (check_path_shared(root, path))
2917 goto out;
2918 btrfs_release_path(path);
2921 if (!check_link) {
2922 err = 0;
2923 goto out;
2926 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2927 dentry->d_name.name, dentry->d_name.len, 0);
2928 if (IS_ERR(di)) {
2929 err = PTR_ERR(di);
2930 goto out;
2932 if (di) {
2933 if (check_path_shared(root, path))
2934 goto out;
2935 } else {
2936 err = 0;
2937 goto out;
2939 btrfs_release_path(path);
2941 ref = btrfs_lookup_inode_ref(trans, root, path,
2942 dentry->d_name.name, dentry->d_name.len,
2943 ino, dir_ino, 0);
2944 if (IS_ERR(ref)) {
2945 err = PTR_ERR(ref);
2946 goto out;
2948 BUG_ON(!ref);
2949 if (check_path_shared(root, path))
2950 goto out;
2951 index = btrfs_inode_ref_index(path->nodes[0], ref);
2952 btrfs_release_path(path);
2955 * This is a commit root search, if we can lookup inode item and other
2956 * relative items in the commit root, it means the transaction of
2957 * dir/file creation has been committed, and the dir index item that we
2958 * delay to insert has also been inserted into the commit root. So
2959 * we needn't worry about the delayed insertion of the dir index item
2960 * here.
2962 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
2963 dentry->d_name.name, dentry->d_name.len, 0);
2964 if (IS_ERR(di)) {
2965 err = PTR_ERR(di);
2966 goto out;
2968 BUG_ON(ret == -ENOENT);
2969 if (check_path_shared(root, path))
2970 goto out;
2972 err = 0;
2973 out:
2974 btrfs_free_path(path);
2975 if (err) {
2976 btrfs_end_transaction(trans, root);
2977 root->fs_info->enospc_unlink = 0;
2978 return ERR_PTR(err);
2981 trans->block_rsv = &root->fs_info->global_block_rsv;
2982 return trans;
2985 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2986 struct btrfs_root *root)
2988 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2989 BUG_ON(!root->fs_info->enospc_unlink);
2990 root->fs_info->enospc_unlink = 0;
2992 btrfs_end_transaction_throttle(trans, root);
2995 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2997 struct btrfs_root *root = BTRFS_I(dir)->root;
2998 struct btrfs_trans_handle *trans;
2999 struct inode *inode = dentry->d_inode;
3000 int ret;
3001 unsigned long nr = 0;
3003 trans = __unlink_start_trans(dir, dentry);
3004 if (IS_ERR(trans))
3005 return PTR_ERR(trans);
3007 btrfs_set_trans_block_group(trans, dir);
3009 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3011 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3012 dentry->d_name.name, dentry->d_name.len);
3013 BUG_ON(ret);
3015 if (inode->i_nlink == 0) {
3016 ret = btrfs_orphan_add(trans, inode);
3017 BUG_ON(ret);
3020 nr = trans->blocks_used;
3021 __unlink_end_trans(trans, root);
3022 btrfs_btree_balance_dirty(root, nr);
3023 return ret;
3026 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3027 struct btrfs_root *root,
3028 struct inode *dir, u64 objectid,
3029 const char *name, int name_len)
3031 struct btrfs_path *path;
3032 struct extent_buffer *leaf;
3033 struct btrfs_dir_item *di;
3034 struct btrfs_key key;
3035 u64 index;
3036 int ret;
3037 u64 dir_ino = btrfs_ino(dir);
3039 path = btrfs_alloc_path();
3040 if (!path)
3041 return -ENOMEM;
3043 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3044 name, name_len, -1);
3045 BUG_ON(IS_ERR_OR_NULL(di));
3047 leaf = path->nodes[0];
3048 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3049 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3050 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3051 BUG_ON(ret);
3052 btrfs_release_path(path);
3054 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3055 objectid, root->root_key.objectid,
3056 dir_ino, &index, name, name_len);
3057 if (ret < 0) {
3058 BUG_ON(ret != -ENOENT);
3059 di = btrfs_search_dir_index_item(root, path, dir_ino,
3060 name, name_len);
3061 BUG_ON(IS_ERR_OR_NULL(di));
3063 leaf = path->nodes[0];
3064 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3065 btrfs_release_path(path);
3066 index = key.offset;
3068 btrfs_release_path(path);
3070 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3071 BUG_ON(ret);
3073 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3074 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3075 ret = btrfs_update_inode(trans, root, dir);
3076 BUG_ON(ret);
3078 return 0;
3081 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3083 struct inode *inode = dentry->d_inode;
3084 int err = 0;
3085 struct btrfs_root *root = BTRFS_I(dir)->root;
3086 struct btrfs_trans_handle *trans;
3087 unsigned long nr = 0;
3089 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3090 btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3091 return -ENOTEMPTY;
3093 trans = __unlink_start_trans(dir, dentry);
3094 if (IS_ERR(trans))
3095 return PTR_ERR(trans);
3097 btrfs_set_trans_block_group(trans, dir);
3099 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3100 err = btrfs_unlink_subvol(trans, root, dir,
3101 BTRFS_I(inode)->location.objectid,
3102 dentry->d_name.name,
3103 dentry->d_name.len);
3104 goto out;
3107 err = btrfs_orphan_add(trans, inode);
3108 if (err)
3109 goto out;
3111 /* now the directory is empty */
3112 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3113 dentry->d_name.name, dentry->d_name.len);
3114 if (!err)
3115 btrfs_i_size_write(inode, 0);
3116 out:
3117 nr = trans->blocks_used;
3118 __unlink_end_trans(trans, root);
3119 btrfs_btree_balance_dirty(root, nr);
3121 return err;
3125 * this can truncate away extent items, csum items and directory items.
3126 * It starts at a high offset and removes keys until it can't find
3127 * any higher than new_size
3129 * csum items that cross the new i_size are truncated to the new size
3130 * as well.
3132 * min_type is the minimum key type to truncate down to. If set to 0, this
3133 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3135 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3136 struct btrfs_root *root,
3137 struct inode *inode,
3138 u64 new_size, u32 min_type)
3140 struct btrfs_path *path;
3141 struct extent_buffer *leaf;
3142 struct btrfs_file_extent_item *fi;
3143 struct btrfs_key key;
3144 struct btrfs_key found_key;
3145 u64 extent_start = 0;
3146 u64 extent_num_bytes = 0;
3147 u64 extent_offset = 0;
3148 u64 item_end = 0;
3149 u64 mask = root->sectorsize - 1;
3150 u32 found_type = (u8)-1;
3151 int found_extent;
3152 int del_item;
3153 int pending_del_nr = 0;
3154 int pending_del_slot = 0;
3155 int extent_type = -1;
3156 int encoding;
3157 int ret;
3158 int err = 0;
3159 u64 ino = btrfs_ino(inode);
3161 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3163 if (root->ref_cows || root == root->fs_info->tree_root)
3164 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3167 * This function is also used to drop the items in the log tree before
3168 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3169 * it is used to drop the loged items. So we shouldn't kill the delayed
3170 * items.
3172 if (min_type == 0 && root == BTRFS_I(inode)->root)
3173 btrfs_kill_delayed_inode_items(inode);
3175 path = btrfs_alloc_path();
3176 BUG_ON(!path);
3177 path->reada = -1;
3179 key.objectid = ino;
3180 key.offset = (u64)-1;
3181 key.type = (u8)-1;
3183 search_again:
3184 path->leave_spinning = 1;
3185 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3186 if (ret < 0) {
3187 err = ret;
3188 goto out;
3191 if (ret > 0) {
3192 /* there are no items in the tree for us to truncate, we're
3193 * done
3195 if (path->slots[0] == 0)
3196 goto out;
3197 path->slots[0]--;
3200 while (1) {
3201 fi = NULL;
3202 leaf = path->nodes[0];
3203 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3204 found_type = btrfs_key_type(&found_key);
3205 encoding = 0;
3207 if (found_key.objectid != ino)
3208 break;
3210 if (found_type < min_type)
3211 break;
3213 item_end = found_key.offset;
3214 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3215 fi = btrfs_item_ptr(leaf, path->slots[0],
3216 struct btrfs_file_extent_item);
3217 extent_type = btrfs_file_extent_type(leaf, fi);
3218 encoding = btrfs_file_extent_compression(leaf, fi);
3219 encoding |= btrfs_file_extent_encryption(leaf, fi);
3220 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3222 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3223 item_end +=
3224 btrfs_file_extent_num_bytes(leaf, fi);
3225 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3226 item_end += btrfs_file_extent_inline_len(leaf,
3227 fi);
3229 item_end--;
3231 if (found_type > min_type) {
3232 del_item = 1;
3233 } else {
3234 if (item_end < new_size)
3235 break;
3236 if (found_key.offset >= new_size)
3237 del_item = 1;
3238 else
3239 del_item = 0;
3241 found_extent = 0;
3242 /* FIXME, shrink the extent if the ref count is only 1 */
3243 if (found_type != BTRFS_EXTENT_DATA_KEY)
3244 goto delete;
3246 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3247 u64 num_dec;
3248 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3249 if (!del_item && !encoding) {
3250 u64 orig_num_bytes =
3251 btrfs_file_extent_num_bytes(leaf, fi);
3252 extent_num_bytes = new_size -
3253 found_key.offset + root->sectorsize - 1;
3254 extent_num_bytes = extent_num_bytes &
3255 ~((u64)root->sectorsize - 1);
3256 btrfs_set_file_extent_num_bytes(leaf, fi,
3257 extent_num_bytes);
3258 num_dec = (orig_num_bytes -
3259 extent_num_bytes);
3260 if (root->ref_cows && extent_start != 0)
3261 inode_sub_bytes(inode, num_dec);
3262 btrfs_mark_buffer_dirty(leaf);
3263 } else {
3264 extent_num_bytes =
3265 btrfs_file_extent_disk_num_bytes(leaf,
3266 fi);
3267 extent_offset = found_key.offset -
3268 btrfs_file_extent_offset(leaf, fi);
3270 /* FIXME blocksize != 4096 */
3271 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3272 if (extent_start != 0) {
3273 found_extent = 1;
3274 if (root->ref_cows)
3275 inode_sub_bytes(inode, num_dec);
3278 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3280 * we can't truncate inline items that have had
3281 * special encodings
3283 if (!del_item &&
3284 btrfs_file_extent_compression(leaf, fi) == 0 &&
3285 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3286 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3287 u32 size = new_size - found_key.offset;
3289 if (root->ref_cows) {
3290 inode_sub_bytes(inode, item_end + 1 -
3291 new_size);
3293 size =
3294 btrfs_file_extent_calc_inline_size(size);
3295 ret = btrfs_truncate_item(trans, root, path,
3296 size, 1);
3297 } else if (root->ref_cows) {
3298 inode_sub_bytes(inode, item_end + 1 -
3299 found_key.offset);
3302 delete:
3303 if (del_item) {
3304 if (!pending_del_nr) {
3305 /* no pending yet, add ourselves */
3306 pending_del_slot = path->slots[0];
3307 pending_del_nr = 1;
3308 } else if (pending_del_nr &&
3309 path->slots[0] + 1 == pending_del_slot) {
3310 /* hop on the pending chunk */
3311 pending_del_nr++;
3312 pending_del_slot = path->slots[0];
3313 } else {
3314 BUG();
3316 } else {
3317 break;
3319 if (found_extent && (root->ref_cows ||
3320 root == root->fs_info->tree_root)) {
3321 btrfs_set_path_blocking(path);
3322 ret = btrfs_free_extent(trans, root, extent_start,
3323 extent_num_bytes, 0,
3324 btrfs_header_owner(leaf),
3325 ino, extent_offset);
3326 BUG_ON(ret);
3329 if (found_type == BTRFS_INODE_ITEM_KEY)
3330 break;
3332 if (path->slots[0] == 0 ||
3333 path->slots[0] != pending_del_slot) {
3334 if (root->ref_cows &&
3335 BTRFS_I(inode)->location.objectid !=
3336 BTRFS_FREE_INO_OBJECTID) {
3337 err = -EAGAIN;
3338 goto out;
3340 if (pending_del_nr) {
3341 ret = btrfs_del_items(trans, root, path,
3342 pending_del_slot,
3343 pending_del_nr);
3344 BUG_ON(ret);
3345 pending_del_nr = 0;
3347 btrfs_release_path(path);
3348 goto search_again;
3349 } else {
3350 path->slots[0]--;
3353 out:
3354 if (pending_del_nr) {
3355 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3356 pending_del_nr);
3357 BUG_ON(ret);
3359 btrfs_free_path(path);
3360 return err;
3364 * taken from block_truncate_page, but does cow as it zeros out
3365 * any bytes left in the last page in the file.
3367 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3369 struct inode *inode = mapping->host;
3370 struct btrfs_root *root = BTRFS_I(inode)->root;
3371 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3372 struct btrfs_ordered_extent *ordered;
3373 struct extent_state *cached_state = NULL;
3374 char *kaddr;
3375 u32 blocksize = root->sectorsize;
3376 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3377 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3378 struct page *page;
3379 int ret = 0;
3380 u64 page_start;
3381 u64 page_end;
3383 if ((offset & (blocksize - 1)) == 0)
3384 goto out;
3385 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3386 if (ret)
3387 goto out;
3389 ret = -ENOMEM;
3390 again:
3391 page = grab_cache_page(mapping, index);
3392 if (!page) {
3393 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3394 goto out;
3397 page_start = page_offset(page);
3398 page_end = page_start + PAGE_CACHE_SIZE - 1;
3400 if (!PageUptodate(page)) {
3401 ret = btrfs_readpage(NULL, page);
3402 lock_page(page);
3403 if (page->mapping != mapping) {
3404 unlock_page(page);
3405 page_cache_release(page);
3406 goto again;
3408 if (!PageUptodate(page)) {
3409 ret = -EIO;
3410 goto out_unlock;
3413 wait_on_page_writeback(page);
3415 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3416 GFP_NOFS);
3417 set_page_extent_mapped(page);
3419 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3420 if (ordered) {
3421 unlock_extent_cached(io_tree, page_start, page_end,
3422 &cached_state, GFP_NOFS);
3423 unlock_page(page);
3424 page_cache_release(page);
3425 btrfs_start_ordered_extent(inode, ordered, 1);
3426 btrfs_put_ordered_extent(ordered);
3427 goto again;
3430 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3431 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3432 0, 0, &cached_state, GFP_NOFS);
3434 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3435 &cached_state);
3436 if (ret) {
3437 unlock_extent_cached(io_tree, page_start, page_end,
3438 &cached_state, GFP_NOFS);
3439 goto out_unlock;
3442 ret = 0;
3443 if (offset != PAGE_CACHE_SIZE) {
3444 kaddr = kmap(page);
3445 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3446 flush_dcache_page(page);
3447 kunmap(page);
3449 ClearPageChecked(page);
3450 set_page_dirty(page);
3451 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3452 GFP_NOFS);
3454 out_unlock:
3455 if (ret)
3456 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3457 unlock_page(page);
3458 page_cache_release(page);
3459 out:
3460 return ret;
3464 * This function puts in dummy file extents for the area we're creating a hole
3465 * for. So if we are truncating this file to a larger size we need to insert
3466 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3467 * the range between oldsize and size
3469 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3471 struct btrfs_trans_handle *trans;
3472 struct btrfs_root *root = BTRFS_I(inode)->root;
3473 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3474 struct extent_map *em = NULL;
3475 struct extent_state *cached_state = NULL;
3476 u64 mask = root->sectorsize - 1;
3477 u64 hole_start = (oldsize + mask) & ~mask;
3478 u64 block_end = (size + mask) & ~mask;
3479 u64 last_byte;
3480 u64 cur_offset;
3481 u64 hole_size;
3482 int err = 0;
3484 if (size <= hole_start)
3485 return 0;
3487 while (1) {
3488 struct btrfs_ordered_extent *ordered;
3489 btrfs_wait_ordered_range(inode, hole_start,
3490 block_end - hole_start);
3491 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3492 &cached_state, GFP_NOFS);
3493 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3494 if (!ordered)
3495 break;
3496 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3497 &cached_state, GFP_NOFS);
3498 btrfs_put_ordered_extent(ordered);
3501 cur_offset = hole_start;
3502 while (1) {
3503 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3504 block_end - cur_offset, 0);
3505 BUG_ON(IS_ERR_OR_NULL(em));
3506 last_byte = min(extent_map_end(em), block_end);
3507 last_byte = (last_byte + mask) & ~mask;
3508 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3509 u64 hint_byte = 0;
3510 hole_size = last_byte - cur_offset;
3512 trans = btrfs_start_transaction(root, 2);
3513 if (IS_ERR(trans)) {
3514 err = PTR_ERR(trans);
3515 break;
3517 btrfs_set_trans_block_group(trans, inode);
3519 err = btrfs_drop_extents(trans, inode, cur_offset,
3520 cur_offset + hole_size,
3521 &hint_byte, 1);
3522 if (err)
3523 break;
3525 err = btrfs_insert_file_extent(trans, root,
3526 btrfs_ino(inode), cur_offset, 0,
3527 0, hole_size, 0, hole_size,
3528 0, 0, 0);
3529 if (err)
3530 break;
3532 btrfs_drop_extent_cache(inode, hole_start,
3533 last_byte - 1, 0);
3535 btrfs_end_transaction(trans, root);
3537 free_extent_map(em);
3538 em = NULL;
3539 cur_offset = last_byte;
3540 if (cur_offset >= block_end)
3541 break;
3544 free_extent_map(em);
3545 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3546 GFP_NOFS);
3547 return err;
3550 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3552 loff_t oldsize = i_size_read(inode);
3553 int ret;
3555 if (newsize == oldsize)
3556 return 0;
3558 if (newsize > oldsize) {
3559 i_size_write(inode, newsize);
3560 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3561 truncate_pagecache(inode, oldsize, newsize);
3562 ret = btrfs_cont_expand(inode, oldsize, newsize);
3563 if (ret) {
3564 btrfs_setsize(inode, oldsize);
3565 return ret;
3568 mark_inode_dirty(inode);
3569 } else {
3572 * We're truncating a file that used to have good data down to
3573 * zero. Make sure it gets into the ordered flush list so that
3574 * any new writes get down to disk quickly.
3576 if (newsize == 0)
3577 BTRFS_I(inode)->ordered_data_close = 1;
3579 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3580 truncate_setsize(inode, newsize);
3581 ret = btrfs_truncate(inode);
3584 return ret;
3587 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3589 struct inode *inode = dentry->d_inode;
3590 struct btrfs_root *root = BTRFS_I(inode)->root;
3591 int err;
3593 if (btrfs_root_readonly(root))
3594 return -EROFS;
3596 err = inode_change_ok(inode, attr);
3597 if (err)
3598 return err;
3600 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3601 err = btrfs_setsize(inode, attr->ia_size);
3602 if (err)
3603 return err;
3606 if (attr->ia_valid) {
3607 setattr_copy(inode, attr);
3608 mark_inode_dirty(inode);
3610 if (attr->ia_valid & ATTR_MODE)
3611 err = btrfs_acl_chmod(inode);
3614 return err;
3617 void btrfs_evict_inode(struct inode *inode)
3619 struct btrfs_trans_handle *trans;
3620 struct btrfs_root *root = BTRFS_I(inode)->root;
3621 unsigned long nr;
3622 int ret;
3624 trace_btrfs_inode_evict(inode);
3626 truncate_inode_pages(&inode->i_data, 0);
3627 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3628 is_free_space_inode(root, inode)))
3629 goto no_delete;
3631 if (is_bad_inode(inode)) {
3632 btrfs_orphan_del(NULL, inode);
3633 goto no_delete;
3635 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3636 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3638 if (root->fs_info->log_root_recovering) {
3639 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3640 goto no_delete;
3643 if (inode->i_nlink > 0) {
3644 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3645 goto no_delete;
3648 btrfs_i_size_write(inode, 0);
3650 while (1) {
3651 trans = btrfs_start_transaction(root, 0);
3652 BUG_ON(IS_ERR(trans));
3653 btrfs_set_trans_block_group(trans, inode);
3654 trans->block_rsv = root->orphan_block_rsv;
3656 ret = btrfs_block_rsv_check(trans, root,
3657 root->orphan_block_rsv, 0, 5);
3658 if (ret) {
3659 BUG_ON(ret != -EAGAIN);
3660 ret = btrfs_commit_transaction(trans, root);
3661 BUG_ON(ret);
3662 continue;
3665 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3666 if (ret != -EAGAIN)
3667 break;
3669 nr = trans->blocks_used;
3670 btrfs_end_transaction(trans, root);
3671 trans = NULL;
3672 btrfs_btree_balance_dirty(root, nr);
3676 if (ret == 0) {
3677 ret = btrfs_orphan_del(trans, inode);
3678 BUG_ON(ret);
3681 if (!(root == root->fs_info->tree_root ||
3682 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3683 btrfs_return_ino(root, btrfs_ino(inode));
3685 nr = trans->blocks_used;
3686 btrfs_end_transaction(trans, root);
3687 btrfs_btree_balance_dirty(root, nr);
3688 no_delete:
3689 end_writeback(inode);
3690 return;
3694 * this returns the key found in the dir entry in the location pointer.
3695 * If no dir entries were found, location->objectid is 0.
3697 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3698 struct btrfs_key *location)
3700 const char *name = dentry->d_name.name;
3701 int namelen = dentry->d_name.len;
3702 struct btrfs_dir_item *di;
3703 struct btrfs_path *path;
3704 struct btrfs_root *root = BTRFS_I(dir)->root;
3705 int ret = 0;
3707 path = btrfs_alloc_path();
3708 BUG_ON(!path);
3710 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3711 namelen, 0);
3712 if (IS_ERR(di))
3713 ret = PTR_ERR(di);
3715 if (IS_ERR_OR_NULL(di))
3716 goto out_err;
3718 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3719 out:
3720 btrfs_free_path(path);
3721 return ret;
3722 out_err:
3723 location->objectid = 0;
3724 goto out;
3728 * when we hit a tree root in a directory, the btrfs part of the inode
3729 * needs to be changed to reflect the root directory of the tree root. This
3730 * is kind of like crossing a mount point.
3732 static int fixup_tree_root_location(struct btrfs_root *root,
3733 struct inode *dir,
3734 struct dentry *dentry,
3735 struct btrfs_key *location,
3736 struct btrfs_root **sub_root)
3738 struct btrfs_path *path;
3739 struct btrfs_root *new_root;
3740 struct btrfs_root_ref *ref;
3741 struct extent_buffer *leaf;
3742 int ret;
3743 int err = 0;
3745 path = btrfs_alloc_path();
3746 if (!path) {
3747 err = -ENOMEM;
3748 goto out;
3751 err = -ENOENT;
3752 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3753 BTRFS_I(dir)->root->root_key.objectid,
3754 location->objectid);
3755 if (ret) {
3756 if (ret < 0)
3757 err = ret;
3758 goto out;
3761 leaf = path->nodes[0];
3762 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3763 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3764 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3765 goto out;
3767 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3768 (unsigned long)(ref + 1),
3769 dentry->d_name.len);
3770 if (ret)
3771 goto out;
3773 btrfs_release_path(path);
3775 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3776 if (IS_ERR(new_root)) {
3777 err = PTR_ERR(new_root);
3778 goto out;
3781 if (btrfs_root_refs(&new_root->root_item) == 0) {
3782 err = -ENOENT;
3783 goto out;
3786 *sub_root = new_root;
3787 location->objectid = btrfs_root_dirid(&new_root->root_item);
3788 location->type = BTRFS_INODE_ITEM_KEY;
3789 location->offset = 0;
3790 err = 0;
3791 out:
3792 btrfs_free_path(path);
3793 return err;
3796 static void inode_tree_add(struct inode *inode)
3798 struct btrfs_root *root = BTRFS_I(inode)->root;
3799 struct btrfs_inode *entry;
3800 struct rb_node **p;
3801 struct rb_node *parent;
3802 u64 ino = btrfs_ino(inode);
3803 again:
3804 p = &root->inode_tree.rb_node;
3805 parent = NULL;
3807 if (inode_unhashed(inode))
3808 return;
3810 spin_lock(&root->inode_lock);
3811 while (*p) {
3812 parent = *p;
3813 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3815 if (ino < btrfs_ino(&entry->vfs_inode))
3816 p = &parent->rb_left;
3817 else if (ino > btrfs_ino(&entry->vfs_inode))
3818 p = &parent->rb_right;
3819 else {
3820 WARN_ON(!(entry->vfs_inode.i_state &
3821 (I_WILL_FREE | I_FREEING)));
3822 rb_erase(parent, &root->inode_tree);
3823 RB_CLEAR_NODE(parent);
3824 spin_unlock(&root->inode_lock);
3825 goto again;
3828 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3829 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3830 spin_unlock(&root->inode_lock);
3833 static void inode_tree_del(struct inode *inode)
3835 struct btrfs_root *root = BTRFS_I(inode)->root;
3836 int empty = 0;
3838 spin_lock(&root->inode_lock);
3839 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3840 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3841 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3842 empty = RB_EMPTY_ROOT(&root->inode_tree);
3844 spin_unlock(&root->inode_lock);
3847 * Free space cache has inodes in the tree root, but the tree root has a
3848 * root_refs of 0, so this could end up dropping the tree root as a
3849 * snapshot, so we need the extra !root->fs_info->tree_root check to
3850 * make sure we don't drop it.
3852 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3853 root != root->fs_info->tree_root) {
3854 synchronize_srcu(&root->fs_info->subvol_srcu);
3855 spin_lock(&root->inode_lock);
3856 empty = RB_EMPTY_ROOT(&root->inode_tree);
3857 spin_unlock(&root->inode_lock);
3858 if (empty)
3859 btrfs_add_dead_root(root);
3863 int btrfs_invalidate_inodes(struct btrfs_root *root)
3865 struct rb_node *node;
3866 struct rb_node *prev;
3867 struct btrfs_inode *entry;
3868 struct inode *inode;
3869 u64 objectid = 0;
3871 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3873 spin_lock(&root->inode_lock);
3874 again:
3875 node = root->inode_tree.rb_node;
3876 prev = NULL;
3877 while (node) {
3878 prev = node;
3879 entry = rb_entry(node, struct btrfs_inode, rb_node);
3881 if (objectid < btrfs_ino(&entry->vfs_inode))
3882 node = node->rb_left;
3883 else if (objectid > btrfs_ino(&entry->vfs_inode))
3884 node = node->rb_right;
3885 else
3886 break;
3888 if (!node) {
3889 while (prev) {
3890 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3891 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
3892 node = prev;
3893 break;
3895 prev = rb_next(prev);
3898 while (node) {
3899 entry = rb_entry(node, struct btrfs_inode, rb_node);
3900 objectid = btrfs_ino(&entry->vfs_inode) + 1;
3901 inode = igrab(&entry->vfs_inode);
3902 if (inode) {
3903 spin_unlock(&root->inode_lock);
3904 if (atomic_read(&inode->i_count) > 1)
3905 d_prune_aliases(inode);
3907 * btrfs_drop_inode will have it removed from
3908 * the inode cache when its usage count
3909 * hits zero.
3911 iput(inode);
3912 cond_resched();
3913 spin_lock(&root->inode_lock);
3914 goto again;
3917 if (cond_resched_lock(&root->inode_lock))
3918 goto again;
3920 node = rb_next(node);
3922 spin_unlock(&root->inode_lock);
3923 return 0;
3926 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3928 struct btrfs_iget_args *args = p;
3929 inode->i_ino = args->ino;
3930 BTRFS_I(inode)->root = args->root;
3931 btrfs_set_inode_space_info(args->root, inode);
3932 return 0;
3935 static int btrfs_find_actor(struct inode *inode, void *opaque)
3937 struct btrfs_iget_args *args = opaque;
3938 return args->ino == btrfs_ino(inode) &&
3939 args->root == BTRFS_I(inode)->root;
3942 static struct inode *btrfs_iget_locked(struct super_block *s,
3943 u64 objectid,
3944 struct btrfs_root *root)
3946 struct inode *inode;
3947 struct btrfs_iget_args args;
3948 args.ino = objectid;
3949 args.root = root;
3951 inode = iget5_locked(s, objectid, btrfs_find_actor,
3952 btrfs_init_locked_inode,
3953 (void *)&args);
3954 return inode;
3957 /* Get an inode object given its location and corresponding root.
3958 * Returns in *is_new if the inode was read from disk
3960 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
3961 struct btrfs_root *root, int *new)
3963 struct inode *inode;
3965 inode = btrfs_iget_locked(s, location->objectid, root);
3966 if (!inode)
3967 return ERR_PTR(-ENOMEM);
3969 if (inode->i_state & I_NEW) {
3970 BTRFS_I(inode)->root = root;
3971 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3972 btrfs_read_locked_inode(inode);
3973 inode_tree_add(inode);
3974 unlock_new_inode(inode);
3975 if (new)
3976 *new = 1;
3979 return inode;
3982 static struct inode *new_simple_dir(struct super_block *s,
3983 struct btrfs_key *key,
3984 struct btrfs_root *root)
3986 struct inode *inode = new_inode(s);
3988 if (!inode)
3989 return ERR_PTR(-ENOMEM);
3991 BTRFS_I(inode)->root = root;
3992 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3993 BTRFS_I(inode)->dummy_inode = 1;
3995 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3996 inode->i_op = &simple_dir_inode_operations;
3997 inode->i_fop = &simple_dir_operations;
3998 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3999 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4001 return inode;
4004 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4006 struct inode *inode;
4007 struct btrfs_root *root = BTRFS_I(dir)->root;
4008 struct btrfs_root *sub_root = root;
4009 struct btrfs_key location;
4010 int index;
4011 int ret;
4013 if (dentry->d_name.len > BTRFS_NAME_LEN)
4014 return ERR_PTR(-ENAMETOOLONG);
4016 ret = btrfs_inode_by_name(dir, dentry, &location);
4018 if (ret < 0)
4019 return ERR_PTR(ret);
4021 if (location.objectid == 0)
4022 return NULL;
4024 if (location.type == BTRFS_INODE_ITEM_KEY) {
4025 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4026 return inode;
4029 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4031 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4032 ret = fixup_tree_root_location(root, dir, dentry,
4033 &location, &sub_root);
4034 if (ret < 0) {
4035 if (ret != -ENOENT)
4036 inode = ERR_PTR(ret);
4037 else
4038 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4039 } else {
4040 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4042 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4044 if (!IS_ERR(inode) && root != sub_root) {
4045 down_read(&root->fs_info->cleanup_work_sem);
4046 if (!(inode->i_sb->s_flags & MS_RDONLY))
4047 ret = btrfs_orphan_cleanup(sub_root);
4048 up_read(&root->fs_info->cleanup_work_sem);
4049 if (ret)
4050 inode = ERR_PTR(ret);
4053 return inode;
4056 static int btrfs_dentry_delete(const struct dentry *dentry)
4058 struct btrfs_root *root;
4060 if (!dentry->d_inode && !IS_ROOT(dentry))
4061 dentry = dentry->d_parent;
4063 if (dentry->d_inode) {
4064 root = BTRFS_I(dentry->d_inode)->root;
4065 if (btrfs_root_refs(&root->root_item) == 0)
4066 return 1;
4068 return 0;
4071 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4072 struct nameidata *nd)
4074 struct inode *inode;
4076 inode = btrfs_lookup_dentry(dir, dentry);
4077 if (IS_ERR(inode))
4078 return ERR_CAST(inode);
4080 return d_splice_alias(inode, dentry);
4083 unsigned char btrfs_filetype_table[] = {
4084 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4087 static int btrfs_real_readdir(struct file *filp, void *dirent,
4088 filldir_t filldir)
4090 struct inode *inode = filp->f_dentry->d_inode;
4091 struct btrfs_root *root = BTRFS_I(inode)->root;
4092 struct btrfs_item *item;
4093 struct btrfs_dir_item *di;
4094 struct btrfs_key key;
4095 struct btrfs_key found_key;
4096 struct btrfs_path *path;
4097 struct list_head ins_list;
4098 struct list_head del_list;
4099 int ret;
4100 struct extent_buffer *leaf;
4101 int slot;
4102 unsigned char d_type;
4103 int over = 0;
4104 u32 di_cur;
4105 u32 di_total;
4106 u32 di_len;
4107 int key_type = BTRFS_DIR_INDEX_KEY;
4108 char tmp_name[32];
4109 char *name_ptr;
4110 int name_len;
4111 int is_curr = 0; /* filp->f_pos points to the current index? */
4113 /* FIXME, use a real flag for deciding about the key type */
4114 if (root->fs_info->tree_root == root)
4115 key_type = BTRFS_DIR_ITEM_KEY;
4117 /* special case for "." */
4118 if (filp->f_pos == 0) {
4119 over = filldir(dirent, ".", 1, 1, btrfs_ino(inode), DT_DIR);
4120 if (over)
4121 return 0;
4122 filp->f_pos = 1;
4124 /* special case for .., just use the back ref */
4125 if (filp->f_pos == 1) {
4126 u64 pino = parent_ino(filp->f_path.dentry);
4127 over = filldir(dirent, "..", 2,
4128 2, pino, DT_DIR);
4129 if (over)
4130 return 0;
4131 filp->f_pos = 2;
4133 path = btrfs_alloc_path();
4134 if (!path)
4135 return -ENOMEM;
4136 path->reada = 2;
4138 if (key_type == BTRFS_DIR_INDEX_KEY) {
4139 INIT_LIST_HEAD(&ins_list);
4140 INIT_LIST_HEAD(&del_list);
4141 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4144 btrfs_set_key_type(&key, key_type);
4145 key.offset = filp->f_pos;
4146 key.objectid = btrfs_ino(inode);
4148 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4149 if (ret < 0)
4150 goto err;
4152 while (1) {
4153 leaf = path->nodes[0];
4154 slot = path->slots[0];
4155 if (slot >= btrfs_header_nritems(leaf)) {
4156 ret = btrfs_next_leaf(root, path);
4157 if (ret < 0)
4158 goto err;
4159 else if (ret > 0)
4160 break;
4161 continue;
4164 item = btrfs_item_nr(leaf, slot);
4165 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4167 if (found_key.objectid != key.objectid)
4168 break;
4169 if (btrfs_key_type(&found_key) != key_type)
4170 break;
4171 if (found_key.offset < filp->f_pos)
4172 goto next;
4173 if (key_type == BTRFS_DIR_INDEX_KEY &&
4174 btrfs_should_delete_dir_index(&del_list,
4175 found_key.offset))
4176 goto next;
4178 filp->f_pos = found_key.offset;
4179 is_curr = 1;
4181 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4182 di_cur = 0;
4183 di_total = btrfs_item_size(leaf, item);
4185 while (di_cur < di_total) {
4186 struct btrfs_key location;
4188 if (verify_dir_item(root, leaf, di))
4189 break;
4191 name_len = btrfs_dir_name_len(leaf, di);
4192 if (name_len <= sizeof(tmp_name)) {
4193 name_ptr = tmp_name;
4194 } else {
4195 name_ptr = kmalloc(name_len, GFP_NOFS);
4196 if (!name_ptr) {
4197 ret = -ENOMEM;
4198 goto err;
4201 read_extent_buffer(leaf, name_ptr,
4202 (unsigned long)(di + 1), name_len);
4204 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4205 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4207 /* is this a reference to our own snapshot? If so
4208 * skip it
4210 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4211 location.objectid == root->root_key.objectid) {
4212 over = 0;
4213 goto skip;
4215 over = filldir(dirent, name_ptr, name_len,
4216 found_key.offset, location.objectid,
4217 d_type);
4219 skip:
4220 if (name_ptr != tmp_name)
4221 kfree(name_ptr);
4223 if (over)
4224 goto nopos;
4225 di_len = btrfs_dir_name_len(leaf, di) +
4226 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4227 di_cur += di_len;
4228 di = (struct btrfs_dir_item *)((char *)di + di_len);
4230 next:
4231 path->slots[0]++;
4234 if (key_type == BTRFS_DIR_INDEX_KEY) {
4235 if (is_curr)
4236 filp->f_pos++;
4237 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4238 &ins_list);
4239 if (ret)
4240 goto nopos;
4243 /* Reached end of directory/root. Bump pos past the last item. */
4244 if (key_type == BTRFS_DIR_INDEX_KEY)
4246 * 32-bit glibc will use getdents64, but then strtol -
4247 * so the last number we can serve is this.
4249 filp->f_pos = 0x7fffffff;
4250 else
4251 filp->f_pos++;
4252 nopos:
4253 ret = 0;
4254 err:
4255 if (key_type == BTRFS_DIR_INDEX_KEY)
4256 btrfs_put_delayed_items(&ins_list, &del_list);
4257 btrfs_free_path(path);
4258 return ret;
4261 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4263 struct btrfs_root *root = BTRFS_I(inode)->root;
4264 struct btrfs_trans_handle *trans;
4265 int ret = 0;
4266 bool nolock = false;
4268 if (BTRFS_I(inode)->dummy_inode)
4269 return 0;
4271 smp_mb();
4272 if (root->fs_info->closing && is_free_space_inode(root, inode))
4273 nolock = true;
4275 if (wbc->sync_mode == WB_SYNC_ALL) {
4276 if (nolock)
4277 trans = btrfs_join_transaction_nolock(root, 1);
4278 else
4279 trans = btrfs_join_transaction(root, 1);
4280 if (IS_ERR(trans))
4281 return PTR_ERR(trans);
4282 btrfs_set_trans_block_group(trans, inode);
4283 if (nolock)
4284 ret = btrfs_end_transaction_nolock(trans, root);
4285 else
4286 ret = btrfs_commit_transaction(trans, root);
4288 return ret;
4292 * This is somewhat expensive, updating the tree every time the
4293 * inode changes. But, it is most likely to find the inode in cache.
4294 * FIXME, needs more benchmarking...there are no reasons other than performance
4295 * to keep or drop this code.
4297 void btrfs_dirty_inode(struct inode *inode)
4299 struct btrfs_root *root = BTRFS_I(inode)->root;
4300 struct btrfs_trans_handle *trans;
4301 int ret;
4303 if (BTRFS_I(inode)->dummy_inode)
4304 return;
4306 trans = btrfs_join_transaction(root, 1);
4307 BUG_ON(IS_ERR(trans));
4308 btrfs_set_trans_block_group(trans, inode);
4310 ret = btrfs_update_inode(trans, root, inode);
4311 if (ret && ret == -ENOSPC) {
4312 /* whoops, lets try again with the full transaction */
4313 btrfs_end_transaction(trans, root);
4314 trans = btrfs_start_transaction(root, 1);
4315 if (IS_ERR(trans)) {
4316 printk_ratelimited(KERN_ERR "btrfs: fail to "
4317 "dirty inode %llu error %ld\n",
4318 (unsigned long long)btrfs_ino(inode),
4319 PTR_ERR(trans));
4320 return;
4322 btrfs_set_trans_block_group(trans, inode);
4324 ret = btrfs_update_inode(trans, root, inode);
4325 if (ret) {
4326 printk_ratelimited(KERN_ERR "btrfs: fail to "
4327 "dirty inode %llu error %d\n",
4328 (unsigned long long)btrfs_ino(inode),
4329 ret);
4332 btrfs_end_transaction(trans, root);
4333 if (BTRFS_I(inode)->delayed_node)
4334 btrfs_balance_delayed_items(root);
4338 * find the highest existing sequence number in a directory
4339 * and then set the in-memory index_cnt variable to reflect
4340 * free sequence numbers
4342 static int btrfs_set_inode_index_count(struct inode *inode)
4344 struct btrfs_root *root = BTRFS_I(inode)->root;
4345 struct btrfs_key key, found_key;
4346 struct btrfs_path *path;
4347 struct extent_buffer *leaf;
4348 int ret;
4350 key.objectid = btrfs_ino(inode);
4351 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4352 key.offset = (u64)-1;
4354 path = btrfs_alloc_path();
4355 if (!path)
4356 return -ENOMEM;
4358 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4359 if (ret < 0)
4360 goto out;
4361 /* FIXME: we should be able to handle this */
4362 if (ret == 0)
4363 goto out;
4364 ret = 0;
4367 * MAGIC NUMBER EXPLANATION:
4368 * since we search a directory based on f_pos we have to start at 2
4369 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4370 * else has to start at 2
4372 if (path->slots[0] == 0) {
4373 BTRFS_I(inode)->index_cnt = 2;
4374 goto out;
4377 path->slots[0]--;
4379 leaf = path->nodes[0];
4380 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4382 if (found_key.objectid != btrfs_ino(inode) ||
4383 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4384 BTRFS_I(inode)->index_cnt = 2;
4385 goto out;
4388 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4389 out:
4390 btrfs_free_path(path);
4391 return ret;
4395 * helper to find a free sequence number in a given directory. This current
4396 * code is very simple, later versions will do smarter things in the btree
4398 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4400 int ret = 0;
4402 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4403 ret = btrfs_inode_delayed_dir_index_count(dir);
4404 if (ret) {
4405 ret = btrfs_set_inode_index_count(dir);
4406 if (ret)
4407 return ret;
4411 *index = BTRFS_I(dir)->index_cnt;
4412 BTRFS_I(dir)->index_cnt++;
4414 return ret;
4417 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4418 struct btrfs_root *root,
4419 struct inode *dir,
4420 const char *name, int name_len,
4421 u64 ref_objectid, u64 objectid,
4422 u64 alloc_hint, int mode, u64 *index)
4424 struct inode *inode;
4425 struct btrfs_inode_item *inode_item;
4426 struct btrfs_key *location;
4427 struct btrfs_path *path;
4428 struct btrfs_inode_ref *ref;
4429 struct btrfs_key key[2];
4430 u32 sizes[2];
4431 unsigned long ptr;
4432 int ret;
4433 int owner;
4435 path = btrfs_alloc_path();
4436 BUG_ON(!path);
4438 inode = new_inode(root->fs_info->sb);
4439 if (!inode) {
4440 btrfs_free_path(path);
4441 return ERR_PTR(-ENOMEM);
4445 * we have to initialize this early, so we can reclaim the inode
4446 * number if we fail afterwards in this function.
4448 inode->i_ino = objectid;
4450 if (dir) {
4451 trace_btrfs_inode_request(dir);
4453 ret = btrfs_set_inode_index(dir, index);
4454 if (ret) {
4455 btrfs_free_path(path);
4456 iput(inode);
4457 return ERR_PTR(ret);
4461 * index_cnt is ignored for everything but a dir,
4462 * btrfs_get_inode_index_count has an explanation for the magic
4463 * number
4465 BTRFS_I(inode)->index_cnt = 2;
4466 BTRFS_I(inode)->root = root;
4467 BTRFS_I(inode)->generation = trans->transid;
4468 inode->i_generation = BTRFS_I(inode)->generation;
4469 btrfs_set_inode_space_info(root, inode);
4471 if (mode & S_IFDIR)
4472 owner = 0;
4473 else
4474 owner = 1;
4475 BTRFS_I(inode)->block_group =
4476 btrfs_find_block_group(root, 0, alloc_hint, owner);
4478 key[0].objectid = objectid;
4479 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4480 key[0].offset = 0;
4482 key[1].objectid = objectid;
4483 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4484 key[1].offset = ref_objectid;
4486 sizes[0] = sizeof(struct btrfs_inode_item);
4487 sizes[1] = name_len + sizeof(*ref);
4489 path->leave_spinning = 1;
4490 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4491 if (ret != 0)
4492 goto fail;
4494 inode_init_owner(inode, dir, mode);
4495 inode_set_bytes(inode, 0);
4496 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4497 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4498 struct btrfs_inode_item);
4499 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4501 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4502 struct btrfs_inode_ref);
4503 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4504 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4505 ptr = (unsigned long)(ref + 1);
4506 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4508 btrfs_mark_buffer_dirty(path->nodes[0]);
4509 btrfs_free_path(path);
4511 location = &BTRFS_I(inode)->location;
4512 location->objectid = objectid;
4513 location->offset = 0;
4514 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4516 btrfs_inherit_iflags(inode, dir);
4518 if ((mode & S_IFREG)) {
4519 if (btrfs_test_opt(root, NODATASUM))
4520 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4521 if (btrfs_test_opt(root, NODATACOW) ||
4522 (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4523 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4526 insert_inode_hash(inode);
4527 inode_tree_add(inode);
4529 trace_btrfs_inode_new(inode);
4531 return inode;
4532 fail:
4533 if (dir)
4534 BTRFS_I(dir)->index_cnt--;
4535 btrfs_free_path(path);
4536 iput(inode);
4537 return ERR_PTR(ret);
4540 static inline u8 btrfs_inode_type(struct inode *inode)
4542 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4546 * utility function to add 'inode' into 'parent_inode' with
4547 * a give name and a given sequence number.
4548 * if 'add_backref' is true, also insert a backref from the
4549 * inode to the parent directory.
4551 int btrfs_add_link(struct btrfs_trans_handle *trans,
4552 struct inode *parent_inode, struct inode *inode,
4553 const char *name, int name_len, int add_backref, u64 index)
4555 int ret = 0;
4556 struct btrfs_key key;
4557 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4558 u64 ino = btrfs_ino(inode);
4559 u64 parent_ino = btrfs_ino(parent_inode);
4561 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4562 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4563 } else {
4564 key.objectid = ino;
4565 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4566 key.offset = 0;
4569 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4570 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4571 key.objectid, root->root_key.objectid,
4572 parent_ino, index, name, name_len);
4573 } else if (add_backref) {
4574 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4575 parent_ino, index);
4578 if (ret == 0) {
4579 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4580 parent_inode, &key,
4581 btrfs_inode_type(inode), index);
4582 BUG_ON(ret);
4584 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4585 name_len * 2);
4586 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4587 ret = btrfs_update_inode(trans, root, parent_inode);
4589 return ret;
4592 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4593 struct inode *dir, struct dentry *dentry,
4594 struct inode *inode, int backref, u64 index)
4596 int err = btrfs_add_link(trans, dir, inode,
4597 dentry->d_name.name, dentry->d_name.len,
4598 backref, index);
4599 if (!err) {
4600 d_instantiate(dentry, inode);
4601 return 0;
4603 if (err > 0)
4604 err = -EEXIST;
4605 return err;
4608 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4609 int mode, dev_t rdev)
4611 struct btrfs_trans_handle *trans;
4612 struct btrfs_root *root = BTRFS_I(dir)->root;
4613 struct inode *inode = NULL;
4614 int err;
4615 int drop_inode = 0;
4616 u64 objectid;
4617 unsigned long nr = 0;
4618 u64 index = 0;
4620 if (!new_valid_dev(rdev))
4621 return -EINVAL;
4624 * 2 for inode item and ref
4625 * 2 for dir items
4626 * 1 for xattr if selinux is on
4628 trans = btrfs_start_transaction(root, 5);
4629 if (IS_ERR(trans))
4630 return PTR_ERR(trans);
4632 btrfs_set_trans_block_group(trans, dir);
4634 err = btrfs_find_free_ino(root, &objectid);
4635 if (err)
4636 goto out_unlock;
4638 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4639 dentry->d_name.len, btrfs_ino(dir), objectid,
4640 BTRFS_I(dir)->block_group, mode, &index);
4641 if (IS_ERR(inode)) {
4642 err = PTR_ERR(inode);
4643 goto out_unlock;
4646 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4647 if (err) {
4648 drop_inode = 1;
4649 goto out_unlock;
4652 btrfs_set_trans_block_group(trans, inode);
4653 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4654 if (err)
4655 drop_inode = 1;
4656 else {
4657 inode->i_op = &btrfs_special_inode_operations;
4658 init_special_inode(inode, inode->i_mode, rdev);
4659 btrfs_update_inode(trans, root, inode);
4661 btrfs_update_inode_block_group(trans, inode);
4662 btrfs_update_inode_block_group(trans, dir);
4663 out_unlock:
4664 nr = trans->blocks_used;
4665 btrfs_end_transaction_throttle(trans, root);
4666 btrfs_btree_balance_dirty(root, nr);
4667 if (drop_inode) {
4668 inode_dec_link_count(inode);
4669 iput(inode);
4671 return err;
4674 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4675 int mode, struct nameidata *nd)
4677 struct btrfs_trans_handle *trans;
4678 struct btrfs_root *root = BTRFS_I(dir)->root;
4679 struct inode *inode = NULL;
4680 int drop_inode = 0;
4681 int err;
4682 unsigned long nr = 0;
4683 u64 objectid;
4684 u64 index = 0;
4687 * 2 for inode item and ref
4688 * 2 for dir items
4689 * 1 for xattr if selinux is on
4691 trans = btrfs_start_transaction(root, 5);
4692 if (IS_ERR(trans))
4693 return PTR_ERR(trans);
4695 btrfs_set_trans_block_group(trans, dir);
4697 err = btrfs_find_free_ino(root, &objectid);
4698 if (err)
4699 goto out_unlock;
4701 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4702 dentry->d_name.len, btrfs_ino(dir), objectid,
4703 BTRFS_I(dir)->block_group, mode, &index);
4704 if (IS_ERR(inode)) {
4705 err = PTR_ERR(inode);
4706 goto out_unlock;
4709 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4710 if (err) {
4711 drop_inode = 1;
4712 goto out_unlock;
4715 btrfs_set_trans_block_group(trans, inode);
4716 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4717 if (err)
4718 drop_inode = 1;
4719 else {
4720 inode->i_mapping->a_ops = &btrfs_aops;
4721 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4722 inode->i_fop = &btrfs_file_operations;
4723 inode->i_op = &btrfs_file_inode_operations;
4724 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4726 btrfs_update_inode_block_group(trans, inode);
4727 btrfs_update_inode_block_group(trans, dir);
4728 out_unlock:
4729 nr = trans->blocks_used;
4730 btrfs_end_transaction_throttle(trans, root);
4731 if (drop_inode) {
4732 inode_dec_link_count(inode);
4733 iput(inode);
4735 btrfs_btree_balance_dirty(root, nr);
4736 return err;
4739 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4740 struct dentry *dentry)
4742 struct btrfs_trans_handle *trans;
4743 struct btrfs_root *root = BTRFS_I(dir)->root;
4744 struct inode *inode = old_dentry->d_inode;
4745 u64 index;
4746 unsigned long nr = 0;
4747 int err;
4748 int drop_inode = 0;
4750 /* do not allow sys_link's with other subvols of the same device */
4751 if (root->objectid != BTRFS_I(inode)->root->objectid)
4752 return -EXDEV;
4754 if (inode->i_nlink == ~0U)
4755 return -EMLINK;
4757 err = btrfs_set_inode_index(dir, &index);
4758 if (err)
4759 goto fail;
4762 * 2 items for inode and inode ref
4763 * 2 items for dir items
4764 * 1 item for parent inode
4766 trans = btrfs_start_transaction(root, 5);
4767 if (IS_ERR(trans)) {
4768 err = PTR_ERR(trans);
4769 goto fail;
4772 btrfs_inc_nlink(inode);
4773 inode->i_ctime = CURRENT_TIME;
4775 btrfs_set_trans_block_group(trans, dir);
4776 ihold(inode);
4778 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4780 if (err) {
4781 drop_inode = 1;
4782 } else {
4783 struct dentry *parent = dget_parent(dentry);
4784 btrfs_update_inode_block_group(trans, dir);
4785 err = btrfs_update_inode(trans, root, inode);
4786 BUG_ON(err);
4787 btrfs_log_new_name(trans, inode, NULL, parent);
4788 dput(parent);
4791 nr = trans->blocks_used;
4792 btrfs_end_transaction_throttle(trans, root);
4793 fail:
4794 if (drop_inode) {
4795 inode_dec_link_count(inode);
4796 iput(inode);
4798 btrfs_btree_balance_dirty(root, nr);
4799 return err;
4802 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4804 struct inode *inode = NULL;
4805 struct btrfs_trans_handle *trans;
4806 struct btrfs_root *root = BTRFS_I(dir)->root;
4807 int err = 0;
4808 int drop_on_err = 0;
4809 u64 objectid = 0;
4810 u64 index = 0;
4811 unsigned long nr = 1;
4814 * 2 items for inode and ref
4815 * 2 items for dir items
4816 * 1 for xattr if selinux is on
4818 trans = btrfs_start_transaction(root, 5);
4819 if (IS_ERR(trans))
4820 return PTR_ERR(trans);
4821 btrfs_set_trans_block_group(trans, dir);
4823 err = btrfs_find_free_ino(root, &objectid);
4824 if (err)
4825 goto out_fail;
4827 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4828 dentry->d_name.len, btrfs_ino(dir), objectid,
4829 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4830 &index);
4831 if (IS_ERR(inode)) {
4832 err = PTR_ERR(inode);
4833 goto out_fail;
4836 drop_on_err = 1;
4838 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4839 if (err)
4840 goto out_fail;
4842 inode->i_op = &btrfs_dir_inode_operations;
4843 inode->i_fop = &btrfs_dir_file_operations;
4844 btrfs_set_trans_block_group(trans, inode);
4846 btrfs_i_size_write(inode, 0);
4847 err = btrfs_update_inode(trans, root, inode);
4848 if (err)
4849 goto out_fail;
4851 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4852 dentry->d_name.len, 0, index);
4853 if (err)
4854 goto out_fail;
4856 d_instantiate(dentry, inode);
4857 drop_on_err = 0;
4858 btrfs_update_inode_block_group(trans, inode);
4859 btrfs_update_inode_block_group(trans, dir);
4861 out_fail:
4862 nr = trans->blocks_used;
4863 btrfs_end_transaction_throttle(trans, root);
4864 if (drop_on_err)
4865 iput(inode);
4866 btrfs_btree_balance_dirty(root, nr);
4867 return err;
4870 /* helper for btfs_get_extent. Given an existing extent in the tree,
4871 * and an extent that you want to insert, deal with overlap and insert
4872 * the new extent into the tree.
4874 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4875 struct extent_map *existing,
4876 struct extent_map *em,
4877 u64 map_start, u64 map_len)
4879 u64 start_diff;
4881 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4882 start_diff = map_start - em->start;
4883 em->start = map_start;
4884 em->len = map_len;
4885 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4886 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4887 em->block_start += start_diff;
4888 em->block_len -= start_diff;
4890 return add_extent_mapping(em_tree, em);
4893 static noinline int uncompress_inline(struct btrfs_path *path,
4894 struct inode *inode, struct page *page,
4895 size_t pg_offset, u64 extent_offset,
4896 struct btrfs_file_extent_item *item)
4898 int ret;
4899 struct extent_buffer *leaf = path->nodes[0];
4900 char *tmp;
4901 size_t max_size;
4902 unsigned long inline_size;
4903 unsigned long ptr;
4904 int compress_type;
4906 WARN_ON(pg_offset != 0);
4907 compress_type = btrfs_file_extent_compression(leaf, item);
4908 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4909 inline_size = btrfs_file_extent_inline_item_len(leaf,
4910 btrfs_item_nr(leaf, path->slots[0]));
4911 tmp = kmalloc(inline_size, GFP_NOFS);
4912 if (!tmp)
4913 return -ENOMEM;
4914 ptr = btrfs_file_extent_inline_start(item);
4916 read_extent_buffer(leaf, tmp, ptr, inline_size);
4918 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4919 ret = btrfs_decompress(compress_type, tmp, page,
4920 extent_offset, inline_size, max_size);
4921 if (ret) {
4922 char *kaddr = kmap_atomic(page, KM_USER0);
4923 unsigned long copy_size = min_t(u64,
4924 PAGE_CACHE_SIZE - pg_offset,
4925 max_size - extent_offset);
4926 memset(kaddr + pg_offset, 0, copy_size);
4927 kunmap_atomic(kaddr, KM_USER0);
4929 kfree(tmp);
4930 return 0;
4934 * a bit scary, this does extent mapping from logical file offset to the disk.
4935 * the ugly parts come from merging extents from the disk with the in-ram
4936 * representation. This gets more complex because of the data=ordered code,
4937 * where the in-ram extents might be locked pending data=ordered completion.
4939 * This also copies inline extents directly into the page.
4942 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4943 size_t pg_offset, u64 start, u64 len,
4944 int create)
4946 int ret;
4947 int err = 0;
4948 u64 bytenr;
4949 u64 extent_start = 0;
4950 u64 extent_end = 0;
4951 u64 objectid = btrfs_ino(inode);
4952 u32 found_type;
4953 struct btrfs_path *path = NULL;
4954 struct btrfs_root *root = BTRFS_I(inode)->root;
4955 struct btrfs_file_extent_item *item;
4956 struct extent_buffer *leaf;
4957 struct btrfs_key found_key;
4958 struct extent_map *em = NULL;
4959 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4960 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4961 struct btrfs_trans_handle *trans = NULL;
4962 int compress_type;
4964 again:
4965 read_lock(&em_tree->lock);
4966 em = lookup_extent_mapping(em_tree, start, len);
4967 if (em)
4968 em->bdev = root->fs_info->fs_devices->latest_bdev;
4969 read_unlock(&em_tree->lock);
4971 if (em) {
4972 if (em->start > start || em->start + em->len <= start)
4973 free_extent_map(em);
4974 else if (em->block_start == EXTENT_MAP_INLINE && page)
4975 free_extent_map(em);
4976 else
4977 goto out;
4979 em = alloc_extent_map();
4980 if (!em) {
4981 err = -ENOMEM;
4982 goto out;
4984 em->bdev = root->fs_info->fs_devices->latest_bdev;
4985 em->start = EXTENT_MAP_HOLE;
4986 em->orig_start = EXTENT_MAP_HOLE;
4987 em->len = (u64)-1;
4988 em->block_len = (u64)-1;
4990 if (!path) {
4991 path = btrfs_alloc_path();
4992 BUG_ON(!path);
4995 ret = btrfs_lookup_file_extent(trans, root, path,
4996 objectid, start, trans != NULL);
4997 if (ret < 0) {
4998 err = ret;
4999 goto out;
5002 if (ret != 0) {
5003 if (path->slots[0] == 0)
5004 goto not_found;
5005 path->slots[0]--;
5008 leaf = path->nodes[0];
5009 item = btrfs_item_ptr(leaf, path->slots[0],
5010 struct btrfs_file_extent_item);
5011 /* are we inside the extent that was found? */
5012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5013 found_type = btrfs_key_type(&found_key);
5014 if (found_key.objectid != objectid ||
5015 found_type != BTRFS_EXTENT_DATA_KEY) {
5016 goto not_found;
5019 found_type = btrfs_file_extent_type(leaf, item);
5020 extent_start = found_key.offset;
5021 compress_type = btrfs_file_extent_compression(leaf, item);
5022 if (found_type == BTRFS_FILE_EXTENT_REG ||
5023 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5024 extent_end = extent_start +
5025 btrfs_file_extent_num_bytes(leaf, item);
5026 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5027 size_t size;
5028 size = btrfs_file_extent_inline_len(leaf, item);
5029 extent_end = (extent_start + size + root->sectorsize - 1) &
5030 ~((u64)root->sectorsize - 1);
5033 if (start >= extent_end) {
5034 path->slots[0]++;
5035 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5036 ret = btrfs_next_leaf(root, path);
5037 if (ret < 0) {
5038 err = ret;
5039 goto out;
5041 if (ret > 0)
5042 goto not_found;
5043 leaf = path->nodes[0];
5045 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5046 if (found_key.objectid != objectid ||
5047 found_key.type != BTRFS_EXTENT_DATA_KEY)
5048 goto not_found;
5049 if (start + len <= found_key.offset)
5050 goto not_found;
5051 em->start = start;
5052 em->len = found_key.offset - start;
5053 goto not_found_em;
5056 if (found_type == BTRFS_FILE_EXTENT_REG ||
5057 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5058 em->start = extent_start;
5059 em->len = extent_end - extent_start;
5060 em->orig_start = extent_start -
5061 btrfs_file_extent_offset(leaf, item);
5062 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5063 if (bytenr == 0) {
5064 em->block_start = EXTENT_MAP_HOLE;
5065 goto insert;
5067 if (compress_type != BTRFS_COMPRESS_NONE) {
5068 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5069 em->compress_type = compress_type;
5070 em->block_start = bytenr;
5071 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5072 item);
5073 } else {
5074 bytenr += btrfs_file_extent_offset(leaf, item);
5075 em->block_start = bytenr;
5076 em->block_len = em->len;
5077 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5078 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5080 goto insert;
5081 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5082 unsigned long ptr;
5083 char *map;
5084 size_t size;
5085 size_t extent_offset;
5086 size_t copy_size;
5088 em->block_start = EXTENT_MAP_INLINE;
5089 if (!page || create) {
5090 em->start = extent_start;
5091 em->len = extent_end - extent_start;
5092 goto out;
5095 size = btrfs_file_extent_inline_len(leaf, item);
5096 extent_offset = page_offset(page) + pg_offset - extent_start;
5097 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5098 size - extent_offset);
5099 em->start = extent_start + extent_offset;
5100 em->len = (copy_size + root->sectorsize - 1) &
5101 ~((u64)root->sectorsize - 1);
5102 em->orig_start = EXTENT_MAP_INLINE;
5103 if (compress_type) {
5104 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5105 em->compress_type = compress_type;
5107 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5108 if (create == 0 && !PageUptodate(page)) {
5109 if (btrfs_file_extent_compression(leaf, item) !=
5110 BTRFS_COMPRESS_NONE) {
5111 ret = uncompress_inline(path, inode, page,
5112 pg_offset,
5113 extent_offset, item);
5114 BUG_ON(ret);
5115 } else {
5116 map = kmap(page);
5117 read_extent_buffer(leaf, map + pg_offset, ptr,
5118 copy_size);
5119 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5120 memset(map + pg_offset + copy_size, 0,
5121 PAGE_CACHE_SIZE - pg_offset -
5122 copy_size);
5124 kunmap(page);
5126 flush_dcache_page(page);
5127 } else if (create && PageUptodate(page)) {
5128 WARN_ON(1);
5129 if (!trans) {
5130 kunmap(page);
5131 free_extent_map(em);
5132 em = NULL;
5133 btrfs_release_path(path);
5134 trans = btrfs_join_transaction(root, 1);
5135 if (IS_ERR(trans))
5136 return ERR_CAST(trans);
5137 goto again;
5139 map = kmap(page);
5140 write_extent_buffer(leaf, map + pg_offset, ptr,
5141 copy_size);
5142 kunmap(page);
5143 btrfs_mark_buffer_dirty(leaf);
5145 set_extent_uptodate(io_tree, em->start,
5146 extent_map_end(em) - 1, NULL, GFP_NOFS);
5147 goto insert;
5148 } else {
5149 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5150 WARN_ON(1);
5152 not_found:
5153 em->start = start;
5154 em->len = len;
5155 not_found_em:
5156 em->block_start = EXTENT_MAP_HOLE;
5157 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5158 insert:
5159 btrfs_release_path(path);
5160 if (em->start > start || extent_map_end(em) <= start) {
5161 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5162 "[%llu %llu]\n", (unsigned long long)em->start,
5163 (unsigned long long)em->len,
5164 (unsigned long long)start,
5165 (unsigned long long)len);
5166 err = -EIO;
5167 goto out;
5170 err = 0;
5171 write_lock(&em_tree->lock);
5172 ret = add_extent_mapping(em_tree, em);
5173 /* it is possible that someone inserted the extent into the tree
5174 * while we had the lock dropped. It is also possible that
5175 * an overlapping map exists in the tree
5177 if (ret == -EEXIST) {
5178 struct extent_map *existing;
5180 ret = 0;
5182 existing = lookup_extent_mapping(em_tree, start, len);
5183 if (existing && (existing->start > start ||
5184 existing->start + existing->len <= start)) {
5185 free_extent_map(existing);
5186 existing = NULL;
5188 if (!existing) {
5189 existing = lookup_extent_mapping(em_tree, em->start,
5190 em->len);
5191 if (existing) {
5192 err = merge_extent_mapping(em_tree, existing,
5193 em, start,
5194 root->sectorsize);
5195 free_extent_map(existing);
5196 if (err) {
5197 free_extent_map(em);
5198 em = NULL;
5200 } else {
5201 err = -EIO;
5202 free_extent_map(em);
5203 em = NULL;
5205 } else {
5206 free_extent_map(em);
5207 em = existing;
5208 err = 0;
5211 write_unlock(&em_tree->lock);
5212 out:
5214 trace_btrfs_get_extent(root, em);
5216 if (path)
5217 btrfs_free_path(path);
5218 if (trans) {
5219 ret = btrfs_end_transaction(trans, root);
5220 if (!err)
5221 err = ret;
5223 if (err) {
5224 free_extent_map(em);
5225 return ERR_PTR(err);
5227 return em;
5230 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5231 size_t pg_offset, u64 start, u64 len,
5232 int create)
5234 struct extent_map *em;
5235 struct extent_map *hole_em = NULL;
5236 u64 range_start = start;
5237 u64 end;
5238 u64 found;
5239 u64 found_end;
5240 int err = 0;
5242 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5243 if (IS_ERR(em))
5244 return em;
5245 if (em) {
5247 * if our em maps to a hole, there might
5248 * actually be delalloc bytes behind it
5250 if (em->block_start != EXTENT_MAP_HOLE)
5251 return em;
5252 else
5253 hole_em = em;
5256 /* check to see if we've wrapped (len == -1 or similar) */
5257 end = start + len;
5258 if (end < start)
5259 end = (u64)-1;
5260 else
5261 end -= 1;
5263 em = NULL;
5265 /* ok, we didn't find anything, lets look for delalloc */
5266 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5267 end, len, EXTENT_DELALLOC, 1);
5268 found_end = range_start + found;
5269 if (found_end < range_start)
5270 found_end = (u64)-1;
5273 * we didn't find anything useful, return
5274 * the original results from get_extent()
5276 if (range_start > end || found_end <= start) {
5277 em = hole_em;
5278 hole_em = NULL;
5279 goto out;
5282 /* adjust the range_start to make sure it doesn't
5283 * go backwards from the start they passed in
5285 range_start = max(start,range_start);
5286 found = found_end - range_start;
5288 if (found > 0) {
5289 u64 hole_start = start;
5290 u64 hole_len = len;
5292 em = alloc_extent_map();
5293 if (!em) {
5294 err = -ENOMEM;
5295 goto out;
5298 * when btrfs_get_extent can't find anything it
5299 * returns one huge hole
5301 * make sure what it found really fits our range, and
5302 * adjust to make sure it is based on the start from
5303 * the caller
5305 if (hole_em) {
5306 u64 calc_end = extent_map_end(hole_em);
5308 if (calc_end <= start || (hole_em->start > end)) {
5309 free_extent_map(hole_em);
5310 hole_em = NULL;
5311 } else {
5312 hole_start = max(hole_em->start, start);
5313 hole_len = calc_end - hole_start;
5316 em->bdev = NULL;
5317 if (hole_em && range_start > hole_start) {
5318 /* our hole starts before our delalloc, so we
5319 * have to return just the parts of the hole
5320 * that go until the delalloc starts
5322 em->len = min(hole_len,
5323 range_start - hole_start);
5324 em->start = hole_start;
5325 em->orig_start = hole_start;
5327 * don't adjust block start at all,
5328 * it is fixed at EXTENT_MAP_HOLE
5330 em->block_start = hole_em->block_start;
5331 em->block_len = hole_len;
5332 } else {
5333 em->start = range_start;
5334 em->len = found;
5335 em->orig_start = range_start;
5336 em->block_start = EXTENT_MAP_DELALLOC;
5337 em->block_len = found;
5339 } else if (hole_em) {
5340 return hole_em;
5342 out:
5344 free_extent_map(hole_em);
5345 if (err) {
5346 free_extent_map(em);
5347 return ERR_PTR(err);
5349 return em;
5352 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5353 struct extent_map *em,
5354 u64 start, u64 len)
5356 struct btrfs_root *root = BTRFS_I(inode)->root;
5357 struct btrfs_trans_handle *trans;
5358 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5359 struct btrfs_key ins;
5360 u64 alloc_hint;
5361 int ret;
5362 bool insert = false;
5365 * Ok if the extent map we looked up is a hole and is for the exact
5366 * range we want, there is no reason to allocate a new one, however if
5367 * it is not right then we need to free this one and drop the cache for
5368 * our range.
5370 if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5371 em->len != len) {
5372 free_extent_map(em);
5373 em = NULL;
5374 insert = true;
5375 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5378 trans = btrfs_join_transaction(root, 0);
5379 if (IS_ERR(trans))
5380 return ERR_CAST(trans);
5382 if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5383 btrfs_add_inode_defrag(trans, inode);
5385 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5387 alloc_hint = get_extent_allocation_hint(inode, start, len);
5388 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5389 alloc_hint, (u64)-1, &ins, 1);
5390 if (ret) {
5391 em = ERR_PTR(ret);
5392 goto out;
5395 if (!em) {
5396 em = alloc_extent_map();
5397 if (!em) {
5398 em = ERR_PTR(-ENOMEM);
5399 goto out;
5403 em->start = start;
5404 em->orig_start = em->start;
5405 em->len = ins.offset;
5407 em->block_start = ins.objectid;
5408 em->block_len = ins.offset;
5409 em->bdev = root->fs_info->fs_devices->latest_bdev;
5412 * We need to do this because if we're using the original em we searched
5413 * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5415 em->flags = 0;
5416 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5418 while (insert) {
5419 write_lock(&em_tree->lock);
5420 ret = add_extent_mapping(em_tree, em);
5421 write_unlock(&em_tree->lock);
5422 if (ret != -EEXIST)
5423 break;
5424 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5427 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5428 ins.offset, ins.offset, 0);
5429 if (ret) {
5430 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5431 em = ERR_PTR(ret);
5433 out:
5434 btrfs_end_transaction(trans, root);
5435 return em;
5439 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5440 * block must be cow'd
5442 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5443 struct inode *inode, u64 offset, u64 len)
5445 struct btrfs_path *path;
5446 int ret;
5447 struct extent_buffer *leaf;
5448 struct btrfs_root *root = BTRFS_I(inode)->root;
5449 struct btrfs_file_extent_item *fi;
5450 struct btrfs_key key;
5451 u64 disk_bytenr;
5452 u64 backref_offset;
5453 u64 extent_end;
5454 u64 num_bytes;
5455 int slot;
5456 int found_type;
5458 path = btrfs_alloc_path();
5459 if (!path)
5460 return -ENOMEM;
5462 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5463 offset, 0);
5464 if (ret < 0)
5465 goto out;
5467 slot = path->slots[0];
5468 if (ret == 1) {
5469 if (slot == 0) {
5470 /* can't find the item, must cow */
5471 ret = 0;
5472 goto out;
5474 slot--;
5476 ret = 0;
5477 leaf = path->nodes[0];
5478 btrfs_item_key_to_cpu(leaf, &key, slot);
5479 if (key.objectid != btrfs_ino(inode) ||
5480 key.type != BTRFS_EXTENT_DATA_KEY) {
5481 /* not our file or wrong item type, must cow */
5482 goto out;
5485 if (key.offset > offset) {
5486 /* Wrong offset, must cow */
5487 goto out;
5490 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5491 found_type = btrfs_file_extent_type(leaf, fi);
5492 if (found_type != BTRFS_FILE_EXTENT_REG &&
5493 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5494 /* not a regular extent, must cow */
5495 goto out;
5497 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5498 backref_offset = btrfs_file_extent_offset(leaf, fi);
5500 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5501 if (extent_end < offset + len) {
5502 /* extent doesn't include our full range, must cow */
5503 goto out;
5506 if (btrfs_extent_readonly(root, disk_bytenr))
5507 goto out;
5510 * look for other files referencing this extent, if we
5511 * find any we must cow
5513 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5514 key.offset - backref_offset, disk_bytenr))
5515 goto out;
5518 * adjust disk_bytenr and num_bytes to cover just the bytes
5519 * in this extent we are about to write. If there
5520 * are any csums in that range we have to cow in order
5521 * to keep the csums correct
5523 disk_bytenr += backref_offset;
5524 disk_bytenr += offset - key.offset;
5525 num_bytes = min(offset + len, extent_end) - offset;
5526 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5527 goto out;
5529 * all of the above have passed, it is safe to overwrite this extent
5530 * without cow
5532 ret = 1;
5533 out:
5534 btrfs_free_path(path);
5535 return ret;
5538 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5539 struct buffer_head *bh_result, int create)
5541 struct extent_map *em;
5542 struct btrfs_root *root = BTRFS_I(inode)->root;
5543 u64 start = iblock << inode->i_blkbits;
5544 u64 len = bh_result->b_size;
5545 struct btrfs_trans_handle *trans;
5547 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5548 if (IS_ERR(em))
5549 return PTR_ERR(em);
5552 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5553 * io. INLINE is special, and we could probably kludge it in here, but
5554 * it's still buffered so for safety lets just fall back to the generic
5555 * buffered path.
5557 * For COMPRESSED we _have_ to read the entire extent in so we can
5558 * decompress it, so there will be buffering required no matter what we
5559 * do, so go ahead and fallback to buffered.
5561 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5562 * to buffered IO. Don't blame me, this is the price we pay for using
5563 * the generic code.
5565 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5566 em->block_start == EXTENT_MAP_INLINE) {
5567 free_extent_map(em);
5568 return -ENOTBLK;
5571 /* Just a good old fashioned hole, return */
5572 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5573 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5574 free_extent_map(em);
5575 /* DIO will do one hole at a time, so just unlock a sector */
5576 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5577 start + root->sectorsize - 1, GFP_NOFS);
5578 return 0;
5582 * We don't allocate a new extent in the following cases
5584 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5585 * existing extent.
5586 * 2) The extent is marked as PREALLOC. We're good to go here and can
5587 * just use the extent.
5590 if (!create) {
5591 len = em->len - (start - em->start);
5592 goto map;
5595 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5596 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5597 em->block_start != EXTENT_MAP_HOLE)) {
5598 int type;
5599 int ret;
5600 u64 block_start;
5602 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5603 type = BTRFS_ORDERED_PREALLOC;
5604 else
5605 type = BTRFS_ORDERED_NOCOW;
5606 len = min(len, em->len - (start - em->start));
5607 block_start = em->block_start + (start - em->start);
5610 * we're not going to log anything, but we do need
5611 * to make sure the current transaction stays open
5612 * while we look for nocow cross refs
5614 trans = btrfs_join_transaction(root, 0);
5615 if (IS_ERR(trans))
5616 goto must_cow;
5618 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5619 ret = btrfs_add_ordered_extent_dio(inode, start,
5620 block_start, len, len, type);
5621 btrfs_end_transaction(trans, root);
5622 if (ret) {
5623 free_extent_map(em);
5624 return ret;
5626 goto unlock;
5628 btrfs_end_transaction(trans, root);
5630 must_cow:
5632 * this will cow the extent, reset the len in case we changed
5633 * it above
5635 len = bh_result->b_size;
5636 em = btrfs_new_extent_direct(inode, em, start, len);
5637 if (IS_ERR(em))
5638 return PTR_ERR(em);
5639 len = min(len, em->len - (start - em->start));
5640 unlock:
5641 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5642 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5643 0, NULL, GFP_NOFS);
5644 map:
5645 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5646 inode->i_blkbits;
5647 bh_result->b_size = len;
5648 bh_result->b_bdev = em->bdev;
5649 set_buffer_mapped(bh_result);
5650 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5651 set_buffer_new(bh_result);
5653 free_extent_map(em);
5655 return 0;
5658 struct btrfs_dio_private {
5659 struct inode *inode;
5660 u64 logical_offset;
5661 u64 disk_bytenr;
5662 u64 bytes;
5663 u32 *csums;
5664 void *private;
5666 /* number of bios pending for this dio */
5667 atomic_t pending_bios;
5669 /* IO errors */
5670 int errors;
5672 struct bio *orig_bio;
5675 static void btrfs_endio_direct_read(struct bio *bio, int err)
5677 struct btrfs_dio_private *dip = bio->bi_private;
5678 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5679 struct bio_vec *bvec = bio->bi_io_vec;
5680 struct inode *inode = dip->inode;
5681 struct btrfs_root *root = BTRFS_I(inode)->root;
5682 u64 start;
5683 u32 *private = dip->csums;
5685 start = dip->logical_offset;
5686 do {
5687 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5688 struct page *page = bvec->bv_page;
5689 char *kaddr;
5690 u32 csum = ~(u32)0;
5691 unsigned long flags;
5693 local_irq_save(flags);
5694 kaddr = kmap_atomic(page, KM_IRQ0);
5695 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5696 csum, bvec->bv_len);
5697 btrfs_csum_final(csum, (char *)&csum);
5698 kunmap_atomic(kaddr, KM_IRQ0);
5699 local_irq_restore(flags);
5701 flush_dcache_page(bvec->bv_page);
5702 if (csum != *private) {
5703 printk(KERN_ERR "btrfs csum failed ino %llu off"
5704 " %llu csum %u private %u\n",
5705 (unsigned long long)btrfs_ino(inode),
5706 (unsigned long long)start,
5707 csum, *private);
5708 err = -EIO;
5712 start += bvec->bv_len;
5713 private++;
5714 bvec++;
5715 } while (bvec <= bvec_end);
5717 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5718 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5719 bio->bi_private = dip->private;
5721 kfree(dip->csums);
5722 kfree(dip);
5724 /* If we had a csum failure make sure to clear the uptodate flag */
5725 if (err)
5726 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5727 dio_end_io(bio, err);
5730 static void btrfs_endio_direct_write(struct bio *bio, int err)
5732 struct btrfs_dio_private *dip = bio->bi_private;
5733 struct inode *inode = dip->inode;
5734 struct btrfs_root *root = BTRFS_I(inode)->root;
5735 struct btrfs_trans_handle *trans;
5736 struct btrfs_ordered_extent *ordered = NULL;
5737 struct extent_state *cached_state = NULL;
5738 u64 ordered_offset = dip->logical_offset;
5739 u64 ordered_bytes = dip->bytes;
5740 int ret;
5742 if (err)
5743 goto out_done;
5744 again:
5745 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5746 &ordered_offset,
5747 ordered_bytes);
5748 if (!ret)
5749 goto out_test;
5751 BUG_ON(!ordered);
5753 trans = btrfs_join_transaction(root, 1);
5754 if (IS_ERR(trans)) {
5755 err = -ENOMEM;
5756 goto out;
5758 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5760 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5761 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5762 if (!ret)
5763 ret = btrfs_update_inode(trans, root, inode);
5764 err = ret;
5765 goto out;
5768 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5769 ordered->file_offset + ordered->len - 1, 0,
5770 &cached_state, GFP_NOFS);
5772 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5773 ret = btrfs_mark_extent_written(trans, inode,
5774 ordered->file_offset,
5775 ordered->file_offset +
5776 ordered->len);
5777 if (ret) {
5778 err = ret;
5779 goto out_unlock;
5781 } else {
5782 ret = insert_reserved_file_extent(trans, inode,
5783 ordered->file_offset,
5784 ordered->start,
5785 ordered->disk_len,
5786 ordered->len,
5787 ordered->len,
5788 0, 0, 0,
5789 BTRFS_FILE_EXTENT_REG);
5790 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5791 ordered->file_offset, ordered->len);
5792 if (ret) {
5793 err = ret;
5794 WARN_ON(1);
5795 goto out_unlock;
5799 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5800 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5801 if (!ret)
5802 btrfs_update_inode(trans, root, inode);
5803 ret = 0;
5804 out_unlock:
5805 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5806 ordered->file_offset + ordered->len - 1,
5807 &cached_state, GFP_NOFS);
5808 out:
5809 btrfs_delalloc_release_metadata(inode, ordered->len);
5810 btrfs_end_transaction(trans, root);
5811 ordered_offset = ordered->file_offset + ordered->len;
5812 btrfs_put_ordered_extent(ordered);
5813 btrfs_put_ordered_extent(ordered);
5815 out_test:
5817 * our bio might span multiple ordered extents. If we haven't
5818 * completed the accounting for the whole dio, go back and try again
5820 if (ordered_offset < dip->logical_offset + dip->bytes) {
5821 ordered_bytes = dip->logical_offset + dip->bytes -
5822 ordered_offset;
5823 goto again;
5825 out_done:
5826 bio->bi_private = dip->private;
5828 kfree(dip->csums);
5829 kfree(dip);
5831 /* If we had an error make sure to clear the uptodate flag */
5832 if (err)
5833 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5834 dio_end_io(bio, err);
5837 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5838 struct bio *bio, int mirror_num,
5839 unsigned long bio_flags, u64 offset)
5841 int ret;
5842 struct btrfs_root *root = BTRFS_I(inode)->root;
5843 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5844 BUG_ON(ret);
5845 return 0;
5848 static void btrfs_end_dio_bio(struct bio *bio, int err)
5850 struct btrfs_dio_private *dip = bio->bi_private;
5852 if (err) {
5853 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
5854 "sector %#Lx len %u err no %d\n",
5855 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
5856 (unsigned long long)bio->bi_sector, bio->bi_size, err);
5857 dip->errors = 1;
5860 * before atomic variable goto zero, we must make sure
5861 * dip->errors is perceived to be set.
5863 smp_mb__before_atomic_dec();
5866 /* if there are more bios still pending for this dio, just exit */
5867 if (!atomic_dec_and_test(&dip->pending_bios))
5868 goto out;
5870 if (dip->errors)
5871 bio_io_error(dip->orig_bio);
5872 else {
5873 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5874 bio_endio(dip->orig_bio, 0);
5876 out:
5877 bio_put(bio);
5880 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5881 u64 first_sector, gfp_t gfp_flags)
5883 int nr_vecs = bio_get_nr_vecs(bdev);
5884 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5887 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5888 int rw, u64 file_offset, int skip_sum,
5889 u32 *csums, int async_submit)
5891 int write = rw & REQ_WRITE;
5892 struct btrfs_root *root = BTRFS_I(inode)->root;
5893 int ret;
5895 bio_get(bio);
5896 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5897 if (ret)
5898 goto err;
5900 if (skip_sum)
5901 goto map;
5903 if (write && async_submit) {
5904 ret = btrfs_wq_submit_bio(root->fs_info,
5905 inode, rw, bio, 0, 0,
5906 file_offset,
5907 __btrfs_submit_bio_start_direct_io,
5908 __btrfs_submit_bio_done);
5909 goto err;
5910 } else if (write) {
5912 * If we aren't doing async submit, calculate the csum of the
5913 * bio now.
5915 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
5916 if (ret)
5917 goto err;
5918 } else if (!skip_sum) {
5919 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
5920 file_offset, csums);
5921 if (ret)
5922 goto err;
5925 map:
5926 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
5927 err:
5928 bio_put(bio);
5929 return ret;
5932 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5933 int skip_sum)
5935 struct inode *inode = dip->inode;
5936 struct btrfs_root *root = BTRFS_I(inode)->root;
5937 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5938 struct bio *bio;
5939 struct bio *orig_bio = dip->orig_bio;
5940 struct bio_vec *bvec = orig_bio->bi_io_vec;
5941 u64 start_sector = orig_bio->bi_sector;
5942 u64 file_offset = dip->logical_offset;
5943 u64 submit_len = 0;
5944 u64 map_length;
5945 int nr_pages = 0;
5946 u32 *csums = dip->csums;
5947 int ret = 0;
5948 int async_submit = 0;
5949 int write = rw & REQ_WRITE;
5951 map_length = orig_bio->bi_size;
5952 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5953 &map_length, NULL, 0);
5954 if (ret) {
5955 bio_put(orig_bio);
5956 return -EIO;
5959 if (map_length >= orig_bio->bi_size) {
5960 bio = orig_bio;
5961 goto submit;
5964 async_submit = 1;
5965 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5966 if (!bio)
5967 return -ENOMEM;
5968 bio->bi_private = dip;
5969 bio->bi_end_io = btrfs_end_dio_bio;
5970 atomic_inc(&dip->pending_bios);
5972 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5973 if (unlikely(map_length < submit_len + bvec->bv_len ||
5974 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5975 bvec->bv_offset) < bvec->bv_len)) {
5977 * inc the count before we submit the bio so
5978 * we know the end IO handler won't happen before
5979 * we inc the count. Otherwise, the dip might get freed
5980 * before we're done setting it up
5982 atomic_inc(&dip->pending_bios);
5983 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5984 file_offset, skip_sum,
5985 csums, async_submit);
5986 if (ret) {
5987 bio_put(bio);
5988 atomic_dec(&dip->pending_bios);
5989 goto out_err;
5992 /* Write's use the ordered csums */
5993 if (!write && !skip_sum)
5994 csums = csums + nr_pages;
5995 start_sector += submit_len >> 9;
5996 file_offset += submit_len;
5998 submit_len = 0;
5999 nr_pages = 0;
6001 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6002 start_sector, GFP_NOFS);
6003 if (!bio)
6004 goto out_err;
6005 bio->bi_private = dip;
6006 bio->bi_end_io = btrfs_end_dio_bio;
6008 map_length = orig_bio->bi_size;
6009 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6010 &map_length, NULL, 0);
6011 if (ret) {
6012 bio_put(bio);
6013 goto out_err;
6015 } else {
6016 submit_len += bvec->bv_len;
6017 nr_pages ++;
6018 bvec++;
6022 submit:
6023 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6024 csums, async_submit);
6025 if (!ret)
6026 return 0;
6028 bio_put(bio);
6029 out_err:
6030 dip->errors = 1;
6032 * before atomic variable goto zero, we must
6033 * make sure dip->errors is perceived to be set.
6035 smp_mb__before_atomic_dec();
6036 if (atomic_dec_and_test(&dip->pending_bios))
6037 bio_io_error(dip->orig_bio);
6039 /* bio_end_io() will handle error, so we needn't return it */
6040 return 0;
6043 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6044 loff_t file_offset)
6046 struct btrfs_root *root = BTRFS_I(inode)->root;
6047 struct btrfs_dio_private *dip;
6048 struct bio_vec *bvec = bio->bi_io_vec;
6049 int skip_sum;
6050 int write = rw & REQ_WRITE;
6051 int ret = 0;
6053 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6055 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6056 if (!dip) {
6057 ret = -ENOMEM;
6058 goto free_ordered;
6060 dip->csums = NULL;
6062 /* Write's use the ordered csum stuff, so we don't need dip->csums */
6063 if (!write && !skip_sum) {
6064 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6065 if (!dip->csums) {
6066 kfree(dip);
6067 ret = -ENOMEM;
6068 goto free_ordered;
6072 dip->private = bio->bi_private;
6073 dip->inode = inode;
6074 dip->logical_offset = file_offset;
6076 dip->bytes = 0;
6077 do {
6078 dip->bytes += bvec->bv_len;
6079 bvec++;
6080 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6082 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6083 bio->bi_private = dip;
6084 dip->errors = 0;
6085 dip->orig_bio = bio;
6086 atomic_set(&dip->pending_bios, 0);
6088 if (write)
6089 bio->bi_end_io = btrfs_endio_direct_write;
6090 else
6091 bio->bi_end_io = btrfs_endio_direct_read;
6093 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6094 if (!ret)
6095 return;
6096 free_ordered:
6098 * If this is a write, we need to clean up the reserved space and kill
6099 * the ordered extent.
6101 if (write) {
6102 struct btrfs_ordered_extent *ordered;
6103 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6104 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6105 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6106 btrfs_free_reserved_extent(root, ordered->start,
6107 ordered->disk_len);
6108 btrfs_put_ordered_extent(ordered);
6109 btrfs_put_ordered_extent(ordered);
6111 bio_endio(bio, ret);
6114 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6115 const struct iovec *iov, loff_t offset,
6116 unsigned long nr_segs)
6118 int seg;
6119 int i;
6120 size_t size;
6121 unsigned long addr;
6122 unsigned blocksize_mask = root->sectorsize - 1;
6123 ssize_t retval = -EINVAL;
6124 loff_t end = offset;
6126 if (offset & blocksize_mask)
6127 goto out;
6129 /* Check the memory alignment. Blocks cannot straddle pages */
6130 for (seg = 0; seg < nr_segs; seg++) {
6131 addr = (unsigned long)iov[seg].iov_base;
6132 size = iov[seg].iov_len;
6133 end += size;
6134 if ((addr & blocksize_mask) || (size & blocksize_mask))
6135 goto out;
6137 /* If this is a write we don't need to check anymore */
6138 if (rw & WRITE)
6139 continue;
6142 * Check to make sure we don't have duplicate iov_base's in this
6143 * iovec, if so return EINVAL, otherwise we'll get csum errors
6144 * when reading back.
6146 for (i = seg + 1; i < nr_segs; i++) {
6147 if (iov[seg].iov_base == iov[i].iov_base)
6148 goto out;
6151 retval = 0;
6152 out:
6153 return retval;
6155 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6156 const struct iovec *iov, loff_t offset,
6157 unsigned long nr_segs)
6159 struct file *file = iocb->ki_filp;
6160 struct inode *inode = file->f_mapping->host;
6161 struct btrfs_ordered_extent *ordered;
6162 struct extent_state *cached_state = NULL;
6163 u64 lockstart, lockend;
6164 ssize_t ret;
6165 int writing = rw & WRITE;
6166 int write_bits = 0;
6167 size_t count = iov_length(iov, nr_segs);
6169 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6170 offset, nr_segs)) {
6171 return 0;
6174 lockstart = offset;
6175 lockend = offset + count - 1;
6177 if (writing) {
6178 ret = btrfs_delalloc_reserve_space(inode, count);
6179 if (ret)
6180 goto out;
6183 while (1) {
6184 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6185 0, &cached_state, GFP_NOFS);
6187 * We're concerned with the entire range that we're going to be
6188 * doing DIO to, so we need to make sure theres no ordered
6189 * extents in this range.
6191 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6192 lockend - lockstart + 1);
6193 if (!ordered)
6194 break;
6195 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6196 &cached_state, GFP_NOFS);
6197 btrfs_start_ordered_extent(inode, ordered, 1);
6198 btrfs_put_ordered_extent(ordered);
6199 cond_resched();
6203 * we don't use btrfs_set_extent_delalloc because we don't want
6204 * the dirty or uptodate bits
6206 if (writing) {
6207 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6208 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6209 EXTENT_DELALLOC, 0, NULL, &cached_state,
6210 GFP_NOFS);
6211 if (ret) {
6212 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6213 lockend, EXTENT_LOCKED | write_bits,
6214 1, 0, &cached_state, GFP_NOFS);
6215 goto out;
6219 free_extent_state(cached_state);
6220 cached_state = NULL;
6222 ret = __blockdev_direct_IO(rw, iocb, inode,
6223 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6224 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6225 btrfs_submit_direct, 0);
6227 if (ret < 0 && ret != -EIOCBQUEUED) {
6228 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6229 offset + iov_length(iov, nr_segs) - 1,
6230 EXTENT_LOCKED | write_bits, 1, 0,
6231 &cached_state, GFP_NOFS);
6232 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6234 * We're falling back to buffered, unlock the section we didn't
6235 * do IO on.
6237 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6238 offset + iov_length(iov, nr_segs) - 1,
6239 EXTENT_LOCKED | write_bits, 1, 0,
6240 &cached_state, GFP_NOFS);
6242 out:
6243 free_extent_state(cached_state);
6244 return ret;
6247 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6248 __u64 start, __u64 len)
6250 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6253 int btrfs_readpage(struct file *file, struct page *page)
6255 struct extent_io_tree *tree;
6256 tree = &BTRFS_I(page->mapping->host)->io_tree;
6257 return extent_read_full_page(tree, page, btrfs_get_extent);
6260 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6262 struct extent_io_tree *tree;
6265 if (current->flags & PF_MEMALLOC) {
6266 redirty_page_for_writepage(wbc, page);
6267 unlock_page(page);
6268 return 0;
6270 tree = &BTRFS_I(page->mapping->host)->io_tree;
6271 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6274 int btrfs_writepages(struct address_space *mapping,
6275 struct writeback_control *wbc)
6277 struct extent_io_tree *tree;
6279 tree = &BTRFS_I(mapping->host)->io_tree;
6280 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6283 static int
6284 btrfs_readpages(struct file *file, struct address_space *mapping,
6285 struct list_head *pages, unsigned nr_pages)
6287 struct extent_io_tree *tree;
6288 tree = &BTRFS_I(mapping->host)->io_tree;
6289 return extent_readpages(tree, mapping, pages, nr_pages,
6290 btrfs_get_extent);
6292 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6294 struct extent_io_tree *tree;
6295 struct extent_map_tree *map;
6296 int ret;
6298 tree = &BTRFS_I(page->mapping->host)->io_tree;
6299 map = &BTRFS_I(page->mapping->host)->extent_tree;
6300 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6301 if (ret == 1) {
6302 ClearPagePrivate(page);
6303 set_page_private(page, 0);
6304 page_cache_release(page);
6306 return ret;
6309 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6311 if (PageWriteback(page) || PageDirty(page))
6312 return 0;
6313 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6316 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6318 struct extent_io_tree *tree;
6319 struct btrfs_ordered_extent *ordered;
6320 struct extent_state *cached_state = NULL;
6321 u64 page_start = page_offset(page);
6322 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6326 * we have the page locked, so new writeback can't start,
6327 * and the dirty bit won't be cleared while we are here.
6329 * Wait for IO on this page so that we can safely clear
6330 * the PagePrivate2 bit and do ordered accounting
6332 wait_on_page_writeback(page);
6334 tree = &BTRFS_I(page->mapping->host)->io_tree;
6335 if (offset) {
6336 btrfs_releasepage(page, GFP_NOFS);
6337 return;
6339 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6340 GFP_NOFS);
6341 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6342 page_offset(page));
6343 if (ordered) {
6345 * IO on this page will never be started, so we need
6346 * to account for any ordered extents now
6348 clear_extent_bit(tree, page_start, page_end,
6349 EXTENT_DIRTY | EXTENT_DELALLOC |
6350 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6351 &cached_state, GFP_NOFS);
6353 * whoever cleared the private bit is responsible
6354 * for the finish_ordered_io
6356 if (TestClearPagePrivate2(page)) {
6357 btrfs_finish_ordered_io(page->mapping->host,
6358 page_start, page_end);
6360 btrfs_put_ordered_extent(ordered);
6361 cached_state = NULL;
6362 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6363 GFP_NOFS);
6365 clear_extent_bit(tree, page_start, page_end,
6366 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6367 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6368 __btrfs_releasepage(page, GFP_NOFS);
6370 ClearPageChecked(page);
6371 if (PagePrivate(page)) {
6372 ClearPagePrivate(page);
6373 set_page_private(page, 0);
6374 page_cache_release(page);
6379 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6380 * called from a page fault handler when a page is first dirtied. Hence we must
6381 * be careful to check for EOF conditions here. We set the page up correctly
6382 * for a written page which means we get ENOSPC checking when writing into
6383 * holes and correct delalloc and unwritten extent mapping on filesystems that
6384 * support these features.
6386 * We are not allowed to take the i_mutex here so we have to play games to
6387 * protect against truncate races as the page could now be beyond EOF. Because
6388 * vmtruncate() writes the inode size before removing pages, once we have the
6389 * page lock we can determine safely if the page is beyond EOF. If it is not
6390 * beyond EOF, then the page is guaranteed safe against truncation until we
6391 * unlock the page.
6393 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6395 struct page *page = vmf->page;
6396 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6397 struct btrfs_root *root = BTRFS_I(inode)->root;
6398 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6399 struct btrfs_ordered_extent *ordered;
6400 struct extent_state *cached_state = NULL;
6401 char *kaddr;
6402 unsigned long zero_start;
6403 loff_t size;
6404 int ret;
6405 u64 page_start;
6406 u64 page_end;
6408 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6409 if (ret) {
6410 if (ret == -ENOMEM)
6411 ret = VM_FAULT_OOM;
6412 else /* -ENOSPC, -EIO, etc */
6413 ret = VM_FAULT_SIGBUS;
6414 goto out;
6417 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6418 again:
6419 lock_page(page);
6420 size = i_size_read(inode);
6421 page_start = page_offset(page);
6422 page_end = page_start + PAGE_CACHE_SIZE - 1;
6424 if ((page->mapping != inode->i_mapping) ||
6425 (page_start >= size)) {
6426 /* page got truncated out from underneath us */
6427 goto out_unlock;
6429 wait_on_page_writeback(page);
6431 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6432 GFP_NOFS);
6433 set_page_extent_mapped(page);
6436 * we can't set the delalloc bits if there are pending ordered
6437 * extents. Drop our locks and wait for them to finish
6439 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6440 if (ordered) {
6441 unlock_extent_cached(io_tree, page_start, page_end,
6442 &cached_state, GFP_NOFS);
6443 unlock_page(page);
6444 btrfs_start_ordered_extent(inode, ordered, 1);
6445 btrfs_put_ordered_extent(ordered);
6446 goto again;
6450 * XXX - page_mkwrite gets called every time the page is dirtied, even
6451 * if it was already dirty, so for space accounting reasons we need to
6452 * clear any delalloc bits for the range we are fixing to save. There
6453 * is probably a better way to do this, but for now keep consistent with
6454 * prepare_pages in the normal write path.
6456 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6457 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6458 0, 0, &cached_state, GFP_NOFS);
6460 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6461 &cached_state);
6462 if (ret) {
6463 unlock_extent_cached(io_tree, page_start, page_end,
6464 &cached_state, GFP_NOFS);
6465 ret = VM_FAULT_SIGBUS;
6466 goto out_unlock;
6468 ret = 0;
6470 /* page is wholly or partially inside EOF */
6471 if (page_start + PAGE_CACHE_SIZE > size)
6472 zero_start = size & ~PAGE_CACHE_MASK;
6473 else
6474 zero_start = PAGE_CACHE_SIZE;
6476 if (zero_start != PAGE_CACHE_SIZE) {
6477 kaddr = kmap(page);
6478 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6479 flush_dcache_page(page);
6480 kunmap(page);
6482 ClearPageChecked(page);
6483 set_page_dirty(page);
6484 SetPageUptodate(page);
6486 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6487 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6489 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6491 out_unlock:
6492 if (!ret)
6493 return VM_FAULT_LOCKED;
6494 unlock_page(page);
6495 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6496 out:
6497 return ret;
6500 static int btrfs_truncate(struct inode *inode)
6502 struct btrfs_root *root = BTRFS_I(inode)->root;
6503 int ret;
6504 int err = 0;
6505 struct btrfs_trans_handle *trans;
6506 unsigned long nr;
6507 u64 mask = root->sectorsize - 1;
6509 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6510 if (ret)
6511 return ret;
6513 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6514 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6516 trans = btrfs_start_transaction(root, 5);
6517 if (IS_ERR(trans))
6518 return PTR_ERR(trans);
6520 btrfs_set_trans_block_group(trans, inode);
6522 ret = btrfs_orphan_add(trans, inode);
6523 if (ret) {
6524 btrfs_end_transaction(trans, root);
6525 return ret;
6528 nr = trans->blocks_used;
6529 btrfs_end_transaction(trans, root);
6530 btrfs_btree_balance_dirty(root, nr);
6532 /* Now start a transaction for the truncate */
6533 trans = btrfs_start_transaction(root, 0);
6534 if (IS_ERR(trans))
6535 return PTR_ERR(trans);
6536 btrfs_set_trans_block_group(trans, inode);
6537 trans->block_rsv = root->orphan_block_rsv;
6540 * setattr is responsible for setting the ordered_data_close flag,
6541 * but that is only tested during the last file release. That
6542 * could happen well after the next commit, leaving a great big
6543 * window where new writes may get lost if someone chooses to write
6544 * to this file after truncating to zero
6546 * The inode doesn't have any dirty data here, and so if we commit
6547 * this is a noop. If someone immediately starts writing to the inode
6548 * it is very likely we'll catch some of their writes in this
6549 * transaction, and the commit will find this file on the ordered
6550 * data list with good things to send down.
6552 * This is a best effort solution, there is still a window where
6553 * using truncate to replace the contents of the file will
6554 * end up with a zero length file after a crash.
6556 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6557 btrfs_add_ordered_operation(trans, root, inode);
6559 while (1) {
6560 if (!trans) {
6561 trans = btrfs_start_transaction(root, 0);
6562 if (IS_ERR(trans))
6563 return PTR_ERR(trans);
6564 btrfs_set_trans_block_group(trans, inode);
6565 trans->block_rsv = root->orphan_block_rsv;
6568 ret = btrfs_block_rsv_check(trans, root,
6569 root->orphan_block_rsv, 0, 5);
6570 if (ret == -EAGAIN) {
6571 ret = btrfs_commit_transaction(trans, root);
6572 if (ret)
6573 return ret;
6574 trans = NULL;
6575 continue;
6576 } else if (ret) {
6577 err = ret;
6578 break;
6581 ret = btrfs_truncate_inode_items(trans, root, inode,
6582 inode->i_size,
6583 BTRFS_EXTENT_DATA_KEY);
6584 if (ret != -EAGAIN) {
6585 err = ret;
6586 break;
6589 ret = btrfs_update_inode(trans, root, inode);
6590 if (ret) {
6591 err = ret;
6592 break;
6595 nr = trans->blocks_used;
6596 btrfs_end_transaction(trans, root);
6597 trans = NULL;
6598 btrfs_btree_balance_dirty(root, nr);
6601 if (ret == 0 && inode->i_nlink > 0) {
6602 ret = btrfs_orphan_del(trans, inode);
6603 if (ret)
6604 err = ret;
6605 } else if (ret && inode->i_nlink > 0) {
6607 * Failed to do the truncate, remove us from the in memory
6608 * orphan list.
6610 ret = btrfs_orphan_del(NULL, inode);
6613 ret = btrfs_update_inode(trans, root, inode);
6614 if (ret && !err)
6615 err = ret;
6617 nr = trans->blocks_used;
6618 ret = btrfs_end_transaction_throttle(trans, root);
6619 if (ret && !err)
6620 err = ret;
6621 btrfs_btree_balance_dirty(root, nr);
6623 return err;
6627 * create a new subvolume directory/inode (helper for the ioctl).
6629 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6630 struct btrfs_root *new_root,
6631 u64 new_dirid, u64 alloc_hint)
6633 struct inode *inode;
6634 int err;
6635 u64 index = 0;
6637 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6638 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
6639 if (IS_ERR(inode))
6640 return PTR_ERR(inode);
6641 inode->i_op = &btrfs_dir_inode_operations;
6642 inode->i_fop = &btrfs_dir_file_operations;
6644 inode->i_nlink = 1;
6645 btrfs_i_size_write(inode, 0);
6647 err = btrfs_update_inode(trans, new_root, inode);
6648 BUG_ON(err);
6650 iput(inode);
6651 return 0;
6654 /* helper function for file defrag and space balancing. This
6655 * forces readahead on a given range of bytes in an inode
6657 unsigned long btrfs_force_ra(struct address_space *mapping,
6658 struct file_ra_state *ra, struct file *file,
6659 pgoff_t offset, pgoff_t last_index)
6661 pgoff_t req_size = last_index - offset + 1;
6663 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6664 return offset + req_size;
6667 struct inode *btrfs_alloc_inode(struct super_block *sb)
6669 struct btrfs_inode *ei;
6670 struct inode *inode;
6672 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6673 if (!ei)
6674 return NULL;
6676 ei->root = NULL;
6677 ei->space_info = NULL;
6678 ei->generation = 0;
6679 ei->sequence = 0;
6680 ei->last_trans = 0;
6681 ei->last_sub_trans = 0;
6682 ei->logged_trans = 0;
6683 ei->delalloc_bytes = 0;
6684 ei->reserved_bytes = 0;
6685 ei->disk_i_size = 0;
6686 ei->flags = 0;
6687 ei->index_cnt = (u64)-1;
6688 ei->last_unlink_trans = 0;
6690 atomic_set(&ei->outstanding_extents, 0);
6691 atomic_set(&ei->reserved_extents, 0);
6693 ei->ordered_data_close = 0;
6694 ei->orphan_meta_reserved = 0;
6695 ei->dummy_inode = 0;
6696 ei->in_defrag = 0;
6697 ei->force_compress = BTRFS_COMPRESS_NONE;
6699 ei->delayed_node = NULL;
6701 inode = &ei->vfs_inode;
6702 extent_map_tree_init(&ei->extent_tree);
6703 extent_io_tree_init(&ei->io_tree, &inode->i_data);
6704 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
6705 mutex_init(&ei->log_mutex);
6706 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6707 INIT_LIST_HEAD(&ei->i_orphan);
6708 INIT_LIST_HEAD(&ei->delalloc_inodes);
6709 INIT_LIST_HEAD(&ei->ordered_operations);
6710 RB_CLEAR_NODE(&ei->rb_node);
6712 return inode;
6715 static void btrfs_i_callback(struct rcu_head *head)
6717 struct inode *inode = container_of(head, struct inode, i_rcu);
6718 INIT_LIST_HEAD(&inode->i_dentry);
6719 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6722 void btrfs_destroy_inode(struct inode *inode)
6724 struct btrfs_ordered_extent *ordered;
6725 struct btrfs_root *root = BTRFS_I(inode)->root;
6727 WARN_ON(!list_empty(&inode->i_dentry));
6728 WARN_ON(inode->i_data.nrpages);
6729 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6730 WARN_ON(atomic_read(&BTRFS_I(inode)->reserved_extents));
6733 * This can happen where we create an inode, but somebody else also
6734 * created the same inode and we need to destroy the one we already
6735 * created.
6737 if (!root)
6738 goto free;
6741 * Make sure we're properly removed from the ordered operation
6742 * lists.
6744 smp_mb();
6745 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6746 spin_lock(&root->fs_info->ordered_extent_lock);
6747 list_del_init(&BTRFS_I(inode)->ordered_operations);
6748 spin_unlock(&root->fs_info->ordered_extent_lock);
6751 if (root == root->fs_info->tree_root) {
6752 struct btrfs_block_group_cache *block_group;
6754 block_group = btrfs_lookup_block_group(root->fs_info,
6755 BTRFS_I(inode)->block_group);
6756 if (block_group && block_group->inode == inode) {
6757 spin_lock(&block_group->lock);
6758 block_group->inode = NULL;
6759 spin_unlock(&block_group->lock);
6760 btrfs_put_block_group(block_group);
6761 } else if (block_group) {
6762 btrfs_put_block_group(block_group);
6766 spin_lock(&root->orphan_lock);
6767 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6768 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6769 (unsigned long long)btrfs_ino(inode));
6770 list_del_init(&BTRFS_I(inode)->i_orphan);
6772 spin_unlock(&root->orphan_lock);
6774 while (1) {
6775 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6776 if (!ordered)
6777 break;
6778 else {
6779 printk(KERN_ERR "btrfs found ordered "
6780 "extent %llu %llu on inode cleanup\n",
6781 (unsigned long long)ordered->file_offset,
6782 (unsigned long long)ordered->len);
6783 btrfs_remove_ordered_extent(inode, ordered);
6784 btrfs_put_ordered_extent(ordered);
6785 btrfs_put_ordered_extent(ordered);
6788 inode_tree_del(inode);
6789 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6790 free:
6791 btrfs_remove_delayed_node(inode);
6792 call_rcu(&inode->i_rcu, btrfs_i_callback);
6795 int btrfs_drop_inode(struct inode *inode)
6797 struct btrfs_root *root = BTRFS_I(inode)->root;
6799 if (btrfs_root_refs(&root->root_item) == 0 &&
6800 !is_free_space_inode(root, inode))
6801 return 1;
6802 else
6803 return generic_drop_inode(inode);
6806 static void init_once(void *foo)
6808 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6810 inode_init_once(&ei->vfs_inode);
6813 void btrfs_destroy_cachep(void)
6815 if (btrfs_inode_cachep)
6816 kmem_cache_destroy(btrfs_inode_cachep);
6817 if (btrfs_trans_handle_cachep)
6818 kmem_cache_destroy(btrfs_trans_handle_cachep);
6819 if (btrfs_transaction_cachep)
6820 kmem_cache_destroy(btrfs_transaction_cachep);
6821 if (btrfs_path_cachep)
6822 kmem_cache_destroy(btrfs_path_cachep);
6823 if (btrfs_free_space_cachep)
6824 kmem_cache_destroy(btrfs_free_space_cachep);
6827 int btrfs_init_cachep(void)
6829 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6830 sizeof(struct btrfs_inode), 0,
6831 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6832 if (!btrfs_inode_cachep)
6833 goto fail;
6835 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6836 sizeof(struct btrfs_trans_handle), 0,
6837 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6838 if (!btrfs_trans_handle_cachep)
6839 goto fail;
6841 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6842 sizeof(struct btrfs_transaction), 0,
6843 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6844 if (!btrfs_transaction_cachep)
6845 goto fail;
6847 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6848 sizeof(struct btrfs_path), 0,
6849 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6850 if (!btrfs_path_cachep)
6851 goto fail;
6853 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6854 sizeof(struct btrfs_free_space), 0,
6855 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6856 if (!btrfs_free_space_cachep)
6857 goto fail;
6859 return 0;
6860 fail:
6861 btrfs_destroy_cachep();
6862 return -ENOMEM;
6865 static int btrfs_getattr(struct vfsmount *mnt,
6866 struct dentry *dentry, struct kstat *stat)
6868 struct inode *inode = dentry->d_inode;
6869 generic_fillattr(inode, stat);
6870 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6871 stat->blksize = PAGE_CACHE_SIZE;
6872 stat->blocks = (inode_get_bytes(inode) +
6873 BTRFS_I(inode)->delalloc_bytes) >> 9;
6874 return 0;
6878 * If a file is moved, it will inherit the cow and compression flags of the new
6879 * directory.
6881 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
6883 struct btrfs_inode *b_dir = BTRFS_I(dir);
6884 struct btrfs_inode *b_inode = BTRFS_I(inode);
6886 if (b_dir->flags & BTRFS_INODE_NODATACOW)
6887 b_inode->flags |= BTRFS_INODE_NODATACOW;
6888 else
6889 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
6891 if (b_dir->flags & BTRFS_INODE_COMPRESS)
6892 b_inode->flags |= BTRFS_INODE_COMPRESS;
6893 else
6894 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
6897 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6898 struct inode *new_dir, struct dentry *new_dentry)
6900 struct btrfs_trans_handle *trans;
6901 struct btrfs_root *root = BTRFS_I(old_dir)->root;
6902 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6903 struct inode *new_inode = new_dentry->d_inode;
6904 struct inode *old_inode = old_dentry->d_inode;
6905 struct timespec ctime = CURRENT_TIME;
6906 u64 index = 0;
6907 u64 root_objectid;
6908 int ret;
6909 u64 old_ino = btrfs_ino(old_inode);
6911 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6912 return -EPERM;
6914 /* we only allow rename subvolume link between subvolumes */
6915 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6916 return -EXDEV;
6918 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6919 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
6920 return -ENOTEMPTY;
6922 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6923 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6924 return -ENOTEMPTY;
6926 * we're using rename to replace one file with another.
6927 * and the replacement file is large. Start IO on it now so
6928 * we don't add too much work to the end of the transaction
6930 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6931 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6932 filemap_flush(old_inode->i_mapping);
6934 /* close the racy window with snapshot create/destroy ioctl */
6935 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
6936 down_read(&root->fs_info->subvol_sem);
6938 * We want to reserve the absolute worst case amount of items. So if
6939 * both inodes are subvols and we need to unlink them then that would
6940 * require 4 item modifications, but if they are both normal inodes it
6941 * would require 5 item modifications, so we'll assume their normal
6942 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6943 * should cover the worst case number of items we'll modify.
6945 trans = btrfs_start_transaction(root, 20);
6946 if (IS_ERR(trans)) {
6947 ret = PTR_ERR(trans);
6948 goto out_notrans;
6951 btrfs_set_trans_block_group(trans, new_dir);
6953 if (dest != root)
6954 btrfs_record_root_in_trans(trans, dest);
6956 ret = btrfs_set_inode_index(new_dir, &index);
6957 if (ret)
6958 goto out_fail;
6960 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6961 /* force full log commit if subvolume involved. */
6962 root->fs_info->last_trans_log_full_commit = trans->transid;
6963 } else {
6964 ret = btrfs_insert_inode_ref(trans, dest,
6965 new_dentry->d_name.name,
6966 new_dentry->d_name.len,
6967 old_ino,
6968 btrfs_ino(new_dir), index);
6969 if (ret)
6970 goto out_fail;
6972 * this is an ugly little race, but the rename is required
6973 * to make sure that if we crash, the inode is either at the
6974 * old name or the new one. pinning the log transaction lets
6975 * us make sure we don't allow a log commit to come in after
6976 * we unlink the name but before we add the new name back in.
6978 btrfs_pin_log_trans(root);
6981 * make sure the inode gets flushed if it is replacing
6982 * something.
6984 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
6985 btrfs_add_ordered_operation(trans, root, old_inode);
6987 old_dir->i_ctime = old_dir->i_mtime = ctime;
6988 new_dir->i_ctime = new_dir->i_mtime = ctime;
6989 old_inode->i_ctime = ctime;
6991 if (old_dentry->d_parent != new_dentry->d_parent)
6992 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6994 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6995 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6996 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6997 old_dentry->d_name.name,
6998 old_dentry->d_name.len);
6999 } else {
7000 ret = __btrfs_unlink_inode(trans, root, old_dir,
7001 old_dentry->d_inode,
7002 old_dentry->d_name.name,
7003 old_dentry->d_name.len);
7004 if (!ret)
7005 ret = btrfs_update_inode(trans, root, old_inode);
7007 BUG_ON(ret);
7009 if (new_inode) {
7010 new_inode->i_ctime = CURRENT_TIME;
7011 if (unlikely(btrfs_ino(new_inode) ==
7012 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7013 root_objectid = BTRFS_I(new_inode)->location.objectid;
7014 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7015 root_objectid,
7016 new_dentry->d_name.name,
7017 new_dentry->d_name.len);
7018 BUG_ON(new_inode->i_nlink == 0);
7019 } else {
7020 ret = btrfs_unlink_inode(trans, dest, new_dir,
7021 new_dentry->d_inode,
7022 new_dentry->d_name.name,
7023 new_dentry->d_name.len);
7025 BUG_ON(ret);
7026 if (new_inode->i_nlink == 0) {
7027 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7028 BUG_ON(ret);
7032 fixup_inode_flags(new_dir, old_inode);
7034 ret = btrfs_add_link(trans, new_dir, old_inode,
7035 new_dentry->d_name.name,
7036 new_dentry->d_name.len, 0, index);
7037 BUG_ON(ret);
7039 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7040 struct dentry *parent = dget_parent(new_dentry);
7041 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7042 dput(parent);
7043 btrfs_end_log_trans(root);
7045 out_fail:
7046 btrfs_end_transaction_throttle(trans, root);
7047 out_notrans:
7048 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7049 up_read(&root->fs_info->subvol_sem);
7051 return ret;
7055 * some fairly slow code that needs optimization. This walks the list
7056 * of all the inodes with pending delalloc and forces them to disk.
7058 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7060 struct list_head *head = &root->fs_info->delalloc_inodes;
7061 struct btrfs_inode *binode;
7062 struct inode *inode;
7064 if (root->fs_info->sb->s_flags & MS_RDONLY)
7065 return -EROFS;
7067 spin_lock(&root->fs_info->delalloc_lock);
7068 while (!list_empty(head)) {
7069 binode = list_entry(head->next, struct btrfs_inode,
7070 delalloc_inodes);
7071 inode = igrab(&binode->vfs_inode);
7072 if (!inode)
7073 list_del_init(&binode->delalloc_inodes);
7074 spin_unlock(&root->fs_info->delalloc_lock);
7075 if (inode) {
7076 filemap_flush(inode->i_mapping);
7077 if (delay_iput)
7078 btrfs_add_delayed_iput(inode);
7079 else
7080 iput(inode);
7082 cond_resched();
7083 spin_lock(&root->fs_info->delalloc_lock);
7085 spin_unlock(&root->fs_info->delalloc_lock);
7087 /* the filemap_flush will queue IO into the worker threads, but
7088 * we have to make sure the IO is actually started and that
7089 * ordered extents get created before we return
7091 atomic_inc(&root->fs_info->async_submit_draining);
7092 while (atomic_read(&root->fs_info->nr_async_submits) ||
7093 atomic_read(&root->fs_info->async_delalloc_pages)) {
7094 wait_event(root->fs_info->async_submit_wait,
7095 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7096 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7098 atomic_dec(&root->fs_info->async_submit_draining);
7099 return 0;
7102 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7103 const char *symname)
7105 struct btrfs_trans_handle *trans;
7106 struct btrfs_root *root = BTRFS_I(dir)->root;
7107 struct btrfs_path *path;
7108 struct btrfs_key key;
7109 struct inode *inode = NULL;
7110 int err;
7111 int drop_inode = 0;
7112 u64 objectid;
7113 u64 index = 0 ;
7114 int name_len;
7115 int datasize;
7116 unsigned long ptr;
7117 struct btrfs_file_extent_item *ei;
7118 struct extent_buffer *leaf;
7119 unsigned long nr = 0;
7121 name_len = strlen(symname) + 1;
7122 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7123 return -ENAMETOOLONG;
7126 * 2 items for inode item and ref
7127 * 2 items for dir items
7128 * 1 item for xattr if selinux is on
7130 trans = btrfs_start_transaction(root, 5);
7131 if (IS_ERR(trans))
7132 return PTR_ERR(trans);
7134 btrfs_set_trans_block_group(trans, dir);
7136 err = btrfs_find_free_ino(root, &objectid);
7137 if (err)
7138 goto out_unlock;
7140 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7141 dentry->d_name.len, btrfs_ino(dir), objectid,
7142 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
7143 &index);
7144 if (IS_ERR(inode)) {
7145 err = PTR_ERR(inode);
7146 goto out_unlock;
7149 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7150 if (err) {
7151 drop_inode = 1;
7152 goto out_unlock;
7155 btrfs_set_trans_block_group(trans, inode);
7156 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7157 if (err)
7158 drop_inode = 1;
7159 else {
7160 inode->i_mapping->a_ops = &btrfs_aops;
7161 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7162 inode->i_fop = &btrfs_file_operations;
7163 inode->i_op = &btrfs_file_inode_operations;
7164 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7166 btrfs_update_inode_block_group(trans, inode);
7167 btrfs_update_inode_block_group(trans, dir);
7168 if (drop_inode)
7169 goto out_unlock;
7171 path = btrfs_alloc_path();
7172 BUG_ON(!path);
7173 key.objectid = btrfs_ino(inode);
7174 key.offset = 0;
7175 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7176 datasize = btrfs_file_extent_calc_inline_size(name_len);
7177 err = btrfs_insert_empty_item(trans, root, path, &key,
7178 datasize);
7179 if (err) {
7180 drop_inode = 1;
7181 btrfs_free_path(path);
7182 goto out_unlock;
7184 leaf = path->nodes[0];
7185 ei = btrfs_item_ptr(leaf, path->slots[0],
7186 struct btrfs_file_extent_item);
7187 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7188 btrfs_set_file_extent_type(leaf, ei,
7189 BTRFS_FILE_EXTENT_INLINE);
7190 btrfs_set_file_extent_encryption(leaf, ei, 0);
7191 btrfs_set_file_extent_compression(leaf, ei, 0);
7192 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7193 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7195 ptr = btrfs_file_extent_inline_start(ei);
7196 write_extent_buffer(leaf, symname, ptr, name_len);
7197 btrfs_mark_buffer_dirty(leaf);
7198 btrfs_free_path(path);
7200 inode->i_op = &btrfs_symlink_inode_operations;
7201 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7202 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7203 inode_set_bytes(inode, name_len);
7204 btrfs_i_size_write(inode, name_len - 1);
7205 err = btrfs_update_inode(trans, root, inode);
7206 if (err)
7207 drop_inode = 1;
7209 out_unlock:
7210 nr = trans->blocks_used;
7211 btrfs_end_transaction_throttle(trans, root);
7212 if (drop_inode) {
7213 inode_dec_link_count(inode);
7214 iput(inode);
7216 btrfs_btree_balance_dirty(root, nr);
7217 return err;
7220 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7221 u64 start, u64 num_bytes, u64 min_size,
7222 loff_t actual_len, u64 *alloc_hint,
7223 struct btrfs_trans_handle *trans)
7225 struct btrfs_root *root = BTRFS_I(inode)->root;
7226 struct btrfs_key ins;
7227 u64 cur_offset = start;
7228 u64 i_size;
7229 int ret = 0;
7230 bool own_trans = true;
7232 if (trans)
7233 own_trans = false;
7234 while (num_bytes > 0) {
7235 if (own_trans) {
7236 trans = btrfs_start_transaction(root, 3);
7237 if (IS_ERR(trans)) {
7238 ret = PTR_ERR(trans);
7239 break;
7243 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7244 0, *alloc_hint, (u64)-1, &ins, 1);
7245 if (ret) {
7246 if (own_trans)
7247 btrfs_end_transaction(trans, root);
7248 break;
7251 ret = insert_reserved_file_extent(trans, inode,
7252 cur_offset, ins.objectid,
7253 ins.offset, ins.offset,
7254 ins.offset, 0, 0, 0,
7255 BTRFS_FILE_EXTENT_PREALLOC);
7256 BUG_ON(ret);
7257 btrfs_drop_extent_cache(inode, cur_offset,
7258 cur_offset + ins.offset -1, 0);
7260 num_bytes -= ins.offset;
7261 cur_offset += ins.offset;
7262 *alloc_hint = ins.objectid + ins.offset;
7264 inode->i_ctime = CURRENT_TIME;
7265 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7266 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7267 (actual_len > inode->i_size) &&
7268 (cur_offset > inode->i_size)) {
7269 if (cur_offset > actual_len)
7270 i_size = actual_len;
7271 else
7272 i_size = cur_offset;
7273 i_size_write(inode, i_size);
7274 btrfs_ordered_update_i_size(inode, i_size, NULL);
7277 ret = btrfs_update_inode(trans, root, inode);
7278 BUG_ON(ret);
7280 if (own_trans)
7281 btrfs_end_transaction(trans, root);
7283 return ret;
7286 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7287 u64 start, u64 num_bytes, u64 min_size,
7288 loff_t actual_len, u64 *alloc_hint)
7290 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7291 min_size, actual_len, alloc_hint,
7292 NULL);
7295 int btrfs_prealloc_file_range_trans(struct inode *inode,
7296 struct btrfs_trans_handle *trans, int mode,
7297 u64 start, u64 num_bytes, u64 min_size,
7298 loff_t actual_len, u64 *alloc_hint)
7300 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7301 min_size, actual_len, alloc_hint, trans);
7304 static int btrfs_set_page_dirty(struct page *page)
7306 return __set_page_dirty_nobuffers(page);
7309 static int btrfs_permission(struct inode *inode, int mask, unsigned int flags)
7311 struct btrfs_root *root = BTRFS_I(inode)->root;
7313 if (btrfs_root_readonly(root) && (mask & MAY_WRITE))
7314 return -EROFS;
7315 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
7316 return -EACCES;
7317 return generic_permission(inode, mask, flags, btrfs_check_acl);
7320 static const struct inode_operations btrfs_dir_inode_operations = {
7321 .getattr = btrfs_getattr,
7322 .lookup = btrfs_lookup,
7323 .create = btrfs_create,
7324 .unlink = btrfs_unlink,
7325 .link = btrfs_link,
7326 .mkdir = btrfs_mkdir,
7327 .rmdir = btrfs_rmdir,
7328 .rename = btrfs_rename,
7329 .symlink = btrfs_symlink,
7330 .setattr = btrfs_setattr,
7331 .mknod = btrfs_mknod,
7332 .setxattr = btrfs_setxattr,
7333 .getxattr = btrfs_getxattr,
7334 .listxattr = btrfs_listxattr,
7335 .removexattr = btrfs_removexattr,
7336 .permission = btrfs_permission,
7338 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7339 .lookup = btrfs_lookup,
7340 .permission = btrfs_permission,
7343 static const struct file_operations btrfs_dir_file_operations = {
7344 .llseek = generic_file_llseek,
7345 .read = generic_read_dir,
7346 .readdir = btrfs_real_readdir,
7347 .unlocked_ioctl = btrfs_ioctl,
7348 #ifdef CONFIG_COMPAT
7349 .compat_ioctl = btrfs_ioctl,
7350 #endif
7351 .release = btrfs_release_file,
7352 .fsync = btrfs_sync_file,
7355 static struct extent_io_ops btrfs_extent_io_ops = {
7356 .fill_delalloc = run_delalloc_range,
7357 .submit_bio_hook = btrfs_submit_bio_hook,
7358 .merge_bio_hook = btrfs_merge_bio_hook,
7359 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7360 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7361 .writepage_start_hook = btrfs_writepage_start_hook,
7362 .readpage_io_failed_hook = btrfs_io_failed_hook,
7363 .set_bit_hook = btrfs_set_bit_hook,
7364 .clear_bit_hook = btrfs_clear_bit_hook,
7365 .merge_extent_hook = btrfs_merge_extent_hook,
7366 .split_extent_hook = btrfs_split_extent_hook,
7370 * btrfs doesn't support the bmap operation because swapfiles
7371 * use bmap to make a mapping of extents in the file. They assume
7372 * these extents won't change over the life of the file and they
7373 * use the bmap result to do IO directly to the drive.
7375 * the btrfs bmap call would return logical addresses that aren't
7376 * suitable for IO and they also will change frequently as COW
7377 * operations happen. So, swapfile + btrfs == corruption.
7379 * For now we're avoiding this by dropping bmap.
7381 static const struct address_space_operations btrfs_aops = {
7382 .readpage = btrfs_readpage,
7383 .writepage = btrfs_writepage,
7384 .writepages = btrfs_writepages,
7385 .readpages = btrfs_readpages,
7386 .direct_IO = btrfs_direct_IO,
7387 .invalidatepage = btrfs_invalidatepage,
7388 .releasepage = btrfs_releasepage,
7389 .set_page_dirty = btrfs_set_page_dirty,
7390 .error_remove_page = generic_error_remove_page,
7393 static const struct address_space_operations btrfs_symlink_aops = {
7394 .readpage = btrfs_readpage,
7395 .writepage = btrfs_writepage,
7396 .invalidatepage = btrfs_invalidatepage,
7397 .releasepage = btrfs_releasepage,
7400 static const struct inode_operations btrfs_file_inode_operations = {
7401 .getattr = btrfs_getattr,
7402 .setattr = btrfs_setattr,
7403 .setxattr = btrfs_setxattr,
7404 .getxattr = btrfs_getxattr,
7405 .listxattr = btrfs_listxattr,
7406 .removexattr = btrfs_removexattr,
7407 .permission = btrfs_permission,
7408 .fiemap = btrfs_fiemap,
7410 static const struct inode_operations btrfs_special_inode_operations = {
7411 .getattr = btrfs_getattr,
7412 .setattr = btrfs_setattr,
7413 .permission = btrfs_permission,
7414 .setxattr = btrfs_setxattr,
7415 .getxattr = btrfs_getxattr,
7416 .listxattr = btrfs_listxattr,
7417 .removexattr = btrfs_removexattr,
7419 static const struct inode_operations btrfs_symlink_inode_operations = {
7420 .readlink = generic_readlink,
7421 .follow_link = page_follow_link_light,
7422 .put_link = page_put_link,
7423 .getattr = btrfs_getattr,
7424 .permission = btrfs_permission,
7425 .setxattr = btrfs_setxattr,
7426 .getxattr = btrfs_getxattr,
7427 .listxattr = btrfs_listxattr,
7428 .removexattr = btrfs_removexattr,
7431 const struct dentry_operations btrfs_dentry_operations = {
7432 .d_delete = btrfs_dentry_delete,