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