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