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