btrfs: make inode ref log recovery faster
[linux-2.6-block.git] / fs / btrfs / inode.c
CommitLineData
6cbd5570
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
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.
7 *
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.
12 *
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.
17 */
18
8f18cf13 19#include <linux/kernel.h>
065631f6 20#include <linux/bio.h>
39279cc3 21#include <linux/buffer_head.h>
f2eb0a24 22#include <linux/file.h>
39279cc3
CM
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>
39279cc3
CM
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>
9ebefb18 35#include <linux/bit_spinlock.h>
5103e947 36#include <linux/xattr.h>
33268eaf 37#include <linux/posix_acl.h>
d899e052 38#include <linux/falloc.h>
5a0e3ad6 39#include <linux/slab.h>
4b4e25f2 40#include "compat.h"
39279cc3
CM
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"
0b86a832 47#include "volumes.h"
e6dcd2dc 48#include "ordered-data.h"
95819c05 49#include "xattr.h"
e02119d5 50#include "tree-log.h"
c8b97818 51#include "compression.h"
b4ce94de 52#include "locking.h"
dc89e982 53#include "free-space-cache.h"
39279cc3
CM
54
55struct btrfs_iget_args {
56 u64 ino;
57 struct btrfs_root *root;
58};
59
6e1d5dcc
AD
60static const struct inode_operations btrfs_dir_inode_operations;
61static const struct inode_operations btrfs_symlink_inode_operations;
62static const struct inode_operations btrfs_dir_ro_inode_operations;
63static const struct inode_operations btrfs_special_inode_operations;
64static const struct inode_operations btrfs_file_inode_operations;
7f09410b
AD
65static const struct address_space_operations btrfs_aops;
66static const struct address_space_operations btrfs_symlink_aops;
828c0950 67static const struct file_operations btrfs_dir_file_operations;
d1310b2e 68static struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
69
70static struct kmem_cache *btrfs_inode_cachep;
71struct kmem_cache *btrfs_trans_handle_cachep;
72struct kmem_cache *btrfs_transaction_cachep;
39279cc3 73struct kmem_cache *btrfs_path_cachep;
dc89e982 74struct kmem_cache *btrfs_free_space_cachep;
39279cc3
CM
75
76#define S_SHIFT 12
77static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
78 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
79 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
80 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
81 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
82 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
83 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
84 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
85};
86
a41ad394
JB
87static int btrfs_setsize(struct inode *inode, loff_t newsize);
88static int btrfs_truncate(struct inode *inode);
c8b97818 89static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
771ed689
CM
90static noinline int cow_file_range(struct inode *inode,
91 struct page *locked_page,
92 u64 start, u64 end, int *page_started,
93 unsigned long *nr_written, int unlock);
7b128766 94
f34f57a3
YZ
95static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
96 struct inode *inode, struct inode *dir)
0279b4cd
JO
97{
98 int err;
99
f34f57a3 100 err = btrfs_init_acl(trans, inode, dir);
0279b4cd 101 if (!err)
f34f57a3 102 err = btrfs_xattr_security_init(trans, inode, dir);
0279b4cd
JO
103 return err;
104}
105
c8b97818
CM
106/*
107 * this does all the hard work for inserting an inline extent into
108 * the btree. The caller should have done a btrfs_drop_extents so that
109 * no overlapping inline items exist in the btree
110 */
d397712b 111static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
c8b97818
CM
112 struct btrfs_root *root, struct inode *inode,
113 u64 start, size_t size, size_t compressed_size,
114 struct page **compressed_pages)
115{
116 struct btrfs_key key;
117 struct btrfs_path *path;
118 struct extent_buffer *leaf;
119 struct page *page = NULL;
120 char *kaddr;
121 unsigned long ptr;
122 struct btrfs_file_extent_item *ei;
123 int err = 0;
124 int ret;
125 size_t cur_size = size;
126 size_t datasize;
127 unsigned long offset;
261507a0 128 int compress_type = BTRFS_COMPRESS_NONE;
c8b97818
CM
129
130 if (compressed_size && compressed_pages) {
261507a0 131 compress_type = root->fs_info->compress_type;
c8b97818
CM
132 cur_size = compressed_size;
133 }
134
d397712b
CM
135 path = btrfs_alloc_path();
136 if (!path)
c8b97818
CM
137 return -ENOMEM;
138
b9473439 139 path->leave_spinning = 1;
c8b97818
CM
140 btrfs_set_trans_block_group(trans, inode);
141
142 key.objectid = inode->i_ino;
143 key.offset = start;
144 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
c8b97818
CM
145 datasize = btrfs_file_extent_calc_inline_size(cur_size);
146
147 inode_add_bytes(inode, size);
148 ret = btrfs_insert_empty_item(trans, root, path, &key,
149 datasize);
150 BUG_ON(ret);
151 if (ret) {
152 err = ret;
c8b97818
CM
153 goto fail;
154 }
155 leaf = path->nodes[0];
156 ei = btrfs_item_ptr(leaf, path->slots[0],
157 struct btrfs_file_extent_item);
158 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
159 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
160 btrfs_set_file_extent_encryption(leaf, ei, 0);
161 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
162 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
163 ptr = btrfs_file_extent_inline_start(ei);
164
261507a0 165 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818
CM
166 struct page *cpage;
167 int i = 0;
d397712b 168 while (compressed_size > 0) {
c8b97818 169 cpage = compressed_pages[i];
5b050f04 170 cur_size = min_t(unsigned long, compressed_size,
c8b97818
CM
171 PAGE_CACHE_SIZE);
172
b9473439 173 kaddr = kmap_atomic(cpage, KM_USER0);
c8b97818 174 write_extent_buffer(leaf, kaddr, ptr, cur_size);
b9473439 175 kunmap_atomic(kaddr, KM_USER0);
c8b97818
CM
176
177 i++;
178 ptr += cur_size;
179 compressed_size -= cur_size;
180 }
181 btrfs_set_file_extent_compression(leaf, ei,
261507a0 182 compress_type);
c8b97818
CM
183 } else {
184 page = find_get_page(inode->i_mapping,
185 start >> PAGE_CACHE_SHIFT);
186 btrfs_set_file_extent_compression(leaf, ei, 0);
187 kaddr = kmap_atomic(page, KM_USER0);
188 offset = start & (PAGE_CACHE_SIZE - 1);
189 write_extent_buffer(leaf, kaddr + offset, ptr, size);
190 kunmap_atomic(kaddr, KM_USER0);
191 page_cache_release(page);
192 }
193 btrfs_mark_buffer_dirty(leaf);
194 btrfs_free_path(path);
195
c2167754
YZ
196 /*
197 * we're an inline extent, so nobody can
198 * extend the file past i_size without locking
199 * a page we already have locked.
200 *
201 * We must do any isize and inode updates
202 * before we unlock the pages. Otherwise we
203 * could end up racing with unlink.
204 */
c8b97818
CM
205 BTRFS_I(inode)->disk_i_size = inode->i_size;
206 btrfs_update_inode(trans, root, inode);
c2167754 207
c8b97818
CM
208 return 0;
209fail:
210 btrfs_free_path(path);
211 return err;
212}
213
214
215/*
216 * conditionally insert an inline extent into the file. This
217 * does the checks required to make sure the data is small enough
218 * to fit as an inline extent.
219 */
7f366cfe 220static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
c8b97818
CM
221 struct btrfs_root *root,
222 struct inode *inode, u64 start, u64 end,
223 size_t compressed_size,
224 struct page **compressed_pages)
225{
226 u64 isize = i_size_read(inode);
227 u64 actual_end = min(end + 1, isize);
228 u64 inline_len = actual_end - start;
229 u64 aligned_end = (end + root->sectorsize - 1) &
230 ~((u64)root->sectorsize - 1);
231 u64 hint_byte;
232 u64 data_len = inline_len;
233 int ret;
234
235 if (compressed_size)
236 data_len = compressed_size;
237
238 if (start > 0 ||
70b99e69 239 actual_end >= PAGE_CACHE_SIZE ||
c8b97818
CM
240 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
241 (!compressed_size &&
242 (actual_end & (root->sectorsize - 1)) == 0) ||
243 end + 1 < isize ||
244 data_len > root->fs_info->max_inline) {
245 return 1;
246 }
247
920bbbfb 248 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
a1ed835e 249 &hint_byte, 1);
c8b97818
CM
250 BUG_ON(ret);
251
252 if (isize > actual_end)
253 inline_len = min_t(u64, isize, actual_end);
254 ret = insert_inline_extent(trans, root, inode, start,
255 inline_len, compressed_size,
256 compressed_pages);
257 BUG_ON(ret);
0ca1f7ce 258 btrfs_delalloc_release_metadata(inode, end + 1 - start);
a1ed835e 259 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
c8b97818
CM
260 return 0;
261}
262
771ed689
CM
263struct async_extent {
264 u64 start;
265 u64 ram_size;
266 u64 compressed_size;
267 struct page **pages;
268 unsigned long nr_pages;
261507a0 269 int compress_type;
771ed689
CM
270 struct list_head list;
271};
272
273struct async_cow {
274 struct inode *inode;
275 struct btrfs_root *root;
276 struct page *locked_page;
277 u64 start;
278 u64 end;
279 struct list_head extents;
280 struct btrfs_work work;
281};
282
283static noinline int add_async_extent(struct async_cow *cow,
284 u64 start, u64 ram_size,
285 u64 compressed_size,
286 struct page **pages,
261507a0
LZ
287 unsigned long nr_pages,
288 int compress_type)
771ed689
CM
289{
290 struct async_extent *async_extent;
291
292 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
293 async_extent->start = start;
294 async_extent->ram_size = ram_size;
295 async_extent->compressed_size = compressed_size;
296 async_extent->pages = pages;
297 async_extent->nr_pages = nr_pages;
261507a0 298 async_extent->compress_type = compress_type;
771ed689
CM
299 list_add_tail(&async_extent->list, &cow->extents);
300 return 0;
301}
302
d352ac68 303/*
771ed689
CM
304 * we create compressed extents in two phases. The first
305 * phase compresses a range of pages that have already been
306 * locked (both pages and state bits are locked).
c8b97818 307 *
771ed689
CM
308 * This is done inside an ordered work queue, and the compression
309 * is spread across many cpus. The actual IO submission is step
310 * two, and the ordered work queue takes care of making sure that
311 * happens in the same order things were put onto the queue by
312 * writepages and friends.
c8b97818 313 *
771ed689
CM
314 * If this code finds it can't get good compression, it puts an
315 * entry onto the work queue to write the uncompressed bytes. This
316 * makes sure that both compressed inodes and uncompressed inodes
317 * are written in the same order that pdflush sent them down.
d352ac68 318 */
771ed689
CM
319static noinline int compress_file_range(struct inode *inode,
320 struct page *locked_page,
321 u64 start, u64 end,
322 struct async_cow *async_cow,
323 int *num_added)
b888db2b
CM
324{
325 struct btrfs_root *root = BTRFS_I(inode)->root;
326 struct btrfs_trans_handle *trans;
db94535d 327 u64 num_bytes;
db94535d 328 u64 blocksize = root->sectorsize;
c8b97818 329 u64 actual_end;
42dc7bab 330 u64 isize = i_size_read(inode);
e6dcd2dc 331 int ret = 0;
c8b97818
CM
332 struct page **pages = NULL;
333 unsigned long nr_pages;
334 unsigned long nr_pages_ret = 0;
335 unsigned long total_compressed = 0;
336 unsigned long total_in = 0;
337 unsigned long max_compressed = 128 * 1024;
771ed689 338 unsigned long max_uncompressed = 128 * 1024;
c8b97818
CM
339 int i;
340 int will_compress;
261507a0 341 int compress_type = root->fs_info->compress_type;
b888db2b 342
42dc7bab 343 actual_end = min_t(u64, isize, end + 1);
c8b97818
CM
344again:
345 will_compress = 0;
346 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
347 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
be20aa9d 348
f03d9301
CM
349 /*
350 * we don't want to send crud past the end of i_size through
351 * compression, that's just a waste of CPU time. So, if the
352 * end of the file is before the start of our current
353 * requested range of bytes, we bail out to the uncompressed
354 * cleanup code that can deal with all of this.
355 *
356 * It isn't really the fastest way to fix things, but this is a
357 * very uncommon corner.
358 */
359 if (actual_end <= start)
360 goto cleanup_and_bail_uncompressed;
361
c8b97818
CM
362 total_compressed = actual_end - start;
363
364 /* we want to make sure that amount of ram required to uncompress
365 * an extent is reasonable, so we limit the total size in ram
771ed689
CM
366 * of a compressed extent to 128k. This is a crucial number
367 * because it also controls how easily we can spread reads across
368 * cpus for decompression.
369 *
370 * We also want to make sure the amount of IO required to do
371 * a random read is reasonably small, so we limit the size of
372 * a compressed extent to 128k.
c8b97818
CM
373 */
374 total_compressed = min(total_compressed, max_uncompressed);
db94535d 375 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
be20aa9d 376 num_bytes = max(blocksize, num_bytes);
c8b97818
CM
377 total_in = 0;
378 ret = 0;
db94535d 379
771ed689
CM
380 /*
381 * we do compression for mount -o compress and when the
382 * inode has not been flagged as nocompress. This flag can
383 * change at any time if we discover bad compression ratios.
c8b97818 384 */
6cbff00f 385 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
1e701a32 386 (btrfs_test_opt(root, COMPRESS) ||
75e7cb7f
LB
387 (BTRFS_I(inode)->force_compress) ||
388 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
c8b97818 389 WARN_ON(pages);
cfbc246e 390 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
c8b97818 391
261507a0
LZ
392 if (BTRFS_I(inode)->force_compress)
393 compress_type = BTRFS_I(inode)->force_compress;
394
395 ret = btrfs_compress_pages(compress_type,
396 inode->i_mapping, start,
397 total_compressed, pages,
398 nr_pages, &nr_pages_ret,
399 &total_in,
400 &total_compressed,
401 max_compressed);
c8b97818
CM
402
403 if (!ret) {
404 unsigned long offset = total_compressed &
405 (PAGE_CACHE_SIZE - 1);
406 struct page *page = pages[nr_pages_ret - 1];
407 char *kaddr;
408
409 /* zero the tail end of the last page, we might be
410 * sending it down to disk
411 */
412 if (offset) {
413 kaddr = kmap_atomic(page, KM_USER0);
414 memset(kaddr + offset, 0,
415 PAGE_CACHE_SIZE - offset);
416 kunmap_atomic(kaddr, KM_USER0);
417 }
418 will_compress = 1;
419 }
420 }
421 if (start == 0) {
771ed689 422 trans = btrfs_join_transaction(root, 1);
3612b495 423 BUG_ON(IS_ERR(trans));
771ed689 424 btrfs_set_trans_block_group(trans, inode);
0ca1f7ce 425 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771ed689 426
c8b97818 427 /* lets try to make an inline extent */
771ed689 428 if (ret || total_in < (actual_end - start)) {
c8b97818 429 /* we didn't compress the entire range, try
771ed689 430 * to make an uncompressed inline extent.
c8b97818
CM
431 */
432 ret = cow_file_range_inline(trans, root, inode,
433 start, end, 0, NULL);
434 } else {
771ed689 435 /* try making a compressed inline extent */
c8b97818
CM
436 ret = cow_file_range_inline(trans, root, inode,
437 start, end,
438 total_compressed, pages);
439 }
440 if (ret == 0) {
771ed689
CM
441 /*
442 * inline extent creation worked, we don't need
443 * to create any more async work items. Unlock
444 * and free up our temp pages.
445 */
c8b97818 446 extent_clear_unlock_delalloc(inode,
a791e35e
CM
447 &BTRFS_I(inode)->io_tree,
448 start, end, NULL,
449 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
a3429ab7 450 EXTENT_CLEAR_DELALLOC |
a791e35e 451 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
c2167754
YZ
452
453 btrfs_end_transaction(trans, root);
c8b97818
CM
454 goto free_pages_out;
455 }
c2167754 456 btrfs_end_transaction(trans, root);
c8b97818
CM
457 }
458
459 if (will_compress) {
460 /*
461 * we aren't doing an inline extent round the compressed size
462 * up to a block size boundary so the allocator does sane
463 * things
464 */
465 total_compressed = (total_compressed + blocksize - 1) &
466 ~(blocksize - 1);
467
468 /*
469 * one last check to make sure the compression is really a
470 * win, compare the page count read with the blocks on disk
471 */
472 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
473 ~(PAGE_CACHE_SIZE - 1);
474 if (total_compressed >= total_in) {
475 will_compress = 0;
476 } else {
c8b97818
CM
477 num_bytes = total_in;
478 }
479 }
480 if (!will_compress && pages) {
481 /*
482 * the compression code ran but failed to make things smaller,
483 * free any pages it allocated and our page pointer array
484 */
485 for (i = 0; i < nr_pages_ret; i++) {
70b99e69 486 WARN_ON(pages[i]->mapping);
c8b97818
CM
487 page_cache_release(pages[i]);
488 }
489 kfree(pages);
490 pages = NULL;
491 total_compressed = 0;
492 nr_pages_ret = 0;
493
494 /* flag the file so we don't compress in the future */
1e701a32
CM
495 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
496 !(BTRFS_I(inode)->force_compress)) {
a555f810 497 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
1e701a32 498 }
c8b97818 499 }
771ed689
CM
500 if (will_compress) {
501 *num_added += 1;
c8b97818 502
771ed689
CM
503 /* the async work queues will take care of doing actual
504 * allocation on disk for these compressed pages,
505 * and will submit them to the elevator.
506 */
507 add_async_extent(async_cow, start, num_bytes,
261507a0
LZ
508 total_compressed, pages, nr_pages_ret,
509 compress_type);
179e29e4 510
24ae6365 511 if (start + num_bytes < end) {
771ed689
CM
512 start += num_bytes;
513 pages = NULL;
514 cond_resched();
515 goto again;
516 }
517 } else {
f03d9301 518cleanup_and_bail_uncompressed:
771ed689
CM
519 /*
520 * No compression, but we still need to write the pages in
521 * the file we've been given so far. redirty the locked
522 * page if it corresponds to our extent and set things up
523 * for the async work queue to run cow_file_range to do
524 * the normal delalloc dance
525 */
526 if (page_offset(locked_page) >= start &&
527 page_offset(locked_page) <= end) {
528 __set_page_dirty_nobuffers(locked_page);
529 /* unlocked later on in the async handlers */
530 }
261507a0
LZ
531 add_async_extent(async_cow, start, end - start + 1,
532 0, NULL, 0, BTRFS_COMPRESS_NONE);
771ed689
CM
533 *num_added += 1;
534 }
3b951516 535
771ed689
CM
536out:
537 return 0;
538
539free_pages_out:
540 for (i = 0; i < nr_pages_ret; i++) {
541 WARN_ON(pages[i]->mapping);
542 page_cache_release(pages[i]);
543 }
d397712b 544 kfree(pages);
771ed689
CM
545
546 goto out;
547}
548
549/*
550 * phase two of compressed writeback. This is the ordered portion
551 * of the code, which only gets called in the order the work was
552 * queued. We walk all the async extents created by compress_file_range
553 * and send them down to the disk.
554 */
555static noinline int submit_compressed_extents(struct inode *inode,
556 struct async_cow *async_cow)
557{
558 struct async_extent *async_extent;
559 u64 alloc_hint = 0;
560 struct btrfs_trans_handle *trans;
561 struct btrfs_key ins;
562 struct extent_map *em;
563 struct btrfs_root *root = BTRFS_I(inode)->root;
564 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
565 struct extent_io_tree *io_tree;
f5a84ee3 566 int ret = 0;
771ed689
CM
567
568 if (list_empty(&async_cow->extents))
569 return 0;
570
771ed689 571
d397712b 572 while (!list_empty(&async_cow->extents)) {
771ed689
CM
573 async_extent = list_entry(async_cow->extents.next,
574 struct async_extent, list);
575 list_del(&async_extent->list);
c8b97818 576
771ed689
CM
577 io_tree = &BTRFS_I(inode)->io_tree;
578
f5a84ee3 579retry:
771ed689
CM
580 /* did the compression code fall back to uncompressed IO? */
581 if (!async_extent->pages) {
582 int page_started = 0;
583 unsigned long nr_written = 0;
584
585 lock_extent(io_tree, async_extent->start,
2ac55d41
JB
586 async_extent->start +
587 async_extent->ram_size - 1, GFP_NOFS);
771ed689
CM
588
589 /* allocate blocks */
f5a84ee3
JB
590 ret = cow_file_range(inode, async_cow->locked_page,
591 async_extent->start,
592 async_extent->start +
593 async_extent->ram_size - 1,
594 &page_started, &nr_written, 0);
771ed689
CM
595
596 /*
597 * if page_started, cow_file_range inserted an
598 * inline extent and took care of all the unlocking
599 * and IO for us. Otherwise, we need to submit
600 * all those pages down to the drive.
601 */
f5a84ee3 602 if (!page_started && !ret)
771ed689
CM
603 extent_write_locked_range(io_tree,
604 inode, async_extent->start,
d397712b 605 async_extent->start +
771ed689
CM
606 async_extent->ram_size - 1,
607 btrfs_get_extent,
608 WB_SYNC_ALL);
609 kfree(async_extent);
610 cond_resched();
611 continue;
612 }
613
614 lock_extent(io_tree, async_extent->start,
615 async_extent->start + async_extent->ram_size - 1,
616 GFP_NOFS);
771ed689 617
c2167754 618 trans = btrfs_join_transaction(root, 1);
3612b495 619 BUG_ON(IS_ERR(trans));
771ed689
CM
620 ret = btrfs_reserve_extent(trans, root,
621 async_extent->compressed_size,
622 async_extent->compressed_size,
623 0, alloc_hint,
624 (u64)-1, &ins, 1);
c2167754
YZ
625 btrfs_end_transaction(trans, root);
626
f5a84ee3
JB
627 if (ret) {
628 int i;
629 for (i = 0; i < async_extent->nr_pages; i++) {
630 WARN_ON(async_extent->pages[i]->mapping);
631 page_cache_release(async_extent->pages[i]);
632 }
633 kfree(async_extent->pages);
634 async_extent->nr_pages = 0;
635 async_extent->pages = NULL;
636 unlock_extent(io_tree, async_extent->start,
637 async_extent->start +
638 async_extent->ram_size - 1, GFP_NOFS);
639 goto retry;
640 }
641
c2167754
YZ
642 /*
643 * here we're doing allocation and writeback of the
644 * compressed pages
645 */
646 btrfs_drop_extent_cache(inode, async_extent->start,
647 async_extent->start +
648 async_extent->ram_size - 1, 0);
649
771ed689 650 em = alloc_extent_map(GFP_NOFS);
c26a9203 651 BUG_ON(!em);
771ed689
CM
652 em->start = async_extent->start;
653 em->len = async_extent->ram_size;
445a6944 654 em->orig_start = em->start;
c8b97818 655
771ed689
CM
656 em->block_start = ins.objectid;
657 em->block_len = ins.offset;
658 em->bdev = root->fs_info->fs_devices->latest_bdev;
261507a0 659 em->compress_type = async_extent->compress_type;
771ed689
CM
660 set_bit(EXTENT_FLAG_PINNED, &em->flags);
661 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
662
d397712b 663 while (1) {
890871be 664 write_lock(&em_tree->lock);
771ed689 665 ret = add_extent_mapping(em_tree, em);
890871be 666 write_unlock(&em_tree->lock);
771ed689
CM
667 if (ret != -EEXIST) {
668 free_extent_map(em);
669 break;
670 }
671 btrfs_drop_extent_cache(inode, async_extent->start,
672 async_extent->start +
673 async_extent->ram_size - 1, 0);
674 }
675
261507a0
LZ
676 ret = btrfs_add_ordered_extent_compress(inode,
677 async_extent->start,
678 ins.objectid,
679 async_extent->ram_size,
680 ins.offset,
681 BTRFS_ORDERED_COMPRESSED,
682 async_extent->compress_type);
771ed689
CM
683 BUG_ON(ret);
684
771ed689
CM
685 /*
686 * clear dirty, set writeback and unlock the pages.
687 */
688 extent_clear_unlock_delalloc(inode,
a791e35e
CM
689 &BTRFS_I(inode)->io_tree,
690 async_extent->start,
691 async_extent->start +
692 async_extent->ram_size - 1,
693 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
694 EXTENT_CLEAR_UNLOCK |
a3429ab7 695 EXTENT_CLEAR_DELALLOC |
a791e35e 696 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
771ed689
CM
697
698 ret = btrfs_submit_compressed_write(inode,
d397712b
CM
699 async_extent->start,
700 async_extent->ram_size,
701 ins.objectid,
702 ins.offset, async_extent->pages,
703 async_extent->nr_pages);
771ed689
CM
704
705 BUG_ON(ret);
771ed689
CM
706 alloc_hint = ins.objectid + ins.offset;
707 kfree(async_extent);
708 cond_resched();
709 }
710
771ed689
CM
711 return 0;
712}
713
4b46fce2
JB
714static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
715 u64 num_bytes)
716{
717 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
718 struct extent_map *em;
719 u64 alloc_hint = 0;
720
721 read_lock(&em_tree->lock);
722 em = search_extent_mapping(em_tree, start, num_bytes);
723 if (em) {
724 /*
725 * if block start isn't an actual block number then find the
726 * first block in this inode and use that as a hint. If that
727 * block is also bogus then just don't worry about it.
728 */
729 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
730 free_extent_map(em);
731 em = search_extent_mapping(em_tree, 0, 0);
732 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
733 alloc_hint = em->block_start;
734 if (em)
735 free_extent_map(em);
736 } else {
737 alloc_hint = em->block_start;
738 free_extent_map(em);
739 }
740 }
741 read_unlock(&em_tree->lock);
742
743 return alloc_hint;
744}
745
771ed689
CM
746/*
747 * when extent_io.c finds a delayed allocation range in the file,
748 * the call backs end up in this code. The basic idea is to
749 * allocate extents on disk for the range, and create ordered data structs
750 * in ram to track those extents.
751 *
752 * locked_page is the page that writepage had locked already. We use
753 * it to make sure we don't do extra locks or unlocks.
754 *
755 * *page_started is set to one if we unlock locked_page and do everything
756 * required to start IO on it. It may be clean and already done with
757 * IO when we return.
758 */
759static noinline int cow_file_range(struct inode *inode,
760 struct page *locked_page,
761 u64 start, u64 end, int *page_started,
762 unsigned long *nr_written,
763 int unlock)
764{
765 struct btrfs_root *root = BTRFS_I(inode)->root;
766 struct btrfs_trans_handle *trans;
767 u64 alloc_hint = 0;
768 u64 num_bytes;
769 unsigned long ram_size;
770 u64 disk_num_bytes;
771 u64 cur_alloc_size;
772 u64 blocksize = root->sectorsize;
771ed689
CM
773 struct btrfs_key ins;
774 struct extent_map *em;
775 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
776 int ret = 0;
777
0cb59c99 778 BUG_ON(root == root->fs_info->tree_root);
771ed689 779 trans = btrfs_join_transaction(root, 1);
3612b495 780 BUG_ON(IS_ERR(trans));
771ed689 781 btrfs_set_trans_block_group(trans, inode);
0ca1f7ce 782 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
771ed689 783
771ed689
CM
784 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
785 num_bytes = max(blocksize, num_bytes);
786 disk_num_bytes = num_bytes;
787 ret = 0;
788
789 if (start == 0) {
790 /* lets try to make an inline extent */
791 ret = cow_file_range_inline(trans, root, inode,
792 start, end, 0, NULL);
793 if (ret == 0) {
794 extent_clear_unlock_delalloc(inode,
a791e35e
CM
795 &BTRFS_I(inode)->io_tree,
796 start, end, NULL,
797 EXTENT_CLEAR_UNLOCK_PAGE |
798 EXTENT_CLEAR_UNLOCK |
799 EXTENT_CLEAR_DELALLOC |
800 EXTENT_CLEAR_DIRTY |
801 EXTENT_SET_WRITEBACK |
802 EXTENT_END_WRITEBACK);
c2167754 803
771ed689
CM
804 *nr_written = *nr_written +
805 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
806 *page_started = 1;
807 ret = 0;
808 goto out;
809 }
810 }
811
812 BUG_ON(disk_num_bytes >
813 btrfs_super_total_bytes(&root->fs_info->super_copy));
814
4b46fce2 815 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
771ed689
CM
816 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
817
d397712b 818 while (disk_num_bytes > 0) {
a791e35e
CM
819 unsigned long op;
820
287a0ab9 821 cur_alloc_size = disk_num_bytes;
e6dcd2dc 822 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
771ed689 823 root->sectorsize, 0, alloc_hint,
e6dcd2dc 824 (u64)-1, &ins, 1);
d397712b
CM
825 BUG_ON(ret);
826
e6dcd2dc 827 em = alloc_extent_map(GFP_NOFS);
c26a9203 828 BUG_ON(!em);
e6dcd2dc 829 em->start = start;
445a6944 830 em->orig_start = em->start;
771ed689
CM
831 ram_size = ins.offset;
832 em->len = ins.offset;
c8b97818 833
e6dcd2dc 834 em->block_start = ins.objectid;
c8b97818 835 em->block_len = ins.offset;
e6dcd2dc 836 em->bdev = root->fs_info->fs_devices->latest_bdev;
7f3c74fb 837 set_bit(EXTENT_FLAG_PINNED, &em->flags);
c8b97818 838
d397712b 839 while (1) {
890871be 840 write_lock(&em_tree->lock);
e6dcd2dc 841 ret = add_extent_mapping(em_tree, em);
890871be 842 write_unlock(&em_tree->lock);
e6dcd2dc
CM
843 if (ret != -EEXIST) {
844 free_extent_map(em);
845 break;
846 }
847 btrfs_drop_extent_cache(inode, start,
c8b97818 848 start + ram_size - 1, 0);
e6dcd2dc
CM
849 }
850
98d20f67 851 cur_alloc_size = ins.offset;
e6dcd2dc 852 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 853 ram_size, cur_alloc_size, 0);
e6dcd2dc 854 BUG_ON(ret);
c8b97818 855
17d217fe
YZ
856 if (root->root_key.objectid ==
857 BTRFS_DATA_RELOC_TREE_OBJECTID) {
858 ret = btrfs_reloc_clone_csums(inode, start,
859 cur_alloc_size);
860 BUG_ON(ret);
861 }
862
d397712b 863 if (disk_num_bytes < cur_alloc_size)
3b951516 864 break;
d397712b 865
c8b97818
CM
866 /* we're not doing compressed IO, don't unlock the first
867 * page (which the caller expects to stay locked), don't
868 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
869 *
870 * Do set the Private2 bit so we know this page was properly
871 * setup for writepage
c8b97818 872 */
a791e35e
CM
873 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
874 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
875 EXTENT_SET_PRIVATE2;
876
c8b97818
CM
877 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
878 start, start + ram_size - 1,
a791e35e 879 locked_page, op);
c8b97818 880 disk_num_bytes -= cur_alloc_size;
c59f8951
CM
881 num_bytes -= cur_alloc_size;
882 alloc_hint = ins.objectid + ins.offset;
883 start += cur_alloc_size;
b888db2b 884 }
b888db2b 885out:
771ed689 886 ret = 0;
b888db2b 887 btrfs_end_transaction(trans, root);
c8b97818 888
be20aa9d 889 return ret;
771ed689 890}
c8b97818 891
771ed689
CM
892/*
893 * work queue call back to started compression on a file and pages
894 */
895static noinline void async_cow_start(struct btrfs_work *work)
896{
897 struct async_cow *async_cow;
898 int num_added = 0;
899 async_cow = container_of(work, struct async_cow, work);
900
901 compress_file_range(async_cow->inode, async_cow->locked_page,
902 async_cow->start, async_cow->end, async_cow,
903 &num_added);
904 if (num_added == 0)
905 async_cow->inode = NULL;
906}
907
908/*
909 * work queue call back to submit previously compressed pages
910 */
911static noinline void async_cow_submit(struct btrfs_work *work)
912{
913 struct async_cow *async_cow;
914 struct btrfs_root *root;
915 unsigned long nr_pages;
916
917 async_cow = container_of(work, struct async_cow, work);
918
919 root = async_cow->root;
920 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
921 PAGE_CACHE_SHIFT;
922
923 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
924
925 if (atomic_read(&root->fs_info->async_delalloc_pages) <
926 5 * 1042 * 1024 &&
927 waitqueue_active(&root->fs_info->async_submit_wait))
928 wake_up(&root->fs_info->async_submit_wait);
929
d397712b 930 if (async_cow->inode)
771ed689 931 submit_compressed_extents(async_cow->inode, async_cow);
771ed689 932}
c8b97818 933
771ed689
CM
934static noinline void async_cow_free(struct btrfs_work *work)
935{
936 struct async_cow *async_cow;
937 async_cow = container_of(work, struct async_cow, work);
938 kfree(async_cow);
939}
940
941static int cow_file_range_async(struct inode *inode, struct page *locked_page,
942 u64 start, u64 end, int *page_started,
943 unsigned long *nr_written)
944{
945 struct async_cow *async_cow;
946 struct btrfs_root *root = BTRFS_I(inode)->root;
947 unsigned long nr_pages;
948 u64 cur_end;
949 int limit = 10 * 1024 * 1042;
950
a3429ab7
CM
951 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
952 1, 0, NULL, GFP_NOFS);
d397712b 953 while (start < end) {
771ed689
CM
954 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
955 async_cow->inode = inode;
956 async_cow->root = root;
957 async_cow->locked_page = locked_page;
958 async_cow->start = start;
959
6cbff00f 960 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
771ed689
CM
961 cur_end = end;
962 else
963 cur_end = min(end, start + 512 * 1024 - 1);
964
965 async_cow->end = cur_end;
966 INIT_LIST_HEAD(&async_cow->extents);
967
968 async_cow->work.func = async_cow_start;
969 async_cow->work.ordered_func = async_cow_submit;
970 async_cow->work.ordered_free = async_cow_free;
971 async_cow->work.flags = 0;
972
771ed689
CM
973 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
974 PAGE_CACHE_SHIFT;
975 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
976
977 btrfs_queue_worker(&root->fs_info->delalloc_workers,
978 &async_cow->work);
979
980 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
981 wait_event(root->fs_info->async_submit_wait,
982 (atomic_read(&root->fs_info->async_delalloc_pages) <
983 limit));
984 }
985
d397712b 986 while (atomic_read(&root->fs_info->async_submit_draining) &&
771ed689
CM
987 atomic_read(&root->fs_info->async_delalloc_pages)) {
988 wait_event(root->fs_info->async_submit_wait,
989 (atomic_read(&root->fs_info->async_delalloc_pages) ==
990 0));
991 }
992
993 *nr_written += nr_pages;
994 start = cur_end + 1;
995 }
996 *page_started = 1;
997 return 0;
be20aa9d
CM
998}
999
d397712b 1000static noinline int csum_exist_in_range(struct btrfs_root *root,
17d217fe
YZ
1001 u64 bytenr, u64 num_bytes)
1002{
1003 int ret;
1004 struct btrfs_ordered_sum *sums;
1005 LIST_HEAD(list);
1006
07d400a6
YZ
1007 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1008 bytenr + num_bytes - 1, &list);
17d217fe
YZ
1009 if (ret == 0 && list_empty(&list))
1010 return 0;
1011
1012 while (!list_empty(&list)) {
1013 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1014 list_del(&sums->list);
1015 kfree(sums);
1016 }
1017 return 1;
1018}
1019
d352ac68
CM
1020/*
1021 * when nowcow writeback call back. This checks for snapshots or COW copies
1022 * of the extents that exist in the file, and COWs the file as required.
1023 *
1024 * If no cow copies or snapshots exist, we write directly to the existing
1025 * blocks on disk
1026 */
7f366cfe
CM
1027static noinline int run_delalloc_nocow(struct inode *inode,
1028 struct page *locked_page,
771ed689
CM
1029 u64 start, u64 end, int *page_started, int force,
1030 unsigned long *nr_written)
be20aa9d 1031{
be20aa9d 1032 struct btrfs_root *root = BTRFS_I(inode)->root;
7ea394f1 1033 struct btrfs_trans_handle *trans;
be20aa9d 1034 struct extent_buffer *leaf;
be20aa9d 1035 struct btrfs_path *path;
80ff3856 1036 struct btrfs_file_extent_item *fi;
be20aa9d 1037 struct btrfs_key found_key;
80ff3856
YZ
1038 u64 cow_start;
1039 u64 cur_offset;
1040 u64 extent_end;
5d4f98a2 1041 u64 extent_offset;
80ff3856
YZ
1042 u64 disk_bytenr;
1043 u64 num_bytes;
1044 int extent_type;
1045 int ret;
d899e052 1046 int type;
80ff3856
YZ
1047 int nocow;
1048 int check_prev = 1;
0cb59c99 1049 bool nolock = false;
be20aa9d
CM
1050
1051 path = btrfs_alloc_path();
1052 BUG_ON(!path);
0cb59c99
JB
1053 if (root == root->fs_info->tree_root) {
1054 nolock = true;
1055 trans = btrfs_join_transaction_nolock(root, 1);
1056 } else {
1057 trans = btrfs_join_transaction(root, 1);
1058 }
3612b495 1059 BUG_ON(IS_ERR(trans));
be20aa9d 1060
80ff3856
YZ
1061 cow_start = (u64)-1;
1062 cur_offset = start;
1063 while (1) {
1064 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1065 cur_offset, 0);
1066 BUG_ON(ret < 0);
1067 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1068 leaf = path->nodes[0];
1069 btrfs_item_key_to_cpu(leaf, &found_key,
1070 path->slots[0] - 1);
1071 if (found_key.objectid == inode->i_ino &&
1072 found_key.type == BTRFS_EXTENT_DATA_KEY)
1073 path->slots[0]--;
1074 }
1075 check_prev = 0;
1076next_slot:
1077 leaf = path->nodes[0];
1078 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1079 ret = btrfs_next_leaf(root, path);
1080 if (ret < 0)
1081 BUG_ON(1);
1082 if (ret > 0)
1083 break;
1084 leaf = path->nodes[0];
1085 }
be20aa9d 1086
80ff3856
YZ
1087 nocow = 0;
1088 disk_bytenr = 0;
17d217fe 1089 num_bytes = 0;
80ff3856
YZ
1090 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1091
1092 if (found_key.objectid > inode->i_ino ||
1093 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1094 found_key.offset > end)
1095 break;
1096
1097 if (found_key.offset > cur_offset) {
1098 extent_end = found_key.offset;
e9061e21 1099 extent_type = 0;
80ff3856
YZ
1100 goto out_check;
1101 }
1102
1103 fi = btrfs_item_ptr(leaf, path->slots[0],
1104 struct btrfs_file_extent_item);
1105 extent_type = btrfs_file_extent_type(leaf, fi);
1106
d899e052
YZ
1107 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1108 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1109 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1110 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1111 extent_end = found_key.offset +
1112 btrfs_file_extent_num_bytes(leaf, fi);
1113 if (extent_end <= start) {
1114 path->slots[0]++;
1115 goto next_slot;
1116 }
17d217fe
YZ
1117 if (disk_bytenr == 0)
1118 goto out_check;
80ff3856
YZ
1119 if (btrfs_file_extent_compression(leaf, fi) ||
1120 btrfs_file_extent_encryption(leaf, fi) ||
1121 btrfs_file_extent_other_encoding(leaf, fi))
1122 goto out_check;
d899e052
YZ
1123 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1124 goto out_check;
d2fb3437 1125 if (btrfs_extent_readonly(root, disk_bytenr))
80ff3856 1126 goto out_check;
17d217fe 1127 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5d4f98a2
YZ
1128 found_key.offset -
1129 extent_offset, disk_bytenr))
17d217fe 1130 goto out_check;
5d4f98a2 1131 disk_bytenr += extent_offset;
17d217fe
YZ
1132 disk_bytenr += cur_offset - found_key.offset;
1133 num_bytes = min(end + 1, extent_end) - cur_offset;
1134 /*
1135 * force cow if csum exists in the range.
1136 * this ensure that csum for a given extent are
1137 * either valid or do not exist.
1138 */
1139 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1140 goto out_check;
80ff3856
YZ
1141 nocow = 1;
1142 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1143 extent_end = found_key.offset +
1144 btrfs_file_extent_inline_len(leaf, fi);
1145 extent_end = ALIGN(extent_end, root->sectorsize);
1146 } else {
1147 BUG_ON(1);
1148 }
1149out_check:
1150 if (extent_end <= start) {
1151 path->slots[0]++;
1152 goto next_slot;
1153 }
1154 if (!nocow) {
1155 if (cow_start == (u64)-1)
1156 cow_start = cur_offset;
1157 cur_offset = extent_end;
1158 if (cur_offset > end)
1159 break;
1160 path->slots[0]++;
1161 goto next_slot;
7ea394f1
YZ
1162 }
1163
1164 btrfs_release_path(root, path);
80ff3856
YZ
1165 if (cow_start != (u64)-1) {
1166 ret = cow_file_range(inode, locked_page, cow_start,
771ed689
CM
1167 found_key.offset - 1, page_started,
1168 nr_written, 1);
80ff3856
YZ
1169 BUG_ON(ret);
1170 cow_start = (u64)-1;
7ea394f1 1171 }
80ff3856 1172
d899e052
YZ
1173 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1174 struct extent_map *em;
1175 struct extent_map_tree *em_tree;
1176 em_tree = &BTRFS_I(inode)->extent_tree;
1177 em = alloc_extent_map(GFP_NOFS);
c26a9203 1178 BUG_ON(!em);
d899e052 1179 em->start = cur_offset;
445a6944 1180 em->orig_start = em->start;
d899e052
YZ
1181 em->len = num_bytes;
1182 em->block_len = num_bytes;
1183 em->block_start = disk_bytenr;
1184 em->bdev = root->fs_info->fs_devices->latest_bdev;
1185 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1186 while (1) {
890871be 1187 write_lock(&em_tree->lock);
d899e052 1188 ret = add_extent_mapping(em_tree, em);
890871be 1189 write_unlock(&em_tree->lock);
d899e052
YZ
1190 if (ret != -EEXIST) {
1191 free_extent_map(em);
1192 break;
1193 }
1194 btrfs_drop_extent_cache(inode, em->start,
1195 em->start + em->len - 1, 0);
1196 }
1197 type = BTRFS_ORDERED_PREALLOC;
1198 } else {
1199 type = BTRFS_ORDERED_NOCOW;
1200 }
80ff3856
YZ
1201
1202 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052
YZ
1203 num_bytes, num_bytes, type);
1204 BUG_ON(ret);
771ed689 1205
efa56464
YZ
1206 if (root->root_key.objectid ==
1207 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1208 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1209 num_bytes);
1210 BUG_ON(ret);
1211 }
1212
d899e052 1213 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
a791e35e
CM
1214 cur_offset, cur_offset + num_bytes - 1,
1215 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1216 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1217 EXTENT_SET_PRIVATE2);
80ff3856
YZ
1218 cur_offset = extent_end;
1219 if (cur_offset > end)
1220 break;
be20aa9d 1221 }
80ff3856
YZ
1222 btrfs_release_path(root, path);
1223
1224 if (cur_offset <= end && cow_start == (u64)-1)
1225 cow_start = cur_offset;
1226 if (cow_start != (u64)-1) {
1227 ret = cow_file_range(inode, locked_page, cow_start, end,
771ed689 1228 page_started, nr_written, 1);
80ff3856
YZ
1229 BUG_ON(ret);
1230 }
1231
0cb59c99
JB
1232 if (nolock) {
1233 ret = btrfs_end_transaction_nolock(trans, root);
1234 BUG_ON(ret);
1235 } else {
1236 ret = btrfs_end_transaction(trans, root);
1237 BUG_ON(ret);
1238 }
7ea394f1 1239 btrfs_free_path(path);
80ff3856 1240 return 0;
be20aa9d
CM
1241}
1242
d352ac68
CM
1243/*
1244 * extent_io.c call back to do delayed allocation processing
1245 */
c8b97818 1246static int run_delalloc_range(struct inode *inode, struct page *locked_page,
771ed689
CM
1247 u64 start, u64 end, int *page_started,
1248 unsigned long *nr_written)
be20aa9d 1249{
be20aa9d 1250 int ret;
7f366cfe 1251 struct btrfs_root *root = BTRFS_I(inode)->root;
a2135011 1252
6cbff00f 1253 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
c8b97818 1254 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1255 page_started, 1, nr_written);
6cbff00f 1256 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
d899e052 1257 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1258 page_started, 0, nr_written);
1e701a32 1259 else if (!btrfs_test_opt(root, COMPRESS) &&
75e7cb7f
LB
1260 !(BTRFS_I(inode)->force_compress) &&
1261 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
7f366cfe
CM
1262 ret = cow_file_range(inode, locked_page, start, end,
1263 page_started, nr_written, 1);
be20aa9d 1264 else
771ed689 1265 ret = cow_file_range_async(inode, locked_page, start, end,
d397712b 1266 page_started, nr_written);
b888db2b
CM
1267 return ret;
1268}
1269
9ed74f2d 1270static int btrfs_split_extent_hook(struct inode *inode,
0ca1f7ce 1271 struct extent_state *orig, u64 split)
9ed74f2d 1272{
0ca1f7ce 1273 /* not delalloc, ignore it */
9ed74f2d
JB
1274 if (!(orig->state & EXTENT_DELALLOC))
1275 return 0;
1276
0ca1f7ce 1277 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
9ed74f2d
JB
1278 return 0;
1279}
1280
1281/*
1282 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1283 * extents so we can keep track of new extents that are just merged onto old
1284 * extents, such as when we are doing sequential writes, so we can properly
1285 * account for the metadata space we'll need.
1286 */
1287static int btrfs_merge_extent_hook(struct inode *inode,
1288 struct extent_state *new,
1289 struct extent_state *other)
1290{
9ed74f2d
JB
1291 /* not delalloc, ignore it */
1292 if (!(other->state & EXTENT_DELALLOC))
1293 return 0;
1294
0ca1f7ce 1295 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
9ed74f2d
JB
1296 return 0;
1297}
1298
d352ac68
CM
1299/*
1300 * extent_io.c set_bit_hook, used to track delayed allocation
1301 * bytes in this file, and to maintain the list of inodes that
1302 * have pending delalloc work to be done.
1303 */
0ca1f7ce
YZ
1304static int btrfs_set_bit_hook(struct inode *inode,
1305 struct extent_state *state, int *bits)
291d673e 1306{
9ed74f2d 1307
75eff68e
CM
1308 /*
1309 * set_bit and clear bit hooks normally require _irqsave/restore
1310 * but in this case, we are only testeing for the DELALLOC
1311 * bit, which is only set or cleared with irqs on
1312 */
0ca1f7ce 1313 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1314 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1315 u64 len = state->end + 1 - state->start;
0cb59c99
JB
1316 int do_list = (root->root_key.objectid !=
1317 BTRFS_ROOT_TREE_OBJECTID);
9ed74f2d 1318
0ca1f7ce
YZ
1319 if (*bits & EXTENT_FIRST_DELALLOC)
1320 *bits &= ~EXTENT_FIRST_DELALLOC;
1321 else
1322 atomic_inc(&BTRFS_I(inode)->outstanding_extents);
287a0ab9 1323
75eff68e 1324 spin_lock(&root->fs_info->delalloc_lock);
0ca1f7ce
YZ
1325 BTRFS_I(inode)->delalloc_bytes += len;
1326 root->fs_info->delalloc_bytes += len;
0cb59c99 1327 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
ea8c2819
CM
1328 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1329 &root->fs_info->delalloc_inodes);
1330 }
75eff68e 1331 spin_unlock(&root->fs_info->delalloc_lock);
291d673e
CM
1332 }
1333 return 0;
1334}
1335
d352ac68
CM
1336/*
1337 * extent_io.c clear_bit_hook, see set_bit_hook for why
1338 */
9ed74f2d 1339static int btrfs_clear_bit_hook(struct inode *inode,
0ca1f7ce 1340 struct extent_state *state, int *bits)
291d673e 1341{
75eff68e
CM
1342 /*
1343 * set_bit and clear bit hooks normally require _irqsave/restore
1344 * but in this case, we are only testeing for the DELALLOC
1345 * bit, which is only set or cleared with irqs on
1346 */
0ca1f7ce 1347 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1348 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1349 u64 len = state->end + 1 - state->start;
0cb59c99
JB
1350 int do_list = (root->root_key.objectid !=
1351 BTRFS_ROOT_TREE_OBJECTID);
bcbfce8a 1352
0ca1f7ce
YZ
1353 if (*bits & EXTENT_FIRST_DELALLOC)
1354 *bits &= ~EXTENT_FIRST_DELALLOC;
1355 else if (!(*bits & EXTENT_DO_ACCOUNTING))
1356 atomic_dec(&BTRFS_I(inode)->outstanding_extents);
1357
1358 if (*bits & EXTENT_DO_ACCOUNTING)
1359 btrfs_delalloc_release_metadata(inode, len);
1360
0cb59c99
JB
1361 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1362 && do_list)
0ca1f7ce 1363 btrfs_free_reserved_data_space(inode, len);
9ed74f2d 1364
75eff68e 1365 spin_lock(&root->fs_info->delalloc_lock);
0ca1f7ce
YZ
1366 root->fs_info->delalloc_bytes -= len;
1367 BTRFS_I(inode)->delalloc_bytes -= len;
1368
0cb59c99 1369 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
ea8c2819
CM
1370 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1371 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1372 }
75eff68e 1373 spin_unlock(&root->fs_info->delalloc_lock);
291d673e
CM
1374 }
1375 return 0;
1376}
1377
d352ac68
CM
1378/*
1379 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1380 * we don't create bios that span stripes or chunks
1381 */
239b14b3 1382int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
c8b97818
CM
1383 size_t size, struct bio *bio,
1384 unsigned long bio_flags)
239b14b3
CM
1385{
1386 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1387 struct btrfs_mapping_tree *map_tree;
a62b9401 1388 u64 logical = (u64)bio->bi_sector << 9;
239b14b3
CM
1389 u64 length = 0;
1390 u64 map_length;
239b14b3
CM
1391 int ret;
1392
771ed689
CM
1393 if (bio_flags & EXTENT_BIO_COMPRESSED)
1394 return 0;
1395
f2d8d74d 1396 length = bio->bi_size;
239b14b3
CM
1397 map_tree = &root->fs_info->mapping_tree;
1398 map_length = length;
cea9e445 1399 ret = btrfs_map_block(map_tree, READ, logical,
f188591e 1400 &map_length, NULL, 0);
cea9e445 1401
d397712b 1402 if (map_length < length + size)
239b14b3 1403 return 1;
411fc6bc 1404 return ret;
239b14b3
CM
1405}
1406
d352ac68
CM
1407/*
1408 * in order to insert checksums into the metadata in large chunks,
1409 * we wait until bio submission time. All the pages in the bio are
1410 * checksummed and sums are attached onto the ordered extent record.
1411 *
1412 * At IO completion time the cums attached on the ordered extent record
1413 * are inserted into the btree
1414 */
d397712b
CM
1415static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1416 struct bio *bio, int mirror_num,
eaf25d93
CM
1417 unsigned long bio_flags,
1418 u64 bio_offset)
065631f6 1419{
065631f6 1420 struct btrfs_root *root = BTRFS_I(inode)->root;
065631f6 1421 int ret = 0;
e015640f 1422
d20f7043 1423 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
44b8bd7e 1424 BUG_ON(ret);
4a69a410
CM
1425 return 0;
1426}
e015640f 1427
4a69a410
CM
1428/*
1429 * in order to insert checksums into the metadata in large chunks,
1430 * we wait until bio submission time. All the pages in the bio are
1431 * checksummed and sums are attached onto the ordered extent record.
1432 *
1433 * At IO completion time the cums attached on the ordered extent record
1434 * are inserted into the btree
1435 */
b2950863 1436static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1437 int mirror_num, unsigned long bio_flags,
1438 u64 bio_offset)
4a69a410
CM
1439{
1440 struct btrfs_root *root = BTRFS_I(inode)->root;
8b712842 1441 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
44b8bd7e
CM
1442}
1443
d352ac68 1444/*
cad321ad
CM
1445 * extent_io.c submission hook. This does the right thing for csum calculation
1446 * on write, or reading the csums from the tree before a read
d352ac68 1447 */
b2950863 1448static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
eaf25d93
CM
1449 int mirror_num, unsigned long bio_flags,
1450 u64 bio_offset)
44b8bd7e
CM
1451{
1452 struct btrfs_root *root = BTRFS_I(inode)->root;
1453 int ret = 0;
19b9bdb0 1454 int skip_sum;
44b8bd7e 1455
6cbff00f 1456 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 1457
0cb59c99
JB
1458 if (root == root->fs_info->tree_root)
1459 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1460 else
1461 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
e6dcd2dc 1462 BUG_ON(ret);
065631f6 1463
7b6d91da 1464 if (!(rw & REQ_WRITE)) {
d20f7043 1465 if (bio_flags & EXTENT_BIO_COMPRESSED) {
c8b97818
CM
1466 return btrfs_submit_compressed_read(inode, bio,
1467 mirror_num, bio_flags);
d20f7043
CM
1468 } else if (!skip_sum)
1469 btrfs_lookup_bio_sums(root, inode, bio, NULL);
4d1b5fb4 1470 goto mapit;
19b9bdb0 1471 } else if (!skip_sum) {
17d217fe
YZ
1472 /* csum items have already been cloned */
1473 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1474 goto mapit;
19b9bdb0
CM
1475 /* we're doing a write, do the async checksumming */
1476 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
44b8bd7e 1477 inode, rw, bio, mirror_num,
eaf25d93
CM
1478 bio_flags, bio_offset,
1479 __btrfs_submit_bio_start,
4a69a410 1480 __btrfs_submit_bio_done);
19b9bdb0
CM
1481 }
1482
0b86a832 1483mapit:
8b712842 1484 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
065631f6 1485}
6885f308 1486
d352ac68
CM
1487/*
1488 * given a list of ordered sums record them in the inode. This happens
1489 * at IO completion time based on sums calculated at bio submission time.
1490 */
ba1da2f4 1491static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
e6dcd2dc
CM
1492 struct inode *inode, u64 file_offset,
1493 struct list_head *list)
1494{
e6dcd2dc
CM
1495 struct btrfs_ordered_sum *sum;
1496
1497 btrfs_set_trans_block_group(trans, inode);
c6e30871
QF
1498
1499 list_for_each_entry(sum, list, list) {
d20f7043
CM
1500 btrfs_csum_file_blocks(trans,
1501 BTRFS_I(inode)->root->fs_info->csum_root, sum);
e6dcd2dc
CM
1502 }
1503 return 0;
1504}
1505
2ac55d41
JB
1506int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1507 struct extent_state **cached_state)
ea8c2819 1508{
d397712b 1509 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
771ed689 1510 WARN_ON(1);
ea8c2819 1511 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2ac55d41 1512 cached_state, GFP_NOFS);
ea8c2819
CM
1513}
1514
d352ac68 1515/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
1516struct btrfs_writepage_fixup {
1517 struct page *page;
1518 struct btrfs_work work;
1519};
1520
b2950863 1521static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
1522{
1523 struct btrfs_writepage_fixup *fixup;
1524 struct btrfs_ordered_extent *ordered;
2ac55d41 1525 struct extent_state *cached_state = NULL;
247e743c
CM
1526 struct page *page;
1527 struct inode *inode;
1528 u64 page_start;
1529 u64 page_end;
1530
1531 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1532 page = fixup->page;
4a096752 1533again:
247e743c
CM
1534 lock_page(page);
1535 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1536 ClearPageChecked(page);
1537 goto out_page;
1538 }
1539
1540 inode = page->mapping->host;
1541 page_start = page_offset(page);
1542 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1543
2ac55d41
JB
1544 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1545 &cached_state, GFP_NOFS);
4a096752
CM
1546
1547 /* already ordered? We're done */
8b62b72b 1548 if (PagePrivate2(page))
247e743c 1549 goto out;
4a096752
CM
1550
1551 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1552 if (ordered) {
2ac55d41
JB
1553 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1554 page_end, &cached_state, GFP_NOFS);
4a096752
CM
1555 unlock_page(page);
1556 btrfs_start_ordered_extent(inode, ordered, 1);
1557 goto again;
1558 }
247e743c 1559
0ca1f7ce 1560 BUG();
2ac55d41 1561 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
247e743c
CM
1562 ClearPageChecked(page);
1563out:
2ac55d41
JB
1564 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1565 &cached_state, GFP_NOFS);
247e743c
CM
1566out_page:
1567 unlock_page(page);
1568 page_cache_release(page);
b897abec 1569 kfree(fixup);
247e743c
CM
1570}
1571
1572/*
1573 * There are a few paths in the higher layers of the kernel that directly
1574 * set the page dirty bit without asking the filesystem if it is a
1575 * good idea. This causes problems because we want to make sure COW
1576 * properly happens and the data=ordered rules are followed.
1577 *
c8b97818 1578 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
1579 * hasn't been properly setup for IO. We kick off an async process
1580 * to fix it up. The async helper will wait for ordered extents, set
1581 * the delalloc bit and make it safe to write the page.
1582 */
b2950863 1583static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
247e743c
CM
1584{
1585 struct inode *inode = page->mapping->host;
1586 struct btrfs_writepage_fixup *fixup;
1587 struct btrfs_root *root = BTRFS_I(inode)->root;
247e743c 1588
8b62b72b
CM
1589 /* this page is properly in the ordered list */
1590 if (TestClearPagePrivate2(page))
247e743c
CM
1591 return 0;
1592
1593 if (PageChecked(page))
1594 return -EAGAIN;
1595
1596 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1597 if (!fixup)
1598 return -EAGAIN;
f421950f 1599
247e743c
CM
1600 SetPageChecked(page);
1601 page_cache_get(page);
1602 fixup->work.func = btrfs_writepage_fixup_worker;
1603 fixup->page = page;
1604 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1605 return -EAGAIN;
1606}
1607
d899e052
YZ
1608static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1609 struct inode *inode, u64 file_pos,
1610 u64 disk_bytenr, u64 disk_num_bytes,
1611 u64 num_bytes, u64 ram_bytes,
1612 u8 compression, u8 encryption,
1613 u16 other_encoding, int extent_type)
1614{
1615 struct btrfs_root *root = BTRFS_I(inode)->root;
1616 struct btrfs_file_extent_item *fi;
1617 struct btrfs_path *path;
1618 struct extent_buffer *leaf;
1619 struct btrfs_key ins;
1620 u64 hint;
1621 int ret;
1622
1623 path = btrfs_alloc_path();
1624 BUG_ON(!path);
1625
b9473439 1626 path->leave_spinning = 1;
a1ed835e
CM
1627
1628 /*
1629 * we may be replacing one extent in the tree with another.
1630 * The new extent is pinned in the extent map, and we don't want
1631 * to drop it from the cache until it is completely in the btree.
1632 *
1633 * So, tell btrfs_drop_extents to leave this extent in the cache.
1634 * the caller is expected to unpin it and allow it to be merged
1635 * with the others.
1636 */
920bbbfb
YZ
1637 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1638 &hint, 0);
d899e052
YZ
1639 BUG_ON(ret);
1640
1641 ins.objectid = inode->i_ino;
1642 ins.offset = file_pos;
1643 ins.type = BTRFS_EXTENT_DATA_KEY;
1644 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1645 BUG_ON(ret);
1646 leaf = path->nodes[0];
1647 fi = btrfs_item_ptr(leaf, path->slots[0],
1648 struct btrfs_file_extent_item);
1649 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1650 btrfs_set_file_extent_type(leaf, fi, extent_type);
1651 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1652 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1653 btrfs_set_file_extent_offset(leaf, fi, 0);
1654 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1655 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1656 btrfs_set_file_extent_compression(leaf, fi, compression);
1657 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1658 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439
CM
1659
1660 btrfs_unlock_up_safe(path, 1);
1661 btrfs_set_lock_blocking(leaf);
1662
d899e052
YZ
1663 btrfs_mark_buffer_dirty(leaf);
1664
1665 inode_add_bytes(inode, num_bytes);
d899e052
YZ
1666
1667 ins.objectid = disk_bytenr;
1668 ins.offset = disk_num_bytes;
1669 ins.type = BTRFS_EXTENT_ITEM_KEY;
5d4f98a2
YZ
1670 ret = btrfs_alloc_reserved_file_extent(trans, root,
1671 root->root_key.objectid,
1672 inode->i_ino, file_pos, &ins);
d899e052 1673 BUG_ON(ret);
d899e052 1674 btrfs_free_path(path);
b9473439 1675
d899e052
YZ
1676 return 0;
1677}
1678
5d13a98f
CM
1679/*
1680 * helper function for btrfs_finish_ordered_io, this
1681 * just reads in some of the csum leaves to prime them into ram
1682 * before we start the transaction. It limits the amount of btree
1683 * reads required while inside the transaction.
1684 */
d352ac68
CM
1685/* as ordered data IO finishes, this gets called so we can finish
1686 * an ordered extent if the range of bytes in the file it covers are
1687 * fully written.
1688 */
211f90e6 1689static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
e6dcd2dc 1690{
e6dcd2dc 1691 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1692 struct btrfs_trans_handle *trans = NULL;
5d13a98f 1693 struct btrfs_ordered_extent *ordered_extent = NULL;
e6dcd2dc 1694 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2ac55d41 1695 struct extent_state *cached_state = NULL;
261507a0 1696 int compress_type = 0;
e6dcd2dc 1697 int ret;
0cb59c99 1698 bool nolock = false;
e6dcd2dc 1699
5a1a3df1
JB
1700 ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1701 end - start + 1);
ba1da2f4 1702 if (!ret)
e6dcd2dc 1703 return 0;
e6dcd2dc 1704 BUG_ON(!ordered_extent);
efd049fb 1705
0cb59c99
JB
1706 nolock = (root == root->fs_info->tree_root);
1707
c2167754
YZ
1708 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1709 BUG_ON(!list_empty(&ordered_extent->list));
1710 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1711 if (!ret) {
0cb59c99
JB
1712 if (nolock)
1713 trans = btrfs_join_transaction_nolock(root, 1);
1714 else
1715 trans = btrfs_join_transaction(root, 1);
3612b495 1716 BUG_ON(IS_ERR(trans));
0ca1f7ce
YZ
1717 btrfs_set_trans_block_group(trans, inode);
1718 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
c2167754
YZ
1719 ret = btrfs_update_inode(trans, root, inode);
1720 BUG_ON(ret);
c2167754
YZ
1721 }
1722 goto out;
1723 }
e6dcd2dc 1724
2ac55d41
JB
1725 lock_extent_bits(io_tree, ordered_extent->file_offset,
1726 ordered_extent->file_offset + ordered_extent->len - 1,
1727 0, &cached_state, GFP_NOFS);
e6dcd2dc 1728
0cb59c99
JB
1729 if (nolock)
1730 trans = btrfs_join_transaction_nolock(root, 1);
1731 else
1732 trans = btrfs_join_transaction(root, 1);
3612b495 1733 BUG_ON(IS_ERR(trans));
0ca1f7ce
YZ
1734 btrfs_set_trans_block_group(trans, inode);
1735 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
c2167754 1736
c8b97818 1737 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
261507a0 1738 compress_type = ordered_extent->compress_type;
d899e052 1739 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
261507a0 1740 BUG_ON(compress_type);
920bbbfb 1741 ret = btrfs_mark_extent_written(trans, inode,
d899e052
YZ
1742 ordered_extent->file_offset,
1743 ordered_extent->file_offset +
1744 ordered_extent->len);
1745 BUG_ON(ret);
1746 } else {
0af3d00b 1747 BUG_ON(root == root->fs_info->tree_root);
d899e052
YZ
1748 ret = insert_reserved_file_extent(trans, inode,
1749 ordered_extent->file_offset,
1750 ordered_extent->start,
1751 ordered_extent->disk_len,
1752 ordered_extent->len,
1753 ordered_extent->len,
261507a0 1754 compress_type, 0, 0,
d899e052 1755 BTRFS_FILE_EXTENT_REG);
a1ed835e
CM
1756 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1757 ordered_extent->file_offset,
1758 ordered_extent->len);
d899e052
YZ
1759 BUG_ON(ret);
1760 }
2ac55d41
JB
1761 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1762 ordered_extent->file_offset +
1763 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1764
e6dcd2dc
CM
1765 add_pending_csums(trans, inode, ordered_extent->file_offset,
1766 &ordered_extent->list);
1767
c2167754
YZ
1768 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1769 ret = btrfs_update_inode(trans, root, inode);
1770 BUG_ON(ret);
c2167754 1771out:
0cb59c99
JB
1772 if (nolock) {
1773 if (trans)
1774 btrfs_end_transaction_nolock(trans, root);
1775 } else {
1776 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1777 if (trans)
1778 btrfs_end_transaction(trans, root);
1779 }
1780
e6dcd2dc
CM
1781 /* once for us */
1782 btrfs_put_ordered_extent(ordered_extent);
1783 /* once for the tree */
1784 btrfs_put_ordered_extent(ordered_extent);
1785
e6dcd2dc
CM
1786 return 0;
1787}
1788
b2950863 1789static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
211f90e6
CM
1790 struct extent_state *state, int uptodate)
1791{
1abe9b8a 1792 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1793
8b62b72b 1794 ClearPagePrivate2(page);
211f90e6
CM
1795 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1796}
1797
d352ac68
CM
1798/*
1799 * When IO fails, either with EIO or csum verification fails, we
1800 * try other mirrors that might have a good copy of the data. This
1801 * io_failure_record is used to record state as we go through all the
1802 * mirrors. If another mirror has good data, the page is set up to date
1803 * and things continue. If a good mirror can't be found, the original
1804 * bio end_io callback is called to indicate things have failed.
1805 */
7e38326f
CM
1806struct io_failure_record {
1807 struct page *page;
1808 u64 start;
1809 u64 len;
1810 u64 logical;
d20f7043 1811 unsigned long bio_flags;
7e38326f
CM
1812 int last_mirror;
1813};
1814
b2950863 1815static int btrfs_io_failed_hook(struct bio *failed_bio,
1259ab75
CM
1816 struct page *page, u64 start, u64 end,
1817 struct extent_state *state)
7e38326f
CM
1818{
1819 struct io_failure_record *failrec = NULL;
1820 u64 private;
1821 struct extent_map *em;
1822 struct inode *inode = page->mapping->host;
1823 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
3b951516 1824 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7e38326f
CM
1825 struct bio *bio;
1826 int num_copies;
1827 int ret;
1259ab75 1828 int rw;
7e38326f
CM
1829 u64 logical;
1830
1831 ret = get_state_private(failure_tree, start, &private);
1832 if (ret) {
7e38326f
CM
1833 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1834 if (!failrec)
1835 return -ENOMEM;
1836 failrec->start = start;
1837 failrec->len = end - start + 1;
1838 failrec->last_mirror = 0;
d20f7043 1839 failrec->bio_flags = 0;
7e38326f 1840
890871be 1841 read_lock(&em_tree->lock);
3b951516
CM
1842 em = lookup_extent_mapping(em_tree, start, failrec->len);
1843 if (em->start > start || em->start + em->len < start) {
1844 free_extent_map(em);
1845 em = NULL;
1846 }
890871be 1847 read_unlock(&em_tree->lock);
7e38326f
CM
1848
1849 if (!em || IS_ERR(em)) {
1850 kfree(failrec);
1851 return -EIO;
1852 }
1853 logical = start - em->start;
1854 logical = em->block_start + logical;
d20f7043
CM
1855 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1856 logical = em->block_start;
1857 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
261507a0
LZ
1858 extent_set_compress_type(&failrec->bio_flags,
1859 em->compress_type);
d20f7043 1860 }
7e38326f
CM
1861 failrec->logical = logical;
1862 free_extent_map(em);
1863 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1864 EXTENT_DIRTY, GFP_NOFS);
587f7704
CM
1865 set_state_private(failure_tree, start,
1866 (u64)(unsigned long)failrec);
7e38326f 1867 } else {
587f7704 1868 failrec = (struct io_failure_record *)(unsigned long)private;
7e38326f
CM
1869 }
1870 num_copies = btrfs_num_copies(
1871 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1872 failrec->logical, failrec->len);
1873 failrec->last_mirror++;
1874 if (!state) {
cad321ad 1875 spin_lock(&BTRFS_I(inode)->io_tree.lock);
7e38326f
CM
1876 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1877 failrec->start,
1878 EXTENT_LOCKED);
1879 if (state && state->start != failrec->start)
1880 state = NULL;
cad321ad 1881 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
7e38326f
CM
1882 }
1883 if (!state || failrec->last_mirror > num_copies) {
1884 set_state_private(failure_tree, failrec->start, 0);
1885 clear_extent_bits(failure_tree, failrec->start,
1886 failrec->start + failrec->len - 1,
1887 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1888 kfree(failrec);
1889 return -EIO;
1890 }
1891 bio = bio_alloc(GFP_NOFS, 1);
1892 bio->bi_private = state;
1893 bio->bi_end_io = failed_bio->bi_end_io;
1894 bio->bi_sector = failrec->logical >> 9;
1895 bio->bi_bdev = failed_bio->bi_bdev;
e1c4b745 1896 bio->bi_size = 0;
d20f7043 1897
7e38326f 1898 bio_add_page(bio, page, failrec->len, start - page_offset(page));
7b6d91da 1899 if (failed_bio->bi_rw & REQ_WRITE)
1259ab75
CM
1900 rw = WRITE;
1901 else
1902 rw = READ;
1903
1904 BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
c8b97818 1905 failrec->last_mirror,
eaf25d93 1906 failrec->bio_flags, 0);
1259ab75
CM
1907 return 0;
1908}
1909
d352ac68
CM
1910/*
1911 * each time an IO finishes, we do a fast check in the IO failure tree
1912 * to see if we need to process or clean up an io_failure_record
1913 */
b2950863 1914static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1259ab75
CM
1915{
1916 u64 private;
1917 u64 private_failure;
1918 struct io_failure_record *failure;
1919 int ret;
1920
1921 private = 0;
1922 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
ec29ed5b 1923 (u64)-1, 1, EXTENT_DIRTY, 0)) {
1259ab75
CM
1924 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1925 start, &private_failure);
1926 if (ret == 0) {
1927 failure = (struct io_failure_record *)(unsigned long)
1928 private_failure;
1929 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1930 failure->start, 0);
1931 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1932 failure->start,
1933 failure->start + failure->len - 1,
1934 EXTENT_DIRTY | EXTENT_LOCKED,
1935 GFP_NOFS);
1936 kfree(failure);
1937 }
1938 }
7e38326f
CM
1939 return 0;
1940}
1941
d352ac68
CM
1942/*
1943 * when reads are done, we need to check csums to verify the data is correct
1944 * if there's a match, we allow the bio to finish. If not, we go through
1945 * the io_failure_record routines to find good copies
1946 */
b2950863 1947static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
70dec807 1948 struct extent_state *state)
07157aac 1949{
35ebb934 1950 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
07157aac 1951 struct inode *inode = page->mapping->host;
d1310b2e 1952 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
07157aac 1953 char *kaddr;
aadfeb6e 1954 u64 private = ~(u32)0;
07157aac 1955 int ret;
ff79f819
CM
1956 struct btrfs_root *root = BTRFS_I(inode)->root;
1957 u32 csum = ~(u32)0;
d1310b2e 1958
d20f7043
CM
1959 if (PageChecked(page)) {
1960 ClearPageChecked(page);
1961 goto good;
1962 }
6cbff00f
CH
1963
1964 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
17d217fe
YZ
1965 return 0;
1966
1967 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 1968 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
17d217fe
YZ
1969 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1970 GFP_NOFS);
b6cda9bc 1971 return 0;
17d217fe 1972 }
d20f7043 1973
c2e639f0 1974 if (state && state->start == start) {
70dec807
CM
1975 private = state->private;
1976 ret = 0;
1977 } else {
1978 ret = get_state_private(io_tree, start, &private);
1979 }
9ab86c8e 1980 kaddr = kmap_atomic(page, KM_USER0);
d397712b 1981 if (ret)
07157aac 1982 goto zeroit;
d397712b 1983
ff79f819
CM
1984 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1985 btrfs_csum_final(csum, (char *)&csum);
d397712b 1986 if (csum != private)
07157aac 1987 goto zeroit;
d397712b 1988
9ab86c8e 1989 kunmap_atomic(kaddr, KM_USER0);
d20f7043 1990good:
7e38326f
CM
1991 /* if the io failure tree for this inode is non-empty,
1992 * check to see if we've recovered from a failed IO
1993 */
1259ab75 1994 btrfs_clean_io_failures(inode, start);
07157aac
CM
1995 return 0;
1996
1997zeroit:
193f284d
CM
1998 if (printk_ratelimit()) {
1999 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
2000 "private %llu\n", page->mapping->host->i_ino,
2001 (unsigned long long)start, csum,
2002 (unsigned long long)private);
2003 }
db94535d
CM
2004 memset(kaddr + offset, 1, end - start + 1);
2005 flush_dcache_page(page);
9ab86c8e 2006 kunmap_atomic(kaddr, KM_USER0);
3b951516
CM
2007 if (private == 0)
2008 return 0;
7e38326f 2009 return -EIO;
07157aac 2010}
b888db2b 2011
24bbcf04
YZ
2012struct delayed_iput {
2013 struct list_head list;
2014 struct inode *inode;
2015};
2016
2017void btrfs_add_delayed_iput(struct inode *inode)
2018{
2019 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2020 struct delayed_iput *delayed;
2021
2022 if (atomic_add_unless(&inode->i_count, -1, 1))
2023 return;
2024
2025 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2026 delayed->inode = inode;
2027
2028 spin_lock(&fs_info->delayed_iput_lock);
2029 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2030 spin_unlock(&fs_info->delayed_iput_lock);
2031}
2032
2033void btrfs_run_delayed_iputs(struct btrfs_root *root)
2034{
2035 LIST_HEAD(list);
2036 struct btrfs_fs_info *fs_info = root->fs_info;
2037 struct delayed_iput *delayed;
2038 int empty;
2039
2040 spin_lock(&fs_info->delayed_iput_lock);
2041 empty = list_empty(&fs_info->delayed_iputs);
2042 spin_unlock(&fs_info->delayed_iput_lock);
2043 if (empty)
2044 return;
2045
2046 down_read(&root->fs_info->cleanup_work_sem);
2047 spin_lock(&fs_info->delayed_iput_lock);
2048 list_splice_init(&fs_info->delayed_iputs, &list);
2049 spin_unlock(&fs_info->delayed_iput_lock);
2050
2051 while (!list_empty(&list)) {
2052 delayed = list_entry(list.next, struct delayed_iput, list);
2053 list_del(&delayed->list);
2054 iput(delayed->inode);
2055 kfree(delayed);
2056 }
2057 up_read(&root->fs_info->cleanup_work_sem);
2058}
2059
d68fc57b
YZ
2060/*
2061 * calculate extra metadata reservation when snapshotting a subvolume
2062 * contains orphan files.
2063 */
2064void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2065 struct btrfs_pending_snapshot *pending,
2066 u64 *bytes_to_reserve)
2067{
2068 struct btrfs_root *root;
2069 struct btrfs_block_rsv *block_rsv;
2070 u64 num_bytes;
2071 int index;
2072
2073 root = pending->root;
2074 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2075 return;
2076
2077 block_rsv = root->orphan_block_rsv;
2078
2079 /* orphan block reservation for the snapshot */
2080 num_bytes = block_rsv->size;
2081
2082 /*
2083 * after the snapshot is created, COWing tree blocks may use more
2084 * space than it frees. So we should make sure there is enough
2085 * reserved space.
2086 */
2087 index = trans->transid & 0x1;
2088 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2089 num_bytes += block_rsv->size -
2090 (block_rsv->reserved + block_rsv->freed[index]);
2091 }
2092
2093 *bytes_to_reserve += num_bytes;
2094}
2095
2096void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2097 struct btrfs_pending_snapshot *pending)
2098{
2099 struct btrfs_root *root = pending->root;
2100 struct btrfs_root *snap = pending->snap;
2101 struct btrfs_block_rsv *block_rsv;
2102 u64 num_bytes;
2103 int index;
2104 int ret;
2105
2106 if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2107 return;
2108
2109 /* refill source subvolume's orphan block reservation */
2110 block_rsv = root->orphan_block_rsv;
2111 index = trans->transid & 0x1;
2112 if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2113 num_bytes = block_rsv->size -
2114 (block_rsv->reserved + block_rsv->freed[index]);
2115 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2116 root->orphan_block_rsv,
2117 num_bytes);
2118 BUG_ON(ret);
2119 }
2120
2121 /* setup orphan block reservation for the snapshot */
2122 block_rsv = btrfs_alloc_block_rsv(snap);
2123 BUG_ON(!block_rsv);
2124
2125 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2126 snap->orphan_block_rsv = block_rsv;
2127
2128 num_bytes = root->orphan_block_rsv->size;
2129 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2130 block_rsv, num_bytes);
2131 BUG_ON(ret);
2132
2133#if 0
2134 /* insert orphan item for the snapshot */
2135 WARN_ON(!root->orphan_item_inserted);
2136 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2137 snap->root_key.objectid);
2138 BUG_ON(ret);
2139 snap->orphan_item_inserted = 1;
2140#endif
2141}
2142
2143enum btrfs_orphan_cleanup_state {
2144 ORPHAN_CLEANUP_STARTED = 1,
2145 ORPHAN_CLEANUP_DONE = 2,
2146};
2147
2148/*
2149 * This is called in transaction commmit time. If there are no orphan
2150 * files in the subvolume, it removes orphan item and frees block_rsv
2151 * structure.
2152 */
2153void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2154 struct btrfs_root *root)
2155{
2156 int ret;
2157
2158 if (!list_empty(&root->orphan_list) ||
2159 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2160 return;
2161
2162 if (root->orphan_item_inserted &&
2163 btrfs_root_refs(&root->root_item) > 0) {
2164 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2165 root->root_key.objectid);
2166 BUG_ON(ret);
2167 root->orphan_item_inserted = 0;
2168 }
2169
2170 if (root->orphan_block_rsv) {
2171 WARN_ON(root->orphan_block_rsv->size > 0);
2172 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2173 root->orphan_block_rsv = NULL;
2174 }
2175}
2176
7b128766
JB
2177/*
2178 * This creates an orphan entry for the given inode in case something goes
2179 * wrong in the middle of an unlink/truncate.
d68fc57b
YZ
2180 *
2181 * NOTE: caller of this function should reserve 5 units of metadata for
2182 * this function.
7b128766
JB
2183 */
2184int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2185{
2186 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
2187 struct btrfs_block_rsv *block_rsv = NULL;
2188 int reserve = 0;
2189 int insert = 0;
2190 int ret;
7b128766 2191
d68fc57b
YZ
2192 if (!root->orphan_block_rsv) {
2193 block_rsv = btrfs_alloc_block_rsv(root);
2194 BUG_ON(!block_rsv);
2195 }
7b128766 2196
d68fc57b
YZ
2197 spin_lock(&root->orphan_lock);
2198 if (!root->orphan_block_rsv) {
2199 root->orphan_block_rsv = block_rsv;
2200 } else if (block_rsv) {
2201 btrfs_free_block_rsv(root, block_rsv);
2202 block_rsv = NULL;
7b128766 2203 }
7b128766 2204
d68fc57b
YZ
2205 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2206 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2207#if 0
2208 /*
2209 * For proper ENOSPC handling, we should do orphan
2210 * cleanup when mounting. But this introduces backward
2211 * compatibility issue.
2212 */
2213 if (!xchg(&root->orphan_item_inserted, 1))
2214 insert = 2;
2215 else
2216 insert = 1;
2217#endif
2218 insert = 1;
2219 } else {
2220 WARN_ON(!BTRFS_I(inode)->orphan_meta_reserved);
7b128766
JB
2221 }
2222
d68fc57b
YZ
2223 if (!BTRFS_I(inode)->orphan_meta_reserved) {
2224 BTRFS_I(inode)->orphan_meta_reserved = 1;
2225 reserve = 1;
2226 }
2227 spin_unlock(&root->orphan_lock);
7b128766 2228
d68fc57b
YZ
2229 if (block_rsv)
2230 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
7b128766 2231
d68fc57b
YZ
2232 /* grab metadata reservation from transaction handle */
2233 if (reserve) {
2234 ret = btrfs_orphan_reserve_metadata(trans, inode);
2235 BUG_ON(ret);
2236 }
7b128766 2237
d68fc57b
YZ
2238 /* insert an orphan item to track this unlinked/truncated file */
2239 if (insert >= 1) {
2240 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2241 BUG_ON(ret);
2242 }
2243
2244 /* insert an orphan item to track subvolume contains orphan files */
2245 if (insert >= 2) {
2246 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2247 root->root_key.objectid);
2248 BUG_ON(ret);
2249 }
2250 return 0;
7b128766
JB
2251}
2252
2253/*
2254 * We have done the truncate/delete so we can go ahead and remove the orphan
2255 * item for this particular inode.
2256 */
2257int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2258{
2259 struct btrfs_root *root = BTRFS_I(inode)->root;
d68fc57b
YZ
2260 int delete_item = 0;
2261 int release_rsv = 0;
7b128766
JB
2262 int ret = 0;
2263
d68fc57b
YZ
2264 spin_lock(&root->orphan_lock);
2265 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2266 list_del_init(&BTRFS_I(inode)->i_orphan);
2267 delete_item = 1;
7b128766
JB
2268 }
2269
d68fc57b
YZ
2270 if (BTRFS_I(inode)->orphan_meta_reserved) {
2271 BTRFS_I(inode)->orphan_meta_reserved = 0;
2272 release_rsv = 1;
7b128766 2273 }
d68fc57b 2274 spin_unlock(&root->orphan_lock);
7b128766 2275
d68fc57b
YZ
2276 if (trans && delete_item) {
2277 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2278 BUG_ON(ret);
2279 }
7b128766 2280
d68fc57b
YZ
2281 if (release_rsv)
2282 btrfs_orphan_release_metadata(inode);
7b128766 2283
d68fc57b 2284 return 0;
7b128766
JB
2285}
2286
2287/*
2288 * this cleans up any orphans that may be left on the list from the last use
2289 * of this root.
2290 */
66b4ffd1 2291int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766
JB
2292{
2293 struct btrfs_path *path;
2294 struct extent_buffer *leaf;
7b128766
JB
2295 struct btrfs_key key, found_key;
2296 struct btrfs_trans_handle *trans;
2297 struct inode *inode;
2298 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2299
d68fc57b 2300 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 2301 return 0;
c71bf099
YZ
2302
2303 path = btrfs_alloc_path();
66b4ffd1
JB
2304 if (!path) {
2305 ret = -ENOMEM;
2306 goto out;
2307 }
7b128766
JB
2308 path->reada = -1;
2309
2310 key.objectid = BTRFS_ORPHAN_OBJECTID;
2311 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2312 key.offset = (u64)-1;
2313
7b128766
JB
2314 while (1) {
2315 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
2316 if (ret < 0)
2317 goto out;
7b128766
JB
2318
2319 /*
2320 * if ret == 0 means we found what we were searching for, which
2321 * is weird, but possible, so only screw with path if we didnt
2322 * find the key and see if we have stuff that matches
2323 */
2324 if (ret > 0) {
66b4ffd1 2325 ret = 0;
7b128766
JB
2326 if (path->slots[0] == 0)
2327 break;
2328 path->slots[0]--;
2329 }
2330
2331 /* pull out the item */
2332 leaf = path->nodes[0];
7b128766
JB
2333 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2334
2335 /* make sure the item matches what we want */
2336 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2337 break;
2338 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2339 break;
2340
2341 /* release the path since we're done with it */
2342 btrfs_release_path(root, path);
2343
2344 /*
2345 * this is where we are basically btrfs_lookup, without the
2346 * crossing root thing. we store the inode number in the
2347 * offset of the orphan item.
2348 */
5d4f98a2
YZ
2349 found_key.objectid = found_key.offset;
2350 found_key.type = BTRFS_INODE_ITEM_KEY;
2351 found_key.offset = 0;
73f73415 2352 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
66b4ffd1
JB
2353 if (IS_ERR(inode)) {
2354 ret = PTR_ERR(inode);
2355 goto out;
2356 }
7b128766 2357
7b128766
JB
2358 /*
2359 * add this inode to the orphan list so btrfs_orphan_del does
2360 * the proper thing when we hit it
2361 */
d68fc57b 2362 spin_lock(&root->orphan_lock);
7b128766 2363 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
d68fc57b 2364 spin_unlock(&root->orphan_lock);
7b128766
JB
2365
2366 /*
2367 * if this is a bad inode, means we actually succeeded in
2368 * removing the inode, but not the orphan record, which means
2369 * we need to manually delete the orphan since iput will just
2370 * do a destroy_inode
2371 */
2372 if (is_bad_inode(inode)) {
a22285a6 2373 trans = btrfs_start_transaction(root, 0);
66b4ffd1
JB
2374 if (IS_ERR(trans)) {
2375 ret = PTR_ERR(trans);
2376 goto out;
2377 }
7b128766 2378 btrfs_orphan_del(trans, inode);
5b21f2ed 2379 btrfs_end_transaction(trans, root);
7b128766
JB
2380 iput(inode);
2381 continue;
2382 }
2383
2384 /* if we have links, this was a truncate, lets do that */
2385 if (inode->i_nlink) {
a41ad394
JB
2386 if (!S_ISREG(inode->i_mode)) {
2387 WARN_ON(1);
2388 iput(inode);
2389 continue;
2390 }
7b128766 2391 nr_truncate++;
66b4ffd1 2392 ret = btrfs_truncate(inode);
7b128766
JB
2393 } else {
2394 nr_unlink++;
2395 }
2396
2397 /* this will do delete_inode and everything for us */
2398 iput(inode);
66b4ffd1
JB
2399 if (ret)
2400 goto out;
7b128766 2401 }
d68fc57b
YZ
2402 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2403
2404 if (root->orphan_block_rsv)
2405 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2406 (u64)-1);
2407
2408 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2409 trans = btrfs_join_transaction(root, 1);
66b4ffd1
JB
2410 if (!IS_ERR(trans))
2411 btrfs_end_transaction(trans, root);
d68fc57b 2412 }
7b128766
JB
2413
2414 if (nr_unlink)
2415 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2416 if (nr_truncate)
2417 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
66b4ffd1
JB
2418
2419out:
2420 if (ret)
2421 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2422 btrfs_free_path(path);
2423 return ret;
7b128766
JB
2424}
2425
46a53cca
CM
2426/*
2427 * very simple check to peek ahead in the leaf looking for xattrs. If we
2428 * don't find any xattrs, we know there can't be any acls.
2429 *
2430 * slot is the slot the inode is in, objectid is the objectid of the inode
2431 */
2432static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2433 int slot, u64 objectid)
2434{
2435 u32 nritems = btrfs_header_nritems(leaf);
2436 struct btrfs_key found_key;
2437 int scanned = 0;
2438
2439 slot++;
2440 while (slot < nritems) {
2441 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2442
2443 /* we found a different objectid, there must not be acls */
2444 if (found_key.objectid != objectid)
2445 return 0;
2446
2447 /* we found an xattr, assume we've got an acl */
2448 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2449 return 1;
2450
2451 /*
2452 * we found a key greater than an xattr key, there can't
2453 * be any acls later on
2454 */
2455 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2456 return 0;
2457
2458 slot++;
2459 scanned++;
2460
2461 /*
2462 * it goes inode, inode backrefs, xattrs, extents,
2463 * so if there are a ton of hard links to an inode there can
2464 * be a lot of backrefs. Don't waste time searching too hard,
2465 * this is just an optimization
2466 */
2467 if (scanned >= 8)
2468 break;
2469 }
2470 /* we hit the end of the leaf before we found an xattr or
2471 * something larger than an xattr. We have to assume the inode
2472 * has acls
2473 */
2474 return 1;
2475}
2476
d352ac68
CM
2477/*
2478 * read an inode from the btree into the in-memory inode
2479 */
5d4f98a2 2480static void btrfs_read_locked_inode(struct inode *inode)
39279cc3
CM
2481{
2482 struct btrfs_path *path;
5f39d397 2483 struct extent_buffer *leaf;
39279cc3 2484 struct btrfs_inode_item *inode_item;
0b86a832 2485 struct btrfs_timespec *tspec;
39279cc3
CM
2486 struct btrfs_root *root = BTRFS_I(inode)->root;
2487 struct btrfs_key location;
46a53cca 2488 int maybe_acls;
39279cc3 2489 u64 alloc_group_block;
618e21d5 2490 u32 rdev;
39279cc3
CM
2491 int ret;
2492
2493 path = btrfs_alloc_path();
2494 BUG_ON(!path);
39279cc3 2495 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 2496
39279cc3 2497 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
5f39d397 2498 if (ret)
39279cc3 2499 goto make_bad;
39279cc3 2500
5f39d397
CM
2501 leaf = path->nodes[0];
2502 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2503 struct btrfs_inode_item);
2504
2505 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2506 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2507 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2508 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
dbe674a9 2509 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
5f39d397
CM
2510
2511 tspec = btrfs_inode_atime(inode_item);
2512 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2513 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2514
2515 tspec = btrfs_inode_mtime(inode_item);
2516 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2517 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2518
2519 tspec = btrfs_inode_ctime(inode_item);
2520 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2521 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2522
a76a3cd4 2523 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 2524 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
c3027eb5 2525 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
e02119d5 2526 inode->i_generation = BTRFS_I(inode)->generation;
618e21d5 2527 inode->i_rdev = 0;
5f39d397
CM
2528 rdev = btrfs_inode_rdev(leaf, inode_item);
2529
aec7477b 2530 BTRFS_I(inode)->index_cnt = (u64)-1;
d2fb3437 2531 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
aec7477b 2532
5f39d397 2533 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
b4ce94de 2534
46a53cca
CM
2535 /*
2536 * try to precache a NULL acl entry for files that don't have
2537 * any xattrs or acls
2538 */
2539 maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
72c04902
AV
2540 if (!maybe_acls)
2541 cache_no_acl(inode);
46a53cca 2542
d2fb3437
YZ
2543 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2544 alloc_group_block, 0);
39279cc3
CM
2545 btrfs_free_path(path);
2546 inode_item = NULL;
2547
39279cc3 2548 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
2549 case S_IFREG:
2550 inode->i_mapping->a_ops = &btrfs_aops;
04160088 2551 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d1310b2e 2552 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
2553 inode->i_fop = &btrfs_file_operations;
2554 inode->i_op = &btrfs_file_inode_operations;
2555 break;
2556 case S_IFDIR:
2557 inode->i_fop = &btrfs_dir_file_operations;
2558 if (root == root->fs_info->tree_root)
2559 inode->i_op = &btrfs_dir_ro_inode_operations;
2560 else
2561 inode->i_op = &btrfs_dir_inode_operations;
2562 break;
2563 case S_IFLNK:
2564 inode->i_op = &btrfs_symlink_inode_operations;
2565 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 2566 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3 2567 break;
618e21d5 2568 default:
0279b4cd 2569 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
2570 init_special_inode(inode, inode->i_mode, rdev);
2571 break;
39279cc3 2572 }
6cbff00f
CH
2573
2574 btrfs_update_iflags(inode);
39279cc3
CM
2575 return;
2576
2577make_bad:
39279cc3 2578 btrfs_free_path(path);
39279cc3
CM
2579 make_bad_inode(inode);
2580}
2581
d352ac68
CM
2582/*
2583 * given a leaf and an inode, copy the inode fields into the leaf
2584 */
e02119d5
CM
2585static void fill_inode_item(struct btrfs_trans_handle *trans,
2586 struct extent_buffer *leaf,
5f39d397 2587 struct btrfs_inode_item *item,
39279cc3
CM
2588 struct inode *inode)
2589{
5f39d397
CM
2590 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2591 btrfs_set_inode_gid(leaf, item, inode->i_gid);
dbe674a9 2592 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
5f39d397
CM
2593 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2594 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2595
2596 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2597 inode->i_atime.tv_sec);
2598 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2599 inode->i_atime.tv_nsec);
2600
2601 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2602 inode->i_mtime.tv_sec);
2603 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2604 inode->i_mtime.tv_nsec);
2605
2606 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2607 inode->i_ctime.tv_sec);
2608 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2609 inode->i_ctime.tv_nsec);
2610
a76a3cd4 2611 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
e02119d5 2612 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
c3027eb5 2613 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
e02119d5 2614 btrfs_set_inode_transid(leaf, item, trans->transid);
5f39d397 2615 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
b98b6767 2616 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
d2fb3437 2617 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
39279cc3
CM
2618}
2619
d352ac68
CM
2620/*
2621 * copy everything in the in-memory inode into the btree.
2622 */
d397712b
CM
2623noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2624 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
2625{
2626 struct btrfs_inode_item *inode_item;
2627 struct btrfs_path *path;
5f39d397 2628 struct extent_buffer *leaf;
39279cc3
CM
2629 int ret;
2630
2631 path = btrfs_alloc_path();
2632 BUG_ON(!path);
b9473439 2633 path->leave_spinning = 1;
39279cc3
CM
2634 ret = btrfs_lookup_inode(trans, root, path,
2635 &BTRFS_I(inode)->location, 1);
2636 if (ret) {
2637 if (ret > 0)
2638 ret = -ENOENT;
2639 goto failed;
2640 }
2641
b4ce94de 2642 btrfs_unlock_up_safe(path, 1);
5f39d397
CM
2643 leaf = path->nodes[0];
2644 inode_item = btrfs_item_ptr(leaf, path->slots[0],
39279cc3
CM
2645 struct btrfs_inode_item);
2646
e02119d5 2647 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 2648 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 2649 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
2650 ret = 0;
2651failed:
39279cc3
CM
2652 btrfs_free_path(path);
2653 return ret;
2654}
2655
2656
d352ac68
CM
2657/*
2658 * unlink helper that gets used here in inode.c and in the tree logging
2659 * recovery code. It remove a link in a directory with a given name, and
2660 * also drops the back refs in the inode to the directory
2661 */
e02119d5
CM
2662int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2663 struct btrfs_root *root,
2664 struct inode *dir, struct inode *inode,
2665 const char *name, int name_len)
39279cc3
CM
2666{
2667 struct btrfs_path *path;
39279cc3 2668 int ret = 0;
5f39d397 2669 struct extent_buffer *leaf;
39279cc3 2670 struct btrfs_dir_item *di;
5f39d397 2671 struct btrfs_key key;
aec7477b 2672 u64 index;
39279cc3
CM
2673
2674 path = btrfs_alloc_path();
54aa1f4d
CM
2675 if (!path) {
2676 ret = -ENOMEM;
554233a6 2677 goto out;
54aa1f4d
CM
2678 }
2679
b9473439 2680 path->leave_spinning = 1;
39279cc3
CM
2681 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2682 name, name_len, -1);
2683 if (IS_ERR(di)) {
2684 ret = PTR_ERR(di);
2685 goto err;
2686 }
2687 if (!di) {
2688 ret = -ENOENT;
2689 goto err;
2690 }
5f39d397
CM
2691 leaf = path->nodes[0];
2692 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 2693 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
2694 if (ret)
2695 goto err;
39279cc3
CM
2696 btrfs_release_path(root, path);
2697
aec7477b 2698 ret = btrfs_del_inode_ref(trans, root, name, name_len,
e02119d5
CM
2699 inode->i_ino,
2700 dir->i_ino, &index);
aec7477b 2701 if (ret) {
d397712b 2702 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
aec7477b 2703 "inode %lu parent %lu\n", name_len, name,
e02119d5 2704 inode->i_ino, dir->i_ino);
aec7477b
JB
2705 goto err;
2706 }
2707
39279cc3 2708 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
aec7477b 2709 index, name, name_len, -1);
39279cc3
CM
2710 if (IS_ERR(di)) {
2711 ret = PTR_ERR(di);
2712 goto err;
2713 }
2714 if (!di) {
2715 ret = -ENOENT;
2716 goto err;
2717 }
2718 ret = btrfs_delete_one_dir_name(trans, root, path, di);
925baedd 2719 btrfs_release_path(root, path);
39279cc3 2720
e02119d5
CM
2721 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2722 inode, dir->i_ino);
49eb7e46 2723 BUG_ON(ret != 0 && ret != -ENOENT);
e02119d5
CM
2724
2725 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2726 dir, index);
6418c961
CM
2727 if (ret == -ENOENT)
2728 ret = 0;
39279cc3
CM
2729err:
2730 btrfs_free_path(path);
e02119d5
CM
2731 if (ret)
2732 goto out;
2733
2734 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2735 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2736 btrfs_update_inode(trans, root, dir);
2737 btrfs_drop_nlink(inode);
2738 ret = btrfs_update_inode(trans, root, inode);
e02119d5 2739out:
39279cc3
CM
2740 return ret;
2741}
2742
a22285a6
YZ
2743/* helper to check if there is any shared block in the path */
2744static int check_path_shared(struct btrfs_root *root,
2745 struct btrfs_path *path)
39279cc3 2746{
a22285a6
YZ
2747 struct extent_buffer *eb;
2748 int level;
0e4dcbef 2749 u64 refs = 1;
5df6a9f6 2750
a22285a6 2751 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
dedefd72
JB
2752 int ret;
2753
a22285a6
YZ
2754 if (!path->nodes[level])
2755 break;
2756 eb = path->nodes[level];
2757 if (!btrfs_block_can_be_shared(root, eb))
2758 continue;
2759 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2760 &refs, NULL);
2761 if (refs > 1)
2762 return 1;
5df6a9f6 2763 }
dedefd72 2764 return 0;
39279cc3
CM
2765}
2766
a22285a6
YZ
2767/*
2768 * helper to start transaction for unlink and rmdir.
2769 *
2770 * unlink and rmdir are special in btrfs, they do not always free space.
2771 * so in enospc case, we should make sure they will free space before
2772 * allowing them to use the global metadata reservation.
2773 */
2774static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2775 struct dentry *dentry)
4df27c4d 2776{
39279cc3 2777 struct btrfs_trans_handle *trans;
a22285a6 2778 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d 2779 struct btrfs_path *path;
a22285a6 2780 struct btrfs_inode_ref *ref;
4df27c4d 2781 struct btrfs_dir_item *di;
7b128766 2782 struct inode *inode = dentry->d_inode;
4df27c4d 2783 u64 index;
a22285a6
YZ
2784 int check_link = 1;
2785 int err = -ENOSPC;
4df27c4d
YZ
2786 int ret;
2787
a22285a6
YZ
2788 trans = btrfs_start_transaction(root, 10);
2789 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2790 return trans;
4df27c4d 2791
a22285a6
YZ
2792 if (inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2793 return ERR_PTR(-ENOSPC);
4df27c4d 2794
a22285a6
YZ
2795 /* check if there is someone else holds reference */
2796 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2797 return ERR_PTR(-ENOSPC);
4df27c4d 2798
a22285a6
YZ
2799 if (atomic_read(&inode->i_count) > 2)
2800 return ERR_PTR(-ENOSPC);
4df27c4d 2801
a22285a6
YZ
2802 if (xchg(&root->fs_info->enospc_unlink, 1))
2803 return ERR_PTR(-ENOSPC);
2804
2805 path = btrfs_alloc_path();
2806 if (!path) {
2807 root->fs_info->enospc_unlink = 0;
2808 return ERR_PTR(-ENOMEM);
4df27c4d
YZ
2809 }
2810
a22285a6 2811 trans = btrfs_start_transaction(root, 0);
5df6a9f6 2812 if (IS_ERR(trans)) {
a22285a6
YZ
2813 btrfs_free_path(path);
2814 root->fs_info->enospc_unlink = 0;
2815 return trans;
2816 }
4df27c4d 2817
a22285a6
YZ
2818 path->skip_locking = 1;
2819 path->search_commit_root = 1;
4df27c4d 2820
a22285a6
YZ
2821 ret = btrfs_lookup_inode(trans, root, path,
2822 &BTRFS_I(dir)->location, 0);
2823 if (ret < 0) {
2824 err = ret;
2825 goto out;
2826 }
2827 if (ret == 0) {
2828 if (check_path_shared(root, path))
2829 goto out;
2830 } else {
2831 check_link = 0;
5df6a9f6 2832 }
a22285a6
YZ
2833 btrfs_release_path(root, path);
2834
2835 ret = btrfs_lookup_inode(trans, root, path,
2836 &BTRFS_I(inode)->location, 0);
2837 if (ret < 0) {
2838 err = ret;
2839 goto out;
2840 }
2841 if (ret == 0) {
2842 if (check_path_shared(root, path))
2843 goto out;
2844 } else {
2845 check_link = 0;
2846 }
2847 btrfs_release_path(root, path);
2848
2849 if (ret == 0 && S_ISREG(inode->i_mode)) {
2850 ret = btrfs_lookup_file_extent(trans, root, path,
2851 inode->i_ino, (u64)-1, 0);
2852 if (ret < 0) {
2853 err = ret;
2854 goto out;
2855 }
2856 BUG_ON(ret == 0);
2857 if (check_path_shared(root, path))
2858 goto out;
2859 btrfs_release_path(root, path);
2860 }
2861
2862 if (!check_link) {
2863 err = 0;
2864 goto out;
2865 }
2866
2867 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2868 dentry->d_name.name, dentry->d_name.len, 0);
2869 if (IS_ERR(di)) {
2870 err = PTR_ERR(di);
2871 goto out;
2872 }
2873 if (di) {
2874 if (check_path_shared(root, path))
2875 goto out;
2876 } else {
2877 err = 0;
2878 goto out;
2879 }
2880 btrfs_release_path(root, path);
2881
2882 ref = btrfs_lookup_inode_ref(trans, root, path,
2883 dentry->d_name.name, dentry->d_name.len,
2884 inode->i_ino, dir->i_ino, 0);
2885 if (IS_ERR(ref)) {
2886 err = PTR_ERR(ref);
2887 goto out;
2888 }
2889 BUG_ON(!ref);
2890 if (check_path_shared(root, path))
2891 goto out;
2892 index = btrfs_inode_ref_index(path->nodes[0], ref);
2893 btrfs_release_path(root, path);
2894
2895 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino, index,
2896 dentry->d_name.name, dentry->d_name.len, 0);
2897 if (IS_ERR(di)) {
2898 err = PTR_ERR(di);
2899 goto out;
2900 }
2901 BUG_ON(ret == -ENOENT);
2902 if (check_path_shared(root, path))
2903 goto out;
2904
2905 err = 0;
2906out:
2907 btrfs_free_path(path);
2908 if (err) {
2909 btrfs_end_transaction(trans, root);
2910 root->fs_info->enospc_unlink = 0;
2911 return ERR_PTR(err);
2912 }
2913
2914 trans->block_rsv = &root->fs_info->global_block_rsv;
2915 return trans;
2916}
2917
2918static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2919 struct btrfs_root *root)
2920{
2921 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2922 BUG_ON(!root->fs_info->enospc_unlink);
2923 root->fs_info->enospc_unlink = 0;
2924 }
2925 btrfs_end_transaction_throttle(trans, root);
2926}
2927
2928static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2929{
2930 struct btrfs_root *root = BTRFS_I(dir)->root;
2931 struct btrfs_trans_handle *trans;
2932 struct inode *inode = dentry->d_inode;
2933 int ret;
2934 unsigned long nr = 0;
2935
2936 trans = __unlink_start_trans(dir, dentry);
2937 if (IS_ERR(trans))
2938 return PTR_ERR(trans);
5f39d397 2939
39279cc3 2940 btrfs_set_trans_block_group(trans, dir);
12fcfd22
CM
2941
2942 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2943
e02119d5
CM
2944 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2945 dentry->d_name.name, dentry->d_name.len);
a22285a6 2946 BUG_ON(ret);
7b128766 2947
a22285a6 2948 if (inode->i_nlink == 0) {
7b128766 2949 ret = btrfs_orphan_add(trans, inode);
a22285a6
YZ
2950 BUG_ON(ret);
2951 }
7b128766 2952
d3c2fdcf 2953 nr = trans->blocks_used;
a22285a6 2954 __unlink_end_trans(trans, root);
d3c2fdcf 2955 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
2956 return ret;
2957}
2958
4df27c4d
YZ
2959int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2960 struct btrfs_root *root,
2961 struct inode *dir, u64 objectid,
2962 const char *name, int name_len)
2963{
2964 struct btrfs_path *path;
2965 struct extent_buffer *leaf;
2966 struct btrfs_dir_item *di;
2967 struct btrfs_key key;
2968 u64 index;
2969 int ret;
2970
2971 path = btrfs_alloc_path();
2972 if (!path)
2973 return -ENOMEM;
2974
2975 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2976 name, name_len, -1);
2977 BUG_ON(!di || IS_ERR(di));
2978
2979 leaf = path->nodes[0];
2980 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2981 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2982 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2983 BUG_ON(ret);
2984 btrfs_release_path(root, path);
2985
2986 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2987 objectid, root->root_key.objectid,
2988 dir->i_ino, &index, name, name_len);
2989 if (ret < 0) {
2990 BUG_ON(ret != -ENOENT);
2991 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2992 name, name_len);
2993 BUG_ON(!di || IS_ERR(di));
2994
2995 leaf = path->nodes[0];
2996 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2997 btrfs_release_path(root, path);
2998 index = key.offset;
2999 }
3000
3001 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
3002 index, name, name_len, -1);
3003 BUG_ON(!di || IS_ERR(di));
3004
3005 leaf = path->nodes[0];
3006 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3007 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3008 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3009 BUG_ON(ret);
3010 btrfs_release_path(root, path);
3011
3012 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3013 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3014 ret = btrfs_update_inode(trans, root, dir);
3015 BUG_ON(ret);
4df27c4d
YZ
3016
3017 btrfs_free_path(path);
3018 return 0;
3019}
3020
39279cc3
CM
3021static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3022{
3023 struct inode *inode = dentry->d_inode;
1832a6d5 3024 int err = 0;
39279cc3 3025 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 3026 struct btrfs_trans_handle *trans;
1832a6d5 3027 unsigned long nr = 0;
39279cc3 3028
3394e160 3029 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
4df27c4d 3030 inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
134d4512
Y
3031 return -ENOTEMPTY;
3032
a22285a6
YZ
3033 trans = __unlink_start_trans(dir, dentry);
3034 if (IS_ERR(trans))
5df6a9f6 3035 return PTR_ERR(trans);
5df6a9f6 3036
39279cc3 3037 btrfs_set_trans_block_group(trans, dir);
39279cc3 3038
4df27c4d
YZ
3039 if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3040 err = btrfs_unlink_subvol(trans, root, dir,
3041 BTRFS_I(inode)->location.objectid,
3042 dentry->d_name.name,
3043 dentry->d_name.len);
3044 goto out;
3045 }
3046
7b128766
JB
3047 err = btrfs_orphan_add(trans, inode);
3048 if (err)
4df27c4d 3049 goto out;
7b128766 3050
39279cc3 3051 /* now the directory is empty */
e02119d5
CM
3052 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3053 dentry->d_name.name, dentry->d_name.len);
d397712b 3054 if (!err)
dbe674a9 3055 btrfs_i_size_write(inode, 0);
4df27c4d 3056out:
d3c2fdcf 3057 nr = trans->blocks_used;
a22285a6 3058 __unlink_end_trans(trans, root);
d3c2fdcf 3059 btrfs_btree_balance_dirty(root, nr);
3954401f 3060
39279cc3
CM
3061 return err;
3062}
3063
d20f7043 3064#if 0
323ac95b
CM
3065/*
3066 * when truncating bytes in a file, it is possible to avoid reading
3067 * the leaves that contain only checksum items. This can be the
3068 * majority of the IO required to delete a large file, but it must
3069 * be done carefully.
3070 *
3071 * The keys in the level just above the leaves are checked to make sure
3072 * the lowest key in a given leaf is a csum key, and starts at an offset
3073 * after the new size.
3074 *
3075 * Then the key for the next leaf is checked to make sure it also has
3076 * a checksum item for the same file. If it does, we know our target leaf
3077 * contains only checksum items, and it can be safely freed without reading
3078 * it.
3079 *
3080 * This is just an optimization targeted at large files. It may do
3081 * nothing. It will return 0 unless things went badly.
3082 */
3083static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
3084 struct btrfs_root *root,
3085 struct btrfs_path *path,
3086 struct inode *inode, u64 new_size)
3087{
3088 struct btrfs_key key;
3089 int ret;
3090 int nritems;
3091 struct btrfs_key found_key;
3092 struct btrfs_key other_key;
5b84e8d6
YZ
3093 struct btrfs_leaf_ref *ref;
3094 u64 leaf_gen;
3095 u64 leaf_start;
323ac95b
CM
3096
3097 path->lowest_level = 1;
3098 key.objectid = inode->i_ino;
3099 key.type = BTRFS_CSUM_ITEM_KEY;
3100 key.offset = new_size;
3101again:
3102 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3103 if (ret < 0)
3104 goto out;
3105
3106 if (path->nodes[1] == NULL) {
3107 ret = 0;
3108 goto out;
3109 }
3110 ret = 0;
3111 btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
3112 nritems = btrfs_header_nritems(path->nodes[1]);
3113
3114 if (!nritems)
3115 goto out;
3116
3117 if (path->slots[1] >= nritems)
3118 goto next_node;
3119
3120 /* did we find a key greater than anything we want to delete? */
3121 if (found_key.objectid > inode->i_ino ||
3122 (found_key.objectid == inode->i_ino && found_key.type > key.type))
3123 goto out;
3124
3125 /* we check the next key in the node to make sure the leave contains
3126 * only checksum items. This comparison doesn't work if our
3127 * leaf is the last one in the node
3128 */
3129 if (path->slots[1] + 1 >= nritems) {
3130next_node:
3131 /* search forward from the last key in the node, this
3132 * will bring us into the next node in the tree
3133 */
3134 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
3135
3136 /* unlikely, but we inc below, so check to be safe */
3137 if (found_key.offset == (u64)-1)
3138 goto out;
3139
3140 /* search_forward needs a path with locks held, do the
3141 * search again for the original key. It is possible
3142 * this will race with a balance and return a path that
3143 * we could modify, but this drop is just an optimization
3144 * and is allowed to miss some leaves.
3145 */
3146 btrfs_release_path(root, path);
3147 found_key.offset++;
3148
3149 /* setup a max key for search_forward */
3150 other_key.offset = (u64)-1;
3151 other_key.type = key.type;
3152 other_key.objectid = key.objectid;
3153
3154 path->keep_locks = 1;
3155 ret = btrfs_search_forward(root, &found_key, &other_key,
3156 path, 0, 0);
3157 path->keep_locks = 0;
3158 if (ret || found_key.objectid != key.objectid ||
3159 found_key.type != key.type) {
3160 ret = 0;
3161 goto out;
3162 }
3163
3164 key.offset = found_key.offset;
3165 btrfs_release_path(root, path);
3166 cond_resched();
3167 goto again;
3168 }
3169
3170 /* we know there's one more slot after us in the tree,
3171 * read that key so we can verify it is also a checksum item
3172 */
3173 btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
3174
3175 if (found_key.objectid < inode->i_ino)
3176 goto next_key;
3177
3178 if (found_key.type != key.type || found_key.offset < new_size)
3179 goto next_key;
3180
3181 /*
3182 * if the key for the next leaf isn't a csum key from this objectid,
3183 * we can't be sure there aren't good items inside this leaf.
3184 * Bail out
3185 */
3186 if (other_key.objectid != inode->i_ino || other_key.type != key.type)
3187 goto out;
3188
5b84e8d6
YZ
3189 leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
3190 leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
323ac95b
CM
3191 /*
3192 * it is safe to delete this leaf, it contains only
3193 * csum items from this inode at an offset >= new_size
3194 */
5b84e8d6 3195 ret = btrfs_del_leaf(trans, root, path, leaf_start);
323ac95b
CM
3196 BUG_ON(ret);
3197
5b84e8d6
YZ
3198 if (root->ref_cows && leaf_gen < trans->transid) {
3199 ref = btrfs_alloc_leaf_ref(root, 0);
3200 if (ref) {
3201 ref->root_gen = root->root_key.offset;
3202 ref->bytenr = leaf_start;
3203 ref->owner = 0;
3204 ref->generation = leaf_gen;
3205 ref->nritems = 0;
3206
bd56b302
CM
3207 btrfs_sort_leaf_ref(ref);
3208
5b84e8d6
YZ
3209 ret = btrfs_add_leaf_ref(root, ref, 0);
3210 WARN_ON(ret);
3211 btrfs_free_leaf_ref(root, ref);
3212 } else {
3213 WARN_ON(1);
3214 }
3215 }
323ac95b
CM
3216next_key:
3217 btrfs_release_path(root, path);
3218
3219 if (other_key.objectid == inode->i_ino &&
3220 other_key.type == key.type && other_key.offset > key.offset) {
3221 key.offset = other_key.offset;
3222 cond_resched();
3223 goto again;
3224 }
3225 ret = 0;
3226out:
3227 /* fixup any changes we've made to the path */
3228 path->lowest_level = 0;
3229 path->keep_locks = 0;
3230 btrfs_release_path(root, path);
3231 return ret;
3232}
3233
d20f7043
CM
3234#endif
3235
39279cc3
CM
3236/*
3237 * this can truncate away extent items, csum items and directory items.
3238 * It starts at a high offset and removes keys until it can't find
d352ac68 3239 * any higher than new_size
39279cc3
CM
3240 *
3241 * csum items that cross the new i_size are truncated to the new size
3242 * as well.
7b128766
JB
3243 *
3244 * min_type is the minimum key type to truncate down to. If set to 0, this
3245 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 3246 */
8082510e
YZ
3247int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3248 struct btrfs_root *root,
3249 struct inode *inode,
3250 u64 new_size, u32 min_type)
39279cc3 3251{
39279cc3 3252 struct btrfs_path *path;
5f39d397 3253 struct extent_buffer *leaf;
39279cc3 3254 struct btrfs_file_extent_item *fi;
8082510e
YZ
3255 struct btrfs_key key;
3256 struct btrfs_key found_key;
39279cc3 3257 u64 extent_start = 0;
db94535d 3258 u64 extent_num_bytes = 0;
5d4f98a2 3259 u64 extent_offset = 0;
39279cc3 3260 u64 item_end = 0;
8082510e
YZ
3261 u64 mask = root->sectorsize - 1;
3262 u32 found_type = (u8)-1;
39279cc3
CM
3263 int found_extent;
3264 int del_item;
85e21bac
CM
3265 int pending_del_nr = 0;
3266 int pending_del_slot = 0;
179e29e4 3267 int extent_type = -1;
771ed689 3268 int encoding;
8082510e
YZ
3269 int ret;
3270 int err = 0;
3271
3272 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 3273
0af3d00b 3274 if (root->ref_cows || root == root->fs_info->tree_root)
5b21f2ed 3275 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
8082510e 3276
39279cc3
CM
3277 path = btrfs_alloc_path();
3278 BUG_ON(!path);
33c17ad5 3279 path->reada = -1;
5f39d397 3280
39279cc3
CM
3281 key.objectid = inode->i_ino;
3282 key.offset = (u64)-1;
5f39d397
CM
3283 key.type = (u8)-1;
3284
85e21bac 3285search_again:
b9473439 3286 path->leave_spinning = 1;
85e21bac 3287 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8082510e
YZ
3288 if (ret < 0) {
3289 err = ret;
3290 goto out;
3291 }
d397712b 3292
85e21bac 3293 if (ret > 0) {
e02119d5
CM
3294 /* there are no items in the tree for us to truncate, we're
3295 * done
3296 */
8082510e
YZ
3297 if (path->slots[0] == 0)
3298 goto out;
85e21bac
CM
3299 path->slots[0]--;
3300 }
3301
d397712b 3302 while (1) {
39279cc3 3303 fi = NULL;
5f39d397
CM
3304 leaf = path->nodes[0];
3305 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3306 found_type = btrfs_key_type(&found_key);
771ed689 3307 encoding = 0;
39279cc3 3308
5f39d397 3309 if (found_key.objectid != inode->i_ino)
39279cc3 3310 break;
5f39d397 3311
85e21bac 3312 if (found_type < min_type)
39279cc3
CM
3313 break;
3314
5f39d397 3315 item_end = found_key.offset;
39279cc3 3316 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 3317 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 3318 struct btrfs_file_extent_item);
179e29e4 3319 extent_type = btrfs_file_extent_type(leaf, fi);
771ed689
CM
3320 encoding = btrfs_file_extent_compression(leaf, fi);
3321 encoding |= btrfs_file_extent_encryption(leaf, fi);
3322 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
3323
179e29e4 3324 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 3325 item_end +=
db94535d 3326 btrfs_file_extent_num_bytes(leaf, fi);
179e29e4 3327 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
179e29e4 3328 item_end += btrfs_file_extent_inline_len(leaf,
c8b97818 3329 fi);
39279cc3 3330 }
008630c1 3331 item_end--;
39279cc3 3332 }
8082510e
YZ
3333 if (found_type > min_type) {
3334 del_item = 1;
3335 } else {
3336 if (item_end < new_size)
b888db2b 3337 break;
8082510e
YZ
3338 if (found_key.offset >= new_size)
3339 del_item = 1;
3340 else
3341 del_item = 0;
39279cc3 3342 }
39279cc3 3343 found_extent = 0;
39279cc3 3344 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
3345 if (found_type != BTRFS_EXTENT_DATA_KEY)
3346 goto delete;
3347
3348 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 3349 u64 num_dec;
db94535d 3350 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
771ed689 3351 if (!del_item && !encoding) {
db94535d
CM
3352 u64 orig_num_bytes =
3353 btrfs_file_extent_num_bytes(leaf, fi);
e02119d5 3354 extent_num_bytes = new_size -
5f39d397 3355 found_key.offset + root->sectorsize - 1;
b1632b10
Y
3356 extent_num_bytes = extent_num_bytes &
3357 ~((u64)root->sectorsize - 1);
db94535d
CM
3358 btrfs_set_file_extent_num_bytes(leaf, fi,
3359 extent_num_bytes);
3360 num_dec = (orig_num_bytes -
9069218d 3361 extent_num_bytes);
e02119d5 3362 if (root->ref_cows && extent_start != 0)
a76a3cd4 3363 inode_sub_bytes(inode, num_dec);
5f39d397 3364 btrfs_mark_buffer_dirty(leaf);
39279cc3 3365 } else {
db94535d
CM
3366 extent_num_bytes =
3367 btrfs_file_extent_disk_num_bytes(leaf,
3368 fi);
5d4f98a2
YZ
3369 extent_offset = found_key.offset -
3370 btrfs_file_extent_offset(leaf, fi);
3371
39279cc3 3372 /* FIXME blocksize != 4096 */
9069218d 3373 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
3374 if (extent_start != 0) {
3375 found_extent = 1;
e02119d5 3376 if (root->ref_cows)
a76a3cd4 3377 inode_sub_bytes(inode, num_dec);
e02119d5 3378 }
39279cc3 3379 }
9069218d 3380 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
3381 /*
3382 * we can't truncate inline items that have had
3383 * special encodings
3384 */
3385 if (!del_item &&
3386 btrfs_file_extent_compression(leaf, fi) == 0 &&
3387 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3388 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
e02119d5
CM
3389 u32 size = new_size - found_key.offset;
3390
3391 if (root->ref_cows) {
a76a3cd4
YZ
3392 inode_sub_bytes(inode, item_end + 1 -
3393 new_size);
e02119d5
CM
3394 }
3395 size =
3396 btrfs_file_extent_calc_inline_size(size);
9069218d 3397 ret = btrfs_truncate_item(trans, root, path,
e02119d5 3398 size, 1);
9069218d 3399 BUG_ON(ret);
e02119d5 3400 } else if (root->ref_cows) {
a76a3cd4
YZ
3401 inode_sub_bytes(inode, item_end + 1 -
3402 found_key.offset);
9069218d 3403 }
39279cc3 3404 }
179e29e4 3405delete:
39279cc3 3406 if (del_item) {
85e21bac
CM
3407 if (!pending_del_nr) {
3408 /* no pending yet, add ourselves */
3409 pending_del_slot = path->slots[0];
3410 pending_del_nr = 1;
3411 } else if (pending_del_nr &&
3412 path->slots[0] + 1 == pending_del_slot) {
3413 /* hop on the pending chunk */
3414 pending_del_nr++;
3415 pending_del_slot = path->slots[0];
3416 } else {
d397712b 3417 BUG();
85e21bac 3418 }
39279cc3
CM
3419 } else {
3420 break;
3421 }
0af3d00b
JB
3422 if (found_extent && (root->ref_cows ||
3423 root == root->fs_info->tree_root)) {
b9473439 3424 btrfs_set_path_blocking(path);
39279cc3 3425 ret = btrfs_free_extent(trans, root, extent_start,
5d4f98a2
YZ
3426 extent_num_bytes, 0,
3427 btrfs_header_owner(leaf),
3428 inode->i_ino, extent_offset);
39279cc3
CM
3429 BUG_ON(ret);
3430 }
85e21bac 3431
8082510e
YZ
3432 if (found_type == BTRFS_INODE_ITEM_KEY)
3433 break;
3434
3435 if (path->slots[0] == 0 ||
3436 path->slots[0] != pending_del_slot) {
3437 if (root->ref_cows) {
3438 err = -EAGAIN;
3439 goto out;
3440 }
3441 if (pending_del_nr) {
3442 ret = btrfs_del_items(trans, root, path,
3443 pending_del_slot,
3444 pending_del_nr);
3445 BUG_ON(ret);
3446 pending_del_nr = 0;
3447 }
85e21bac
CM
3448 btrfs_release_path(root, path);
3449 goto search_again;
8082510e
YZ
3450 } else {
3451 path->slots[0]--;
85e21bac 3452 }
39279cc3 3453 }
8082510e 3454out:
85e21bac
CM
3455 if (pending_del_nr) {
3456 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3457 pending_del_nr);
d68fc57b 3458 BUG_ON(ret);
85e21bac 3459 }
39279cc3 3460 btrfs_free_path(path);
8082510e 3461 return err;
39279cc3
CM
3462}
3463
3464/*
3465 * taken from block_truncate_page, but does cow as it zeros out
3466 * any bytes left in the last page in the file.
3467 */
3468static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3469{
3470 struct inode *inode = mapping->host;
db94535d 3471 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
3472 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3473 struct btrfs_ordered_extent *ordered;
2ac55d41 3474 struct extent_state *cached_state = NULL;
e6dcd2dc 3475 char *kaddr;
db94535d 3476 u32 blocksize = root->sectorsize;
39279cc3
CM
3477 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3478 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3479 struct page *page;
39279cc3 3480 int ret = 0;
a52d9a80 3481 u64 page_start;
e6dcd2dc 3482 u64 page_end;
39279cc3
CM
3483
3484 if ((offset & (blocksize - 1)) == 0)
3485 goto out;
0ca1f7ce 3486 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
5d5e103a
JB
3487 if (ret)
3488 goto out;
39279cc3
CM
3489
3490 ret = -ENOMEM;
211c17f5 3491again:
39279cc3 3492 page = grab_cache_page(mapping, index);
5d5e103a 3493 if (!page) {
0ca1f7ce 3494 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
39279cc3 3495 goto out;
5d5e103a 3496 }
e6dcd2dc
CM
3497
3498 page_start = page_offset(page);
3499 page_end = page_start + PAGE_CACHE_SIZE - 1;
3500
39279cc3 3501 if (!PageUptodate(page)) {
9ebefb18 3502 ret = btrfs_readpage(NULL, page);
39279cc3 3503 lock_page(page);
211c17f5
CM
3504 if (page->mapping != mapping) {
3505 unlock_page(page);
3506 page_cache_release(page);
3507 goto again;
3508 }
39279cc3
CM
3509 if (!PageUptodate(page)) {
3510 ret = -EIO;
89642229 3511 goto out_unlock;
39279cc3
CM
3512 }
3513 }
211c17f5 3514 wait_on_page_writeback(page);
e6dcd2dc 3515
2ac55d41
JB
3516 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
3517 GFP_NOFS);
e6dcd2dc
CM
3518 set_page_extent_mapped(page);
3519
3520 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3521 if (ordered) {
2ac55d41
JB
3522 unlock_extent_cached(io_tree, page_start, page_end,
3523 &cached_state, GFP_NOFS);
e6dcd2dc
CM
3524 unlock_page(page);
3525 page_cache_release(page);
eb84ae03 3526 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
3527 btrfs_put_ordered_extent(ordered);
3528 goto again;
3529 }
3530
2ac55d41 3531 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
5d5e103a 3532 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
2ac55d41 3533 0, 0, &cached_state, GFP_NOFS);
5d5e103a 3534
2ac55d41
JB
3535 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3536 &cached_state);
9ed74f2d 3537 if (ret) {
2ac55d41
JB
3538 unlock_extent_cached(io_tree, page_start, page_end,
3539 &cached_state, GFP_NOFS);
9ed74f2d
JB
3540 goto out_unlock;
3541 }
3542
e6dcd2dc
CM
3543 ret = 0;
3544 if (offset != PAGE_CACHE_SIZE) {
3545 kaddr = kmap(page);
3546 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3547 flush_dcache_page(page);
3548 kunmap(page);
3549 }
247e743c 3550 ClearPageChecked(page);
e6dcd2dc 3551 set_page_dirty(page);
2ac55d41
JB
3552 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3553 GFP_NOFS);
39279cc3 3554
89642229 3555out_unlock:
5d5e103a 3556 if (ret)
0ca1f7ce 3557 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
39279cc3
CM
3558 unlock_page(page);
3559 page_cache_release(page);
3560out:
3561 return ret;
3562}
3563
695a0d0d
JB
3564/*
3565 * This function puts in dummy file extents for the area we're creating a hole
3566 * for. So if we are truncating this file to a larger size we need to insert
3567 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3568 * the range between oldsize and size
3569 */
a41ad394 3570int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 3571{
9036c102
YZ
3572 struct btrfs_trans_handle *trans;
3573 struct btrfs_root *root = BTRFS_I(inode)->root;
3574 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 3575 struct extent_map *em = NULL;
2ac55d41 3576 struct extent_state *cached_state = NULL;
9036c102 3577 u64 mask = root->sectorsize - 1;
a41ad394 3578 u64 hole_start = (oldsize + mask) & ~mask;
9036c102
YZ
3579 u64 block_end = (size + mask) & ~mask;
3580 u64 last_byte;
3581 u64 cur_offset;
3582 u64 hole_size;
9ed74f2d 3583 int err = 0;
39279cc3 3584
9036c102
YZ
3585 if (size <= hole_start)
3586 return 0;
3587
9036c102
YZ
3588 while (1) {
3589 struct btrfs_ordered_extent *ordered;
3590 btrfs_wait_ordered_range(inode, hole_start,
3591 block_end - hole_start);
2ac55d41
JB
3592 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3593 &cached_state, GFP_NOFS);
9036c102
YZ
3594 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3595 if (!ordered)
3596 break;
2ac55d41
JB
3597 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3598 &cached_state, GFP_NOFS);
9036c102
YZ
3599 btrfs_put_ordered_extent(ordered);
3600 }
39279cc3 3601
9036c102
YZ
3602 cur_offset = hole_start;
3603 while (1) {
3604 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3605 block_end - cur_offset, 0);
3606 BUG_ON(IS_ERR(em) || !em);
3607 last_byte = min(extent_map_end(em), block_end);
3608 last_byte = (last_byte + mask) & ~mask;
8082510e 3609 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
771ed689 3610 u64 hint_byte = 0;
9036c102 3611 hole_size = last_byte - cur_offset;
9ed74f2d 3612
a22285a6
YZ
3613 trans = btrfs_start_transaction(root, 2);
3614 if (IS_ERR(trans)) {
3615 err = PTR_ERR(trans);
9ed74f2d 3616 break;
a22285a6 3617 }
8082510e
YZ
3618 btrfs_set_trans_block_group(trans, inode);
3619
3620 err = btrfs_drop_extents(trans, inode, cur_offset,
3621 cur_offset + hole_size,
3622 &hint_byte, 1);
3893e33b
JB
3623 if (err)
3624 break;
8082510e 3625
9036c102
YZ
3626 err = btrfs_insert_file_extent(trans, root,
3627 inode->i_ino, cur_offset, 0,
3628 0, hole_size, 0, hole_size,
3629 0, 0, 0);
3893e33b
JB
3630 if (err)
3631 break;
8082510e 3632
9036c102
YZ
3633 btrfs_drop_extent_cache(inode, hole_start,
3634 last_byte - 1, 0);
8082510e
YZ
3635
3636 btrfs_end_transaction(trans, root);
9036c102
YZ
3637 }
3638 free_extent_map(em);
a22285a6 3639 em = NULL;
9036c102 3640 cur_offset = last_byte;
8082510e 3641 if (cur_offset >= block_end)
9036c102
YZ
3642 break;
3643 }
1832a6d5 3644
a22285a6 3645 free_extent_map(em);
2ac55d41
JB
3646 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3647 GFP_NOFS);
9036c102
YZ
3648 return err;
3649}
39279cc3 3650
a41ad394 3651static int btrfs_setsize(struct inode *inode, loff_t newsize)
8082510e 3652{
a41ad394 3653 loff_t oldsize = i_size_read(inode);
8082510e
YZ
3654 int ret;
3655
a41ad394 3656 if (newsize == oldsize)
8082510e
YZ
3657 return 0;
3658
a41ad394
JB
3659 if (newsize > oldsize) {
3660 i_size_write(inode, newsize);
3661 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3662 truncate_pagecache(inode, oldsize, newsize);
3663 ret = btrfs_cont_expand(inode, oldsize, newsize);
8082510e 3664 if (ret) {
a41ad394 3665 btrfs_setsize(inode, oldsize);
8082510e
YZ
3666 return ret;
3667 }
3668
930f028a 3669 mark_inode_dirty(inode);
a41ad394 3670 } else {
8082510e 3671
a41ad394
JB
3672 /*
3673 * We're truncating a file that used to have good data down to
3674 * zero. Make sure it gets into the ordered flush list so that
3675 * any new writes get down to disk quickly.
3676 */
3677 if (newsize == 0)
3678 BTRFS_I(inode)->ordered_data_close = 1;
8082510e 3679
a41ad394
JB
3680 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3681 truncate_setsize(inode, newsize);
3682 ret = btrfs_truncate(inode);
3683 }
8082510e 3684
a41ad394 3685 return ret;
8082510e
YZ
3686}
3687
9036c102
YZ
3688static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3689{
3690 struct inode *inode = dentry->d_inode;
b83cc969 3691 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 3692 int err;
39279cc3 3693
b83cc969
LZ
3694 if (btrfs_root_readonly(root))
3695 return -EROFS;
3696
9036c102
YZ
3697 err = inode_change_ok(inode, attr);
3698 if (err)
3699 return err;
2bf5a725 3700
5a3f23d5 3701 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
a41ad394 3702 err = btrfs_setsize(inode, attr->ia_size);
8082510e
YZ
3703 if (err)
3704 return err;
39279cc3 3705 }
9036c102 3706
1025774c
CH
3707 if (attr->ia_valid) {
3708 setattr_copy(inode, attr);
3709 mark_inode_dirty(inode);
3710
3711 if (attr->ia_valid & ATTR_MODE)
3712 err = btrfs_acl_chmod(inode);
3713 }
33268eaf 3714
39279cc3
CM
3715 return err;
3716}
61295eb8 3717
bd555975 3718void btrfs_evict_inode(struct inode *inode)
39279cc3
CM
3719{
3720 struct btrfs_trans_handle *trans;
3721 struct btrfs_root *root = BTRFS_I(inode)->root;
d3c2fdcf 3722 unsigned long nr;
39279cc3
CM
3723 int ret;
3724
1abe9b8a 3725 trace_btrfs_inode_evict(inode);
3726
39279cc3 3727 truncate_inode_pages(&inode->i_data, 0);
0af3d00b
JB
3728 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3729 root == root->fs_info->tree_root))
bd555975
AV
3730 goto no_delete;
3731
39279cc3 3732 if (is_bad_inode(inode)) {
7b128766 3733 btrfs_orphan_del(NULL, inode);
39279cc3
CM
3734 goto no_delete;
3735 }
bd555975 3736 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4a096752 3737 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5f39d397 3738
c71bf099
YZ
3739 if (root->fs_info->log_root_recovering) {
3740 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3741 goto no_delete;
3742 }
3743
76dda93c
YZ
3744 if (inode->i_nlink > 0) {
3745 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3746 goto no_delete;
3747 }
3748
dbe674a9 3749 btrfs_i_size_write(inode, 0);
5f39d397 3750
8082510e 3751 while (1) {
d68fc57b
YZ
3752 trans = btrfs_start_transaction(root, 0);
3753 BUG_ON(IS_ERR(trans));
8082510e 3754 btrfs_set_trans_block_group(trans, inode);
d68fc57b
YZ
3755 trans->block_rsv = root->orphan_block_rsv;
3756
3757 ret = btrfs_block_rsv_check(trans, root,
3758 root->orphan_block_rsv, 0, 5);
3759 if (ret) {
3760 BUG_ON(ret != -EAGAIN);
3761 ret = btrfs_commit_transaction(trans, root);
3762 BUG_ON(ret);
3763 continue;
3764 }
7b128766 3765
d68fc57b 3766 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
8082510e
YZ
3767 if (ret != -EAGAIN)
3768 break;
85e21bac 3769
8082510e
YZ
3770 nr = trans->blocks_used;
3771 btrfs_end_transaction(trans, root);
3772 trans = NULL;
3773 btrfs_btree_balance_dirty(root, nr);
d68fc57b 3774
8082510e 3775 }
5f39d397 3776
8082510e
YZ
3777 if (ret == 0) {
3778 ret = btrfs_orphan_del(trans, inode);
3779 BUG_ON(ret);
3780 }
54aa1f4d 3781
d3c2fdcf 3782 nr = trans->blocks_used;
54aa1f4d 3783 btrfs_end_transaction(trans, root);
d3c2fdcf 3784 btrfs_btree_balance_dirty(root, nr);
39279cc3 3785no_delete:
bd555975 3786 end_writeback(inode);
8082510e 3787 return;
39279cc3
CM
3788}
3789
3790/*
3791 * this returns the key found in the dir entry in the location pointer.
3792 * If no dir entries were found, location->objectid is 0.
3793 */
3794static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3795 struct btrfs_key *location)
3796{
3797 const char *name = dentry->d_name.name;
3798 int namelen = dentry->d_name.len;
3799 struct btrfs_dir_item *di;
3800 struct btrfs_path *path;
3801 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 3802 int ret = 0;
39279cc3
CM
3803
3804 path = btrfs_alloc_path();
3805 BUG_ON(!path);
3954401f 3806
39279cc3
CM
3807 di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3808 namelen, 0);
0d9f7f3e
Y
3809 if (IS_ERR(di))
3810 ret = PTR_ERR(di);
d397712b
CM
3811
3812 if (!di || IS_ERR(di))
3954401f 3813 goto out_err;
d397712b 3814
5f39d397 3815 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
39279cc3 3816out:
39279cc3
CM
3817 btrfs_free_path(path);
3818 return ret;
3954401f
CM
3819out_err:
3820 location->objectid = 0;
3821 goto out;
39279cc3
CM
3822}
3823
3824/*
3825 * when we hit a tree root in a directory, the btrfs part of the inode
3826 * needs to be changed to reflect the root directory of the tree root. This
3827 * is kind of like crossing a mount point.
3828 */
3829static int fixup_tree_root_location(struct btrfs_root *root,
4df27c4d
YZ
3830 struct inode *dir,
3831 struct dentry *dentry,
3832 struct btrfs_key *location,
3833 struct btrfs_root **sub_root)
39279cc3 3834{
4df27c4d
YZ
3835 struct btrfs_path *path;
3836 struct btrfs_root *new_root;
3837 struct btrfs_root_ref *ref;
3838 struct extent_buffer *leaf;
3839 int ret;
3840 int err = 0;
39279cc3 3841
4df27c4d
YZ
3842 path = btrfs_alloc_path();
3843 if (!path) {
3844 err = -ENOMEM;
3845 goto out;
3846 }
39279cc3 3847
4df27c4d
YZ
3848 err = -ENOENT;
3849 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3850 BTRFS_I(dir)->root->root_key.objectid,
3851 location->objectid);
3852 if (ret) {
3853 if (ret < 0)
3854 err = ret;
3855 goto out;
3856 }
39279cc3 3857
4df27c4d
YZ
3858 leaf = path->nodes[0];
3859 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3860 if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3861 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3862 goto out;
39279cc3 3863
4df27c4d
YZ
3864 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3865 (unsigned long)(ref + 1),
3866 dentry->d_name.len);
3867 if (ret)
3868 goto out;
3869
3870 btrfs_release_path(root->fs_info->tree_root, path);
3871
3872 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3873 if (IS_ERR(new_root)) {
3874 err = PTR_ERR(new_root);
3875 goto out;
3876 }
3877
3878 if (btrfs_root_refs(&new_root->root_item) == 0) {
3879 err = -ENOENT;
3880 goto out;
3881 }
3882
3883 *sub_root = new_root;
3884 location->objectid = btrfs_root_dirid(&new_root->root_item);
3885 location->type = BTRFS_INODE_ITEM_KEY;
3886 location->offset = 0;
3887 err = 0;
3888out:
3889 btrfs_free_path(path);
3890 return err;
39279cc3
CM
3891}
3892
5d4f98a2
YZ
3893static void inode_tree_add(struct inode *inode)
3894{
3895 struct btrfs_root *root = BTRFS_I(inode)->root;
3896 struct btrfs_inode *entry;
03e860bd
FNP
3897 struct rb_node **p;
3898 struct rb_node *parent;
03e860bd
FNP
3899again:
3900 p = &root->inode_tree.rb_node;
3901 parent = NULL;
5d4f98a2 3902
1d3382cb 3903 if (inode_unhashed(inode))
76dda93c
YZ
3904 return;
3905
5d4f98a2
YZ
3906 spin_lock(&root->inode_lock);
3907 while (*p) {
3908 parent = *p;
3909 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3910
3911 if (inode->i_ino < entry->vfs_inode.i_ino)
03e860bd 3912 p = &parent->rb_left;
5d4f98a2 3913 else if (inode->i_ino > entry->vfs_inode.i_ino)
03e860bd 3914 p = &parent->rb_right;
5d4f98a2
YZ
3915 else {
3916 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 3917 (I_WILL_FREE | I_FREEING)));
03e860bd
FNP
3918 rb_erase(parent, &root->inode_tree);
3919 RB_CLEAR_NODE(parent);
3920 spin_unlock(&root->inode_lock);
3921 goto again;
5d4f98a2
YZ
3922 }
3923 }
3924 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3925 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3926 spin_unlock(&root->inode_lock);
3927}
3928
3929static void inode_tree_del(struct inode *inode)
3930{
3931 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 3932 int empty = 0;
5d4f98a2 3933
03e860bd 3934 spin_lock(&root->inode_lock);
5d4f98a2 3935 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 3936 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 3937 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 3938 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 3939 }
03e860bd 3940 spin_unlock(&root->inode_lock);
76dda93c 3941
0af3d00b
JB
3942 /*
3943 * Free space cache has inodes in the tree root, but the tree root has a
3944 * root_refs of 0, so this could end up dropping the tree root as a
3945 * snapshot, so we need the extra !root->fs_info->tree_root check to
3946 * make sure we don't drop it.
3947 */
3948 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3949 root != root->fs_info->tree_root) {
76dda93c
YZ
3950 synchronize_srcu(&root->fs_info->subvol_srcu);
3951 spin_lock(&root->inode_lock);
3952 empty = RB_EMPTY_ROOT(&root->inode_tree);
3953 spin_unlock(&root->inode_lock);
3954 if (empty)
3955 btrfs_add_dead_root(root);
3956 }
3957}
3958
3959int btrfs_invalidate_inodes(struct btrfs_root *root)
3960{
3961 struct rb_node *node;
3962 struct rb_node *prev;
3963 struct btrfs_inode *entry;
3964 struct inode *inode;
3965 u64 objectid = 0;
3966
3967 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3968
3969 spin_lock(&root->inode_lock);
3970again:
3971 node = root->inode_tree.rb_node;
3972 prev = NULL;
3973 while (node) {
3974 prev = node;
3975 entry = rb_entry(node, struct btrfs_inode, rb_node);
3976
3977 if (objectid < entry->vfs_inode.i_ino)
3978 node = node->rb_left;
3979 else if (objectid > entry->vfs_inode.i_ino)
3980 node = node->rb_right;
3981 else
3982 break;
3983 }
3984 if (!node) {
3985 while (prev) {
3986 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3987 if (objectid <= entry->vfs_inode.i_ino) {
3988 node = prev;
3989 break;
3990 }
3991 prev = rb_next(prev);
3992 }
3993 }
3994 while (node) {
3995 entry = rb_entry(node, struct btrfs_inode, rb_node);
3996 objectid = entry->vfs_inode.i_ino + 1;
3997 inode = igrab(&entry->vfs_inode);
3998 if (inode) {
3999 spin_unlock(&root->inode_lock);
4000 if (atomic_read(&inode->i_count) > 1)
4001 d_prune_aliases(inode);
4002 /*
45321ac5 4003 * btrfs_drop_inode will have it removed from
76dda93c
YZ
4004 * the inode cache when its usage count
4005 * hits zero.
4006 */
4007 iput(inode);
4008 cond_resched();
4009 spin_lock(&root->inode_lock);
4010 goto again;
4011 }
4012
4013 if (cond_resched_lock(&root->inode_lock))
4014 goto again;
4015
4016 node = rb_next(node);
4017 }
4018 spin_unlock(&root->inode_lock);
4019 return 0;
5d4f98a2
YZ
4020}
4021
e02119d5
CM
4022static int btrfs_init_locked_inode(struct inode *inode, void *p)
4023{
4024 struct btrfs_iget_args *args = p;
4025 inode->i_ino = args->ino;
e02119d5 4026 BTRFS_I(inode)->root = args->root;
6a63209f 4027 btrfs_set_inode_space_info(args->root, inode);
39279cc3
CM
4028 return 0;
4029}
4030
4031static int btrfs_find_actor(struct inode *inode, void *opaque)
4032{
4033 struct btrfs_iget_args *args = opaque;
d397712b
CM
4034 return args->ino == inode->i_ino &&
4035 args->root == BTRFS_I(inode)->root;
39279cc3
CM
4036}
4037
5d4f98a2
YZ
4038static struct inode *btrfs_iget_locked(struct super_block *s,
4039 u64 objectid,
4040 struct btrfs_root *root)
39279cc3
CM
4041{
4042 struct inode *inode;
4043 struct btrfs_iget_args args;
4044 args.ino = objectid;
4045 args.root = root;
4046
4047 inode = iget5_locked(s, objectid, btrfs_find_actor,
4048 btrfs_init_locked_inode,
4049 (void *)&args);
4050 return inode;
4051}
4052
1a54ef8c
BR
4053/* Get an inode object given its location and corresponding root.
4054 * Returns in *is_new if the inode was read from disk
4055 */
4056struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
73f73415 4057 struct btrfs_root *root, int *new)
1a54ef8c
BR
4058{
4059 struct inode *inode;
4060
4061 inode = btrfs_iget_locked(s, location->objectid, root);
4062 if (!inode)
5d4f98a2 4063 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
4064
4065 if (inode->i_state & I_NEW) {
4066 BTRFS_I(inode)->root = root;
4067 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4068 btrfs_read_locked_inode(inode);
5d4f98a2
YZ
4069
4070 inode_tree_add(inode);
1a54ef8c 4071 unlock_new_inode(inode);
73f73415
JB
4072 if (new)
4073 *new = 1;
1a54ef8c
BR
4074 }
4075
4076 return inode;
4077}
4078
4df27c4d
YZ
4079static struct inode *new_simple_dir(struct super_block *s,
4080 struct btrfs_key *key,
4081 struct btrfs_root *root)
4082{
4083 struct inode *inode = new_inode(s);
4084
4085 if (!inode)
4086 return ERR_PTR(-ENOMEM);
4087
4df27c4d
YZ
4088 BTRFS_I(inode)->root = root;
4089 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4090 BTRFS_I(inode)->dummy_inode = 1;
4091
4092 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4093 inode->i_op = &simple_dir_inode_operations;
4094 inode->i_fop = &simple_dir_operations;
4095 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4096 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4097
4098 return inode;
4099}
4100
3de4586c 4101struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 4102{
d397712b 4103 struct inode *inode;
4df27c4d 4104 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
4105 struct btrfs_root *sub_root = root;
4106 struct btrfs_key location;
76dda93c 4107 int index;
5d4f98a2 4108 int ret;
39279cc3
CM
4109
4110 if (dentry->d_name.len > BTRFS_NAME_LEN)
4111 return ERR_PTR(-ENAMETOOLONG);
5f39d397 4112
39279cc3 4113 ret = btrfs_inode_by_name(dir, dentry, &location);
5f39d397 4114
39279cc3
CM
4115 if (ret < 0)
4116 return ERR_PTR(ret);
5f39d397 4117
4df27c4d
YZ
4118 if (location.objectid == 0)
4119 return NULL;
4120
4121 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 4122 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4df27c4d
YZ
4123 return inode;
4124 }
4125
4126 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4127
76dda93c 4128 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4df27c4d
YZ
4129 ret = fixup_tree_root_location(root, dir, dentry,
4130 &location, &sub_root);
4131 if (ret < 0) {
4132 if (ret != -ENOENT)
4133 inode = ERR_PTR(ret);
4134 else
4135 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4136 } else {
73f73415 4137 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 4138 }
76dda93c
YZ
4139 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4140
34d19bad 4141 if (!IS_ERR(inode) && root != sub_root) {
c71bf099
YZ
4142 down_read(&root->fs_info->cleanup_work_sem);
4143 if (!(inode->i_sb->s_flags & MS_RDONLY))
66b4ffd1 4144 ret = btrfs_orphan_cleanup(sub_root);
c71bf099 4145 up_read(&root->fs_info->cleanup_work_sem);
66b4ffd1
JB
4146 if (ret)
4147 inode = ERR_PTR(ret);
c71bf099
YZ
4148 }
4149
3de4586c
CM
4150 return inode;
4151}
4152
fe15ce44 4153static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
4154{
4155 struct btrfs_root *root;
4156
efefb143
YZ
4157 if (!dentry->d_inode && !IS_ROOT(dentry))
4158 dentry = dentry->d_parent;
76dda93c 4159
efefb143
YZ
4160 if (dentry->d_inode) {
4161 root = BTRFS_I(dentry->d_inode)->root;
4162 if (btrfs_root_refs(&root->root_item) == 0)
4163 return 1;
4164 }
76dda93c
YZ
4165 return 0;
4166}
4167
3de4586c
CM
4168static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4169 struct nameidata *nd)
4170{
4171 struct inode *inode;
4172
3de4586c
CM
4173 inode = btrfs_lookup_dentry(dir, dentry);
4174 if (IS_ERR(inode))
4175 return ERR_CAST(inode);
7b128766 4176
39279cc3
CM
4177 return d_splice_alias(inode, dentry);
4178}
4179
39279cc3
CM
4180static unsigned char btrfs_filetype_table[] = {
4181 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4182};
4183
cbdf5a24
DW
4184static int btrfs_real_readdir(struct file *filp, void *dirent,
4185 filldir_t filldir)
39279cc3 4186{
6da6abae 4187 struct inode *inode = filp->f_dentry->d_inode;
39279cc3
CM
4188 struct btrfs_root *root = BTRFS_I(inode)->root;
4189 struct btrfs_item *item;
4190 struct btrfs_dir_item *di;
4191 struct btrfs_key key;
5f39d397 4192 struct btrfs_key found_key;
39279cc3
CM
4193 struct btrfs_path *path;
4194 int ret;
4195 u32 nritems;
5f39d397 4196 struct extent_buffer *leaf;
39279cc3
CM
4197 int slot;
4198 int advance;
4199 unsigned char d_type;
4200 int over = 0;
4201 u32 di_cur;
4202 u32 di_total;
4203 u32 di_len;
4204 int key_type = BTRFS_DIR_INDEX_KEY;
5f39d397
CM
4205 char tmp_name[32];
4206 char *name_ptr;
4207 int name_len;
39279cc3
CM
4208
4209 /* FIXME, use a real flag for deciding about the key type */
4210 if (root->fs_info->tree_root == root)
4211 key_type = BTRFS_DIR_ITEM_KEY;
5f39d397 4212
3954401f
CM
4213 /* special case for "." */
4214 if (filp->f_pos == 0) {
4215 over = filldir(dirent, ".", 1,
4216 1, inode->i_ino,
4217 DT_DIR);
4218 if (over)
4219 return 0;
4220 filp->f_pos = 1;
4221 }
3954401f
CM
4222 /* special case for .., just use the back ref */
4223 if (filp->f_pos == 1) {
5ecc7e5d 4224 u64 pino = parent_ino(filp->f_path.dentry);
3954401f 4225 over = filldir(dirent, "..", 2,
5ecc7e5d 4226 2, pino, DT_DIR);
3954401f 4227 if (over)
49593bfa 4228 return 0;
3954401f
CM
4229 filp->f_pos = 2;
4230 }
49593bfa
DW
4231 path = btrfs_alloc_path();
4232 path->reada = 2;
4233
39279cc3
CM
4234 btrfs_set_key_type(&key, key_type);
4235 key.offset = filp->f_pos;
49593bfa 4236 key.objectid = inode->i_ino;
5f39d397 4237
39279cc3
CM
4238 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4239 if (ret < 0)
4240 goto err;
4241 advance = 0;
49593bfa
DW
4242
4243 while (1) {
5f39d397
CM
4244 leaf = path->nodes[0];
4245 nritems = btrfs_header_nritems(leaf);
39279cc3
CM
4246 slot = path->slots[0];
4247 if (advance || slot >= nritems) {
49593bfa 4248 if (slot >= nritems - 1) {
39279cc3
CM
4249 ret = btrfs_next_leaf(root, path);
4250 if (ret)
4251 break;
5f39d397
CM
4252 leaf = path->nodes[0];
4253 nritems = btrfs_header_nritems(leaf);
39279cc3
CM
4254 slot = path->slots[0];
4255 } else {
4256 slot++;
4257 path->slots[0]++;
4258 }
4259 }
3de4586c 4260
39279cc3 4261 advance = 1;
5f39d397
CM
4262 item = btrfs_item_nr(leaf, slot);
4263 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4264
4265 if (found_key.objectid != key.objectid)
39279cc3 4266 break;
5f39d397 4267 if (btrfs_key_type(&found_key) != key_type)
39279cc3 4268 break;
5f39d397 4269 if (found_key.offset < filp->f_pos)
39279cc3 4270 continue;
5f39d397
CM
4271
4272 filp->f_pos = found_key.offset;
49593bfa 4273
39279cc3
CM
4274 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4275 di_cur = 0;
5f39d397 4276 di_total = btrfs_item_size(leaf, item);
49593bfa
DW
4277
4278 while (di_cur < di_total) {
5f39d397
CM
4279 struct btrfs_key location;
4280
22a94d44
JB
4281 if (verify_dir_item(root, leaf, di))
4282 break;
4283
5f39d397 4284 name_len = btrfs_dir_name_len(leaf, di);
49593bfa 4285 if (name_len <= sizeof(tmp_name)) {
5f39d397
CM
4286 name_ptr = tmp_name;
4287 } else {
4288 name_ptr = kmalloc(name_len, GFP_NOFS);
49593bfa
DW
4289 if (!name_ptr) {
4290 ret = -ENOMEM;
4291 goto err;
4292 }
5f39d397
CM
4293 }
4294 read_extent_buffer(leaf, name_ptr,
4295 (unsigned long)(di + 1), name_len);
4296
4297 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4298 btrfs_dir_item_key_to_cpu(leaf, di, &location);
3de4586c
CM
4299
4300 /* is this a reference to our own snapshot? If so
4301 * skip it
4302 */
4303 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4304 location.objectid == root->root_key.objectid) {
4305 over = 0;
4306 goto skip;
4307 }
5f39d397 4308 over = filldir(dirent, name_ptr, name_len,
49593bfa 4309 found_key.offset, location.objectid,
39279cc3 4310 d_type);
5f39d397 4311
3de4586c 4312skip:
5f39d397
CM
4313 if (name_ptr != tmp_name)
4314 kfree(name_ptr);
4315
39279cc3
CM
4316 if (over)
4317 goto nopos;
5103e947 4318 di_len = btrfs_dir_name_len(leaf, di) +
49593bfa 4319 btrfs_dir_data_len(leaf, di) + sizeof(*di);
39279cc3
CM
4320 di_cur += di_len;
4321 di = (struct btrfs_dir_item *)((char *)di + di_len);
4322 }
4323 }
49593bfa
DW
4324
4325 /* Reached end of directory/root. Bump pos past the last item. */
5e591a07 4326 if (key_type == BTRFS_DIR_INDEX_KEY)
406266ab
JE
4327 /*
4328 * 32-bit glibc will use getdents64, but then strtol -
4329 * so the last number we can serve is this.
4330 */
4331 filp->f_pos = 0x7fffffff;
5e591a07
YZ
4332 else
4333 filp->f_pos++;
39279cc3
CM
4334nopos:
4335 ret = 0;
4336err:
39279cc3 4337 btrfs_free_path(path);
39279cc3
CM
4338 return ret;
4339}
4340
a9185b41 4341int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
39279cc3
CM
4342{
4343 struct btrfs_root *root = BTRFS_I(inode)->root;
4344 struct btrfs_trans_handle *trans;
4345 int ret = 0;
0af3d00b 4346 bool nolock = false;
39279cc3 4347
8929ecfa 4348 if (BTRFS_I(inode)->dummy_inode)
4ca8b41e
CM
4349 return 0;
4350
0af3d00b
JB
4351 smp_mb();
4352 nolock = (root->fs_info->closing && root == root->fs_info->tree_root);
4353
a9185b41 4354 if (wbc->sync_mode == WB_SYNC_ALL) {
0af3d00b
JB
4355 if (nolock)
4356 trans = btrfs_join_transaction_nolock(root, 1);
4357 else
4358 trans = btrfs_join_transaction(root, 1);
3612b495
TI
4359 if (IS_ERR(trans))
4360 return PTR_ERR(trans);
39279cc3 4361 btrfs_set_trans_block_group(trans, inode);
0af3d00b
JB
4362 if (nolock)
4363 ret = btrfs_end_transaction_nolock(trans, root);
4364 else
4365 ret = btrfs_commit_transaction(trans, root);
39279cc3
CM
4366 }
4367 return ret;
4368}
4369
4370/*
54aa1f4d 4371 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
4372 * inode changes. But, it is most likely to find the inode in cache.
4373 * FIXME, needs more benchmarking...there are no reasons other than performance
4374 * to keep or drop this code.
4375 */
4376void btrfs_dirty_inode(struct inode *inode)
4377{
4378 struct btrfs_root *root = BTRFS_I(inode)->root;
4379 struct btrfs_trans_handle *trans;
8929ecfa
YZ
4380 int ret;
4381
4382 if (BTRFS_I(inode)->dummy_inode)
4383 return;
39279cc3 4384
f9295749 4385 trans = btrfs_join_transaction(root, 1);
3612b495 4386 BUG_ON(IS_ERR(trans));
39279cc3 4387 btrfs_set_trans_block_group(trans, inode);
8929ecfa
YZ
4388
4389 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
4390 if (ret && ret == -ENOSPC) {
4391 /* whoops, lets try again with the full transaction */
4392 btrfs_end_transaction(trans, root);
4393 trans = btrfs_start_transaction(root, 1);
9aeead73
CM
4394 if (IS_ERR(trans)) {
4395 if (printk_ratelimit()) {
4396 printk(KERN_ERR "btrfs: fail to "
4397 "dirty inode %lu error %ld\n",
4398 inode->i_ino, PTR_ERR(trans));
4399 }
4400 return;
4401 }
94b60442 4402 btrfs_set_trans_block_group(trans, inode);
8929ecfa 4403
94b60442
CM
4404 ret = btrfs_update_inode(trans, root, inode);
4405 if (ret) {
9aeead73
CM
4406 if (printk_ratelimit()) {
4407 printk(KERN_ERR "btrfs: fail to "
4408 "dirty inode %lu error %d\n",
4409 inode->i_ino, ret);
4410 }
94b60442
CM
4411 }
4412 }
39279cc3 4413 btrfs_end_transaction(trans, root);
39279cc3
CM
4414}
4415
d352ac68
CM
4416/*
4417 * find the highest existing sequence number in a directory
4418 * and then set the in-memory index_cnt variable to reflect
4419 * free sequence numbers
4420 */
aec7477b
JB
4421static int btrfs_set_inode_index_count(struct inode *inode)
4422{
4423 struct btrfs_root *root = BTRFS_I(inode)->root;
4424 struct btrfs_key key, found_key;
4425 struct btrfs_path *path;
4426 struct extent_buffer *leaf;
4427 int ret;
4428
4429 key.objectid = inode->i_ino;
4430 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4431 key.offset = (u64)-1;
4432
4433 path = btrfs_alloc_path();
4434 if (!path)
4435 return -ENOMEM;
4436
4437 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4438 if (ret < 0)
4439 goto out;
4440 /* FIXME: we should be able to handle this */
4441 if (ret == 0)
4442 goto out;
4443 ret = 0;
4444
4445 /*
4446 * MAGIC NUMBER EXPLANATION:
4447 * since we search a directory based on f_pos we have to start at 2
4448 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4449 * else has to start at 2
4450 */
4451 if (path->slots[0] == 0) {
4452 BTRFS_I(inode)->index_cnt = 2;
4453 goto out;
4454 }
4455
4456 path->slots[0]--;
4457
4458 leaf = path->nodes[0];
4459 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4460
4461 if (found_key.objectid != inode->i_ino ||
4462 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4463 BTRFS_I(inode)->index_cnt = 2;
4464 goto out;
4465 }
4466
4467 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4468out:
4469 btrfs_free_path(path);
4470 return ret;
4471}
4472
d352ac68
CM
4473/*
4474 * helper to find a free sequence number in a given directory. This current
4475 * code is very simple, later versions will do smarter things in the btree
4476 */
3de4586c 4477int btrfs_set_inode_index(struct inode *dir, u64 *index)
aec7477b
JB
4478{
4479 int ret = 0;
4480
4481 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4482 ret = btrfs_set_inode_index_count(dir);
d397712b 4483 if (ret)
aec7477b
JB
4484 return ret;
4485 }
4486
00e4e6b3 4487 *index = BTRFS_I(dir)->index_cnt;
aec7477b
JB
4488 BTRFS_I(dir)->index_cnt++;
4489
4490 return ret;
4491}
4492
39279cc3
CM
4493static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4494 struct btrfs_root *root,
aec7477b 4495 struct inode *dir,
9c58309d 4496 const char *name, int name_len,
d2fb3437
YZ
4497 u64 ref_objectid, u64 objectid,
4498 u64 alloc_hint, int mode, u64 *index)
39279cc3
CM
4499{
4500 struct inode *inode;
5f39d397 4501 struct btrfs_inode_item *inode_item;
39279cc3 4502 struct btrfs_key *location;
5f39d397 4503 struct btrfs_path *path;
9c58309d
CM
4504 struct btrfs_inode_ref *ref;
4505 struct btrfs_key key[2];
4506 u32 sizes[2];
4507 unsigned long ptr;
39279cc3
CM
4508 int ret;
4509 int owner;
4510
5f39d397
CM
4511 path = btrfs_alloc_path();
4512 BUG_ON(!path);
4513
39279cc3
CM
4514 inode = new_inode(root->fs_info->sb);
4515 if (!inode)
4516 return ERR_PTR(-ENOMEM);
4517
aec7477b 4518 if (dir) {
1abe9b8a 4519 trace_btrfs_inode_request(dir);
4520
3de4586c 4521 ret = btrfs_set_inode_index(dir, index);
09771430
SF
4522 if (ret) {
4523 iput(inode);
aec7477b 4524 return ERR_PTR(ret);
09771430 4525 }
aec7477b
JB
4526 }
4527 /*
4528 * index_cnt is ignored for everything but a dir,
4529 * btrfs_get_inode_index_count has an explanation for the magic
4530 * number
4531 */
4532 BTRFS_I(inode)->index_cnt = 2;
39279cc3 4533 BTRFS_I(inode)->root = root;
e02119d5 4534 BTRFS_I(inode)->generation = trans->transid;
76195853 4535 inode->i_generation = BTRFS_I(inode)->generation;
6a63209f 4536 btrfs_set_inode_space_info(root, inode);
b888db2b 4537
39279cc3
CM
4538 if (mode & S_IFDIR)
4539 owner = 0;
4540 else
4541 owner = 1;
d2fb3437
YZ
4542 BTRFS_I(inode)->block_group =
4543 btrfs_find_block_group(root, 0, alloc_hint, owner);
9c58309d
CM
4544
4545 key[0].objectid = objectid;
4546 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4547 key[0].offset = 0;
4548
4549 key[1].objectid = objectid;
4550 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4551 key[1].offset = ref_objectid;
4552
4553 sizes[0] = sizeof(struct btrfs_inode_item);
4554 sizes[1] = name_len + sizeof(*ref);
4555
b9473439 4556 path->leave_spinning = 1;
9c58309d
CM
4557 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4558 if (ret != 0)
5f39d397
CM
4559 goto fail;
4560
ecc11fab 4561 inode_init_owner(inode, dir, mode);
39279cc3 4562 inode->i_ino = objectid;
a76a3cd4 4563 inode_set_bytes(inode, 0);
39279cc3 4564 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5f39d397
CM
4565 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4566 struct btrfs_inode_item);
e02119d5 4567 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d
CM
4568
4569 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4570 struct btrfs_inode_ref);
4571 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
00e4e6b3 4572 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
9c58309d
CM
4573 ptr = (unsigned long)(ref + 1);
4574 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4575
5f39d397
CM
4576 btrfs_mark_buffer_dirty(path->nodes[0]);
4577 btrfs_free_path(path);
4578
39279cc3
CM
4579 location = &BTRFS_I(inode)->location;
4580 location->objectid = objectid;
39279cc3
CM
4581 location->offset = 0;
4582 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4583
6cbff00f
CH
4584 btrfs_inherit_iflags(inode, dir);
4585
94272164
CM
4586 if ((mode & S_IFREG)) {
4587 if (btrfs_test_opt(root, NODATASUM))
4588 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
75e7cb7f
LB
4589 if (btrfs_test_opt(root, NODATACOW) ||
4590 (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
94272164
CM
4591 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4592 }
4593
39279cc3 4594 insert_inode_hash(inode);
5d4f98a2 4595 inode_tree_add(inode);
1abe9b8a 4596
4597 trace_btrfs_inode_new(inode);
4598
39279cc3 4599 return inode;
5f39d397 4600fail:
aec7477b
JB
4601 if (dir)
4602 BTRFS_I(dir)->index_cnt--;
5f39d397 4603 btrfs_free_path(path);
09771430 4604 iput(inode);
5f39d397 4605 return ERR_PTR(ret);
39279cc3
CM
4606}
4607
4608static inline u8 btrfs_inode_type(struct inode *inode)
4609{
4610 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4611}
4612
d352ac68
CM
4613/*
4614 * utility function to add 'inode' into 'parent_inode' with
4615 * a give name and a given sequence number.
4616 * if 'add_backref' is true, also insert a backref from the
4617 * inode to the parent directory.
4618 */
e02119d5
CM
4619int btrfs_add_link(struct btrfs_trans_handle *trans,
4620 struct inode *parent_inode, struct inode *inode,
4621 const char *name, int name_len, int add_backref, u64 index)
39279cc3 4622{
4df27c4d 4623 int ret = 0;
39279cc3 4624 struct btrfs_key key;
e02119d5 4625 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5f39d397 4626
4df27c4d
YZ
4627 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4628 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4629 } else {
4630 key.objectid = inode->i_ino;
4631 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4632 key.offset = 0;
4633 }
4634
4635 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4636 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4637 key.objectid, root->root_key.objectid,
4638 parent_inode->i_ino,
4639 index, name, name_len);
4640 } else if (add_backref) {
4641 ret = btrfs_insert_inode_ref(trans, root,
4642 name, name_len, inode->i_ino,
4643 parent_inode->i_ino, index);
4644 }
39279cc3 4645
39279cc3 4646 if (ret == 0) {
4df27c4d
YZ
4647 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4648 parent_inode->i_ino, &key,
4649 btrfs_inode_type(inode), index);
4650 BUG_ON(ret);
4651
dbe674a9 4652 btrfs_i_size_write(parent_inode, parent_inode->i_size +
e02119d5 4653 name_len * 2);
79c44584 4654 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
e02119d5 4655 ret = btrfs_update_inode(trans, root, parent_inode);
39279cc3
CM
4656 }
4657 return ret;
4658}
4659
4660static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
a1b075d2
JB
4661 struct inode *dir, struct dentry *dentry,
4662 struct inode *inode, int backref, u64 index)
39279cc3 4663{
a1b075d2
JB
4664 int err = btrfs_add_link(trans, dir, inode,
4665 dentry->d_name.name, dentry->d_name.len,
4666 backref, index);
39279cc3
CM
4667 if (!err) {
4668 d_instantiate(dentry, inode);
4669 return 0;
4670 }
4671 if (err > 0)
4672 err = -EEXIST;
4673 return err;
4674}
4675
618e21d5
JB
4676static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4677 int mode, dev_t rdev)
4678{
4679 struct btrfs_trans_handle *trans;
4680 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4681 struct inode *inode = NULL;
618e21d5
JB
4682 int err;
4683 int drop_inode = 0;
4684 u64 objectid;
1832a6d5 4685 unsigned long nr = 0;
00e4e6b3 4686 u64 index = 0;
618e21d5
JB
4687
4688 if (!new_valid_dev(rdev))
4689 return -EINVAL;
4690
a22285a6
YZ
4691 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4692 if (err)
4693 return err;
4694
9ed74f2d
JB
4695 /*
4696 * 2 for inode item and ref
4697 * 2 for dir items
4698 * 1 for xattr if selinux is on
4699 */
a22285a6
YZ
4700 trans = btrfs_start_transaction(root, 5);
4701 if (IS_ERR(trans))
4702 return PTR_ERR(trans);
1832a6d5 4703
618e21d5
JB
4704 btrfs_set_trans_block_group(trans, dir);
4705
aec7477b 4706 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
a1b075d2 4707 dentry->d_name.len, dir->i_ino, objectid,
00e4e6b3 4708 BTRFS_I(dir)->block_group, mode, &index);
618e21d5
JB
4709 err = PTR_ERR(inode);
4710 if (IS_ERR(inode))
4711 goto out_unlock;
4712
f34f57a3 4713 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4714 if (err) {
4715 drop_inode = 1;
4716 goto out_unlock;
4717 }
4718
618e21d5 4719 btrfs_set_trans_block_group(trans, inode);
a1b075d2 4720 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
618e21d5
JB
4721 if (err)
4722 drop_inode = 1;
4723 else {
4724 inode->i_op = &btrfs_special_inode_operations;
4725 init_special_inode(inode, inode->i_mode, rdev);
1b4ab1bb 4726 btrfs_update_inode(trans, root, inode);
618e21d5 4727 }
618e21d5
JB
4728 btrfs_update_inode_block_group(trans, inode);
4729 btrfs_update_inode_block_group(trans, dir);
4730out_unlock:
d3c2fdcf 4731 nr = trans->blocks_used;
89ce8a63 4732 btrfs_end_transaction_throttle(trans, root);
a22285a6 4733 btrfs_btree_balance_dirty(root, nr);
618e21d5
JB
4734 if (drop_inode) {
4735 inode_dec_link_count(inode);
4736 iput(inode);
4737 }
618e21d5
JB
4738 return err;
4739}
4740
39279cc3
CM
4741static int btrfs_create(struct inode *dir, struct dentry *dentry,
4742 int mode, struct nameidata *nd)
4743{
4744 struct btrfs_trans_handle *trans;
4745 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4746 struct inode *inode = NULL;
39279cc3 4747 int drop_inode = 0;
a22285a6 4748 int err;
1832a6d5 4749 unsigned long nr = 0;
39279cc3 4750 u64 objectid;
00e4e6b3 4751 u64 index = 0;
39279cc3 4752
a22285a6
YZ
4753 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4754 if (err)
4755 return err;
9ed74f2d
JB
4756 /*
4757 * 2 for inode item and ref
4758 * 2 for dir items
4759 * 1 for xattr if selinux is on
4760 */
a22285a6
YZ
4761 trans = btrfs_start_transaction(root, 5);
4762 if (IS_ERR(trans))
4763 return PTR_ERR(trans);
9ed74f2d 4764
39279cc3
CM
4765 btrfs_set_trans_block_group(trans, dir);
4766
aec7477b 4767 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
a1b075d2
JB
4768 dentry->d_name.len, dir->i_ino, objectid,
4769 BTRFS_I(dir)->block_group, mode, &index);
39279cc3
CM
4770 err = PTR_ERR(inode);
4771 if (IS_ERR(inode))
4772 goto out_unlock;
4773
f34f57a3 4774 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4775 if (err) {
4776 drop_inode = 1;
4777 goto out_unlock;
4778 }
4779
39279cc3 4780 btrfs_set_trans_block_group(trans, inode);
a1b075d2 4781 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3
CM
4782 if (err)
4783 drop_inode = 1;
4784 else {
4785 inode->i_mapping->a_ops = &btrfs_aops;
04160088 4786 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
4787 inode->i_fop = &btrfs_file_operations;
4788 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 4789 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 4790 }
39279cc3
CM
4791 btrfs_update_inode_block_group(trans, inode);
4792 btrfs_update_inode_block_group(trans, dir);
4793out_unlock:
d3c2fdcf 4794 nr = trans->blocks_used;
ab78c84d 4795 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
4796 if (drop_inode) {
4797 inode_dec_link_count(inode);
4798 iput(inode);
4799 }
d3c2fdcf 4800 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4801 return err;
4802}
4803
4804static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4805 struct dentry *dentry)
4806{
4807 struct btrfs_trans_handle *trans;
4808 struct btrfs_root *root = BTRFS_I(dir)->root;
4809 struct inode *inode = old_dentry->d_inode;
00e4e6b3 4810 u64 index;
1832a6d5 4811 unsigned long nr = 0;
39279cc3
CM
4812 int err;
4813 int drop_inode = 0;
4814
4815 if (inode->i_nlink == 0)
4816 return -ENOENT;
4817
4a8be425
TH
4818 /* do not allow sys_link's with other subvols of the same device */
4819 if (root->objectid != BTRFS_I(inode)->root->objectid)
3ab3564f 4820 return -EXDEV;
4a8be425 4821
9ed74f2d 4822 btrfs_inc_nlink(inode);
bc1cbf1f 4823 inode->i_ctime = CURRENT_TIME;
9ed74f2d 4824
3de4586c 4825 err = btrfs_set_inode_index(dir, &index);
aec7477b
JB
4826 if (err)
4827 goto fail;
4828
a22285a6 4829 /*
7e6b6465 4830 * 2 items for inode and inode ref
a22285a6 4831 * 2 items for dir items
7e6b6465 4832 * 1 item for parent inode
a22285a6 4833 */
7e6b6465 4834 trans = btrfs_start_transaction(root, 5);
a22285a6
YZ
4835 if (IS_ERR(trans)) {
4836 err = PTR_ERR(trans);
4837 goto fail;
4838 }
5f39d397 4839
39279cc3 4840 btrfs_set_trans_block_group(trans, dir);
7de9c6ee 4841 ihold(inode);
aec7477b 4842
a1b075d2 4843 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5f39d397 4844
a5719521 4845 if (err) {
54aa1f4d 4846 drop_inode = 1;
a5719521 4847 } else {
6a912213 4848 struct dentry *parent = dget_parent(dentry);
a5719521
YZ
4849 btrfs_update_inode_block_group(trans, dir);
4850 err = btrfs_update_inode(trans, root, inode);
4851 BUG_ON(err);
6a912213
JB
4852 btrfs_log_new_name(trans, inode, NULL, parent);
4853 dput(parent);
a5719521 4854 }
39279cc3 4855
d3c2fdcf 4856 nr = trans->blocks_used;
ab78c84d 4857 btrfs_end_transaction_throttle(trans, root);
1832a6d5 4858fail:
39279cc3
CM
4859 if (drop_inode) {
4860 inode_dec_link_count(inode);
4861 iput(inode);
4862 }
d3c2fdcf 4863 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4864 return err;
4865}
4866
39279cc3
CM
4867static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4868{
b9d86667 4869 struct inode *inode = NULL;
39279cc3
CM
4870 struct btrfs_trans_handle *trans;
4871 struct btrfs_root *root = BTRFS_I(dir)->root;
4872 int err = 0;
4873 int drop_on_err = 0;
b9d86667 4874 u64 objectid = 0;
00e4e6b3 4875 u64 index = 0;
d3c2fdcf 4876 unsigned long nr = 1;
39279cc3 4877
a22285a6
YZ
4878 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
4879 if (err)
4880 return err;
4881
9ed74f2d
JB
4882 /*
4883 * 2 items for inode and ref
4884 * 2 items for dir items
4885 * 1 for xattr if selinux is on
4886 */
a22285a6
YZ
4887 trans = btrfs_start_transaction(root, 5);
4888 if (IS_ERR(trans))
4889 return PTR_ERR(trans);
9ed74f2d 4890 btrfs_set_trans_block_group(trans, dir);
39279cc3 4891
aec7477b 4892 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
a1b075d2 4893 dentry->d_name.len, dir->i_ino, objectid,
00e4e6b3
CM
4894 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4895 &index);
39279cc3
CM
4896 if (IS_ERR(inode)) {
4897 err = PTR_ERR(inode);
4898 goto out_fail;
4899 }
5f39d397 4900
39279cc3 4901 drop_on_err = 1;
33268eaf 4902
f34f57a3 4903 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4904 if (err)
4905 goto out_fail;
4906
39279cc3
CM
4907 inode->i_op = &btrfs_dir_inode_operations;
4908 inode->i_fop = &btrfs_dir_file_operations;
4909 btrfs_set_trans_block_group(trans, inode);
4910
dbe674a9 4911 btrfs_i_size_write(inode, 0);
39279cc3
CM
4912 err = btrfs_update_inode(trans, root, inode);
4913 if (err)
4914 goto out_fail;
5f39d397 4915
a1b075d2
JB
4916 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
4917 dentry->d_name.len, 0, index);
39279cc3
CM
4918 if (err)
4919 goto out_fail;
5f39d397 4920
39279cc3
CM
4921 d_instantiate(dentry, inode);
4922 drop_on_err = 0;
39279cc3
CM
4923 btrfs_update_inode_block_group(trans, inode);
4924 btrfs_update_inode_block_group(trans, dir);
4925
4926out_fail:
d3c2fdcf 4927 nr = trans->blocks_used;
ab78c84d 4928 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
4929 if (drop_on_err)
4930 iput(inode);
d3c2fdcf 4931 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4932 return err;
4933}
4934
d352ac68
CM
4935/* helper for btfs_get_extent. Given an existing extent in the tree,
4936 * and an extent that you want to insert, deal with overlap and insert
4937 * the new extent into the tree.
4938 */
3b951516
CM
4939static int merge_extent_mapping(struct extent_map_tree *em_tree,
4940 struct extent_map *existing,
e6dcd2dc
CM
4941 struct extent_map *em,
4942 u64 map_start, u64 map_len)
3b951516
CM
4943{
4944 u64 start_diff;
3b951516 4945
e6dcd2dc
CM
4946 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4947 start_diff = map_start - em->start;
4948 em->start = map_start;
4949 em->len = map_len;
c8b97818
CM
4950 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4951 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
e6dcd2dc 4952 em->block_start += start_diff;
c8b97818
CM
4953 em->block_len -= start_diff;
4954 }
e6dcd2dc 4955 return add_extent_mapping(em_tree, em);
3b951516
CM
4956}
4957
c8b97818
CM
4958static noinline int uncompress_inline(struct btrfs_path *path,
4959 struct inode *inode, struct page *page,
4960 size_t pg_offset, u64 extent_offset,
4961 struct btrfs_file_extent_item *item)
4962{
4963 int ret;
4964 struct extent_buffer *leaf = path->nodes[0];
4965 char *tmp;
4966 size_t max_size;
4967 unsigned long inline_size;
4968 unsigned long ptr;
261507a0 4969 int compress_type;
c8b97818
CM
4970
4971 WARN_ON(pg_offset != 0);
261507a0 4972 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
4973 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4974 inline_size = btrfs_file_extent_inline_item_len(leaf,
4975 btrfs_item_nr(leaf, path->slots[0]));
4976 tmp = kmalloc(inline_size, GFP_NOFS);
4977 ptr = btrfs_file_extent_inline_start(item);
4978
4979 read_extent_buffer(leaf, tmp, ptr, inline_size);
4980
5b050f04 4981 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
261507a0
LZ
4982 ret = btrfs_decompress(compress_type, tmp, page,
4983 extent_offset, inline_size, max_size);
c8b97818
CM
4984 if (ret) {
4985 char *kaddr = kmap_atomic(page, KM_USER0);
4986 unsigned long copy_size = min_t(u64,
4987 PAGE_CACHE_SIZE - pg_offset,
4988 max_size - extent_offset);
4989 memset(kaddr + pg_offset, 0, copy_size);
4990 kunmap_atomic(kaddr, KM_USER0);
4991 }
4992 kfree(tmp);
4993 return 0;
4994}
4995
d352ac68
CM
4996/*
4997 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
4998 * the ugly parts come from merging extents from the disk with the in-ram
4999 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
5000 * where the in-ram extents might be locked pending data=ordered completion.
5001 *
5002 * This also copies inline extents directly into the page.
5003 */
d397712b 5004
a52d9a80 5005struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
70dec807 5006 size_t pg_offset, u64 start, u64 len,
a52d9a80
CM
5007 int create)
5008{
5009 int ret;
5010 int err = 0;
db94535d 5011 u64 bytenr;
a52d9a80
CM
5012 u64 extent_start = 0;
5013 u64 extent_end = 0;
5014 u64 objectid = inode->i_ino;
5015 u32 found_type;
f421950f 5016 struct btrfs_path *path = NULL;
a52d9a80
CM
5017 struct btrfs_root *root = BTRFS_I(inode)->root;
5018 struct btrfs_file_extent_item *item;
5f39d397
CM
5019 struct extent_buffer *leaf;
5020 struct btrfs_key found_key;
a52d9a80
CM
5021 struct extent_map *em = NULL;
5022 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
d1310b2e 5023 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a52d9a80 5024 struct btrfs_trans_handle *trans = NULL;
261507a0 5025 int compress_type;
a52d9a80 5026
a52d9a80 5027again:
890871be 5028 read_lock(&em_tree->lock);
d1310b2e 5029 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d
CM
5030 if (em)
5031 em->bdev = root->fs_info->fs_devices->latest_bdev;
890871be 5032 read_unlock(&em_tree->lock);
d1310b2e 5033
a52d9a80 5034 if (em) {
e1c4b745
CM
5035 if (em->start > start || em->start + em->len <= start)
5036 free_extent_map(em);
5037 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
5038 free_extent_map(em);
5039 else
5040 goto out;
a52d9a80 5041 }
d1310b2e 5042 em = alloc_extent_map(GFP_NOFS);
a52d9a80 5043 if (!em) {
d1310b2e
CM
5044 err = -ENOMEM;
5045 goto out;
a52d9a80 5046 }
e6dcd2dc 5047 em->bdev = root->fs_info->fs_devices->latest_bdev;
d1310b2e 5048 em->start = EXTENT_MAP_HOLE;
445a6944 5049 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 5050 em->len = (u64)-1;
c8b97818 5051 em->block_len = (u64)-1;
f421950f
CM
5052
5053 if (!path) {
5054 path = btrfs_alloc_path();
5055 BUG_ON(!path);
5056 }
5057
179e29e4
CM
5058 ret = btrfs_lookup_file_extent(trans, root, path,
5059 objectid, start, trans != NULL);
a52d9a80
CM
5060 if (ret < 0) {
5061 err = ret;
5062 goto out;
5063 }
5064
5065 if (ret != 0) {
5066 if (path->slots[0] == 0)
5067 goto not_found;
5068 path->slots[0]--;
5069 }
5070
5f39d397
CM
5071 leaf = path->nodes[0];
5072 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 5073 struct btrfs_file_extent_item);
a52d9a80 5074 /* are we inside the extent that was found? */
5f39d397
CM
5075 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5076 found_type = btrfs_key_type(&found_key);
5077 if (found_key.objectid != objectid ||
a52d9a80
CM
5078 found_type != BTRFS_EXTENT_DATA_KEY) {
5079 goto not_found;
5080 }
5081
5f39d397
CM
5082 found_type = btrfs_file_extent_type(leaf, item);
5083 extent_start = found_key.offset;
261507a0 5084 compress_type = btrfs_file_extent_compression(leaf, item);
d899e052
YZ
5085 if (found_type == BTRFS_FILE_EXTENT_REG ||
5086 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 5087 extent_end = extent_start +
db94535d 5088 btrfs_file_extent_num_bytes(leaf, item);
9036c102
YZ
5089 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5090 size_t size;
5091 size = btrfs_file_extent_inline_len(leaf, item);
5092 extent_end = (extent_start + size + root->sectorsize - 1) &
5093 ~((u64)root->sectorsize - 1);
5094 }
5095
5096 if (start >= extent_end) {
5097 path->slots[0]++;
5098 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5099 ret = btrfs_next_leaf(root, path);
5100 if (ret < 0) {
5101 err = ret;
5102 goto out;
a52d9a80 5103 }
9036c102
YZ
5104 if (ret > 0)
5105 goto not_found;
5106 leaf = path->nodes[0];
a52d9a80 5107 }
9036c102
YZ
5108 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5109 if (found_key.objectid != objectid ||
5110 found_key.type != BTRFS_EXTENT_DATA_KEY)
5111 goto not_found;
5112 if (start + len <= found_key.offset)
5113 goto not_found;
5114 em->start = start;
5115 em->len = found_key.offset - start;
5116 goto not_found_em;
5117 }
5118
d899e052
YZ
5119 if (found_type == BTRFS_FILE_EXTENT_REG ||
5120 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
9036c102
YZ
5121 em->start = extent_start;
5122 em->len = extent_end - extent_start;
ff5b7ee3
YZ
5123 em->orig_start = extent_start -
5124 btrfs_file_extent_offset(leaf, item);
db94535d
CM
5125 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5126 if (bytenr == 0) {
5f39d397 5127 em->block_start = EXTENT_MAP_HOLE;
a52d9a80
CM
5128 goto insert;
5129 }
261507a0 5130 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818 5131 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
261507a0 5132 em->compress_type = compress_type;
c8b97818
CM
5133 em->block_start = bytenr;
5134 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5135 item);
5136 } else {
5137 bytenr += btrfs_file_extent_offset(leaf, item);
5138 em->block_start = bytenr;
5139 em->block_len = em->len;
d899e052
YZ
5140 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5141 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
c8b97818 5142 }
a52d9a80
CM
5143 goto insert;
5144 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 5145 unsigned long ptr;
a52d9a80 5146 char *map;
3326d1b0
CM
5147 size_t size;
5148 size_t extent_offset;
5149 size_t copy_size;
a52d9a80 5150
689f9346 5151 em->block_start = EXTENT_MAP_INLINE;
c8b97818 5152 if (!page || create) {
689f9346 5153 em->start = extent_start;
9036c102 5154 em->len = extent_end - extent_start;
689f9346
Y
5155 goto out;
5156 }
5f39d397 5157
9036c102
YZ
5158 size = btrfs_file_extent_inline_len(leaf, item);
5159 extent_offset = page_offset(page) + pg_offset - extent_start;
70dec807 5160 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3326d1b0 5161 size - extent_offset);
3326d1b0 5162 em->start = extent_start + extent_offset;
70dec807
CM
5163 em->len = (copy_size + root->sectorsize - 1) &
5164 ~((u64)root->sectorsize - 1);
ff5b7ee3 5165 em->orig_start = EXTENT_MAP_INLINE;
261507a0 5166 if (compress_type) {
c8b97818 5167 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
261507a0
LZ
5168 em->compress_type = compress_type;
5169 }
689f9346 5170 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
179e29e4 5171 if (create == 0 && !PageUptodate(page)) {
261507a0
LZ
5172 if (btrfs_file_extent_compression(leaf, item) !=
5173 BTRFS_COMPRESS_NONE) {
c8b97818
CM
5174 ret = uncompress_inline(path, inode, page,
5175 pg_offset,
5176 extent_offset, item);
5177 BUG_ON(ret);
5178 } else {
5179 map = kmap(page);
5180 read_extent_buffer(leaf, map + pg_offset, ptr,
5181 copy_size);
93c82d57
CM
5182 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5183 memset(map + pg_offset + copy_size, 0,
5184 PAGE_CACHE_SIZE - pg_offset -
5185 copy_size);
5186 }
c8b97818
CM
5187 kunmap(page);
5188 }
179e29e4
CM
5189 flush_dcache_page(page);
5190 } else if (create && PageUptodate(page)) {
0ca1f7ce 5191 WARN_ON(1);
179e29e4
CM
5192 if (!trans) {
5193 kunmap(page);
5194 free_extent_map(em);
5195 em = NULL;
5196 btrfs_release_path(root, path);
f9295749 5197 trans = btrfs_join_transaction(root, 1);
3612b495
TI
5198 if (IS_ERR(trans))
5199 return ERR_CAST(trans);
179e29e4
CM
5200 goto again;
5201 }
c8b97818 5202 map = kmap(page);
70dec807 5203 write_extent_buffer(leaf, map + pg_offset, ptr,
179e29e4 5204 copy_size);
c8b97818 5205 kunmap(page);
179e29e4 5206 btrfs_mark_buffer_dirty(leaf);
a52d9a80 5207 }
d1310b2e
CM
5208 set_extent_uptodate(io_tree, em->start,
5209 extent_map_end(em) - 1, GFP_NOFS);
a52d9a80
CM
5210 goto insert;
5211 } else {
d397712b 5212 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
a52d9a80
CM
5213 WARN_ON(1);
5214 }
5215not_found:
5216 em->start = start;
d1310b2e 5217 em->len = len;
a52d9a80 5218not_found_em:
5f39d397 5219 em->block_start = EXTENT_MAP_HOLE;
9036c102 5220 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
a52d9a80
CM
5221insert:
5222 btrfs_release_path(root, path);
d1310b2e 5223 if (em->start > start || extent_map_end(em) <= start) {
d397712b
CM
5224 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5225 "[%llu %llu]\n", (unsigned long long)em->start,
5226 (unsigned long long)em->len,
5227 (unsigned long long)start,
5228 (unsigned long long)len);
a52d9a80
CM
5229 err = -EIO;
5230 goto out;
5231 }
d1310b2e
CM
5232
5233 err = 0;
890871be 5234 write_lock(&em_tree->lock);
a52d9a80 5235 ret = add_extent_mapping(em_tree, em);
3b951516
CM
5236 /* it is possible that someone inserted the extent into the tree
5237 * while we had the lock dropped. It is also possible that
5238 * an overlapping map exists in the tree
5239 */
a52d9a80 5240 if (ret == -EEXIST) {
3b951516 5241 struct extent_map *existing;
e6dcd2dc
CM
5242
5243 ret = 0;
5244
3b951516 5245 existing = lookup_extent_mapping(em_tree, start, len);
e1c4b745
CM
5246 if (existing && (existing->start > start ||
5247 existing->start + existing->len <= start)) {
5248 free_extent_map(existing);
5249 existing = NULL;
5250 }
3b951516
CM
5251 if (!existing) {
5252 existing = lookup_extent_mapping(em_tree, em->start,
5253 em->len);
5254 if (existing) {
5255 err = merge_extent_mapping(em_tree, existing,
e6dcd2dc
CM
5256 em, start,
5257 root->sectorsize);
3b951516
CM
5258 free_extent_map(existing);
5259 if (err) {
5260 free_extent_map(em);
5261 em = NULL;
5262 }
5263 } else {
5264 err = -EIO;
3b951516
CM
5265 free_extent_map(em);
5266 em = NULL;
5267 }
5268 } else {
5269 free_extent_map(em);
5270 em = existing;
e6dcd2dc 5271 err = 0;
a52d9a80 5272 }
a52d9a80 5273 }
890871be 5274 write_unlock(&em_tree->lock);
a52d9a80 5275out:
1abe9b8a 5276
5277 trace_btrfs_get_extent(root, em);
5278
f421950f
CM
5279 if (path)
5280 btrfs_free_path(path);
a52d9a80
CM
5281 if (trans) {
5282 ret = btrfs_end_transaction(trans, root);
d397712b 5283 if (!err)
a52d9a80
CM
5284 err = ret;
5285 }
a52d9a80
CM
5286 if (err) {
5287 free_extent_map(em);
a52d9a80
CM
5288 return ERR_PTR(err);
5289 }
5290 return em;
5291}
5292
ec29ed5b
CM
5293struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5294 size_t pg_offset, u64 start, u64 len,
5295 int create)
5296{
5297 struct extent_map *em;
5298 struct extent_map *hole_em = NULL;
5299 u64 range_start = start;
5300 u64 end;
5301 u64 found;
5302 u64 found_end;
5303 int err = 0;
5304
5305 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5306 if (IS_ERR(em))
5307 return em;
5308 if (em) {
5309 /*
5310 * if our em maps to a hole, there might
5311 * actually be delalloc bytes behind it
5312 */
5313 if (em->block_start != EXTENT_MAP_HOLE)
5314 return em;
5315 else
5316 hole_em = em;
5317 }
5318
5319 /* check to see if we've wrapped (len == -1 or similar) */
5320 end = start + len;
5321 if (end < start)
5322 end = (u64)-1;
5323 else
5324 end -= 1;
5325
5326 em = NULL;
5327
5328 /* ok, we didn't find anything, lets look for delalloc */
5329 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5330 end, len, EXTENT_DELALLOC, 1);
5331 found_end = range_start + found;
5332 if (found_end < range_start)
5333 found_end = (u64)-1;
5334
5335 /*
5336 * we didn't find anything useful, return
5337 * the original results from get_extent()
5338 */
5339 if (range_start > end || found_end <= start) {
5340 em = hole_em;
5341 hole_em = NULL;
5342 goto out;
5343 }
5344
5345 /* adjust the range_start to make sure it doesn't
5346 * go backwards from the start they passed in
5347 */
5348 range_start = max(start,range_start);
5349 found = found_end - range_start;
5350
5351 if (found > 0) {
5352 u64 hole_start = start;
5353 u64 hole_len = len;
5354
5355 em = alloc_extent_map(GFP_NOFS);
5356 if (!em) {
5357 err = -ENOMEM;
5358 goto out;
5359 }
5360 /*
5361 * when btrfs_get_extent can't find anything it
5362 * returns one huge hole
5363 *
5364 * make sure what it found really fits our range, and
5365 * adjust to make sure it is based on the start from
5366 * the caller
5367 */
5368 if (hole_em) {
5369 u64 calc_end = extent_map_end(hole_em);
5370
5371 if (calc_end <= start || (hole_em->start > end)) {
5372 free_extent_map(hole_em);
5373 hole_em = NULL;
5374 } else {
5375 hole_start = max(hole_em->start, start);
5376 hole_len = calc_end - hole_start;
5377 }
5378 }
5379 em->bdev = NULL;
5380 if (hole_em && range_start > hole_start) {
5381 /* our hole starts before our delalloc, so we
5382 * have to return just the parts of the hole
5383 * that go until the delalloc starts
5384 */
5385 em->len = min(hole_len,
5386 range_start - hole_start);
5387 em->start = hole_start;
5388 em->orig_start = hole_start;
5389 /*
5390 * don't adjust block start at all,
5391 * it is fixed at EXTENT_MAP_HOLE
5392 */
5393 em->block_start = hole_em->block_start;
5394 em->block_len = hole_len;
5395 } else {
5396 em->start = range_start;
5397 em->len = found;
5398 em->orig_start = range_start;
5399 em->block_start = EXTENT_MAP_DELALLOC;
5400 em->block_len = found;
5401 }
5402 } else if (hole_em) {
5403 return hole_em;
5404 }
5405out:
5406
5407 free_extent_map(hole_em);
5408 if (err) {
5409 free_extent_map(em);
5410 return ERR_PTR(err);
5411 }
5412 return em;
5413}
5414
4b46fce2
JB
5415static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5416 u64 start, u64 len)
5417{
5418 struct btrfs_root *root = BTRFS_I(inode)->root;
5419 struct btrfs_trans_handle *trans;
5420 struct extent_map *em;
5421 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5422 struct btrfs_key ins;
5423 u64 alloc_hint;
5424 int ret;
5425
5426 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5427
5428 trans = btrfs_join_transaction(root, 0);
3612b495
TI
5429 if (IS_ERR(trans))
5430 return ERR_CAST(trans);
4b46fce2
JB
5431
5432 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5433
5434 alloc_hint = get_extent_allocation_hint(inode, start, len);
5435 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5436 alloc_hint, (u64)-1, &ins, 1);
5437 if (ret) {
5438 em = ERR_PTR(ret);
5439 goto out;
5440 }
5441
5442 em = alloc_extent_map(GFP_NOFS);
5443 if (!em) {
5444 em = ERR_PTR(-ENOMEM);
5445 goto out;
5446 }
5447
5448 em->start = start;
5449 em->orig_start = em->start;
5450 em->len = ins.offset;
5451
5452 em->block_start = ins.objectid;
5453 em->block_len = ins.offset;
5454 em->bdev = root->fs_info->fs_devices->latest_bdev;
5455 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5456
5457 while (1) {
5458 write_lock(&em_tree->lock);
5459 ret = add_extent_mapping(em_tree, em);
5460 write_unlock(&em_tree->lock);
5461 if (ret != -EEXIST)
5462 break;
5463 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5464 }
5465
5466 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5467 ins.offset, ins.offset, 0);
5468 if (ret) {
5469 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5470 em = ERR_PTR(ret);
5471 }
5472out:
5473 btrfs_end_transaction(trans, root);
5474 return em;
5475}
5476
46bfbb5c
CM
5477/*
5478 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5479 * block must be cow'd
5480 */
5481static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5482 struct inode *inode, u64 offset, u64 len)
5483{
5484 struct btrfs_path *path;
5485 int ret;
5486 struct extent_buffer *leaf;
5487 struct btrfs_root *root = BTRFS_I(inode)->root;
5488 struct btrfs_file_extent_item *fi;
5489 struct btrfs_key key;
5490 u64 disk_bytenr;
5491 u64 backref_offset;
5492 u64 extent_end;
5493 u64 num_bytes;
5494 int slot;
5495 int found_type;
5496
5497 path = btrfs_alloc_path();
5498 if (!path)
5499 return -ENOMEM;
5500
5501 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
5502 offset, 0);
5503 if (ret < 0)
5504 goto out;
5505
5506 slot = path->slots[0];
5507 if (ret == 1) {
5508 if (slot == 0) {
5509 /* can't find the item, must cow */
5510 ret = 0;
5511 goto out;
5512 }
5513 slot--;
5514 }
5515 ret = 0;
5516 leaf = path->nodes[0];
5517 btrfs_item_key_to_cpu(leaf, &key, slot);
5518 if (key.objectid != inode->i_ino ||
5519 key.type != BTRFS_EXTENT_DATA_KEY) {
5520 /* not our file or wrong item type, must cow */
5521 goto out;
5522 }
5523
5524 if (key.offset > offset) {
5525 /* Wrong offset, must cow */
5526 goto out;
5527 }
5528
5529 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5530 found_type = btrfs_file_extent_type(leaf, fi);
5531 if (found_type != BTRFS_FILE_EXTENT_REG &&
5532 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5533 /* not a regular extent, must cow */
5534 goto out;
5535 }
5536 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5537 backref_offset = btrfs_file_extent_offset(leaf, fi);
5538
5539 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5540 if (extent_end < offset + len) {
5541 /* extent doesn't include our full range, must cow */
5542 goto out;
5543 }
5544
5545 if (btrfs_extent_readonly(root, disk_bytenr))
5546 goto out;
5547
5548 /*
5549 * look for other files referencing this extent, if we
5550 * find any we must cow
5551 */
5552 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5553 key.offset - backref_offset, disk_bytenr))
5554 goto out;
5555
5556 /*
5557 * adjust disk_bytenr and num_bytes to cover just the bytes
5558 * in this extent we are about to write. If there
5559 * are any csums in that range we have to cow in order
5560 * to keep the csums correct
5561 */
5562 disk_bytenr += backref_offset;
5563 disk_bytenr += offset - key.offset;
5564 num_bytes = min(offset + len, extent_end) - offset;
5565 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5566 goto out;
5567 /*
5568 * all of the above have passed, it is safe to overwrite this extent
5569 * without cow
5570 */
5571 ret = 1;
5572out:
5573 btrfs_free_path(path);
5574 return ret;
5575}
5576
4b46fce2
JB
5577static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5578 struct buffer_head *bh_result, int create)
5579{
5580 struct extent_map *em;
5581 struct btrfs_root *root = BTRFS_I(inode)->root;
5582 u64 start = iblock << inode->i_blkbits;
5583 u64 len = bh_result->b_size;
46bfbb5c 5584 struct btrfs_trans_handle *trans;
4b46fce2
JB
5585
5586 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5587 if (IS_ERR(em))
5588 return PTR_ERR(em);
5589
5590 /*
5591 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5592 * io. INLINE is special, and we could probably kludge it in here, but
5593 * it's still buffered so for safety lets just fall back to the generic
5594 * buffered path.
5595 *
5596 * For COMPRESSED we _have_ to read the entire extent in so we can
5597 * decompress it, so there will be buffering required no matter what we
5598 * do, so go ahead and fallback to buffered.
5599 *
5600 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5601 * to buffered IO. Don't blame me, this is the price we pay for using
5602 * the generic code.
5603 */
5604 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5605 em->block_start == EXTENT_MAP_INLINE) {
5606 free_extent_map(em);
5607 return -ENOTBLK;
5608 }
5609
5610 /* Just a good old fashioned hole, return */
5611 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5612 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5613 free_extent_map(em);
5614 /* DIO will do one hole at a time, so just unlock a sector */
5615 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5616 start + root->sectorsize - 1, GFP_NOFS);
5617 return 0;
5618 }
5619
5620 /*
5621 * We don't allocate a new extent in the following cases
5622 *
5623 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5624 * existing extent.
5625 * 2) The extent is marked as PREALLOC. We're good to go here and can
5626 * just use the extent.
5627 *
5628 */
46bfbb5c
CM
5629 if (!create) {
5630 len = em->len - (start - em->start);
4b46fce2 5631 goto map;
46bfbb5c 5632 }
4b46fce2
JB
5633
5634 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5635 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5636 em->block_start != EXTENT_MAP_HOLE)) {
4b46fce2
JB
5637 int type;
5638 int ret;
46bfbb5c 5639 u64 block_start;
4b46fce2
JB
5640
5641 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5642 type = BTRFS_ORDERED_PREALLOC;
5643 else
5644 type = BTRFS_ORDERED_NOCOW;
46bfbb5c 5645 len = min(len, em->len - (start - em->start));
4b46fce2 5646 block_start = em->block_start + (start - em->start);
46bfbb5c
CM
5647
5648 /*
5649 * we're not going to log anything, but we do need
5650 * to make sure the current transaction stays open
5651 * while we look for nocow cross refs
5652 */
5653 trans = btrfs_join_transaction(root, 0);
3612b495 5654 if (IS_ERR(trans))
46bfbb5c
CM
5655 goto must_cow;
5656
5657 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5658 ret = btrfs_add_ordered_extent_dio(inode, start,
5659 block_start, len, len, type);
5660 btrfs_end_transaction(trans, root);
5661 if (ret) {
5662 free_extent_map(em);
5663 return ret;
5664 }
5665 goto unlock;
4b46fce2 5666 }
46bfbb5c 5667 btrfs_end_transaction(trans, root);
4b46fce2 5668 }
46bfbb5c
CM
5669must_cow:
5670 /*
5671 * this will cow the extent, reset the len in case we changed
5672 * it above
5673 */
5674 len = bh_result->b_size;
5675 free_extent_map(em);
5676 em = btrfs_new_extent_direct(inode, start, len);
5677 if (IS_ERR(em))
5678 return PTR_ERR(em);
5679 len = min(len, em->len - (start - em->start));
5680unlock:
4845e44f
CM
5681 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5682 EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5683 0, NULL, GFP_NOFS);
4b46fce2
JB
5684map:
5685 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5686 inode->i_blkbits;
46bfbb5c 5687 bh_result->b_size = len;
4b46fce2
JB
5688 bh_result->b_bdev = em->bdev;
5689 set_buffer_mapped(bh_result);
5690 if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5691 set_buffer_new(bh_result);
5692
5693 free_extent_map(em);
5694
5695 return 0;
5696}
5697
5698struct btrfs_dio_private {
5699 struct inode *inode;
5700 u64 logical_offset;
5701 u64 disk_bytenr;
5702 u64 bytes;
5703 u32 *csums;
5704 void *private;
e65e1535
MX
5705
5706 /* number of bios pending for this dio */
5707 atomic_t pending_bios;
5708
5709 /* IO errors */
5710 int errors;
5711
5712 struct bio *orig_bio;
4b46fce2
JB
5713};
5714
5715static void btrfs_endio_direct_read(struct bio *bio, int err)
5716{
e65e1535 5717 struct btrfs_dio_private *dip = bio->bi_private;
4b46fce2
JB
5718 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5719 struct bio_vec *bvec = bio->bi_io_vec;
4b46fce2
JB
5720 struct inode *inode = dip->inode;
5721 struct btrfs_root *root = BTRFS_I(inode)->root;
5722 u64 start;
5723 u32 *private = dip->csums;
5724
5725 start = dip->logical_offset;
5726 do {
5727 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5728 struct page *page = bvec->bv_page;
5729 char *kaddr;
5730 u32 csum = ~(u32)0;
5731 unsigned long flags;
5732
5733 local_irq_save(flags);
5734 kaddr = kmap_atomic(page, KM_IRQ0);
5735 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5736 csum, bvec->bv_len);
5737 btrfs_csum_final(csum, (char *)&csum);
5738 kunmap_atomic(kaddr, KM_IRQ0);
5739 local_irq_restore(flags);
5740
5741 flush_dcache_page(bvec->bv_page);
5742 if (csum != *private) {
5743 printk(KERN_ERR "btrfs csum failed ino %lu off"
5744 " %llu csum %u private %u\n",
5745 inode->i_ino, (unsigned long long)start,
5746 csum, *private);
5747 err = -EIO;
5748 }
5749 }
5750
5751 start += bvec->bv_len;
5752 private++;
5753 bvec++;
5754 } while (bvec <= bvec_end);
5755
5756 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5757 dip->logical_offset + dip->bytes - 1, GFP_NOFS);
5758 bio->bi_private = dip->private;
5759
5760 kfree(dip->csums);
5761 kfree(dip);
c0da7aa1
JB
5762
5763 /* If we had a csum failure make sure to clear the uptodate flag */
5764 if (err)
5765 clear_bit(BIO_UPTODATE, &bio->bi_flags);
4b46fce2
JB
5766 dio_end_io(bio, err);
5767}
5768
5769static void btrfs_endio_direct_write(struct bio *bio, int err)
5770{
5771 struct btrfs_dio_private *dip = bio->bi_private;
5772 struct inode *inode = dip->inode;
5773 struct btrfs_root *root = BTRFS_I(inode)->root;
5774 struct btrfs_trans_handle *trans;
5775 struct btrfs_ordered_extent *ordered = NULL;
5776 struct extent_state *cached_state = NULL;
163cf09c
CM
5777 u64 ordered_offset = dip->logical_offset;
5778 u64 ordered_bytes = dip->bytes;
4b46fce2
JB
5779 int ret;
5780
5781 if (err)
5782 goto out_done;
163cf09c
CM
5783again:
5784 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5785 &ordered_offset,
5786 ordered_bytes);
4b46fce2 5787 if (!ret)
163cf09c 5788 goto out_test;
4b46fce2
JB
5789
5790 BUG_ON(!ordered);
5791
5792 trans = btrfs_join_transaction(root, 1);
3612b495 5793 if (IS_ERR(trans)) {
4b46fce2
JB
5794 err = -ENOMEM;
5795 goto out;
5796 }
5797 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5798
5799 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) {
5800 ret = btrfs_ordered_update_i_size(inode, 0, ordered);
5801 if (!ret)
5802 ret = btrfs_update_inode(trans, root, inode);
5803 err = ret;
5804 goto out;
5805 }
5806
5807 lock_extent_bits(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5808 ordered->file_offset + ordered->len - 1, 0,
5809 &cached_state, GFP_NOFS);
5810
5811 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags)) {
5812 ret = btrfs_mark_extent_written(trans, inode,
5813 ordered->file_offset,
5814 ordered->file_offset +
5815 ordered->len);
5816 if (ret) {
5817 err = ret;
5818 goto out_unlock;
5819 }
5820 } else {
5821 ret = insert_reserved_file_extent(trans, inode,
5822 ordered->file_offset,
5823 ordered->start,
5824 ordered->disk_len,
5825 ordered->len,
5826 ordered->len,
5827 0, 0, 0,
5828 BTRFS_FILE_EXTENT_REG);
5829 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
5830 ordered->file_offset, ordered->len);
5831 if (ret) {
5832 err = ret;
5833 WARN_ON(1);
5834 goto out_unlock;
5835 }
5836 }
5837
5838 add_pending_csums(trans, inode, ordered->file_offset, &ordered->list);
5839 btrfs_ordered_update_i_size(inode, 0, ordered);
5840 btrfs_update_inode(trans, root, inode);
5841out_unlock:
5842 unlock_extent_cached(&BTRFS_I(inode)->io_tree, ordered->file_offset,
5843 ordered->file_offset + ordered->len - 1,
5844 &cached_state, GFP_NOFS);
5845out:
5846 btrfs_delalloc_release_metadata(inode, ordered->len);
5847 btrfs_end_transaction(trans, root);
163cf09c 5848 ordered_offset = ordered->file_offset + ordered->len;
4b46fce2
JB
5849 btrfs_put_ordered_extent(ordered);
5850 btrfs_put_ordered_extent(ordered);
163cf09c
CM
5851
5852out_test:
5853 /*
5854 * our bio might span multiple ordered extents. If we haven't
5855 * completed the accounting for the whole dio, go back and try again
5856 */
5857 if (ordered_offset < dip->logical_offset + dip->bytes) {
5858 ordered_bytes = dip->logical_offset + dip->bytes -
5859 ordered_offset;
5860 goto again;
5861 }
4b46fce2
JB
5862out_done:
5863 bio->bi_private = dip->private;
5864
5865 kfree(dip->csums);
5866 kfree(dip);
c0da7aa1
JB
5867
5868 /* If we had an error make sure to clear the uptodate flag */
5869 if (err)
5870 clear_bit(BIO_UPTODATE, &bio->bi_flags);
4b46fce2
JB
5871 dio_end_io(bio, err);
5872}
5873
eaf25d93
CM
5874static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5875 struct bio *bio, int mirror_num,
5876 unsigned long bio_flags, u64 offset)
5877{
5878 int ret;
5879 struct btrfs_root *root = BTRFS_I(inode)->root;
5880 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5881 BUG_ON(ret);
5882 return 0;
5883}
5884
e65e1535
MX
5885static void btrfs_end_dio_bio(struct bio *bio, int err)
5886{
5887 struct btrfs_dio_private *dip = bio->bi_private;
5888
5889 if (err) {
5890 printk(KERN_ERR "btrfs direct IO failed ino %lu rw %lu "
3dd1462e
JB
5891 "sector %#Lx len %u err no %d\n",
5892 dip->inode->i_ino, bio->bi_rw,
5893 (unsigned long long)bio->bi_sector, bio->bi_size, err);
e65e1535
MX
5894 dip->errors = 1;
5895
5896 /*
5897 * before atomic variable goto zero, we must make sure
5898 * dip->errors is perceived to be set.
5899 */
5900 smp_mb__before_atomic_dec();
5901 }
5902
5903 /* if there are more bios still pending for this dio, just exit */
5904 if (!atomic_dec_and_test(&dip->pending_bios))
5905 goto out;
5906
5907 if (dip->errors)
5908 bio_io_error(dip->orig_bio);
5909 else {
5910 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
5911 bio_endio(dip->orig_bio, 0);
5912 }
5913out:
5914 bio_put(bio);
5915}
5916
5917static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
5918 u64 first_sector, gfp_t gfp_flags)
5919{
5920 int nr_vecs = bio_get_nr_vecs(bdev);
5921 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
5922}
5923
5924static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
5925 int rw, u64 file_offset, int skip_sum,
5926 u32 *csums)
5927{
5928 int write = rw & REQ_WRITE;
5929 struct btrfs_root *root = BTRFS_I(inode)->root;
5930 int ret;
5931
5932 bio_get(bio);
5933 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
5934 if (ret)
5935 goto err;
5936
5937 if (write && !skip_sum) {
5938 ret = btrfs_wq_submit_bio(root->fs_info,
5939 inode, rw, bio, 0, 0,
5940 file_offset,
5941 __btrfs_submit_bio_start_direct_io,
5942 __btrfs_submit_bio_done);
5943 goto err;
5944 } else if (!skip_sum)
5945 btrfs_lookup_bio_sums_dio(root, inode, bio,
5946 file_offset, csums);
5947
5948 ret = btrfs_map_bio(root, rw, bio, 0, 1);
5949err:
5950 bio_put(bio);
5951 return ret;
5952}
5953
5954static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
5955 int skip_sum)
5956{
5957 struct inode *inode = dip->inode;
5958 struct btrfs_root *root = BTRFS_I(inode)->root;
5959 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
5960 struct bio *bio;
5961 struct bio *orig_bio = dip->orig_bio;
5962 struct bio_vec *bvec = orig_bio->bi_io_vec;
5963 u64 start_sector = orig_bio->bi_sector;
5964 u64 file_offset = dip->logical_offset;
5965 u64 submit_len = 0;
5966 u64 map_length;
5967 int nr_pages = 0;
5968 u32 *csums = dip->csums;
5969 int ret = 0;
98bc3149 5970 int write = rw & REQ_WRITE;
e65e1535
MX
5971
5972 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
5973 if (!bio)
5974 return -ENOMEM;
5975 bio->bi_private = dip;
5976 bio->bi_end_io = btrfs_end_dio_bio;
5977 atomic_inc(&dip->pending_bios);
5978
5979 map_length = orig_bio->bi_size;
5980 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
5981 &map_length, NULL, 0);
5982 if (ret) {
5983 bio_put(bio);
5984 return -EIO;
5985 }
5986
5987 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
5988 if (unlikely(map_length < submit_len + bvec->bv_len ||
5989 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
5990 bvec->bv_offset) < bvec->bv_len)) {
5991 /*
5992 * inc the count before we submit the bio so
5993 * we know the end IO handler won't happen before
5994 * we inc the count. Otherwise, the dip might get freed
5995 * before we're done setting it up
5996 */
5997 atomic_inc(&dip->pending_bios);
5998 ret = __btrfs_submit_dio_bio(bio, inode, rw,
5999 file_offset, skip_sum,
6000 csums);
6001 if (ret) {
6002 bio_put(bio);
6003 atomic_dec(&dip->pending_bios);
6004 goto out_err;
6005 }
6006
98bc3149
JB
6007 /* Write's use the ordered csums */
6008 if (!write && !skip_sum)
e65e1535
MX
6009 csums = csums + nr_pages;
6010 start_sector += submit_len >> 9;
6011 file_offset += submit_len;
6012
6013 submit_len = 0;
6014 nr_pages = 0;
6015
6016 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6017 start_sector, GFP_NOFS);
6018 if (!bio)
6019 goto out_err;
6020 bio->bi_private = dip;
6021 bio->bi_end_io = btrfs_end_dio_bio;
6022
6023 map_length = orig_bio->bi_size;
6024 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6025 &map_length, NULL, 0);
6026 if (ret) {
6027 bio_put(bio);
6028 goto out_err;
6029 }
6030 } else {
6031 submit_len += bvec->bv_len;
6032 nr_pages ++;
6033 bvec++;
6034 }
6035 }
6036
6037 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6038 csums);
6039 if (!ret)
6040 return 0;
6041
6042 bio_put(bio);
6043out_err:
6044 dip->errors = 1;
6045 /*
6046 * before atomic variable goto zero, we must
6047 * make sure dip->errors is perceived to be set.
6048 */
6049 smp_mb__before_atomic_dec();
6050 if (atomic_dec_and_test(&dip->pending_bios))
6051 bio_io_error(dip->orig_bio);
6052
6053 /* bio_end_io() will handle error, so we needn't return it */
6054 return 0;
6055}
6056
4b46fce2
JB
6057static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6058 loff_t file_offset)
6059{
6060 struct btrfs_root *root = BTRFS_I(inode)->root;
6061 struct btrfs_dio_private *dip;
6062 struct bio_vec *bvec = bio->bi_io_vec;
4b46fce2 6063 int skip_sum;
7b6d91da 6064 int write = rw & REQ_WRITE;
4b46fce2
JB
6065 int ret = 0;
6066
6067 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6068
6069 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6070 if (!dip) {
6071 ret = -ENOMEM;
6072 goto free_ordered;
6073 }
6074 dip->csums = NULL;
6075
98bc3149
JB
6076 /* Write's use the ordered csum stuff, so we don't need dip->csums */
6077 if (!write && !skip_sum) {
4b46fce2
JB
6078 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6079 if (!dip->csums) {
b4966b77 6080 kfree(dip);
4b46fce2
JB
6081 ret = -ENOMEM;
6082 goto free_ordered;
6083 }
6084 }
6085
6086 dip->private = bio->bi_private;
6087 dip->inode = inode;
6088 dip->logical_offset = file_offset;
6089
4b46fce2
JB
6090 dip->bytes = 0;
6091 do {
6092 dip->bytes += bvec->bv_len;
6093 bvec++;
6094 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6095
46bfbb5c 6096 dip->disk_bytenr = (u64)bio->bi_sector << 9;
4b46fce2 6097 bio->bi_private = dip;
e65e1535
MX
6098 dip->errors = 0;
6099 dip->orig_bio = bio;
6100 atomic_set(&dip->pending_bios, 0);
4b46fce2
JB
6101
6102 if (write)
6103 bio->bi_end_io = btrfs_endio_direct_write;
6104 else
6105 bio->bi_end_io = btrfs_endio_direct_read;
6106
e65e1535
MX
6107 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6108 if (!ret)
eaf25d93 6109 return;
4b46fce2
JB
6110free_ordered:
6111 /*
6112 * If this is a write, we need to clean up the reserved space and kill
6113 * the ordered extent.
6114 */
6115 if (write) {
6116 struct btrfs_ordered_extent *ordered;
955256f2 6117 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
4b46fce2
JB
6118 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6119 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6120 btrfs_free_reserved_extent(root, ordered->start,
6121 ordered->disk_len);
6122 btrfs_put_ordered_extent(ordered);
6123 btrfs_put_ordered_extent(ordered);
6124 }
6125 bio_endio(bio, ret);
6126}
6127
5a5f79b5
CM
6128static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6129 const struct iovec *iov, loff_t offset,
6130 unsigned long nr_segs)
6131{
6132 int seg;
6133 size_t size;
6134 unsigned long addr;
6135 unsigned blocksize_mask = root->sectorsize - 1;
6136 ssize_t retval = -EINVAL;
6137 loff_t end = offset;
6138
6139 if (offset & blocksize_mask)
6140 goto out;
6141
6142 /* Check the memory alignment. Blocks cannot straddle pages */
6143 for (seg = 0; seg < nr_segs; seg++) {
6144 addr = (unsigned long)iov[seg].iov_base;
6145 size = iov[seg].iov_len;
6146 end += size;
6147 if ((addr & blocksize_mask) || (size & blocksize_mask))
6148 goto out;
6149 }
6150 retval = 0;
6151out:
6152 return retval;
6153}
16432985
CM
6154static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6155 const struct iovec *iov, loff_t offset,
6156 unsigned long nr_segs)
6157{
4b46fce2
JB
6158 struct file *file = iocb->ki_filp;
6159 struct inode *inode = file->f_mapping->host;
6160 struct btrfs_ordered_extent *ordered;
4845e44f 6161 struct extent_state *cached_state = NULL;
4b46fce2
JB
6162 u64 lockstart, lockend;
6163 ssize_t ret;
4845e44f
CM
6164 int writing = rw & WRITE;
6165 int write_bits = 0;
3f7c579c 6166 size_t count = iov_length(iov, nr_segs);
4b46fce2 6167
5a5f79b5
CM
6168 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6169 offset, nr_segs)) {
6170 return 0;
6171 }
6172
4b46fce2 6173 lockstart = offset;
3f7c579c
CM
6174 lockend = offset + count - 1;
6175
6176 if (writing) {
6177 ret = btrfs_delalloc_reserve_space(inode, count);
6178 if (ret)
6179 goto out;
6180 }
4845e44f 6181
4b46fce2 6182 while (1) {
4845e44f
CM
6183 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6184 0, &cached_state, GFP_NOFS);
4b46fce2
JB
6185 /*
6186 * We're concerned with the entire range that we're going to be
6187 * doing DIO to, so we need to make sure theres no ordered
6188 * extents in this range.
6189 */
6190 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6191 lockend - lockstart + 1);
6192 if (!ordered)
6193 break;
4845e44f
CM
6194 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6195 &cached_state, GFP_NOFS);
4b46fce2
JB
6196 btrfs_start_ordered_extent(inode, ordered, 1);
6197 btrfs_put_ordered_extent(ordered);
6198 cond_resched();
6199 }
6200
4845e44f
CM
6201 /*
6202 * we don't use btrfs_set_extent_delalloc because we don't want
6203 * the dirty or uptodate bits
6204 */
6205 if (writing) {
6206 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6207 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6208 EXTENT_DELALLOC, 0, NULL, &cached_state,
6209 GFP_NOFS);
6210 if (ret) {
6211 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6212 lockend, EXTENT_LOCKED | write_bits,
6213 1, 0, &cached_state, GFP_NOFS);
6214 goto out;
6215 }
6216 }
6217
6218 free_extent_state(cached_state);
6219 cached_state = NULL;
6220
5a5f79b5
CM
6221 ret = __blockdev_direct_IO(rw, iocb, inode,
6222 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6223 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6224 btrfs_submit_direct, 0);
4b46fce2
JB
6225
6226 if (ret < 0 && ret != -EIOCBQUEUED) {
4845e44f
CM
6227 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6228 offset + iov_length(iov, nr_segs) - 1,
6229 EXTENT_LOCKED | write_bits, 1, 0,
6230 &cached_state, GFP_NOFS);
4b46fce2
JB
6231 } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6232 /*
6233 * We're falling back to buffered, unlock the section we didn't
6234 * do IO on.
6235 */
4845e44f
CM
6236 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6237 offset + iov_length(iov, nr_segs) - 1,
6238 EXTENT_LOCKED | write_bits, 1, 0,
6239 &cached_state, GFP_NOFS);
4b46fce2 6240 }
4845e44f
CM
6241out:
6242 free_extent_state(cached_state);
4b46fce2 6243 return ret;
16432985
CM
6244}
6245
1506fcc8
YS
6246static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6247 __u64 start, __u64 len)
6248{
ec29ed5b 6249 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
1506fcc8
YS
6250}
6251
a52d9a80 6252int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 6253{
d1310b2e
CM
6254 struct extent_io_tree *tree;
6255 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 6256 return extent_read_full_page(tree, page, btrfs_get_extent);
9ebefb18 6257}
1832a6d5 6258
a52d9a80 6259static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 6260{
d1310b2e 6261 struct extent_io_tree *tree;
b888db2b
CM
6262
6263
6264 if (current->flags & PF_MEMALLOC) {
6265 redirty_page_for_writepage(wbc, page);
6266 unlock_page(page);
6267 return 0;
6268 }
d1310b2e 6269 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 6270 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
9ebefb18
CM
6271}
6272
f421950f
CM
6273int btrfs_writepages(struct address_space *mapping,
6274 struct writeback_control *wbc)
b293f02e 6275{
d1310b2e 6276 struct extent_io_tree *tree;
771ed689 6277
d1310b2e 6278 tree = &BTRFS_I(mapping->host)->io_tree;
b293f02e
CM
6279 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6280}
6281
3ab2fb5a
CM
6282static int
6283btrfs_readpages(struct file *file, struct address_space *mapping,
6284 struct list_head *pages, unsigned nr_pages)
6285{
d1310b2e
CM
6286 struct extent_io_tree *tree;
6287 tree = &BTRFS_I(mapping->host)->io_tree;
3ab2fb5a
CM
6288 return extent_readpages(tree, mapping, pages, nr_pages,
6289 btrfs_get_extent);
6290}
e6dcd2dc 6291static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 6292{
d1310b2e
CM
6293 struct extent_io_tree *tree;
6294 struct extent_map_tree *map;
a52d9a80 6295 int ret;
8c2383c3 6296
d1310b2e
CM
6297 tree = &BTRFS_I(page->mapping->host)->io_tree;
6298 map = &BTRFS_I(page->mapping->host)->extent_tree;
70dec807 6299 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
a52d9a80
CM
6300 if (ret == 1) {
6301 ClearPagePrivate(page);
6302 set_page_private(page, 0);
6303 page_cache_release(page);
39279cc3 6304 }
a52d9a80 6305 return ret;
39279cc3
CM
6306}
6307
e6dcd2dc
CM
6308static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6309{
98509cfc
CM
6310 if (PageWriteback(page) || PageDirty(page))
6311 return 0;
b335b003 6312 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
e6dcd2dc
CM
6313}
6314
a52d9a80 6315static void btrfs_invalidatepage(struct page *page, unsigned long offset)
39279cc3 6316{
d1310b2e 6317 struct extent_io_tree *tree;
e6dcd2dc 6318 struct btrfs_ordered_extent *ordered;
2ac55d41 6319 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
6320 u64 page_start = page_offset(page);
6321 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
39279cc3 6322
8b62b72b
CM
6323
6324 /*
6325 * we have the page locked, so new writeback can't start,
6326 * and the dirty bit won't be cleared while we are here.
6327 *
6328 * Wait for IO on this page so that we can safely clear
6329 * the PagePrivate2 bit and do ordered accounting
6330 */
e6dcd2dc 6331 wait_on_page_writeback(page);
8b62b72b 6332
d1310b2e 6333 tree = &BTRFS_I(page->mapping->host)->io_tree;
e6dcd2dc
CM
6334 if (offset) {
6335 btrfs_releasepage(page, GFP_NOFS);
6336 return;
6337 }
2ac55d41
JB
6338 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6339 GFP_NOFS);
e6dcd2dc
CM
6340 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
6341 page_offset(page));
6342 if (ordered) {
eb84ae03
CM
6343 /*
6344 * IO on this page will never be started, so we need
6345 * to account for any ordered extents now
6346 */
e6dcd2dc
CM
6347 clear_extent_bit(tree, page_start, page_end,
6348 EXTENT_DIRTY | EXTENT_DELALLOC |
32c00aff 6349 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
2ac55d41 6350 &cached_state, GFP_NOFS);
8b62b72b
CM
6351 /*
6352 * whoever cleared the private bit is responsible
6353 * for the finish_ordered_io
6354 */
6355 if (TestClearPagePrivate2(page)) {
6356 btrfs_finish_ordered_io(page->mapping->host,
6357 page_start, page_end);
6358 }
e6dcd2dc 6359 btrfs_put_ordered_extent(ordered);
2ac55d41
JB
6360 cached_state = NULL;
6361 lock_extent_bits(tree, page_start, page_end, 0, &cached_state,
6362 GFP_NOFS);
e6dcd2dc
CM
6363 }
6364 clear_extent_bit(tree, page_start, page_end,
32c00aff 6365 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
2ac55d41 6366 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
e6dcd2dc
CM
6367 __btrfs_releasepage(page, GFP_NOFS);
6368
4a096752 6369 ClearPageChecked(page);
9ad6b7bc 6370 if (PagePrivate(page)) {
9ad6b7bc
CM
6371 ClearPagePrivate(page);
6372 set_page_private(page, 0);
6373 page_cache_release(page);
6374 }
39279cc3
CM
6375}
6376
9ebefb18
CM
6377/*
6378 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6379 * called from a page fault handler when a page is first dirtied. Hence we must
6380 * be careful to check for EOF conditions here. We set the page up correctly
6381 * for a written page which means we get ENOSPC checking when writing into
6382 * holes and correct delalloc and unwritten extent mapping on filesystems that
6383 * support these features.
6384 *
6385 * We are not allowed to take the i_mutex here so we have to play games to
6386 * protect against truncate races as the page could now be beyond EOF. Because
6387 * vmtruncate() writes the inode size before removing pages, once we have the
6388 * page lock we can determine safely if the page is beyond EOF. If it is not
6389 * beyond EOF, then the page is guaranteed safe against truncation until we
6390 * unlock the page.
6391 */
c2ec175c 6392int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
9ebefb18 6393{
c2ec175c 6394 struct page *page = vmf->page;
6da6abae 6395 struct inode *inode = fdentry(vma->vm_file)->d_inode;
1832a6d5 6396 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
6397 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6398 struct btrfs_ordered_extent *ordered;
2ac55d41 6399 struct extent_state *cached_state = NULL;
e6dcd2dc
CM
6400 char *kaddr;
6401 unsigned long zero_start;
9ebefb18 6402 loff_t size;
1832a6d5 6403 int ret;
a52d9a80 6404 u64 page_start;
e6dcd2dc 6405 u64 page_end;
9ebefb18 6406
0ca1f7ce 6407 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
56a76f82
NP
6408 if (ret) {
6409 if (ret == -ENOMEM)
6410 ret = VM_FAULT_OOM;
6411 else /* -ENOSPC, -EIO, etc */
6412 ret = VM_FAULT_SIGBUS;
1832a6d5 6413 goto out;
56a76f82 6414 }
1832a6d5 6415
56a76f82 6416 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 6417again:
9ebefb18 6418 lock_page(page);
9ebefb18 6419 size = i_size_read(inode);
e6dcd2dc
CM
6420 page_start = page_offset(page);
6421 page_end = page_start + PAGE_CACHE_SIZE - 1;
a52d9a80 6422
9ebefb18 6423 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 6424 (page_start >= size)) {
9ebefb18
CM
6425 /* page got truncated out from underneath us */
6426 goto out_unlock;
6427 }
e6dcd2dc
CM
6428 wait_on_page_writeback(page);
6429
2ac55d41
JB
6430 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state,
6431 GFP_NOFS);
e6dcd2dc
CM
6432 set_page_extent_mapped(page);
6433
eb84ae03
CM
6434 /*
6435 * we can't set the delalloc bits if there are pending ordered
6436 * extents. Drop our locks and wait for them to finish
6437 */
e6dcd2dc
CM
6438 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6439 if (ordered) {
2ac55d41
JB
6440 unlock_extent_cached(io_tree, page_start, page_end,
6441 &cached_state, GFP_NOFS);
e6dcd2dc 6442 unlock_page(page);
eb84ae03 6443 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
6444 btrfs_put_ordered_extent(ordered);
6445 goto again;
6446 }
6447
fbf19087
JB
6448 /*
6449 * XXX - page_mkwrite gets called every time the page is dirtied, even
6450 * if it was already dirty, so for space accounting reasons we need to
6451 * clear any delalloc bits for the range we are fixing to save. There
6452 * is probably a better way to do this, but for now keep consistent with
6453 * prepare_pages in the normal write path.
6454 */
2ac55d41 6455 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
32c00aff 6456 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
2ac55d41 6457 0, 0, &cached_state, GFP_NOFS);
fbf19087 6458
2ac55d41
JB
6459 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6460 &cached_state);
9ed74f2d 6461 if (ret) {
2ac55d41
JB
6462 unlock_extent_cached(io_tree, page_start, page_end,
6463 &cached_state, GFP_NOFS);
9ed74f2d
JB
6464 ret = VM_FAULT_SIGBUS;
6465 goto out_unlock;
6466 }
e6dcd2dc 6467 ret = 0;
9ebefb18
CM
6468
6469 /* page is wholly or partially inside EOF */
a52d9a80 6470 if (page_start + PAGE_CACHE_SIZE > size)
e6dcd2dc 6471 zero_start = size & ~PAGE_CACHE_MASK;
9ebefb18 6472 else
e6dcd2dc 6473 zero_start = PAGE_CACHE_SIZE;
9ebefb18 6474
e6dcd2dc
CM
6475 if (zero_start != PAGE_CACHE_SIZE) {
6476 kaddr = kmap(page);
6477 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6478 flush_dcache_page(page);
6479 kunmap(page);
6480 }
247e743c 6481 ClearPageChecked(page);
e6dcd2dc 6482 set_page_dirty(page);
50a9b214 6483 SetPageUptodate(page);
5a3f23d5 6484
257c62e1
CM
6485 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6486 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6487
2ac55d41 6488 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9ebefb18
CM
6489
6490out_unlock:
50a9b214
CM
6491 if (!ret)
6492 return VM_FAULT_LOCKED;
9ebefb18 6493 unlock_page(page);
0ca1f7ce 6494 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
1832a6d5 6495out:
9ebefb18
CM
6496 return ret;
6497}
6498
a41ad394 6499static int btrfs_truncate(struct inode *inode)
39279cc3
CM
6500{
6501 struct btrfs_root *root = BTRFS_I(inode)->root;
6502 int ret;
3893e33b 6503 int err = 0;
39279cc3 6504 struct btrfs_trans_handle *trans;
d3c2fdcf 6505 unsigned long nr;
dbe674a9 6506 u64 mask = root->sectorsize - 1;
39279cc3 6507
5d5e103a
JB
6508 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6509 if (ret)
a41ad394 6510 return ret;
8082510e 6511
4a096752 6512 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
8082510e 6513 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
39279cc3 6514
f0cd846e
JB
6515 trans = btrfs_start_transaction(root, 5);
6516 if (IS_ERR(trans))
6517 return PTR_ERR(trans);
6518
6519 btrfs_set_trans_block_group(trans, inode);
6520
6521 ret = btrfs_orphan_add(trans, inode);
6522 if (ret) {
6523 btrfs_end_transaction(trans, root);
6524 return ret;
6525 }
6526
6527 nr = trans->blocks_used;
6528 btrfs_end_transaction(trans, root);
6529 btrfs_btree_balance_dirty(root, nr);
6530
6531 /* Now start a transaction for the truncate */
d68fc57b 6532 trans = btrfs_start_transaction(root, 0);
3893e33b
JB
6533 if (IS_ERR(trans))
6534 return PTR_ERR(trans);
8082510e 6535 btrfs_set_trans_block_group(trans, inode);
d68fc57b 6536 trans->block_rsv = root->orphan_block_rsv;
5a3f23d5
CM
6537
6538 /*
6539 * setattr is responsible for setting the ordered_data_close flag,
6540 * but that is only tested during the last file release. That
6541 * could happen well after the next commit, leaving a great big
6542 * window where new writes may get lost if someone chooses to write
6543 * to this file after truncating to zero
6544 *
6545 * The inode doesn't have any dirty data here, and so if we commit
6546 * this is a noop. If someone immediately starts writing to the inode
6547 * it is very likely we'll catch some of their writes in this
6548 * transaction, and the commit will find this file on the ordered
6549 * data list with good things to send down.
6550 *
6551 * This is a best effort solution, there is still a window where
6552 * using truncate to replace the contents of the file will
6553 * end up with a zero length file after a crash.
6554 */
6555 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
6556 btrfs_add_ordered_operation(trans, root, inode);
6557
8082510e 6558 while (1) {
d68fc57b
YZ
6559 if (!trans) {
6560 trans = btrfs_start_transaction(root, 0);
3893e33b
JB
6561 if (IS_ERR(trans))
6562 return PTR_ERR(trans);
d68fc57b
YZ
6563 btrfs_set_trans_block_group(trans, inode);
6564 trans->block_rsv = root->orphan_block_rsv;
6565 }
6566
6567 ret = btrfs_block_rsv_check(trans, root,
6568 root->orphan_block_rsv, 0, 5);
3893e33b 6569 if (ret == -EAGAIN) {
d68fc57b 6570 ret = btrfs_commit_transaction(trans, root);
3893e33b
JB
6571 if (ret)
6572 return ret;
d68fc57b
YZ
6573 trans = NULL;
6574 continue;
3893e33b
JB
6575 } else if (ret) {
6576 err = ret;
6577 break;
d68fc57b
YZ
6578 }
6579
8082510e
YZ
6580 ret = btrfs_truncate_inode_items(trans, root, inode,
6581 inode->i_size,
6582 BTRFS_EXTENT_DATA_KEY);
3893e33b
JB
6583 if (ret != -EAGAIN) {
6584 err = ret;
8082510e 6585 break;
3893e33b 6586 }
39279cc3 6587
8082510e 6588 ret = btrfs_update_inode(trans, root, inode);
3893e33b
JB
6589 if (ret) {
6590 err = ret;
6591 break;
6592 }
5f39d397 6593
8082510e
YZ
6594 nr = trans->blocks_used;
6595 btrfs_end_transaction(trans, root);
d68fc57b 6596 trans = NULL;
8082510e 6597 btrfs_btree_balance_dirty(root, nr);
8082510e
YZ
6598 }
6599
6600 if (ret == 0 && inode->i_nlink > 0) {
6601 ret = btrfs_orphan_del(trans, inode);
3893e33b
JB
6602 if (ret)
6603 err = ret;
ded5db9d
JB
6604 } else if (ret && inode->i_nlink > 0) {
6605 /*
6606 * Failed to do the truncate, remove us from the in memory
6607 * orphan list.
6608 */
6609 ret = btrfs_orphan_del(NULL, inode);
8082510e
YZ
6610 }
6611
6612 ret = btrfs_update_inode(trans, root, inode);
3893e33b
JB
6613 if (ret && !err)
6614 err = ret;
7b128766 6615
7b128766 6616 nr = trans->blocks_used;
89ce8a63 6617 ret = btrfs_end_transaction_throttle(trans, root);
3893e33b
JB
6618 if (ret && !err)
6619 err = ret;
d3c2fdcf 6620 btrfs_btree_balance_dirty(root, nr);
a41ad394 6621
3893e33b 6622 return err;
39279cc3
CM
6623}
6624
d352ac68
CM
6625/*
6626 * create a new subvolume directory/inode (helper for the ioctl).
6627 */
d2fb3437 6628int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
76dda93c 6629 struct btrfs_root *new_root,
d2fb3437 6630 u64 new_dirid, u64 alloc_hint)
39279cc3 6631{
39279cc3 6632 struct inode *inode;
76dda93c 6633 int err;
00e4e6b3 6634 u64 index = 0;
39279cc3 6635
aec7477b 6636 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
d2fb3437 6637 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
54aa1f4d 6638 if (IS_ERR(inode))
f46b5a66 6639 return PTR_ERR(inode);
39279cc3
CM
6640 inode->i_op = &btrfs_dir_inode_operations;
6641 inode->i_fop = &btrfs_dir_file_operations;
6642
39279cc3 6643 inode->i_nlink = 1;
dbe674a9 6644 btrfs_i_size_write(inode, 0);
3b96362c 6645
76dda93c
YZ
6646 err = btrfs_update_inode(trans, new_root, inode);
6647 BUG_ON(err);
cb8e7090 6648
76dda93c 6649 iput(inode);
cb8e7090 6650 return 0;
39279cc3
CM
6651}
6652
d352ac68
CM
6653/* helper function for file defrag and space balancing. This
6654 * forces readahead on a given range of bytes in an inode
6655 */
edbd8d4e 6656unsigned long btrfs_force_ra(struct address_space *mapping,
86479a04
CM
6657 struct file_ra_state *ra, struct file *file,
6658 pgoff_t offset, pgoff_t last_index)
6659{
8e7bf94f 6660 pgoff_t req_size = last_index - offset + 1;
86479a04 6661
86479a04
CM
6662 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
6663 return offset + req_size;
86479a04
CM
6664}
6665
39279cc3
CM
6666struct inode *btrfs_alloc_inode(struct super_block *sb)
6667{
6668 struct btrfs_inode *ei;
2ead6ae7 6669 struct inode *inode;
39279cc3
CM
6670
6671 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6672 if (!ei)
6673 return NULL;
2ead6ae7
YZ
6674
6675 ei->root = NULL;
6676 ei->space_info = NULL;
6677 ei->generation = 0;
6678 ei->sequence = 0;
15ee9bc7 6679 ei->last_trans = 0;
257c62e1 6680 ei->last_sub_trans = 0;
e02119d5 6681 ei->logged_trans = 0;
2ead6ae7
YZ
6682 ei->delalloc_bytes = 0;
6683 ei->reserved_bytes = 0;
6684 ei->disk_i_size = 0;
6685 ei->flags = 0;
6686 ei->index_cnt = (u64)-1;
6687 ei->last_unlink_trans = 0;
6688
0ca1f7ce 6689 atomic_set(&ei->outstanding_extents, 0);
57a45ced 6690 atomic_set(&ei->reserved_extents, 0);
2ead6ae7
YZ
6691
6692 ei->ordered_data_close = 0;
d68fc57b 6693 ei->orphan_meta_reserved = 0;
2ead6ae7 6694 ei->dummy_inode = 0;
261507a0 6695 ei->force_compress = BTRFS_COMPRESS_NONE;
2ead6ae7
YZ
6696
6697 inode = &ei->vfs_inode;
6698 extent_map_tree_init(&ei->extent_tree, GFP_NOFS);
6699 extent_io_tree_init(&ei->io_tree, &inode->i_data, GFP_NOFS);
6700 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data, GFP_NOFS);
6701 mutex_init(&ei->log_mutex);
e6dcd2dc 6702 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7b128766 6703 INIT_LIST_HEAD(&ei->i_orphan);
2ead6ae7 6704 INIT_LIST_HEAD(&ei->delalloc_inodes);
5a3f23d5 6705 INIT_LIST_HEAD(&ei->ordered_operations);
2ead6ae7
YZ
6706 RB_CLEAR_NODE(&ei->rb_node);
6707
6708 return inode;
39279cc3
CM
6709}
6710
fa0d7e3d
NP
6711static void btrfs_i_callback(struct rcu_head *head)
6712{
6713 struct inode *inode = container_of(head, struct inode, i_rcu);
6714 INIT_LIST_HEAD(&inode->i_dentry);
6715 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6716}
6717
39279cc3
CM
6718void btrfs_destroy_inode(struct inode *inode)
6719{
e6dcd2dc 6720 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
6721 struct btrfs_root *root = BTRFS_I(inode)->root;
6722
39279cc3
CM
6723 WARN_ON(!list_empty(&inode->i_dentry));
6724 WARN_ON(inode->i_data.nrpages);
0ca1f7ce 6725 WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents));
57a45ced 6726 WARN_ON(atomic_read(&BTRFS_I(inode)->reserved_extents));
39279cc3 6727
a6dbd429
JB
6728 /*
6729 * This can happen where we create an inode, but somebody else also
6730 * created the same inode and we need to destroy the one we already
6731 * created.
6732 */
6733 if (!root)
6734 goto free;
6735
5a3f23d5
CM
6736 /*
6737 * Make sure we're properly removed from the ordered operation
6738 * lists.
6739 */
6740 smp_mb();
6741 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6742 spin_lock(&root->fs_info->ordered_extent_lock);
6743 list_del_init(&BTRFS_I(inode)->ordered_operations);
6744 spin_unlock(&root->fs_info->ordered_extent_lock);
6745 }
6746
0af3d00b
JB
6747 if (root == root->fs_info->tree_root) {
6748 struct btrfs_block_group_cache *block_group;
6749
6750 block_group = btrfs_lookup_block_group(root->fs_info,
6751 BTRFS_I(inode)->block_group);
6752 if (block_group && block_group->inode == inode) {
6753 spin_lock(&block_group->lock);
6754 block_group->inode = NULL;
6755 spin_unlock(&block_group->lock);
6756 btrfs_put_block_group(block_group);
6757 } else if (block_group) {
6758 btrfs_put_block_group(block_group);
6759 }
6760 }
6761
d68fc57b 6762 spin_lock(&root->orphan_lock);
7b128766 6763 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
8082510e
YZ
6764 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
6765 inode->i_ino);
6766 list_del_init(&BTRFS_I(inode)->i_orphan);
7b128766 6767 }
d68fc57b 6768 spin_unlock(&root->orphan_lock);
7b128766 6769
d397712b 6770 while (1) {
e6dcd2dc
CM
6771 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6772 if (!ordered)
6773 break;
6774 else {
d397712b
CM
6775 printk(KERN_ERR "btrfs found ordered "
6776 "extent %llu %llu on inode cleanup\n",
6777 (unsigned long long)ordered->file_offset,
6778 (unsigned long long)ordered->len);
e6dcd2dc
CM
6779 btrfs_remove_ordered_extent(inode, ordered);
6780 btrfs_put_ordered_extent(ordered);
6781 btrfs_put_ordered_extent(ordered);
6782 }
6783 }
5d4f98a2 6784 inode_tree_del(inode);
5b21f2ed 6785 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
a6dbd429 6786free:
fa0d7e3d 6787 call_rcu(&inode->i_rcu, btrfs_i_callback);
39279cc3
CM
6788}
6789
45321ac5 6790int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
6791{
6792 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 6793
0af3d00b
JB
6794 if (btrfs_root_refs(&root->root_item) == 0 &&
6795 root != root->fs_info->tree_root)
45321ac5 6796 return 1;
76dda93c 6797 else
45321ac5 6798 return generic_drop_inode(inode);
76dda93c
YZ
6799}
6800
0ee0fda0 6801static void init_once(void *foo)
39279cc3
CM
6802{
6803 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6804
6805 inode_init_once(&ei->vfs_inode);
6806}
6807
6808void btrfs_destroy_cachep(void)
6809{
6810 if (btrfs_inode_cachep)
6811 kmem_cache_destroy(btrfs_inode_cachep);
6812 if (btrfs_trans_handle_cachep)
6813 kmem_cache_destroy(btrfs_trans_handle_cachep);
6814 if (btrfs_transaction_cachep)
6815 kmem_cache_destroy(btrfs_transaction_cachep);
39279cc3
CM
6816 if (btrfs_path_cachep)
6817 kmem_cache_destroy(btrfs_path_cachep);
dc89e982
JB
6818 if (btrfs_free_space_cachep)
6819 kmem_cache_destroy(btrfs_free_space_cachep);
39279cc3
CM
6820}
6821
6822int btrfs_init_cachep(void)
6823{
9601e3f6
CH
6824 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
6825 sizeof(struct btrfs_inode), 0,
6826 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
39279cc3
CM
6827 if (!btrfs_inode_cachep)
6828 goto fail;
9601e3f6
CH
6829
6830 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
6831 sizeof(struct btrfs_trans_handle), 0,
6832 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6833 if (!btrfs_trans_handle_cachep)
6834 goto fail;
9601e3f6
CH
6835
6836 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
6837 sizeof(struct btrfs_transaction), 0,
6838 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6839 if (!btrfs_transaction_cachep)
6840 goto fail;
9601e3f6
CH
6841
6842 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
6843 sizeof(struct btrfs_path), 0,
6844 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
6845 if (!btrfs_path_cachep)
6846 goto fail;
9601e3f6 6847
dc89e982
JB
6848 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
6849 sizeof(struct btrfs_free_space), 0,
6850 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
6851 if (!btrfs_free_space_cachep)
6852 goto fail;
6853
39279cc3
CM
6854 return 0;
6855fail:
6856 btrfs_destroy_cachep();
6857 return -ENOMEM;
6858}
6859
6860static int btrfs_getattr(struct vfsmount *mnt,
6861 struct dentry *dentry, struct kstat *stat)
6862{
6863 struct inode *inode = dentry->d_inode;
6864 generic_fillattr(inode, stat);
3394e160 6865 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
d6667462 6866 stat->blksize = PAGE_CACHE_SIZE;
a76a3cd4
YZ
6867 stat->blocks = (inode_get_bytes(inode) +
6868 BTRFS_I(inode)->delalloc_bytes) >> 9;
39279cc3
CM
6869 return 0;
6870}
6871
75e7cb7f
LB
6872/*
6873 * If a file is moved, it will inherit the cow and compression flags of the new
6874 * directory.
6875 */
6876static void fixup_inode_flags(struct inode *dir, struct inode *inode)
6877{
6878 struct btrfs_inode *b_dir = BTRFS_I(dir);
6879 struct btrfs_inode *b_inode = BTRFS_I(inode);
6880
6881 if (b_dir->flags & BTRFS_INODE_NODATACOW)
6882 b_inode->flags |= BTRFS_INODE_NODATACOW;
6883 else
6884 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
6885
6886 if (b_dir->flags & BTRFS_INODE_COMPRESS)
6887 b_inode->flags |= BTRFS_INODE_COMPRESS;
6888 else
6889 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
6890}
6891
d397712b
CM
6892static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
6893 struct inode *new_dir, struct dentry *new_dentry)
39279cc3
CM
6894{
6895 struct btrfs_trans_handle *trans;
6896 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 6897 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
39279cc3
CM
6898 struct inode *new_inode = new_dentry->d_inode;
6899 struct inode *old_inode = old_dentry->d_inode;
6900 struct timespec ctime = CURRENT_TIME;
00e4e6b3 6901 u64 index = 0;
4df27c4d 6902 u64 root_objectid;
39279cc3
CM
6903 int ret;
6904
f679a840
YZ
6905 if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6906 return -EPERM;
6907
4df27c4d
YZ
6908 /* we only allow rename subvolume link between subvolumes */
6909 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
6910 return -EXDEV;
6911
4df27c4d
YZ
6912 if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
6913 (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 6914 return -ENOTEMPTY;
5f39d397 6915
4df27c4d
YZ
6916 if (S_ISDIR(old_inode->i_mode) && new_inode &&
6917 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
6918 return -ENOTEMPTY;
5a3f23d5
CM
6919 /*
6920 * we're using rename to replace one file with another.
6921 * and the replacement file is large. Start IO on it now so
6922 * we don't add too much work to the end of the transaction
6923 */
4baf8c92 6924 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
5a3f23d5
CM
6925 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
6926 filemap_flush(old_inode->i_mapping);
6927
76dda93c
YZ
6928 /* close the racy window with snapshot create/destroy ioctl */
6929 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
6930 down_read(&root->fs_info->subvol_sem);
a22285a6
YZ
6931 /*
6932 * We want to reserve the absolute worst case amount of items. So if
6933 * both inodes are subvols and we need to unlink them then that would
6934 * require 4 item modifications, but if they are both normal inodes it
6935 * would require 5 item modifications, so we'll assume their normal
6936 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
6937 * should cover the worst case number of items we'll modify.
6938 */
6939 trans = btrfs_start_transaction(root, 20);
6940 if (IS_ERR(trans))
6941 return PTR_ERR(trans);
76dda93c 6942
a5719521 6943 btrfs_set_trans_block_group(trans, new_dir);
5f39d397 6944
4df27c4d
YZ
6945 if (dest != root)
6946 btrfs_record_root_in_trans(trans, dest);
5f39d397 6947
a5719521
YZ
6948 ret = btrfs_set_inode_index(new_dir, &index);
6949 if (ret)
6950 goto out_fail;
5a3f23d5 6951
a5719521 6952 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
6953 /* force full log commit if subvolume involved. */
6954 root->fs_info->last_trans_log_full_commit = trans->transid;
6955 } else {
a5719521
YZ
6956 ret = btrfs_insert_inode_ref(trans, dest,
6957 new_dentry->d_name.name,
6958 new_dentry->d_name.len,
6959 old_inode->i_ino,
6960 new_dir->i_ino, index);
6961 if (ret)
6962 goto out_fail;
4df27c4d
YZ
6963 /*
6964 * this is an ugly little race, but the rename is required
6965 * to make sure that if we crash, the inode is either at the
6966 * old name or the new one. pinning the log transaction lets
6967 * us make sure we don't allow a log commit to come in after
6968 * we unlink the name but before we add the new name back in.
6969 */
6970 btrfs_pin_log_trans(root);
6971 }
5a3f23d5
CM
6972 /*
6973 * make sure the inode gets flushed if it is replacing
6974 * something.
6975 */
6976 if (new_inode && new_inode->i_size &&
6977 old_inode && S_ISREG(old_inode->i_mode)) {
6978 btrfs_add_ordered_operation(trans, root, old_inode);
6979 }
6980
39279cc3
CM
6981 old_dir->i_ctime = old_dir->i_mtime = ctime;
6982 new_dir->i_ctime = new_dir->i_mtime = ctime;
6983 old_inode->i_ctime = ctime;
5f39d397 6984
12fcfd22
CM
6985 if (old_dentry->d_parent != new_dentry->d_parent)
6986 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
6987
4df27c4d
YZ
6988 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
6989 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
6990 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
6991 old_dentry->d_name.name,
6992 old_dentry->d_name.len);
6993 } else {
6994 btrfs_inc_nlink(old_dentry->d_inode);
6995 ret = btrfs_unlink_inode(trans, root, old_dir,
6996 old_dentry->d_inode,
6997 old_dentry->d_name.name,
6998 old_dentry->d_name.len);
6999 }
7000 BUG_ON(ret);
39279cc3
CM
7001
7002 if (new_inode) {
7003 new_inode->i_ctime = CURRENT_TIME;
4df27c4d
YZ
7004 if (unlikely(new_inode->i_ino ==
7005 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7006 root_objectid = BTRFS_I(new_inode)->location.objectid;
7007 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7008 root_objectid,
7009 new_dentry->d_name.name,
7010 new_dentry->d_name.len);
7011 BUG_ON(new_inode->i_nlink == 0);
7012 } else {
7013 ret = btrfs_unlink_inode(trans, dest, new_dir,
7014 new_dentry->d_inode,
7015 new_dentry->d_name.name,
7016 new_dentry->d_name.len);
7017 }
7018 BUG_ON(ret);
7b128766 7019 if (new_inode->i_nlink == 0) {
e02119d5 7020 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
4df27c4d 7021 BUG_ON(ret);
7b128766 7022 }
39279cc3 7023 }
aec7477b 7024
75e7cb7f
LB
7025 fixup_inode_flags(new_dir, old_inode);
7026
4df27c4d
YZ
7027 ret = btrfs_add_link(trans, new_dir, old_inode,
7028 new_dentry->d_name.name,
a5719521 7029 new_dentry->d_name.len, 0, index);
4df27c4d 7030 BUG_ON(ret);
39279cc3 7031
4df27c4d 7032 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
6a912213
JB
7033 struct dentry *parent = dget_parent(new_dentry);
7034 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7035 dput(parent);
4df27c4d
YZ
7036 btrfs_end_log_trans(root);
7037 }
39279cc3 7038out_fail:
ab78c84d 7039 btrfs_end_transaction_throttle(trans, root);
4df27c4d 7040
76dda93c
YZ
7041 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
7042 up_read(&root->fs_info->subvol_sem);
9ed74f2d 7043
39279cc3
CM
7044 return ret;
7045}
7046
d352ac68
CM
7047/*
7048 * some fairly slow code that needs optimization. This walks the list
7049 * of all the inodes with pending delalloc and forces them to disk.
7050 */
24bbcf04 7051int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
ea8c2819
CM
7052{
7053 struct list_head *head = &root->fs_info->delalloc_inodes;
7054 struct btrfs_inode *binode;
5b21f2ed 7055 struct inode *inode;
ea8c2819 7056
c146afad
YZ
7057 if (root->fs_info->sb->s_flags & MS_RDONLY)
7058 return -EROFS;
7059
75eff68e 7060 spin_lock(&root->fs_info->delalloc_lock);
d397712b 7061 while (!list_empty(head)) {
ea8c2819
CM
7062 binode = list_entry(head->next, struct btrfs_inode,
7063 delalloc_inodes);
5b21f2ed
ZY
7064 inode = igrab(&binode->vfs_inode);
7065 if (!inode)
7066 list_del_init(&binode->delalloc_inodes);
75eff68e 7067 spin_unlock(&root->fs_info->delalloc_lock);
5b21f2ed 7068 if (inode) {
8c8bee1d 7069 filemap_flush(inode->i_mapping);
24bbcf04
YZ
7070 if (delay_iput)
7071 btrfs_add_delayed_iput(inode);
7072 else
7073 iput(inode);
5b21f2ed
ZY
7074 }
7075 cond_resched();
75eff68e 7076 spin_lock(&root->fs_info->delalloc_lock);
ea8c2819 7077 }
75eff68e 7078 spin_unlock(&root->fs_info->delalloc_lock);
8c8bee1d
CM
7079
7080 /* the filemap_flush will queue IO into the worker threads, but
7081 * we have to make sure the IO is actually started and that
7082 * ordered extents get created before we return
7083 */
7084 atomic_inc(&root->fs_info->async_submit_draining);
d397712b 7085 while (atomic_read(&root->fs_info->nr_async_submits) ||
771ed689 7086 atomic_read(&root->fs_info->async_delalloc_pages)) {
8c8bee1d 7087 wait_event(root->fs_info->async_submit_wait,
771ed689
CM
7088 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7089 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8c8bee1d
CM
7090 }
7091 atomic_dec(&root->fs_info->async_submit_draining);
ea8c2819
CM
7092 return 0;
7093}
7094
0019f10d
JB
7095int btrfs_start_one_delalloc_inode(struct btrfs_root *root, int delay_iput,
7096 int sync)
5da9d01b
YZ
7097{
7098 struct btrfs_inode *binode;
7099 struct inode *inode = NULL;
7100
7101 spin_lock(&root->fs_info->delalloc_lock);
7102 while (!list_empty(&root->fs_info->delalloc_inodes)) {
7103 binode = list_entry(root->fs_info->delalloc_inodes.next,
7104 struct btrfs_inode, delalloc_inodes);
7105 inode = igrab(&binode->vfs_inode);
7106 if (inode) {
7107 list_move_tail(&binode->delalloc_inodes,
7108 &root->fs_info->delalloc_inodes);
7109 break;
7110 }
7111
7112 list_del_init(&binode->delalloc_inodes);
7113 cond_resched_lock(&root->fs_info->delalloc_lock);
7114 }
7115 spin_unlock(&root->fs_info->delalloc_lock);
7116
7117 if (inode) {
0019f10d
JB
7118 if (sync) {
7119 filemap_write_and_wait(inode->i_mapping);
7120 /*
7121 * We have to do this because compression doesn't
7122 * actually set PG_writeback until it submits the pages
7123 * for IO, which happens in an async thread, so we could
7124 * race and not actually wait for any writeback pages
7125 * because they've not been submitted yet. Technically
7126 * this could still be the case for the ordered stuff
7127 * since the async thread may not have started to do its
7128 * work yet. If this becomes the case then we need to
7129 * figure out a way to make sure that in writepage we
7130 * wait for any async pages to be submitted before
7131 * returning so that fdatawait does what its supposed to
7132 * do.
7133 */
7134 btrfs_wait_ordered_range(inode, 0, (u64)-1);
7135 } else {
7136 filemap_flush(inode->i_mapping);
7137 }
5da9d01b
YZ
7138 if (delay_iput)
7139 btrfs_add_delayed_iput(inode);
7140 else
7141 iput(inode);
7142 return 1;
7143 }
7144 return 0;
7145}
7146
39279cc3
CM
7147static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7148 const char *symname)
7149{
7150 struct btrfs_trans_handle *trans;
7151 struct btrfs_root *root = BTRFS_I(dir)->root;
7152 struct btrfs_path *path;
7153 struct btrfs_key key;
1832a6d5 7154 struct inode *inode = NULL;
39279cc3
CM
7155 int err;
7156 int drop_inode = 0;
7157 u64 objectid;
00e4e6b3 7158 u64 index = 0 ;
39279cc3
CM
7159 int name_len;
7160 int datasize;
5f39d397 7161 unsigned long ptr;
39279cc3 7162 struct btrfs_file_extent_item *ei;
5f39d397 7163 struct extent_buffer *leaf;
1832a6d5 7164 unsigned long nr = 0;
39279cc3
CM
7165
7166 name_len = strlen(symname) + 1;
7167 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7168 return -ENAMETOOLONG;
1832a6d5 7169
a22285a6
YZ
7170 err = btrfs_find_free_objectid(NULL, root, dir->i_ino, &objectid);
7171 if (err)
7172 return err;
9ed74f2d
JB
7173 /*
7174 * 2 items for inode item and ref
7175 * 2 items for dir items
7176 * 1 item for xattr if selinux is on
7177 */
a22285a6
YZ
7178 trans = btrfs_start_transaction(root, 5);
7179 if (IS_ERR(trans))
7180 return PTR_ERR(trans);
1832a6d5 7181
39279cc3
CM
7182 btrfs_set_trans_block_group(trans, dir);
7183
aec7477b 7184 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
a1b075d2 7185 dentry->d_name.len, dir->i_ino, objectid,
00e4e6b3
CM
7186 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
7187 &index);
39279cc3
CM
7188 err = PTR_ERR(inode);
7189 if (IS_ERR(inode))
7190 goto out_unlock;
7191
f34f57a3 7192 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
7193 if (err) {
7194 drop_inode = 1;
7195 goto out_unlock;
7196 }
7197
39279cc3 7198 btrfs_set_trans_block_group(trans, inode);
a1b075d2 7199 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
39279cc3
CM
7200 if (err)
7201 drop_inode = 1;
7202 else {
7203 inode->i_mapping->a_ops = &btrfs_aops;
04160088 7204 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
7205 inode->i_fop = &btrfs_file_operations;
7206 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 7207 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 7208 }
39279cc3
CM
7209 btrfs_update_inode_block_group(trans, inode);
7210 btrfs_update_inode_block_group(trans, dir);
7211 if (drop_inode)
7212 goto out_unlock;
7213
7214 path = btrfs_alloc_path();
7215 BUG_ON(!path);
7216 key.objectid = inode->i_ino;
7217 key.offset = 0;
39279cc3
CM
7218 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7219 datasize = btrfs_file_extent_calc_inline_size(name_len);
7220 err = btrfs_insert_empty_item(trans, root, path, &key,
7221 datasize);
54aa1f4d
CM
7222 if (err) {
7223 drop_inode = 1;
7224 goto out_unlock;
7225 }
5f39d397
CM
7226 leaf = path->nodes[0];
7227 ei = btrfs_item_ptr(leaf, path->slots[0],
7228 struct btrfs_file_extent_item);
7229 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7230 btrfs_set_file_extent_type(leaf, ei,
39279cc3 7231 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
7232 btrfs_set_file_extent_encryption(leaf, ei, 0);
7233 btrfs_set_file_extent_compression(leaf, ei, 0);
7234 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7235 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7236
39279cc3 7237 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
7238 write_extent_buffer(leaf, symname, ptr, name_len);
7239 btrfs_mark_buffer_dirty(leaf);
39279cc3 7240 btrfs_free_path(path);
5f39d397 7241
39279cc3
CM
7242 inode->i_op = &btrfs_symlink_inode_operations;
7243 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 7244 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d899e052 7245 inode_set_bytes(inode, name_len);
dbe674a9 7246 btrfs_i_size_write(inode, name_len - 1);
54aa1f4d
CM
7247 err = btrfs_update_inode(trans, root, inode);
7248 if (err)
7249 drop_inode = 1;
39279cc3
CM
7250
7251out_unlock:
d3c2fdcf 7252 nr = trans->blocks_used;
ab78c84d 7253 btrfs_end_transaction_throttle(trans, root);
39279cc3
CM
7254 if (drop_inode) {
7255 inode_dec_link_count(inode);
7256 iput(inode);
7257 }
d3c2fdcf 7258 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
7259 return err;
7260}
16432985 7261
0af3d00b
JB
7262static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7263 u64 start, u64 num_bytes, u64 min_size,
7264 loff_t actual_len, u64 *alloc_hint,
7265 struct btrfs_trans_handle *trans)
d899e052 7266{
d899e052
YZ
7267 struct btrfs_root *root = BTRFS_I(inode)->root;
7268 struct btrfs_key ins;
d899e052 7269 u64 cur_offset = start;
55a61d1d 7270 u64 i_size;
d899e052 7271 int ret = 0;
0af3d00b 7272 bool own_trans = true;
d899e052 7273
0af3d00b
JB
7274 if (trans)
7275 own_trans = false;
d899e052 7276 while (num_bytes > 0) {
0af3d00b
JB
7277 if (own_trans) {
7278 trans = btrfs_start_transaction(root, 3);
7279 if (IS_ERR(trans)) {
7280 ret = PTR_ERR(trans);
7281 break;
7282 }
5a303d5d
YZ
7283 }
7284
efa56464
YZ
7285 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7286 0, *alloc_hint, (u64)-1, &ins, 1);
5a303d5d 7287 if (ret) {
0af3d00b
JB
7288 if (own_trans)
7289 btrfs_end_transaction(trans, root);
a22285a6 7290 break;
d899e052 7291 }
5a303d5d 7292
d899e052
YZ
7293 ret = insert_reserved_file_extent(trans, inode,
7294 cur_offset, ins.objectid,
7295 ins.offset, ins.offset,
920bbbfb 7296 ins.offset, 0, 0, 0,
d899e052
YZ
7297 BTRFS_FILE_EXTENT_PREALLOC);
7298 BUG_ON(ret);
a1ed835e
CM
7299 btrfs_drop_extent_cache(inode, cur_offset,
7300 cur_offset + ins.offset -1, 0);
5a303d5d 7301
d899e052
YZ
7302 num_bytes -= ins.offset;
7303 cur_offset += ins.offset;
efa56464 7304 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 7305
d899e052 7306 inode->i_ctime = CURRENT_TIME;
6cbff00f 7307 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 7308 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
7309 (actual_len > inode->i_size) &&
7310 (cur_offset > inode->i_size)) {
d1ea6a61 7311 if (cur_offset > actual_len)
55a61d1d 7312 i_size = actual_len;
d1ea6a61 7313 else
55a61d1d
JB
7314 i_size = cur_offset;
7315 i_size_write(inode, i_size);
7316 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
7317 }
7318
d899e052
YZ
7319 ret = btrfs_update_inode(trans, root, inode);
7320 BUG_ON(ret);
d899e052 7321
0af3d00b
JB
7322 if (own_trans)
7323 btrfs_end_transaction(trans, root);
5a303d5d 7324 }
d899e052
YZ
7325 return ret;
7326}
7327
0af3d00b
JB
7328int btrfs_prealloc_file_range(struct inode *inode, int mode,
7329 u64 start, u64 num_bytes, u64 min_size,
7330 loff_t actual_len, u64 *alloc_hint)
7331{
7332 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7333 min_size, actual_len, alloc_hint,
7334 NULL);
7335}
7336
7337int btrfs_prealloc_file_range_trans(struct inode *inode,
7338 struct btrfs_trans_handle *trans, int mode,
7339 u64 start, u64 num_bytes, u64 min_size,
7340 loff_t actual_len, u64 *alloc_hint)
7341{
7342 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7343 min_size, actual_len, alloc_hint, trans);
7344}
7345
e6dcd2dc
CM
7346static int btrfs_set_page_dirty(struct page *page)
7347{
e6dcd2dc
CM
7348 return __set_page_dirty_nobuffers(page);
7349}
7350
b74c79e9 7351static int btrfs_permission(struct inode *inode, int mask, unsigned int flags)
fdebe2bd 7352{
b83cc969
LZ
7353 struct btrfs_root *root = BTRFS_I(inode)->root;
7354
7355 if (btrfs_root_readonly(root) && (mask & MAY_WRITE))
7356 return -EROFS;
6cbff00f 7357 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
fdebe2bd 7358 return -EACCES;
b74c79e9 7359 return generic_permission(inode, mask, flags, btrfs_check_acl);
fdebe2bd 7360}
39279cc3 7361
6e1d5dcc 7362static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 7363 .getattr = btrfs_getattr,
39279cc3
CM
7364 .lookup = btrfs_lookup,
7365 .create = btrfs_create,
7366 .unlink = btrfs_unlink,
7367 .link = btrfs_link,
7368 .mkdir = btrfs_mkdir,
7369 .rmdir = btrfs_rmdir,
7370 .rename = btrfs_rename,
7371 .symlink = btrfs_symlink,
7372 .setattr = btrfs_setattr,
618e21d5 7373 .mknod = btrfs_mknod,
95819c05
CH
7374 .setxattr = btrfs_setxattr,
7375 .getxattr = btrfs_getxattr,
5103e947 7376 .listxattr = btrfs_listxattr,
95819c05 7377 .removexattr = btrfs_removexattr,
fdebe2bd 7378 .permission = btrfs_permission,
39279cc3 7379};
6e1d5dcc 7380static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 7381 .lookup = btrfs_lookup,
fdebe2bd 7382 .permission = btrfs_permission,
39279cc3 7383};
76dda93c 7384
828c0950 7385static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
7386 .llseek = generic_file_llseek,
7387 .read = generic_read_dir,
cbdf5a24 7388 .readdir = btrfs_real_readdir,
34287aa3 7389 .unlocked_ioctl = btrfs_ioctl,
39279cc3 7390#ifdef CONFIG_COMPAT
34287aa3 7391 .compat_ioctl = btrfs_ioctl,
39279cc3 7392#endif
6bf13c0c 7393 .release = btrfs_release_file,
e02119d5 7394 .fsync = btrfs_sync_file,
39279cc3
CM
7395};
7396
d1310b2e 7397static struct extent_io_ops btrfs_extent_io_ops = {
07157aac 7398 .fill_delalloc = run_delalloc_range,
065631f6 7399 .submit_bio_hook = btrfs_submit_bio_hook,
239b14b3 7400 .merge_bio_hook = btrfs_merge_bio_hook,
07157aac 7401 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
e6dcd2dc 7402 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
247e743c 7403 .writepage_start_hook = btrfs_writepage_start_hook,
1259ab75 7404 .readpage_io_failed_hook = btrfs_io_failed_hook,
b0c68f8b
CM
7405 .set_bit_hook = btrfs_set_bit_hook,
7406 .clear_bit_hook = btrfs_clear_bit_hook,
9ed74f2d
JB
7407 .merge_extent_hook = btrfs_merge_extent_hook,
7408 .split_extent_hook = btrfs_split_extent_hook,
07157aac
CM
7409};
7410
35054394
CM
7411/*
7412 * btrfs doesn't support the bmap operation because swapfiles
7413 * use bmap to make a mapping of extents in the file. They assume
7414 * these extents won't change over the life of the file and they
7415 * use the bmap result to do IO directly to the drive.
7416 *
7417 * the btrfs bmap call would return logical addresses that aren't
7418 * suitable for IO and they also will change frequently as COW
7419 * operations happen. So, swapfile + btrfs == corruption.
7420 *
7421 * For now we're avoiding this by dropping bmap.
7422 */
7f09410b 7423static const struct address_space_operations btrfs_aops = {
39279cc3
CM
7424 .readpage = btrfs_readpage,
7425 .writepage = btrfs_writepage,
b293f02e 7426 .writepages = btrfs_writepages,
3ab2fb5a 7427 .readpages = btrfs_readpages,
39279cc3 7428 .sync_page = block_sync_page,
16432985 7429 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
7430 .invalidatepage = btrfs_invalidatepage,
7431 .releasepage = btrfs_releasepage,
e6dcd2dc 7432 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 7433 .error_remove_page = generic_error_remove_page,
39279cc3
CM
7434};
7435
7f09410b 7436static const struct address_space_operations btrfs_symlink_aops = {
39279cc3
CM
7437 .readpage = btrfs_readpage,
7438 .writepage = btrfs_writepage,
2bf5a725
CM
7439 .invalidatepage = btrfs_invalidatepage,
7440 .releasepage = btrfs_releasepage,
39279cc3
CM
7441};
7442
6e1d5dcc 7443static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
7444 .getattr = btrfs_getattr,
7445 .setattr = btrfs_setattr,
95819c05
CH
7446 .setxattr = btrfs_setxattr,
7447 .getxattr = btrfs_getxattr,
5103e947 7448 .listxattr = btrfs_listxattr,
95819c05 7449 .removexattr = btrfs_removexattr,
fdebe2bd 7450 .permission = btrfs_permission,
1506fcc8 7451 .fiemap = btrfs_fiemap,
39279cc3 7452};
6e1d5dcc 7453static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
7454 .getattr = btrfs_getattr,
7455 .setattr = btrfs_setattr,
fdebe2bd 7456 .permission = btrfs_permission,
95819c05
CH
7457 .setxattr = btrfs_setxattr,
7458 .getxattr = btrfs_getxattr,
33268eaf 7459 .listxattr = btrfs_listxattr,
95819c05 7460 .removexattr = btrfs_removexattr,
618e21d5 7461};
6e1d5dcc 7462static const struct inode_operations btrfs_symlink_inode_operations = {
39279cc3
CM
7463 .readlink = generic_readlink,
7464 .follow_link = page_follow_link_light,
7465 .put_link = page_put_link,
f209561a 7466 .getattr = btrfs_getattr,
fdebe2bd 7467 .permission = btrfs_permission,
0279b4cd
JO
7468 .setxattr = btrfs_setxattr,
7469 .getxattr = btrfs_getxattr,
7470 .listxattr = btrfs_listxattr,
7471 .removexattr = btrfs_removexattr,
39279cc3 7472};
76dda93c 7473
82d339d9 7474const struct dentry_operations btrfs_dentry_operations = {
76dda93c
YZ
7475 .d_delete = btrfs_dentry_delete,
7476};