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