RT-AC56 3.0.0.4.374.37 core
[tomato.git] / release / src-rt-6.x.4708 / linux / linux-2.6.36 / fs / btrfs / inode.c
blob9b8e10d057a6e22086af4f501256b8d874fa29f5
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 "compat.h"
41 #include "ctree.h"
42 #include "disk-io.h"
43 #include "transaction.h"
44 #include "btrfs_inode.h"
45 #include "ioctl.h"
46 #include "print-tree.h"
47 #include "volumes.h"
48 #include "ordered-data.h"
49 #include "xattr.h"
50 #include "tree-log.h"
51 #include "compression.h"
52 #include "locking.h"
54 struct btrfs_iget_args {
55 u64 ino;
56 struct btrfs_root *root;
59 static const struct inode_operations btrfs_dir_inode_operations;
60 static const struct inode_operations btrfs_symlink_inode_operations;
61 static const struct inode_operations btrfs_dir_ro_inode_operations;
62 static const struct inode_operations btrfs_special_inode_operations;
63 static const struct inode_operations btrfs_file_inode_operations;
64 static const struct address_space_operations btrfs_aops;
65 static const struct address_space_operations btrfs_symlink_aops;
66 static const struct file_operations btrfs_dir_file_operations;
67 static struct extent_io_ops btrfs_extent_io_ops;
69 static struct kmem_cache *btrfs_inode_cachep;
70 struct kmem_cache *btrfs_trans_handle_cachep;
71 struct kmem_cache *btrfs_transaction_cachep;
72 struct kmem_cache *btrfs_path_cachep;
74 #define S_SHIFT 12
75 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
76 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
77 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
78 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
79 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
80 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
81 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
82 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
85 static void btrfs_truncate(struct inode *inode);
86 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
87 static noinline int cow_file_range(struct inode *inode,
88 struct page *locked_page,
89 u64 start, u64 end, int *page_started,
90 unsigned long *nr_written, int unlock);
92 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
93 struct inode *inode, struct inode *dir)
95 int err;
97 err = btrfs_init_acl(trans, inode, dir);
98 if (!err)
99 err = btrfs_xattr_security_init(trans, inode, dir);
100 return err;
104 * this does all the hard work for inserting an inline extent into
105 * the btree. The caller should have done a btrfs_drop_extents so that
106 * no overlapping inline items exist in the btree
108 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
109 struct btrfs_root *root, struct inode *inode,
110 u64 start, size_t size, size_t compressed_size,
111 struct page **compressed_pages)
113 struct btrfs_key key;
114 struct btrfs_path *path;
115 struct extent_buffer *leaf;
116 struct page *page = NULL;
117 char *kaddr;
118 unsigned long ptr;
119 struct btrfs_file_extent_item *ei;
120 int err = 0;
121 int ret;
122 size_t cur_size = size;
123 size_t datasize;
124 unsigned long offset;
125 int use_compress = 0;
127 if (compressed_size && compressed_pages) {
128 use_compress = 1;
129 cur_size = compressed_size;
132 path = btrfs_alloc_path();
133 if (!path)
134 return -ENOMEM;
136 path->leave_spinning = 1;
137 btrfs_set_trans_block_group(trans, inode);
139 key.objectid = inode->i_ino;
140 key.offset = start;
141 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
142 datasize = btrfs_file_extent_calc_inline_size(cur_size);
144 inode_add_bytes(inode, size);
145 ret = btrfs_insert_empty_item(trans, root, path, &key,
146 datasize);
147 BUG_ON(ret);
148 if (ret) {
149 err = ret;
150 goto fail;
152 leaf = path->nodes[0];
153 ei = btrfs_item_ptr(leaf, path->slots[0],
154 struct btrfs_file_extent_item);
155 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
156 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
157 btrfs_set_file_extent_encryption(leaf, ei, 0);
158 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
159 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
160 ptr = btrfs_file_extent_inline_start(ei);
162 if (use_compress) {
163 struct page *cpage;
164 int i = 0;
165 while (compressed_size > 0) {
166 cpage = compressed_pages[i];
167 cur_size = min_t(unsigned long, compressed_size,
168 PAGE_CACHE_SIZE);
170 kaddr = kmap_atomic(cpage, KM_USER0);
171 write_extent_buffer(leaf, kaddr, ptr, cur_size);
172 kunmap_atomic(kaddr, KM_USER0);
174 i++;
175 ptr += cur_size;
176 compressed_size -= cur_size;
178 btrfs_set_file_extent_compression(leaf, ei,
179 BTRFS_COMPRESS_ZLIB);
180 } else {
181 page = find_get_page(inode->i_mapping,
182 start >> PAGE_CACHE_SHIFT);
183 btrfs_set_file_extent_compression(leaf, ei, 0);
184 kaddr = kmap_atomic(page, KM_USER0);
185 offset = start & (PAGE_CACHE_SIZE - 1);
186 write_extent_buffer(leaf, kaddr + offset, ptr, size);
187 kunmap_atomic(kaddr, KM_USER0);
188 page_cache_release(page);
190 btrfs_mark_buffer_dirty(leaf);
191 btrfs_free_path(path);
194 * we're an inline extent, so nobody can
195 * extend the file past i_size without locking
196 * a page we already have locked.
198 * We must do any isize and inode updates
199 * before we unlock the pages. Otherwise we
200 * could end up racing with unlink.
202 BTRFS_I(inode)->disk_i_size = inode->i_size;
203 btrfs_update_inode(trans, root, inode);
205 return 0;
206 fail:
207 btrfs_free_path(path);
208 return err;
213 * conditionally insert an inline extent into the file. This
214 * does the checks required to make sure the data is small enough
215 * to fit as an inline extent.
217 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
218 struct btrfs_root *root,
219 struct inode *inode, u64 start, u64 end,
220 size_t compressed_size,
221 struct page **compressed_pages)
223 u64 isize = i_size_read(inode);
224 u64 actual_end = min(end + 1, isize);
225 u64 inline_len = actual_end - start;
226 u64 aligned_end = (end + root->sectorsize - 1) &
227 ~((u64)root->sectorsize - 1);
228 u64 hint_byte;
229 u64 data_len = inline_len;
230 int ret;
232 if (compressed_size)
233 data_len = compressed_size;
235 if (start > 0 ||
236 actual_end >= PAGE_CACHE_SIZE ||
237 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
238 (!compressed_size &&
239 (actual_end & (root->sectorsize - 1)) == 0) ||
240 end + 1 < isize ||
241 data_len > root->fs_info->max_inline) {
242 return 1;
245 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
246 &hint_byte, 1);
247 BUG_ON(ret);
249 if (isize > actual_end)
250 inline_len = min_t(u64, isize, actual_end);
251 ret = insert_inline_extent(trans, root, inode, start,
252 inline_len, compressed_size,
253 compressed_pages);
254 BUG_ON(ret);
255 btrfs_delalloc_release_metadata(inode, end + 1 - start);
256 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
257 return 0;
260 struct async_extent {
261 u64 start;
262 u64 ram_size;
263 u64 compressed_size;
264 struct page **pages;
265 unsigned long nr_pages;
266 struct list_head list;
269 struct async_cow {
270 struct inode *inode;
271 struct btrfs_root *root;
272 struct page *locked_page;
273 u64 start;
274 u64 end;
275 struct list_head extents;
276 struct btrfs_work work;
279 static noinline int add_async_extent(struct async_cow *cow,
280 u64 start, u64 ram_size,
281 u64 compressed_size,
282 struct page **pages,
283 unsigned long nr_pages)
285 struct async_extent *async_extent;
287 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
288 async_extent->start = start;
289 async_extent->ram_size = ram_size;
290 async_extent->compressed_size = compressed_size;
291 async_extent->pages = pages;
292 async_extent->nr_pages = nr_pages;
293 list_add_tail(&async_extent->list, &cow->extents);
294 return 0;
298 * we create compressed extents in two phases. The first
299 * phase compresses a range of pages that have already been
300 * locked (both pages and state bits are locked).
302 * This is done inside an ordered work queue, and the compression
303 * is spread across many cpus. The actual IO submission is step
304 * two, and the ordered work queue takes care of making sure that
305 * happens in the same order things were put onto the queue by
306 * writepages and friends.
308 * If this code finds it can't get good compression, it puts an
309 * entry onto the work queue to write the uncompressed bytes. This
310 * makes sure that both compressed inodes and uncompressed inodes
311 * are written in the same order that pdflush sent them down.
313 static noinline int compress_file_range(struct inode *inode,
314 struct page *locked_page,
315 u64 start, u64 end,
316 struct async_cow *async_cow,
317 int *num_added)
319 struct btrfs_root *root = BTRFS_I(inode)->root;
320 struct btrfs_trans_handle *trans;
321 u64 num_bytes;
322 u64 orig_start;
323 u64 disk_num_bytes;
324 u64 blocksize = root->sectorsize;
325 u64 actual_end;
326 u64 isize = i_size_read(inode);
327 int ret = 0;
328 struct page **pages = NULL;
329 unsigned long nr_pages;
330 unsigned long nr_pages_ret = 0;
331 unsigned long total_compressed = 0;
332 unsigned long total_in = 0;
333 unsigned long max_compressed = 128 * 1024;
334 unsigned long max_uncompressed = 128 * 1024;
335 int i;
336 int will_compress;
338 orig_start = start;
340 actual_end = min_t(u64, isize, end + 1);
341 again:
342 will_compress = 0;
343 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
344 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
347 * we don't want to send crud past the end of i_size through
348 * compression, that's just a waste of CPU time. So, if the
349 * end of the file is before the start of our current
350 * requested range of bytes, we bail out to the uncompressed
351 * cleanup code that can deal with all of this.
353 * It isn't really the fastest way to fix things, but this is a
354 * very uncommon corner.
356 if (actual_end <= start)
357 goto cleanup_and_bail_uncompressed;
359 total_compressed = actual_end - start;
361 /* we want to make sure that amount of ram required to uncompress
362 * an extent is reasonable, so we limit the total size in ram
363 * of a compressed extent to 128k. This is a crucial number
364 * because it also controls how easily we can spread reads across
365 * cpus for decompression.
367 * We also want to make sure the amount of IO required to do
368 * a random read is reasonably small, so we limit the size of
369 * a compressed extent to 128k.
371 total_compressed = min(total_compressed, max_uncompressed);
372 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
373 num_bytes = max(blocksize, num_bytes);
374 disk_num_bytes = num_bytes;
375 total_in = 0;
376 ret = 0;
379 * we do compression for mount -o compress and when the
380 * inode has not been flagged as nocompress. This flag can
381 * change at any time if we discover bad compression ratios.
383 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
384 (btrfs_test_opt(root, COMPRESS) ||
385 (BTRFS_I(inode)->force_compress))) {
386 WARN_ON(pages);
387 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
389 ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
390 total_compressed, pages,
391 nr_pages, &nr_pages_ret,
392 &total_in,
393 &total_compressed,
394 max_compressed);
396 if (!ret) {
397 unsigned long offset = total_compressed &
398 (PAGE_CACHE_SIZE - 1);
399 struct page *page = pages[nr_pages_ret - 1];
400 char *kaddr;
402 /* zero the tail end of the last page, we might be
403 * sending it down to disk
405 if (offset) {
406 kaddr = kmap_atomic(page, KM_USER0);
407 memset(kaddr + offset, 0,
408 PAGE_CACHE_SIZE - offset);
409 kunmap_atomic(kaddr, KM_USER0);
411 will_compress = 1;
414 if (start == 0) {
415 trans = btrfs_join_transaction(root, 1);
416 BUG_ON(!trans);
417 btrfs_set_trans_block_group(trans, inode);
418 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
420 /* lets try to make an inline extent */
421 if (ret || total_in < (actual_end - start)) {
422 /* we didn't compress the entire range, try
423 * to make an uncompressed inline extent.
425 ret = cow_file_range_inline(trans, root, inode,
426 start, end, 0, NULL);
427 } else {
428 /* try making a compressed inline extent */
429 ret = cow_file_range_inline(trans, root, inode,
430 start, end,
431 total_compressed, pages);
433 if (ret == 0) {
435 * inline extent creation worked, we don't need
436 * to create any more async work items. Unlock
437 * and free up our temp pages.
439 extent_clear_unlock_delalloc(inode,
440 &BTRFS_I(inode)->io_tree,
441 start, end, NULL,
442 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
443 EXTENT_CLEAR_DELALLOC |
444 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
446 btrfs_end_transaction(trans, root);
447 goto free_pages_out;
449 btrfs_end_transaction(trans, root);
452 if (will_compress) {
454 * we aren't doing an inline extent round the compressed size
455 * up to a block size boundary so the allocator does sane
456 * things
458 total_compressed = (total_compressed + blocksize - 1) &
459 ~(blocksize - 1);
462 * one last check to make sure the compression is really a
463 * win, compare the page count read with the blocks on disk
465 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
466 ~(PAGE_CACHE_SIZE - 1);
467 if (total_compressed >= total_in) {
468 will_compress = 0;
469 } else {
470 disk_num_bytes = total_compressed;
471 num_bytes = total_in;
474 if (!will_compress && pages) {
476 * the compression code ran but failed to make things smaller,
477 * free any pages it allocated and our page pointer array
479 for (i = 0; i < nr_pages_ret; i++) {
480 WARN_ON(pages[i]->mapping);
481 page_cache_release(pages[i]);
483 kfree(pages);
484 pages = NULL;
485 total_compressed = 0;
486 nr_pages_ret = 0;
488 /* flag the file so we don't compress in the future */
489 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
490 !(BTRFS_I(inode)->force_compress)) {
491 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
494 if (will_compress) {
495 *num_added += 1;
497 /* the async work queues will take care of doing actual
498 * allocation on disk for these compressed pages,
499 * and will submit them to the elevator.
501 add_async_extent(async_cow, start, num_bytes,
502 total_compressed, pages, nr_pages_ret);
504 if (start + num_bytes < end && start + num_bytes < actual_end) {
505 start += num_bytes;
506 pages = NULL;
507 cond_resched();
508 goto again;
510 } else {
511 cleanup_and_bail_uncompressed:
513 * No compression, but we still need to write the pages in
514 * the file we've been given so far. redirty the locked
515 * page if it corresponds to our extent and set things up
516 * for the async work queue to run cow_file_range to do
517 * the normal delalloc dance
519 if (page_offset(locked_page) >= start &&
520 page_offset(locked_page) <= end) {
521 __set_page_dirty_nobuffers(locked_page);
522 /* unlocked later on in the async handlers */
524 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0);
525 *num_added += 1;
528 out:
529 return 0;
531 free_pages_out:
532 for (i = 0; i < nr_pages_ret; i++) {
533 WARN_ON(pages[i]->mapping);
534 page_cache_release(pages[i]);
536 kfree(pages);
538 goto out;
542 * phase two of compressed writeback. This is the ordered portion
543 * of the code, which only gets called in the order the work was
544 * queued. We walk all the async extents created by compress_file_range
545 * and send them down to the disk.
547 static noinline int submit_compressed_extents(struct inode *inode,
548 struct async_cow *async_cow)
550 struct async_extent *async_extent;
551 u64 alloc_hint = 0;
552 struct btrfs_trans_handle *trans;
553 struct btrfs_key ins;
554 struct extent_map *em;
555 struct btrfs_root *root = BTRFS_I(inode)->root;
556 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
557 struct extent_io_tree *io_tree;
558 int ret = 0;
560 if (list_empty(&async_cow->extents))
561 return 0;
564 while (!list_empty(&async_cow->extents)) {
565 async_extent = list_entry(async_cow->extents.next,
566 struct async_extent, list);
567 list_del(&async_extent->list);
569 io_tree = &BTRFS_I(inode)->io_tree;
571 retry:
572 /* did the compression code fall back to uncompressed IO? */
573 if (!async_extent->pages) {
574 int page_started = 0;
575 unsigned long nr_written = 0;
577 lock_extent(io_tree, async_extent->start,
578 async_extent->start +
579 async_extent->ram_size - 1, GFP_NOFS);
581 /* allocate blocks */
582 ret = cow_file_range(inode, async_cow->locked_page,
583 async_extent->start,
584 async_extent->start +
585 async_extent->ram_size - 1,
586 &page_started, &nr_written, 0);
589 * if page_started, cow_file_range inserted an
590 * inline extent and took care of all the unlocking
591 * and IO for us. Otherwise, we need to submit
592 * all those pages down to the drive.
594 if (!page_started && !ret)
595 extent_write_locked_range(io_tree,
596 inode, async_extent->start,
597 async_extent->start +
598 async_extent->ram_size - 1,
599 btrfs_get_extent,
600 WB_SYNC_ALL);
601 kfree(async_extent);
602 cond_resched();
603 continue;
606 lock_extent(io_tree, async_extent->start,
607 async_extent->start + async_extent->ram_size - 1,
608 GFP_NOFS);
610 trans = btrfs_join_transaction(root, 1);
611 ret = btrfs_reserve_extent(trans, root,
612 async_extent->compressed_size,
613 async_extent->compressed_size,
614 0, alloc_hint,
615 (u64)-1, &ins, 1);
616 btrfs_end_transaction(trans, root);
618 if (ret) {
619 int i;
620 for (i = 0; i < async_extent->nr_pages; i++) {
621 WARN_ON(async_extent->pages[i]->mapping);
622 page_cache_release(async_extent->pages[i]);
624 kfree(async_extent->pages);
625 async_extent->nr_pages = 0;
626 async_extent->pages = NULL;
627 unlock_extent(io_tree, async_extent->start,
628 async_extent->start +
629 async_extent->ram_size - 1, GFP_NOFS);
630 goto retry;
634 * here we're doing allocation and writeback of the
635 * compressed pages
637 btrfs_drop_extent_cache(inode, async_extent->start,
638 async_extent->start +
639 async_extent->ram_size - 1, 0);
641 em = alloc_extent_map(GFP_NOFS);
642 em->start = async_extent->start;
643 em->len = async_extent->ram_size;
644 em->orig_start = em->start;
646 em->block_start = ins.objectid;
647 em->block_len = ins.offset;
648 em->bdev = root->fs_info->fs_devices->latest_bdev;
649 set_bit(EXTENT_FLAG_PINNED, &em->flags);
650 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
652 while (1) {
653 write_lock(&em_tree->lock);
654 ret = add_extent_mapping(em_tree, em);
655 write_unlock(&em_tree->lock);
656 if (ret != -EEXIST) {
657 free_extent_map(em);
658 break;
660 btrfs_drop_extent_cache(inode, async_extent->start,
661 async_extent->start +
662 async_extent->ram_size - 1, 0);
665 ret = btrfs_add_ordered_extent(inode, async_extent->start,
666 ins.objectid,
667 async_extent->ram_size,
668 ins.offset,
669 BTRFS_ORDERED_COMPRESSED);
670 BUG_ON(ret);
673 * clear dirty, set writeback and unlock the pages.
675 extent_clear_unlock_delalloc(inode,
676 &BTRFS_I(inode)->io_tree,
677 async_extent->start,
678 async_extent->start +
679 async_extent->ram_size - 1,
680 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
681 EXTENT_CLEAR_UNLOCK |
682 EXTENT_CLEAR_DELALLOC |
683 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
685 ret = btrfs_submit_compressed_write(inode,
686 async_extent->start,
687 async_extent->ram_size,
688 ins.objectid,
689 ins.offset, async_extent->pages,
690 async_extent->nr_pages);
692 BUG_ON(ret);
693 alloc_hint = ins.objectid + ins.offset;
694 kfree(async_extent);
695 cond_resched();
698 return 0;
701 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
702 u64 num_bytes)
704 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
705 struct extent_map *em;
706 u64 alloc_hint = 0;
708 read_lock(&em_tree->lock);
709 em = search_extent_mapping(em_tree, start, num_bytes);
710 if (em) {
712 * if block start isn't an actual block number then find the
713 * first block in this inode and use that as a hint. If that
714 * block is also bogus then just don't worry about it.
716 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
717 free_extent_map(em);
718 em = search_extent_mapping(em_tree, 0, 0);
719 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
720 alloc_hint = em->block_start;
721 if (em)
722 free_extent_map(em);
723 } else {
724 alloc_hint = em->block_start;
725 free_extent_map(em);
728 read_unlock(&em_tree->lock);
730 return alloc_hint;
734 * when extent_io.c finds a delayed allocation range in the file,
735 * the call backs end up in this code. The basic idea is to
736 * allocate extents on disk for the range, and create ordered data structs
737 * in ram to track those extents.
739 * locked_page is the page that writepage had locked already. We use
740 * it to make sure we don't do extra locks or unlocks.
742 * *page_started is set to one if we unlock locked_page and do everything
743 * required to start IO on it. It may be clean and already done with
744 * IO when we return.
746 static noinline int cow_file_range(struct inode *inode,
747 struct page *locked_page,
748 u64 start, u64 end, int *page_started,
749 unsigned long *nr_written,
750 int unlock)
752 struct btrfs_root *root = BTRFS_I(inode)->root;
753 struct btrfs_trans_handle *trans;
754 u64 alloc_hint = 0;
755 u64 num_bytes;
756 unsigned long ram_size;
757 u64 disk_num_bytes;
758 u64 cur_alloc_size;
759 u64 blocksize = root->sectorsize;
760 u64 actual_end;
761 u64 isize = i_size_read(inode);
762 struct btrfs_key ins;
763 struct extent_map *em;
764 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
765 int ret = 0;
767 trans = btrfs_join_transaction(root, 1);
768 BUG_ON(!trans);
769 btrfs_set_trans_block_group(trans, inode);
770 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
772 actual_end = min_t(u64, isize, end + 1);
774 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
775 num_bytes = max(blocksize, num_bytes);
776 disk_num_bytes = num_bytes;
777 ret = 0;
779 if (start == 0) {
780 /* lets try to make an inline extent */
781 ret = cow_file_range_inline(trans, root, inode,
782 start, end, 0, NULL);
783 if (ret == 0) {
784 extent_clear_unlock_delalloc(inode,
785 &BTRFS_I(inode)->io_tree,
786 start, end, NULL,
787 EXTENT_CLEAR_UNLOCK_PAGE |
788 EXTENT_CLEAR_UNLOCK |
789 EXTENT_CLEAR_DELALLOC |
790 EXTENT_CLEAR_DIRTY |
791 EXTENT_SET_WRITEBACK |
792 EXTENT_END_WRITEBACK);
794 *nr_written = *nr_written +
795 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
796 *page_started = 1;
797 ret = 0;
798 goto out;
802 BUG_ON(disk_num_bytes >
803 btrfs_super_total_bytes(&root->fs_info->super_copy));
805 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
806 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
808 while (disk_num_bytes > 0) {
809 unsigned long op;
811 cur_alloc_size = disk_num_bytes;
812 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
813 root->sectorsize, 0, alloc_hint,
814 (u64)-1, &ins, 1);
815 BUG_ON(ret);
817 em = alloc_extent_map(GFP_NOFS);
818 em->start = start;
819 em->orig_start = em->start;
820 ram_size = ins.offset;
821 em->len = ins.offset;
823 em->block_start = ins.objectid;
824 em->block_len = ins.offset;
825 em->bdev = root->fs_info->fs_devices->latest_bdev;
826 set_bit(EXTENT_FLAG_PINNED, &em->flags);
828 while (1) {
829 write_lock(&em_tree->lock);
830 ret = add_extent_mapping(em_tree, em);
831 write_unlock(&em_tree->lock);
832 if (ret != -EEXIST) {
833 free_extent_map(em);
834 break;
836 btrfs_drop_extent_cache(inode, start,
837 start + ram_size - 1, 0);
840 cur_alloc_size = ins.offset;
841 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
842 ram_size, cur_alloc_size, 0);
843 BUG_ON(ret);
845 if (root->root_key.objectid ==
846 BTRFS_DATA_RELOC_TREE_OBJECTID) {
847 ret = btrfs_reloc_clone_csums(inode, start,
848 cur_alloc_size);
849 BUG_ON(ret);
852 if (disk_num_bytes < cur_alloc_size)
853 break;
855 /* we're not doing compressed IO, don't unlock the first
856 * page (which the caller expects to stay locked), don't
857 * clear any dirty bits and don't set any writeback bits
859 * Do set the Private2 bit so we know this page was properly
860 * setup for writepage
862 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
863 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
864 EXTENT_SET_PRIVATE2;
866 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
867 start, start + ram_size - 1,
868 locked_page, op);
869 disk_num_bytes -= cur_alloc_size;
870 num_bytes -= cur_alloc_size;
871 alloc_hint = ins.objectid + ins.offset;
872 start += cur_alloc_size;
874 out:
875 ret = 0;
876 btrfs_end_transaction(trans, root);
878 return ret;
882 * work queue call back to started compression on a file and pages
884 static noinline void async_cow_start(struct btrfs_work *work)
886 struct async_cow *async_cow;
887 int num_added = 0;
888 async_cow = container_of(work, struct async_cow, work);
890 compress_file_range(async_cow->inode, async_cow->locked_page,
891 async_cow->start, async_cow->end, async_cow,
892 &num_added);
893 if (num_added == 0)
894 async_cow->inode = NULL;
898 * work queue call back to submit previously compressed pages
900 static noinline void async_cow_submit(struct btrfs_work *work)
902 struct async_cow *async_cow;
903 struct btrfs_root *root;
904 unsigned long nr_pages;
906 async_cow = container_of(work, struct async_cow, work);
908 root = async_cow->root;
909 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
910 PAGE_CACHE_SHIFT;
912 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
914 if (atomic_read(&root->fs_info->async_delalloc_pages) <
915 5 * 1042 * 1024 &&
916 waitqueue_active(&root->fs_info->async_submit_wait))
917 wake_up(&root->fs_info->async_submit_wait);
919 if (async_cow->inode)
920 submit_compressed_extents(async_cow->inode, async_cow);
923 static noinline void async_cow_free(struct btrfs_work *work)
925 struct async_cow *async_cow;
926 async_cow = container_of(work, struct async_cow, work);
927 kfree(async_cow);
930 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
931 u64 start, u64 end, int *page_started,
932 unsigned long *nr_written)
934 struct async_cow *async_cow;
935 struct btrfs_root *root = BTRFS_I(inode)->root;
936 unsigned long nr_pages;
937 u64 cur_end;
938 int limit = 10 * 1024 * 1042;
940 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
941 1, 0, NULL, GFP_NOFS);
942 while (start < end) {
943 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
944 async_cow->inode = inode;
945 async_cow->root = root;
946 async_cow->locked_page = locked_page;
947 async_cow->start = start;
949 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
950 cur_end = end;
951 else
952 cur_end = min(end, start + 512 * 1024 - 1);
954 async_cow->end = cur_end;
955 INIT_LIST_HEAD(&async_cow->extents);
957 async_cow->work.func = async_cow_start;
958 async_cow->work.ordered_func = async_cow_submit;
959 async_cow->work.ordered_free = async_cow_free;
960 async_cow->work.flags = 0;
962 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
963 PAGE_CACHE_SHIFT;
964 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
966 btrfs_queue_worker(&root->fs_info->delalloc_workers,
967 &async_cow->work);
969 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
970 wait_event(root->fs_info->async_submit_wait,
971 (atomic_read(&root->fs_info->async_delalloc_pages) <
972 limit));
975 while (atomic_read(&root->fs_info->async_submit_draining) &&
976 atomic_read(&root->fs_info->async_delalloc_pages)) {
977 wait_event(root->fs_info->async_submit_wait,
978 (atomic_read(&root->fs_info->async_delalloc_pages) ==
979 0));
982 *nr_written += nr_pages;
983 start = cur_end + 1;
985 *page_started = 1;
986 return 0;
989 static noinline int csum_exist_in_range(struct btrfs_root *root,
990 u64 bytenr, u64 num_bytes)
992 int ret;
993 struct btrfs_ordered_sum *sums;
994 LIST_HEAD(list);
996 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
997 bytenr + num_bytes - 1, &list);
998 if (ret == 0 && list_empty(&list))
999 return 0;
1001 while (!list_empty(&list)) {
1002 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1003 list_del(&sums->list);
1004 kfree(sums);
1006 return 1;
1010 * when nowcow writeback call back. This checks for snapshots or COW copies
1011 * of the extents that exist in the file, and COWs the file as required.
1013 * If no cow copies or snapshots exist, we write directly to the existing
1014 * blocks on disk
1016 static noinline int run_delalloc_nocow(struct inode *inode,
1017 struct page *locked_page,
1018 u64 start, u64 end, int *page_started, int force,
1019 unsigned long *nr_written)
1021 struct btrfs_root *root = BTRFS_I(inode)->root;
1022 struct btrfs_trans_handle *trans;
1023 struct extent_buffer *leaf;
1024 struct btrfs_path *path;
1025 struct btrfs_file_extent_item *fi;
1026 struct btrfs_key found_key;
1027 u64 cow_start;
1028 u64 cur_offset;
1029 u64 extent_end;
1030 u64 extent_offset;
1031 u64 disk_bytenr;
1032 u64 num_bytes;
1033 int extent_type;
1034 int ret;
1035 int type;
1036 int nocow;
1037 int check_prev = 1;
1039 path = btrfs_alloc_path();
1040 BUG_ON(!path);
1041 trans = btrfs_join_transaction(root, 1);
1042 BUG_ON(!trans);
1044 cow_start = (u64)-1;
1045 cur_offset = start;
1046 while (1) {
1047 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1048 cur_offset, 0);
1049 BUG_ON(ret < 0);
1050 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1051 leaf = path->nodes[0];
1052 btrfs_item_key_to_cpu(leaf, &found_key,
1053 path->slots[0] - 1);
1054 if (found_key.objectid == inode->i_ino &&
1055 found_key.type == BTRFS_EXTENT_DATA_KEY)
1056 path->slots[0]--;
1058 check_prev = 0;
1059 next_slot:
1060 leaf = path->nodes[0];
1061 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1062 ret = btrfs_next_leaf(root, path);
1063 if (ret < 0)
1064 BUG_ON(1);
1065 if (ret > 0)
1066 break;
1067 leaf = path->nodes[0];
1070 nocow = 0;
1071 disk_bytenr = 0;
1072 num_bytes = 0;
1073 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1075 if (found_key.objectid > inode->i_ino ||
1076 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1077 found_key.offset > end)
1078 break;
1080 if (found_key.offset > cur_offset) {
1081 extent_end = found_key.offset;
1082 extent_type = 0;
1083 goto out_check;
1086 fi = btrfs_item_ptr(leaf, path->slots[0],
1087 struct btrfs_file_extent_item);
1088 extent_type = btrfs_file_extent_type(leaf, fi);
1090 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1091 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1092 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1093 extent_offset = btrfs_file_extent_offset(leaf, fi);
1094 extent_end = found_key.offset +
1095 btrfs_file_extent_num_bytes(leaf, fi);
1096 if (extent_end <= start) {
1097 path->slots[0]++;
1098 goto next_slot;
1100 if (disk_bytenr == 0)
1101 goto out_check;
1102 if (btrfs_file_extent_compression(leaf, fi) ||
1103 btrfs_file_extent_encryption(leaf, fi) ||
1104 btrfs_file_extent_other_encoding(leaf, fi))
1105 goto out_check;
1106 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1107 goto out_check;
1108 if (btrfs_extent_readonly(root, disk_bytenr))
1109 goto out_check;
1110 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
1111 found_key.offset -
1112 extent_offset, disk_bytenr))
1113 goto out_check;
1114 disk_bytenr += extent_offset;
1115 disk_bytenr += cur_offset - found_key.offset;
1116 num_bytes = min(end + 1, extent_end) - cur_offset;
1118 * force cow if csum exists in the range.
1119 * this ensure that csum for a given extent are
1120 * either valid or do not exist.
1122 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1123 goto out_check;
1124 nocow = 1;
1125 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1126 extent_end = found_key.offset +
1127 btrfs_file_extent_inline_len(leaf, fi);
1128 extent_end = ALIGN(extent_end, root->sectorsize);
1129 } else {
1130 BUG_ON(1);
1132 out_check:
1133 if (extent_end <= start) {
1134 path->slots[0]++;
1135 goto next_slot;
1137 if (!nocow) {
1138 if (cow_start == (u64)-1)
1139 cow_start = cur_offset;
1140 cur_offset = extent_end;
1141 if (cur_offset > end)
1142 break;
1143 path->slots[0]++;
1144 goto next_slot;
1147 btrfs_release_path(root, path);
1148 if (cow_start != (u64)-1) {
1149 ret = cow_file_range(inode, locked_page, cow_start,
1150 found_key.offset - 1, page_started,
1151 nr_written, 1);
1152 BUG_ON(ret);
1153 cow_start = (u64)-1;
1156 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1157 struct extent_map *em;
1158 struct extent_map_tree *em_tree;
1159 em_tree = &BTRFS_I(inode)->extent_tree;
1160 em = alloc_extent_map(GFP_NOFS);
1161 em->start = cur_offset;
1162 em->orig_start = em->start;
1163 em->len = num_bytes;
1164 em->block_len = num_bytes;
1165 em->block_start = disk_bytenr;
1166 em->bdev = root->fs_info->fs_devices->latest_bdev;
1167 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1168 while (1) {
1169 write_lock(&em_tree->lock);
1170 ret = add_extent_mapping(em_tree, em);
1171 write_unlock(&em_tree->lock);
1172 if (ret != -EEXIST) {
1173 free_extent_map(em);
1174 break;
1176 btrfs_drop_extent_cache(inode, em->start,
1177 em->start + em->len - 1, 0);
1179 type = BTRFS_ORDERED_PREALLOC;
1180 } else {
1181 type = BTRFS_ORDERED_NOCOW;
1184 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1185 num_bytes, num_bytes, type);
1186 BUG_ON(ret);
1188 if (root->root_key.objectid ==
1189 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1190 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1191 num_bytes);
1192 BUG_ON(ret);
1195 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1196 cur_offset, cur_offset + num_bytes - 1,
1197 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1198 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1199 EXTENT_SET_PRIVATE2);
1200 cur_offset = extent_end;
1201 if (cur_offset > end)
1202 break;
1204 btrfs_release_path(root, path);
1206 if (cur_offset <= end && cow_start == (u64)-1)
1207 cow_start = cur_offset;
1208 if (cow_start != (u64)-1) {
1209 ret = cow_file_range(inode, locked_page, cow_start, end,
1210 page_started, nr_written, 1);
1211 BUG_ON(ret);
1214 ret = btrfs_end_transaction(trans, root);
1215 BUG_ON(ret);
1216 btrfs_free_path(path);
1217 return 0;
1221 * extent_io.c call back to do delayed allocation processing
1223 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1224 u64 start, u64 end, int *page_started,
1225 unsigned long *nr_written)
1227 int ret;
1228 struct btrfs_root *root = BTRFS_I(inode)->root;
1230 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1231 ret = run_delalloc_nocow(inode, locked_page, start, end,
1232 page_started, 1, nr_written);
1233 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1234 ret = run_delalloc_nocow(inode, locked_page, start, end,
1235 page_started, 0, nr_written);
1236 else if (!btrfs_test_opt(root, COMPRESS) &&
1237 !(BTRFS_I(inode)->force_compress))
1238 ret = cow_file_range(inode, locked_page, start, end,
1239 page_started, nr_written, 1);
1240 else
1241 ret = cow_file_range_async(inode, locked_page, start, end,
1242 page_started, nr_written);
1243 return ret;
1246 static int btrfs_split_extent_hook(struct inode *inode,
1247 struct extent_state *orig, u64 split)
1249 /* not delalloc, ignore it */
1250 if (!(orig->state & EXTENT_DELALLOC))
1251 return 0;
1253 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1254 return 0;
1258 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1259 * extents so we can keep track of new extents that are just merged onto old
1260 * extents, such as when we are doing sequential writes, so we can properly
1261 * account for the metadata space we'll need.
1263 static int btrfs_merge_extent_hook(struct inode *inode,
1264 struct extent_state *new,
1265 struct extent_state *other)
1267 /* not delalloc, ignore it */
1268 if (!(other->state & EXTENT_DELALLOC))
1269 return 0;
1271 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1272 return 0;
1276 * extent_io.c set_bit_hook, used to track delayed allocation
1277 * bytes in this file, and to maintain the list of inodes that
1278 * have pending delalloc work to be done.
1280 static int btrfs_set_bit_hook(struct inode *inode,
1281 struct extent_state *state, int *bits)
1285 * set_bit and clear bit hooks normally require _irqsave/restore
1286 * but in this case, we are only testeing for the DELALLOC
1287 * bit, which is only set or cleared with irqs on
1289 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1290 struct btrfs_root *root = BTRFS_I(inode)->root;
1291 u64 len = state->end + 1 - state->start;
1293 if (*bits & EXTENT_FIRST_DELALLOC)
1294 *bits &= ~EXTENT_FIRST_DELALLOC;
1295 else
1296 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
1298 spin_lock(&root->fs_info->delalloc_lock);
1299 BTRFS_I(inode)->delalloc_bytes += len;
1300 root->fs_info->delalloc_bytes += len;
1301 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1302 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1303 &root->fs_info->delalloc_inodes);
1305 spin_unlock(&root->fs_info->delalloc_lock);
1307 return 0;
1311 * extent_io.c clear_bit_hook, see set_bit_hook for why
1313 static int btrfs_clear_bit_hook(struct inode *inode,
1314 struct extent_state *state, int *bits)
1317 * set_bit and clear bit hooks normally require _irqsave/restore
1318 * but in this case, we are only testeing for the DELALLOC
1319 * bit, which is only set or cleared with irqs on
1321 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1322 struct btrfs_root *root = BTRFS_I(inode)->root;
1323 u64 len = state->end + 1 - state->start;
1325 if (*bits & EXTENT_FIRST_DELALLOC)
1326 *bits &= ~EXTENT_FIRST_DELALLOC;
1327 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1328 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1330 if (*bits & EXTENT_DO_ACCOUNTING)
1331 btrfs_delalloc_release_metadata(inode, len);
1333 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID)
1334 btrfs_free_reserved_data_space(inode, len);
1336 spin_lock(&root->fs_info->delalloc_lock);
1337 root->fs_info->delalloc_bytes -= len;
1338 BTRFS_I(inode)->delalloc_bytes -= len;
1340 if (BTRFS_I(inode)->delalloc_bytes == 0 &&
1341 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1342 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1344 spin_unlock(&root->fs_info->delalloc_lock);
1346 return 0;
1350 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1351 * we don't create bios that span stripes or chunks
1353 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1354 size_t size, struct bio *bio,
1355 unsigned long bio_flags)
1357 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1358 struct btrfs_mapping_tree *map_tree;
1359 u64 logical = (u64)bio->bi_sector << 9;
1360 u64 length = 0;
1361 u64 map_length;
1362 int ret;
1364 if (bio_flags & EXTENT_BIO_COMPRESSED)
1365 return 0;
1367 length = bio->bi_size;
1368 map_tree = &root->fs_info->mapping_tree;
1369 map_length = length;
1370 ret = btrfs_map_block(map_tree, READ, logical,
1371 &map_length, NULL, 0);
1373 if (map_length < length + size)
1374 return 1;
1375 return 0;
1379 * in order to insert checksums into the metadata in large chunks,
1380 * we wait until bio submission time. All the pages in the bio are
1381 * checksummed and sums are attached onto the ordered extent record.
1383 * At IO completion time the cums attached on the ordered extent record
1384 * are inserted into the btree
1386 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1387 struct bio *bio, int mirror_num,
1388 unsigned long bio_flags,
1389 u64 bio_offset)
1391 struct btrfs_root *root = BTRFS_I(inode)->root;
1392 int ret = 0;
1394 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1395 BUG_ON(ret);
1396 return 0;
1400 * in order to insert checksums into the metadata in large chunks,
1401 * we wait until bio submission time. All the pages in the bio are
1402 * checksummed and sums are attached onto the ordered extent record.
1404 * At IO completion time the cums attached on the ordered extent record
1405 * are inserted into the btree
1407 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1408 int mirror_num, unsigned long bio_flags,
1409 u64 bio_offset)
1411 struct btrfs_root *root = BTRFS_I(inode)->root;
1412 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1416 * extent_io.c submission hook. This does the right thing for csum calculation
1417 * on write, or reading the csums from the tree before a read
1419 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1420 int mirror_num, unsigned long bio_flags,
1421 u64 bio_offset)
1423 struct btrfs_root *root = BTRFS_I(inode)->root;
1424 int ret = 0;
1425 int skip_sum;
1427 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1429 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1430 BUG_ON(ret);
1432 if (!(rw & REQ_WRITE)) {
1433 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1434 return btrfs_submit_compressed_read(inode, bio,
1435 mirror_num, bio_flags);
1436 } else if (!skip_sum)
1437 btrfs_lookup_bio_sums(root, inode, bio, NULL);
1438 goto mapit;
1439 } else if (!skip_sum) {
1440 /* csum items have already been cloned */
1441 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1442 goto mapit;
1443 /* we're doing a write, do the async checksumming */
1444 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1445 inode, rw, bio, mirror_num,
1446 bio_flags, bio_offset,
1447 __btrfs_submit_bio_start,
1448 __btrfs_submit_bio_done);
1451 mapit:
1452 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1456 * given a list of ordered sums record them in the inode. This happens
1457 * at IO completion time based on sums calculated at bio submission time.
1459 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1460 struct inode *inode, u64 file_offset,
1461 struct list_head *list)
1463 struct btrfs_ordered_sum *sum;
1465 btrfs_set_trans_block_group(trans, inode);
1467 list_for_each_entry(sum, list, list) {
1468 btrfs_csum_file_blocks(trans,
1469 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1471 return 0;
1474 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1475 struct extent_state **cached_state)
1477 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1478 WARN_ON(1);
1479 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1480 cached_state, GFP_NOFS);
1483 /* see btrfs_writepage_start_hook for details on why this is required */
1484 struct btrfs_writepage_fixup {
1485 struct page *page;
1486 struct btrfs_work work;
1489 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1491 struct btrfs_writepage_fixup *fixup;
1492 struct btrfs_ordered_extent *ordered;
1493 struct extent_state *cached_state = NULL;
1494 struct page *page;
1495 struct inode *inode;
1496 u64 page_start;
1497 u64 page_end;
1499 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1500 page = fixup->page;
1501 again:
1502 lock_page(page);
1503 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1504 ClearPageChecked(page);
1505 goto out_page;
1508 inode = page->mapping->host;
1509 page_start = page_offset(page);
1510 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1512 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1513 &cached_state, GFP_NOFS);
1515 /* already ordered? We're done */
1516 if (PagePrivate2(page))
1517 goto out;
1519 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1520 if (ordered) {
1521 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1522 page_end, &cached_state, GFP_NOFS);
1523 unlock_page(page);
1524 btrfs_start_ordered_extent(inode, ordered, 1);
1525 goto again;
1528 BUG();
1529 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1530 ClearPageChecked(page);
1531 out:
1532 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1533 &cached_state, GFP_NOFS);
1534 out_page:
1535 unlock_page(page);
1536 page_cache_release(page);
1540 * There are a few paths in the higher layers of the kernel that directly
1541 * set the page dirty bit without asking the filesystem if it is a
1542 * good idea. This causes problems because we want to make sure COW
1543 * properly happens and the data=ordered rules are followed.
1545 * In our case any range that doesn't have the ORDERED bit set
1546 * hasn't been properly setup for IO. We kick off an async process
1547 * to fix it up. The async helper will wait for ordered extents, set
1548 * the delalloc bit and make it safe to write the page.
1550 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1552 struct inode *inode = page->mapping->host;
1553 struct btrfs_writepage_fixup *fixup;
1554 struct btrfs_root *root = BTRFS_I(inode)->root;
1556 /* this page is properly in the ordered list */
1557 if (TestClearPagePrivate2(page))
1558 return 0;
1560 if (PageChecked(page))
1561 return -EAGAIN;
1563 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1564 if (!fixup)
1565 return -EAGAIN;
1567 SetPageChecked(page);
1568 page_cache_get(page);
1569 fixup->work.func = btrfs_writepage_fixup_worker;
1570 fixup->page = page;
1571 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1572 return -EAGAIN;
1575 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1576 struct inode *inode, u64 file_pos,
1577 u64 disk_bytenr, u64 disk_num_bytes,
1578 u64 num_bytes, u64 ram_bytes,
1579 u8 compression, u8 encryption,
1580 u16 other_encoding, int extent_type)
1582 struct btrfs_root *root = BTRFS_I(inode)->root;
1583 struct btrfs_file_extent_item *fi;
1584 struct btrfs_path *path;
1585 struct extent_buffer *leaf;
1586 struct btrfs_key ins;
1587 u64 hint;
1588 int ret;
1590 path = btrfs_alloc_path();
1591 BUG_ON(!path);
1593 path->leave_spinning = 1;
1596 * we may be replacing one extent in the tree with another.
1597 * The new extent is pinned in the extent map, and we don't want
1598 * to drop it from the cache until it is completely in the btree.
1600 * So, tell btrfs_drop_extents to leave this extent in the cache.
1601 * the caller is expected to unpin it and allow it to be merged
1602 * with the others.
1604 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1605 &hint, 0);
1606 BUG_ON(ret);
1608 ins.objectid = inode->i_ino;
1609 ins.offset = file_pos;
1610 ins.type = BTRFS_EXTENT_DATA_KEY;
1611 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1612 BUG_ON(ret);
1613 leaf = path->nodes[0];
1614 fi = btrfs_item_ptr(leaf, path->slots[0],
1615 struct btrfs_file_extent_item);
1616 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1617 btrfs_set_file_extent_type(leaf, fi, extent_type);
1618 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1619 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1620 btrfs_set_file_extent_offset(leaf, fi, 0);
1621 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1622 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1623 btrfs_set_file_extent_compression(leaf, fi, compression);
1624 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1625 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1627 btrfs_unlock_up_safe(path, 1);
1628 btrfs_set_lock_blocking(leaf);
1630 btrfs_mark_buffer_dirty(leaf);
1632 inode_add_bytes(inode, num_bytes);
1634 ins.objectid = disk_bytenr;
1635 ins.offset = disk_num_bytes;
1636 ins.type = BTRFS_EXTENT_ITEM_KEY;
1637 ret = btrfs_alloc_reserved_file_extent(trans, root,
1638 root->root_key.objectid,
1639 inode->i_ino, file_pos, &ins);
1640 BUG_ON(ret);
1641 btrfs_free_path(path);
1643 return 0;
1647 * helper function for btrfs_finish_ordered_io, this
1648 * just reads in some of the csum leaves to prime them into ram
1649 * before we start the transaction. It limits the amount of btree
1650 * reads required while inside the transaction.
1652 /* as ordered data IO finishes, this gets called so we can finish
1653 * an ordered extent if the range of bytes in the file it covers are
1654 * fully written.
1656 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1658 struct btrfs_root *root = BTRFS_I(inode)->root;
1659 struct btrfs_trans_handle *trans = NULL;
1660 struct btrfs_ordered_extent *ordered_extent = NULL;
1661 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1662 struct extent_state *cached_state = NULL;
1663 int compressed = 0;
1664 int ret;
1666 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1667 end - start + 1);
1668 if (!ret)
1669 return 0;
1670 BUG_ON(!ordered_extent);
1672 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1673 BUG_ON(!list_empty(&ordered_extent->list));
1674 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1675 if (!ret) {
1676 trans = btrfs_join_transaction(root, 1);
1677 btrfs_set_trans_block_group(trans, inode);
1678 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1679 ret = btrfs_update_inode(trans, root, inode);
1680 BUG_ON(ret);
1682 goto out;
1685 lock_extent_bits(io_tree, ordered_extent->file_offset,
1686 ordered_extent->file_offset + ordered_extent->len - 1,
1687 0, &cached_state, GFP_NOFS);
1689 trans = btrfs_join_transaction(root, 1);
1690 btrfs_set_trans_block_group(trans, inode);
1691 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1693 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1694 compressed = 1;
1695 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1696 BUG_ON(compressed);
1697 ret = btrfs_mark_extent_written(trans, inode,
1698 ordered_extent->file_offset,
1699 ordered_extent->file_offset +
1700 ordered_extent->len);
1701 BUG_ON(ret);
1702 } else {
1703 ret = insert_reserved_file_extent(trans, inode,
1704 ordered_extent->file_offset,
1705 ordered_extent->start,
1706 ordered_extent->disk_len,
1707 ordered_extent->len,
1708 ordered_extent->len,
1709 compressed, 0, 0,
1710 BTRFS_FILE_EXTENT_REG);
1711 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1712 ordered_extent->file_offset,
1713 ordered_extent->len);
1714 BUG_ON(ret);
1716 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1717 ordered_extent->file_offset +
1718 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1720 add_pending_csums(trans, inode, ordered_extent->file_offset,
1721 &ordered_extent->list);
1723 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1724 ret = btrfs_update_inode(trans, root, inode);
1725 BUG_ON(ret);
1726 out:
1727 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1728 if (trans)
1729 btrfs_end_transaction(trans, root);
1730 /* once for us */
1731 btrfs_put_ordered_extent(ordered_extent);
1732 /* once for the tree */
1733 btrfs_put_ordered_extent(ordered_extent);
1735 return 0;
1738 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1739 struct extent_state *state, int uptodate)
1741 ClearPagePrivate2(page);
1742 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1746 * When IO fails, either with EIO or csum verification fails, we
1747 * try other mirrors that might have a good copy of the data. This
1748 * io_failure_record is used to record state as we go through all the
1749 * mirrors. If another mirror has good data, the page is set up to date
1750 * and things continue. If a good mirror can't be found, the original
1751 * bio end_io callback is called to indicate things have failed.
1753 struct io_failure_record {
1754 struct page *page;
1755 u64 start;
1756 u64 len;
1757 u64 logical;
1758 unsigned long bio_flags;
1759 int last_mirror;
1762 static int btrfs_io_failed_hook(struct bio *failed_bio,
1763 struct page *page, u64 start, u64 end,
1764 struct extent_state *state)
1766 struct io_failure_record *failrec = NULL;
1767 u64 private;
1768 struct extent_map *em;
1769 struct inode *inode = page->mapping->host;
1770 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1771 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1772 struct bio *bio;
1773 int num_copies;
1774 int ret;
1775 int rw;
1776 u64 logical;
1778 ret = get_state_private(failure_tree, start, &private);
1779 if (ret) {
1780 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1781 if (!failrec)
1782 return -ENOMEM;
1783 failrec->start = start;
1784 failrec->len = end - start + 1;
1785 failrec->last_mirror = 0;
1786 failrec->bio_flags = 0;
1788 read_lock(&em_tree->lock);
1789 em = lookup_extent_mapping(em_tree, start, failrec->len);
1790 if (em->start > start || em->start + em->len < start) {
1791 free_extent_map(em);
1792 em = NULL;
1794 read_unlock(&em_tree->lock);
1796 if (!em || IS_ERR(em)) {
1797 kfree(failrec);
1798 return -EIO;
1800 logical = start - em->start;
1801 logical = em->block_start + logical;
1802 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1803 logical = em->block_start;
1804 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1806 failrec->logical = logical;
1807 free_extent_map(em);
1808 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1809 EXTENT_DIRTY, GFP_NOFS);
1810 set_state_private(failure_tree, start,
1811 (u64)(unsigned long)failrec);
1812 } else {
1813 failrec = (struct io_failure_record *)(unsigned long)private;
1815 num_copies = btrfs_num_copies(
1816 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1817 failrec->logical, failrec->len);
1818 failrec->last_mirror++;
1819 if (!state) {
1820 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1821 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1822 failrec->start,
1823 EXTENT_LOCKED);
1824 if (state && state->start != failrec->start)
1825 state = NULL;
1826 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1828 if (!state || failrec->last_mirror > num_copies) {
1829 set_state_private(failure_tree, failrec->start, 0);
1830 clear_extent_bits(failure_tree, failrec->start,
1831 failrec->start + failrec->len - 1,
1832 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1833 kfree(failrec);
1834 return -EIO;
1836 bio = bio_alloc(GFP_NOFS, 1);
1837 bio->bi_private = state;
1838 bio->bi_end_io = failed_bio->bi_end_io;
1839 bio->bi_sector = failrec->logical >> 9;
1840 bio->bi_bdev = failed_bio->bi_bdev;
1841 bio->bi_size = 0;
1843 bio_add_page(bio, page, failrec->len, start - page_offset(page));
1844 if (failed_bio->bi_rw & REQ_WRITE)
1845 rw = WRITE;
1846 else
1847 rw = READ;
1849 BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1850 failrec->last_mirror,
1851 failrec->bio_flags, 0);
1852 return 0;
1856 * each time an IO finishes, we do a fast check in the IO failure tree
1857 * to see if we need to process or clean up an io_failure_record
1859 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1861 u64 private;
1862 u64 private_failure;
1863 struct io_failure_record *failure;
1864 int ret;
1866 private = 0;
1867 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1868 (u64)-1, 1, EXTENT_DIRTY)) {
1869 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1870 start, &private_failure);
1871 if (ret == 0) {
1872 failure = (struct io_failure_record *)(unsigned long)
1873 private_failure;
1874 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1875 failure->start, 0);
1876 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1877 failure->start,
1878 failure->start + failure->len - 1,
1879 EXTENT_DIRTY | EXTENT_LOCKED,
1880 GFP_NOFS);
1881 kfree(failure);
1884 return 0;
1888 * when reads are done, we need to check csums to verify the data is correct
1889 * if there's a match, we allow the bio to finish. If not, we go through
1890 * the io_failure_record routines to find good copies
1892 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1893 struct extent_state *state)
1895 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1896 struct inode *inode = page->mapping->host;
1897 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1898 char *kaddr;
1899 u64 private = ~(u32)0;
1900 int ret;
1901 struct btrfs_root *root = BTRFS_I(inode)->root;
1902 u32 csum = ~(u32)0;
1904 if (PageChecked(page)) {
1905 ClearPageChecked(page);
1906 goto good;
1909 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1910 return 0;
1912 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1913 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1914 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1915 GFP_NOFS);
1916 return 0;
1919 if (state && state->start == start) {
1920 private = state->private;
1921 ret = 0;
1922 } else {
1923 ret = get_state_private(io_tree, start, &private);
1925 kaddr = kmap_atomic(page, KM_USER0);
1926 if (ret)
1927 goto zeroit;
1929 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1930 btrfs_csum_final(csum, (char *)&csum);
1931 if (csum != private)
1932 goto zeroit;
1934 kunmap_atomic(kaddr, KM_USER0);
1935 good:
1936 /* if the io failure tree for this inode is non-empty,
1937 * check to see if we've recovered from a failed IO
1939 btrfs_clean_io_failures(inode, start);
1940 return 0;
1942 zeroit:
1943 if (printk_ratelimit()) {
1944 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1945 "private %llu\n", page->mapping->host->i_ino,
1946 (unsigned long long)start, csum,
1947 (unsigned long long)private);
1949 memset(kaddr + offset, 1, end - start + 1);
1950 flush_dcache_page(page);
1951 kunmap_atomic(kaddr, KM_USER0);
1952 if (private == 0)
1953 return 0;
1954 return -EIO;
1957 struct delayed_iput {
1958 struct list_head list;
1959 struct inode *inode;
1962 void btrfs_add_delayed_iput(struct inode *inode)
1964 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1965 struct delayed_iput *delayed;
1967 if (atomic_add_unless(&inode->i_count, -1, 1))
1968 return;
1970 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1971 delayed->inode = inode;
1973 spin_lock(&fs_info->delayed_iput_lock);
1974 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
1975 spin_unlock(&fs_info->delayed_iput_lock);
1978 void btrfs_run_delayed_iputs(struct btrfs_root *root)
1980 LIST_HEAD(list);
1981 struct btrfs_fs_info *fs_info = root->fs_info;
1982 struct delayed_iput *delayed;
1983 int empty;
1985 spin_lock(&fs_info->delayed_iput_lock);
1986 empty = list_empty(&fs_info->delayed_iputs);
1987 spin_unlock(&fs_info->delayed_iput_lock);
1988 if (empty)
1989 return;
1991 down_read(&root->fs_info->cleanup_work_sem);
1992 spin_lock(&fs_info->delayed_iput_lock);
1993 list_splice_init(&fs_info->delayed_iputs, &list);
1994 spin_unlock(&fs_info->delayed_iput_lock);
1996 while (!list_empty(&list)) {
1997 delayed = list_entry(list.next, struct delayed_iput, list);
1998 list_del(&delayed->list);
1999 iput(delayed->inode);
2000 kfree(delayed);
2002 up_read(&root->fs_info->cleanup_work_sem);
2006 * calculate extra metadata reservation when snapshotting a subvolume
2007 * contains orphan files.
2009 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2010 struct btrfs_pending_snapshot *pending,
2011 u64 *bytes_to_reserve)
2013 struct btrfs_root *root;
2014 struct btrfs_block_rsv *block_rsv;
2015 u64 num_bytes;
2016 int index;
2018 root = pending->root;
2019 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2020 return;
2022 block_rsv = root->orphan_block_rsv;
2024 /* orphan block reservation for the snapshot */
2025 num_bytes = block_rsv->size;
2028 * after the snapshot is created, COWing tree blocks may use more
2029 * space than it frees. So we should make sure there is enough
2030 * reserved space.
2032 index = trans->transid & 0x1;
2033 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2034 num_bytes += block_rsv->size -
2035 (block_rsv->reserved + block_rsv->freed[index]);
2038 *bytes_to_reserve += num_bytes;
2041 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2042 struct btrfs_pending_snapshot *pending)
2044 struct btrfs_root *root = pending->root;
2045 struct btrfs_root *snap = pending->snap;
2046 struct btrfs_block_rsv *block_rsv;
2047 u64 num_bytes;
2048 int index;
2049 int ret;
2051 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2052 return;
2054 /* refill source subvolume's orphan block reservation */
2055 block_rsv = root->orphan_block_rsv;
2056 index = trans->transid & 0x1;
2057 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2058 num_bytes = block_rsv->size -
2059 (block_rsv->reserved + block_rsv->freed[index]);
2060 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2061 root->orphan_block_rsv,
2062 num_bytes);
2063 BUG_ON(ret);
2066 /* setup orphan block reservation for the snapshot */
2067 block_rsv = btrfs_alloc_block_rsv(snap);
2068 BUG_ON(!block_rsv);
2070 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2071 snap->orphan_block_rsv = block_rsv;
2073 num_bytes = root->orphan_block_rsv->size;
2074 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2075 block_rsv, num_bytes);
2076 BUG_ON(ret);
2080 enum btrfs_orphan_cleanup_state {
2081 ORPHAN_CLEANUP_STARTED = 1,
2082 ORPHAN_CLEANUP_DONE = 2,
2086 * This is called in transaction commmit time. If there are no orphan
2087 * files in the subvolume, it removes orphan item and frees block_rsv
2088 * structure.
2090 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2091 struct btrfs_root *root)
2093 int ret;
2095 if (!list_empty(&root->orphan_list) ||
2096 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2097 return;
2099 if (root->orphan_item_inserted &&
2100 btrfs_root_refs(&root->root_item) > 0) {
2101 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2102 root->root_key.objectid);
2103 BUG_ON(ret);
2104 root->orphan_item_inserted = 0;
2107 if (root->orphan_block_rsv) {
2108 WARN_ON(root->orphan_block_rsv->size > 0);
2109 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2110 root->orphan_block_rsv = NULL;
2115 * This creates an orphan entry for the given inode in case something goes
2116 * wrong in the middle of an unlink/truncate.
2118 * NOTE: caller of this function should reserve 5 units of metadata for
2119 * this function.
2121 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2123 struct btrfs_root *root = BTRFS_I(inode)->root;
2124 struct btrfs_block_rsv *block_rsv = NULL;
2125 int reserve = 0;
2126 int insert = 0;
2127 int ret;
2129 if (!root->orphan_block_rsv) {
2130 block_rsv = btrfs_alloc_block_rsv(root);
2131 BUG_ON(!block_rsv);
2134 spin_lock(&root->orphan_lock);
2135 if (!root->orphan_block_rsv) {
2136 root->orphan_block_rsv = block_rsv;
2137 } else if (block_rsv) {
2138 btrfs_free_block_rsv(root, block_rsv);
2139 block_rsv = NULL;
2142 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2143 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2144 insert = 1;
2145 } else {
2146 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
2149 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2150 BTRFS_I(inode)->orphan_meta_reserved = 1;
2151 reserve = 1;
2153 spin_unlock(&root->orphan_lock);
2155 if (block_rsv)
2156 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2158 /* grab metadata reservation from transaction handle */
2159 if (reserve) {
2160 ret = btrfs_orphan_reserve_metadata(trans, inode);
2161 BUG_ON(ret);
2164 /* insert an orphan item to track this unlinked/truncated file */
2165 if (insert >= 1) {
2166 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2167 BUG_ON(ret);
2170 /* insert an orphan item to track subvolume contains orphan files */
2171 if (insert >= 2) {
2172 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2173 root->root_key.objectid);
2174 BUG_ON(ret);
2176 return 0;
2180 * We have done the truncate/delete so we can go ahead and remove the orphan
2181 * item for this particular inode.
2183 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2185 struct btrfs_root *root = BTRFS_I(inode)->root;
2186 int delete_item = 0;
2187 int release_rsv = 0;
2188 int ret = 0;
2190 spin_lock(&root->orphan_lock);
2191 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2192 list_del_init(&BTRFS_I(inode)->i_orphan);
2193 delete_item = 1;
2196 if (BTRFS_I(inode)->orphan_meta_reserved) {
2197 BTRFS_I(inode)->orphan_meta_reserved = 0;
2198 release_rsv = 1;
2200 spin_unlock(&root->orphan_lock);
2202 if (trans && delete_item) {
2203 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2204 BUG_ON(ret);
2207 if (release_rsv)
2208 btrfs_orphan_release_metadata(inode);
2210 return 0;
2214 * this cleans up any orphans that may be left on the list from the last use
2215 * of this root.
2217 void btrfs_orphan_cleanup(struct btrfs_root *root)
2219 struct btrfs_path *path;
2220 struct extent_buffer *leaf;
2221 struct btrfs_item *item;
2222 struct btrfs_key key, found_key;
2223 struct btrfs_trans_handle *trans;
2224 struct inode *inode;
2225 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2227 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2228 return;
2230 path = btrfs_alloc_path();
2231 BUG_ON(!path);
2232 path->reada = -1;
2234 key.objectid = BTRFS_ORPHAN_OBJECTID;
2235 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2236 key.offset = (u64)-1;
2238 while (1) {
2239 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2240 if (ret < 0) {
2241 printk(KERN_ERR "Error searching slot for orphan: %d"
2242 "\n", ret);
2243 break;
2247 * if ret == 0 means we found what we were searching for, which
2248 * is weird, but possible, so only screw with path if we didnt
2249 * find the key and see if we have stuff that matches
2251 if (ret > 0) {
2252 if (path->slots[0] == 0)
2253 break;
2254 path->slots[0]--;
2257 /* pull out the item */
2258 leaf = path->nodes[0];
2259 item = btrfs_item_nr(leaf, path->slots[0]);
2260 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2262 /* make sure the item matches what we want */
2263 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2264 break;
2265 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2266 break;
2268 /* release the path since we're done with it */
2269 btrfs_release_path(root, path);
2272 * this is where we are basically btrfs_lookup, without the
2273 * crossing root thing. we store the inode number in the
2274 * offset of the orphan item.
2276 found_key.objectid = found_key.offset;
2277 found_key.type = BTRFS_INODE_ITEM_KEY;
2278 found_key.offset = 0;
2279 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2280 BUG_ON(IS_ERR(inode));
2283 * add this inode to the orphan list so btrfs_orphan_del does
2284 * the proper thing when we hit it
2286 spin_lock(&root->orphan_lock);
2287 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2288 spin_unlock(&root->orphan_lock);
2291 * if this is a bad inode, means we actually succeeded in
2292 * removing the inode, but not the orphan record, which means
2293 * we need to manually delete the orphan since iput will just
2294 * do a destroy_inode
2296 if (is_bad_inode(inode)) {
2297 trans = btrfs_start_transaction(root, 0);
2298 btrfs_orphan_del(trans, inode);
2299 btrfs_end_transaction(trans, root);
2300 iput(inode);
2301 continue;
2304 /* if we have links, this was a truncate, lets do that */
2305 if (inode->i_nlink) {
2306 nr_truncate++;
2307 btrfs_truncate(inode);
2308 } else {
2309 nr_unlink++;
2312 /* this will do delete_inode and everything for us */
2313 iput(inode);
2315 btrfs_free_path(path);
2317 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2319 if (root->orphan_block_rsv)
2320 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2321 (u64)-1);
2323 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2324 trans = btrfs_join_transaction(root, 1);
2325 btrfs_end_transaction(trans, root);
2328 if (nr_unlink)
2329 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2330 if (nr_truncate)
2331 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2335 * very simple check to peek ahead in the leaf looking for xattrs. If we
2336 * don't find any xattrs, we know there can't be any acls.
2338 * slot is the slot the inode is in, objectid is the objectid of the inode
2340 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2341 int slot, u64 objectid)
2343 u32 nritems = btrfs_header_nritems(leaf);
2344 struct btrfs_key found_key;
2345 int scanned = 0;
2347 slot++;
2348 while (slot < nritems) {
2349 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2351 /* we found a different objectid, there must not be acls */
2352 if (found_key.objectid != objectid)
2353 return 0;
2355 /* we found an xattr, assume we've got an acl */
2356 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2357 return 1;
2360 * we found a key greater than an xattr key, there can't
2361 * be any acls later on
2363 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2364 return 0;
2366 slot++;
2367 scanned++;
2370 * it goes inode, inode backrefs, xattrs, extents,
2371 * so if there are a ton of hard links to an inode there can
2372 * be a lot of backrefs. Don't waste time searching too hard,
2373 * this is just an optimization
2375 if (scanned >= 8)
2376 break;
2378 /* we hit the end of the leaf before we found an xattr or
2379 * something larger than an xattr. We have to assume the inode
2380 * has acls
2382 return 1;
2386 * read an inode from the btree into the in-memory inode
2388 static void btrfs_read_locked_inode(struct inode *inode)
2390 struct btrfs_path *path;
2391 struct extent_buffer *leaf;
2392 struct btrfs_inode_item *inode_item;
2393 struct btrfs_timespec *tspec;
2394 struct btrfs_root *root = BTRFS_I(inode)->root;
2395 struct btrfs_key location;
2396 int maybe_acls;
2397 u64 alloc_group_block;
2398 u32 rdev;
2399 int ret;
2401 path = btrfs_alloc_path();
2402 BUG_ON(!path);
2403 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2405 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2406 if (ret)
2407 goto make_bad;
2409 leaf = path->nodes[0];
2410 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2411 struct btrfs_inode_item);
2413 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2414 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2415 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2416 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2417 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2419 tspec = btrfs_inode_atime(inode_item);
2420 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2421 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2423 tspec = btrfs_inode_mtime(inode_item);
2424 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2425 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2427 tspec = btrfs_inode_ctime(inode_item);
2428 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2429 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2431 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2432 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2433 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2434 inode->i_generation = BTRFS_I(inode)->generation;
2435 inode->i_rdev = 0;
2436 rdev = btrfs_inode_rdev(leaf, inode_item);
2438 BTRFS_I(inode)->index_cnt = (u64)-1;
2439 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2441 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
2444 * try to precache a NULL acl entry for files that don't have
2445 * any xattrs or acls
2447 maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
2448 if (!maybe_acls)
2449 cache_no_acl(inode);
2451 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2452 alloc_group_block, 0);
2453 btrfs_free_path(path);
2454 inode_item = NULL;
2456 switch (inode->i_mode & S_IFMT) {
2457 case S_IFREG:
2458 inode->i_mapping->a_ops = &btrfs_aops;
2459 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2460 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2461 inode->i_fop = &btrfs_file_operations;
2462 inode->i_op = &btrfs_file_inode_operations;
2463 break;
2464 case S_IFDIR:
2465 inode->i_fop = &btrfs_dir_file_operations;
2466 if (root == root->fs_info->tree_root)
2467 inode->i_op = &btrfs_dir_ro_inode_operations;
2468 else
2469 inode->i_op = &btrfs_dir_inode_operations;
2470 break;
2471 case S_IFLNK:
2472 inode->i_op = &btrfs_symlink_inode_operations;
2473 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2474 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2475 break;
2476 default:
2477 inode->i_op = &btrfs_special_inode_operations;
2478 init_special_inode(inode, inode->i_mode, rdev);
2479 break;
2482 btrfs_update_iflags(inode);
2483 return;
2485 make_bad:
2486 btrfs_free_path(path);
2487 make_bad_inode(inode);
2491 * given a leaf and an inode, copy the inode fields into the leaf
2493 static void fill_inode_item(struct btrfs_trans_handle *trans,
2494 struct extent_buffer *leaf,
2495 struct btrfs_inode_item *item,
2496 struct inode *inode)
2498 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2499 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2500 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2501 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2502 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2504 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2505 inode->i_atime.tv_sec);
2506 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2507 inode->i_atime.tv_nsec);
2509 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2510 inode->i_mtime.tv_sec);
2511 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2512 inode->i_mtime.tv_nsec);
2514 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2515 inode->i_ctime.tv_sec);
2516 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2517 inode->i_ctime.tv_nsec);
2519 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2520 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2521 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2522 btrfs_set_inode_transid(leaf, item, trans->transid);
2523 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2524 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2525 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
2529 * copy everything in the in-memory inode into the btree.
2531 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2532 struct btrfs_root *root, struct inode *inode)
2534 struct btrfs_inode_item *inode_item;
2535 struct btrfs_path *path;
2536 struct extent_buffer *leaf;
2537 int ret;
2539 path = btrfs_alloc_path();
2540 BUG_ON(!path);
2541 path->leave_spinning = 1;
2542 ret = btrfs_lookup_inode(trans, root, path,
2543 &BTRFS_I(inode)->location, 1);
2544 if (ret) {
2545 if (ret > 0)
2546 ret = -ENOENT;
2547 goto failed;
2550 btrfs_unlock_up_safe(path, 1);
2551 leaf = path->nodes[0];
2552 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2553 struct btrfs_inode_item);
2555 fill_inode_item(trans, leaf, inode_item, inode);
2556 btrfs_mark_buffer_dirty(leaf);
2557 btrfs_set_inode_last_trans(trans, inode);
2558 ret = 0;
2559 failed:
2560 btrfs_free_path(path);
2561 return ret;
2566 * unlink helper that gets used here in inode.c and in the tree logging
2567 * recovery code. It remove a link in a directory with a given name, and
2568 * also drops the back refs in the inode to the directory
2570 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2571 struct btrfs_root *root,
2572 struct inode *dir, struct inode *inode,
2573 const char *name, int name_len)
2575 struct btrfs_path *path;
2576 int ret = 0;
2577 struct extent_buffer *leaf;
2578 struct btrfs_dir_item *di;
2579 struct btrfs_key key;
2580 u64 index;
2582 path = btrfs_alloc_path();
2583 if (!path) {
2584 ret = -ENOMEM;
2585 goto err;
2588 path->leave_spinning = 1;
2589 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2590 name, name_len, -1);
2591 if (IS_ERR(di)) {
2592 ret = PTR_ERR(di);
2593 goto err;
2595 if (!di) {
2596 ret = -ENOENT;
2597 goto err;
2599 leaf = path->nodes[0];
2600 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2601 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2602 if (ret)
2603 goto err;
2604 btrfs_release_path(root, path);
2606 ret = btrfs_del_inode_ref(trans, root, name, name_len,
2607 inode->i_ino,
2608 dir->i_ino, &index);
2609 if (ret) {
2610 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2611 "inode %lu parent %lu\n", name_len, name,
2612 inode->i_ino, dir->i_ino);
2613 goto err;
2616 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2617 index, name, name_len, -1);
2618 if (IS_ERR(di)) {
2619 ret = PTR_ERR(di);
2620 goto err;
2622 if (!di) {
2623 ret = -ENOENT;
2624 goto err;
2626 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2627 btrfs_release_path(root, path);
2629 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2630 inode, dir->i_ino);
2631 BUG_ON(ret != 0 && ret != -ENOENT);
2633 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2634 dir, index);
2635 BUG_ON(ret);
2636 err:
2637 btrfs_free_path(path);
2638 if (ret)
2639 goto out;
2641 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2642 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2643 btrfs_update_inode(trans, root, dir);
2644 btrfs_drop_nlink(inode);
2645 ret = btrfs_update_inode(trans, root, inode);
2646 out:
2647 return ret;
2650 /* helper to check if there is any shared block in the path */
2651 static int check_path_shared(struct btrfs_root *root,
2652 struct btrfs_path *path)
2654 struct extent_buffer *eb;
2655 int level;
2656 int ret;
2657 u64 refs = 1;
2659 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2660 if (!path->nodes[level])
2661 break;
2662 eb = path->nodes[level];
2663 if (!btrfs_block_can_be_shared(root, eb))
2664 continue;
2665 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2666 &refs, NULL);
2667 if (refs > 1)
2668 return 1;
2670 return 0;
2674 * helper to start transaction for unlink and rmdir.
2676 * unlink and rmdir are special in btrfs, they do not always free space.
2677 * so in enospc case, we should make sure they will free space before
2678 * allowing them to use the global metadata reservation.
2680 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2681 struct dentry *dentry)
2683 struct btrfs_trans_handle *trans;
2684 struct btrfs_root *root = BTRFS_I(dir)->root;
2685 struct btrfs_path *path;
2686 struct btrfs_inode_ref *ref;
2687 struct btrfs_dir_item *di;
2688 struct inode *inode = dentry->d_inode;
2689 u64 index;
2690 int check_link = 1;
2691 int err = -ENOSPC;
2692 int ret;
2694 trans = btrfs_start_transaction(root, 10);
2695 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2696 return trans;
2698 if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2699 return ERR_PTR(-ENOSPC);
2701 /* check if there is someone else holds reference */
2702 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2703 return ERR_PTR(-ENOSPC);
2705 if (atomic_read(&inode->i_count) > 2)
2706 return ERR_PTR(-ENOSPC);
2708 if (xchg(&root->fs_info->enospc_unlink, 1))
2709 return ERR_PTR(-ENOSPC);
2711 path = btrfs_alloc_path();
2712 if (!path) {
2713 root->fs_info->enospc_unlink = 0;
2714 return ERR_PTR(-ENOMEM);
2717 trans = btrfs_start_transaction(root, 0);
2718 if (IS_ERR(trans)) {
2719 btrfs_free_path(path);
2720 root->fs_info->enospc_unlink = 0;
2721 return trans;
2724 path->skip_locking = 1;
2725 path->search_commit_root = 1;
2727 ret = btrfs_lookup_inode(trans, root, path,
2728 &BTRFS_I(dir)->location, 0);
2729 if (ret < 0) {
2730 err = ret;
2731 goto out;
2733 if (ret == 0) {
2734 if (check_path_shared(root, path))
2735 goto out;
2736 } else {
2737 check_link = 0;
2739 btrfs_release_path(root, path);
2741 ret = btrfs_lookup_inode(trans, root, path,
2742 &BTRFS_I(inode)->location, 0);
2743 if (ret < 0) {
2744 err = ret;
2745 goto out;
2747 if (ret == 0) {
2748 if (check_path_shared(root, path))
2749 goto out;
2750 } else {
2751 check_link = 0;
2753 btrfs_release_path(root, path);
2755 if (ret == 0 && S_ISREG(inode->i_mode)) {
2756 ret = btrfs_lookup_file_extent(trans, root, path,
2757 inode->i_ino, (u64)-1, 0);
2758 if (ret < 0) {
2759 err = ret;
2760 goto out;
2762 BUG_ON(ret == 0);
2763 if (check_path_shared(root, path))
2764 goto out;
2765 btrfs_release_path(root, path);
2768 if (!check_link) {
2769 err = 0;
2770 goto out;
2773 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2774 dentry->d_name.name, dentry->d_name.len, 0);
2775 if (IS_ERR(di)) {
2776 err = PTR_ERR(di);
2777 goto out;
2779 if (di) {
2780 if (check_path_shared(root, path))
2781 goto out;
2782 } else {
2783 err = 0;
2784 goto out;
2786 btrfs_release_path(root, path);
2788 ref = btrfs_lookup_inode_ref(trans, root, path,
2789 dentry->d_name.name, dentry->d_name.len,
2790 inode->i_ino, dir->i_ino, 0);
2791 if (IS_ERR(ref)) {
2792 err = PTR_ERR(ref);
2793 goto out;
2795 BUG_ON(!ref);
2796 if (check_path_shared(root, path))
2797 goto out;
2798 index = btrfs_inode_ref_index(path->nodes[0], ref);
2799 btrfs_release_path(root, path);
2801 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2802 dentry->d_name.name, dentry->d_name.len, 0);
2803 if (IS_ERR(di)) {
2804 err = PTR_ERR(di);
2805 goto out;
2807 BUG_ON(ret == -ENOENT);
2808 if (check_path_shared(root, path))
2809 goto out;
2811 err = 0;
2812 out:
2813 btrfs_free_path(path);
2814 if (err) {
2815 btrfs_end_transaction(trans, root);
2816 root->fs_info->enospc_unlink = 0;
2817 return ERR_PTR(err);
2820 trans->block_rsv = &root->fs_info->global_block_rsv;
2821 return trans;
2824 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2825 struct btrfs_root *root)
2827 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2828 BUG_ON(!root->fs_info->enospc_unlink);
2829 root->fs_info->enospc_unlink = 0;
2831 btrfs_end_transaction_throttle(trans, root);
2834 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2836 struct btrfs_root *root = BTRFS_I(dir)->root;
2837 struct btrfs_trans_handle *trans;
2838 struct inode *inode = dentry->d_inode;
2839 int ret;
2840 unsigned long nr = 0;
2842 trans = __unlink_start_trans(dir, dentry);
2843 if (IS_ERR(trans))
2844 return PTR_ERR(trans);
2846 btrfs_set_trans_block_group(trans, dir);
2848 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2850 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2851 dentry->d_name.name, dentry->d_name.len);
2852 BUG_ON(ret);
2854 if (inode->i_nlink == 0) {
2855 ret = btrfs_orphan_add(trans, inode);
2856 BUG_ON(ret);
2859 nr = trans->blocks_used;
2860 __unlink_end_trans(trans, root);
2861 btrfs_btree_balance_dirty(root, nr);
2862 return ret;
2865 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2866 struct btrfs_root *root,
2867 struct inode *dir, u64 objectid,
2868 const char *name, int name_len)
2870 struct btrfs_path *path;
2871 struct extent_buffer *leaf;
2872 struct btrfs_dir_item *di;
2873 struct btrfs_key key;
2874 u64 index;
2875 int ret;
2877 path = btrfs_alloc_path();
2878 if (!path)
2879 return -ENOMEM;
2881 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2882 name, name_len, -1);
2883 BUG_ON(!di || IS_ERR(di));
2885 leaf = path->nodes[0];
2886 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2887 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2888 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2889 BUG_ON(ret);
2890 btrfs_release_path(root, path);
2892 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2893 objectid, root->root_key.objectid,
2894 dir->i_ino, &index, name, name_len);
2895 if (ret < 0) {
2896 BUG_ON(ret != -ENOENT);
2897 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2898 name, name_len);
2899 BUG_ON(!di || IS_ERR(di));
2901 leaf = path->nodes[0];
2902 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2903 btrfs_release_path(root, path);
2904 index = key.offset;
2907 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2908 index, name, name_len, -1);
2909 BUG_ON(!di || IS_ERR(di));
2911 leaf = path->nodes[0];
2912 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2913 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2914 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2915 BUG_ON(ret);
2916 btrfs_release_path(root, path);
2918 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2919 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2920 ret = btrfs_update_inode(trans, root, dir);
2921 BUG_ON(ret);
2923 btrfs_free_path(path);
2924 return 0;
2927 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2929 struct inode *inode = dentry->d_inode;
2930 int err = 0;
2931 struct btrfs_root *root = BTRFS_I(dir)->root;
2932 struct btrfs_trans_handle *trans;
2933 unsigned long nr = 0;
2935 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
2936 inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
2937 return -ENOTEMPTY;
2939 trans = __unlink_start_trans(dir, dentry);
2940 if (IS_ERR(trans))
2941 return PTR_ERR(trans);
2943 btrfs_set_trans_block_group(trans, dir);
2945 if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2946 err = btrfs_unlink_subvol(trans, root, dir,
2947 BTRFS_I(inode)->location.objectid,
2948 dentry->d_name.name,
2949 dentry->d_name.len);
2950 goto out;
2953 err = btrfs_orphan_add(trans, inode);
2954 if (err)
2955 goto out;
2957 /* now the directory is empty */
2958 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2959 dentry->d_name.name, dentry->d_name.len);
2960 if (!err)
2961 btrfs_i_size_write(inode, 0);
2962 out:
2963 nr = trans->blocks_used;
2964 __unlink_end_trans(trans, root);
2965 btrfs_btree_balance_dirty(root, nr);
2967 return err;
2972 * this can truncate away extent items, csum items and directory items.
2973 * It starts at a high offset and removes keys until it can't find
2974 * any higher than new_size
2976 * csum items that cross the new i_size are truncated to the new size
2977 * as well.
2979 * min_type is the minimum key type to truncate down to. If set to 0, this
2980 * will kill all the items on this inode, including the INODE_ITEM_KEY.
2982 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2983 struct btrfs_root *root,
2984 struct inode *inode,
2985 u64 new_size, u32 min_type)
2987 struct btrfs_path *path;
2988 struct extent_buffer *leaf;
2989 struct btrfs_file_extent_item *fi;
2990 struct btrfs_key key;
2991 struct btrfs_key found_key;
2992 u64 extent_start = 0;
2993 u64 extent_num_bytes = 0;
2994 u64 extent_offset = 0;
2995 u64 item_end = 0;
2996 u64 mask = root->sectorsize - 1;
2997 u32 found_type = (u8)-1;
2998 int found_extent;
2999 int del_item;
3000 int pending_del_nr = 0;
3001 int pending_del_slot = 0;
3002 int extent_type = -1;
3003 int encoding;
3004 int ret;
3005 int err = 0;
3007 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3009 if (root->ref_cows)
3010 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3012 path = btrfs_alloc_path();
3013 BUG_ON(!path);
3014 path->reada = -1;
3016 key.objectid = inode->i_ino;
3017 key.offset = (u64)-1;
3018 key.type = (u8)-1;
3020 search_again:
3021 path->leave_spinning = 1;
3022 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3023 if (ret < 0) {
3024 err = ret;
3025 goto out;
3028 if (ret > 0) {
3029 /* there are no items in the tree for us to truncate, we're
3030 * done
3032 if (path->slots[0] == 0)
3033 goto out;
3034 path->slots[0]--;
3037 while (1) {
3038 fi = NULL;
3039 leaf = path->nodes[0];
3040 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3041 found_type = btrfs_key_type(&found_key);
3042 encoding = 0;
3044 if (found_key.objectid != inode->i_ino)
3045 break;
3047 if (found_type < min_type)
3048 break;
3050 item_end = found_key.offset;
3051 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3052 fi = btrfs_item_ptr(leaf, path->slots[0],
3053 struct btrfs_file_extent_item);
3054 extent_type = btrfs_file_extent_type(leaf, fi);
3055 encoding = btrfs_file_extent_compression(leaf, fi);
3056 encoding |= btrfs_file_extent_encryption(leaf, fi);
3057 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3059 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3060 item_end +=
3061 btrfs_file_extent_num_bytes(leaf, fi);
3062 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3063 item_end += btrfs_file_extent_inline_len(leaf,
3064 fi);
3066 item_end--;
3068 if (found_type > min_type) {
3069 del_item = 1;
3070 } else {
3071 if (item_end < new_size)
3072 break;
3073 if (found_key.offset >= new_size)
3074 del_item = 1;
3075 else
3076 del_item = 0;
3078 found_extent = 0;
3079 if (found_type != BTRFS_EXTENT_DATA_KEY)
3080 goto delete;
3082 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3083 u64 num_dec;
3084 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3085 if (!del_item && !encoding) {
3086 u64 orig_num_bytes =
3087 btrfs_file_extent_num_bytes(leaf, fi);
3088 extent_num_bytes = new_size -
3089 found_key.offset + root->sectorsize - 1;
3090 extent_num_bytes = extent_num_bytes &
3091 ~((u64)root->sectorsize - 1);
3092 btrfs_set_file_extent_num_bytes(leaf, fi,
3093 extent_num_bytes);
3094 num_dec = (orig_num_bytes -
3095 extent_num_bytes);
3096 if (root->ref_cows && extent_start != 0)
3097 inode_sub_bytes(inode, num_dec);
3098 btrfs_mark_buffer_dirty(leaf);
3099 } else {
3100 extent_num_bytes =
3101 btrfs_file_extent_disk_num_bytes(leaf,
3102 fi);
3103 extent_offset = found_key.offset -
3104 btrfs_file_extent_offset(leaf, fi);
3106 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3107 if (extent_start != 0) {
3108 found_extent = 1;
3109 if (root->ref_cows)
3110 inode_sub_bytes(inode, num_dec);
3113 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3115 * we can't truncate inline items that have had
3116 * special encodings
3118 if (!del_item &&
3119 btrfs_file_extent_compression(leaf, fi) == 0 &&
3120 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3121 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3122 u32 size = new_size - found_key.offset;
3124 if (root->ref_cows) {
3125 inode_sub_bytes(inode, item_end + 1 -
3126 new_size);
3128 size =
3129 btrfs_file_extent_calc_inline_size(size);
3130 ret = btrfs_truncate_item(trans, root, path,
3131 size, 1);
3132 BUG_ON(ret);
3133 } else if (root->ref_cows) {
3134 inode_sub_bytes(inode, item_end + 1 -
3135 found_key.offset);
3138 delete:
3139 if (del_item) {
3140 if (!pending_del_nr) {
3141 /* no pending yet, add ourselves */
3142 pending_del_slot = path->slots[0];
3143 pending_del_nr = 1;
3144 } else if (pending_del_nr &&
3145 path->slots[0] + 1 == pending_del_slot) {
3146 /* hop on the pending chunk */
3147 pending_del_nr++;
3148 pending_del_slot = path->slots[0];
3149 } else {
3150 BUG();
3152 } else {
3153 break;
3155 if (found_extent && root->ref_cows) {
3156 btrfs_set_path_blocking(path);
3157 ret = btrfs_free_extent(trans, root, extent_start,
3158 extent_num_bytes, 0,
3159 btrfs_header_owner(leaf),
3160 inode->i_ino, extent_offset);
3161 BUG_ON(ret);
3164 if (found_type == BTRFS_INODE_ITEM_KEY)
3165 break;
3167 if (path->slots[0] == 0 ||
3168 path->slots[0] != pending_del_slot) {
3169 if (root->ref_cows) {
3170 err = -EAGAIN;
3171 goto out;
3173 if (pending_del_nr) {
3174 ret = btrfs_del_items(trans, root, path,
3175 pending_del_slot,
3176 pending_del_nr);
3177 BUG_ON(ret);
3178 pending_del_nr = 0;
3180 btrfs_release_path(root, path);
3181 goto search_again;
3182 } else {
3183 path->slots[0]--;
3186 out:
3187 if (pending_del_nr) {
3188 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3189 pending_del_nr);
3190 BUG_ON(ret);
3192 btrfs_free_path(path);
3193 return err;
3197 * taken from block_truncate_page, but does cow as it zeros out
3198 * any bytes left in the last page in the file.
3200 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3202 struct inode *inode = mapping->host;
3203 struct btrfs_root *root = BTRFS_I(inode)->root;
3204 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3205 struct btrfs_ordered_extent *ordered;
3206 struct extent_state *cached_state = NULL;
3207 char *kaddr;
3208 u32 blocksize = root->sectorsize;
3209 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3210 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3211 struct page *page;
3212 int ret = 0;
3213 u64 page_start;
3214 u64 page_end;
3216 if ((offset & (blocksize - 1)) == 0)
3217 goto out;
3218 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3219 if (ret)
3220 goto out;
3222 ret = -ENOMEM;
3223 again:
3224 page = grab_cache_page(mapping, index);
3225 if (!page) {
3226 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3227 goto out;
3230 page_start = page_offset(page);
3231 page_end = page_start + PAGE_CACHE_SIZE - 1;
3233 if (!PageUptodate(page)) {
3234 ret = btrfs_readpage(NULL, page);
3235 lock_page(page);
3236 if (page->mapping != mapping) {
3237 unlock_page(page);
3238 page_cache_release(page);
3239 goto again;
3241 if (!PageUptodate(page)) {
3242 ret = -EIO;
3243 goto out_unlock;
3246 wait_on_page_writeback(page);
3248 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3249 GFP_NOFS);
3250 set_page_extent_mapped(page);
3252 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3253 if (ordered) {
3254 unlock_extent_cached(io_tree, page_start, page_end,
3255 &cached_state, GFP_NOFS);
3256 unlock_page(page);
3257 page_cache_release(page);
3258 btrfs_start_ordered_extent(inode, ordered, 1);
3259 btrfs_put_ordered_extent(ordered);
3260 goto again;
3263 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3264 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3265 0, 0, &cached_state, GFP_NOFS);
3267 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3268 &cached_state);
3269 if (ret) {
3270 unlock_extent_cached(io_tree, page_start, page_end,
3271 &cached_state, GFP_NOFS);
3272 goto out_unlock;
3275 ret = 0;
3276 if (offset != PAGE_CACHE_SIZE) {
3277 kaddr = kmap(page);
3278 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3279 flush_dcache_page(page);
3280 kunmap(page);
3282 ClearPageChecked(page);
3283 set_page_dirty(page);
3284 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3285 GFP_NOFS);
3287 out_unlock:
3288 if (ret)
3289 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3290 unlock_page(page);
3291 page_cache_release(page);
3292 out:
3293 return ret;
3296 int btrfs_cont_expand(struct inode *inode, loff_t size)
3298 struct btrfs_trans_handle *trans;
3299 struct btrfs_root *root = BTRFS_I(inode)->root;
3300 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3301 struct extent_map *em = NULL;
3302 struct extent_state *cached_state = NULL;
3303 u64 mask = root->sectorsize - 1;
3304 u64 hole_start = (inode->i_size + mask) & ~mask;
3305 u64 block_end = (size + mask) & ~mask;
3306 u64 last_byte;
3307 u64 cur_offset;
3308 u64 hole_size;
3309 int err = 0;
3311 if (size <= hole_start)
3312 return 0;
3314 while (1) {
3315 struct btrfs_ordered_extent *ordered;
3316 btrfs_wait_ordered_range(inode, hole_start,
3317 block_end - hole_start);
3318 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3319 &cached_state, GFP_NOFS);
3320 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3321 if (!ordered)
3322 break;
3323 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3324 &cached_state, GFP_NOFS);
3325 btrfs_put_ordered_extent(ordered);
3328 cur_offset = hole_start;
3329 while (1) {
3330 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3331 block_end - cur_offset, 0);
3332 BUG_ON(IS_ERR(em) || !em);
3333 last_byte = min(extent_map_end(em), block_end);
3334 last_byte = (last_byte + mask) & ~mask;
3335 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3336 u64 hint_byte = 0;
3337 hole_size = last_byte - cur_offset;
3339 trans = btrfs_start_transaction(root, 2);
3340 if (IS_ERR(trans)) {
3341 err = PTR_ERR(trans);
3342 break;
3344 btrfs_set_trans_block_group(trans, inode);
3346 err = btrfs_drop_extents(trans, inode, cur_offset,
3347 cur_offset + hole_size,
3348 &hint_byte, 1);
3349 BUG_ON(err);
3351 err = btrfs_insert_file_extent(trans, root,
3352 inode->i_ino, cur_offset, 0,
3353 0, hole_size, 0, hole_size,
3354 0, 0, 0);
3355 BUG_ON(err);
3357 btrfs_drop_extent_cache(inode, hole_start,
3358 last_byte - 1, 0);
3360 btrfs_end_transaction(trans, root);
3362 free_extent_map(em);
3363 em = NULL;
3364 cur_offset = last_byte;
3365 if (cur_offset >= block_end)
3366 break;
3369 free_extent_map(em);
3370 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3371 GFP_NOFS);
3372 return err;
3375 static int btrfs_setattr_size(struct inode *inode, struct iattr *attr)
3377 struct btrfs_root *root = BTRFS_I(inode)->root;
3378 struct btrfs_trans_handle *trans;
3379 unsigned long nr;
3380 int ret;
3382 if (attr->ia_size == inode->i_size)
3383 return 0;
3385 if (attr->ia_size > inode->i_size) {
3386 unsigned long limit;
3387 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
3388 if (attr->ia_size > inode->i_sb->s_maxbytes)
3389 return -EFBIG;
3390 if (limit != RLIM_INFINITY && attr->ia_size > limit) {
3391 send_sig(SIGXFSZ, current, 0);
3392 return -EFBIG;
3396 trans = btrfs_start_transaction(root, 5);
3397 if (IS_ERR(trans))
3398 return PTR_ERR(trans);
3400 btrfs_set_trans_block_group(trans, inode);
3402 ret = btrfs_orphan_add(trans, inode);
3403 BUG_ON(ret);
3405 nr = trans->blocks_used;
3406 btrfs_end_transaction(trans, root);
3407 btrfs_btree_balance_dirty(root, nr);
3409 if (attr->ia_size > inode->i_size) {
3410 ret = btrfs_cont_expand(inode, attr->ia_size);
3411 if (ret) {
3412 btrfs_truncate(inode);
3413 return ret;
3416 i_size_write(inode, attr->ia_size);
3417 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
3419 trans = btrfs_start_transaction(root, 0);
3420 BUG_ON(IS_ERR(trans));
3421 btrfs_set_trans_block_group(trans, inode);
3422 trans->block_rsv = root->orphan_block_rsv;
3423 BUG_ON(!trans->block_rsv);
3425 ret = btrfs_update_inode(trans, root, inode);
3426 BUG_ON(ret);
3427 if (inode->i_nlink > 0) {
3428 ret = btrfs_orphan_del(trans, inode);
3429 BUG_ON(ret);
3431 nr = trans->blocks_used;
3432 btrfs_end_transaction(trans, root);
3433 btrfs_btree_balance_dirty(root, nr);
3434 return 0;
3438 * We're truncating a file that used to have good data down to
3439 * zero. Make sure it gets into the ordered flush list so that
3440 * any new writes get down to disk quickly.
3442 if (attr->ia_size == 0)
3443 BTRFS_I(inode)->ordered_data_close = 1;
3445 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3446 ret = vmtruncate(inode, attr->ia_size);
3447 BUG_ON(ret);
3449 return 0;
3452 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3454 struct inode *inode = dentry->d_inode;
3455 int err;
3457 err = inode_change_ok(inode, attr);
3458 if (err)
3459 return err;
3461 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3462 err = btrfs_setattr_size(inode, attr);
3463 if (err)
3464 return err;
3467 if (attr->ia_valid) {
3468 setattr_copy(inode, attr);
3469 mark_inode_dirty(inode);
3471 if (attr->ia_valid & ATTR_MODE)
3472 err = btrfs_acl_chmod(inode);
3475 return err;
3478 void btrfs_evict_inode(struct inode *inode)
3480 struct btrfs_trans_handle *trans;
3481 struct btrfs_root *root = BTRFS_I(inode)->root;
3482 unsigned long nr;
3483 int ret;
3485 truncate_inode_pages(&inode->i_data, 0);
3486 if (inode->i_nlink && btrfs_root_refs(&root->root_item) != 0)
3487 goto no_delete;
3489 if (is_bad_inode(inode)) {
3490 btrfs_orphan_del(NULL, inode);
3491 goto no_delete;
3493 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3494 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3496 if (root->fs_info->log_root_recovering) {
3497 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3498 goto no_delete;
3501 if (inode->i_nlink > 0) {
3502 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3503 goto no_delete;
3506 btrfs_i_size_write(inode, 0);
3508 while (1) {
3509 trans = btrfs_start_transaction(root, 0);
3510 BUG_ON(IS_ERR(trans));
3511 btrfs_set_trans_block_group(trans, inode);
3512 trans->block_rsv = root->orphan_block_rsv;
3514 ret = btrfs_block_rsv_check(trans, root,
3515 root->orphan_block_rsv, 0, 5);
3516 if (ret) {
3517 BUG_ON(ret != -EAGAIN);
3518 ret = btrfs_commit_transaction(trans, root);
3519 BUG_ON(ret);
3520 continue;
3523 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3524 if (ret != -EAGAIN)
3525 break;
3527 nr = trans->blocks_used;
3528 btrfs_end_transaction(trans, root);
3529 trans = NULL;
3530 btrfs_btree_balance_dirty(root, nr);
3534 if (ret == 0) {
3535 ret = btrfs_orphan_del(trans, inode);
3536 BUG_ON(ret);
3539 nr = trans->blocks_used;
3540 btrfs_end_transaction(trans, root);
3541 btrfs_btree_balance_dirty(root, nr);
3542 no_delete:
3543 end_writeback(inode);
3544 return;
3548 * this returns the key found in the dir entry in the location pointer.
3549 * If no dir entries were found, location->objectid is 0.
3551 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3552 struct btrfs_key *location)
3554 const char *name = dentry->d_name.name;
3555 int namelen = dentry->d_name.len;
3556 struct btrfs_dir_item *di;
3557 struct btrfs_path *path;
3558 struct btrfs_root *root = BTRFS_I(dir)->root;
3559 int ret = 0;
3561 path = btrfs_alloc_path();
3562 BUG_ON(!path);
3564 di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3565 namelen, 0);
3566 if (IS_ERR(di))
3567 ret = PTR_ERR(di);
3569 if (!di || IS_ERR(di))
3570 goto out_err;
3572 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3573 out:
3574 btrfs_free_path(path);
3575 return ret;
3576 out_err:
3577 location->objectid = 0;
3578 goto out;
3582 * when we hit a tree root in a directory, the btrfs part of the inode
3583 * needs to be changed to reflect the root directory of the tree root. This
3584 * is kind of like crossing a mount point.
3586 static int fixup_tree_root_location(struct btrfs_root *root,
3587 struct inode *dir,
3588 struct dentry *dentry,
3589 struct btrfs_key *location,
3590 struct btrfs_root **sub_root)
3592 struct btrfs_path *path;
3593 struct btrfs_root *new_root;
3594 struct btrfs_root_ref *ref;
3595 struct extent_buffer *leaf;
3596 int ret;
3597 int err = 0;
3599 path = btrfs_alloc_path();
3600 if (!path) {
3601 err = -ENOMEM;
3602 goto out;
3605 err = -ENOENT;
3606 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3607 BTRFS_I(dir)->root->root_key.objectid,
3608 location->objectid);
3609 if (ret) {
3610 if (ret < 0)
3611 err = ret;
3612 goto out;
3615 leaf = path->nodes[0];
3616 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3617 if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3618 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3619 goto out;
3621 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3622 (unsigned long)(ref + 1),
3623 dentry->d_name.len);
3624 if (ret)
3625 goto out;
3627 btrfs_release_path(root->fs_info->tree_root, path);
3629 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3630 if (IS_ERR(new_root)) {
3631 err = PTR_ERR(new_root);
3632 goto out;
3635 if (btrfs_root_refs(&new_root->root_item) == 0) {
3636 err = -ENOENT;
3637 goto out;
3640 *sub_root = new_root;
3641 location->objectid = btrfs_root_dirid(&new_root->root_item);
3642 location->type = BTRFS_INODE_ITEM_KEY;
3643 location->offset = 0;
3644 err = 0;
3645 out:
3646 btrfs_free_path(path);
3647 return err;
3650 static void inode_tree_add(struct inode *inode)
3652 struct btrfs_root *root = BTRFS_I(inode)->root;
3653 struct btrfs_inode *entry;
3654 struct rb_node **p;
3655 struct rb_node *parent;
3656 again:
3657 p = &root->inode_tree.rb_node;
3658 parent = NULL;
3660 if (hlist_unhashed(&inode->i_hash))
3661 return;
3663 spin_lock(&root->inode_lock);
3664 while (*p) {
3665 parent = *p;
3666 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3668 if (inode->i_ino < entry->vfs_inode.i_ino)
3669 p = &parent->rb_left;
3670 else if (inode->i_ino > entry->vfs_inode.i_ino)
3671 p = &parent->rb_right;
3672 else {
3673 WARN_ON(!(entry->vfs_inode.i_state &
3674 (I_WILL_FREE | I_FREEING)));
3675 rb_erase(parent, &root->inode_tree);
3676 RB_CLEAR_NODE(parent);
3677 spin_unlock(&root->inode_lock);
3678 goto again;
3681 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3682 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3683 spin_unlock(&root->inode_lock);
3686 static void inode_tree_del(struct inode *inode)
3688 struct btrfs_root *root = BTRFS_I(inode)->root;
3689 int empty = 0;
3691 spin_lock(&root->inode_lock);
3692 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3693 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3694 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3695 empty = RB_EMPTY_ROOT(&root->inode_tree);
3697 spin_unlock(&root->inode_lock);
3699 if (empty && btrfs_root_refs(&root->root_item) == 0) {
3700 synchronize_srcu(&root->fs_info->subvol_srcu);
3701 spin_lock(&root->inode_lock);
3702 empty = RB_EMPTY_ROOT(&root->inode_tree);
3703 spin_unlock(&root->inode_lock);
3704 if (empty)
3705 btrfs_add_dead_root(root);
3709 int btrfs_invalidate_inodes(struct btrfs_root *root)
3711 struct rb_node *node;
3712 struct rb_node *prev;
3713 struct btrfs_inode *entry;
3714 struct inode *inode;
3715 u64 objectid = 0;
3717 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3719 spin_lock(&root->inode_lock);
3720 again:
3721 node = root->inode_tree.rb_node;
3722 prev = NULL;
3723 while (node) {
3724 prev = node;
3725 entry = rb_entry(node, struct btrfs_inode, rb_node);
3727 if (objectid < entry->vfs_inode.i_ino)
3728 node = node->rb_left;
3729 else if (objectid > entry->vfs_inode.i_ino)
3730 node = node->rb_right;
3731 else
3732 break;
3734 if (!node) {
3735 while (prev) {
3736 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3737 if (objectid <= entry->vfs_inode.i_ino) {
3738 node = prev;
3739 break;
3741 prev = rb_next(prev);
3744 while (node) {
3745 entry = rb_entry(node, struct btrfs_inode, rb_node);
3746 objectid = entry->vfs_inode.i_ino + 1;
3747 inode = igrab(&entry->vfs_inode);
3748 if (inode) {
3749 spin_unlock(&root->inode_lock);
3750 if (atomic_read(&inode->i_count) > 1)
3751 d_prune_aliases(inode);
3753 * btrfs_drop_inode will have it removed from
3754 * the inode cache when its usage count
3755 * hits zero.
3757 iput(inode);
3758 cond_resched();
3759 spin_lock(&root->inode_lock);
3760 goto again;
3763 if (cond_resched_lock(&root->inode_lock))
3764 goto again;
3766 node = rb_next(node);
3768 spin_unlock(&root->inode_lock);
3769 return 0;
3772 static int btrfs_init_locked_inode(struct inode *inode, void *p)
3774 struct btrfs_iget_args *args = p;
3775 inode->i_ino = args->ino;
3776 BTRFS_I(inode)->root = args->root;
3777 btrfs_set_inode_space_info(args->root, inode);
3778 return 0;
3781 static int btrfs_find_actor(struct inode *inode, void *opaque)
3783 struct btrfs_iget_args *args = opaque;
3784 return args->ino == inode->i_ino &&
3785 args->root == BTRFS_I(inode)->root;
3788 static struct inode *btrfs_iget_locked(struct super_block *s,
3789 u64 objectid,
3790 struct btrfs_root *root)
3792 struct inode *inode;
3793 struct btrfs_iget_args args;
3794 args.ino = objectid;
3795 args.root = root;
3797 inode = iget5_locked(s, objectid, btrfs_find_actor,
3798 btrfs_init_locked_inode,
3799 (void *)&args);
3800 return inode;
3803 /* Get an inode object given its location and corresponding root.
3804 * Returns in *is_new if the inode was read from disk
3806 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
3807 struct btrfs_root *root, int *new)
3809 struct inode *inode;
3811 inode = btrfs_iget_locked(s, location->objectid, root);
3812 if (!inode)
3813 return ERR_PTR(-ENOMEM);
3815 if (inode->i_state & I_NEW) {
3816 BTRFS_I(inode)->root = root;
3817 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3818 btrfs_read_locked_inode(inode);
3820 inode_tree_add(inode);
3821 unlock_new_inode(inode);
3822 if (new)
3823 *new = 1;
3826 return inode;
3829 static struct inode *new_simple_dir(struct super_block *s,
3830 struct btrfs_key *key,
3831 struct btrfs_root *root)
3833 struct inode *inode = new_inode(s);
3835 if (!inode)
3836 return ERR_PTR(-ENOMEM);
3838 BTRFS_I(inode)->root = root;
3839 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3840 BTRFS_I(inode)->dummy_inode = 1;
3842 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3843 inode->i_op = &simple_dir_inode_operations;
3844 inode->i_fop = &simple_dir_operations;
3845 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3846 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3848 return inode;
3851 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
3853 struct inode *inode;
3854 struct btrfs_root *root = BTRFS_I(dir)->root;
3855 struct btrfs_root *sub_root = root;
3856 struct btrfs_key location;
3857 int index;
3858 int ret;
3860 dentry->d_op = &btrfs_dentry_operations;
3862 if (dentry->d_name.len > BTRFS_NAME_LEN)
3863 return ERR_PTR(-ENAMETOOLONG);
3865 ret = btrfs_inode_by_name(dir, dentry, &location);
3867 if (ret < 0)
3868 return ERR_PTR(ret);
3870 if (location.objectid == 0)
3871 return NULL;
3873 if (location.type == BTRFS_INODE_ITEM_KEY) {
3874 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
3875 return inode;
3878 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
3880 index = srcu_read_lock(&root->fs_info->subvol_srcu);
3881 ret = fixup_tree_root_location(root, dir, dentry,
3882 &location, &sub_root);
3883 if (ret < 0) {
3884 if (ret != -ENOENT)
3885 inode = ERR_PTR(ret);
3886 else
3887 inode = new_simple_dir(dir->i_sb, &location, sub_root);
3888 } else {
3889 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
3891 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
3893 if (root != sub_root) {
3894 down_read(&root->fs_info->cleanup_work_sem);
3895 if (!(inode->i_sb->s_flags & MS_RDONLY))
3896 btrfs_orphan_cleanup(sub_root);
3897 up_read(&root->fs_info->cleanup_work_sem);
3900 return inode;
3903 static int btrfs_dentry_delete(struct dentry *dentry)
3905 struct btrfs_root *root;
3907 if (!dentry->d_inode && !IS_ROOT(dentry))
3908 dentry = dentry->d_parent;
3910 if (dentry->d_inode) {
3911 root = BTRFS_I(dentry->d_inode)->root;
3912 if (btrfs_root_refs(&root->root_item) == 0)
3913 return 1;
3915 return 0;
3918 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
3919 struct nameidata *nd)
3921 struct inode *inode;
3923 inode = btrfs_lookup_dentry(dir, dentry);
3924 if (IS_ERR(inode))
3925 return ERR_CAST(inode);
3927 return d_splice_alias(inode, dentry);
3930 static unsigned char btrfs_filetype_table[] = {
3931 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
3934 static int btrfs_real_readdir(struct file *filp, void *dirent,
3935 filldir_t filldir)
3937 struct inode *inode = filp->f_dentry->d_inode;
3938 struct btrfs_root *root = BTRFS_I(inode)->root;
3939 struct btrfs_item *item;
3940 struct btrfs_dir_item *di;
3941 struct btrfs_key key;
3942 struct btrfs_key found_key;
3943 struct btrfs_path *path;
3944 int ret;
3945 u32 nritems;
3946 struct extent_buffer *leaf;
3947 int slot;
3948 int advance;
3949 unsigned char d_type;
3950 int over = 0;
3951 u32 di_cur;
3952 u32 di_total;
3953 u32 di_len;
3954 int key_type = BTRFS_DIR_INDEX_KEY;
3955 char tmp_name[32];
3956 char *name_ptr;
3957 int name_len;
3959 if (root->fs_info->tree_root == root)
3960 key_type = BTRFS_DIR_ITEM_KEY;
3962 /* special case for "." */
3963 if (filp->f_pos == 0) {
3964 over = filldir(dirent, ".", 1,
3965 1, inode->i_ino,
3966 DT_DIR);
3967 if (over)
3968 return 0;
3969 filp->f_pos = 1;
3971 /* special case for .., just use the back ref */
3972 if (filp->f_pos == 1) {
3973 u64 pino = parent_ino(filp->f_path.dentry);
3974 over = filldir(dirent, "..", 2,
3975 2, pino, DT_DIR);
3976 if (over)
3977 return 0;
3978 filp->f_pos = 2;
3980 path = btrfs_alloc_path();
3981 path->reada = 2;
3983 btrfs_set_key_type(&key, key_type);
3984 key.offset = filp->f_pos;
3985 key.objectid = inode->i_ino;
3987 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3988 if (ret < 0)
3989 goto err;
3990 advance = 0;
3992 while (1) {
3993 leaf = path->nodes[0];
3994 nritems = btrfs_header_nritems(leaf);
3995 slot = path->slots[0];
3996 if (advance || slot >= nritems) {
3997 if (slot >= nritems - 1) {
3998 ret = btrfs_next_leaf(root, path);
3999 if (ret)
4000 break;
4001 leaf = path->nodes[0];
4002 nritems = btrfs_header_nritems(leaf);
4003 slot = path->slots[0];
4004 } else {
4005 slot++;
4006 path->slots[0]++;
4010 advance = 1;
4011 item = btrfs_item_nr(leaf, slot);
4012 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4014 if (found_key.objectid != key.objectid)
4015 break;
4016 if (btrfs_key_type(&found_key) != key_type)
4017 break;
4018 if (found_key.offset < filp->f_pos)
4019 continue;
4021 filp->f_pos = found_key.offset;
4023 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4024 di_cur = 0;
4025 di_total = btrfs_item_size(leaf, item);
4027 while (di_cur < di_total) {
4028 struct btrfs_key location;
4030 name_len = btrfs_dir_name_len(leaf, di);
4031 if (name_len <= sizeof(tmp_name)) {
4032 name_ptr = tmp_name;
4033 } else {
4034 name_ptr = kmalloc(name_len, GFP_NOFS);
4035 if (!name_ptr) {
4036 ret = -ENOMEM;
4037 goto err;
4040 read_extent_buffer(leaf, name_ptr,
4041 (unsigned long)(di + 1), name_len);
4043 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4044 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4046 /* is this a reference to our own snapshot? If so
4047 * skip it
4049 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4050 location.objectid == root->root_key.objectid) {
4051 over = 0;
4052 goto skip;
4054 over = filldir(dirent, name_ptr, name_len,
4055 found_key.offset, location.objectid,
4056 d_type);
4058 skip:
4059 if (name_ptr != tmp_name)
4060 kfree(name_ptr);
4062 if (over)
4063 goto nopos;
4064 di_len = btrfs_dir_name_len(leaf, di) +
4065 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4066 di_cur += di_len;
4067 di = (struct btrfs_dir_item *)((char *)di + di_len);
4071 /* Reached end of directory/root. Bump pos past the last item. */
4072 if (key_type == BTRFS_DIR_INDEX_KEY)
4074 * 32-bit glibc will use getdents64, but then strtol -
4075 * so the last number we can serve is this.
4077 filp->f_pos = 0x7fffffff;
4078 else
4079 filp->f_pos++;
4080 nopos:
4081 ret = 0;
4082 err:
4083 btrfs_free_path(path);
4084 return ret;
4087 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4089 struct btrfs_root *root = BTRFS_I(inode)->root;
4090 struct btrfs_trans_handle *trans;
4091 int ret = 0;
4093 if (BTRFS_I(inode)->dummy_inode)
4094 return 0;
4096 if (wbc->sync_mode == WB_SYNC_ALL) {
4097 trans = btrfs_join_transaction(root, 1);
4098 btrfs_set_trans_block_group(trans, inode);
4099 ret = btrfs_commit_transaction(trans, root);
4101 return ret;
4104 void btrfs_dirty_inode(struct inode *inode)
4106 struct btrfs_root *root = BTRFS_I(inode)->root;
4107 struct btrfs_trans_handle *trans;
4108 int ret;
4110 if (BTRFS_I(inode)->dummy_inode)
4111 return;
4113 trans = btrfs_join_transaction(root, 1);
4114 btrfs_set_trans_block_group(trans, inode);
4116 ret = btrfs_update_inode(trans, root, inode);
4117 if (ret && ret == -ENOSPC) {
4118 /* whoops, lets try again with the full transaction */
4119 btrfs_end_transaction(trans, root);
4120 trans = btrfs_start_transaction(root, 1);
4121 if (IS_ERR(trans)) {
4122 if (printk_ratelimit()) {
4123 printk(KERN_ERR "btrfs: fail to "
4124 "dirty inode %lu error %ld\n",
4125 inode->i_ino, PTR_ERR(trans));
4127 return;
4129 btrfs_set_trans_block_group(trans, inode);
4131 ret = btrfs_update_inode(trans, root, inode);
4132 if (ret) {
4133 if (printk_ratelimit()) {
4134 printk(KERN_ERR "btrfs: fail to "
4135 "dirty inode %lu error %d\n",
4136 inode->i_ino, ret);
4140 btrfs_end_transaction(trans, root);
4144 * find the highest existing sequence number in a directory
4145 * and then set the in-memory index_cnt variable to reflect
4146 * free sequence numbers
4148 static int btrfs_set_inode_index_count(struct inode *inode)
4150 struct btrfs_root *root = BTRFS_I(inode)->root;
4151 struct btrfs_key key, found_key;
4152 struct btrfs_path *path;
4153 struct extent_buffer *leaf;
4154 int ret;
4156 key.objectid = inode->i_ino;
4157 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4158 key.offset = (u64)-1;
4160 path = btrfs_alloc_path();
4161 if (!path)
4162 return -ENOMEM;
4164 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4165 if (ret < 0)
4166 goto out;
4167 if (ret == 0)
4168 goto out;
4169 ret = 0;
4172 * MAGIC NUMBER EXPLANATION:
4173 * since we search a directory based on f_pos we have to start at 2
4174 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4175 * else has to start at 2
4177 if (path->slots[0] == 0) {
4178 BTRFS_I(inode)->index_cnt = 2;
4179 goto out;
4182 path->slots[0]--;
4184 leaf = path->nodes[0];
4185 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4187 if (found_key.objectid != inode->i_ino ||
4188 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4189 BTRFS_I(inode)->index_cnt = 2;
4190 goto out;
4193 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4194 out:
4195 btrfs_free_path(path);
4196 return ret;
4200 * helper to find a free sequence number in a given directory. This current
4201 * code is very simple, later versions will do smarter things in the btree
4203 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4205 int ret = 0;
4207 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4208 ret = btrfs_set_inode_index_count(dir);
4209 if (ret)
4210 return ret;
4213 *index = BTRFS_I(dir)->index_cnt;
4214 BTRFS_I(dir)->index_cnt++;
4216 return ret;
4219 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4220 struct btrfs_root *root,
4221 struct inode *dir,
4222 const char *name, int name_len,
4223 u64 ref_objectid, u64 objectid,
4224 u64 alloc_hint, int mode, u64 *index)
4226 struct inode *inode;
4227 struct btrfs_inode_item *inode_item;
4228 struct btrfs_key *location;
4229 struct btrfs_path *path;
4230 struct btrfs_inode_ref *ref;
4231 struct btrfs_key key[2];
4232 u32 sizes[2];
4233 unsigned long ptr;
4234 int ret;
4235 int owner;
4237 path = btrfs_alloc_path();
4238 BUG_ON(!path);
4240 inode = new_inode(root->fs_info->sb);
4241 if (!inode)
4242 return ERR_PTR(-ENOMEM);
4244 if (dir) {
4245 ret = btrfs_set_inode_index(dir, index);
4246 if (ret) {
4247 iput(inode);
4248 return ERR_PTR(ret);
4252 * index_cnt is ignored for everything but a dir,
4253 * btrfs_get_inode_index_count has an explanation for the magic
4254 * number
4256 BTRFS_I(inode)->index_cnt = 2;
4257 BTRFS_I(inode)->root = root;
4258 BTRFS_I(inode)->generation = trans->transid;
4259 btrfs_set_inode_space_info(root, inode);
4261 if (mode & S_IFDIR)
4262 owner = 0;
4263 else
4264 owner = 1;
4265 BTRFS_I(inode)->block_group =
4266 btrfs_find_block_group(root, 0, alloc_hint, owner);
4268 key[0].objectid = objectid;
4269 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4270 key[0].offset = 0;
4272 key[1].objectid = objectid;
4273 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4274 key[1].offset = ref_objectid;
4276 sizes[0] = sizeof(struct btrfs_inode_item);
4277 sizes[1] = name_len + sizeof(*ref);
4279 path->leave_spinning = 1;
4280 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4281 if (ret != 0)
4282 goto fail;
4284 inode_init_owner(inode, dir, mode);
4285 inode->i_ino = objectid;
4286 inode_set_bytes(inode, 0);
4287 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4288 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4289 struct btrfs_inode_item);
4290 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4292 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4293 struct btrfs_inode_ref);
4294 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4295 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4296 ptr = (unsigned long)(ref + 1);
4297 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4299 btrfs_mark_buffer_dirty(path->nodes[0]);
4300 btrfs_free_path(path);
4302 location = &BTRFS_I(inode)->location;
4303 location->objectid = objectid;
4304 location->offset = 0;
4305 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4307 btrfs_inherit_iflags(inode, dir);
4309 if ((mode & S_IFREG)) {
4310 if (btrfs_test_opt(root, NODATASUM))
4311 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4312 if (btrfs_test_opt(root, NODATACOW))
4313 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4316 insert_inode_hash(inode);
4317 inode_tree_add(inode);
4318 return inode;
4319 fail:
4320 if (dir)
4321 BTRFS_I(dir)->index_cnt--;
4322 btrfs_free_path(path);
4323 iput(inode);
4324 return ERR_PTR(ret);
4327 static inline u8 btrfs_inode_type(struct inode *inode)
4329 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4333 * utility function to add 'inode' into 'parent_inode' with
4334 * a give name and a given sequence number.
4335 * if 'add_backref' is true, also insert a backref from the
4336 * inode to the parent directory.
4338 int btrfs_add_link(struct btrfs_trans_handle *trans,
4339 struct inode *parent_inode, struct inode *inode,
4340 const char *name, int name_len, int add_backref, u64 index)
4342 int ret = 0;
4343 struct btrfs_key key;
4344 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4346 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4347 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4348 } else {
4349 key.objectid = inode->i_ino;
4350 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4351 key.offset = 0;
4354 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4355 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4356 key.objectid, root->root_key.objectid,
4357 parent_inode->i_ino,
4358 index, name, name_len);
4359 } else if (add_backref) {
4360 ret = btrfs_insert_inode_ref(trans, root,
4361 name, name_len, inode->i_ino,
4362 parent_inode->i_ino, index);
4365 if (ret == 0) {
4366 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4367 parent_inode->i_ino, &key,
4368 btrfs_inode_type(inode), index);
4369 BUG_ON(ret);
4371 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4372 name_len * 2);
4373 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4374 ret = btrfs_update_inode(trans, root, parent_inode);
4376 return ret;
4379 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4380 struct dentry *dentry, struct inode *inode,
4381 int backref, u64 index)
4383 int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4384 inode, dentry->d_name.name,
4385 dentry->d_name.len, backref, index);
4386 if (!err) {
4387 d_instantiate(dentry, inode);
4388 return 0;
4390 if (err > 0)
4391 err = -EEXIST;
4392 return err;
4395 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4396 int mode, dev_t rdev)
4398 struct btrfs_trans_handle *trans;
4399 struct btrfs_root *root = BTRFS_I(dir)->root;
4400 struct inode *inode = NULL;
4401 int err;
4402 int drop_inode = 0;
4403 u64 objectid;
4404 unsigned long nr = 0;
4405 u64 index = 0;
4407 if (!new_valid_dev(rdev))
4408 return -EINVAL;
4410 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4411 if (err)
4412 return err;
4415 * 2 for inode item and ref
4416 * 2 for dir items
4417 * 1 for xattr if selinux is on
4419 trans = btrfs_start_transaction(root, 5);
4420 if (IS_ERR(trans))
4421 return PTR_ERR(trans);
4423 btrfs_set_trans_block_group(trans, dir);
4425 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4426 dentry->d_name.len,
4427 dentry->d_parent->d_inode->i_ino, objectid,
4428 BTRFS_I(dir)->block_group, mode, &index);
4429 err = PTR_ERR(inode);
4430 if (IS_ERR(inode))
4431 goto out_unlock;
4433 err = btrfs_init_inode_security(trans, inode, dir);
4434 if (err) {
4435 drop_inode = 1;
4436 goto out_unlock;
4439 btrfs_set_trans_block_group(trans, inode);
4440 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4441 if (err)
4442 drop_inode = 1;
4443 else {
4444 inode->i_op = &btrfs_special_inode_operations;
4445 init_special_inode(inode, inode->i_mode, rdev);
4446 btrfs_update_inode(trans, root, inode);
4448 btrfs_update_inode_block_group(trans, inode);
4449 btrfs_update_inode_block_group(trans, dir);
4450 out_unlock:
4451 nr = trans->blocks_used;
4452 btrfs_end_transaction_throttle(trans, root);
4453 btrfs_btree_balance_dirty(root, nr);
4454 if (drop_inode) {
4455 inode_dec_link_count(inode);
4456 iput(inode);
4458 return err;
4461 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4462 int mode, struct nameidata *nd)
4464 struct btrfs_trans_handle *trans;
4465 struct btrfs_root *root = BTRFS_I(dir)->root;
4466 struct inode *inode = NULL;
4467 int drop_inode = 0;
4468 int err;
4469 unsigned long nr = 0;
4470 u64 objectid;
4471 u64 index = 0;
4473 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4474 if (err)
4475 return err;
4477 * 2 for inode item and ref
4478 * 2 for dir items
4479 * 1 for xattr if selinux is on
4481 trans = btrfs_start_transaction(root, 5);
4482 if (IS_ERR(trans))
4483 return PTR_ERR(trans);
4485 btrfs_set_trans_block_group(trans, dir);
4487 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4488 dentry->d_name.len,
4489 dentry->d_parent->d_inode->i_ino,
4490 objectid, BTRFS_I(dir)->block_group, mode,
4491 &index);
4492 err = PTR_ERR(inode);
4493 if (IS_ERR(inode))
4494 goto out_unlock;
4496 err = btrfs_init_inode_security(trans, inode, dir);
4497 if (err) {
4498 drop_inode = 1;
4499 goto out_unlock;
4502 btrfs_set_trans_block_group(trans, inode);
4503 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
4504 if (err)
4505 drop_inode = 1;
4506 else {
4507 inode->i_mapping->a_ops = &btrfs_aops;
4508 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4509 inode->i_fop = &btrfs_file_operations;
4510 inode->i_op = &btrfs_file_inode_operations;
4511 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4513 btrfs_update_inode_block_group(trans, inode);
4514 btrfs_update_inode_block_group(trans, dir);
4515 out_unlock:
4516 nr = trans->blocks_used;
4517 btrfs_end_transaction_throttle(trans, root);
4518 if (drop_inode) {
4519 inode_dec_link_count(inode);
4520 iput(inode);
4522 btrfs_btree_balance_dirty(root, nr);
4523 return err;
4526 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4527 struct dentry *dentry)
4529 struct btrfs_trans_handle *trans;
4530 struct btrfs_root *root = BTRFS_I(dir)->root;
4531 struct inode *inode = old_dentry->d_inode;
4532 u64 index;
4533 unsigned long nr = 0;
4534 int err;
4535 int drop_inode = 0;
4537 if (inode->i_nlink == 0)
4538 return -ENOENT;
4540 /* do not allow sys_link's with other subvols of the same device */
4541 if (root->objectid != BTRFS_I(inode)->root->objectid)
4542 return -EPERM;
4544 btrfs_inc_nlink(inode);
4546 err = btrfs_set_inode_index(dir, &index);
4547 if (err)
4548 goto fail;
4551 * 1 item for inode ref
4552 * 2 items for dir items
4554 trans = btrfs_start_transaction(root, 3);
4555 if (IS_ERR(trans)) {
4556 err = PTR_ERR(trans);
4557 goto fail;
4560 btrfs_set_trans_block_group(trans, dir);
4561 atomic_inc(&inode->i_count);
4563 err = btrfs_add_nondir(trans, dentry, inode, 1, index);
4565 if (err) {
4566 drop_inode = 1;
4567 } else {
4568 btrfs_update_inode_block_group(trans, dir);
4569 err = btrfs_update_inode(trans, root, inode);
4570 BUG_ON(err);
4571 btrfs_log_new_name(trans, inode, NULL, dentry->d_parent);
4574 nr = trans->blocks_used;
4575 btrfs_end_transaction_throttle(trans, root);
4576 fail:
4577 if (drop_inode) {
4578 inode_dec_link_count(inode);
4579 iput(inode);
4581 btrfs_btree_balance_dirty(root, nr);
4582 return err;
4585 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4587 struct inode *inode = NULL;
4588 struct btrfs_trans_handle *trans;
4589 struct btrfs_root *root = BTRFS_I(dir)->root;
4590 int err = 0;
4591 int drop_on_err = 0;
4592 u64 objectid = 0;
4593 u64 index = 0;
4594 unsigned long nr = 1;
4596 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4597 if (err)
4598 return err;
4601 * 2 items for inode and ref
4602 * 2 items for dir items
4603 * 1 for xattr if selinux is on
4605 trans = btrfs_start_transaction(root, 5);
4606 if (IS_ERR(trans))
4607 return PTR_ERR(trans);
4608 btrfs_set_trans_block_group(trans, dir);
4610 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4611 dentry->d_name.len,
4612 dentry->d_parent->d_inode->i_ino, objectid,
4613 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4614 &index);
4615 if (IS_ERR(inode)) {
4616 err = PTR_ERR(inode);
4617 goto out_fail;
4620 drop_on_err = 1;
4622 err = btrfs_init_inode_security(trans, inode, dir);
4623 if (err)
4624 goto out_fail;
4626 inode->i_op = &btrfs_dir_inode_operations;
4627 inode->i_fop = &btrfs_dir_file_operations;
4628 btrfs_set_trans_block_group(trans, inode);
4630 btrfs_i_size_write(inode, 0);
4631 err = btrfs_update_inode(trans, root, inode);
4632 if (err)
4633 goto out_fail;
4635 err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4636 inode, dentry->d_name.name,
4637 dentry->d_name.len, 0, index);
4638 if (err)
4639 goto out_fail;
4641 d_instantiate(dentry, inode);
4642 drop_on_err = 0;
4643 btrfs_update_inode_block_group(trans, inode);
4644 btrfs_update_inode_block_group(trans, dir);
4646 out_fail:
4647 nr = trans->blocks_used;
4648 btrfs_end_transaction_throttle(trans, root);
4649 if (drop_on_err)
4650 iput(inode);
4651 btrfs_btree_balance_dirty(root, nr);
4652 return err;
4655 /* helper for btfs_get_extent. Given an existing extent in the tree,
4656 * and an extent that you want to insert, deal with overlap and insert
4657 * the new extent into the tree.
4659 static int merge_extent_mapping(struct extent_map_tree *em_tree,
4660 struct extent_map *existing,
4661 struct extent_map *em,
4662 u64 map_start, u64 map_len)
4664 u64 start_diff;
4666 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4667 start_diff = map_start - em->start;
4668 em->start = map_start;
4669 em->len = map_len;
4670 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4671 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
4672 em->block_start += start_diff;
4673 em->block_len -= start_diff;
4675 return add_extent_mapping(em_tree, em);
4678 static noinline int uncompress_inline(struct btrfs_path *path,
4679 struct inode *inode, struct page *page,
4680 size_t pg_offset, u64 extent_offset,
4681 struct btrfs_file_extent_item *item)
4683 int ret;
4684 struct extent_buffer *leaf = path->nodes[0];
4685 char *tmp;
4686 size_t max_size;
4687 unsigned long inline_size;
4688 unsigned long ptr;
4690 WARN_ON(pg_offset != 0);
4691 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4692 inline_size = btrfs_file_extent_inline_item_len(leaf,
4693 btrfs_item_nr(leaf, path->slots[0]));
4694 tmp = kmalloc(inline_size, GFP_NOFS);
4695 ptr = btrfs_file_extent_inline_start(item);
4697 read_extent_buffer(leaf, tmp, ptr, inline_size);
4699 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
4700 ret = btrfs_zlib_decompress(tmp, page, extent_offset,
4701 inline_size, max_size);
4702 if (ret) {
4703 char *kaddr = kmap_atomic(page, KM_USER0);
4704 unsigned long copy_size = min_t(u64,
4705 PAGE_CACHE_SIZE - pg_offset,
4706 max_size - extent_offset);
4707 memset(kaddr + pg_offset, 0, copy_size);
4708 kunmap_atomic(kaddr, KM_USER0);
4710 kfree(tmp);
4711 return 0;
4715 * a bit scary, this does extent mapping from logical file offset to the disk.
4716 * the ugly parts come from merging extents from the disk with the in-ram
4717 * representation. This gets more complex because of the data=ordered code,
4718 * where the in-ram extents might be locked pending data=ordered completion.
4720 * This also copies inline extents directly into the page.
4723 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
4724 size_t pg_offset, u64 start, u64 len,
4725 int create)
4727 int ret;
4728 int err = 0;
4729 u64 bytenr;
4730 u64 extent_start = 0;
4731 u64 extent_end = 0;
4732 u64 objectid = inode->i_ino;
4733 u32 found_type;
4734 struct btrfs_path *path = NULL;
4735 struct btrfs_root *root = BTRFS_I(inode)->root;
4736 struct btrfs_file_extent_item *item;
4737 struct extent_buffer *leaf;
4738 struct btrfs_key found_key;
4739 struct extent_map *em = NULL;
4740 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4741 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4742 struct btrfs_trans_handle *trans = NULL;
4743 int compressed;
4745 again:
4746 read_lock(&em_tree->lock);
4747 em = lookup_extent_mapping(em_tree, start, len);
4748 if (em)
4749 em->bdev = root->fs_info->fs_devices->latest_bdev;
4750 read_unlock(&em_tree->lock);
4752 if (em) {
4753 if (em->start > start || em->start + em->len <= start)
4754 free_extent_map(em);
4755 else if (em->block_start == EXTENT_MAP_INLINE && page)
4756 free_extent_map(em);
4757 else
4758 goto out;
4760 em = alloc_extent_map(GFP_NOFS);
4761 if (!em) {
4762 err = -ENOMEM;
4763 goto out;
4765 em->bdev = root->fs_info->fs_devices->latest_bdev;
4766 em->start = EXTENT_MAP_HOLE;
4767 em->orig_start = EXTENT_MAP_HOLE;
4768 em->len = (u64)-1;
4769 em->block_len = (u64)-1;
4771 if (!path) {
4772 path = btrfs_alloc_path();
4773 BUG_ON(!path);
4776 ret = btrfs_lookup_file_extent(trans, root, path,
4777 objectid, start, trans != NULL);
4778 if (ret < 0) {
4779 err = ret;
4780 goto out;
4783 if (ret != 0) {
4784 if (path->slots[0] == 0)
4785 goto not_found;
4786 path->slots[0]--;
4789 leaf = path->nodes[0];
4790 item = btrfs_item_ptr(leaf, path->slots[0],
4791 struct btrfs_file_extent_item);
4792 /* are we inside the extent that was found? */
4793 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4794 found_type = btrfs_key_type(&found_key);
4795 if (found_key.objectid != objectid ||
4796 found_type != BTRFS_EXTENT_DATA_KEY) {
4797 goto not_found;
4800 found_type = btrfs_file_extent_type(leaf, item);
4801 extent_start = found_key.offset;
4802 compressed = btrfs_file_extent_compression(leaf, item);
4803 if (found_type == BTRFS_FILE_EXTENT_REG ||
4804 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4805 extent_end = extent_start +
4806 btrfs_file_extent_num_bytes(leaf, item);
4807 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4808 size_t size;
4809 size = btrfs_file_extent_inline_len(leaf, item);
4810 extent_end = (extent_start + size + root->sectorsize - 1) &
4811 ~((u64)root->sectorsize - 1);
4814 if (start >= extent_end) {
4815 path->slots[0]++;
4816 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4817 ret = btrfs_next_leaf(root, path);
4818 if (ret < 0) {
4819 err = ret;
4820 goto out;
4822 if (ret > 0)
4823 goto not_found;
4824 leaf = path->nodes[0];
4826 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4827 if (found_key.objectid != objectid ||
4828 found_key.type != BTRFS_EXTENT_DATA_KEY)
4829 goto not_found;
4830 if (start + len <= found_key.offset)
4831 goto not_found;
4832 em->start = start;
4833 em->len = found_key.offset - start;
4834 goto not_found_em;
4837 if (found_type == BTRFS_FILE_EXTENT_REG ||
4838 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
4839 em->start = extent_start;
4840 em->len = extent_end - extent_start;
4841 em->orig_start = extent_start -
4842 btrfs_file_extent_offset(leaf, item);
4843 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
4844 if (bytenr == 0) {
4845 em->block_start = EXTENT_MAP_HOLE;
4846 goto insert;
4848 if (compressed) {
4849 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4850 em->block_start = bytenr;
4851 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
4852 item);
4853 } else {
4854 bytenr += btrfs_file_extent_offset(leaf, item);
4855 em->block_start = bytenr;
4856 em->block_len = em->len;
4857 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
4858 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
4860 goto insert;
4861 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4862 unsigned long ptr;
4863 char *map;
4864 size_t size;
4865 size_t extent_offset;
4866 size_t copy_size;
4868 em->block_start = EXTENT_MAP_INLINE;
4869 if (!page || create) {
4870 em->start = extent_start;
4871 em->len = extent_end - extent_start;
4872 goto out;
4875 size = btrfs_file_extent_inline_len(leaf, item);
4876 extent_offset = page_offset(page) + pg_offset - extent_start;
4877 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
4878 size - extent_offset);
4879 em->start = extent_start + extent_offset;
4880 em->len = (copy_size + root->sectorsize - 1) &
4881 ~((u64)root->sectorsize - 1);
4882 em->orig_start = EXTENT_MAP_INLINE;
4883 if (compressed)
4884 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4885 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
4886 if (create == 0 && !PageUptodate(page)) {
4887 if (btrfs_file_extent_compression(leaf, item) ==
4888 BTRFS_COMPRESS_ZLIB) {
4889 ret = uncompress_inline(path, inode, page,
4890 pg_offset,
4891 extent_offset, item);
4892 BUG_ON(ret);
4893 } else {
4894 map = kmap(page);
4895 read_extent_buffer(leaf, map + pg_offset, ptr,
4896 copy_size);
4897 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
4898 memset(map + pg_offset + copy_size, 0,
4899 PAGE_CACHE_SIZE - pg_offset -
4900 copy_size);
4902 kunmap(page);
4904 flush_dcache_page(page);
4905 } else if (create && PageUptodate(page)) {
4906 WARN_ON(1);
4907 if (!trans) {
4908 kunmap(page);
4909 free_extent_map(em);
4910 em = NULL;
4911 btrfs_release_path(root, path);
4912 trans = btrfs_join_transaction(root, 1);
4913 goto again;
4915 map = kmap(page);
4916 write_extent_buffer(leaf, map + pg_offset, ptr,
4917 copy_size);
4918 kunmap(page);
4919 btrfs_mark_buffer_dirty(leaf);
4921 set_extent_uptodate(io_tree, em->start,
4922 extent_map_end(em) - 1, GFP_NOFS);
4923 goto insert;
4924 } else {
4925 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
4926 WARN_ON(1);
4928 not_found:
4929 em->start = start;
4930 em->len = len;
4931 not_found_em:
4932 em->block_start = EXTENT_MAP_HOLE;
4933 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
4934 insert:
4935 btrfs_release_path(root, path);
4936 if (em->start > start || extent_map_end(em) <= start) {
4937 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
4938 "[%llu %llu]\n", (unsigned long long)em->start,
4939 (unsigned long long)em->len,
4940 (unsigned long long)start,
4941 (unsigned long long)len);
4942 err = -EIO;
4943 goto out;
4946 err = 0;
4947 write_lock(&em_tree->lock);
4948 ret = add_extent_mapping(em_tree, em);
4949 /* it is possible that someone inserted the extent into the tree
4950 * while we had the lock dropped. It is also possible that
4951 * an overlapping map exists in the tree
4953 if (ret == -EEXIST) {
4954 struct extent_map *existing;
4956 ret = 0;
4958 existing = lookup_extent_mapping(em_tree, start, len);
4959 if (existing && (existing->start > start ||
4960 existing->start + existing->len <= start)) {
4961 free_extent_map(existing);
4962 existing = NULL;
4964 if (!existing) {
4965 existing = lookup_extent_mapping(em_tree, em->start,
4966 em->len);
4967 if (existing) {
4968 err = merge_extent_mapping(em_tree, existing,
4969 em, start,
4970 root->sectorsize);
4971 free_extent_map(existing);
4972 if (err) {
4973 free_extent_map(em);
4974 em = NULL;
4976 } else {
4977 err = -EIO;
4978 free_extent_map(em);
4979 em = NULL;
4981 } else {
4982 free_extent_map(em);
4983 em = existing;
4984 err = 0;
4987 write_unlock(&em_tree->lock);
4988 out:
4989 if (path)
4990 btrfs_free_path(path);
4991 if (trans) {
4992 ret = btrfs_end_transaction(trans, root);
4993 if (!err)
4994 err = ret;
4996 if (err) {
4997 free_extent_map(em);
4998 return ERR_PTR(err);
5000 return em;
5003 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5004 u64 start, u64 len)
5006 struct btrfs_root *root = BTRFS_I(inode)->root;
5007 struct btrfs_trans_handle *trans;
5008 struct extent_map *em;
5009 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5010 struct btrfs_key ins;
5011 u64 alloc_hint;
5012 int ret;
5014 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5016 trans = btrfs_join_transaction(root, 0);
5017 if (!trans)
5018 return ERR_PTR(-ENOMEM);
5020 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5022 alloc_hint = get_extent_allocation_hint(inode, start, len);
5023 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5024 alloc_hint, (u64)-1, &ins, 1);
5025 if (ret) {
5026 em = ERR_PTR(ret);
5027 goto out;
5030 em = alloc_extent_map(GFP_NOFS);
5031 if (!em) {
5032 em = ERR_PTR(-ENOMEM);
5033 goto out;
5036 em->start = start;
5037 em->orig_start = em->start;
5038 em->len = ins.offset;
5040 em->block_start = ins.objectid;
5041 em->block_len = ins.offset;
5042 em->bdev = root->fs_info->fs_devices->latest_bdev;
5043 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5045 while (1) {
5046 write_lock(&em_tree->lock);
5047 ret = add_extent_mapping(em_tree, em);
5048 write_unlock(&em_tree->lock);
5049 if (ret != -EEXIST)
5050 break;
5051 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5054 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5055 ins.offset, ins.offset, 0);
5056 if (ret) {
5057 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5058 em = ERR_PTR(ret);
5060 out:
5061 btrfs_end_transaction(trans, root);
5062 return em;
5066 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5067 * block must be cow'd
5069 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5070 struct inode *inode, u64 offset, u64 len)
5072 struct btrfs_path *path;
5073 int ret;
5074 struct extent_buffer *leaf;
5075 struct btrfs_root *root = BTRFS_I(inode)->root;
5076 struct btrfs_file_extent_item *fi;
5077 struct btrfs_key key;
5078 u64 disk_bytenr;
5079 u64 backref_offset;
5080 u64 extent_end;
5081 u64 num_bytes;
5082 int slot;
5083 int found_type;
5085 path = btrfs_alloc_path();
5086 if (!path)
5087 return -ENOMEM;
5089 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
5090 offset, 0);
5091 if (ret < 0)
5092 goto out;
5094 slot = path->slots[0];
5095 if (ret == 1) {
5096 if (slot == 0) {
5097 /* can't find the item, must cow */
5098 ret = 0;
5099 goto out;
5101 slot--;
5103 ret = 0;
5104 leaf = path->nodes[0];
5105 btrfs_item_key_to_cpu(leaf, &key, slot);
5106 if (key.objectid != inode->i_ino ||
5107 key.type != BTRFS_EXTENT_DATA_KEY) {
5108 /* not our file or wrong item type, must cow */
5109 goto out;
5112 if (key.offset > offset) {
5113 /* Wrong offset, must cow */
5114 goto out;
5117 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5118 found_type = btrfs_file_extent_type(leaf, fi);
5119 if (found_type != BTRFS_FILE_EXTENT_REG &&
5120 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5121 /* not a regular extent, must cow */
5122 goto out;
5124 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5125 backref_offset = btrfs_file_extent_offset(leaf, fi);
5127 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5128 if (extent_end < offset + len) {
5129 /* extent doesn't include our full range, must cow */
5130 goto out;
5133 if (btrfs_extent_readonly(root, disk_bytenr))
5134 goto out;
5137 * look for other files referencing this extent, if we
5138 * find any we must cow
5140 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5141 key.offset - backref_offset, disk_bytenr))
5142 goto out;
5145 * adjust disk_bytenr and num_bytes to cover just the bytes
5146 * in this extent we are about to write. If there
5147 * are any csums in that range we have to cow in order
5148 * to keep the csums correct
5150 disk_bytenr += backref_offset;
5151 disk_bytenr += offset - key.offset;
5152 num_bytes = min(offset + len, extent_end) - offset;
5153 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5154 goto out;
5156 * all of the above have passed, it is safe to overwrite this extent
5157 * without cow
5159 ret = 1;
5160 out:
5161 btrfs_free_path(path);
5162 return ret;
5165 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5166 struct buffer_head *bh_result, int create)
5168 struct extent_map *em;
5169 struct btrfs_root *root = BTRFS_I(inode)->root;
5170 u64 start = iblock << inode->i_blkbits;
5171 u64 len = bh_result->b_size;
5172 struct btrfs_trans_handle *trans;
5174 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5175 if (IS_ERR(em))
5176 return PTR_ERR(em);
5179 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5180 * io. INLINE is special, and we could probably kludge it in here, but
5181 * it's still buffered so for safety lets just fall back to the generic
5182 * buffered path.
5184 * For COMPRESSED we _have_ to read the entire extent in so we can
5185 * decompress it, so there will be buffering required no matter what we
5186 * do, so go ahead and fallback to buffered.
5188 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5189 * to buffered IO. Don't blame me, this is the price we pay for using
5190 * the generic code.
5192 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5193 em->block_start == EXTENT_MAP_INLINE) {
5194 free_extent_map(em);
5195 return -ENOTBLK;
5198 /* Just a good old fashioned hole, return */
5199 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5200 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5201 free_extent_map(em);
5202 /* DIO will do one hole at a time, so just unlock a sector */
5203 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5204 start + root->sectorsize - 1, GFP_NOFS);
5205 return 0;
5209 * We don't allocate a new extent in the following cases
5211 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5212 * existing extent.
5213 * 2) The extent is marked as PREALLOC. We're good to go here and can
5214 * just use the extent.
5217 if (!create) {
5218 len = em->len - (start - em->start);
5219 goto map;
5222 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5223 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5224 em->block_start != EXTENT_MAP_HOLE)) {
5225 int type;
5226 int ret;
5227 u64 block_start;
5229 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5230 type = BTRFS_ORDERED_PREALLOC;
5231 else
5232 type = BTRFS_ORDERED_NOCOW;
5233 len = min(len, em->len - (start - em->start));
5234 block_start = em->block_start + (start - em->start);
5237 * we're not going to log anything, but we do need
5238 * to make sure the current transaction stays open
5239 * while we look for nocow cross refs
5241 trans = btrfs_join_transaction(root, 0);
5242 if (!trans)
5243 goto must_cow;
5245 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5246 ret = btrfs_add_ordered_extent_dio(inode, start,
5247 block_start, len, len, type);
5248 btrfs_end_transaction(trans, root);
5249 if (ret) {
5250 free_extent_map(em);
5251 return ret;
5253 goto unlock;
5255 btrfs_end_transaction(trans, root);
5257 must_cow:
5259 * this will cow the extent, reset the len in case we changed
5260 * it above
5262 len = bh_result->b_size;
5263 free_extent_map(em);
5264 em = btrfs_new_extent_direct(inode, start, len);
5265 if (IS_ERR(em))
5266 return PTR_ERR(em);
5267 len = min(len, em->len - (start - em->start));
5268 unlock:
5269 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5270 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5271 0, NULL, GFP_NOFS);
5272 map:
5273 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5274 inode->i_blkbits;
5275 bh_result->b_size = len;
5276 bh_result->b_bdev = em->bdev;
5277 set_buffer_mapped(bh_result);
5278 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5279 set_buffer_new(bh_result);
5281 free_extent_map(em);
5283 return 0;
5286 struct btrfs_dio_private {
5287 struct inode *inode;
5288 u64 logical_offset;
5289 u64 disk_bytenr;
5290 u64 bytes;
5291 u32 *csums;
5292 void *private;
5295 static void btrfs_endio_direct_read(struct bio *bio, int err)
5297 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5298 struct bio_vec *bvec = bio->bi_io_vec;
5299 struct btrfs_dio_private *dip = bio->bi_private;
5300 struct inode *inode = dip->inode;
5301 struct btrfs_root *root = BTRFS_I(inode)->root;
5302 u64 start;
5303 u32 *private = dip->csums;
5305 start = dip->logical_offset;
5306 do {
5307 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5308 struct page *page = bvec->bv_page;
5309 char *kaddr;
5310 u32 csum = ~(u32)0;
5311 unsigned long flags;
5313 local_irq_save(flags);
5314 kaddr = kmap_atomic(page, KM_IRQ0);
5315 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5316 csum, bvec->bv_len);
5317 btrfs_csum_final(csum, (char *)&csum);
5318 kunmap_atomic(kaddr, KM_IRQ0);
5319 local_irq_restore(flags);
5321 flush_dcache_page(bvec->bv_page);
5322 if (csum != *private) {
5323 printk(KERN_ERR "btrfs csum failed ino %lu off"
5324 " %llu csum %u private %u\n",
5325 inode->i_ino, (unsigned long long)start,
5326 csum, *private);
5327 err = -EIO;
5331 start += bvec->bv_len;
5332 private++;
5333 bvec++;
5334 } while (bvec <= bvec_end);
5336 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5337 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5338 bio->bi_private = dip->private;
5340 kfree(dip->csums);
5341 kfree(dip);
5342 dio_end_io(bio, err);
5345 static void btrfs_endio_direct_write(struct bio *bio, int err)
5347 struct btrfs_dio_private *dip = bio->bi_private;
5348 struct inode *inode = dip->inode;
5349 struct btrfs_root *root = BTRFS_I(inode)->root;
5350 struct btrfs_trans_handle *trans;
5351 struct btrfs_ordered_extent *ordered = NULL;
5352 struct extent_state *cached_state = NULL;
5353 int ret;
5355 if (err)
5356 goto out_done;
5358 ret = btrfs_dec_test_ordered_pending(inode, &ordered,
5359 dip->logical_offset, dip->bytes);
5360 if (!ret)
5361 goto out_done;
5363 BUG_ON(!ordered);
5365 trans = btrfs_join_transaction(root, 1);
5366 if (!trans) {
5367 err = -ENOMEM;
5368 goto out;
5370 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5372 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5373 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5374 if (!ret)
5375 ret = btrfs_update_inode(trans, root, inode);
5376 err = ret;
5377 goto out;
5380 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5381 ordered->file_offset + ordered->len - 1, 0,
5382 &cached_state, GFP_NOFS);
5384 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5385 ret = btrfs_mark_extent_written(trans, inode,
5386 ordered->file_offset,
5387 ordered->file_offset +
5388 ordered->len);
5389 if (ret) {
5390 err = ret;
5391 goto out_unlock;
5393 } else {
5394 ret = insert_reserved_file_extent(trans, inode,
5395 ordered->file_offset,
5396 ordered->start,
5397 ordered->disk_len,
5398 ordered->len,
5399 ordered->len,
5400 0, 0, 0,
5401 BTRFS_FILE_EXTENT_REG);
5402 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5403 ordered->file_offset, ordered->len);
5404 if (ret) {
5405 err = ret;
5406 WARN_ON(1);
5407 goto out_unlock;
5411 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5412 btrfs_ordered_update_i_size(inode, 0, ordered);
5413 btrfs_update_inode(trans, root, inode);
5414 out_unlock:
5415 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5416 ordered->file_offset + ordered->len - 1,
5417 &cached_state, GFP_NOFS);
5418 out:
5419 btrfs_delalloc_release_metadata(inode, ordered->len);
5420 btrfs_end_transaction(trans, root);
5421 btrfs_put_ordered_extent(ordered);
5422 btrfs_put_ordered_extent(ordered);
5423 out_done:
5424 bio->bi_private = dip->private;
5426 kfree(dip->csums);
5427 kfree(dip);
5428 dio_end_io(bio, err);
5431 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5432 struct bio *bio, int mirror_num,
5433 unsigned long bio_flags, u64 offset)
5435 int ret;
5436 struct btrfs_root *root = BTRFS_I(inode)->root;
5437 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5438 BUG_ON(ret);
5439 return 0;
5442 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
5443 loff_t file_offset)
5445 struct btrfs_root *root = BTRFS_I(inode)->root;
5446 struct btrfs_dio_private *dip;
5447 struct bio_vec *bvec = bio->bi_io_vec;
5448 u64 start;
5449 int skip_sum;
5450 int write = rw & REQ_WRITE;
5451 int ret = 0;
5453 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
5455 dip = kmalloc(sizeof(*dip), GFP_NOFS);
5456 if (!dip) {
5457 ret = -ENOMEM;
5458 goto free_ordered;
5460 dip->csums = NULL;
5462 if (!skip_sum) {
5463 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
5464 if (!dip->csums) {
5465 ret = -ENOMEM;
5466 goto free_ordered;
5470 dip->private = bio->bi_private;
5471 dip->inode = inode;
5472 dip->logical_offset = file_offset;
5474 start = dip->logical_offset;
5475 dip->bytes = 0;
5476 do {
5477 dip->bytes += bvec->bv_len;
5478 bvec++;
5479 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
5481 dip->disk_bytenr = (u64)bio->bi_sector << 9;
5482 bio->bi_private = dip;
5484 if (write)
5485 bio->bi_end_io = btrfs_endio_direct_write;
5486 else
5487 bio->bi_end_io = btrfs_endio_direct_read;
5489 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5490 if (ret)
5491 goto out_err;
5493 if (write && !skip_sum) {
5494 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
5495 inode, rw, bio, 0, 0,
5496 dip->logical_offset,
5497 __btrfs_submit_bio_start_direct_io,
5498 __btrfs_submit_bio_done);
5499 if (ret)
5500 goto out_err;
5501 return;
5502 } else if (!skip_sum)
5503 btrfs_lookup_bio_sums_dio(root, inode, bio,
5504 dip->logical_offset, dip->csums);
5506 ret = btrfs_map_bio(root, rw, bio, 0, 1);
5507 if (ret)
5508 goto out_err;
5509 return;
5510 out_err:
5511 kfree(dip->csums);
5512 kfree(dip);
5513 free_ordered:
5515 * If this is a write, we need to clean up the reserved space and kill
5516 * the ordered extent.
5518 if (write) {
5519 struct btrfs_ordered_extent *ordered;
5520 ordered = btrfs_lookup_ordered_extent(inode,
5521 dip->logical_offset);
5522 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
5523 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
5524 btrfs_free_reserved_extent(root, ordered->start,
5525 ordered->disk_len);
5526 btrfs_put_ordered_extent(ordered);
5527 btrfs_put_ordered_extent(ordered);
5529 bio_endio(bio, ret);
5532 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
5533 const struct iovec *iov, loff_t offset,
5534 unsigned long nr_segs)
5536 int seg;
5537 size_t size;
5538 unsigned long addr;
5539 unsigned blocksize_mask = root->sectorsize - 1;
5540 ssize_t retval = -EINVAL;
5541 loff_t end = offset;
5543 if (offset & blocksize_mask)
5544 goto out;
5546 /* Check the memory alignment. Blocks cannot straddle pages */
5547 for (seg = 0; seg < nr_segs; seg++) {
5548 addr = (unsigned long)iov[seg].iov_base;
5549 size = iov[seg].iov_len;
5550 end += size;
5551 if ((addr & blocksize_mask) || (size & blocksize_mask))
5552 goto out;
5554 retval = 0;
5555 out:
5556 return retval;
5558 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
5559 const struct iovec *iov, loff_t offset,
5560 unsigned long nr_segs)
5562 struct file *file = iocb->ki_filp;
5563 struct inode *inode = file->f_mapping->host;
5564 struct btrfs_ordered_extent *ordered;
5565 struct extent_state *cached_state = NULL;
5566 u64 lockstart, lockend;
5567 ssize_t ret;
5568 int writing = rw & WRITE;
5569 int write_bits = 0;
5570 size_t count = iov_length(iov, nr_segs);
5572 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
5573 offset, nr_segs)) {
5574 return 0;
5577 lockstart = offset;
5578 lockend = offset + count - 1;
5580 if (writing) {
5581 ret = btrfs_delalloc_reserve_space(inode, count);
5582 if (ret)
5583 goto out;
5586 while (1) {
5587 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5588 0, &cached_state, GFP_NOFS);
5590 * We're concerned with the entire range that we're going to be
5591 * doing DIO to, so we need to make sure theres no ordered
5592 * extents in this range.
5594 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5595 lockend - lockstart + 1);
5596 if (!ordered)
5597 break;
5598 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5599 &cached_state, GFP_NOFS);
5600 btrfs_start_ordered_extent(inode, ordered, 1);
5601 btrfs_put_ordered_extent(ordered);
5602 cond_resched();
5606 * we don't use btrfs_set_extent_delalloc because we don't want
5607 * the dirty or uptodate bits
5609 if (writing) {
5610 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
5611 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5612 EXTENT_DELALLOC, 0, NULL, &cached_state,
5613 GFP_NOFS);
5614 if (ret) {
5615 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
5616 lockend, EXTENT_LOCKED | write_bits,
5617 1, 0, &cached_state, GFP_NOFS);
5618 goto out;
5622 free_extent_state(cached_state);
5623 cached_state = NULL;
5625 ret = __blockdev_direct_IO(rw, iocb, inode,
5626 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
5627 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
5628 btrfs_submit_direct, 0);
5630 if (ret < 0 && ret != -EIOCBQUEUED) {
5631 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
5632 offset + iov_length(iov, nr_segs) - 1,
5633 EXTENT_LOCKED | write_bits, 1, 0,
5634 &cached_state, GFP_NOFS);
5635 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
5637 * We're falling back to buffered, unlock the section we didn't
5638 * do IO on.
5640 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
5641 offset + iov_length(iov, nr_segs) - 1,
5642 EXTENT_LOCKED | write_bits, 1, 0,
5643 &cached_state, GFP_NOFS);
5645 out:
5646 free_extent_state(cached_state);
5647 return ret;
5650 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
5651 __u64 start, __u64 len)
5653 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent);
5656 int btrfs_readpage(struct file *file, struct page *page)
5658 struct extent_io_tree *tree;
5659 tree = &BTRFS_I(page->mapping->host)->io_tree;
5660 return extent_read_full_page(tree, page, btrfs_get_extent);
5663 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
5665 struct extent_io_tree *tree;
5668 if (current->flags & PF_MEMALLOC) {
5669 redirty_page_for_writepage(wbc, page);
5670 unlock_page(page);
5671 return 0;
5673 tree = &BTRFS_I(page->mapping->host)->io_tree;
5674 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
5677 int btrfs_writepages(struct address_space *mapping,
5678 struct writeback_control *wbc)
5680 struct extent_io_tree *tree;
5682 tree = &BTRFS_I(mapping->host)->io_tree;
5683 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
5686 static int
5687 btrfs_readpages(struct file *file, struct address_space *mapping,
5688 struct list_head *pages, unsigned nr_pages)
5690 struct extent_io_tree *tree;
5691 tree = &BTRFS_I(mapping->host)->io_tree;
5692 return extent_readpages(tree, mapping, pages, nr_pages,
5693 btrfs_get_extent);
5695 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5697 struct extent_io_tree *tree;
5698 struct extent_map_tree *map;
5699 int ret;
5701 tree = &BTRFS_I(page->mapping->host)->io_tree;
5702 map = &BTRFS_I(page->mapping->host)->extent_tree;
5703 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
5704 if (ret == 1) {
5705 ClearPagePrivate(page);
5706 set_page_private(page, 0);
5707 page_cache_release(page);
5709 return ret;
5712 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
5714 if (PageWriteback(page) || PageDirty(page))
5715 return 0;
5716 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
5719 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
5721 struct extent_io_tree *tree;
5722 struct btrfs_ordered_extent *ordered;
5723 struct extent_state *cached_state = NULL;
5724 u64 page_start = page_offset(page);
5725 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
5729 * we have the page locked, so new writeback can't start,
5730 * and the dirty bit won't be cleared while we are here.
5732 * Wait for IO on this page so that we can safely clear
5733 * the PagePrivate2 bit and do ordered accounting
5735 wait_on_page_writeback(page);
5737 tree = &BTRFS_I(page->mapping->host)->io_tree;
5738 if (offset) {
5739 btrfs_releasepage(page, GFP_NOFS);
5740 return;
5742 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5743 GFP_NOFS);
5744 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
5745 page_offset(page));
5746 if (ordered) {
5748 * IO on this page will never be started, so we need
5749 * to account for any ordered extents now
5751 clear_extent_bit(tree, page_start, page_end,
5752 EXTENT_DIRTY | EXTENT_DELALLOC |
5753 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
5754 &cached_state, GFP_NOFS);
5756 * whoever cleared the private bit is responsible
5757 * for the finish_ordered_io
5759 if (TestClearPagePrivate2(page)) {
5760 btrfs_finish_ordered_io(page->mapping->host,
5761 page_start, page_end);
5763 btrfs_put_ordered_extent(ordered);
5764 cached_state = NULL;
5765 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
5766 GFP_NOFS);
5768 clear_extent_bit(tree, page_start, page_end,
5769 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
5770 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
5771 __btrfs_releasepage(page, GFP_NOFS);
5773 ClearPageChecked(page);
5774 if (PagePrivate(page)) {
5775 ClearPagePrivate(page);
5776 set_page_private(page, 0);
5777 page_cache_release(page);
5782 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
5783 * called from a page fault handler when a page is first dirtied. Hence we must
5784 * be careful to check for EOF conditions here. We set the page up correctly
5785 * for a written page which means we get ENOSPC checking when writing into
5786 * holes and correct delalloc and unwritten extent mapping on filesystems that
5787 * support these features.
5789 * We are not allowed to take the i_mutex here so we have to play games to
5790 * protect against truncate races as the page could now be beyond EOF. Because
5791 * vmtruncate() writes the inode size before removing pages, once we have the
5792 * page lock we can determine safely if the page is beyond EOF. If it is not
5793 * beyond EOF, then the page is guaranteed safe against truncation until we
5794 * unlock the page.
5796 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5798 struct page *page = vmf->page;
5799 struct inode *inode = fdentry(vma->vm_file)->d_inode;
5800 struct btrfs_root *root = BTRFS_I(inode)->root;
5801 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5802 struct btrfs_ordered_extent *ordered;
5803 struct extent_state *cached_state = NULL;
5804 char *kaddr;
5805 unsigned long zero_start;
5806 loff_t size;
5807 int ret;
5808 u64 page_start;
5809 u64 page_end;
5811 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
5812 if (ret) {
5813 if (ret == -ENOMEM)
5814 ret = VM_FAULT_OOM;
5815 else /* -ENOSPC, -EIO, etc */
5816 ret = VM_FAULT_SIGBUS;
5817 goto out;
5820 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
5821 again:
5822 lock_page(page);
5823 size = i_size_read(inode);
5824 page_start = page_offset(page);
5825 page_end = page_start + PAGE_CACHE_SIZE - 1;
5827 if ((page->mapping != inode->i_mapping) ||
5828 (page_start >= size)) {
5829 /* page got truncated out from underneath us */
5830 goto out_unlock;
5832 wait_on_page_writeback(page);
5834 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
5835 GFP_NOFS);
5836 set_page_extent_mapped(page);
5839 * we can't set the delalloc bits if there are pending ordered
5840 * extents. Drop our locks and wait for them to finish
5842 ordered = btrfs_lookup_ordered_extent(inode, page_start);
5843 if (ordered) {
5844 unlock_extent_cached(io_tree, page_start, page_end,
5845 &cached_state, GFP_NOFS);
5846 unlock_page(page);
5847 btrfs_start_ordered_extent(inode, ordered, 1);
5848 btrfs_put_ordered_extent(ordered);
5849 goto again;
5852 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
5853 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
5854 0, 0, &cached_state, GFP_NOFS);
5856 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
5857 &cached_state);
5858 if (ret) {
5859 unlock_extent_cached(io_tree, page_start, page_end,
5860 &cached_state, GFP_NOFS);
5861 ret = VM_FAULT_SIGBUS;
5862 goto out_unlock;
5864 ret = 0;
5866 /* page is wholly or partially inside EOF */
5867 if (page_start + PAGE_CACHE_SIZE > size)
5868 zero_start = size & ~PAGE_CACHE_MASK;
5869 else
5870 zero_start = PAGE_CACHE_SIZE;
5872 if (zero_start != PAGE_CACHE_SIZE) {
5873 kaddr = kmap(page);
5874 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
5875 flush_dcache_page(page);
5876 kunmap(page);
5878 ClearPageChecked(page);
5879 set_page_dirty(page);
5880 SetPageUptodate(page);
5882 BTRFS_I(inode)->last_trans = root->fs_info->generation;
5883 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
5885 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
5887 out_unlock:
5888 if (!ret)
5889 return VM_FAULT_LOCKED;
5890 unlock_page(page);
5891 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
5892 out:
5893 return ret;
5896 static void btrfs_truncate(struct inode *inode)
5898 struct btrfs_root *root = BTRFS_I(inode)->root;
5899 int ret;
5900 struct btrfs_trans_handle *trans;
5901 unsigned long nr;
5902 u64 mask = root->sectorsize - 1;
5904 if (!S_ISREG(inode->i_mode)) {
5905 WARN_ON(1);
5906 return;
5909 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
5910 if (ret)
5911 return;
5913 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
5914 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
5916 trans = btrfs_start_transaction(root, 0);
5917 BUG_ON(IS_ERR(trans));
5918 btrfs_set_trans_block_group(trans, inode);
5919 trans->block_rsv = root->orphan_block_rsv;
5922 * setattr is responsible for setting the ordered_data_close flag,
5923 * but that is only tested during the last file release. That
5924 * could happen well after the next commit, leaving a great big
5925 * window where new writes may get lost if someone chooses to write
5926 * to this file after truncating to zero
5928 * The inode doesn't have any dirty data here, and so if we commit
5929 * this is a noop. If someone immediately starts writing to the inode
5930 * it is very likely we'll catch some of their writes in this
5931 * transaction, and the commit will find this file on the ordered
5932 * data list with good things to send down.
5934 * This is a best effort solution, there is still a window where
5935 * using truncate to replace the contents of the file will
5936 * end up with a zero length file after a crash.
5938 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
5939 btrfs_add_ordered_operation(trans, root, inode);
5941 while (1) {
5942 if (!trans) {
5943 trans = btrfs_start_transaction(root, 0);
5944 BUG_ON(IS_ERR(trans));
5945 btrfs_set_trans_block_group(trans, inode);
5946 trans->block_rsv = root->orphan_block_rsv;
5949 ret = btrfs_block_rsv_check(trans, root,
5950 root->orphan_block_rsv, 0, 5);
5951 if (ret) {
5952 BUG_ON(ret != -EAGAIN);
5953 ret = btrfs_commit_transaction(trans, root);
5954 BUG_ON(ret);
5955 trans = NULL;
5956 continue;
5959 ret = btrfs_truncate_inode_items(trans, root, inode,
5960 inode->i_size,
5961 BTRFS_EXTENT_DATA_KEY);
5962 if (ret != -EAGAIN)
5963 break;
5965 ret = btrfs_update_inode(trans, root, inode);
5966 BUG_ON(ret);
5968 nr = trans->blocks_used;
5969 btrfs_end_transaction(trans, root);
5970 trans = NULL;
5971 btrfs_btree_balance_dirty(root, nr);
5974 if (ret == 0 && inode->i_nlink > 0) {
5975 ret = btrfs_orphan_del(trans, inode);
5976 BUG_ON(ret);
5979 ret = btrfs_update_inode(trans, root, inode);
5980 BUG_ON(ret);
5982 nr = trans->blocks_used;
5983 ret = btrfs_end_transaction_throttle(trans, root);
5984 BUG_ON(ret);
5985 btrfs_btree_balance_dirty(root, nr);
5989 * create a new subvolume directory/inode (helper for the ioctl).
5991 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
5992 struct btrfs_root *new_root,
5993 u64 new_dirid, u64 alloc_hint)
5995 struct inode *inode;
5996 int err;
5997 u64 index = 0;
5999 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
6000 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
6001 if (IS_ERR(inode))
6002 return PTR_ERR(inode);
6003 inode->i_op = &btrfs_dir_inode_operations;
6004 inode->i_fop = &btrfs_dir_file_operations;
6006 inode->i_nlink = 1;
6007 btrfs_i_size_write(inode, 0);
6009 err = btrfs_update_inode(trans, new_root, inode);
6010 BUG_ON(err);
6012 iput(inode);
6013 return 0;
6016 /* helper function for file defrag and space balancing. This
6017 * forces readahead on a given range of bytes in an inode
6019 unsigned long btrfs_force_ra(struct address_space *mapping,
6020 struct file_ra_state *ra, struct file *file,
6021 pgoff_t offset, pgoff_t last_index)
6023 pgoff_t req_size = last_index - offset + 1;
6025 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6026 return offset + req_size;
6029 struct inode *btrfs_alloc_inode(struct super_block *sb)
6031 struct btrfs_inode *ei;
6032 struct inode *inode;
6034 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6035 if (!ei)
6036 return NULL;
6038 ei->root = NULL;
6039 ei->space_info = NULL;
6040 ei->generation = 0;
6041 ei->sequence = 0;
6042 ei->last_trans = 0;
6043 ei->last_sub_trans = 0;
6044 ei->logged_trans = 0;
6045 ei->delalloc_bytes = 0;
6046 ei->reserved_bytes = 0;
6047 ei->disk_i_size = 0;
6048 ei->flags = 0;
6049 ei->index_cnt = (u64)-1;
6050 ei->last_unlink_trans = 0;
6052 spin_lock_init(&ei->accounting_lock);
6053 atomic_set(&ei->outstanding_extents, 0);
6054 ei->reserved_extents = 0;
6056 ei->ordered_data_close = 0;
6057 ei->orphan_meta_reserved = 0;
6058 ei->dummy_inode = 0;
6059 ei->force_compress = 0;
6061 inode = &ei->vfs_inode;
6062 extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6063 extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6064 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6065 mutex_init(&ei->log_mutex);
6066 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6067 INIT_LIST_HEAD(&ei->i_orphan);
6068 INIT_LIST_HEAD(&ei->delalloc_inodes);
6069 INIT_LIST_HEAD(&ei->ordered_operations);
6070 RB_CLEAR_NODE(&ei->rb_node);
6072 return inode;
6075 void btrfs_destroy_inode(struct inode *inode)
6077 struct btrfs_ordered_extent *ordered;
6078 struct btrfs_root *root = BTRFS_I(inode)->root;
6080 WARN_ON(!list_empty(&inode->i_dentry));
6081 WARN_ON(inode->i_data.nrpages);
6082 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
6083 WARN_ON(BTRFS_I(inode)->reserved_extents);
6086 * This can happen where we create an inode, but somebody else also
6087 * created the same inode and we need to destroy the one we already
6088 * created.
6090 if (!root)
6091 goto free;
6094 * Make sure we're properly removed from the ordered operation
6095 * lists.
6097 smp_mb();
6098 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6099 spin_lock(&root->fs_info->ordered_extent_lock);
6100 list_del_init(&BTRFS_I(inode)->ordered_operations);
6101 spin_unlock(&root->fs_info->ordered_extent_lock);
6104 spin_lock(&root->orphan_lock);
6105 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6106 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6107 inode->i_ino);
6108 list_del_init(&BTRFS_I(inode)->i_orphan);
6110 spin_unlock(&root->orphan_lock);
6112 while (1) {
6113 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6114 if (!ordered)
6115 break;
6116 else {
6117 printk(KERN_ERR "btrfs found ordered "
6118 "extent %llu %llu on inode cleanup\n",
6119 (unsigned long long)ordered->file_offset,
6120 (unsigned long long)ordered->len);
6121 btrfs_remove_ordered_extent(inode, ordered);
6122 btrfs_put_ordered_extent(ordered);
6123 btrfs_put_ordered_extent(ordered);
6126 inode_tree_del(inode);
6127 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6128 free:
6129 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6132 int btrfs_drop_inode(struct inode *inode)
6134 struct btrfs_root *root = BTRFS_I(inode)->root;
6136 if (btrfs_root_refs(&root->root_item) == 0)
6137 return 1;
6138 else
6139 return generic_drop_inode(inode);
6142 static void init_once(void *foo)
6144 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6146 inode_init_once(&ei->vfs_inode);
6149 void btrfs_destroy_cachep(void)
6151 if (btrfs_inode_cachep)
6152 kmem_cache_destroy(btrfs_inode_cachep);
6153 if (btrfs_trans_handle_cachep)
6154 kmem_cache_destroy(btrfs_trans_handle_cachep);
6155 if (btrfs_transaction_cachep)
6156 kmem_cache_destroy(btrfs_transaction_cachep);
6157 if (btrfs_path_cachep)
6158 kmem_cache_destroy(btrfs_path_cachep);
6161 int btrfs_init_cachep(void)
6163 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6164 sizeof(struct btrfs_inode), 0,
6165 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
6166 if (!btrfs_inode_cachep)
6167 goto fail;
6169 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6170 sizeof(struct btrfs_trans_handle), 0,
6171 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6172 if (!btrfs_trans_handle_cachep)
6173 goto fail;
6175 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6176 sizeof(struct btrfs_transaction), 0,
6177 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6178 if (!btrfs_transaction_cachep)
6179 goto fail;
6181 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6182 sizeof(struct btrfs_path), 0,
6183 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6184 if (!btrfs_path_cachep)
6185 goto fail;
6187 return 0;
6188 fail:
6189 btrfs_destroy_cachep();
6190 return -ENOMEM;
6193 static int btrfs_getattr(struct vfsmount *mnt,
6194 struct dentry *dentry, struct kstat *stat)
6196 struct inode *inode = dentry->d_inode;
6197 generic_fillattr(inode, stat);
6198 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
6199 stat->blksize = PAGE_CACHE_SIZE;
6200 stat->blocks = (inode_get_bytes(inode) +
6201 BTRFS_I(inode)->delalloc_bytes) >> 9;
6202 return 0;
6205 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6206 struct inode *new_dir, struct dentry *new_dentry)
6208 struct btrfs_trans_handle *trans;
6209 struct btrfs_root *root = BTRFS_I(old_dir)->root;
6210 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
6211 struct inode *new_inode = new_dentry->d_inode;
6212 struct inode *old_inode = old_dentry->d_inode;
6213 struct timespec ctime = CURRENT_TIME;
6214 u64 index = 0;
6215 u64 root_objectid;
6216 int ret;
6218 if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6219 return -EPERM;
6221 /* we only allow rename subvolume link between subvolumes */
6222 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
6223 return -EXDEV;
6225 if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6226 (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
6227 return -ENOTEMPTY;
6229 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6230 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6231 return -ENOTEMPTY;
6233 * we're using rename to replace one file with another.
6234 * and the replacement file is large. Start IO on it now so
6235 * we don't add too much work to the end of the transaction
6237 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
6238 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6239 filemap_flush(old_inode->i_mapping);
6241 /* close the racy window with snapshot create/destroy ioctl */
6242 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6243 down_read(&root->fs_info->subvol_sem);
6245 * We want to reserve the absolute worst case amount of items. So if
6246 * both inodes are subvols and we need to unlink them then that would
6247 * require 4 item modifications, but if they are both normal inodes it
6248 * would require 5 item modifications, so we'll assume their normal
6249 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6250 * should cover the worst case number of items we'll modify.
6252 trans = btrfs_start_transaction(root, 20);
6253 if (IS_ERR(trans))
6254 return PTR_ERR(trans);
6256 btrfs_set_trans_block_group(trans, new_dir);
6258 if (dest != root)
6259 btrfs_record_root_in_trans(trans, dest);
6261 ret = btrfs_set_inode_index(new_dir, &index);
6262 if (ret)
6263 goto out_fail;
6265 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6266 /* force full log commit if subvolume involved. */
6267 root->fs_info->last_trans_log_full_commit = trans->transid;
6268 } else {
6269 ret = btrfs_insert_inode_ref(trans, dest,
6270 new_dentry->d_name.name,
6271 new_dentry->d_name.len,
6272 old_inode->i_ino,
6273 new_dir->i_ino, index);
6274 if (ret)
6275 goto out_fail;
6277 * this is an ugly little race, but the rename is required
6278 * to make sure that if we crash, the inode is either at the
6279 * old name or the new one. pinning the log transaction lets
6280 * us make sure we don't allow a log commit to come in after
6281 * we unlink the name but before we add the new name back in.
6283 btrfs_pin_log_trans(root);
6286 * make sure the inode gets flushed if it is replacing
6287 * something.
6289 if (new_inode && new_inode->i_size &&
6290 old_inode && S_ISREG(old_inode->i_mode)) {
6291 btrfs_add_ordered_operation(trans, root, old_inode);
6294 old_dir->i_ctime = old_dir->i_mtime = ctime;
6295 new_dir->i_ctime = new_dir->i_mtime = ctime;
6296 old_inode->i_ctime = ctime;
6298 if (old_dentry->d_parent != new_dentry->d_parent)
6299 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6301 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6302 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6303 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6304 old_dentry->d_name.name,
6305 old_dentry->d_name.len);
6306 } else {
6307 btrfs_inc_nlink(old_dentry->d_inode);
6308 ret = btrfs_unlink_inode(trans, root, old_dir,
6309 old_dentry->d_inode,
6310 old_dentry->d_name.name,
6311 old_dentry->d_name.len);
6313 BUG_ON(ret);
6315 if (new_inode) {
6316 new_inode->i_ctime = CURRENT_TIME;
6317 if (unlikely(new_inode->i_ino ==
6318 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
6319 root_objectid = BTRFS_I(new_inode)->location.objectid;
6320 ret = btrfs_unlink_subvol(trans, dest, new_dir,
6321 root_objectid,
6322 new_dentry->d_name.name,
6323 new_dentry->d_name.len);
6324 BUG_ON(new_inode->i_nlink == 0);
6325 } else {
6326 ret = btrfs_unlink_inode(trans, dest, new_dir,
6327 new_dentry->d_inode,
6328 new_dentry->d_name.name,
6329 new_dentry->d_name.len);
6331 BUG_ON(ret);
6332 if (new_inode->i_nlink == 0) {
6333 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
6334 BUG_ON(ret);
6338 ret = btrfs_add_link(trans, new_dir, old_inode,
6339 new_dentry->d_name.name,
6340 new_dentry->d_name.len, 0, index);
6341 BUG_ON(ret);
6343 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6344 btrfs_log_new_name(trans, old_inode, old_dir,
6345 new_dentry->d_parent);
6346 btrfs_end_log_trans(root);
6348 out_fail:
6349 btrfs_end_transaction_throttle(trans, root);
6351 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6352 up_read(&root->fs_info->subvol_sem);
6354 return ret;
6358 * some fairly slow code that needs optimization. This walks the list
6359 * of all the inodes with pending delalloc and forces them to disk.
6361 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
6363 struct list_head *head = &root->fs_info->delalloc_inodes;
6364 struct btrfs_inode *binode;
6365 struct inode *inode;
6367 if (root->fs_info->sb->s_flags & MS_RDONLY)
6368 return -EROFS;
6370 spin_lock(&root->fs_info->delalloc_lock);
6371 while (!list_empty(head)) {
6372 binode = list_entry(head->next, struct btrfs_inode,
6373 delalloc_inodes);
6374 inode = igrab(&binode->vfs_inode);
6375 if (!inode)
6376 list_del_init(&binode->delalloc_inodes);
6377 spin_unlock(&root->fs_info->delalloc_lock);
6378 if (inode) {
6379 filemap_flush(inode->i_mapping);
6380 if (delay_iput)
6381 btrfs_add_delayed_iput(inode);
6382 else
6383 iput(inode);
6385 cond_resched();
6386 spin_lock(&root->fs_info->delalloc_lock);
6388 spin_unlock(&root->fs_info->delalloc_lock);
6390 /* the filemap_flush will queue IO into the worker threads, but
6391 * we have to make sure the IO is actually started and that
6392 * ordered extents get created before we return
6394 atomic_inc(&root->fs_info->async_submit_draining);
6395 while (atomic_read(&root->fs_info->nr_async_submits) ||
6396 atomic_read(&root->fs_info->async_delalloc_pages)) {
6397 wait_event(root->fs_info->async_submit_wait,
6398 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
6399 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
6401 atomic_dec(&root->fs_info->async_submit_draining);
6402 return 0;
6405 int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput)
6407 struct btrfs_inode *binode;
6408 struct inode *inode = NULL;
6410 spin_lock(&root->fs_info->delalloc_lock);
6411 while (!list_empty(&root->fs_info->delalloc_inodes)) {
6412 binode = list_entry(root->fs_info->delalloc_inodes.next,
6413 struct btrfs_inode, delalloc_inodes);
6414 inode = igrab(&binode->vfs_inode);
6415 if (inode) {
6416 list_move_tail(&binode->delalloc_inodes,
6417 &root->fs_info->delalloc_inodes);
6418 break;
6421 list_del_init(&binode->delalloc_inodes);
6422 cond_resched_lock(&root->fs_info->delalloc_lock);
6424 spin_unlock(&root->fs_info->delalloc_lock);
6426 if (inode) {
6427 write_inode_now(inode, 0);
6428 if (delay_iput)
6429 btrfs_add_delayed_iput(inode);
6430 else
6431 iput(inode);
6432 return 1;
6434 return 0;
6437 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
6438 const char *symname)
6440 struct btrfs_trans_handle *trans;
6441 struct btrfs_root *root = BTRFS_I(dir)->root;
6442 struct btrfs_path *path;
6443 struct btrfs_key key;
6444 struct inode *inode = NULL;
6445 int err;
6446 int drop_inode = 0;
6447 u64 objectid;
6448 u64 index = 0 ;
6449 int name_len;
6450 int datasize;
6451 unsigned long ptr;
6452 struct btrfs_file_extent_item *ei;
6453 struct extent_buffer *leaf;
6454 unsigned long nr = 0;
6456 name_len = strlen(symname) + 1;
6457 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
6458 return -ENAMETOOLONG;
6460 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
6461 if (err)
6462 return err;
6464 * 2 items for inode item and ref
6465 * 2 items for dir items
6466 * 1 item for xattr if selinux is on
6468 trans = btrfs_start_transaction(root, 5);
6469 if (IS_ERR(trans))
6470 return PTR_ERR(trans);
6472 btrfs_set_trans_block_group(trans, dir);
6474 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6475 dentry->d_name.len,
6476 dentry->d_parent->d_inode->i_ino, objectid,
6477 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
6478 &index);
6479 err = PTR_ERR(inode);
6480 if (IS_ERR(inode))
6481 goto out_unlock;
6483 err = btrfs_init_inode_security(trans, inode, dir);
6484 if (err) {
6485 drop_inode = 1;
6486 goto out_unlock;
6489 btrfs_set_trans_block_group(trans, inode);
6490 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
6491 if (err)
6492 drop_inode = 1;
6493 else {
6494 inode->i_mapping->a_ops = &btrfs_aops;
6495 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6496 inode->i_fop = &btrfs_file_operations;
6497 inode->i_op = &btrfs_file_inode_operations;
6498 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6500 btrfs_update_inode_block_group(trans, inode);
6501 btrfs_update_inode_block_group(trans, dir);
6502 if (drop_inode)
6503 goto out_unlock;
6505 path = btrfs_alloc_path();
6506 BUG_ON(!path);
6507 key.objectid = inode->i_ino;
6508 key.offset = 0;
6509 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
6510 datasize = btrfs_file_extent_calc_inline_size(name_len);
6511 err = btrfs_insert_empty_item(trans, root, path, &key,
6512 datasize);
6513 if (err) {
6514 drop_inode = 1;
6515 goto out_unlock;
6517 leaf = path->nodes[0];
6518 ei = btrfs_item_ptr(leaf, path->slots[0],
6519 struct btrfs_file_extent_item);
6520 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
6521 btrfs_set_file_extent_type(leaf, ei,
6522 BTRFS_FILE_EXTENT_INLINE);
6523 btrfs_set_file_extent_encryption(leaf, ei, 0);
6524 btrfs_set_file_extent_compression(leaf, ei, 0);
6525 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
6526 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
6528 ptr = btrfs_file_extent_inline_start(ei);
6529 write_extent_buffer(leaf, symname, ptr, name_len);
6530 btrfs_mark_buffer_dirty(leaf);
6531 btrfs_free_path(path);
6533 inode->i_op = &btrfs_symlink_inode_operations;
6534 inode->i_mapping->a_ops = &btrfs_symlink_aops;
6535 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6536 inode_set_bytes(inode, name_len);
6537 btrfs_i_size_write(inode, name_len - 1);
6538 err = btrfs_update_inode(trans, root, inode);
6539 if (err)
6540 drop_inode = 1;
6542 out_unlock:
6543 nr = trans->blocks_used;
6544 btrfs_end_transaction_throttle(trans, root);
6545 if (drop_inode) {
6546 inode_dec_link_count(inode);
6547 iput(inode);
6549 btrfs_btree_balance_dirty(root, nr);
6550 return err;
6553 int btrfs_prealloc_file_range(struct inode *inode, int mode,
6554 u64 start, u64 num_bytes, u64 min_size,
6555 loff_t actual_len, u64 *alloc_hint)
6557 struct btrfs_trans_handle *trans;
6558 struct btrfs_root *root = BTRFS_I(inode)->root;
6559 struct btrfs_key ins;
6560 u64 cur_offset = start;
6561 int ret = 0;
6563 while (num_bytes > 0) {
6564 trans = btrfs_start_transaction(root, 3);
6565 if (IS_ERR(trans)) {
6566 ret = PTR_ERR(trans);
6567 break;
6570 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
6571 0, *alloc_hint, (u64)-1, &ins, 1);
6572 if (ret) {
6573 btrfs_end_transaction(trans, root);
6574 break;
6577 ret = insert_reserved_file_extent(trans, inode,
6578 cur_offset, ins.objectid,
6579 ins.offset, ins.offset,
6580 ins.offset, 0, 0, 0,
6581 BTRFS_FILE_EXTENT_PREALLOC);
6582 BUG_ON(ret);
6583 btrfs_drop_extent_cache(inode, cur_offset,
6584 cur_offset + ins.offset -1, 0);
6586 num_bytes -= ins.offset;
6587 cur_offset += ins.offset;
6588 *alloc_hint = ins.objectid + ins.offset;
6590 inode->i_ctime = CURRENT_TIME;
6591 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
6592 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
6593 (actual_len > inode->i_size) &&
6594 (cur_offset > inode->i_size)) {
6595 if (cur_offset > actual_len)
6596 i_size_write(inode, actual_len);
6597 else
6598 i_size_write(inode, cur_offset);
6599 i_size_write(inode, cur_offset);
6600 btrfs_ordered_update_i_size(inode, cur_offset, NULL);
6603 ret = btrfs_update_inode(trans, root, inode);
6604 BUG_ON(ret);
6606 btrfs_end_transaction(trans, root);
6608 return ret;
6611 static long btrfs_fallocate(struct inode *inode, int mode,
6612 loff_t offset, loff_t len)
6614 struct extent_state *cached_state = NULL;
6615 u64 cur_offset;
6616 u64 last_byte;
6617 u64 alloc_start;
6618 u64 alloc_end;
6619 u64 alloc_hint = 0;
6620 u64 locked_end;
6621 u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
6622 struct extent_map *em;
6623 int ret;
6625 alloc_start = offset & ~mask;
6626 alloc_end = (offset + len + mask) & ~mask;
6629 * wait for ordered IO before we have any locks. We'll loop again
6630 * below with the locks held.
6632 btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
6634 mutex_lock(&inode->i_mutex);
6635 if (alloc_start > inode->i_size) {
6636 ret = btrfs_cont_expand(inode, alloc_start);
6637 if (ret)
6638 goto out;
6641 ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
6642 if (ret)
6643 goto out;
6645 locked_end = alloc_end - 1;
6646 while (1) {
6647 struct btrfs_ordered_extent *ordered;
6649 /* the extent lock is ordered inside the running
6650 * transaction
6652 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
6653 locked_end, 0, &cached_state, GFP_NOFS);
6654 ordered = btrfs_lookup_first_ordered_extent(inode,
6655 alloc_end - 1);
6656 if (ordered &&
6657 ordered->file_offset + ordered->len > alloc_start &&
6658 ordered->file_offset < alloc_end) {
6659 btrfs_put_ordered_extent(ordered);
6660 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
6661 alloc_start, locked_end,
6662 &cached_state, GFP_NOFS);
6664 * we can't wait on the range with the transaction
6665 * running or with the extent lock held
6667 btrfs_wait_ordered_range(inode, alloc_start,
6668 alloc_end - alloc_start);
6669 } else {
6670 if (ordered)
6671 btrfs_put_ordered_extent(ordered);
6672 break;
6676 cur_offset = alloc_start;
6677 while (1) {
6678 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
6679 alloc_end - cur_offset, 0);
6680 BUG_ON(IS_ERR(em) || !em);
6681 last_byte = min(extent_map_end(em), alloc_end);
6682 last_byte = (last_byte + mask) & ~mask;
6683 if (em->block_start == EXTENT_MAP_HOLE ||
6684 (cur_offset >= inode->i_size &&
6685 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6686 ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
6687 last_byte - cur_offset,
6688 1 << inode->i_blkbits,
6689 offset + len,
6690 &alloc_hint);
6691 if (ret < 0) {
6692 free_extent_map(em);
6693 break;
6696 free_extent_map(em);
6698 cur_offset = last_byte;
6699 if (cur_offset >= alloc_end) {
6700 ret = 0;
6701 break;
6704 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
6705 &cached_state, GFP_NOFS);
6707 btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
6708 out:
6709 mutex_unlock(&inode->i_mutex);
6710 return ret;
6713 static int btrfs_set_page_dirty(struct page *page)
6715 return __set_page_dirty_nobuffers(page);
6718 static int btrfs_permission(struct inode *inode, int mask)
6720 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
6721 return -EACCES;
6722 return generic_permission(inode, mask, btrfs_check_acl);
6725 static const struct inode_operations btrfs_dir_inode_operations = {
6726 .getattr = btrfs_getattr,
6727 .lookup = btrfs_lookup,
6728 .create = btrfs_create,
6729 .unlink = btrfs_unlink,
6730 .link = btrfs_link,
6731 .mkdir = btrfs_mkdir,
6732 .rmdir = btrfs_rmdir,
6733 .rename = btrfs_rename,
6734 .symlink = btrfs_symlink,
6735 .setattr = btrfs_setattr,
6736 .mknod = btrfs_mknod,
6737 .setxattr = btrfs_setxattr,
6738 .getxattr = btrfs_getxattr,
6739 .listxattr = btrfs_listxattr,
6740 .removexattr = btrfs_removexattr,
6741 .permission = btrfs_permission,
6743 static const struct inode_operations btrfs_dir_ro_inode_operations = {
6744 .lookup = btrfs_lookup,
6745 .permission = btrfs_permission,
6748 static const struct file_operations btrfs_dir_file_operations = {
6749 .llseek = generic_file_llseek,
6750 .read = generic_read_dir,
6751 .readdir = btrfs_real_readdir,
6752 .unlocked_ioctl = btrfs_ioctl,
6753 #ifdef CONFIG_COMPAT
6754 .compat_ioctl = btrfs_ioctl,
6755 #endif
6756 .release = btrfs_release_file,
6757 .fsync = btrfs_sync_file,
6760 static struct extent_io_ops btrfs_extent_io_ops = {
6761 .fill_delalloc = run_delalloc_range,
6762 .submit_bio_hook = btrfs_submit_bio_hook,
6763 .merge_bio_hook = btrfs_merge_bio_hook,
6764 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
6765 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
6766 .writepage_start_hook = btrfs_writepage_start_hook,
6767 .readpage_io_failed_hook = btrfs_io_failed_hook,
6768 .set_bit_hook = btrfs_set_bit_hook,
6769 .clear_bit_hook = btrfs_clear_bit_hook,
6770 .merge_extent_hook = btrfs_merge_extent_hook,
6771 .split_extent_hook = btrfs_split_extent_hook,
6775 * btrfs doesn't support the bmap operation because swapfiles
6776 * use bmap to make a mapping of extents in the file. They assume
6777 * these extents won't change over the life of the file and they
6778 * use the bmap result to do IO directly to the drive.
6780 * the btrfs bmap call would return logical addresses that aren't
6781 * suitable for IO and they also will change frequently as COW
6782 * operations happen. So, swapfile + btrfs == corruption.
6784 * For now we're avoiding this by dropping bmap.
6786 static const struct address_space_operations btrfs_aops = {
6787 .readpage = btrfs_readpage,
6788 .writepage = btrfs_writepage,
6789 .writepages = btrfs_writepages,
6790 .readpages = btrfs_readpages,
6791 .sync_page = block_sync_page,
6792 .direct_IO = btrfs_direct_IO,
6793 .invalidatepage = btrfs_invalidatepage,
6794 .releasepage = btrfs_releasepage,
6795 .set_page_dirty = btrfs_set_page_dirty,
6796 .error_remove_page = generic_error_remove_page,
6799 static const struct address_space_operations btrfs_symlink_aops = {
6800 .readpage = btrfs_readpage,
6801 .writepage = btrfs_writepage,
6802 .invalidatepage = btrfs_invalidatepage,
6803 .releasepage = btrfs_releasepage,
6806 static const struct inode_operations btrfs_file_inode_operations = {
6807 .truncate = btrfs_truncate,
6808 .getattr = btrfs_getattr,
6809 .setattr = btrfs_setattr,
6810 .setxattr = btrfs_setxattr,
6811 .getxattr = btrfs_getxattr,
6812 .listxattr = btrfs_listxattr,
6813 .removexattr = btrfs_removexattr,
6814 .permission = btrfs_permission,
6815 .fallocate = btrfs_fallocate,
6816 .fiemap = btrfs_fiemap,
6818 static const struct inode_operations btrfs_special_inode_operations = {
6819 .getattr = btrfs_getattr,
6820 .setattr = btrfs_setattr,
6821 .permission = btrfs_permission,
6822 .setxattr = btrfs_setxattr,
6823 .getxattr = btrfs_getxattr,
6824 .listxattr = btrfs_listxattr,
6825 .removexattr = btrfs_removexattr,
6827 static const struct inode_operations btrfs_symlink_inode_operations = {
6828 .readlink = generic_readlink,
6829 .follow_link = page_follow_link_light,
6830 .put_link = page_put_link,
6831 .permission = btrfs_permission,
6832 .setxattr = btrfs_setxattr,
6833 .getxattr = btrfs_getxattr,
6834 .listxattr = btrfs_listxattr,
6835 .removexattr = btrfs_removexattr,
6838 const struct dentry_operations btrfs_dentry_operations = {
6839 .d_delete = btrfs_dentry_delete,