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