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