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