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