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