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