]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/inode.c
btrfs: Remove fs_info from struct async_chunk
[mirror_ubuntu-jammy-kernel.git] / fs / btrfs / inode.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
6cbd5570
CM
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
6cbd5570
CM
4 */
5
8f18cf13 6#include <linux/kernel.h>
065631f6 7#include <linux/bio.h>
39279cc3 8#include <linux/buffer_head.h>
f2eb0a24 9#include <linux/file.h>
39279cc3
CM
10#include <linux/fs.h>
11#include <linux/pagemap.h>
12#include <linux/highmem.h>
13#include <linux/time.h>
14#include <linux/init.h>
15#include <linux/string.h>
39279cc3 16#include <linux/backing-dev.h>
39279cc3 17#include <linux/writeback.h>
39279cc3 18#include <linux/compat.h>
5103e947 19#include <linux/xattr.h>
33268eaf 20#include <linux/posix_acl.h>
d899e052 21#include <linux/falloc.h>
5a0e3ad6 22#include <linux/slab.h>
7a36ddec 23#include <linux/ratelimit.h>
55e301fd 24#include <linux/btrfs.h>
53b381b3 25#include <linux/blkdev.h>
f23b5a59 26#include <linux/posix_acl_xattr.h>
e2e40f2c 27#include <linux/uio.h>
69fe2d75 28#include <linux/magic.h>
ae5e165d 29#include <linux/iversion.h>
ed46ff3d 30#include <linux/swap.h>
92d32170 31#include <asm/unaligned.h>
39279cc3
CM
32#include "ctree.h"
33#include "disk-io.h"
34#include "transaction.h"
35#include "btrfs_inode.h"
39279cc3 36#include "print-tree.h"
e6dcd2dc 37#include "ordered-data.h"
95819c05 38#include "xattr.h"
e02119d5 39#include "tree-log.h"
4a54c8c1 40#include "volumes.h"
c8b97818 41#include "compression.h"
b4ce94de 42#include "locking.h"
dc89e982 43#include "free-space-cache.h"
581bb050 44#include "inode-map.h"
38c227d8 45#include "backref.h"
63541927 46#include "props.h"
31193213 47#include "qgroup.h"
dda3245e 48#include "dedupe.h"
39279cc3
CM
49
50struct btrfs_iget_args {
90d3e592 51 struct btrfs_key *location;
39279cc3
CM
52 struct btrfs_root *root;
53};
54
f28a4928 55struct btrfs_dio_data {
f28a4928
FM
56 u64 reserve;
57 u64 unsubmitted_oe_range_start;
58 u64 unsubmitted_oe_range_end;
4aaedfb0 59 int overwrite;
f28a4928
FM
60};
61
6e1d5dcc
AD
62static const struct inode_operations btrfs_dir_inode_operations;
63static const struct inode_operations btrfs_symlink_inode_operations;
64static const struct inode_operations btrfs_dir_ro_inode_operations;
65static const struct inode_operations btrfs_special_inode_operations;
66static const struct inode_operations btrfs_file_inode_operations;
7f09410b 67static const struct address_space_operations btrfs_aops;
828c0950 68static const struct file_operations btrfs_dir_file_operations;
20e5506b 69static const struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
70
71static struct kmem_cache *btrfs_inode_cachep;
72struct kmem_cache *btrfs_trans_handle_cachep;
39279cc3 73struct kmem_cache *btrfs_path_cachep;
dc89e982 74struct kmem_cache *btrfs_free_space_cachep;
39279cc3 75
3972f260 76static int btrfs_setsize(struct inode *inode, struct iattr *attr);
213e8c55 77static int btrfs_truncate(struct inode *inode, bool skip_writeback);
5fd02043 78static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
771ed689
CM
79static noinline int cow_file_range(struct inode *inode,
80 struct page *locked_page,
dda3245e
WX
81 u64 start, u64 end, u64 delalloc_end,
82 int *page_started, unsigned long *nr_written,
83 int unlock, struct btrfs_dedupe_hash *hash);
6f9994db
LB
84static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
85 u64 orig_start, u64 block_start,
86 u64 block_len, u64 orig_block_len,
87 u64 ram_bytes, int compress_type,
88 int type);
7b128766 89
52427260
QW
90static void __endio_write_update_ordered(struct inode *inode,
91 const u64 offset, const u64 bytes,
92 const bool uptodate);
93
94/*
95 * Cleanup all submitted ordered extents in specified range to handle errors
52042d8e 96 * from the btrfs_run_delalloc_range() callback.
52427260
QW
97 *
98 * NOTE: caller must ensure that when an error happens, it can not call
99 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
100 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
101 * to be released, which we want to happen only when finishing the ordered
d1051d6e 102 * extent (btrfs_finish_ordered_io()).
52427260
QW
103 */
104static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
d1051d6e
NB
105 struct page *locked_page,
106 u64 offset, u64 bytes)
52427260 107{
63d71450
NA
108 unsigned long index = offset >> PAGE_SHIFT;
109 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
d1051d6e
NB
110 u64 page_start = page_offset(locked_page);
111 u64 page_end = page_start + PAGE_SIZE - 1;
112
63d71450
NA
113 struct page *page;
114
115 while (index <= end_index) {
116 page = find_get_page(inode->i_mapping, index);
117 index++;
118 if (!page)
119 continue;
120 ClearPagePrivate2(page);
121 put_page(page);
122 }
d1051d6e
NB
123
124 /*
125 * In case this page belongs to the delalloc range being instantiated
126 * then skip it, since the first page of a range is going to be
127 * properly cleaned up by the caller of run_delalloc_range
128 */
129 if (page_start >= offset && page_end <= (offset + bytes - 1)) {
130 offset += PAGE_SIZE;
131 bytes -= PAGE_SIZE;
132 }
133
134 return __endio_write_update_ordered(inode, offset, bytes, false);
52427260
QW
135}
136
48a3b636 137static int btrfs_dirty_inode(struct inode *inode);
7b128766 138
6a3891c5
JB
139#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
140void btrfs_test_inode_set_ops(struct inode *inode)
141{
142 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
143}
144#endif
145
f34f57a3 146static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
2a7dba39
EP
147 struct inode *inode, struct inode *dir,
148 const struct qstr *qstr)
0279b4cd
JO
149{
150 int err;
151
f34f57a3 152 err = btrfs_init_acl(trans, inode, dir);
0279b4cd 153 if (!err)
2a7dba39 154 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
0279b4cd
JO
155 return err;
156}
157
c8b97818
CM
158/*
159 * this does all the hard work for inserting an inline extent into
160 * the btree. The caller should have done a btrfs_drop_extents so that
161 * no overlapping inline items exist in the btree
162 */
40f76580 163static int insert_inline_extent(struct btrfs_trans_handle *trans,
1acae57b 164 struct btrfs_path *path, int extent_inserted,
c8b97818
CM
165 struct btrfs_root *root, struct inode *inode,
166 u64 start, size_t size, size_t compressed_size,
fe3f566c 167 int compress_type,
c8b97818
CM
168 struct page **compressed_pages)
169{
c8b97818
CM
170 struct extent_buffer *leaf;
171 struct page *page = NULL;
172 char *kaddr;
173 unsigned long ptr;
174 struct btrfs_file_extent_item *ei;
c8b97818
CM
175 int ret;
176 size_t cur_size = size;
c8b97818 177 unsigned long offset;
c8b97818 178
fe3f566c 179 if (compressed_size && compressed_pages)
c8b97818 180 cur_size = compressed_size;
c8b97818 181
1acae57b 182 inode_add_bytes(inode, size);
c8b97818 183
1acae57b
FDBM
184 if (!extent_inserted) {
185 struct btrfs_key key;
186 size_t datasize;
c8b97818 187
4a0cc7ca 188 key.objectid = btrfs_ino(BTRFS_I(inode));
1acae57b 189 key.offset = start;
962a298f 190 key.type = BTRFS_EXTENT_DATA_KEY;
c8b97818 191
1acae57b
FDBM
192 datasize = btrfs_file_extent_calc_inline_size(cur_size);
193 path->leave_spinning = 1;
194 ret = btrfs_insert_empty_item(trans, root, path, &key,
195 datasize);
79b4f4c6 196 if (ret)
1acae57b 197 goto fail;
c8b97818
CM
198 }
199 leaf = path->nodes[0];
200 ei = btrfs_item_ptr(leaf, path->slots[0],
201 struct btrfs_file_extent_item);
202 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
203 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
204 btrfs_set_file_extent_encryption(leaf, ei, 0);
205 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
206 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
207 ptr = btrfs_file_extent_inline_start(ei);
208
261507a0 209 if (compress_type != BTRFS_COMPRESS_NONE) {
c8b97818
CM
210 struct page *cpage;
211 int i = 0;
d397712b 212 while (compressed_size > 0) {
c8b97818 213 cpage = compressed_pages[i];
5b050f04 214 cur_size = min_t(unsigned long, compressed_size,
09cbfeaf 215 PAGE_SIZE);
c8b97818 216
7ac687d9 217 kaddr = kmap_atomic(cpage);
c8b97818 218 write_extent_buffer(leaf, kaddr, ptr, cur_size);
7ac687d9 219 kunmap_atomic(kaddr);
c8b97818
CM
220
221 i++;
222 ptr += cur_size;
223 compressed_size -= cur_size;
224 }
225 btrfs_set_file_extent_compression(leaf, ei,
261507a0 226 compress_type);
c8b97818
CM
227 } else {
228 page = find_get_page(inode->i_mapping,
09cbfeaf 229 start >> PAGE_SHIFT);
c8b97818 230 btrfs_set_file_extent_compression(leaf, ei, 0);
7ac687d9 231 kaddr = kmap_atomic(page);
7073017a 232 offset = offset_in_page(start);
c8b97818 233 write_extent_buffer(leaf, kaddr + offset, ptr, size);
7ac687d9 234 kunmap_atomic(kaddr);
09cbfeaf 235 put_page(page);
c8b97818
CM
236 }
237 btrfs_mark_buffer_dirty(leaf);
1acae57b 238 btrfs_release_path(path);
c8b97818 239
c2167754
YZ
240 /*
241 * we're an inline extent, so nobody can
242 * extend the file past i_size without locking
243 * a page we already have locked.
244 *
245 * We must do any isize and inode updates
246 * before we unlock the pages. Otherwise we
247 * could end up racing with unlink.
248 */
c8b97818 249 BTRFS_I(inode)->disk_i_size = inode->i_size;
79787eaa 250 ret = btrfs_update_inode(trans, root, inode);
c2167754 251
c8b97818 252fail:
79b4f4c6 253 return ret;
c8b97818
CM
254}
255
256
257/*
258 * conditionally insert an inline extent into the file. This
259 * does the checks required to make sure the data is small enough
260 * to fit as an inline extent.
261 */
d02c0e20 262static noinline int cow_file_range_inline(struct inode *inode, u64 start,
00361589
JB
263 u64 end, size_t compressed_size,
264 int compress_type,
265 struct page **compressed_pages)
c8b97818 266{
d02c0e20 267 struct btrfs_root *root = BTRFS_I(inode)->root;
0b246afa 268 struct btrfs_fs_info *fs_info = root->fs_info;
00361589 269 struct btrfs_trans_handle *trans;
c8b97818
CM
270 u64 isize = i_size_read(inode);
271 u64 actual_end = min(end + 1, isize);
272 u64 inline_len = actual_end - start;
0b246afa 273 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
c8b97818
CM
274 u64 data_len = inline_len;
275 int ret;
1acae57b
FDBM
276 struct btrfs_path *path;
277 int extent_inserted = 0;
278 u32 extent_item_size;
c8b97818
CM
279
280 if (compressed_size)
281 data_len = compressed_size;
282
283 if (start > 0 ||
0b246afa
JM
284 actual_end > fs_info->sectorsize ||
285 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
c8b97818 286 (!compressed_size &&
0b246afa 287 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
c8b97818 288 end + 1 < isize ||
0b246afa 289 data_len > fs_info->max_inline) {
c8b97818
CM
290 return 1;
291 }
292
1acae57b
FDBM
293 path = btrfs_alloc_path();
294 if (!path)
295 return -ENOMEM;
296
00361589 297 trans = btrfs_join_transaction(root);
1acae57b
FDBM
298 if (IS_ERR(trans)) {
299 btrfs_free_path(path);
00361589 300 return PTR_ERR(trans);
1acae57b 301 }
69fe2d75 302 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
00361589 303
1acae57b
FDBM
304 if (compressed_size && compressed_pages)
305 extent_item_size = btrfs_file_extent_calc_inline_size(
306 compressed_size);
307 else
308 extent_item_size = btrfs_file_extent_calc_inline_size(
309 inline_len);
310
311 ret = __btrfs_drop_extents(trans, root, inode, path,
312 start, aligned_end, NULL,
313 1, 1, extent_item_size, &extent_inserted);
00361589 314 if (ret) {
66642832 315 btrfs_abort_transaction(trans, ret);
00361589
JB
316 goto out;
317 }
c8b97818
CM
318
319 if (isize > actual_end)
320 inline_len = min_t(u64, isize, actual_end);
1acae57b
FDBM
321 ret = insert_inline_extent(trans, path, extent_inserted,
322 root, inode, start,
c8b97818 323 inline_len, compressed_size,
fe3f566c 324 compress_type, compressed_pages);
2adcac1a 325 if (ret && ret != -ENOSPC) {
66642832 326 btrfs_abort_transaction(trans, ret);
00361589 327 goto out;
2adcac1a 328 } else if (ret == -ENOSPC) {
00361589
JB
329 ret = 1;
330 goto out;
79787eaa 331 }
2adcac1a 332
bdc20e67 333 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
dcdbc059 334 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
00361589 335out:
94ed938a
QW
336 /*
337 * Don't forget to free the reserved space, as for inlined extent
338 * it won't count as data extent, free them directly here.
339 * And at reserve time, it's always aligned to page size, so
340 * just free one page here.
341 */
bc42bda2 342 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
1acae57b 343 btrfs_free_path(path);
3a45bb20 344 btrfs_end_transaction(trans);
00361589 345 return ret;
c8b97818
CM
346}
347
771ed689
CM
348struct async_extent {
349 u64 start;
350 u64 ram_size;
351 u64 compressed_size;
352 struct page **pages;
353 unsigned long nr_pages;
261507a0 354 int compress_type;
771ed689
CM
355 struct list_head list;
356};
357
97db1204 358struct async_chunk {
771ed689 359 struct inode *inode;
771ed689
CM
360 struct page *locked_page;
361 u64 start;
362 u64 end;
f82b7359 363 unsigned int write_flags;
771ed689
CM
364 struct list_head extents;
365 struct btrfs_work work;
97db1204
NB
366 atomic_t *pending;
367};
368
369struct async_cow {
370 /* Number of chunks in flight; must be first in the structure */
371 atomic_t num_chunks;
372 struct async_chunk chunks[];
771ed689
CM
373};
374
97db1204 375static noinline int add_async_extent(struct async_chunk *cow,
771ed689
CM
376 u64 start, u64 ram_size,
377 u64 compressed_size,
378 struct page **pages,
261507a0
LZ
379 unsigned long nr_pages,
380 int compress_type)
771ed689
CM
381{
382 struct async_extent *async_extent;
383
384 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
79787eaa 385 BUG_ON(!async_extent); /* -ENOMEM */
771ed689
CM
386 async_extent->start = start;
387 async_extent->ram_size = ram_size;
388 async_extent->compressed_size = compressed_size;
389 async_extent->pages = pages;
390 async_extent->nr_pages = nr_pages;
261507a0 391 async_extent->compress_type = compress_type;
771ed689
CM
392 list_add_tail(&async_extent->list, &cow->extents);
393 return 0;
394}
395
c2fcdcdf 396static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
f79707b0 397{
0b246afa 398 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
f79707b0
WS
399
400 /* force compress */
0b246afa 401 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
f79707b0 402 return 1;
eec63c65
DS
403 /* defrag ioctl */
404 if (BTRFS_I(inode)->defrag_compress)
405 return 1;
f79707b0
WS
406 /* bad compression ratios */
407 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
408 return 0;
0b246afa 409 if (btrfs_test_opt(fs_info, COMPRESS) ||
f79707b0 410 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
b52aa8c9 411 BTRFS_I(inode)->prop_compress)
c2fcdcdf 412 return btrfs_compress_heuristic(inode, start, end);
f79707b0
WS
413 return 0;
414}
415
6158e1ce 416static inline void inode_should_defrag(struct btrfs_inode *inode,
26d30f85
AJ
417 u64 start, u64 end, u64 num_bytes, u64 small_write)
418{
419 /* If this is a small write inside eof, kick off a defrag */
420 if (num_bytes < small_write &&
6158e1ce 421 (start > 0 || end + 1 < inode->disk_i_size))
26d30f85
AJ
422 btrfs_add_inode_defrag(NULL, inode);
423}
424
d352ac68 425/*
771ed689
CM
426 * we create compressed extents in two phases. The first
427 * phase compresses a range of pages that have already been
428 * locked (both pages and state bits are locked).
c8b97818 429 *
771ed689
CM
430 * This is done inside an ordered work queue, and the compression
431 * is spread across many cpus. The actual IO submission is step
432 * two, and the ordered work queue takes care of making sure that
433 * happens in the same order things were put onto the queue by
434 * writepages and friends.
c8b97818 435 *
771ed689
CM
436 * If this code finds it can't get good compression, it puts an
437 * entry onto the work queue to write the uncompressed bytes. This
438 * makes sure that both compressed inodes and uncompressed inodes
b2570314
AB
439 * are written in the same order that the flusher thread sent them
440 * down.
d352ac68 441 */
c44f649e 442static noinline void compress_file_range(struct inode *inode,
771ed689
CM
443 struct page *locked_page,
444 u64 start, u64 end,
b5326271 445 struct async_chunk *async_chunk,
771ed689 446 int *num_added)
b888db2b 447{
0b246afa 448 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
0b246afa 449 u64 blocksize = fs_info->sectorsize;
c8b97818 450 u64 actual_end;
e6dcd2dc 451 int ret = 0;
c8b97818
CM
452 struct page **pages = NULL;
453 unsigned long nr_pages;
c8b97818
CM
454 unsigned long total_compressed = 0;
455 unsigned long total_in = 0;
c8b97818
CM
456 int i;
457 int will_compress;
0b246afa 458 int compress_type = fs_info->compress_type;
4adaa611 459 int redirty = 0;
b888db2b 460
6158e1ce
NB
461 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
462 SZ_16K);
4cb5300b 463
62b37622 464 actual_end = min_t(u64, i_size_read(inode), end + 1);
c8b97818
CM
465again:
466 will_compress = 0;
09cbfeaf 467 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
069eac78
DS
468 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469 nr_pages = min_t(unsigned long, nr_pages,
470 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
be20aa9d 471
f03d9301
CM
472 /*
473 * we don't want to send crud past the end of i_size through
474 * compression, that's just a waste of CPU time. So, if the
475 * end of the file is before the start of our current
476 * requested range of bytes, we bail out to the uncompressed
477 * cleanup code that can deal with all of this.
478 *
479 * It isn't really the fastest way to fix things, but this is a
480 * very uncommon corner.
481 */
482 if (actual_end <= start)
483 goto cleanup_and_bail_uncompressed;
484
c8b97818
CM
485 total_compressed = actual_end - start;
486
4bcbb332
SW
487 /*
488 * skip compression for a small file range(<=blocksize) that
01327610 489 * isn't an inline extent, since it doesn't save disk space at all.
4bcbb332
SW
490 */
491 if (total_compressed <= blocksize &&
492 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493 goto cleanup_and_bail_uncompressed;
494
069eac78
DS
495 total_compressed = min_t(unsigned long, total_compressed,
496 BTRFS_MAX_UNCOMPRESSED);
c8b97818
CM
497 total_in = 0;
498 ret = 0;
db94535d 499
771ed689
CM
500 /*
501 * we do compression for mount -o compress and when the
502 * inode has not been flagged as nocompress. This flag can
503 * change at any time if we discover bad compression ratios.
c8b97818 504 */
c2fcdcdf 505 if (inode_need_compress(inode, start, end)) {
c8b97818 506 WARN_ON(pages);
31e818fe 507 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
560f7d75
LZ
508 if (!pages) {
509 /* just bail out to the uncompressed code */
3527a018 510 nr_pages = 0;
560f7d75
LZ
511 goto cont;
512 }
c8b97818 513
eec63c65
DS
514 if (BTRFS_I(inode)->defrag_compress)
515 compress_type = BTRFS_I(inode)->defrag_compress;
516 else if (BTRFS_I(inode)->prop_compress)
b52aa8c9 517 compress_type = BTRFS_I(inode)->prop_compress;
261507a0 518
4adaa611
CM
519 /*
520 * we need to call clear_page_dirty_for_io on each
521 * page in the range. Otherwise applications with the file
522 * mmap'd can wander in and change the page contents while
523 * we are compressing them.
524 *
525 * If the compression fails for any reason, we set the pages
526 * dirty again later on.
e9679de3
TT
527 *
528 * Note that the remaining part is redirtied, the start pointer
529 * has moved, the end is the original one.
4adaa611 530 */
e9679de3
TT
531 if (!redirty) {
532 extent_range_clear_dirty_for_io(inode, start, end);
533 redirty = 1;
534 }
f51d2b59
DS
535
536 /* Compression level is applied here and only here */
537 ret = btrfs_compress_pages(
538 compress_type | (fs_info->compress_level << 4),
261507a0 539 inode->i_mapping, start,
38c31464 540 pages,
4d3a800e 541 &nr_pages,
261507a0 542 &total_in,
e5d74902 543 &total_compressed);
c8b97818
CM
544
545 if (!ret) {
7073017a 546 unsigned long offset = offset_in_page(total_compressed);
4d3a800e 547 struct page *page = pages[nr_pages - 1];
c8b97818
CM
548 char *kaddr;
549
550 /* zero the tail end of the last page, we might be
551 * sending it down to disk
552 */
553 if (offset) {
7ac687d9 554 kaddr = kmap_atomic(page);
c8b97818 555 memset(kaddr + offset, 0,
09cbfeaf 556 PAGE_SIZE - offset);
7ac687d9 557 kunmap_atomic(kaddr);
c8b97818
CM
558 }
559 will_compress = 1;
560 }
561 }
560f7d75 562cont:
c8b97818
CM
563 if (start == 0) {
564 /* lets try to make an inline extent */
6018ba0a 565 if (ret || total_in < actual_end) {
c8b97818 566 /* we didn't compress the entire range, try
771ed689 567 * to make an uncompressed inline extent.
c8b97818 568 */
d02c0e20
NB
569 ret = cow_file_range_inline(inode, start, end, 0,
570 BTRFS_COMPRESS_NONE, NULL);
c8b97818 571 } else {
771ed689 572 /* try making a compressed inline extent */
d02c0e20 573 ret = cow_file_range_inline(inode, start, end,
fe3f566c
LZ
574 total_compressed,
575 compress_type, pages);
c8b97818 576 }
79787eaa 577 if (ret <= 0) {
151a41bc 578 unsigned long clear_flags = EXTENT_DELALLOC |
8b62f87b
JB
579 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580 EXTENT_DO_ACCOUNTING;
e6eb4314
FM
581 unsigned long page_error_op;
582
e6eb4314 583 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
151a41bc 584
771ed689 585 /*
79787eaa
JM
586 * inline extent creation worked or returned error,
587 * we don't need to create any more async work items.
588 * Unlock and free up our temp pages.
8b62f87b
JB
589 *
590 * We use DO_ACCOUNTING here because we need the
591 * delalloc_release_metadata to be done _after_ we drop
592 * our outstanding extent for clearing delalloc for this
593 * range.
771ed689 594 */
ba8b04c1
QW
595 extent_clear_unlock_delalloc(inode, start, end, end,
596 NULL, clear_flags,
597 PAGE_UNLOCK |
c2790a2e
JB
598 PAGE_CLEAR_DIRTY |
599 PAGE_SET_WRITEBACK |
e6eb4314 600 page_error_op |
c2790a2e 601 PAGE_END_WRITEBACK);
c8b97818
CM
602 goto free_pages_out;
603 }
604 }
605
606 if (will_compress) {
607 /*
608 * we aren't doing an inline extent round the compressed size
609 * up to a block size boundary so the allocator does sane
610 * things
611 */
fda2832f 612 total_compressed = ALIGN(total_compressed, blocksize);
c8b97818
CM
613
614 /*
615 * one last check to make sure the compression is really a
170607eb
TT
616 * win, compare the page count read with the blocks on disk,
617 * compression must free at least one sector size
c8b97818 618 */
09cbfeaf 619 total_in = ALIGN(total_in, PAGE_SIZE);
170607eb 620 if (total_compressed + blocksize <= total_in) {
c8bb0c8b
AS
621 *num_added += 1;
622
623 /*
624 * The async work queues will take care of doing actual
625 * allocation on disk for these compressed pages, and
626 * will submit them to the elevator.
627 */
b5326271 628 add_async_extent(async_chunk, start, total_in,
4d3a800e 629 total_compressed, pages, nr_pages,
c8bb0c8b
AS
630 compress_type);
631
1170862d
TT
632 if (start + total_in < end) {
633 start += total_in;
c8bb0c8b
AS
634 pages = NULL;
635 cond_resched();
636 goto again;
637 }
638 return;
c8b97818
CM
639 }
640 }
c8bb0c8b 641 if (pages) {
c8b97818
CM
642 /*
643 * the compression code ran but failed to make things smaller,
644 * free any pages it allocated and our page pointer array
645 */
4d3a800e 646 for (i = 0; i < nr_pages; i++) {
70b99e69 647 WARN_ON(pages[i]->mapping);
09cbfeaf 648 put_page(pages[i]);
c8b97818
CM
649 }
650 kfree(pages);
651 pages = NULL;
652 total_compressed = 0;
4d3a800e 653 nr_pages = 0;
c8b97818
CM
654
655 /* flag the file so we don't compress in the future */
0b246afa 656 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
b52aa8c9 657 !(BTRFS_I(inode)->prop_compress)) {
a555f810 658 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
1e701a32 659 }
c8b97818 660 }
f03d9301 661cleanup_and_bail_uncompressed:
c8bb0c8b
AS
662 /*
663 * No compression, but we still need to write the pages in the file
664 * we've been given so far. redirty the locked page if it corresponds
665 * to our extent and set things up for the async work queue to run
666 * cow_file_range to do the normal delalloc dance.
667 */
668 if (page_offset(locked_page) >= start &&
669 page_offset(locked_page) <= end)
670 __set_page_dirty_nobuffers(locked_page);
671 /* unlocked later on in the async handlers */
672
673 if (redirty)
674 extent_range_redirty_for_io(inode, start, end);
b5326271 675 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
c8bb0c8b
AS
676 BTRFS_COMPRESS_NONE);
677 *num_added += 1;
3b951516 678
c44f649e 679 return;
771ed689
CM
680
681free_pages_out:
4d3a800e 682 for (i = 0; i < nr_pages; i++) {
771ed689 683 WARN_ON(pages[i]->mapping);
09cbfeaf 684 put_page(pages[i]);
771ed689 685 }
d397712b 686 kfree(pages);
771ed689 687}
771ed689 688
40ae837b
FM
689static void free_async_extent_pages(struct async_extent *async_extent)
690{
691 int i;
692
693 if (!async_extent->pages)
694 return;
695
696 for (i = 0; i < async_extent->nr_pages; i++) {
697 WARN_ON(async_extent->pages[i]->mapping);
09cbfeaf 698 put_page(async_extent->pages[i]);
40ae837b
FM
699 }
700 kfree(async_extent->pages);
701 async_extent->nr_pages = 0;
702 async_extent->pages = NULL;
771ed689
CM
703}
704
705/*
706 * phase two of compressed writeback. This is the ordered portion
707 * of the code, which only gets called in the order the work was
708 * queued. We walk all the async extents created by compress_file_range
709 * and send them down to the disk.
710 */
b5326271 711static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
771ed689 712{
b5326271 713 struct inode *inode = async_chunk->inode;
0b246afa 714 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
771ed689
CM
715 struct async_extent *async_extent;
716 u64 alloc_hint = 0;
771ed689
CM
717 struct btrfs_key ins;
718 struct extent_map *em;
719 struct btrfs_root *root = BTRFS_I(inode)->root;
771ed689 720 struct extent_io_tree *io_tree;
f5a84ee3 721 int ret = 0;
771ed689 722
3e04e7f1 723again:
b5326271
NB
724 while (!list_empty(&async_chunk->extents)) {
725 async_extent = list_entry(async_chunk->extents.next,
771ed689
CM
726 struct async_extent, list);
727 list_del(&async_extent->list);
c8b97818 728
771ed689
CM
729 io_tree = &BTRFS_I(inode)->io_tree;
730
f5a84ee3 731retry:
771ed689
CM
732 /* did the compression code fall back to uncompressed IO? */
733 if (!async_extent->pages) {
734 int page_started = 0;
735 unsigned long nr_written = 0;
736
737 lock_extent(io_tree, async_extent->start,
2ac55d41 738 async_extent->start +
d0082371 739 async_extent->ram_size - 1);
771ed689
CM
740
741 /* allocate blocks */
b5326271 742 ret = cow_file_range(inode, async_chunk->locked_page,
f5a84ee3
JB
743 async_extent->start,
744 async_extent->start +
745 async_extent->ram_size - 1,
dda3245e
WX
746 async_extent->start +
747 async_extent->ram_size - 1,
748 &page_started, &nr_written, 0,
749 NULL);
771ed689 750
79787eaa
JM
751 /* JDM XXX */
752
771ed689
CM
753 /*
754 * if page_started, cow_file_range inserted an
755 * inline extent and took care of all the unlocking
756 * and IO for us. Otherwise, we need to submit
757 * all those pages down to the drive.
758 */
f5a84ee3 759 if (!page_started && !ret)
5e3ee236
NB
760 extent_write_locked_range(inode,
761 async_extent->start,
d397712b 762 async_extent->start +
771ed689 763 async_extent->ram_size - 1,
771ed689 764 WB_SYNC_ALL);
3e04e7f1 765 else if (ret)
b5326271 766 unlock_page(async_chunk->locked_page);
771ed689
CM
767 kfree(async_extent);
768 cond_resched();
769 continue;
770 }
771
772 lock_extent(io_tree, async_extent->start,
d0082371 773 async_extent->start + async_extent->ram_size - 1);
771ed689 774
18513091 775 ret = btrfs_reserve_extent(root, async_extent->ram_size,
771ed689
CM
776 async_extent->compressed_size,
777 async_extent->compressed_size,
e570fd27 778 0, alloc_hint, &ins, 1, 1);
f5a84ee3 779 if (ret) {
40ae837b 780 free_async_extent_pages(async_extent);
3e04e7f1 781
fdf8e2ea
JB
782 if (ret == -ENOSPC) {
783 unlock_extent(io_tree, async_extent->start,
784 async_extent->start +
785 async_extent->ram_size - 1);
ce62003f
LB
786
787 /*
788 * we need to redirty the pages if we decide to
789 * fallback to uncompressed IO, otherwise we
790 * will not submit these pages down to lower
791 * layers.
792 */
793 extent_range_redirty_for_io(inode,
794 async_extent->start,
795 async_extent->start +
796 async_extent->ram_size - 1);
797
79787eaa 798 goto retry;
fdf8e2ea 799 }
3e04e7f1 800 goto out_free;
f5a84ee3 801 }
c2167754
YZ
802 /*
803 * here we're doing allocation and writeback of the
804 * compressed pages
805 */
6f9994db
LB
806 em = create_io_em(inode, async_extent->start,
807 async_extent->ram_size, /* len */
808 async_extent->start, /* orig_start */
809 ins.objectid, /* block_start */
810 ins.offset, /* block_len */
811 ins.offset, /* orig_block_len */
812 async_extent->ram_size, /* ram_bytes */
813 async_extent->compress_type,
814 BTRFS_ORDERED_COMPRESSED);
815 if (IS_ERR(em))
816 /* ret value is not necessary due to void function */
3e04e7f1 817 goto out_free_reserve;
6f9994db 818 free_extent_map(em);
3e04e7f1 819
261507a0
LZ
820 ret = btrfs_add_ordered_extent_compress(inode,
821 async_extent->start,
822 ins.objectid,
823 async_extent->ram_size,
824 ins.offset,
825 BTRFS_ORDERED_COMPRESSED,
826 async_extent->compress_type);
d9f85963 827 if (ret) {
dcdbc059
NB
828 btrfs_drop_extent_cache(BTRFS_I(inode),
829 async_extent->start,
d9f85963
FM
830 async_extent->start +
831 async_extent->ram_size - 1, 0);
3e04e7f1 832 goto out_free_reserve;
d9f85963 833 }
0b246afa 834 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
771ed689 835
771ed689
CM
836 /*
837 * clear dirty, set writeback and unlock the pages.
838 */
c2790a2e 839 extent_clear_unlock_delalloc(inode, async_extent->start,
ba8b04c1
QW
840 async_extent->start +
841 async_extent->ram_size - 1,
a791e35e
CM
842 async_extent->start +
843 async_extent->ram_size - 1,
151a41bc
JB
844 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
c2790a2e 846 PAGE_SET_WRITEBACK);
4e4cbee9 847 if (btrfs_submit_compressed_write(inode,
d397712b
CM
848 async_extent->start,
849 async_extent->ram_size,
850 ins.objectid,
851 ins.offset, async_extent->pages,
f82b7359 852 async_extent->nr_pages,
b5326271 853 async_chunk->write_flags)) {
fce2a4e6
FM
854 struct page *p = async_extent->pages[0];
855 const u64 start = async_extent->start;
856 const u64 end = start + async_extent->ram_size - 1;
857
858 p->mapping = inode->i_mapping;
c629732d 859 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
7087a9d8 860
fce2a4e6 861 p->mapping = NULL;
ba8b04c1
QW
862 extent_clear_unlock_delalloc(inode, start, end, end,
863 NULL, 0,
fce2a4e6
FM
864 PAGE_END_WRITEBACK |
865 PAGE_SET_ERROR);
40ae837b 866 free_async_extent_pages(async_extent);
fce2a4e6 867 }
771ed689
CM
868 alloc_hint = ins.objectid + ins.offset;
869 kfree(async_extent);
870 cond_resched();
871 }
dec8f175 872 return;
3e04e7f1 873out_free_reserve:
0b246afa 874 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
2ff7e61e 875 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
79787eaa 876out_free:
c2790a2e 877 extent_clear_unlock_delalloc(inode, async_extent->start,
ba8b04c1
QW
878 async_extent->start +
879 async_extent->ram_size - 1,
3e04e7f1
JB
880 async_extent->start +
881 async_extent->ram_size - 1,
c2790a2e 882 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
a7e3b975 883 EXTENT_DELALLOC_NEW |
151a41bc
JB
884 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
885 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
704de49d
FM
886 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
887 PAGE_SET_ERROR);
40ae837b 888 free_async_extent_pages(async_extent);
79787eaa 889 kfree(async_extent);
3e04e7f1 890 goto again;
771ed689
CM
891}
892
4b46fce2
JB
893static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
894 u64 num_bytes)
895{
896 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
897 struct extent_map *em;
898 u64 alloc_hint = 0;
899
900 read_lock(&em_tree->lock);
901 em = search_extent_mapping(em_tree, start, num_bytes);
902 if (em) {
903 /*
904 * if block start isn't an actual block number then find the
905 * first block in this inode and use that as a hint. If that
906 * block is also bogus then just don't worry about it.
907 */
908 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
909 free_extent_map(em);
910 em = search_extent_mapping(em_tree, 0, 0);
911 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
912 alloc_hint = em->block_start;
913 if (em)
914 free_extent_map(em);
915 } else {
916 alloc_hint = em->block_start;
917 free_extent_map(em);
918 }
919 }
920 read_unlock(&em_tree->lock);
921
922 return alloc_hint;
923}
924
771ed689
CM
925/*
926 * when extent_io.c finds a delayed allocation range in the file,
927 * the call backs end up in this code. The basic idea is to
928 * allocate extents on disk for the range, and create ordered data structs
929 * in ram to track those extents.
930 *
931 * locked_page is the page that writepage had locked already. We use
932 * it to make sure we don't do extra locks or unlocks.
933 *
934 * *page_started is set to one if we unlock locked_page and do everything
935 * required to start IO on it. It may be clean and already done with
936 * IO when we return.
937 */
00361589
JB
938static noinline int cow_file_range(struct inode *inode,
939 struct page *locked_page,
dda3245e
WX
940 u64 start, u64 end, u64 delalloc_end,
941 int *page_started, unsigned long *nr_written,
942 int unlock, struct btrfs_dedupe_hash *hash)
771ed689 943{
0b246afa 944 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
00361589 945 struct btrfs_root *root = BTRFS_I(inode)->root;
771ed689
CM
946 u64 alloc_hint = 0;
947 u64 num_bytes;
948 unsigned long ram_size;
a315e68f 949 u64 cur_alloc_size = 0;
0b246afa 950 u64 blocksize = fs_info->sectorsize;
771ed689
CM
951 struct btrfs_key ins;
952 struct extent_map *em;
a315e68f
FM
953 unsigned clear_bits;
954 unsigned long page_ops;
955 bool extent_reserved = false;
771ed689
CM
956 int ret = 0;
957
70ddc553 958 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
02ecd2c2 959 WARN_ON_ONCE(1);
29bce2f3
JB
960 ret = -EINVAL;
961 goto out_unlock;
02ecd2c2 962 }
771ed689 963
fda2832f 964 num_bytes = ALIGN(end - start + 1, blocksize);
771ed689 965 num_bytes = max(blocksize, num_bytes);
566b1760 966 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
771ed689 967
6158e1ce 968 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
4cb5300b 969
771ed689
CM
970 if (start == 0) {
971 /* lets try to make an inline extent */
d02c0e20
NB
972 ret = cow_file_range_inline(inode, start, end, 0,
973 BTRFS_COMPRESS_NONE, NULL);
771ed689 974 if (ret == 0) {
8b62f87b
JB
975 /*
976 * We use DO_ACCOUNTING here because we need the
977 * delalloc_release_metadata to be run _after_ we drop
978 * our outstanding extent for clearing delalloc for this
979 * range.
980 */
ba8b04c1
QW
981 extent_clear_unlock_delalloc(inode, start, end,
982 delalloc_end, NULL,
c2790a2e 983 EXTENT_LOCKED | EXTENT_DELALLOC |
8b62f87b
JB
984 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
985 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
c2790a2e
JB
986 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
987 PAGE_END_WRITEBACK);
771ed689 988 *nr_written = *nr_written +
09cbfeaf 989 (end - start + PAGE_SIZE) / PAGE_SIZE;
771ed689 990 *page_started = 1;
771ed689 991 goto out;
79787eaa 992 } else if (ret < 0) {
79787eaa 993 goto out_unlock;
771ed689
CM
994 }
995 }
996
4b46fce2 997 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
dcdbc059
NB
998 btrfs_drop_extent_cache(BTRFS_I(inode), start,
999 start + num_bytes - 1, 0);
771ed689 1000
3752d22f
AJ
1001 while (num_bytes > 0) {
1002 cur_alloc_size = num_bytes;
18513091 1003 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
0b246afa 1004 fs_info->sectorsize, 0, alloc_hint,
e570fd27 1005 &ins, 1, 1);
00361589 1006 if (ret < 0)
79787eaa 1007 goto out_unlock;
a315e68f
FM
1008 cur_alloc_size = ins.offset;
1009 extent_reserved = true;
d397712b 1010
771ed689 1011 ram_size = ins.offset;
6f9994db
LB
1012 em = create_io_em(inode, start, ins.offset, /* len */
1013 start, /* orig_start */
1014 ins.objectid, /* block_start */
1015 ins.offset, /* block_len */
1016 ins.offset, /* orig_block_len */
1017 ram_size, /* ram_bytes */
1018 BTRFS_COMPRESS_NONE, /* compress_type */
1af4a0aa 1019 BTRFS_ORDERED_REGULAR /* type */);
090a127a
SY
1020 if (IS_ERR(em)) {
1021 ret = PTR_ERR(em);
ace68bac 1022 goto out_reserve;
090a127a 1023 }
6f9994db 1024 free_extent_map(em);
e6dcd2dc 1025
e6dcd2dc 1026 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 1027 ram_size, cur_alloc_size, 0);
ace68bac 1028 if (ret)
d9f85963 1029 goto out_drop_extent_cache;
c8b97818 1030
17d217fe
YZ
1031 if (root->root_key.objectid ==
1032 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1033 ret = btrfs_reloc_clone_csums(inode, start,
1034 cur_alloc_size);
4dbd80fb
QW
1035 /*
1036 * Only drop cache here, and process as normal.
1037 *
1038 * We must not allow extent_clear_unlock_delalloc()
1039 * at out_unlock label to free meta of this ordered
1040 * extent, as its meta should be freed by
1041 * btrfs_finish_ordered_io().
1042 *
1043 * So we must continue until @start is increased to
1044 * skip current ordered extent.
1045 */
00361589 1046 if (ret)
4dbd80fb
QW
1047 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1048 start + ram_size - 1, 0);
17d217fe
YZ
1049 }
1050
0b246afa 1051 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9cfa3e34 1052
c8b97818
CM
1053 /* we're not doing compressed IO, don't unlock the first
1054 * page (which the caller expects to stay locked), don't
1055 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
1056 *
1057 * Do set the Private2 bit so we know this page was properly
1058 * setup for writepage
c8b97818 1059 */
a315e68f
FM
1060 page_ops = unlock ? PAGE_UNLOCK : 0;
1061 page_ops |= PAGE_SET_PRIVATE2;
a791e35e 1062
c2790a2e 1063 extent_clear_unlock_delalloc(inode, start,
ba8b04c1
QW
1064 start + ram_size - 1,
1065 delalloc_end, locked_page,
c2790a2e 1066 EXTENT_LOCKED | EXTENT_DELALLOC,
a315e68f 1067 page_ops);
3752d22f
AJ
1068 if (num_bytes < cur_alloc_size)
1069 num_bytes = 0;
4dbd80fb 1070 else
3752d22f 1071 num_bytes -= cur_alloc_size;
c59f8951
CM
1072 alloc_hint = ins.objectid + ins.offset;
1073 start += cur_alloc_size;
a315e68f 1074 extent_reserved = false;
4dbd80fb
QW
1075
1076 /*
1077 * btrfs_reloc_clone_csums() error, since start is increased
1078 * extent_clear_unlock_delalloc() at out_unlock label won't
1079 * free metadata of current ordered extent, we're OK to exit.
1080 */
1081 if (ret)
1082 goto out_unlock;
b888db2b 1083 }
79787eaa 1084out:
be20aa9d 1085 return ret;
b7d5b0a8 1086
d9f85963 1087out_drop_extent_cache:
dcdbc059 1088 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
ace68bac 1089out_reserve:
0b246afa 1090 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
2ff7e61e 1091 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
79787eaa 1092out_unlock:
a7e3b975
FM
1093 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1094 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
a315e68f
FM
1095 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1096 PAGE_END_WRITEBACK;
1097 /*
1098 * If we reserved an extent for our delalloc range (or a subrange) and
1099 * failed to create the respective ordered extent, then it means that
1100 * when we reserved the extent we decremented the extent's size from
1101 * the data space_info's bytes_may_use counter and incremented the
1102 * space_info's bytes_reserved counter by the same amount. We must make
1103 * sure extent_clear_unlock_delalloc() does not try to decrement again
1104 * the data space_info's bytes_may_use counter, therefore we do not pass
1105 * it the flag EXTENT_CLEAR_DATA_RESV.
1106 */
1107 if (extent_reserved) {
1108 extent_clear_unlock_delalloc(inode, start,
1109 start + cur_alloc_size,
1110 start + cur_alloc_size,
1111 locked_page,
1112 clear_bits,
1113 page_ops);
1114 start += cur_alloc_size;
1115 if (start >= end)
1116 goto out;
1117 }
ba8b04c1
QW
1118 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1119 locked_page,
a315e68f
FM
1120 clear_bits | EXTENT_CLEAR_DATA_RESV,
1121 page_ops);
79787eaa 1122 goto out;
771ed689 1123}
c8b97818 1124
771ed689
CM
1125/*
1126 * work queue call back to started compression on a file and pages
1127 */
1128static noinline void async_cow_start(struct btrfs_work *work)
1129{
b5326271 1130 struct async_chunk *async_chunk;
771ed689 1131 int num_added = 0;
97db1204 1132
b5326271 1133 async_chunk = container_of(work, struct async_chunk, work);
771ed689 1134
b5326271
NB
1135 compress_file_range(async_chunk->inode, async_chunk->locked_page,
1136 async_chunk->start, async_chunk->end, async_chunk,
771ed689 1137 &num_added);
8180ef88 1138 if (num_added == 0) {
b5326271
NB
1139 btrfs_add_delayed_iput(async_chunk->inode);
1140 async_chunk->inode = NULL;
8180ef88 1141 }
771ed689
CM
1142}
1143
1144/*
1145 * work queue call back to submit previously compressed pages
1146 */
1147static noinline void async_cow_submit(struct btrfs_work *work)
1148{
c5a68aec
NB
1149 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1150 work);
1151 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
771ed689
CM
1152 unsigned long nr_pages;
1153
b5326271 1154 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
09cbfeaf 1155 PAGE_SHIFT;
771ed689 1156
093258e6 1157 /* atomic_sub_return implies a barrier */
0b246afa 1158 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
093258e6
DS
1159 5 * SZ_1M)
1160 cond_wake_up_nomb(&fs_info->async_submit_wait);
771ed689 1161
4546d178 1162 /*
b5326271 1163 * ->inode could be NULL if async_chunk_start has failed to compress,
4546d178
NB
1164 * in which case we don't have anything to submit, yet we need to
1165 * always adjust ->async_delalloc_pages as its paired with the init
1166 * happening in cow_file_range_async
1167 */
b5326271
NB
1168 if (async_chunk->inode)
1169 submit_compressed_extents(async_chunk);
771ed689 1170}
c8b97818 1171
771ed689
CM
1172static noinline void async_cow_free(struct btrfs_work *work)
1173{
b5326271 1174 struct async_chunk *async_chunk;
97db1204 1175
b5326271
NB
1176 async_chunk = container_of(work, struct async_chunk, work);
1177 if (async_chunk->inode)
1178 btrfs_add_delayed_iput(async_chunk->inode);
97db1204
NB
1179 /*
1180 * Since the pointer to 'pending' is at the beginning of the array of
b5326271 1181 * async_chunk's, freeing it ensures the whole array has been freed.
97db1204 1182 */
b5326271
NB
1183 if (atomic_dec_and_test(async_chunk->pending))
1184 kfree(async_chunk->pending);
771ed689
CM
1185}
1186
1187static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1188 u64 start, u64 end, int *page_started,
f82b7359
LB
1189 unsigned long *nr_written,
1190 unsigned int write_flags)
771ed689 1191{
0b246afa 1192 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
97db1204
NB
1193 struct async_cow *ctx;
1194 struct async_chunk *async_chunk;
771ed689
CM
1195 unsigned long nr_pages;
1196 u64 cur_end;
97db1204
NB
1197 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1198 int i;
1199 bool should_compress;
771ed689 1200
a3429ab7 1201 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
ae0f1625 1202 1, 0, NULL);
97db1204
NB
1203
1204 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1205 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1206 num_chunks = 1;
1207 should_compress = false;
1208 } else {
1209 should_compress = true;
1210 }
1211
1212 ctx = kmalloc(struct_size(ctx, chunks, num_chunks), GFP_NOFS);
1213 if (!ctx) {
1214 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1215 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1216 EXTENT_DO_ACCOUNTING;
1217 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1218 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1219 PAGE_SET_ERROR;
1220
1221 extent_clear_unlock_delalloc(inode, start, end, 0, locked_page,
1222 clear_bits, page_ops);
1223 return -ENOMEM;
1224 }
1225
1226 async_chunk = ctx->chunks;
1227 atomic_set(&ctx->num_chunks, num_chunks);
1228
1229 for (i = 0; i < num_chunks; i++) {
1230 if (should_compress)
1231 cur_end = min(end, start + SZ_512K - 1);
1232 else
1233 cur_end = end;
1234
bd4691a0
NB
1235 /*
1236 * igrab is called higher up in the call chain, take only the
1237 * lightweight reference for the callback lifetime
1238 */
1239 ihold(inode);
97db1204
NB
1240 async_chunk[i].pending = &ctx->num_chunks;
1241 async_chunk[i].inode = inode;
1242 async_chunk[i].start = start;
1243 async_chunk[i].end = cur_end;
97db1204
NB
1244 async_chunk[i].locked_page = locked_page;
1245 async_chunk[i].write_flags = write_flags;
1246 INIT_LIST_HEAD(&async_chunk[i].extents);
1247
1248 btrfs_init_work(&async_chunk[i].work,
9e0af237
LB
1249 btrfs_delalloc_helper,
1250 async_cow_start, async_cow_submit,
1251 async_cow_free);
771ed689 1252
97db1204 1253 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
0b246afa 1254 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
771ed689 1255
97db1204 1256 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
771ed689 1257
771ed689
CM
1258 *nr_written += nr_pages;
1259 start = cur_end + 1;
1260 }
1261 *page_started = 1;
1262 return 0;
be20aa9d
CM
1263}
1264
2ff7e61e 1265static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
17d217fe
YZ
1266 u64 bytenr, u64 num_bytes)
1267{
1268 int ret;
1269 struct btrfs_ordered_sum *sums;
1270 LIST_HEAD(list);
1271
0b246afa 1272 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
a2de733c 1273 bytenr + num_bytes - 1, &list, 0);
17d217fe
YZ
1274 if (ret == 0 && list_empty(&list))
1275 return 0;
1276
1277 while (!list_empty(&list)) {
1278 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1279 list_del(&sums->list);
1280 kfree(sums);
1281 }
58113753
LB
1282 if (ret < 0)
1283 return ret;
17d217fe
YZ
1284 return 1;
1285}
1286
d352ac68
CM
1287/*
1288 * when nowcow writeback call back. This checks for snapshots or COW copies
1289 * of the extents that exist in the file, and COWs the file as required.
1290 *
1291 * If no cow copies or snapshots exist, we write directly to the existing
1292 * blocks on disk
1293 */
7f366cfe
CM
1294static noinline int run_delalloc_nocow(struct inode *inode,
1295 struct page *locked_page,
771ed689
CM
1296 u64 start, u64 end, int *page_started, int force,
1297 unsigned long *nr_written)
be20aa9d 1298{
0b246afa 1299 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
be20aa9d
CM
1300 struct btrfs_root *root = BTRFS_I(inode)->root;
1301 struct extent_buffer *leaf;
be20aa9d 1302 struct btrfs_path *path;
80ff3856 1303 struct btrfs_file_extent_item *fi;
be20aa9d 1304 struct btrfs_key found_key;
6f9994db 1305 struct extent_map *em;
80ff3856
YZ
1306 u64 cow_start;
1307 u64 cur_offset;
1308 u64 extent_end;
5d4f98a2 1309 u64 extent_offset;
80ff3856
YZ
1310 u64 disk_bytenr;
1311 u64 num_bytes;
b4939680 1312 u64 disk_num_bytes;
cc95bef6 1313 u64 ram_bytes;
80ff3856 1314 int extent_type;
8ecebf4d 1315 int ret;
d899e052 1316 int type;
80ff3856
YZ
1317 int nocow;
1318 int check_prev = 1;
82d5902d 1319 bool nolock;
4a0cc7ca 1320 u64 ino = btrfs_ino(BTRFS_I(inode));
be20aa9d
CM
1321
1322 path = btrfs_alloc_path();
17ca04af 1323 if (!path) {
ba8b04c1
QW
1324 extent_clear_unlock_delalloc(inode, start, end, end,
1325 locked_page,
c2790a2e 1326 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
1327 EXTENT_DO_ACCOUNTING |
1328 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
1329 PAGE_CLEAR_DIRTY |
1330 PAGE_SET_WRITEBACK |
1331 PAGE_END_WRITEBACK);
d8926bb3 1332 return -ENOMEM;
17ca04af 1333 }
82d5902d 1334
70ddc553 1335 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
82d5902d 1336
80ff3856
YZ
1337 cow_start = (u64)-1;
1338 cur_offset = start;
1339 while (1) {
e4c3b2dc 1340 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
80ff3856 1341 cur_offset, 0);
d788a349 1342 if (ret < 0)
79787eaa 1343 goto error;
80ff3856
YZ
1344 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1345 leaf = path->nodes[0];
1346 btrfs_item_key_to_cpu(leaf, &found_key,
1347 path->slots[0] - 1);
33345d01 1348 if (found_key.objectid == ino &&
80ff3856
YZ
1349 found_key.type == BTRFS_EXTENT_DATA_KEY)
1350 path->slots[0]--;
1351 }
1352 check_prev = 0;
1353next_slot:
1354 leaf = path->nodes[0];
1355 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1356 ret = btrfs_next_leaf(root, path);
e8916699
LB
1357 if (ret < 0) {
1358 if (cow_start != (u64)-1)
1359 cur_offset = cow_start;
79787eaa 1360 goto error;
e8916699 1361 }
80ff3856
YZ
1362 if (ret > 0)
1363 break;
1364 leaf = path->nodes[0];
1365 }
be20aa9d 1366
80ff3856
YZ
1367 nocow = 0;
1368 disk_bytenr = 0;
17d217fe 1369 num_bytes = 0;
80ff3856
YZ
1370 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1371
1d512cb7
FM
1372 if (found_key.objectid > ino)
1373 break;
1374 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1375 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1376 path->slots[0]++;
1377 goto next_slot;
1378 }
1379 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
80ff3856
YZ
1380 found_key.offset > end)
1381 break;
1382
1383 if (found_key.offset > cur_offset) {
1384 extent_end = found_key.offset;
e9061e21 1385 extent_type = 0;
80ff3856
YZ
1386 goto out_check;
1387 }
1388
1389 fi = btrfs_item_ptr(leaf, path->slots[0],
1390 struct btrfs_file_extent_item);
1391 extent_type = btrfs_file_extent_type(leaf, fi);
1392
cc95bef6 1393 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
d899e052
YZ
1394 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1395 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1396 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1397 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1398 extent_end = found_key.offset +
1399 btrfs_file_extent_num_bytes(leaf, fi);
b4939680
JB
1400 disk_num_bytes =
1401 btrfs_file_extent_disk_num_bytes(leaf, fi);
80ff3856
YZ
1402 if (extent_end <= start) {
1403 path->slots[0]++;
1404 goto next_slot;
1405 }
17d217fe
YZ
1406 if (disk_bytenr == 0)
1407 goto out_check;
80ff3856
YZ
1408 if (btrfs_file_extent_compression(leaf, fi) ||
1409 btrfs_file_extent_encryption(leaf, fi) ||
1410 btrfs_file_extent_other_encoding(leaf, fi))
1411 goto out_check;
78d4295b
EL
1412 /*
1413 * Do the same check as in btrfs_cross_ref_exist but
1414 * without the unnecessary search.
1415 */
27a7ff55
LF
1416 if (!nolock &&
1417 btrfs_file_extent_generation(leaf, fi) <=
78d4295b
EL
1418 btrfs_root_last_snapshot(&root->root_item))
1419 goto out_check;
d899e052
YZ
1420 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1421 goto out_check;
2ff7e61e 1422 if (btrfs_extent_readonly(fs_info, disk_bytenr))
80ff3856 1423 goto out_check;
58113753
LB
1424 ret = btrfs_cross_ref_exist(root, ino,
1425 found_key.offset -
1426 extent_offset, disk_bytenr);
1427 if (ret) {
1428 /*
1429 * ret could be -EIO if the above fails to read
1430 * metadata.
1431 */
1432 if (ret < 0) {
1433 if (cow_start != (u64)-1)
1434 cur_offset = cow_start;
1435 goto error;
1436 }
1437
1438 WARN_ON_ONCE(nolock);
17d217fe 1439 goto out_check;
58113753 1440 }
5d4f98a2 1441 disk_bytenr += extent_offset;
17d217fe
YZ
1442 disk_bytenr += cur_offset - found_key.offset;
1443 num_bytes = min(end + 1, extent_end) - cur_offset;
e9894fd3
WS
1444 /*
1445 * if there are pending snapshots for this root,
1446 * we fall into common COW way.
1447 */
8ecebf4d
RK
1448 if (!nolock && atomic_read(&root->snapshot_force_cow))
1449 goto out_check;
17d217fe
YZ
1450 /*
1451 * force cow if csum exists in the range.
1452 * this ensure that csum for a given extent are
1453 * either valid or do not exist.
1454 */
58113753
LB
1455 ret = csum_exist_in_range(fs_info, disk_bytenr,
1456 num_bytes);
1457 if (ret) {
58113753
LB
1458 /*
1459 * ret could be -EIO if the above fails to read
1460 * metadata.
1461 */
1462 if (ret < 0) {
1463 if (cow_start != (u64)-1)
1464 cur_offset = cow_start;
1465 goto error;
1466 }
1467 WARN_ON_ONCE(nolock);
17d217fe 1468 goto out_check;
91e1f56a 1469 }
8ecebf4d 1470 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
f78c436c 1471 goto out_check;
80ff3856
YZ
1472 nocow = 1;
1473 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1474 extent_end = found_key.offset +
e41ca589 1475 btrfs_file_extent_ram_bytes(leaf, fi);
da17066c 1476 extent_end = ALIGN(extent_end,
0b246afa 1477 fs_info->sectorsize);
80ff3856 1478 } else {
290342f6 1479 BUG();
80ff3856
YZ
1480 }
1481out_check:
1482 if (extent_end <= start) {
1483 path->slots[0]++;
f78c436c 1484 if (nocow)
0b246afa 1485 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
80ff3856
YZ
1486 goto next_slot;
1487 }
1488 if (!nocow) {
1489 if (cow_start == (u64)-1)
1490 cow_start = cur_offset;
1491 cur_offset = extent_end;
1492 if (cur_offset > end)
1493 break;
1494 path->slots[0]++;
1495 goto next_slot;
7ea394f1
YZ
1496 }
1497
b3b4aa74 1498 btrfs_release_path(path);
80ff3856 1499 if (cow_start != (u64)-1) {
00361589
JB
1500 ret = cow_file_range(inode, locked_page,
1501 cow_start, found_key.offset - 1,
dda3245e
WX
1502 end, page_started, nr_written, 1,
1503 NULL);
e9894fd3 1504 if (ret) {
f78c436c 1505 if (nocow)
0b246afa 1506 btrfs_dec_nocow_writers(fs_info,
f78c436c 1507 disk_bytenr);
79787eaa 1508 goto error;
e9894fd3 1509 }
80ff3856 1510 cow_start = (u64)-1;
7ea394f1 1511 }
80ff3856 1512
d899e052 1513 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6f9994db
LB
1514 u64 orig_start = found_key.offset - extent_offset;
1515
1516 em = create_io_em(inode, cur_offset, num_bytes,
1517 orig_start,
1518 disk_bytenr, /* block_start */
1519 num_bytes, /* block_len */
1520 disk_num_bytes, /* orig_block_len */
1521 ram_bytes, BTRFS_COMPRESS_NONE,
1522 BTRFS_ORDERED_PREALLOC);
1523 if (IS_ERR(em)) {
6f9994db
LB
1524 if (nocow)
1525 btrfs_dec_nocow_writers(fs_info,
1526 disk_bytenr);
1527 ret = PTR_ERR(em);
1528 goto error;
d899e052 1529 }
6f9994db
LB
1530 free_extent_map(em);
1531 }
1532
1533 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
d899e052
YZ
1534 type = BTRFS_ORDERED_PREALLOC;
1535 } else {
1536 type = BTRFS_ORDERED_NOCOW;
1537 }
80ff3856
YZ
1538
1539 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052 1540 num_bytes, num_bytes, type);
f78c436c 1541 if (nocow)
0b246afa 1542 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
79787eaa 1543 BUG_ON(ret); /* -ENOMEM */
771ed689 1544
efa56464 1545 if (root->root_key.objectid ==
4dbd80fb
QW
1546 BTRFS_DATA_RELOC_TREE_OBJECTID)
1547 /*
1548 * Error handled later, as we must prevent
1549 * extent_clear_unlock_delalloc() in error handler
1550 * from freeing metadata of created ordered extent.
1551 */
efa56464
YZ
1552 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1553 num_bytes);
efa56464 1554
c2790a2e 1555 extent_clear_unlock_delalloc(inode, cur_offset,
ba8b04c1 1556 cur_offset + num_bytes - 1, end,
c2790a2e 1557 locked_page, EXTENT_LOCKED |
18513091
WX
1558 EXTENT_DELALLOC |
1559 EXTENT_CLEAR_DATA_RESV,
1560 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1561
80ff3856 1562 cur_offset = extent_end;
4dbd80fb
QW
1563
1564 /*
1565 * btrfs_reloc_clone_csums() error, now we're OK to call error
1566 * handler, as metadata for created ordered extent will only
1567 * be freed by btrfs_finish_ordered_io().
1568 */
1569 if (ret)
1570 goto error;
80ff3856
YZ
1571 if (cur_offset > end)
1572 break;
be20aa9d 1573 }
b3b4aa74 1574 btrfs_release_path(path);
80ff3856 1575
506481b2 1576 if (cur_offset <= end && cow_start == (u64)-1)
80ff3856 1577 cow_start = cur_offset;
17ca04af 1578
80ff3856 1579 if (cow_start != (u64)-1) {
506481b2 1580 cur_offset = end;
dda3245e
WX
1581 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1582 page_started, nr_written, 1, NULL);
d788a349 1583 if (ret)
79787eaa 1584 goto error;
80ff3856
YZ
1585 }
1586
79787eaa 1587error:
17ca04af 1588 if (ret && cur_offset < end)
ba8b04c1 1589 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
c2790a2e 1590 locked_page, EXTENT_LOCKED |
151a41bc
JB
1591 EXTENT_DELALLOC | EXTENT_DEFRAG |
1592 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1593 PAGE_CLEAR_DIRTY |
c2790a2e
JB
1594 PAGE_SET_WRITEBACK |
1595 PAGE_END_WRITEBACK);
7ea394f1 1596 btrfs_free_path(path);
79787eaa 1597 return ret;
be20aa9d
CM
1598}
1599
47059d93
WS
1600static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1601{
1602
1603 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1604 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1605 return 0;
1606
1607 /*
1608 * @defrag_bytes is a hint value, no spinlock held here,
1609 * if is not zero, it means the file is defragging.
1610 * Force cow if given extent needs to be defragged.
1611 */
1612 if (BTRFS_I(inode)->defrag_bytes &&
1613 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1614 EXTENT_DEFRAG, 0, NULL))
1615 return 1;
1616
1617 return 0;
1618}
1619
d352ac68 1620/*
5eaad97a
NB
1621 * Function to process delayed allocation (create CoW) for ranges which are
1622 * being touched for the first time.
d352ac68 1623 */
bc9a8bf7 1624int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
5eaad97a
NB
1625 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1626 struct writeback_control *wbc)
be20aa9d 1627{
be20aa9d 1628 int ret;
47059d93 1629 int force_cow = need_force_cow(inode, start, end);
f82b7359 1630 unsigned int write_flags = wbc_to_write_flags(wbc);
a2135011 1631
47059d93 1632 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
c8b97818 1633 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1634 page_started, 1, nr_written);
47059d93 1635 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
d899e052 1636 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1637 page_started, 0, nr_written);
c2fcdcdf 1638 } else if (!inode_need_compress(inode, start, end)) {
dda3245e
WX
1639 ret = cow_file_range(inode, locked_page, start, end, end,
1640 page_started, nr_written, 1, NULL);
7ddf5a42
JB
1641 } else {
1642 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1643 &BTRFS_I(inode)->runtime_flags);
771ed689 1644 ret = cow_file_range_async(inode, locked_page, start, end,
f82b7359
LB
1645 page_started, nr_written,
1646 write_flags);
7ddf5a42 1647 }
52427260 1648 if (ret)
d1051d6e
NB
1649 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1650 end - start + 1);
b888db2b
CM
1651 return ret;
1652}
1653
abbb55f4
NB
1654void btrfs_split_delalloc_extent(struct inode *inode,
1655 struct extent_state *orig, u64 split)
9ed74f2d 1656{
dcab6a3b
JB
1657 u64 size;
1658
0ca1f7ce 1659 /* not delalloc, ignore it */
9ed74f2d 1660 if (!(orig->state & EXTENT_DELALLOC))
1bf85046 1661 return;
9ed74f2d 1662
dcab6a3b
JB
1663 size = orig->end - orig->start + 1;
1664 if (size > BTRFS_MAX_EXTENT_SIZE) {
823bb20a 1665 u32 num_extents;
dcab6a3b
JB
1666 u64 new_size;
1667
1668 /*
5c848198 1669 * See the explanation in btrfs_merge_delalloc_extent, the same
ba117213 1670 * applies here, just in reverse.
dcab6a3b
JB
1671 */
1672 new_size = orig->end - split + 1;
823bb20a 1673 num_extents = count_max_extents(new_size);
ba117213 1674 new_size = split - orig->start;
823bb20a
DS
1675 num_extents += count_max_extents(new_size);
1676 if (count_max_extents(size) >= num_extents)
dcab6a3b
JB
1677 return;
1678 }
1679
9e0baf60 1680 spin_lock(&BTRFS_I(inode)->lock);
8b62f87b 1681 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
9e0baf60 1682 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1683}
1684
1685/*
5c848198
NB
1686 * Handle merged delayed allocation extents so we can keep track of new extents
1687 * that are just merged onto old extents, such as when we are doing sequential
1688 * writes, so we can properly account for the metadata space we'll need.
9ed74f2d 1689 */
5c848198
NB
1690void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1691 struct extent_state *other)
9ed74f2d 1692{
dcab6a3b 1693 u64 new_size, old_size;
823bb20a 1694 u32 num_extents;
dcab6a3b 1695
9ed74f2d
JB
1696 /* not delalloc, ignore it */
1697 if (!(other->state & EXTENT_DELALLOC))
1bf85046 1698 return;
9ed74f2d 1699
8461a3de
JB
1700 if (new->start > other->start)
1701 new_size = new->end - other->start + 1;
1702 else
1703 new_size = other->end - new->start + 1;
dcab6a3b
JB
1704
1705 /* we're not bigger than the max, unreserve the space and go */
1706 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1707 spin_lock(&BTRFS_I(inode)->lock);
8b62f87b 1708 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
dcab6a3b
JB
1709 spin_unlock(&BTRFS_I(inode)->lock);
1710 return;
1711 }
1712
1713 /*
ba117213
JB
1714 * We have to add up either side to figure out how many extents were
1715 * accounted for before we merged into one big extent. If the number of
1716 * extents we accounted for is <= the amount we need for the new range
1717 * then we can return, otherwise drop. Think of it like this
1718 *
1719 * [ 4k][MAX_SIZE]
1720 *
1721 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1722 * need 2 outstanding extents, on one side we have 1 and the other side
1723 * we have 1 so they are == and we can return. But in this case
1724 *
1725 * [MAX_SIZE+4k][MAX_SIZE+4k]
1726 *
1727 * Each range on their own accounts for 2 extents, but merged together
1728 * they are only 3 extents worth of accounting, so we need to drop in
1729 * this case.
dcab6a3b 1730 */
ba117213 1731 old_size = other->end - other->start + 1;
823bb20a 1732 num_extents = count_max_extents(old_size);
ba117213 1733 old_size = new->end - new->start + 1;
823bb20a
DS
1734 num_extents += count_max_extents(old_size);
1735 if (count_max_extents(new_size) >= num_extents)
dcab6a3b
JB
1736 return;
1737
9e0baf60 1738 spin_lock(&BTRFS_I(inode)->lock);
8b62f87b 1739 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
9e0baf60 1740 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1741}
1742
eb73c1b7
MX
1743static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1744 struct inode *inode)
1745{
0b246afa
JM
1746 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1747
eb73c1b7
MX
1748 spin_lock(&root->delalloc_lock);
1749 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1750 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1751 &root->delalloc_inodes);
1752 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1753 &BTRFS_I(inode)->runtime_flags);
1754 root->nr_delalloc_inodes++;
1755 if (root->nr_delalloc_inodes == 1) {
0b246afa 1756 spin_lock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1757 BUG_ON(!list_empty(&root->delalloc_root));
1758 list_add_tail(&root->delalloc_root,
0b246afa
JM
1759 &fs_info->delalloc_roots);
1760 spin_unlock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1761 }
1762 }
1763 spin_unlock(&root->delalloc_lock);
1764}
1765
2b877331
NB
1766
1767void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1768 struct btrfs_inode *inode)
eb73c1b7 1769{
3ffbd68c 1770 struct btrfs_fs_info *fs_info = root->fs_info;
0b246afa 1771
9e3e97f4
NB
1772 if (!list_empty(&inode->delalloc_inodes)) {
1773 list_del_init(&inode->delalloc_inodes);
eb73c1b7 1774 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
9e3e97f4 1775 &inode->runtime_flags);
eb73c1b7
MX
1776 root->nr_delalloc_inodes--;
1777 if (!root->nr_delalloc_inodes) {
7c8a0d36 1778 ASSERT(list_empty(&root->delalloc_inodes));
0b246afa 1779 spin_lock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1780 BUG_ON(list_empty(&root->delalloc_root));
1781 list_del_init(&root->delalloc_root);
0b246afa 1782 spin_unlock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1783 }
1784 }
2b877331
NB
1785}
1786
1787static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1788 struct btrfs_inode *inode)
1789{
1790 spin_lock(&root->delalloc_lock);
1791 __btrfs_del_delalloc_inode(root, inode);
eb73c1b7
MX
1792 spin_unlock(&root->delalloc_lock);
1793}
1794
d352ac68 1795/*
e06a1fc9
NB
1796 * Properly track delayed allocation bytes in the inode and to maintain the
1797 * list of inodes that have pending delalloc work to be done.
d352ac68 1798 */
e06a1fc9
NB
1799void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1800 unsigned *bits)
291d673e 1801{
0b246afa
JM
1802 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1803
47059d93
WS
1804 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1805 WARN_ON(1);
75eff68e
CM
1806 /*
1807 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1808 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1809 * bit, which is only set or cleared with irqs on
1810 */
0ca1f7ce 1811 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1812 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1813 u64 len = state->end + 1 - state->start;
8b62f87b 1814 u32 num_extents = count_max_extents(len);
70ddc553 1815 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
9ed74f2d 1816
8b62f87b
JB
1817 spin_lock(&BTRFS_I(inode)->lock);
1818 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1819 spin_unlock(&BTRFS_I(inode)->lock);
287a0ab9 1820
6a3891c5 1821 /* For sanity tests */
0b246afa 1822 if (btrfs_is_testing(fs_info))
6a3891c5
JB
1823 return;
1824
104b4e51
NB
1825 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1826 fs_info->delalloc_batch);
df0af1a5 1827 spin_lock(&BTRFS_I(inode)->lock);
0ca1f7ce 1828 BTRFS_I(inode)->delalloc_bytes += len;
47059d93
WS
1829 if (*bits & EXTENT_DEFRAG)
1830 BTRFS_I(inode)->defrag_bytes += len;
df0af1a5 1831 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
eb73c1b7
MX
1832 &BTRFS_I(inode)->runtime_flags))
1833 btrfs_add_delalloc_inodes(root, inode);
df0af1a5 1834 spin_unlock(&BTRFS_I(inode)->lock);
291d673e 1835 }
a7e3b975
FM
1836
1837 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1838 (*bits & EXTENT_DELALLOC_NEW)) {
1839 spin_lock(&BTRFS_I(inode)->lock);
1840 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1841 state->start;
1842 spin_unlock(&BTRFS_I(inode)->lock);
1843 }
291d673e
CM
1844}
1845
d352ac68 1846/*
a36bb5f9
NB
1847 * Once a range is no longer delalloc this function ensures that proper
1848 * accounting happens.
d352ac68 1849 */
a36bb5f9
NB
1850void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1851 struct extent_state *state, unsigned *bits)
291d673e 1852{
a36bb5f9
NB
1853 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1854 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
47059d93 1855 u64 len = state->end + 1 - state->start;
823bb20a 1856 u32 num_extents = count_max_extents(len);
47059d93 1857
4a4b964f
FM
1858 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1859 spin_lock(&inode->lock);
6fc0ef68 1860 inode->defrag_bytes -= len;
4a4b964f
FM
1861 spin_unlock(&inode->lock);
1862 }
47059d93 1863
75eff68e
CM
1864 /*
1865 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1866 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1867 * bit, which is only set or cleared with irqs on
1868 */
0ca1f7ce 1869 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
6fc0ef68 1870 struct btrfs_root *root = inode->root;
83eea1f1 1871 bool do_list = !btrfs_is_free_space_inode(inode);
bcbfce8a 1872
8b62f87b
JB
1873 spin_lock(&inode->lock);
1874 btrfs_mod_outstanding_extents(inode, -num_extents);
1875 spin_unlock(&inode->lock);
0ca1f7ce 1876
b6d08f06
JB
1877 /*
1878 * We don't reserve metadata space for space cache inodes so we
52042d8e 1879 * don't need to call delalloc_release_metadata if there is an
b6d08f06
JB
1880 * error.
1881 */
a315e68f 1882 if (*bits & EXTENT_CLEAR_META_RESV &&
0b246afa 1883 root != fs_info->tree_root)
43b18595 1884 btrfs_delalloc_release_metadata(inode, len, false);
0ca1f7ce 1885
6a3891c5 1886 /* For sanity tests. */
0b246afa 1887 if (btrfs_is_testing(fs_info))
6a3891c5
JB
1888 return;
1889
a315e68f
FM
1890 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1891 do_list && !(state->state & EXTENT_NORESERVE) &&
1892 (*bits & EXTENT_CLEAR_DATA_RESV))
6fc0ef68
NB
1893 btrfs_free_reserved_data_space_noquota(
1894 &inode->vfs_inode,
51773bec 1895 state->start, len);
9ed74f2d 1896
104b4e51
NB
1897 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1898 fs_info->delalloc_batch);
6fc0ef68
NB
1899 spin_lock(&inode->lock);
1900 inode->delalloc_bytes -= len;
1901 if (do_list && inode->delalloc_bytes == 0 &&
df0af1a5 1902 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
9e3e97f4 1903 &inode->runtime_flags))
eb73c1b7 1904 btrfs_del_delalloc_inode(root, inode);
6fc0ef68 1905 spin_unlock(&inode->lock);
291d673e 1906 }
a7e3b975
FM
1907
1908 if ((state->state & EXTENT_DELALLOC_NEW) &&
1909 (*bits & EXTENT_DELALLOC_NEW)) {
1910 spin_lock(&inode->lock);
1911 ASSERT(inode->new_delalloc_bytes >= len);
1912 inode->new_delalloc_bytes -= len;
1913 spin_unlock(&inode->lock);
1914 }
291d673e
CM
1915}
1916
d352ac68 1917/*
da12fe54
NB
1918 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1919 * in a chunk's stripe. This function ensures that bios do not span a
1920 * stripe/chunk
6f034ece 1921 *
da12fe54
NB
1922 * @page - The page we are about to add to the bio
1923 * @size - size we want to add to the bio
1924 * @bio - bio we want to ensure is smaller than a stripe
1925 * @bio_flags - flags of the bio
1926 *
1927 * return 1 if page cannot be added to the bio
1928 * return 0 if page can be added to the bio
6f034ece 1929 * return error otherwise
d352ac68 1930 */
da12fe54
NB
1931int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
1932 unsigned long bio_flags)
239b14b3 1933{
0b246afa
JM
1934 struct inode *inode = page->mapping->host;
1935 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4f024f37 1936 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
239b14b3
CM
1937 u64 length = 0;
1938 u64 map_length;
239b14b3
CM
1939 int ret;
1940
771ed689
CM
1941 if (bio_flags & EXTENT_BIO_COMPRESSED)
1942 return 0;
1943
4f024f37 1944 length = bio->bi_iter.bi_size;
239b14b3 1945 map_length = length;
0b246afa
JM
1946 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1947 NULL, 0);
6f034ece
LB
1948 if (ret < 0)
1949 return ret;
d397712b 1950 if (map_length < length + size)
239b14b3 1951 return 1;
3444a972 1952 return 0;
239b14b3
CM
1953}
1954
d352ac68
CM
1955/*
1956 * in order to insert checksums into the metadata in large chunks,
1957 * we wait until bio submission time. All the pages in the bio are
1958 * checksummed and sums are attached onto the ordered extent record.
1959 *
1960 * At IO completion time the cums attached on the ordered extent record
1961 * are inserted into the btree
1962 */
d0ee3934 1963static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
eaf25d93 1964 u64 bio_offset)
065631f6 1965{
c6100a4b 1966 struct inode *inode = private_data;
4e4cbee9 1967 blk_status_t ret = 0;
e015640f 1968
2ff7e61e 1969 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
79787eaa 1970 BUG_ON(ret); /* -ENOMEM */
4a69a410
CM
1971 return 0;
1972}
e015640f 1973
d352ac68 1974/*
cad321ad 1975 * extent_io.c submission hook. This does the right thing for csum calculation
4c274bc6
LB
1976 * on write, or reading the csums from the tree before a read.
1977 *
1978 * Rules about async/sync submit,
1979 * a) read: sync submit
1980 *
1981 * b) write without checksum: sync submit
1982 *
1983 * c) write with checksum:
1984 * c-1) if bio is issued by fsync: sync submit
1985 * (sync_writers != 0)
1986 *
1987 * c-2) if root is reloc root: sync submit
1988 * (only in case of buffered IO)
1989 *
1990 * c-3) otherwise: async submit
d352ac68 1991 */
a56b1c7b 1992static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
50489a57
NB
1993 int mirror_num,
1994 unsigned long bio_flags)
1995
44b8bd7e 1996{
0b246afa 1997 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44b8bd7e 1998 struct btrfs_root *root = BTRFS_I(inode)->root;
0d51e28a 1999 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
4e4cbee9 2000 blk_status_t ret = 0;
19b9bdb0 2001 int skip_sum;
b812ce28 2002 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
44b8bd7e 2003
6cbff00f 2004 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 2005
70ddc553 2006 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
0d51e28a 2007 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
0417341e 2008
37226b21 2009 if (bio_op(bio) != REQ_OP_WRITE) {
0b246afa 2010 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
5fd02043 2011 if (ret)
61891923 2012 goto out;
5fd02043 2013
d20f7043 2014 if (bio_flags & EXTENT_BIO_COMPRESSED) {
61891923
SB
2015 ret = btrfs_submit_compressed_read(inode, bio,
2016 mirror_num,
2017 bio_flags);
2018 goto out;
c2db1073 2019 } else if (!skip_sum) {
2ff7e61e 2020 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
c2db1073 2021 if (ret)
61891923 2022 goto out;
c2db1073 2023 }
4d1b5fb4 2024 goto mapit;
b812ce28 2025 } else if (async && !skip_sum) {
17d217fe
YZ
2026 /* csum items have already been cloned */
2027 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2028 goto mapit;
19b9bdb0 2029 /* we're doing a write, do the async checksumming */
c6100a4b 2030 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
e7681167 2031 0, inode, btrfs_submit_bio_start);
61891923 2032 goto out;
b812ce28 2033 } else if (!skip_sum) {
2ff7e61e 2034 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
b812ce28
JB
2035 if (ret)
2036 goto out;
19b9bdb0
CM
2037 }
2038
0b86a832 2039mapit:
2ff7e61e 2040 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
61891923
SB
2041
2042out:
4e4cbee9
CH
2043 if (ret) {
2044 bio->bi_status = ret;
4246a0b6
CH
2045 bio_endio(bio);
2046 }
61891923 2047 return ret;
065631f6 2048}
6885f308 2049
d352ac68
CM
2050/*
2051 * given a list of ordered sums record them in the inode. This happens
2052 * at IO completion time based on sums calculated at bio submission time.
2053 */
ba1da2f4 2054static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
df9f628e 2055 struct inode *inode, struct list_head *list)
e6dcd2dc 2056{
e6dcd2dc 2057 struct btrfs_ordered_sum *sum;
ac01f26a 2058 int ret;
e6dcd2dc 2059
c6e30871 2060 list_for_each_entry(sum, list, list) {
7c2871a2 2061 trans->adding_csums = true;
ac01f26a 2062 ret = btrfs_csum_file_blocks(trans,
d20f7043 2063 BTRFS_I(inode)->root->fs_info->csum_root, sum);
7c2871a2 2064 trans->adding_csums = false;
ac01f26a
NB
2065 if (ret)
2066 return ret;
e6dcd2dc
CM
2067 }
2068 return 0;
2069}
2070
2ac55d41 2071int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
e3b8a485 2072 unsigned int extra_bits,
ba8b04c1 2073 struct extent_state **cached_state, int dedupe)
ea8c2819 2074{
fdb1e121 2075 WARN_ON(PAGE_ALIGNED(end));
ea8c2819 2076 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
e3b8a485 2077 extra_bits, cached_state);
ea8c2819
CM
2078}
2079
d352ac68 2080/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
2081struct btrfs_writepage_fixup {
2082 struct page *page;
2083 struct btrfs_work work;
2084};
2085
b2950863 2086static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
2087{
2088 struct btrfs_writepage_fixup *fixup;
2089 struct btrfs_ordered_extent *ordered;
2ac55d41 2090 struct extent_state *cached_state = NULL;
364ecf36 2091 struct extent_changeset *data_reserved = NULL;
247e743c
CM
2092 struct page *page;
2093 struct inode *inode;
2094 u64 page_start;
2095 u64 page_end;
87826df0 2096 int ret;
247e743c
CM
2097
2098 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2099 page = fixup->page;
4a096752 2100again:
247e743c
CM
2101 lock_page(page);
2102 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2103 ClearPageChecked(page);
2104 goto out_page;
2105 }
2106
2107 inode = page->mapping->host;
2108 page_start = page_offset(page);
09cbfeaf 2109 page_end = page_offset(page) + PAGE_SIZE - 1;
247e743c 2110
ff13db41 2111 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
d0082371 2112 &cached_state);
4a096752
CM
2113
2114 /* already ordered? We're done */
8b62b72b 2115 if (PagePrivate2(page))
247e743c 2116 goto out;
4a096752 2117
a776c6fa 2118 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
09cbfeaf 2119 PAGE_SIZE);
4a096752 2120 if (ordered) {
2ac55d41 2121 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
e43bbe5e 2122 page_end, &cached_state);
4a096752
CM
2123 unlock_page(page);
2124 btrfs_start_ordered_extent(inode, ordered, 1);
87826df0 2125 btrfs_put_ordered_extent(ordered);
4a096752
CM
2126 goto again;
2127 }
247e743c 2128
364ecf36 2129 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
09cbfeaf 2130 PAGE_SIZE);
87826df0
JM
2131 if (ret) {
2132 mapping_set_error(page->mapping, ret);
2133 end_extent_writepage(page, ret, page_start, page_end);
2134 ClearPageChecked(page);
2135 goto out;
2136 }
2137
f3038ee3
NB
2138 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2139 &cached_state, 0);
2140 if (ret) {
2141 mapping_set_error(page->mapping, ret);
2142 end_extent_writepage(page, ret, page_start, page_end);
2143 ClearPageChecked(page);
2144 goto out;
2145 }
2146
247e743c 2147 ClearPageChecked(page);
87826df0 2148 set_page_dirty(page);
43b18595 2149 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
247e743c 2150out:
2ac55d41 2151 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
e43bbe5e 2152 &cached_state);
247e743c
CM
2153out_page:
2154 unlock_page(page);
09cbfeaf 2155 put_page(page);
b897abec 2156 kfree(fixup);
364ecf36 2157 extent_changeset_free(data_reserved);
247e743c
CM
2158}
2159
2160/*
2161 * There are a few paths in the higher layers of the kernel that directly
2162 * set the page dirty bit without asking the filesystem if it is a
2163 * good idea. This causes problems because we want to make sure COW
2164 * properly happens and the data=ordered rules are followed.
2165 *
c8b97818 2166 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
2167 * hasn't been properly setup for IO. We kick off an async process
2168 * to fix it up. The async helper will wait for ordered extents, set
2169 * the delalloc bit and make it safe to write the page.
2170 */
d75855b4 2171int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
247e743c
CM
2172{
2173 struct inode *inode = page->mapping->host;
0b246afa 2174 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
247e743c 2175 struct btrfs_writepage_fixup *fixup;
247e743c 2176
8b62b72b
CM
2177 /* this page is properly in the ordered list */
2178 if (TestClearPagePrivate2(page))
247e743c
CM
2179 return 0;
2180
2181 if (PageChecked(page))
2182 return -EAGAIN;
2183
2184 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2185 if (!fixup)
2186 return -EAGAIN;
f421950f 2187
247e743c 2188 SetPageChecked(page);
09cbfeaf 2189 get_page(page);
9e0af237
LB
2190 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2191 btrfs_writepage_fixup_worker, NULL, NULL);
247e743c 2192 fixup->page = page;
0b246afa 2193 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
87826df0 2194 return -EBUSY;
247e743c
CM
2195}
2196
d899e052
YZ
2197static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2198 struct inode *inode, u64 file_pos,
2199 u64 disk_bytenr, u64 disk_num_bytes,
2200 u64 num_bytes, u64 ram_bytes,
2201 u8 compression, u8 encryption,
2202 u16 other_encoding, int extent_type)
2203{
2204 struct btrfs_root *root = BTRFS_I(inode)->root;
2205 struct btrfs_file_extent_item *fi;
2206 struct btrfs_path *path;
2207 struct extent_buffer *leaf;
2208 struct btrfs_key ins;
a12b877b 2209 u64 qg_released;
1acae57b 2210 int extent_inserted = 0;
d899e052
YZ
2211 int ret;
2212
2213 path = btrfs_alloc_path();
d8926bb3
MF
2214 if (!path)
2215 return -ENOMEM;
d899e052 2216
a1ed835e
CM
2217 /*
2218 * we may be replacing one extent in the tree with another.
2219 * The new extent is pinned in the extent map, and we don't want
2220 * to drop it from the cache until it is completely in the btree.
2221 *
2222 * So, tell btrfs_drop_extents to leave this extent in the cache.
2223 * the caller is expected to unpin it and allow it to be merged
2224 * with the others.
2225 */
1acae57b
FDBM
2226 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2227 file_pos + num_bytes, NULL, 0,
2228 1, sizeof(*fi), &extent_inserted);
79787eaa
JM
2229 if (ret)
2230 goto out;
d899e052 2231
1acae57b 2232 if (!extent_inserted) {
4a0cc7ca 2233 ins.objectid = btrfs_ino(BTRFS_I(inode));
1acae57b
FDBM
2234 ins.offset = file_pos;
2235 ins.type = BTRFS_EXTENT_DATA_KEY;
2236
2237 path->leave_spinning = 1;
2238 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2239 sizeof(*fi));
2240 if (ret)
2241 goto out;
2242 }
d899e052
YZ
2243 leaf = path->nodes[0];
2244 fi = btrfs_item_ptr(leaf, path->slots[0],
2245 struct btrfs_file_extent_item);
2246 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2247 btrfs_set_file_extent_type(leaf, fi, extent_type);
2248 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2249 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2250 btrfs_set_file_extent_offset(leaf, fi, 0);
2251 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2252 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2253 btrfs_set_file_extent_compression(leaf, fi, compression);
2254 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2255 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439 2256
d899e052 2257 btrfs_mark_buffer_dirty(leaf);
ce195332 2258 btrfs_release_path(path);
d899e052
YZ
2259
2260 inode_add_bytes(inode, num_bytes);
d899e052
YZ
2261
2262 ins.objectid = disk_bytenr;
2263 ins.offset = disk_num_bytes;
2264 ins.type = BTRFS_EXTENT_ITEM_KEY;
a12b877b 2265
297d750b 2266 /*
5846a3c2
QW
2267 * Release the reserved range from inode dirty range map, as it is
2268 * already moved into delayed_ref_head
297d750b 2269 */
a12b877b
QW
2270 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2271 if (ret < 0)
2272 goto out;
2273 qg_released = ret;
84f7d8e6
JB
2274 ret = btrfs_alloc_reserved_file_extent(trans, root,
2275 btrfs_ino(BTRFS_I(inode)),
2276 file_pos, qg_released, &ins);
79787eaa 2277out:
d899e052 2278 btrfs_free_path(path);
b9473439 2279
79787eaa 2280 return ret;
d899e052
YZ
2281}
2282
38c227d8
LB
2283/* snapshot-aware defrag */
2284struct sa_defrag_extent_backref {
2285 struct rb_node node;
2286 struct old_sa_defrag_extent *old;
2287 u64 root_id;
2288 u64 inum;
2289 u64 file_pos;
2290 u64 extent_offset;
2291 u64 num_bytes;
2292 u64 generation;
2293};
2294
2295struct old_sa_defrag_extent {
2296 struct list_head list;
2297 struct new_sa_defrag_extent *new;
2298
2299 u64 extent_offset;
2300 u64 bytenr;
2301 u64 offset;
2302 u64 len;
2303 int count;
2304};
2305
2306struct new_sa_defrag_extent {
2307 struct rb_root root;
2308 struct list_head head;
2309 struct btrfs_path *path;
2310 struct inode *inode;
2311 u64 file_pos;
2312 u64 len;
2313 u64 bytenr;
2314 u64 disk_len;
2315 u8 compress_type;
2316};
2317
2318static int backref_comp(struct sa_defrag_extent_backref *b1,
2319 struct sa_defrag_extent_backref *b2)
2320{
2321 if (b1->root_id < b2->root_id)
2322 return -1;
2323 else if (b1->root_id > b2->root_id)
2324 return 1;
2325
2326 if (b1->inum < b2->inum)
2327 return -1;
2328 else if (b1->inum > b2->inum)
2329 return 1;
2330
2331 if (b1->file_pos < b2->file_pos)
2332 return -1;
2333 else if (b1->file_pos > b2->file_pos)
2334 return 1;
2335
2336 /*
2337 * [------------------------------] ===> (a range of space)
2338 * |<--->| |<---->| =============> (fs/file tree A)
2339 * |<---------------------------->| ===> (fs/file tree B)
2340 *
2341 * A range of space can refer to two file extents in one tree while
2342 * refer to only one file extent in another tree.
2343 *
2344 * So we may process a disk offset more than one time(two extents in A)
2345 * and locate at the same extent(one extent in B), then insert two same
2346 * backrefs(both refer to the extent in B).
2347 */
2348 return 0;
2349}
2350
2351static void backref_insert(struct rb_root *root,
2352 struct sa_defrag_extent_backref *backref)
2353{
2354 struct rb_node **p = &root->rb_node;
2355 struct rb_node *parent = NULL;
2356 struct sa_defrag_extent_backref *entry;
2357 int ret;
2358
2359 while (*p) {
2360 parent = *p;
2361 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2362
2363 ret = backref_comp(backref, entry);
2364 if (ret < 0)
2365 p = &(*p)->rb_left;
2366 else
2367 p = &(*p)->rb_right;
2368 }
2369
2370 rb_link_node(&backref->node, parent, p);
2371 rb_insert_color(&backref->node, root);
2372}
2373
2374/*
2375 * Note the backref might has changed, and in this case we just return 0.
2376 */
2377static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2378 void *ctx)
2379{
2380 struct btrfs_file_extent_item *extent;
38c227d8
LB
2381 struct old_sa_defrag_extent *old = ctx;
2382 struct new_sa_defrag_extent *new = old->new;
2383 struct btrfs_path *path = new->path;
2384 struct btrfs_key key;
2385 struct btrfs_root *root;
2386 struct sa_defrag_extent_backref *backref;
2387 struct extent_buffer *leaf;
2388 struct inode *inode = new->inode;
0b246afa 2389 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
38c227d8
LB
2390 int slot;
2391 int ret;
2392 u64 extent_offset;
2393 u64 num_bytes;
2394
2395 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
4a0cc7ca 2396 inum == btrfs_ino(BTRFS_I(inode)))
38c227d8
LB
2397 return 0;
2398
2399 key.objectid = root_id;
2400 key.type = BTRFS_ROOT_ITEM_KEY;
2401 key.offset = (u64)-1;
2402
38c227d8
LB
2403 root = btrfs_read_fs_root_no_name(fs_info, &key);
2404 if (IS_ERR(root)) {
2405 if (PTR_ERR(root) == -ENOENT)
2406 return 0;
2407 WARN_ON(1);
ab8d0fc4 2408 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
38c227d8
LB
2409 inum, offset, root_id);
2410 return PTR_ERR(root);
2411 }
2412
2413 key.objectid = inum;
2414 key.type = BTRFS_EXTENT_DATA_KEY;
2415 if (offset > (u64)-1 << 32)
2416 key.offset = 0;
2417 else
2418 key.offset = offset;
2419
2420 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
fae7f21c 2421 if (WARN_ON(ret < 0))
38c227d8 2422 return ret;
50f1319c 2423 ret = 0;
38c227d8
LB
2424
2425 while (1) {
2426 cond_resched();
2427
2428 leaf = path->nodes[0];
2429 slot = path->slots[0];
2430
2431 if (slot >= btrfs_header_nritems(leaf)) {
2432 ret = btrfs_next_leaf(root, path);
2433 if (ret < 0) {
2434 goto out;
2435 } else if (ret > 0) {
2436 ret = 0;
2437 goto out;
2438 }
2439 continue;
2440 }
2441
2442 path->slots[0]++;
2443
2444 btrfs_item_key_to_cpu(leaf, &key, slot);
2445
2446 if (key.objectid > inum)
2447 goto out;
2448
2449 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2450 continue;
2451
2452 extent = btrfs_item_ptr(leaf, slot,
2453 struct btrfs_file_extent_item);
2454
2455 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2456 continue;
2457
e68afa49
LB
2458 /*
2459 * 'offset' refers to the exact key.offset,
2460 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2461 * (key.offset - extent_offset).
2462 */
2463 if (key.offset != offset)
38c227d8
LB
2464 continue;
2465
e68afa49 2466 extent_offset = btrfs_file_extent_offset(leaf, extent);
38c227d8 2467 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
e68afa49 2468
38c227d8
LB
2469 if (extent_offset >= old->extent_offset + old->offset +
2470 old->len || extent_offset + num_bytes <=
2471 old->extent_offset + old->offset)
2472 continue;
38c227d8
LB
2473 break;
2474 }
2475
2476 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2477 if (!backref) {
2478 ret = -ENOENT;
2479 goto out;
2480 }
2481
2482 backref->root_id = root_id;
2483 backref->inum = inum;
e68afa49 2484 backref->file_pos = offset;
38c227d8
LB
2485 backref->num_bytes = num_bytes;
2486 backref->extent_offset = extent_offset;
2487 backref->generation = btrfs_file_extent_generation(leaf, extent);
2488 backref->old = old;
2489 backref_insert(&new->root, backref);
2490 old->count++;
2491out:
2492 btrfs_release_path(path);
2493 WARN_ON(ret);
2494 return ret;
2495}
2496
2497static noinline bool record_extent_backrefs(struct btrfs_path *path,
2498 struct new_sa_defrag_extent *new)
2499{
0b246afa 2500 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8
LB
2501 struct old_sa_defrag_extent *old, *tmp;
2502 int ret;
2503
2504 new->path = path;
2505
2506 list_for_each_entry_safe(old, tmp, &new->head, list) {
e68afa49
LB
2507 ret = iterate_inodes_from_logical(old->bytenr +
2508 old->extent_offset, fs_info,
38c227d8 2509 path, record_one_backref,
c995ab3c 2510 old, false);
4724b106
JB
2511 if (ret < 0 && ret != -ENOENT)
2512 return false;
38c227d8
LB
2513
2514 /* no backref to be processed for this extent */
2515 if (!old->count) {
2516 list_del(&old->list);
2517 kfree(old);
2518 }
2519 }
2520
2521 if (list_empty(&new->head))
2522 return false;
2523
2524 return true;
2525}
2526
2527static int relink_is_mergable(struct extent_buffer *leaf,
2528 struct btrfs_file_extent_item *fi,
116e0024 2529 struct new_sa_defrag_extent *new)
38c227d8 2530{
116e0024 2531 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
38c227d8
LB
2532 return 0;
2533
2534 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2535 return 0;
2536
116e0024
LB
2537 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2538 return 0;
2539
2540 if (btrfs_file_extent_encryption(leaf, fi) ||
38c227d8
LB
2541 btrfs_file_extent_other_encoding(leaf, fi))
2542 return 0;
2543
2544 return 1;
2545}
2546
2547/*
2548 * Note the backref might has changed, and in this case we just return 0.
2549 */
2550static noinline int relink_extent_backref(struct btrfs_path *path,
2551 struct sa_defrag_extent_backref *prev,
2552 struct sa_defrag_extent_backref *backref)
2553{
2554 struct btrfs_file_extent_item *extent;
2555 struct btrfs_file_extent_item *item;
2556 struct btrfs_ordered_extent *ordered;
2557 struct btrfs_trans_handle *trans;
82fa113f 2558 struct btrfs_ref ref = { 0 };
38c227d8
LB
2559 struct btrfs_root *root;
2560 struct btrfs_key key;
2561 struct extent_buffer *leaf;
2562 struct old_sa_defrag_extent *old = backref->old;
2563 struct new_sa_defrag_extent *new = old->new;
0b246afa 2564 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8
LB
2565 struct inode *inode;
2566 struct extent_state *cached = NULL;
2567 int ret = 0;
2568 u64 start;
2569 u64 len;
2570 u64 lock_start;
2571 u64 lock_end;
2572 bool merge = false;
2573 int index;
2574
2575 if (prev && prev->root_id == backref->root_id &&
2576 prev->inum == backref->inum &&
2577 prev->file_pos + prev->num_bytes == backref->file_pos)
2578 merge = true;
2579
2580 /* step 1: get root */
2581 key.objectid = backref->root_id;
2582 key.type = BTRFS_ROOT_ITEM_KEY;
2583 key.offset = (u64)-1;
2584
38c227d8
LB
2585 index = srcu_read_lock(&fs_info->subvol_srcu);
2586
2587 root = btrfs_read_fs_root_no_name(fs_info, &key);
2588 if (IS_ERR(root)) {
2589 srcu_read_unlock(&fs_info->subvol_srcu, index);
2590 if (PTR_ERR(root) == -ENOENT)
2591 return 0;
2592 return PTR_ERR(root);
2593 }
38c227d8 2594
bcbba5e6
WS
2595 if (btrfs_root_readonly(root)) {
2596 srcu_read_unlock(&fs_info->subvol_srcu, index);
2597 return 0;
2598 }
2599
38c227d8
LB
2600 /* step 2: get inode */
2601 key.objectid = backref->inum;
2602 key.type = BTRFS_INODE_ITEM_KEY;
2603 key.offset = 0;
2604
2605 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2606 if (IS_ERR(inode)) {
2607 srcu_read_unlock(&fs_info->subvol_srcu, index);
2608 return 0;
2609 }
2610
2611 srcu_read_unlock(&fs_info->subvol_srcu, index);
2612
2613 /* step 3: relink backref */
2614 lock_start = backref->file_pos;
2615 lock_end = backref->file_pos + backref->num_bytes - 1;
2616 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
ff13db41 2617 &cached);
38c227d8
LB
2618
2619 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2620 if (ordered) {
2621 btrfs_put_ordered_extent(ordered);
2622 goto out_unlock;
2623 }
2624
2625 trans = btrfs_join_transaction(root);
2626 if (IS_ERR(trans)) {
2627 ret = PTR_ERR(trans);
2628 goto out_unlock;
2629 }
2630
2631 key.objectid = backref->inum;
2632 key.type = BTRFS_EXTENT_DATA_KEY;
2633 key.offset = backref->file_pos;
2634
2635 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2636 if (ret < 0) {
2637 goto out_free_path;
2638 } else if (ret > 0) {
2639 ret = 0;
2640 goto out_free_path;
2641 }
2642
2643 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2644 struct btrfs_file_extent_item);
2645
2646 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2647 backref->generation)
2648 goto out_free_path;
2649
2650 btrfs_release_path(path);
2651
2652 start = backref->file_pos;
2653 if (backref->extent_offset < old->extent_offset + old->offset)
2654 start += old->extent_offset + old->offset -
2655 backref->extent_offset;
2656
2657 len = min(backref->extent_offset + backref->num_bytes,
2658 old->extent_offset + old->offset + old->len);
2659 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2660
2661 ret = btrfs_drop_extents(trans, root, inode, start,
2662 start + len, 1);
2663 if (ret)
2664 goto out_free_path;
2665again:
4a0cc7ca 2666 key.objectid = btrfs_ino(BTRFS_I(inode));
38c227d8
LB
2667 key.type = BTRFS_EXTENT_DATA_KEY;
2668 key.offset = start;
2669
a09a0a70 2670 path->leave_spinning = 1;
38c227d8
LB
2671 if (merge) {
2672 struct btrfs_file_extent_item *fi;
2673 u64 extent_len;
2674 struct btrfs_key found_key;
2675
3c9665df 2676 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
38c227d8
LB
2677 if (ret < 0)
2678 goto out_free_path;
2679
2680 path->slots[0]--;
2681 leaf = path->nodes[0];
2682 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2683
2684 fi = btrfs_item_ptr(leaf, path->slots[0],
2685 struct btrfs_file_extent_item);
2686 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2687
116e0024
LB
2688 if (extent_len + found_key.offset == start &&
2689 relink_is_mergable(leaf, fi, new)) {
38c227d8
LB
2690 btrfs_set_file_extent_num_bytes(leaf, fi,
2691 extent_len + len);
2692 btrfs_mark_buffer_dirty(leaf);
2693 inode_add_bytes(inode, len);
2694
2695 ret = 1;
2696 goto out_free_path;
2697 } else {
2698 merge = false;
2699 btrfs_release_path(path);
2700 goto again;
2701 }
2702 }
2703
2704 ret = btrfs_insert_empty_item(trans, root, path, &key,
2705 sizeof(*extent));
2706 if (ret) {
66642832 2707 btrfs_abort_transaction(trans, ret);
38c227d8
LB
2708 goto out_free_path;
2709 }
2710
2711 leaf = path->nodes[0];
2712 item = btrfs_item_ptr(leaf, path->slots[0],
2713 struct btrfs_file_extent_item);
2714 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2715 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2716 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2717 btrfs_set_file_extent_num_bytes(leaf, item, len);
2718 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2719 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2720 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2721 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2722 btrfs_set_file_extent_encryption(leaf, item, 0);
2723 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2724
2725 btrfs_mark_buffer_dirty(leaf);
2726 inode_add_bytes(inode, len);
a09a0a70 2727 btrfs_release_path(path);
38c227d8 2728
82fa113f
QW
2729 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, new->bytenr,
2730 new->disk_len, 0);
2731 btrfs_init_data_ref(&ref, backref->root_id, backref->inum,
2732 new->file_pos); /* start - extent_offset */
2733 ret = btrfs_inc_extent_ref(trans, &ref);
38c227d8 2734 if (ret) {
66642832 2735 btrfs_abort_transaction(trans, ret);
38c227d8
LB
2736 goto out_free_path;
2737 }
2738
2739 ret = 1;
2740out_free_path:
2741 btrfs_release_path(path);
a09a0a70 2742 path->leave_spinning = 0;
3a45bb20 2743 btrfs_end_transaction(trans);
38c227d8
LB
2744out_unlock:
2745 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
e43bbe5e 2746 &cached);
38c227d8
LB
2747 iput(inode);
2748 return ret;
2749}
2750
6f519564
LB
2751static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2752{
2753 struct old_sa_defrag_extent *old, *tmp;
2754
2755 if (!new)
2756 return;
2757
2758 list_for_each_entry_safe(old, tmp, &new->head, list) {
6f519564
LB
2759 kfree(old);
2760 }
2761 kfree(new);
2762}
2763
38c227d8
LB
2764static void relink_file_extents(struct new_sa_defrag_extent *new)
2765{
0b246afa 2766 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8 2767 struct btrfs_path *path;
38c227d8
LB
2768 struct sa_defrag_extent_backref *backref;
2769 struct sa_defrag_extent_backref *prev = NULL;
38c227d8
LB
2770 struct rb_node *node;
2771 int ret;
2772
38c227d8
LB
2773 path = btrfs_alloc_path();
2774 if (!path)
2775 return;
2776
2777 if (!record_extent_backrefs(path, new)) {
2778 btrfs_free_path(path);
2779 goto out;
2780 }
2781 btrfs_release_path(path);
2782
2783 while (1) {
2784 node = rb_first(&new->root);
2785 if (!node)
2786 break;
2787 rb_erase(node, &new->root);
2788
2789 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2790
2791 ret = relink_extent_backref(path, prev, backref);
2792 WARN_ON(ret < 0);
2793
2794 kfree(prev);
2795
2796 if (ret == 1)
2797 prev = backref;
2798 else
2799 prev = NULL;
2800 cond_resched();
2801 }
2802 kfree(prev);
2803
2804 btrfs_free_path(path);
38c227d8 2805out:
6f519564
LB
2806 free_sa_defrag_extent(new);
2807
0b246afa
JM
2808 atomic_dec(&fs_info->defrag_running);
2809 wake_up(&fs_info->transaction_wait);
38c227d8
LB
2810}
2811
2812static struct new_sa_defrag_extent *
2813record_old_file_extents(struct inode *inode,
2814 struct btrfs_ordered_extent *ordered)
2815{
0b246afa 2816 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
38c227d8
LB
2817 struct btrfs_root *root = BTRFS_I(inode)->root;
2818 struct btrfs_path *path;
2819 struct btrfs_key key;
6f519564 2820 struct old_sa_defrag_extent *old;
38c227d8
LB
2821 struct new_sa_defrag_extent *new;
2822 int ret;
2823
2824 new = kmalloc(sizeof(*new), GFP_NOFS);
2825 if (!new)
2826 return NULL;
2827
2828 new->inode = inode;
2829 new->file_pos = ordered->file_offset;
2830 new->len = ordered->len;
2831 new->bytenr = ordered->start;
2832 new->disk_len = ordered->disk_len;
2833 new->compress_type = ordered->compress_type;
2834 new->root = RB_ROOT;
2835 INIT_LIST_HEAD(&new->head);
2836
2837 path = btrfs_alloc_path();
2838 if (!path)
2839 goto out_kfree;
2840
4a0cc7ca 2841 key.objectid = btrfs_ino(BTRFS_I(inode));
38c227d8
LB
2842 key.type = BTRFS_EXTENT_DATA_KEY;
2843 key.offset = new->file_pos;
2844
2845 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2846 if (ret < 0)
2847 goto out_free_path;
2848 if (ret > 0 && path->slots[0] > 0)
2849 path->slots[0]--;
2850
2851 /* find out all the old extents for the file range */
2852 while (1) {
2853 struct btrfs_file_extent_item *extent;
2854 struct extent_buffer *l;
2855 int slot;
2856 u64 num_bytes;
2857 u64 offset;
2858 u64 end;
2859 u64 disk_bytenr;
2860 u64 extent_offset;
2861
2862 l = path->nodes[0];
2863 slot = path->slots[0];
2864
2865 if (slot >= btrfs_header_nritems(l)) {
2866 ret = btrfs_next_leaf(root, path);
2867 if (ret < 0)
6f519564 2868 goto out_free_path;
38c227d8
LB
2869 else if (ret > 0)
2870 break;
2871 continue;
2872 }
2873
2874 btrfs_item_key_to_cpu(l, &key, slot);
2875
4a0cc7ca 2876 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
38c227d8
LB
2877 break;
2878 if (key.type != BTRFS_EXTENT_DATA_KEY)
2879 break;
2880 if (key.offset >= new->file_pos + new->len)
2881 break;
2882
2883 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2884
2885 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2886 if (key.offset + num_bytes < new->file_pos)
2887 goto next;
2888
2889 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2890 if (!disk_bytenr)
2891 goto next;
2892
2893 extent_offset = btrfs_file_extent_offset(l, extent);
2894
2895 old = kmalloc(sizeof(*old), GFP_NOFS);
2896 if (!old)
6f519564 2897 goto out_free_path;
38c227d8
LB
2898
2899 offset = max(new->file_pos, key.offset);
2900 end = min(new->file_pos + new->len, key.offset + num_bytes);
2901
2902 old->bytenr = disk_bytenr;
2903 old->extent_offset = extent_offset;
2904 old->offset = offset - key.offset;
2905 old->len = end - offset;
2906 old->new = new;
2907 old->count = 0;
2908 list_add_tail(&old->list, &new->head);
2909next:
2910 path->slots[0]++;
2911 cond_resched();
2912 }
2913
2914 btrfs_free_path(path);
0b246afa 2915 atomic_inc(&fs_info->defrag_running);
38c227d8
LB
2916
2917 return new;
2918
38c227d8
LB
2919out_free_path:
2920 btrfs_free_path(path);
2921out_kfree:
6f519564 2922 free_sa_defrag_extent(new);
38c227d8
LB
2923 return NULL;
2924}
2925
2ff7e61e 2926static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
e570fd27
MX
2927 u64 start, u64 len)
2928{
2929 struct btrfs_block_group_cache *cache;
2930
0b246afa 2931 cache = btrfs_lookup_block_group(fs_info, start);
e570fd27
MX
2932 ASSERT(cache);
2933
2934 spin_lock(&cache->lock);
2935 cache->delalloc_bytes -= len;
2936 spin_unlock(&cache->lock);
2937
2938 btrfs_put_block_group(cache);
2939}
2940
d352ac68
CM
2941/* as ordered data IO finishes, this gets called so we can finish
2942 * an ordered extent if the range of bytes in the file it covers are
2943 * fully written.
2944 */
5fd02043 2945static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
e6dcd2dc 2946{
5fd02043 2947 struct inode *inode = ordered_extent->inode;
0b246afa 2948 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc 2949 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 2950 struct btrfs_trans_handle *trans = NULL;
e6dcd2dc 2951 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2ac55d41 2952 struct extent_state *cached_state = NULL;
38c227d8 2953 struct new_sa_defrag_extent *new = NULL;
261507a0 2954 int compress_type = 0;
77cef2ec
JB
2955 int ret = 0;
2956 u64 logical_len = ordered_extent->len;
82d5902d 2957 bool nolock;
77cef2ec 2958 bool truncated = false;
a7e3b975
FM
2959 bool range_locked = false;
2960 bool clear_new_delalloc_bytes = false;
49940bdd 2961 bool clear_reserved_extent = true;
a7e3b975
FM
2962
2963 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2964 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2965 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2966 clear_new_delalloc_bytes = true;
e6dcd2dc 2967
70ddc553 2968 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
0cb59c99 2969
5fd02043
JB
2970 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2971 ret = -EIO;
2972 goto out;
2973 }
2974
7ab7956e
NB
2975 btrfs_free_io_failure_record(BTRFS_I(inode),
2976 ordered_extent->file_offset,
2977 ordered_extent->file_offset +
2978 ordered_extent->len - 1);
f612496b 2979
77cef2ec
JB
2980 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2981 truncated = true;
2982 logical_len = ordered_extent->truncated_len;
2983 /* Truncated the entire extent, don't bother adding */
2984 if (!logical_len)
2985 goto out;
2986 }
2987
c2167754 2988 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
79787eaa 2989 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
94ed938a
QW
2990
2991 /*
2992 * For mwrite(mmap + memset to write) case, we still reserve
2993 * space for NOCOW range.
2994 * As NOCOW won't cause a new delayed ref, just free the space
2995 */
bc42bda2 2996 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
94ed938a 2997 ordered_extent->len);
6c760c07
JB
2998 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2999 if (nolock)
3000 trans = btrfs_join_transaction_nolock(root);
3001 else
3002 trans = btrfs_join_transaction(root);
3003 if (IS_ERR(trans)) {
3004 ret = PTR_ERR(trans);
3005 trans = NULL;
3006 goto out;
c2167754 3007 }
69fe2d75 3008 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
6c760c07
JB
3009 ret = btrfs_update_inode_fallback(trans, root, inode);
3010 if (ret) /* -ENOMEM or corruption */
66642832 3011 btrfs_abort_transaction(trans, ret);
c2167754
YZ
3012 goto out;
3013 }
e6dcd2dc 3014
a7e3b975 3015 range_locked = true;
2ac55d41
JB
3016 lock_extent_bits(io_tree, ordered_extent->file_offset,
3017 ordered_extent->file_offset + ordered_extent->len - 1,
ff13db41 3018 &cached_state);
e6dcd2dc 3019
38c227d8
LB
3020 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3021 ordered_extent->file_offset + ordered_extent->len - 1,
452e62b7 3022 EXTENT_DEFRAG, 0, cached_state);
38c227d8
LB
3023 if (ret) {
3024 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
8101c8db 3025 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
38c227d8
LB
3026 /* the inode is shared */
3027 new = record_old_file_extents(inode, ordered_extent);
3028
3029 clear_extent_bit(io_tree, ordered_extent->file_offset,
3030 ordered_extent->file_offset + ordered_extent->len - 1,
ae0f1625 3031 EXTENT_DEFRAG, 0, 0, &cached_state);
38c227d8
LB
3032 }
3033
0cb59c99 3034 if (nolock)
7a7eaa40 3035 trans = btrfs_join_transaction_nolock(root);
0cb59c99 3036 else
7a7eaa40 3037 trans = btrfs_join_transaction(root);
79787eaa
JM
3038 if (IS_ERR(trans)) {
3039 ret = PTR_ERR(trans);
3040 trans = NULL;
a7e3b975 3041 goto out;
79787eaa 3042 }
a79b7d4b 3043
69fe2d75 3044 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
c2167754 3045
c8b97818 3046 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
261507a0 3047 compress_type = ordered_extent->compress_type;
d899e052 3048 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
261507a0 3049 BUG_ON(compress_type);
b430b775
JM
3050 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3051 ordered_extent->len);
7a6d7067 3052 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
d899e052
YZ
3053 ordered_extent->file_offset,
3054 ordered_extent->file_offset +
77cef2ec 3055 logical_len);
d899e052 3056 } else {
0b246afa 3057 BUG_ON(root == fs_info->tree_root);
d899e052
YZ
3058 ret = insert_reserved_file_extent(trans, inode,
3059 ordered_extent->file_offset,
3060 ordered_extent->start,
3061 ordered_extent->disk_len,
77cef2ec 3062 logical_len, logical_len,
261507a0 3063 compress_type, 0, 0,
d899e052 3064 BTRFS_FILE_EXTENT_REG);
49940bdd
JB
3065 if (!ret) {
3066 clear_reserved_extent = false;
2ff7e61e 3067 btrfs_release_delalloc_bytes(fs_info,
e570fd27
MX
3068 ordered_extent->start,
3069 ordered_extent->disk_len);
49940bdd 3070 }
d899e052 3071 }
5dc562c5
JB
3072 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3073 ordered_extent->file_offset, ordered_extent->len,
3074 trans->transid);
79787eaa 3075 if (ret < 0) {
66642832 3076 btrfs_abort_transaction(trans, ret);
a7e3b975 3077 goto out;
79787eaa 3078 }
2ac55d41 3079
ac01f26a
NB
3080 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3081 if (ret) {
3082 btrfs_abort_transaction(trans, ret);
3083 goto out;
3084 }
e6dcd2dc 3085
6c760c07
JB
3086 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3087 ret = btrfs_update_inode_fallback(trans, root, inode);
3088 if (ret) { /* -ENOMEM or corruption */
66642832 3089 btrfs_abort_transaction(trans, ret);
a7e3b975 3090 goto out;
1ef30be1
JB
3091 }
3092 ret = 0;
c2167754 3093out:
a7e3b975
FM
3094 if (range_locked || clear_new_delalloc_bytes) {
3095 unsigned int clear_bits = 0;
3096
3097 if (range_locked)
3098 clear_bits |= EXTENT_LOCKED;
3099 if (clear_new_delalloc_bytes)
3100 clear_bits |= EXTENT_DELALLOC_NEW;
3101 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3102 ordered_extent->file_offset,
3103 ordered_extent->file_offset +
3104 ordered_extent->len - 1,
3105 clear_bits,
3106 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
ae0f1625 3107 0, &cached_state);
a7e3b975
FM
3108 }
3109
a698d075 3110 if (trans)
3a45bb20 3111 btrfs_end_transaction(trans);
0cb59c99 3112
77cef2ec
JB
3113 if (ret || truncated) {
3114 u64 start, end;
3115
3116 if (truncated)
3117 start = ordered_extent->file_offset + logical_len;
3118 else
3119 start = ordered_extent->file_offset;
3120 end = ordered_extent->file_offset + ordered_extent->len - 1;
f08dc36f 3121 clear_extent_uptodate(io_tree, start, end, NULL);
77cef2ec
JB
3122
3123 /* Drop the cache for the part of the extent we didn't write. */
dcdbc059 3124 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
5fd02043 3125
0bec9ef5
JB
3126 /*
3127 * If the ordered extent had an IOERR or something else went
3128 * wrong we need to return the space for this ordered extent
77cef2ec
JB
3129 * back to the allocator. We only free the extent in the
3130 * truncated case if we didn't write out the extent at all.
49940bdd
JB
3131 *
3132 * If we made it past insert_reserved_file_extent before we
3133 * errored out then we don't need to do this as the accounting
3134 * has already been done.
0bec9ef5 3135 */
77cef2ec 3136 if ((ret || !logical_len) &&
49940bdd 3137 clear_reserved_extent &&
77cef2ec 3138 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
0bec9ef5 3139 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2ff7e61e
JM
3140 btrfs_free_reserved_extent(fs_info,
3141 ordered_extent->start,
e570fd27 3142 ordered_extent->disk_len, 1);
0bec9ef5
JB
3143 }
3144
3145
5fd02043 3146 /*
8bad3c02
LB
3147 * This needs to be done to make sure anybody waiting knows we are done
3148 * updating everything for this ordered extent.
5fd02043
JB
3149 */
3150 btrfs_remove_ordered_extent(inode, ordered_extent);
3151
38c227d8 3152 /* for snapshot-aware defrag */
6f519564
LB
3153 if (new) {
3154 if (ret) {
3155 free_sa_defrag_extent(new);
0b246afa 3156 atomic_dec(&fs_info->defrag_running);
6f519564
LB
3157 } else {
3158 relink_file_extents(new);
3159 }
3160 }
38c227d8 3161
e6dcd2dc
CM
3162 /* once for us */
3163 btrfs_put_ordered_extent(ordered_extent);
3164 /* once for the tree */
3165 btrfs_put_ordered_extent(ordered_extent);
3166
5fd02043
JB
3167 return ret;
3168}
3169
3170static void finish_ordered_fn(struct btrfs_work *work)
3171{
3172 struct btrfs_ordered_extent *ordered_extent;
3173 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3174 btrfs_finish_ordered_io(ordered_extent);
e6dcd2dc
CM
3175}
3176
c629732d
NB
3177void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3178 u64 end, int uptodate)
211f90e6 3179{
5fd02043 3180 struct inode *inode = page->mapping->host;
0b246afa 3181 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5fd02043 3182 struct btrfs_ordered_extent *ordered_extent = NULL;
9e0af237
LB
3183 struct btrfs_workqueue *wq;
3184 btrfs_work_func_t func;
5fd02043 3185
1abe9b8a 3186 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3187
8b62b72b 3188 ClearPagePrivate2(page);
5fd02043
JB
3189 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3190 end - start + 1, uptodate))
c3988d63 3191 return;
5fd02043 3192
70ddc553 3193 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
0b246afa 3194 wq = fs_info->endio_freespace_worker;
9e0af237
LB
3195 func = btrfs_freespace_write_helper;
3196 } else {
0b246afa 3197 wq = fs_info->endio_write_workers;
9e0af237
LB
3198 func = btrfs_endio_write_helper;
3199 }
5fd02043 3200
9e0af237
LB
3201 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3202 NULL);
3203 btrfs_queue_work(wq, &ordered_extent->work);
211f90e6
CM
3204}
3205
dc380aea
MX
3206static int __readpage_endio_check(struct inode *inode,
3207 struct btrfs_io_bio *io_bio,
3208 int icsum, struct page *page,
3209 int pgoff, u64 start, size_t len)
3210{
3211 char *kaddr;
3212 u32 csum_expected;
3213 u32 csum = ~(u32)0;
dc380aea
MX
3214
3215 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3216
3217 kaddr = kmap_atomic(page);
3218 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
0b5e3daf 3219 btrfs_csum_final(csum, (u8 *)&csum);
dc380aea
MX
3220 if (csum != csum_expected)
3221 goto zeroit;
3222
3223 kunmap_atomic(kaddr);
3224 return 0;
3225zeroit:
0970a22e 3226 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
6f6b643e 3227 io_bio->mirror_num);
dc380aea
MX
3228 memset(kaddr + pgoff, 1, len);
3229 flush_dcache_page(page);
3230 kunmap_atomic(kaddr);
dc380aea
MX
3231 return -EIO;
3232}
3233
d352ac68
CM
3234/*
3235 * when reads are done, we need to check csums to verify the data is correct
4a54c8c1
JS
3236 * if there's a match, we allow the bio to finish. If not, the code in
3237 * extent_io.c will try to find good copies for us.
d352ac68 3238 */
facc8a22
MX
3239static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3240 u64 phy_offset, struct page *page,
3241 u64 start, u64 end, int mirror)
07157aac 3242{
4eee4fa4 3243 size_t offset = start - page_offset(page);
07157aac 3244 struct inode *inode = page->mapping->host;
d1310b2e 3245 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
ff79f819 3246 struct btrfs_root *root = BTRFS_I(inode)->root;
d1310b2e 3247
d20f7043
CM
3248 if (PageChecked(page)) {
3249 ClearPageChecked(page);
dc380aea 3250 return 0;
d20f7043 3251 }
6cbff00f
CH
3252
3253 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
dc380aea 3254 return 0;
17d217fe
YZ
3255
3256 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 3257 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
91166212 3258 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
b6cda9bc 3259 return 0;
17d217fe 3260 }
d20f7043 3261
facc8a22 3262 phy_offset >>= inode->i_sb->s_blocksize_bits;
dc380aea
MX
3263 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3264 start, (size_t)(end - start + 1));
07157aac 3265}
b888db2b 3266
c1c3fac2
NB
3267/*
3268 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3269 *
3270 * @inode: The inode we want to perform iput on
3271 *
3272 * This function uses the generic vfs_inode::i_count to track whether we should
3273 * just decrement it (in case it's > 1) or if this is the last iput then link
3274 * the inode to the delayed iput machinery. Delayed iputs are processed at
3275 * transaction commit time/superblock commit/cleaner kthread.
3276 */
24bbcf04
YZ
3277void btrfs_add_delayed_iput(struct inode *inode)
3278{
0b246afa 3279 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8089fe62 3280 struct btrfs_inode *binode = BTRFS_I(inode);
24bbcf04
YZ
3281
3282 if (atomic_add_unless(&inode->i_count, -1, 1))
3283 return;
3284
034f784d 3285 atomic_inc(&fs_info->nr_delayed_iputs);
24bbcf04 3286 spin_lock(&fs_info->delayed_iput_lock);
c1c3fac2
NB
3287 ASSERT(list_empty(&binode->delayed_iput));
3288 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
24bbcf04 3289 spin_unlock(&fs_info->delayed_iput_lock);
fd340d0f
JB
3290 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3291 wake_up_process(fs_info->cleaner_kthread);
24bbcf04
YZ
3292}
3293
2ff7e61e 3294void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
24bbcf04 3295{
24bbcf04 3296
24bbcf04 3297 spin_lock(&fs_info->delayed_iput_lock);
8089fe62
DS
3298 while (!list_empty(&fs_info->delayed_iputs)) {
3299 struct btrfs_inode *inode;
3300
3301 inode = list_first_entry(&fs_info->delayed_iputs,
3302 struct btrfs_inode, delayed_iput);
c1c3fac2 3303 list_del_init(&inode->delayed_iput);
8089fe62
DS
3304 spin_unlock(&fs_info->delayed_iput_lock);
3305 iput(&inode->vfs_inode);
034f784d
JB
3306 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3307 wake_up(&fs_info->delayed_iputs_wait);
8089fe62 3308 spin_lock(&fs_info->delayed_iput_lock);
24bbcf04 3309 }
8089fe62 3310 spin_unlock(&fs_info->delayed_iput_lock);
24bbcf04
YZ
3311}
3312
034f784d
JB
3313/**
3314 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3315 * @fs_info - the fs_info for this fs
3316 * @return - EINTR if we were killed, 0 if nothing's pending
3317 *
3318 * This will wait on any delayed iputs that are currently running with KILLABLE
3319 * set. Once they are all done running we will return, unless we are killed in
3320 * which case we return EINTR. This helps in user operations like fallocate etc
3321 * that might get blocked on the iputs.
3322 */
3323int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3324{
3325 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3326 atomic_read(&fs_info->nr_delayed_iputs) == 0);
3327 if (ret)
3328 return -EINTR;
3329 return 0;
3330}
3331
7b128766 3332/*
f7e9e8fc
OS
3333 * This creates an orphan entry for the given inode in case something goes wrong
3334 * in the middle of an unlink.
7b128766 3335 */
73f2e545 3336int btrfs_orphan_add(struct btrfs_trans_handle *trans,
27919067 3337 struct btrfs_inode *inode)
7b128766 3338{
d68fc57b 3339 int ret;
7b128766 3340
27919067
OS
3341 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3342 if (ret && ret != -EEXIST) {
3343 btrfs_abort_transaction(trans, ret);
3344 return ret;
d68fc57b
YZ
3345 }
3346
d68fc57b 3347 return 0;
7b128766
JB
3348}
3349
3350/*
f7e9e8fc
OS
3351 * We have done the delete so we can go ahead and remove the orphan item for
3352 * this particular inode.
7b128766 3353 */
48a3b636 3354static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3d6ae7bb 3355 struct btrfs_inode *inode)
7b128766 3356{
27919067 3357 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
7b128766
JB
3358}
3359
3360/*
3361 * this cleans up any orphans that may be left on the list from the last use
3362 * of this root.
3363 */
66b4ffd1 3364int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766 3365{
0b246afa 3366 struct btrfs_fs_info *fs_info = root->fs_info;
7b128766
JB
3367 struct btrfs_path *path;
3368 struct extent_buffer *leaf;
7b128766
JB
3369 struct btrfs_key key, found_key;
3370 struct btrfs_trans_handle *trans;
3371 struct inode *inode;
8f6d7f4f 3372 u64 last_objectid = 0;
f7e9e8fc 3373 int ret = 0, nr_unlink = 0;
7b128766 3374
d68fc57b 3375 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 3376 return 0;
c71bf099
YZ
3377
3378 path = btrfs_alloc_path();
66b4ffd1
JB
3379 if (!path) {
3380 ret = -ENOMEM;
3381 goto out;
3382 }
e4058b54 3383 path->reada = READA_BACK;
7b128766
JB
3384
3385 key.objectid = BTRFS_ORPHAN_OBJECTID;
962a298f 3386 key.type = BTRFS_ORPHAN_ITEM_KEY;
7b128766
JB
3387 key.offset = (u64)-1;
3388
7b128766
JB
3389 while (1) {
3390 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
3391 if (ret < 0)
3392 goto out;
7b128766
JB
3393
3394 /*
3395 * if ret == 0 means we found what we were searching for, which
25985edc 3396 * is weird, but possible, so only screw with path if we didn't
7b128766
JB
3397 * find the key and see if we have stuff that matches
3398 */
3399 if (ret > 0) {
66b4ffd1 3400 ret = 0;
7b128766
JB
3401 if (path->slots[0] == 0)
3402 break;
3403 path->slots[0]--;
3404 }
3405
3406 /* pull out the item */
3407 leaf = path->nodes[0];
7b128766
JB
3408 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3409
3410 /* make sure the item matches what we want */
3411 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3412 break;
962a298f 3413 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
7b128766
JB
3414 break;
3415
3416 /* release the path since we're done with it */
b3b4aa74 3417 btrfs_release_path(path);
7b128766
JB
3418
3419 /*
3420 * this is where we are basically btrfs_lookup, without the
3421 * crossing root thing. we store the inode number in the
3422 * offset of the orphan item.
3423 */
8f6d7f4f
JB
3424
3425 if (found_key.offset == last_objectid) {
0b246afa
JM
3426 btrfs_err(fs_info,
3427 "Error removing orphan entry, stopping orphan cleanup");
8f6d7f4f
JB
3428 ret = -EINVAL;
3429 goto out;
3430 }
3431
3432 last_objectid = found_key.offset;
3433
5d4f98a2
YZ
3434 found_key.objectid = found_key.offset;
3435 found_key.type = BTRFS_INODE_ITEM_KEY;
3436 found_key.offset = 0;
0b246afa 3437 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
8c6ffba0 3438 ret = PTR_ERR_OR_ZERO(inode);
67710892 3439 if (ret && ret != -ENOENT)
66b4ffd1 3440 goto out;
7b128766 3441
0b246afa 3442 if (ret == -ENOENT && root == fs_info->tree_root) {
f8e9e0b0
AJ
3443 struct btrfs_root *dead_root;
3444 struct btrfs_fs_info *fs_info = root->fs_info;
3445 int is_dead_root = 0;
3446
3447 /*
3448 * this is an orphan in the tree root. Currently these
3449 * could come from 2 sources:
3450 * a) a snapshot deletion in progress
3451 * b) a free space cache inode
3452 * We need to distinguish those two, as the snapshot
3453 * orphan must not get deleted.
3454 * find_dead_roots already ran before us, so if this
3455 * is a snapshot deletion, we should find the root
3456 * in the dead_roots list
3457 */
3458 spin_lock(&fs_info->trans_lock);
3459 list_for_each_entry(dead_root, &fs_info->dead_roots,
3460 root_list) {
3461 if (dead_root->root_key.objectid ==
3462 found_key.objectid) {
3463 is_dead_root = 1;
3464 break;
3465 }
3466 }
3467 spin_unlock(&fs_info->trans_lock);
3468 if (is_dead_root) {
3469 /* prevent this orphan from being found again */
3470 key.offset = found_key.objectid - 1;
3471 continue;
3472 }
f7e9e8fc 3473
f8e9e0b0 3474 }
f7e9e8fc 3475
7b128766 3476 /*
f7e9e8fc
OS
3477 * If we have an inode with links, there are a couple of
3478 * possibilities. Old kernels (before v3.12) used to create an
3479 * orphan item for truncate indicating that there were possibly
3480 * extent items past i_size that needed to be deleted. In v3.12,
3481 * truncate was changed to update i_size in sync with the extent
3482 * items, but the (useless) orphan item was still created. Since
3483 * v4.18, we don't create the orphan item for truncate at all.
3484 *
3485 * So, this item could mean that we need to do a truncate, but
3486 * only if this filesystem was last used on a pre-v3.12 kernel
3487 * and was not cleanly unmounted. The odds of that are quite
3488 * slim, and it's a pain to do the truncate now, so just delete
3489 * the orphan item.
3490 *
3491 * It's also possible that this orphan item was supposed to be
3492 * deleted but wasn't. The inode number may have been reused,
3493 * but either way, we can delete the orphan item.
7b128766 3494 */
f7e9e8fc
OS
3495 if (ret == -ENOENT || inode->i_nlink) {
3496 if (!ret)
3497 iput(inode);
a8c9e576 3498 trans = btrfs_start_transaction(root, 1);
66b4ffd1
JB
3499 if (IS_ERR(trans)) {
3500 ret = PTR_ERR(trans);
3501 goto out;
3502 }
0b246afa
JM
3503 btrfs_debug(fs_info, "auto deleting %Lu",
3504 found_key.objectid);
a8c9e576
JB
3505 ret = btrfs_del_orphan_item(trans, root,
3506 found_key.objectid);
3a45bb20 3507 btrfs_end_transaction(trans);
4ef31a45
JB
3508 if (ret)
3509 goto out;
7b128766
JB
3510 continue;
3511 }
3512
f7e9e8fc 3513 nr_unlink++;
7b128766
JB
3514
3515 /* this will do delete_inode and everything for us */
3516 iput(inode);
3517 }
3254c876
MX
3518 /* release the path since we're done with it */
3519 btrfs_release_path(path);
3520
d68fc57b
YZ
3521 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3522
a575ceeb 3523 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
7a7eaa40 3524 trans = btrfs_join_transaction(root);
66b4ffd1 3525 if (!IS_ERR(trans))
3a45bb20 3526 btrfs_end_transaction(trans);
d68fc57b 3527 }
7b128766
JB
3528
3529 if (nr_unlink)
0b246afa 3530 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
66b4ffd1
JB
3531
3532out:
3533 if (ret)
0b246afa 3534 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
66b4ffd1
JB
3535 btrfs_free_path(path);
3536 return ret;
7b128766
JB
3537}
3538
46a53cca
CM
3539/*
3540 * very simple check to peek ahead in the leaf looking for xattrs. If we
3541 * don't find any xattrs, we know there can't be any acls.
3542 *
3543 * slot is the slot the inode is in, objectid is the objectid of the inode
3544 */
3545static noinline int acls_after_inode_item(struct extent_buffer *leaf,
63541927
FDBM
3546 int slot, u64 objectid,
3547 int *first_xattr_slot)
46a53cca
CM
3548{
3549 u32 nritems = btrfs_header_nritems(leaf);
3550 struct btrfs_key found_key;
f23b5a59
JB
3551 static u64 xattr_access = 0;
3552 static u64 xattr_default = 0;
46a53cca
CM
3553 int scanned = 0;
3554
f23b5a59 3555 if (!xattr_access) {
97d79299
AG
3556 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3557 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3558 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3559 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
f23b5a59
JB
3560 }
3561
46a53cca 3562 slot++;
63541927 3563 *first_xattr_slot = -1;
46a53cca
CM
3564 while (slot < nritems) {
3565 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3566
3567 /* we found a different objectid, there must not be acls */
3568 if (found_key.objectid != objectid)
3569 return 0;
3570
3571 /* we found an xattr, assume we've got an acl */
f23b5a59 3572 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
63541927
FDBM
3573 if (*first_xattr_slot == -1)
3574 *first_xattr_slot = slot;
f23b5a59
JB
3575 if (found_key.offset == xattr_access ||
3576 found_key.offset == xattr_default)
3577 return 1;
3578 }
46a53cca
CM
3579
3580 /*
3581 * we found a key greater than an xattr key, there can't
3582 * be any acls later on
3583 */
3584 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3585 return 0;
3586
3587 slot++;
3588 scanned++;
3589
3590 /*
3591 * it goes inode, inode backrefs, xattrs, extents,
3592 * so if there are a ton of hard links to an inode there can
3593 * be a lot of backrefs. Don't waste time searching too hard,
3594 * this is just an optimization
3595 */
3596 if (scanned >= 8)
3597 break;
3598 }
3599 /* we hit the end of the leaf before we found an xattr or
3600 * something larger than an xattr. We have to assume the inode
3601 * has acls
3602 */
63541927
FDBM
3603 if (*first_xattr_slot == -1)
3604 *first_xattr_slot = slot;
46a53cca
CM
3605 return 1;
3606}
3607
d352ac68
CM
3608/*
3609 * read an inode from the btree into the in-memory inode
3610 */
4222ea71
FM
3611static int btrfs_read_locked_inode(struct inode *inode,
3612 struct btrfs_path *in_path)
39279cc3 3613{
0b246afa 3614 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4222ea71 3615 struct btrfs_path *path = in_path;
5f39d397 3616 struct extent_buffer *leaf;
39279cc3
CM
3617 struct btrfs_inode_item *inode_item;
3618 struct btrfs_root *root = BTRFS_I(inode)->root;
3619 struct btrfs_key location;
67de1176 3620 unsigned long ptr;
46a53cca 3621 int maybe_acls;
618e21d5 3622 u32 rdev;
39279cc3 3623 int ret;
2f7e33d4 3624 bool filled = false;
63541927 3625 int first_xattr_slot;
2f7e33d4
MX
3626
3627 ret = btrfs_fill_inode(inode, &rdev);
3628 if (!ret)
3629 filled = true;
39279cc3 3630
4222ea71
FM
3631 if (!path) {
3632 path = btrfs_alloc_path();
3633 if (!path)
3634 return -ENOMEM;
3635 }
1748f843 3636
39279cc3 3637 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 3638
39279cc3 3639 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
67710892 3640 if (ret) {
4222ea71
FM
3641 if (path != in_path)
3642 btrfs_free_path(path);
f5b3a417 3643 return ret;
67710892 3644 }
39279cc3 3645
5f39d397 3646 leaf = path->nodes[0];
2f7e33d4
MX
3647
3648 if (filled)
67de1176 3649 goto cache_index;
2f7e33d4 3650
5f39d397
CM
3651 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3652 struct btrfs_inode_item);
5f39d397 3653 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
bfe86848 3654 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2f2f43d3
EB
3655 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3656 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
6ef06d27 3657 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
5f39d397 3658
a937b979
DS
3659 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3660 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
5f39d397 3661
a937b979
DS
3662 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3663 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
5f39d397 3664
a937b979
DS
3665 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3666 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
5f39d397 3667
9cc97d64 3668 BTRFS_I(inode)->i_otime.tv_sec =
3669 btrfs_timespec_sec(leaf, &inode_item->otime);
3670 BTRFS_I(inode)->i_otime.tv_nsec =
3671 btrfs_timespec_nsec(leaf, &inode_item->otime);
5f39d397 3672
a76a3cd4 3673 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 3674 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
5dc562c5
JB
3675 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3676
c7f88c4e
JL
3677 inode_set_iversion_queried(inode,
3678 btrfs_inode_sequence(leaf, inode_item));
6e17d30b
YD
3679 inode->i_generation = BTRFS_I(inode)->generation;
3680 inode->i_rdev = 0;
3681 rdev = btrfs_inode_rdev(leaf, inode_item);
3682
3683 BTRFS_I(inode)->index_cnt = (u64)-1;
3684 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3685
3686cache_index:
5dc562c5
JB
3687 /*
3688 * If we were modified in the current generation and evicted from memory
3689 * and then re-read we need to do a full sync since we don't have any
3690 * idea about which extents were modified before we were evicted from
3691 * cache.
6e17d30b
YD
3692 *
3693 * This is required for both inode re-read from disk and delayed inode
3694 * in delayed_nodes_tree.
5dc562c5 3695 */
0b246afa 3696 if (BTRFS_I(inode)->last_trans == fs_info->generation)
5dc562c5
JB
3697 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3698 &BTRFS_I(inode)->runtime_flags);
3699
bde6c242
FM
3700 /*
3701 * We don't persist the id of the transaction where an unlink operation
3702 * against the inode was last made. So here we assume the inode might
3703 * have been evicted, and therefore the exact value of last_unlink_trans
3704 * lost, and set it to last_trans to avoid metadata inconsistencies
3705 * between the inode and its parent if the inode is fsync'ed and the log
3706 * replayed. For example, in the scenario:
3707 *
3708 * touch mydir/foo
3709 * ln mydir/foo mydir/bar
3710 * sync
3711 * unlink mydir/bar
3712 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3713 * xfs_io -c fsync mydir/foo
3714 * <power failure>
3715 * mount fs, triggers fsync log replay
3716 *
3717 * We must make sure that when we fsync our inode foo we also log its
3718 * parent inode, otherwise after log replay the parent still has the
3719 * dentry with the "bar" name but our inode foo has a link count of 1
3720 * and doesn't have an inode ref with the name "bar" anymore.
3721 *
3722 * Setting last_unlink_trans to last_trans is a pessimistic approach,
01327610 3723 * but it guarantees correctness at the expense of occasional full
bde6c242
FM
3724 * transaction commits on fsync if our inode is a directory, or if our
3725 * inode is not a directory, logging its parent unnecessarily.
3726 */
3727 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3728
67de1176
MX
3729 path->slots[0]++;
3730 if (inode->i_nlink != 1 ||
3731 path->slots[0] >= btrfs_header_nritems(leaf))
3732 goto cache_acl;
3733
3734 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4a0cc7ca 3735 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
67de1176
MX
3736 goto cache_acl;
3737
3738 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3739 if (location.type == BTRFS_INODE_REF_KEY) {
3740 struct btrfs_inode_ref *ref;
3741
3742 ref = (struct btrfs_inode_ref *)ptr;
3743 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3744 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3745 struct btrfs_inode_extref *extref;
3746
3747 extref = (struct btrfs_inode_extref *)ptr;
3748 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3749 extref);
3750 }
2f7e33d4 3751cache_acl:
46a53cca
CM
3752 /*
3753 * try to precache a NULL acl entry for files that don't have
3754 * any xattrs or acls
3755 */
33345d01 3756 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
f85b7379 3757 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
63541927
FDBM
3758 if (first_xattr_slot != -1) {
3759 path->slots[0] = first_xattr_slot;
3760 ret = btrfs_load_inode_props(inode, path);
3761 if (ret)
0b246afa 3762 btrfs_err(fs_info,
351fd353 3763 "error loading props for ino %llu (root %llu): %d",
4a0cc7ca 3764 btrfs_ino(BTRFS_I(inode)),
63541927
FDBM
3765 root->root_key.objectid, ret);
3766 }
4222ea71
FM
3767 if (path != in_path)
3768 btrfs_free_path(path);
63541927 3769
72c04902
AV
3770 if (!maybe_acls)
3771 cache_no_acl(inode);
46a53cca 3772
39279cc3 3773 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
3774 case S_IFREG:
3775 inode->i_mapping->a_ops = &btrfs_aops;
d1310b2e 3776 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
3777 inode->i_fop = &btrfs_file_operations;
3778 inode->i_op = &btrfs_file_inode_operations;
3779 break;
3780 case S_IFDIR:
3781 inode->i_fop = &btrfs_dir_file_operations;
67ade058 3782 inode->i_op = &btrfs_dir_inode_operations;
39279cc3
CM
3783 break;
3784 case S_IFLNK:
3785 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 3786 inode_nohighmem(inode);
4779cc04 3787 inode->i_mapping->a_ops = &btrfs_aops;
39279cc3 3788 break;
618e21d5 3789 default:
0279b4cd 3790 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
3791 init_special_inode(inode, inode->i_mode, rdev);
3792 break;
39279cc3 3793 }
6cbff00f 3794
7b6a221e 3795 btrfs_sync_inode_flags_to_i_flags(inode);
67710892 3796 return 0;
39279cc3
CM
3797}
3798
d352ac68
CM
3799/*
3800 * given a leaf and an inode, copy the inode fields into the leaf
3801 */
e02119d5
CM
3802static void fill_inode_item(struct btrfs_trans_handle *trans,
3803 struct extent_buffer *leaf,
5f39d397 3804 struct btrfs_inode_item *item,
39279cc3
CM
3805 struct inode *inode)
3806{
51fab693
LB
3807 struct btrfs_map_token token;
3808
3809 btrfs_init_map_token(&token);
5f39d397 3810
51fab693
LB
3811 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3812 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3813 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3814 &token);
3815 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3816 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
5f39d397 3817
a937b979 3818 btrfs_set_token_timespec_sec(leaf, &item->atime,
51fab693 3819 inode->i_atime.tv_sec, &token);
a937b979 3820 btrfs_set_token_timespec_nsec(leaf, &item->atime,
51fab693 3821 inode->i_atime.tv_nsec, &token);
5f39d397 3822
a937b979 3823 btrfs_set_token_timespec_sec(leaf, &item->mtime,
51fab693 3824 inode->i_mtime.tv_sec, &token);
a937b979 3825 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
51fab693 3826 inode->i_mtime.tv_nsec, &token);
5f39d397 3827
a937b979 3828 btrfs_set_token_timespec_sec(leaf, &item->ctime,
51fab693 3829 inode->i_ctime.tv_sec, &token);
a937b979 3830 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
51fab693 3831 inode->i_ctime.tv_nsec, &token);
5f39d397 3832
9cc97d64 3833 btrfs_set_token_timespec_sec(leaf, &item->otime,
3834 BTRFS_I(inode)->i_otime.tv_sec, &token);
3835 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3836 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3837
51fab693
LB
3838 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3839 &token);
3840 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3841 &token);
c7f88c4e
JL
3842 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3843 &token);
51fab693
LB
3844 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3845 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3846 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3847 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
39279cc3
CM
3848}
3849
d352ac68
CM
3850/*
3851 * copy everything in the in-memory inode into the btree.
3852 */
2115133f 3853static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
d397712b 3854 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
3855{
3856 struct btrfs_inode_item *inode_item;
3857 struct btrfs_path *path;
5f39d397 3858 struct extent_buffer *leaf;
39279cc3
CM
3859 int ret;
3860
3861 path = btrfs_alloc_path();
16cdcec7
MX
3862 if (!path)
3863 return -ENOMEM;
3864
b9473439 3865 path->leave_spinning = 1;
16cdcec7
MX
3866 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3867 1);
39279cc3
CM
3868 if (ret) {
3869 if (ret > 0)
3870 ret = -ENOENT;
3871 goto failed;
3872 }
3873
5f39d397
CM
3874 leaf = path->nodes[0];
3875 inode_item = btrfs_item_ptr(leaf, path->slots[0],
16cdcec7 3876 struct btrfs_inode_item);
39279cc3 3877
e02119d5 3878 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 3879 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 3880 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
3881 ret = 0;
3882failed:
39279cc3
CM
3883 btrfs_free_path(path);
3884 return ret;
3885}
3886
2115133f
CM
3887/*
3888 * copy everything in the in-memory inode into the btree.
3889 */
3890noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3891 struct btrfs_root *root, struct inode *inode)
3892{
0b246afa 3893 struct btrfs_fs_info *fs_info = root->fs_info;
2115133f
CM
3894 int ret;
3895
3896 /*
3897 * If the inode is a free space inode, we can deadlock during commit
3898 * if we put it into the delayed code.
3899 *
3900 * The data relocation inode should also be directly updated
3901 * without delay
3902 */
70ddc553 3903 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
1d52c78a 3904 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
0b246afa 3905 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
8ea05e3a
AB
3906 btrfs_update_root_times(trans, root);
3907
2115133f
CM
3908 ret = btrfs_delayed_update_inode(trans, root, inode);
3909 if (!ret)
3910 btrfs_set_inode_last_trans(trans, inode);
3911 return ret;
3912 }
3913
3914 return btrfs_update_inode_item(trans, root, inode);
3915}
3916
be6aef60
JB
3917noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3918 struct btrfs_root *root,
3919 struct inode *inode)
2115133f
CM
3920{
3921 int ret;
3922
3923 ret = btrfs_update_inode(trans, root, inode);
3924 if (ret == -ENOSPC)
3925 return btrfs_update_inode_item(trans, root, inode);
3926 return ret;
3927}
3928
d352ac68
CM
3929/*
3930 * unlink helper that gets used here in inode.c and in the tree logging
3931 * recovery code. It remove a link in a directory with a given name, and
3932 * also drops the back refs in the inode to the directory
3933 */
92986796
AV
3934static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3935 struct btrfs_root *root,
4ec5934e
NB
3936 struct btrfs_inode *dir,
3937 struct btrfs_inode *inode,
92986796 3938 const char *name, int name_len)
39279cc3 3939{
0b246afa 3940 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 3941 struct btrfs_path *path;
39279cc3 3942 int ret = 0;
5f39d397 3943 struct extent_buffer *leaf;
39279cc3 3944 struct btrfs_dir_item *di;
5f39d397 3945 struct btrfs_key key;
aec7477b 3946 u64 index;
33345d01
LZ
3947 u64 ino = btrfs_ino(inode);
3948 u64 dir_ino = btrfs_ino(dir);
39279cc3
CM
3949
3950 path = btrfs_alloc_path();
54aa1f4d
CM
3951 if (!path) {
3952 ret = -ENOMEM;
554233a6 3953 goto out;
54aa1f4d
CM
3954 }
3955
b9473439 3956 path->leave_spinning = 1;
33345d01 3957 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
39279cc3 3958 name, name_len, -1);
3cf5068f
LB
3959 if (IS_ERR_OR_NULL(di)) {
3960 ret = di ? PTR_ERR(di) : -ENOENT;
39279cc3
CM
3961 goto err;
3962 }
5f39d397
CM
3963 leaf = path->nodes[0];
3964 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 3965 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
3966 if (ret)
3967 goto err;
b3b4aa74 3968 btrfs_release_path(path);
39279cc3 3969
67de1176
MX
3970 /*
3971 * If we don't have dir index, we have to get it by looking up
3972 * the inode ref, since we get the inode ref, remove it directly,
3973 * it is unnecessary to do delayed deletion.
3974 *
3975 * But if we have dir index, needn't search inode ref to get it.
3976 * Since the inode ref is close to the inode item, it is better
3977 * that we delay to delete it, and just do this deletion when
3978 * we update the inode item.
3979 */
4ec5934e 3980 if (inode->dir_index) {
67de1176
MX
3981 ret = btrfs_delayed_delete_inode_ref(inode);
3982 if (!ret) {
4ec5934e 3983 index = inode->dir_index;
67de1176
MX
3984 goto skip_backref;
3985 }
3986 }
3987
33345d01
LZ
3988 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3989 dir_ino, &index);
aec7477b 3990 if (ret) {
0b246afa 3991 btrfs_info(fs_info,
c2cf52eb 3992 "failed to delete reference to %.*s, inode %llu parent %llu",
c1c9ff7c 3993 name_len, name, ino, dir_ino);
66642832 3994 btrfs_abort_transaction(trans, ret);
aec7477b
JB
3995 goto err;
3996 }
67de1176 3997skip_backref:
9add2945 3998 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
79787eaa 3999 if (ret) {
66642832 4000 btrfs_abort_transaction(trans, ret);
39279cc3 4001 goto err;
79787eaa 4002 }
39279cc3 4003
4ec5934e
NB
4004 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4005 dir_ino);
79787eaa 4006 if (ret != 0 && ret != -ENOENT) {
66642832 4007 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4008 goto err;
4009 }
e02119d5 4010
4ec5934e
NB
4011 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4012 index);
6418c961
CM
4013 if (ret == -ENOENT)
4014 ret = 0;
d4e3991b 4015 else if (ret)
66642832 4016 btrfs_abort_transaction(trans, ret);
39279cc3
CM
4017err:
4018 btrfs_free_path(path);
e02119d5
CM
4019 if (ret)
4020 goto out;
4021
6ef06d27 4022 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4ec5934e
NB
4023 inode_inc_iversion(&inode->vfs_inode);
4024 inode_inc_iversion(&dir->vfs_inode);
4025 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4026 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4027 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
e02119d5 4028out:
39279cc3
CM
4029 return ret;
4030}
4031
92986796
AV
4032int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4033 struct btrfs_root *root,
4ec5934e 4034 struct btrfs_inode *dir, struct btrfs_inode *inode,
92986796
AV
4035 const char *name, int name_len)
4036{
4037 int ret;
4038 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4039 if (!ret) {
4ec5934e
NB
4040 drop_nlink(&inode->vfs_inode);
4041 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
92986796
AV
4042 }
4043 return ret;
4044}
39279cc3 4045
a22285a6
YZ
4046/*
4047 * helper to start transaction for unlink and rmdir.
4048 *
d52be818
JB
4049 * unlink and rmdir are special in btrfs, they do not always free space, so
4050 * if we cannot make our reservations the normal way try and see if there is
4051 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4052 * allow the unlink to occur.
a22285a6 4053 */
d52be818 4054static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4df27c4d 4055{
a22285a6 4056 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d 4057
e70bea5f
JB
4058 /*
4059 * 1 for the possible orphan item
4060 * 1 for the dir item
4061 * 1 for the dir index
4062 * 1 for the inode ref
e70bea5f
JB
4063 * 1 for the inode
4064 */
8eab77ff 4065 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
a22285a6
YZ
4066}
4067
4068static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4069{
4070 struct btrfs_root *root = BTRFS_I(dir)->root;
4071 struct btrfs_trans_handle *trans;
2b0143b5 4072 struct inode *inode = d_inode(dentry);
a22285a6 4073 int ret;
a22285a6 4074
d52be818 4075 trans = __unlink_start_trans(dir);
a22285a6
YZ
4076 if (IS_ERR(trans))
4077 return PTR_ERR(trans);
5f39d397 4078
4ec5934e
NB
4079 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4080 0);
12fcfd22 4081
4ec5934e
NB
4082 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4083 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4084 dentry->d_name.len);
b532402e
TI
4085 if (ret)
4086 goto out;
7b128766 4087
a22285a6 4088 if (inode->i_nlink == 0) {
73f2e545 4089 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
b532402e
TI
4090 if (ret)
4091 goto out;
a22285a6 4092 }
7b128766 4093
b532402e 4094out:
3a45bb20 4095 btrfs_end_transaction(trans);
2ff7e61e 4096 btrfs_btree_balance_dirty(root->fs_info);
39279cc3
CM
4097 return ret;
4098}
4099
f60a2364 4100static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
401b3b19
LF
4101 struct inode *dir, u64 objectid,
4102 const char *name, int name_len)
4df27c4d 4103{
401b3b19 4104 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d
YZ
4105 struct btrfs_path *path;
4106 struct extent_buffer *leaf;
4107 struct btrfs_dir_item *di;
4108 struct btrfs_key key;
4109 u64 index;
4110 int ret;
4a0cc7ca 4111 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4df27c4d
YZ
4112
4113 path = btrfs_alloc_path();
4114 if (!path)
4115 return -ENOMEM;
4116
33345d01 4117 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4df27c4d 4118 name, name_len, -1);
79787eaa 4119 if (IS_ERR_OR_NULL(di)) {
3cf5068f 4120 ret = di ? PTR_ERR(di) : -ENOENT;
79787eaa
JM
4121 goto out;
4122 }
4df27c4d
YZ
4123
4124 leaf = path->nodes[0];
4125 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4126 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4127 ret = btrfs_delete_one_dir_name(trans, root, path, di);
79787eaa 4128 if (ret) {
66642832 4129 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4130 goto out;
4131 }
b3b4aa74 4132 btrfs_release_path(path);
4df27c4d 4133
3ee1c553
LF
4134 ret = btrfs_del_root_ref(trans, objectid, root->root_key.objectid,
4135 dir_ino, &index, name, name_len);
4df27c4d 4136 if (ret < 0) {
79787eaa 4137 if (ret != -ENOENT) {
66642832 4138 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4139 goto out;
4140 }
33345d01 4141 di = btrfs_search_dir_index_item(root, path, dir_ino,
4df27c4d 4142 name, name_len);
79787eaa
JM
4143 if (IS_ERR_OR_NULL(di)) {
4144 if (!di)
4145 ret = -ENOENT;
4146 else
4147 ret = PTR_ERR(di);
66642832 4148 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4149 goto out;
4150 }
4df27c4d
YZ
4151
4152 leaf = path->nodes[0];
4153 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4df27c4d
YZ
4154 index = key.offset;
4155 }
945d8962 4156 btrfs_release_path(path);
4df27c4d 4157
9add2945 4158 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
79787eaa 4159 if (ret) {
66642832 4160 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4161 goto out;
4162 }
4df27c4d 4163
6ef06d27 4164 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
0c4d2d95 4165 inode_inc_iversion(dir);
c2050a45 4166 dir->i_mtime = dir->i_ctime = current_time(dir);
5a24e84c 4167 ret = btrfs_update_inode_fallback(trans, root, dir);
79787eaa 4168 if (ret)
66642832 4169 btrfs_abort_transaction(trans, ret);
79787eaa 4170out:
71d7aed0 4171 btrfs_free_path(path);
79787eaa 4172 return ret;
4df27c4d
YZ
4173}
4174
ec42f167
MT
4175/*
4176 * Helper to check if the subvolume references other subvolumes or if it's
4177 * default.
4178 */
f60a2364 4179static noinline int may_destroy_subvol(struct btrfs_root *root)
ec42f167
MT
4180{
4181 struct btrfs_fs_info *fs_info = root->fs_info;
4182 struct btrfs_path *path;
4183 struct btrfs_dir_item *di;
4184 struct btrfs_key key;
4185 u64 dir_id;
4186 int ret;
4187
4188 path = btrfs_alloc_path();
4189 if (!path)
4190 return -ENOMEM;
4191
4192 /* Make sure this root isn't set as the default subvol */
4193 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4194 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4195 dir_id, "default", 7, 0);
4196 if (di && !IS_ERR(di)) {
4197 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4198 if (key.objectid == root->root_key.objectid) {
4199 ret = -EPERM;
4200 btrfs_err(fs_info,
4201 "deleting default subvolume %llu is not allowed",
4202 key.objectid);
4203 goto out;
4204 }
4205 btrfs_release_path(path);
4206 }
4207
4208 key.objectid = root->root_key.objectid;
4209 key.type = BTRFS_ROOT_REF_KEY;
4210 key.offset = (u64)-1;
4211
4212 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4213 if (ret < 0)
4214 goto out;
4215 BUG_ON(ret == 0);
4216
4217 ret = 0;
4218 if (path->slots[0] > 0) {
4219 path->slots[0]--;
4220 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4221 if (key.objectid == root->root_key.objectid &&
4222 key.type == BTRFS_ROOT_REF_KEY)
4223 ret = -ENOTEMPTY;
4224 }
4225out:
4226 btrfs_free_path(path);
4227 return ret;
4228}
4229
20a68004
NB
4230/* Delete all dentries for inodes belonging to the root */
4231static void btrfs_prune_dentries(struct btrfs_root *root)
4232{
4233 struct btrfs_fs_info *fs_info = root->fs_info;
4234 struct rb_node *node;
4235 struct rb_node *prev;
4236 struct btrfs_inode *entry;
4237 struct inode *inode;
4238 u64 objectid = 0;
4239
4240 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4241 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4242
4243 spin_lock(&root->inode_lock);
4244again:
4245 node = root->inode_tree.rb_node;
4246 prev = NULL;
4247 while (node) {
4248 prev = node;
4249 entry = rb_entry(node, struct btrfs_inode, rb_node);
4250
37508515 4251 if (objectid < btrfs_ino(entry))
20a68004 4252 node = node->rb_left;
37508515 4253 else if (objectid > btrfs_ino(entry))
20a68004
NB
4254 node = node->rb_right;
4255 else
4256 break;
4257 }
4258 if (!node) {
4259 while (prev) {
4260 entry = rb_entry(prev, struct btrfs_inode, rb_node);
37508515 4261 if (objectid <= btrfs_ino(entry)) {
20a68004
NB
4262 node = prev;
4263 break;
4264 }
4265 prev = rb_next(prev);
4266 }
4267 }
4268 while (node) {
4269 entry = rb_entry(node, struct btrfs_inode, rb_node);
37508515 4270 objectid = btrfs_ino(entry) + 1;
20a68004
NB
4271 inode = igrab(&entry->vfs_inode);
4272 if (inode) {
4273 spin_unlock(&root->inode_lock);
4274 if (atomic_read(&inode->i_count) > 1)
4275 d_prune_aliases(inode);
4276 /*
4277 * btrfs_drop_inode will have it removed from the inode
4278 * cache when its usage count hits zero.
4279 */
4280 iput(inode);
4281 cond_resched();
4282 spin_lock(&root->inode_lock);
4283 goto again;
4284 }
4285
4286 if (cond_resched_lock(&root->inode_lock))
4287 goto again;
4288
4289 node = rb_next(node);
4290 }
4291 spin_unlock(&root->inode_lock);
4292}
4293
f60a2364
MT
4294int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4295{
4296 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4297 struct btrfs_root *root = BTRFS_I(dir)->root;
4298 struct inode *inode = d_inode(dentry);
4299 struct btrfs_root *dest = BTRFS_I(inode)->root;
4300 struct btrfs_trans_handle *trans;
4301 struct btrfs_block_rsv block_rsv;
4302 u64 root_flags;
f60a2364
MT
4303 int ret;
4304 int err;
4305
4306 /*
4307 * Don't allow to delete a subvolume with send in progress. This is
4308 * inside the inode lock so the error handling that has to drop the bit
4309 * again is not run concurrently.
4310 */
4311 spin_lock(&dest->root_item_lock);
a7176f74 4312 if (dest->send_in_progress) {
f60a2364
MT
4313 spin_unlock(&dest->root_item_lock);
4314 btrfs_warn(fs_info,
4315 "attempt to delete subvolume %llu during send",
4316 dest->root_key.objectid);
4317 return -EPERM;
4318 }
a7176f74
LF
4319 root_flags = btrfs_root_flags(&dest->root_item);
4320 btrfs_set_root_flags(&dest->root_item,
4321 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4322 spin_unlock(&dest->root_item_lock);
f60a2364
MT
4323
4324 down_write(&fs_info->subvol_sem);
4325
4326 err = may_destroy_subvol(dest);
4327 if (err)
4328 goto out_up_write;
4329
4330 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4331 /*
4332 * One for dir inode,
4333 * two for dir entries,
4334 * two for root ref/backref.
4335 */
c4c129db 4336 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
f60a2364
MT
4337 if (err)
4338 goto out_up_write;
4339
4340 trans = btrfs_start_transaction(root, 0);
4341 if (IS_ERR(trans)) {
4342 err = PTR_ERR(trans);
4343 goto out_release;
4344 }
4345 trans->block_rsv = &block_rsv;
4346 trans->bytes_reserved = block_rsv.size;
4347
4348 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4349
401b3b19
LF
4350 ret = btrfs_unlink_subvol(trans, dir, dest->root_key.objectid,
4351 dentry->d_name.name, dentry->d_name.len);
f60a2364
MT
4352 if (ret) {
4353 err = ret;
4354 btrfs_abort_transaction(trans, ret);
4355 goto out_end_trans;
4356 }
4357
4358 btrfs_record_root_in_trans(trans, dest);
4359
4360 memset(&dest->root_item.drop_progress, 0,
4361 sizeof(dest->root_item.drop_progress));
4362 dest->root_item.drop_level = 0;
4363 btrfs_set_root_refs(&dest->root_item, 0);
4364
4365 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4366 ret = btrfs_insert_orphan_item(trans,
4367 fs_info->tree_root,
4368 dest->root_key.objectid);
4369 if (ret) {
4370 btrfs_abort_transaction(trans, ret);
4371 err = ret;
4372 goto out_end_trans;
4373 }
4374 }
4375
d1957791 4376 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
f60a2364
MT
4377 BTRFS_UUID_KEY_SUBVOL,
4378 dest->root_key.objectid);
4379 if (ret && ret != -ENOENT) {
4380 btrfs_abort_transaction(trans, ret);
4381 err = ret;
4382 goto out_end_trans;
4383 }
4384 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
d1957791 4385 ret = btrfs_uuid_tree_remove(trans,
f60a2364
MT
4386 dest->root_item.received_uuid,
4387 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4388 dest->root_key.objectid);
4389 if (ret && ret != -ENOENT) {
4390 btrfs_abort_transaction(trans, ret);
4391 err = ret;
4392 goto out_end_trans;
4393 }
4394 }
4395
4396out_end_trans:
4397 trans->block_rsv = NULL;
4398 trans->bytes_reserved = 0;
4399 ret = btrfs_end_transaction(trans);
4400 if (ret && !err)
4401 err = ret;
4402 inode->i_flags |= S_DEAD;
4403out_release:
4404 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4405out_up_write:
4406 up_write(&fs_info->subvol_sem);
4407 if (err) {
4408 spin_lock(&dest->root_item_lock);
4409 root_flags = btrfs_root_flags(&dest->root_item);
4410 btrfs_set_root_flags(&dest->root_item,
4411 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4412 spin_unlock(&dest->root_item_lock);
4413 } else {
4414 d_invalidate(dentry);
20a68004 4415 btrfs_prune_dentries(dest);
f60a2364
MT
4416 ASSERT(dest->send_in_progress == 0);
4417
4418 /* the last ref */
4419 if (dest->ino_cache_inode) {
4420 iput(dest->ino_cache_inode);
4421 dest->ino_cache_inode = NULL;
4422 }
4423 }
4424
4425 return err;
4426}
4427
39279cc3
CM
4428static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4429{
2b0143b5 4430 struct inode *inode = d_inode(dentry);
1832a6d5 4431 int err = 0;
39279cc3 4432 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 4433 struct btrfs_trans_handle *trans;
44f714da 4434 u64 last_unlink_trans;
39279cc3 4435
b3ae244e 4436 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
134d4512 4437 return -ENOTEMPTY;
4a0cc7ca 4438 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
a79a464d 4439 return btrfs_delete_subvolume(dir, dentry);
134d4512 4440
d52be818 4441 trans = __unlink_start_trans(dir);
a22285a6 4442 if (IS_ERR(trans))
5df6a9f6 4443 return PTR_ERR(trans);
5df6a9f6 4444
4a0cc7ca 4445 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
401b3b19 4446 err = btrfs_unlink_subvol(trans, dir,
4df27c4d
YZ
4447 BTRFS_I(inode)->location.objectid,
4448 dentry->d_name.name,
4449 dentry->d_name.len);
4450 goto out;
4451 }
4452
73f2e545 4453 err = btrfs_orphan_add(trans, BTRFS_I(inode));
7b128766 4454 if (err)
4df27c4d 4455 goto out;
7b128766 4456
44f714da
FM
4457 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4458
39279cc3 4459 /* now the directory is empty */
4ec5934e
NB
4460 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4461 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4462 dentry->d_name.len);
44f714da 4463 if (!err) {
6ef06d27 4464 btrfs_i_size_write(BTRFS_I(inode), 0);
44f714da
FM
4465 /*
4466 * Propagate the last_unlink_trans value of the deleted dir to
4467 * its parent directory. This is to prevent an unrecoverable
4468 * log tree in the case we do something like this:
4469 * 1) create dir foo
4470 * 2) create snapshot under dir foo
4471 * 3) delete the snapshot
4472 * 4) rmdir foo
4473 * 5) mkdir foo
4474 * 6) fsync foo or some file inside foo
4475 */
4476 if (last_unlink_trans >= trans->transid)
4477 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4478 }
4df27c4d 4479out:
3a45bb20 4480 btrfs_end_transaction(trans);
2ff7e61e 4481 btrfs_btree_balance_dirty(root->fs_info);
3954401f 4482
39279cc3
CM
4483 return err;
4484}
4485
ddfae63c
JB
4486/*
4487 * Return this if we need to call truncate_block for the last bit of the
4488 * truncate.
4489 */
4490#define NEED_TRUNCATE_BLOCK 1
0305cd5f 4491
39279cc3
CM
4492/*
4493 * this can truncate away extent items, csum items and directory items.
4494 * It starts at a high offset and removes keys until it can't find
d352ac68 4495 * any higher than new_size
39279cc3
CM
4496 *
4497 * csum items that cross the new i_size are truncated to the new size
4498 * as well.
7b128766
JB
4499 *
4500 * min_type is the minimum key type to truncate down to. If set to 0, this
4501 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 4502 */
8082510e
YZ
4503int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4504 struct btrfs_root *root,
4505 struct inode *inode,
4506 u64 new_size, u32 min_type)
39279cc3 4507{
0b246afa 4508 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 4509 struct btrfs_path *path;
5f39d397 4510 struct extent_buffer *leaf;
39279cc3 4511 struct btrfs_file_extent_item *fi;
8082510e
YZ
4512 struct btrfs_key key;
4513 struct btrfs_key found_key;
39279cc3 4514 u64 extent_start = 0;
db94535d 4515 u64 extent_num_bytes = 0;
5d4f98a2 4516 u64 extent_offset = 0;
39279cc3 4517 u64 item_end = 0;
c1aa4575 4518 u64 last_size = new_size;
8082510e 4519 u32 found_type = (u8)-1;
39279cc3
CM
4520 int found_extent;
4521 int del_item;
85e21bac
CM
4522 int pending_del_nr = 0;
4523 int pending_del_slot = 0;
179e29e4 4524 int extent_type = -1;
8082510e 4525 int ret;
4a0cc7ca 4526 u64 ino = btrfs_ino(BTRFS_I(inode));
28ed1345 4527 u64 bytes_deleted = 0;
897ca819
TM
4528 bool be_nice = false;
4529 bool should_throttle = false;
8082510e
YZ
4530
4531 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 4532
28ed1345
CM
4533 /*
4534 * for non-free space inodes and ref cows, we want to back off from
4535 * time to time
4536 */
70ddc553 4537 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
28ed1345 4538 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
897ca819 4539 be_nice = true;
28ed1345 4540
0eb0e19c
MF
4541 path = btrfs_alloc_path();
4542 if (!path)
4543 return -ENOMEM;
e4058b54 4544 path->reada = READA_BACK;
0eb0e19c 4545
5dc562c5
JB
4546 /*
4547 * We want to drop from the next block forward in case this new size is
4548 * not block aligned since we will be keeping the last block of the
4549 * extent just the way it is.
4550 */
27cdeb70 4551 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4552 root == fs_info->tree_root)
dcdbc059 4553 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
0b246afa 4554 fs_info->sectorsize),
da17066c 4555 (u64)-1, 0);
8082510e 4556
16cdcec7
MX
4557 /*
4558 * This function is also used to drop the items in the log tree before
4559 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
52042d8e 4560 * it is used to drop the logged items. So we shouldn't kill the delayed
16cdcec7
MX
4561 * items.
4562 */
4563 if (min_type == 0 && root == BTRFS_I(inode)->root)
4ccb5c72 4564 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
16cdcec7 4565
33345d01 4566 key.objectid = ino;
39279cc3 4567 key.offset = (u64)-1;
5f39d397
CM
4568 key.type = (u8)-1;
4569
85e21bac 4570search_again:
28ed1345
CM
4571 /*
4572 * with a 16K leaf size and 128MB extents, you can actually queue
4573 * up a huge file in a single leaf. Most of the time that
4574 * bytes_deleted is > 0, it will be huge by the time we get here
4575 */
fd86a3a3
OS
4576 if (be_nice && bytes_deleted > SZ_32M &&
4577 btrfs_should_end_transaction(trans)) {
4578 ret = -EAGAIN;
4579 goto out;
28ed1345
CM
4580 }
4581
b9473439 4582 path->leave_spinning = 1;
85e21bac 4583 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
fd86a3a3 4584 if (ret < 0)
8082510e 4585 goto out;
d397712b 4586
85e21bac 4587 if (ret > 0) {
fd86a3a3 4588 ret = 0;
e02119d5
CM
4589 /* there are no items in the tree for us to truncate, we're
4590 * done
4591 */
8082510e
YZ
4592 if (path->slots[0] == 0)
4593 goto out;
85e21bac
CM
4594 path->slots[0]--;
4595 }
4596
d397712b 4597 while (1) {
39279cc3 4598 fi = NULL;
5f39d397
CM
4599 leaf = path->nodes[0];
4600 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 4601 found_type = found_key.type;
39279cc3 4602
33345d01 4603 if (found_key.objectid != ino)
39279cc3 4604 break;
5f39d397 4605
85e21bac 4606 if (found_type < min_type)
39279cc3
CM
4607 break;
4608
5f39d397 4609 item_end = found_key.offset;
39279cc3 4610 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 4611 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 4612 struct btrfs_file_extent_item);
179e29e4
CM
4613 extent_type = btrfs_file_extent_type(leaf, fi);
4614 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 4615 item_end +=
db94535d 4616 btrfs_file_extent_num_bytes(leaf, fi);
09ed2f16
LB
4617
4618 trace_btrfs_truncate_show_fi_regular(
4619 BTRFS_I(inode), leaf, fi,
4620 found_key.offset);
179e29e4 4621 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
e41ca589
QW
4622 item_end += btrfs_file_extent_ram_bytes(leaf,
4623 fi);
09ed2f16
LB
4624
4625 trace_btrfs_truncate_show_fi_inline(
4626 BTRFS_I(inode), leaf, fi, path->slots[0],
4627 found_key.offset);
39279cc3 4628 }
008630c1 4629 item_end--;
39279cc3 4630 }
8082510e
YZ
4631 if (found_type > min_type) {
4632 del_item = 1;
4633 } else {
76b42abb 4634 if (item_end < new_size)
b888db2b 4635 break;
8082510e
YZ
4636 if (found_key.offset >= new_size)
4637 del_item = 1;
4638 else
4639 del_item = 0;
39279cc3 4640 }
39279cc3 4641 found_extent = 0;
39279cc3 4642 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
4643 if (found_type != BTRFS_EXTENT_DATA_KEY)
4644 goto delete;
4645
4646 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 4647 u64 num_dec;
db94535d 4648 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
f70a9a6b 4649 if (!del_item) {
db94535d
CM
4650 u64 orig_num_bytes =
4651 btrfs_file_extent_num_bytes(leaf, fi);
fda2832f
QW
4652 extent_num_bytes = ALIGN(new_size -
4653 found_key.offset,
0b246afa 4654 fs_info->sectorsize);
db94535d
CM
4655 btrfs_set_file_extent_num_bytes(leaf, fi,
4656 extent_num_bytes);
4657 num_dec = (orig_num_bytes -
9069218d 4658 extent_num_bytes);
27cdeb70
MX
4659 if (test_bit(BTRFS_ROOT_REF_COWS,
4660 &root->state) &&
4661 extent_start != 0)
a76a3cd4 4662 inode_sub_bytes(inode, num_dec);
5f39d397 4663 btrfs_mark_buffer_dirty(leaf);
39279cc3 4664 } else {
db94535d
CM
4665 extent_num_bytes =
4666 btrfs_file_extent_disk_num_bytes(leaf,
4667 fi);
5d4f98a2
YZ
4668 extent_offset = found_key.offset -
4669 btrfs_file_extent_offset(leaf, fi);
4670
39279cc3 4671 /* FIXME blocksize != 4096 */
9069218d 4672 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
4673 if (extent_start != 0) {
4674 found_extent = 1;
27cdeb70
MX
4675 if (test_bit(BTRFS_ROOT_REF_COWS,
4676 &root->state))
a76a3cd4 4677 inode_sub_bytes(inode, num_dec);
e02119d5 4678 }
39279cc3 4679 }
9069218d 4680 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
4681 /*
4682 * we can't truncate inline items that have had
4683 * special encodings
4684 */
4685 if (!del_item &&
c8b97818 4686 btrfs_file_extent_encryption(leaf, fi) == 0 &&
ddfae63c
JB
4687 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4688 btrfs_file_extent_compression(leaf, fi) == 0) {
4689 u32 size = (u32)(new_size - found_key.offset);
4690
4691 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4692 size = btrfs_file_extent_calc_inline_size(size);
78ac4f9e 4693 btrfs_truncate_item(path, size, 1);
ddfae63c 4694 } else if (!del_item) {
514ac8ad 4695 /*
ddfae63c
JB
4696 * We have to bail so the last_size is set to
4697 * just before this extent.
514ac8ad 4698 */
fd86a3a3 4699 ret = NEED_TRUNCATE_BLOCK;
ddfae63c
JB
4700 break;
4701 }
0305cd5f 4702
ddfae63c 4703 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
0305cd5f 4704 inode_sub_bytes(inode, item_end + 1 - new_size);
39279cc3 4705 }
179e29e4 4706delete:
ddfae63c
JB
4707 if (del_item)
4708 last_size = found_key.offset;
4709 else
4710 last_size = new_size;
39279cc3 4711 if (del_item) {
85e21bac
CM
4712 if (!pending_del_nr) {
4713 /* no pending yet, add ourselves */
4714 pending_del_slot = path->slots[0];
4715 pending_del_nr = 1;
4716 } else if (pending_del_nr &&
4717 path->slots[0] + 1 == pending_del_slot) {
4718 /* hop on the pending chunk */
4719 pending_del_nr++;
4720 pending_del_slot = path->slots[0];
4721 } else {
d397712b 4722 BUG();
85e21bac 4723 }
39279cc3
CM
4724 } else {
4725 break;
4726 }
897ca819 4727 should_throttle = false;
28f75a0e 4728
27cdeb70
MX
4729 if (found_extent &&
4730 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4731 root == fs_info->tree_root)) {
ffd4bb2a
QW
4732 struct btrfs_ref ref = { 0 };
4733
b9473439 4734 btrfs_set_path_blocking(path);
28ed1345 4735 bytes_deleted += extent_num_bytes;
ffd4bb2a
QW
4736
4737 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4738 extent_start, extent_num_bytes, 0);
4739 ref.real_root = root->root_key.objectid;
4740 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4741 ino, extent_offset);
4742 ret = btrfs_free_extent(trans, &ref);
05522109
OS
4743 if (ret) {
4744 btrfs_abort_transaction(trans, ret);
4745 break;
4746 }
28f75a0e 4747 if (be_nice) {
7c861627 4748 if (btrfs_should_throttle_delayed_refs(trans))
897ca819 4749 should_throttle = true;
28f75a0e 4750 }
39279cc3 4751 }
85e21bac 4752
8082510e
YZ
4753 if (found_type == BTRFS_INODE_ITEM_KEY)
4754 break;
4755
4756 if (path->slots[0] == 0 ||
1262133b 4757 path->slots[0] != pending_del_slot ||
28bad212 4758 should_throttle) {
8082510e
YZ
4759 if (pending_del_nr) {
4760 ret = btrfs_del_items(trans, root, path,
4761 pending_del_slot,
4762 pending_del_nr);
79787eaa 4763 if (ret) {
66642832 4764 btrfs_abort_transaction(trans, ret);
fd86a3a3 4765 break;
79787eaa 4766 }
8082510e
YZ
4767 pending_del_nr = 0;
4768 }
b3b4aa74 4769 btrfs_release_path(path);
28bad212 4770
28f75a0e 4771 /*
28bad212
JB
4772 * We can generate a lot of delayed refs, so we need to
4773 * throttle every once and a while and make sure we're
4774 * adding enough space to keep up with the work we are
4775 * generating. Since we hold a transaction here we
4776 * can't flush, and we don't want to FLUSH_LIMIT because
4777 * we could have generated too many delayed refs to
4778 * actually allocate, so just bail if we're short and
4779 * let the normal reservation dance happen higher up.
28f75a0e 4780 */
28bad212
JB
4781 if (should_throttle) {
4782 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4783 BTRFS_RESERVE_NO_FLUSH);
4784 if (ret) {
4785 ret = -EAGAIN;
4786 break;
4787 }
28f75a0e 4788 }
85e21bac 4789 goto search_again;
8082510e
YZ
4790 } else {
4791 path->slots[0]--;
85e21bac 4792 }
39279cc3 4793 }
8082510e 4794out:
fd86a3a3
OS
4795 if (ret >= 0 && pending_del_nr) {
4796 int err;
4797
4798 err = btrfs_del_items(trans, root, path, pending_del_slot,
85e21bac 4799 pending_del_nr);
fd86a3a3
OS
4800 if (err) {
4801 btrfs_abort_transaction(trans, err);
4802 ret = err;
4803 }
85e21bac 4804 }
76b42abb
FM
4805 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4806 ASSERT(last_size >= new_size);
fd86a3a3 4807 if (!ret && last_size > new_size)
76b42abb 4808 last_size = new_size;
7f4f6e0a 4809 btrfs_ordered_update_i_size(inode, last_size, NULL);
76b42abb 4810 }
28ed1345 4811
39279cc3 4812 btrfs_free_path(path);
fd86a3a3 4813 return ret;
39279cc3
CM
4814}
4815
4816/*
9703fefe 4817 * btrfs_truncate_block - read, zero a chunk and write a block
2aaa6655
JB
4818 * @inode - inode that we're zeroing
4819 * @from - the offset to start zeroing
4820 * @len - the length to zero, 0 to zero the entire range respective to the
4821 * offset
4822 * @front - zero up to the offset instead of from the offset on
4823 *
9703fefe 4824 * This will find the block for the "from" offset and cow the block and zero the
2aaa6655 4825 * part we want to zero. This is used with truncate and hole punching.
39279cc3 4826 */
9703fefe 4827int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
2aaa6655 4828 int front)
39279cc3 4829{
0b246afa 4830 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2aaa6655 4831 struct address_space *mapping = inode->i_mapping;
e6dcd2dc
CM
4832 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4833 struct btrfs_ordered_extent *ordered;
2ac55d41 4834 struct extent_state *cached_state = NULL;
364ecf36 4835 struct extent_changeset *data_reserved = NULL;
e6dcd2dc 4836 char *kaddr;
0b246afa 4837 u32 blocksize = fs_info->sectorsize;
09cbfeaf 4838 pgoff_t index = from >> PAGE_SHIFT;
9703fefe 4839 unsigned offset = from & (blocksize - 1);
39279cc3 4840 struct page *page;
3b16a4e3 4841 gfp_t mask = btrfs_alloc_write_mask(mapping);
39279cc3 4842 int ret = 0;
9703fefe
CR
4843 u64 block_start;
4844 u64 block_end;
39279cc3 4845
b03ebd99
NB
4846 if (IS_ALIGNED(offset, blocksize) &&
4847 (!len || IS_ALIGNED(len, blocksize)))
39279cc3 4848 goto out;
9703fefe 4849
8b62f87b
JB
4850 block_start = round_down(from, blocksize);
4851 block_end = block_start + blocksize - 1;
4852
364ecf36 4853 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8b62f87b 4854 block_start, blocksize);
5d5e103a
JB
4855 if (ret)
4856 goto out;
39279cc3 4857
211c17f5 4858again:
3b16a4e3 4859 page = find_or_create_page(mapping, index, mask);
5d5e103a 4860 if (!page) {
bc42bda2 4861 btrfs_delalloc_release_space(inode, data_reserved,
43b18595
QW
4862 block_start, blocksize, true);
4863 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
ac6a2b36 4864 ret = -ENOMEM;
39279cc3 4865 goto out;
5d5e103a 4866 }
e6dcd2dc 4867
39279cc3 4868 if (!PageUptodate(page)) {
9ebefb18 4869 ret = btrfs_readpage(NULL, page);
39279cc3 4870 lock_page(page);
211c17f5
CM
4871 if (page->mapping != mapping) {
4872 unlock_page(page);
09cbfeaf 4873 put_page(page);
211c17f5
CM
4874 goto again;
4875 }
39279cc3
CM
4876 if (!PageUptodate(page)) {
4877 ret = -EIO;
89642229 4878 goto out_unlock;
39279cc3
CM
4879 }
4880 }
211c17f5 4881 wait_on_page_writeback(page);
e6dcd2dc 4882
9703fefe 4883 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
e6dcd2dc
CM
4884 set_page_extent_mapped(page);
4885
9703fefe 4886 ordered = btrfs_lookup_ordered_extent(inode, block_start);
e6dcd2dc 4887 if (ordered) {
9703fefe 4888 unlock_extent_cached(io_tree, block_start, block_end,
e43bbe5e 4889 &cached_state);
e6dcd2dc 4890 unlock_page(page);
09cbfeaf 4891 put_page(page);
eb84ae03 4892 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
4893 btrfs_put_ordered_extent(ordered);
4894 goto again;
4895 }
4896
9703fefe 4897 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
9e8a4a8b
LB
4898 EXTENT_DIRTY | EXTENT_DELALLOC |
4899 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
ae0f1625 4900 0, 0, &cached_state);
5d5e103a 4901
e3b8a485 4902 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
ba8b04c1 4903 &cached_state, 0);
9ed74f2d 4904 if (ret) {
9703fefe 4905 unlock_extent_cached(io_tree, block_start, block_end,
e43bbe5e 4906 &cached_state);
9ed74f2d
JB
4907 goto out_unlock;
4908 }
4909
9703fefe 4910 if (offset != blocksize) {
2aaa6655 4911 if (!len)
9703fefe 4912 len = blocksize - offset;
e6dcd2dc 4913 kaddr = kmap(page);
2aaa6655 4914 if (front)
9703fefe
CR
4915 memset(kaddr + (block_start - page_offset(page)),
4916 0, offset);
2aaa6655 4917 else
9703fefe
CR
4918 memset(kaddr + (block_start - page_offset(page)) + offset,
4919 0, len);
e6dcd2dc
CM
4920 flush_dcache_page(page);
4921 kunmap(page);
4922 }
247e743c 4923 ClearPageChecked(page);
e6dcd2dc 4924 set_page_dirty(page);
e43bbe5e 4925 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
39279cc3 4926
89642229 4927out_unlock:
5d5e103a 4928 if (ret)
bc42bda2 4929 btrfs_delalloc_release_space(inode, data_reserved, block_start,
43b18595
QW
4930 blocksize, true);
4931 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
39279cc3 4932 unlock_page(page);
09cbfeaf 4933 put_page(page);
39279cc3 4934out:
364ecf36 4935 extent_changeset_free(data_reserved);
39279cc3
CM
4936 return ret;
4937}
4938
16e7549f
JB
4939static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4940 u64 offset, u64 len)
4941{
0b246afa 4942 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
16e7549f
JB
4943 struct btrfs_trans_handle *trans;
4944 int ret;
4945
4946 /*
4947 * Still need to make sure the inode looks like it's been updated so
4948 * that any holes get logged if we fsync.
4949 */
0b246afa
JM
4950 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4951 BTRFS_I(inode)->last_trans = fs_info->generation;
16e7549f
JB
4952 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4953 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4954 return 0;
4955 }
4956
4957 /*
4958 * 1 - for the one we're dropping
4959 * 1 - for the one we're adding
4960 * 1 - for updating the inode.
4961 */
4962 trans = btrfs_start_transaction(root, 3);
4963 if (IS_ERR(trans))
4964 return PTR_ERR(trans);
4965
4966 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4967 if (ret) {
66642832 4968 btrfs_abort_transaction(trans, ret);
3a45bb20 4969 btrfs_end_transaction(trans);
16e7549f
JB
4970 return ret;
4971 }
4972
f85b7379
DS
4973 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4974 offset, 0, 0, len, 0, len, 0, 0, 0);
16e7549f 4975 if (ret)
66642832 4976 btrfs_abort_transaction(trans, ret);
16e7549f
JB
4977 else
4978 btrfs_update_inode(trans, root, inode);
3a45bb20 4979 btrfs_end_transaction(trans);
16e7549f
JB
4980 return ret;
4981}
4982
695a0d0d
JB
4983/*
4984 * This function puts in dummy file extents for the area we're creating a hole
4985 * for. So if we are truncating this file to a larger size we need to insert
4986 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4987 * the range between oldsize and size
4988 */
a41ad394 4989int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 4990{
0b246afa 4991 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9036c102
YZ
4992 struct btrfs_root *root = BTRFS_I(inode)->root;
4993 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 4994 struct extent_map *em = NULL;
2ac55d41 4995 struct extent_state *cached_state = NULL;
5dc562c5 4996 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
0b246afa
JM
4997 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4998 u64 block_end = ALIGN(size, fs_info->sectorsize);
9036c102
YZ
4999 u64 last_byte;
5000 u64 cur_offset;
5001 u64 hole_size;
9ed74f2d 5002 int err = 0;
39279cc3 5003
a71754fc 5004 /*
9703fefe
CR
5005 * If our size started in the middle of a block we need to zero out the
5006 * rest of the block before we expand the i_size, otherwise we could
a71754fc
JB
5007 * expose stale data.
5008 */
9703fefe 5009 err = btrfs_truncate_block(inode, oldsize, 0, 0);
a71754fc
JB
5010 if (err)
5011 return err;
5012
9036c102
YZ
5013 if (size <= hole_start)
5014 return 0;
5015
9036c102
YZ
5016 while (1) {
5017 struct btrfs_ordered_extent *ordered;
fa7c1494 5018
ff13db41 5019 lock_extent_bits(io_tree, hole_start, block_end - 1,
d0082371 5020 &cached_state);
a776c6fa 5021 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
fa7c1494 5022 block_end - hole_start);
9036c102
YZ
5023 if (!ordered)
5024 break;
2ac55d41 5025 unlock_extent_cached(io_tree, hole_start, block_end - 1,
e43bbe5e 5026 &cached_state);
fa7c1494 5027 btrfs_start_ordered_extent(inode, ordered, 1);
9036c102
YZ
5028 btrfs_put_ordered_extent(ordered);
5029 }
39279cc3 5030
9036c102
YZ
5031 cur_offset = hole_start;
5032 while (1) {
fc4f21b1 5033 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
9036c102 5034 block_end - cur_offset, 0);
79787eaa
JM
5035 if (IS_ERR(em)) {
5036 err = PTR_ERR(em);
f2767956 5037 em = NULL;
79787eaa
JM
5038 break;
5039 }
9036c102 5040 last_byte = min(extent_map_end(em), block_end);
0b246afa 5041 last_byte = ALIGN(last_byte, fs_info->sectorsize);
8082510e 5042 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5dc562c5 5043 struct extent_map *hole_em;
9036c102 5044 hole_size = last_byte - cur_offset;
9ed74f2d 5045
16e7549f
JB
5046 err = maybe_insert_hole(root, inode, cur_offset,
5047 hole_size);
5048 if (err)
3893e33b 5049 break;
dcdbc059 5050 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
5051 cur_offset + hole_size - 1, 0);
5052 hole_em = alloc_extent_map();
5053 if (!hole_em) {
5054 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5055 &BTRFS_I(inode)->runtime_flags);
5056 goto next;
5057 }
5058 hole_em->start = cur_offset;
5059 hole_em->len = hole_size;
5060 hole_em->orig_start = cur_offset;
8082510e 5061
5dc562c5
JB
5062 hole_em->block_start = EXTENT_MAP_HOLE;
5063 hole_em->block_len = 0;
b4939680 5064 hole_em->orig_block_len = 0;
cc95bef6 5065 hole_em->ram_bytes = hole_size;
0b246afa 5066 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5dc562c5 5067 hole_em->compress_type = BTRFS_COMPRESS_NONE;
0b246afa 5068 hole_em->generation = fs_info->generation;
8082510e 5069
5dc562c5
JB
5070 while (1) {
5071 write_lock(&em_tree->lock);
09a2a8f9 5072 err = add_extent_mapping(em_tree, hole_em, 1);
5dc562c5
JB
5073 write_unlock(&em_tree->lock);
5074 if (err != -EEXIST)
5075 break;
dcdbc059
NB
5076 btrfs_drop_extent_cache(BTRFS_I(inode),
5077 cur_offset,
5dc562c5
JB
5078 cur_offset +
5079 hole_size - 1, 0);
5080 }
5081 free_extent_map(hole_em);
9036c102 5082 }
16e7549f 5083next:
9036c102 5084 free_extent_map(em);
a22285a6 5085 em = NULL;
9036c102 5086 cur_offset = last_byte;
8082510e 5087 if (cur_offset >= block_end)
9036c102
YZ
5088 break;
5089 }
a22285a6 5090 free_extent_map(em);
e43bbe5e 5091 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
9036c102
YZ
5092 return err;
5093}
39279cc3 5094
3972f260 5095static int btrfs_setsize(struct inode *inode, struct iattr *attr)
8082510e 5096{
f4a2f4c5
MX
5097 struct btrfs_root *root = BTRFS_I(inode)->root;
5098 struct btrfs_trans_handle *trans;
a41ad394 5099 loff_t oldsize = i_size_read(inode);
3972f260
ES
5100 loff_t newsize = attr->ia_size;
5101 int mask = attr->ia_valid;
8082510e
YZ
5102 int ret;
5103
3972f260
ES
5104 /*
5105 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5106 * special case where we need to update the times despite not having
5107 * these flags set. For all other operations the VFS set these flags
5108 * explicitly if it wants a timestamp update.
5109 */
dff6efc3
CH
5110 if (newsize != oldsize) {
5111 inode_inc_iversion(inode);
5112 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5113 inode->i_ctime = inode->i_mtime =
c2050a45 5114 current_time(inode);
dff6efc3 5115 }
3972f260 5116
a41ad394 5117 if (newsize > oldsize) {
9ea24bbe 5118 /*
ea14b57f 5119 * Don't do an expanding truncate while snapshotting is ongoing.
9ea24bbe
FM
5120 * This is to ensure the snapshot captures a fully consistent
5121 * state of this file - if the snapshot captures this expanding
5122 * truncation, it must capture all writes that happened before
5123 * this truncation.
5124 */
0bc19f90 5125 btrfs_wait_for_snapshot_creation(root);
a41ad394 5126 ret = btrfs_cont_expand(inode, oldsize, newsize);
9ea24bbe 5127 if (ret) {
ea14b57f 5128 btrfs_end_write_no_snapshotting(root);
8082510e 5129 return ret;
9ea24bbe 5130 }
8082510e 5131
f4a2f4c5 5132 trans = btrfs_start_transaction(root, 1);
9ea24bbe 5133 if (IS_ERR(trans)) {
ea14b57f 5134 btrfs_end_write_no_snapshotting(root);
f4a2f4c5 5135 return PTR_ERR(trans);
9ea24bbe 5136 }
f4a2f4c5
MX
5137
5138 i_size_write(inode, newsize);
5139 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
27772b68 5140 pagecache_isize_extended(inode, oldsize, newsize);
f4a2f4c5 5141 ret = btrfs_update_inode(trans, root, inode);
ea14b57f 5142 btrfs_end_write_no_snapshotting(root);
3a45bb20 5143 btrfs_end_transaction(trans);
a41ad394 5144 } else {
8082510e 5145
a41ad394
JB
5146 /*
5147 * We're truncating a file that used to have good data down to
5148 * zero. Make sure it gets into the ordered flush list so that
5149 * any new writes get down to disk quickly.
5150 */
5151 if (newsize == 0)
72ac3c0d
JB
5152 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5153 &BTRFS_I(inode)->runtime_flags);
8082510e 5154
a41ad394 5155 truncate_setsize(inode, newsize);
2e60a51e 5156
52042d8e 5157 /* Disable nonlocked read DIO to avoid the endless truncate */
abcefb1e 5158 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
2e60a51e 5159 inode_dio_wait(inode);
0b581701 5160 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
2e60a51e 5161
213e8c55 5162 ret = btrfs_truncate(inode, newsize == oldsize);
7f4f6e0a
JB
5163 if (ret && inode->i_nlink) {
5164 int err;
5165
5166 /*
f7e9e8fc
OS
5167 * Truncate failed, so fix up the in-memory size. We
5168 * adjusted disk_i_size down as we removed extents, so
5169 * wait for disk_i_size to be stable and then update the
5170 * in-memory size to match.
7f4f6e0a 5171 */
f7e9e8fc 5172 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
7f4f6e0a 5173 if (err)
f7e9e8fc
OS
5174 return err;
5175 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
7f4f6e0a 5176 }
8082510e
YZ
5177 }
5178
a41ad394 5179 return ret;
8082510e
YZ
5180}
5181
9036c102
YZ
5182static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5183{
2b0143b5 5184 struct inode *inode = d_inode(dentry);
b83cc969 5185 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 5186 int err;
39279cc3 5187
b83cc969
LZ
5188 if (btrfs_root_readonly(root))
5189 return -EROFS;
5190
31051c85 5191 err = setattr_prepare(dentry, attr);
9036c102
YZ
5192 if (err)
5193 return err;
2bf5a725 5194
5a3f23d5 5195 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3972f260 5196 err = btrfs_setsize(inode, attr);
8082510e
YZ
5197 if (err)
5198 return err;
39279cc3 5199 }
9036c102 5200
1025774c
CH
5201 if (attr->ia_valid) {
5202 setattr_copy(inode, attr);
0c4d2d95 5203 inode_inc_iversion(inode);
22c44fe6 5204 err = btrfs_dirty_inode(inode);
1025774c 5205
22c44fe6 5206 if (!err && attr->ia_valid & ATTR_MODE)
996a710d 5207 err = posix_acl_chmod(inode, inode->i_mode);
1025774c 5208 }
33268eaf 5209
39279cc3
CM
5210 return err;
5211}
61295eb8 5212
131e404a
FDBM
5213/*
5214 * While truncating the inode pages during eviction, we get the VFS calling
5215 * btrfs_invalidatepage() against each page of the inode. This is slow because
5216 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5217 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5218 * extent_state structures over and over, wasting lots of time.
5219 *
5220 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5221 * those expensive operations on a per page basis and do only the ordered io
5222 * finishing, while we release here the extent_map and extent_state structures,
5223 * without the excessive merging and splitting.
5224 */
5225static void evict_inode_truncate_pages(struct inode *inode)
5226{
5227 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5228 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5229 struct rb_node *node;
5230
5231 ASSERT(inode->i_state & I_FREEING);
91b0abe3 5232 truncate_inode_pages_final(&inode->i_data);
131e404a
FDBM
5233
5234 write_lock(&map_tree->lock);
07e1ce09 5235 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
131e404a
FDBM
5236 struct extent_map *em;
5237
07e1ce09 5238 node = rb_first_cached(&map_tree->map);
131e404a 5239 em = rb_entry(node, struct extent_map, rb_node);
180589ef
WS
5240 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5241 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
131e404a
FDBM
5242 remove_extent_mapping(map_tree, em);
5243 free_extent_map(em);
7064dd5c
FM
5244 if (need_resched()) {
5245 write_unlock(&map_tree->lock);
5246 cond_resched();
5247 write_lock(&map_tree->lock);
5248 }
131e404a
FDBM
5249 }
5250 write_unlock(&map_tree->lock);
5251
6ca07097
FM
5252 /*
5253 * Keep looping until we have no more ranges in the io tree.
5254 * We can have ongoing bios started by readpages (called from readahead)
9c6429d9
FM
5255 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5256 * still in progress (unlocked the pages in the bio but did not yet
5257 * unlocked the ranges in the io tree). Therefore this means some
6ca07097
FM
5258 * ranges can still be locked and eviction started because before
5259 * submitting those bios, which are executed by a separate task (work
5260 * queue kthread), inode references (inode->i_count) were not taken
5261 * (which would be dropped in the end io callback of each bio).
5262 * Therefore here we effectively end up waiting for those bios and
5263 * anyone else holding locked ranges without having bumped the inode's
5264 * reference count - if we don't do it, when they access the inode's
5265 * io_tree to unlock a range it may be too late, leading to an
5266 * use-after-free issue.
5267 */
131e404a
FDBM
5268 spin_lock(&io_tree->lock);
5269 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5270 struct extent_state *state;
5271 struct extent_state *cached_state = NULL;
6ca07097
FM
5272 u64 start;
5273 u64 end;
421f0922 5274 unsigned state_flags;
131e404a
FDBM
5275
5276 node = rb_first(&io_tree->state);
5277 state = rb_entry(node, struct extent_state, rb_node);
6ca07097
FM
5278 start = state->start;
5279 end = state->end;
421f0922 5280 state_flags = state->state;
131e404a
FDBM
5281 spin_unlock(&io_tree->lock);
5282
ff13db41 5283 lock_extent_bits(io_tree, start, end, &cached_state);
b9d0b389
QW
5284
5285 /*
5286 * If still has DELALLOC flag, the extent didn't reach disk,
5287 * and its reserved space won't be freed by delayed_ref.
5288 * So we need to free its reserved space here.
5289 * (Refer to comment in btrfs_invalidatepage, case 2)
5290 *
5291 * Note, end is the bytenr of last byte, so we need + 1 here.
5292 */
421f0922 5293 if (state_flags & EXTENT_DELALLOC)
bc42bda2 5294 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
b9d0b389 5295
6ca07097 5296 clear_extent_bit(io_tree, start, end,
131e404a
FDBM
5297 EXTENT_LOCKED | EXTENT_DIRTY |
5298 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
ae0f1625 5299 EXTENT_DEFRAG, 1, 1, &cached_state);
131e404a 5300
7064dd5c 5301 cond_resched();
131e404a
FDBM
5302 spin_lock(&io_tree->lock);
5303 }
5304 spin_unlock(&io_tree->lock);
5305}
5306
4b9d7b59 5307static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
ad80cf50 5308 struct btrfs_block_rsv *rsv)
4b9d7b59
OS
5309{
5310 struct btrfs_fs_info *fs_info = root->fs_info;
5311 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
260e7702 5312 u64 delayed_refs_extra = btrfs_calc_trans_metadata_size(fs_info, 1);
4b9d7b59
OS
5313 int failures = 0;
5314
5315 for (;;) {
5316 struct btrfs_trans_handle *trans;
5317 int ret;
5318
260e7702
JB
5319 ret = btrfs_block_rsv_refill(root, rsv,
5320 rsv->size + delayed_refs_extra,
4b9d7b59
OS
5321 BTRFS_RESERVE_FLUSH_LIMIT);
5322
5323 if (ret && ++failures > 2) {
5324 btrfs_warn(fs_info,
5325 "could not allocate space for a delete; will truncate on mount");
5326 return ERR_PTR(-ENOSPC);
5327 }
5328
260e7702
JB
5329 /*
5330 * Evict can generate a large amount of delayed refs without
5331 * having a way to add space back since we exhaust our temporary
5332 * block rsv. We aren't allowed to do FLUSH_ALL in this case
5333 * because we could deadlock with so many things in the flushing
5334 * code, so we have to try and hold some extra space to
5335 * compensate for our delayed ref generation. If we can't get
5336 * that space then we need see if we can steal our minimum from
5337 * the global reserve. We will be ratelimited by the amount of
5338 * space we have for the delayed refs rsv, so we'll end up
5339 * committing and trying again.
5340 */
4b9d7b59 5341 trans = btrfs_join_transaction(root);
260e7702
JB
5342 if (IS_ERR(trans) || !ret) {
5343 if (!IS_ERR(trans)) {
5344 trans->block_rsv = &fs_info->trans_block_rsv;
5345 trans->bytes_reserved = delayed_refs_extra;
5346 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5347 delayed_refs_extra, 1);
5348 }
4b9d7b59 5349 return trans;
260e7702 5350 }
4b9d7b59
OS
5351
5352 /*
5353 * Try to steal from the global reserve if there is space for
5354 * it.
5355 */
64403612
JB
5356 if (!btrfs_check_space_for_delayed_refs(fs_info) &&
5357 !btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0))
4b9d7b59
OS
5358 return trans;
5359
5360 /* If not, commit and try again. */
5361 ret = btrfs_commit_transaction(trans);
5362 if (ret)
5363 return ERR_PTR(ret);
5364 }
5365}
5366
bd555975 5367void btrfs_evict_inode(struct inode *inode)
39279cc3 5368{
0b246afa 5369 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
5370 struct btrfs_trans_handle *trans;
5371 struct btrfs_root *root = BTRFS_I(inode)->root;
4b9d7b59 5372 struct btrfs_block_rsv *rsv;
39279cc3
CM
5373 int ret;
5374
1abe9b8a 5375 trace_btrfs_inode_evict(inode);
5376
3d48d981 5377 if (!root) {
e8f1bc14 5378 clear_inode(inode);
3d48d981
NB
5379 return;
5380 }
5381
131e404a
FDBM
5382 evict_inode_truncate_pages(inode);
5383
69e9c6c6
SB
5384 if (inode->i_nlink &&
5385 ((btrfs_root_refs(&root->root_item) != 0 &&
5386 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
70ddc553 5387 btrfs_is_free_space_inode(BTRFS_I(inode))))
bd555975
AV
5388 goto no_delete;
5389
27919067 5390 if (is_bad_inode(inode))
39279cc3 5391 goto no_delete;
5f39d397 5392
7ab7956e 5393 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
f612496b 5394
7b40b695 5395 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
c71bf099 5396 goto no_delete;
c71bf099 5397
76dda93c 5398 if (inode->i_nlink > 0) {
69e9c6c6
SB
5399 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5400 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
76dda93c
YZ
5401 goto no_delete;
5402 }
5403
aa79021f 5404 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
27919067 5405 if (ret)
0e8c36a9 5406 goto no_delete;
0e8c36a9 5407
2ff7e61e 5408 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
27919067 5409 if (!rsv)
4289a667 5410 goto no_delete;
ad80cf50 5411 rsv->size = btrfs_calc_trunc_metadata_size(fs_info, 1);
ca7e70f5 5412 rsv->failfast = 1;
4289a667 5413
6ef06d27 5414 btrfs_i_size_write(BTRFS_I(inode), 0);
5f39d397 5415
8082510e 5416 while (1) {
ad80cf50 5417 trans = evict_refill_and_join(root, rsv);
27919067
OS
5418 if (IS_ERR(trans))
5419 goto free_rsv;
7b128766 5420
4289a667
JB
5421 trans->block_rsv = rsv;
5422
d68fc57b 5423 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
27919067
OS
5424 trans->block_rsv = &fs_info->trans_block_rsv;
5425 btrfs_end_transaction(trans);
5426 btrfs_btree_balance_dirty(fs_info);
5427 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5428 goto free_rsv;
5429 else if (!ret)
8082510e 5430 break;
8082510e 5431 }
5f39d397 5432
4ef31a45 5433 /*
27919067
OS
5434 * Errors here aren't a big deal, it just means we leave orphan items in
5435 * the tree. They will be cleaned up on the next mount. If the inode
5436 * number gets reused, cleanup deletes the orphan item without doing
5437 * anything, and unlink reuses the existing orphan item.
5438 *
5439 * If it turns out that we are dropping too many of these, we might want
5440 * to add a mechanism for retrying these after a commit.
4ef31a45 5441 */
ad80cf50 5442 trans = evict_refill_and_join(root, rsv);
27919067
OS
5443 if (!IS_ERR(trans)) {
5444 trans->block_rsv = rsv;
5445 btrfs_orphan_del(trans, BTRFS_I(inode));
5446 trans->block_rsv = &fs_info->trans_block_rsv;
5447 btrfs_end_transaction(trans);
5448 }
54aa1f4d 5449
0b246afa 5450 if (!(root == fs_info->tree_root ||
581bb050 5451 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4a0cc7ca 5452 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
581bb050 5453
27919067
OS
5454free_rsv:
5455 btrfs_free_block_rsv(fs_info, rsv);
39279cc3 5456no_delete:
27919067
OS
5457 /*
5458 * If we didn't successfully delete, the orphan item will still be in
5459 * the tree and we'll retry on the next mount. Again, we might also want
5460 * to retry these periodically in the future.
5461 */
f48d1cf5 5462 btrfs_remove_delayed_node(BTRFS_I(inode));
dbd5768f 5463 clear_inode(inode);
39279cc3
CM
5464}
5465
5466/*
6bf9e4bd
QW
5467 * Return the key found in the dir entry in the location pointer, fill @type
5468 * with BTRFS_FT_*, and return 0.
5469 *
005d6712
SY
5470 * If no dir entries were found, returns -ENOENT.
5471 * If found a corrupted location in dir entry, returns -EUCLEAN.
39279cc3
CM
5472 */
5473static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
6bf9e4bd 5474 struct btrfs_key *location, u8 *type)
39279cc3
CM
5475{
5476 const char *name = dentry->d_name.name;
5477 int namelen = dentry->d_name.len;
5478 struct btrfs_dir_item *di;
5479 struct btrfs_path *path;
5480 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 5481 int ret = 0;
39279cc3
CM
5482
5483 path = btrfs_alloc_path();
d8926bb3
MF
5484 if (!path)
5485 return -ENOMEM;
3954401f 5486
f85b7379
DS
5487 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5488 name, namelen, 0);
3cf5068f
LB
5489 if (IS_ERR_OR_NULL(di)) {
5490 ret = di ? PTR_ERR(di) : -ENOENT;
005d6712
SY
5491 goto out;
5492 }
d397712b 5493
5f39d397 5494 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
56a0e706
LB
5495 if (location->type != BTRFS_INODE_ITEM_KEY &&
5496 location->type != BTRFS_ROOT_ITEM_KEY) {
005d6712 5497 ret = -EUCLEAN;
56a0e706
LB
5498 btrfs_warn(root->fs_info,
5499"%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5500 __func__, name, btrfs_ino(BTRFS_I(dir)),
5501 location->objectid, location->type, location->offset);
56a0e706 5502 }
6bf9e4bd
QW
5503 if (!ret)
5504 *type = btrfs_dir_type(path->nodes[0], di);
39279cc3 5505out:
39279cc3
CM
5506 btrfs_free_path(path);
5507 return ret;
5508}
5509
5510/*
5511 * when we hit a tree root in a directory, the btrfs part of the inode
5512 * needs to be changed to reflect the root directory of the tree root. This
5513 * is kind of like crossing a mount point.
5514 */
2ff7e61e 5515static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
4df27c4d
YZ
5516 struct inode *dir,
5517 struct dentry *dentry,
5518 struct btrfs_key *location,
5519 struct btrfs_root **sub_root)
39279cc3 5520{
4df27c4d
YZ
5521 struct btrfs_path *path;
5522 struct btrfs_root *new_root;
5523 struct btrfs_root_ref *ref;
5524 struct extent_buffer *leaf;
1d4c08e0 5525 struct btrfs_key key;
4df27c4d
YZ
5526 int ret;
5527 int err = 0;
39279cc3 5528
4df27c4d
YZ
5529 path = btrfs_alloc_path();
5530 if (!path) {
5531 err = -ENOMEM;
5532 goto out;
5533 }
39279cc3 5534
4df27c4d 5535 err = -ENOENT;
1d4c08e0
DS
5536 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5537 key.type = BTRFS_ROOT_REF_KEY;
5538 key.offset = location->objectid;
5539
0b246afa 5540 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4df27c4d
YZ
5541 if (ret) {
5542 if (ret < 0)
5543 err = ret;
5544 goto out;
5545 }
39279cc3 5546
4df27c4d
YZ
5547 leaf = path->nodes[0];
5548 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4a0cc7ca 5549 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
4df27c4d
YZ
5550 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5551 goto out;
39279cc3 5552
4df27c4d
YZ
5553 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5554 (unsigned long)(ref + 1),
5555 dentry->d_name.len);
5556 if (ret)
5557 goto out;
5558
b3b4aa74 5559 btrfs_release_path(path);
4df27c4d 5560
0b246afa 5561 new_root = btrfs_read_fs_root_no_name(fs_info, location);
4df27c4d
YZ
5562 if (IS_ERR(new_root)) {
5563 err = PTR_ERR(new_root);
5564 goto out;
5565 }
5566
4df27c4d
YZ
5567 *sub_root = new_root;
5568 location->objectid = btrfs_root_dirid(&new_root->root_item);
5569 location->type = BTRFS_INODE_ITEM_KEY;
5570 location->offset = 0;
5571 err = 0;
5572out:
5573 btrfs_free_path(path);
5574 return err;
39279cc3
CM
5575}
5576
5d4f98a2
YZ
5577static void inode_tree_add(struct inode *inode)
5578{
5579 struct btrfs_root *root = BTRFS_I(inode)->root;
5580 struct btrfs_inode *entry;
03e860bd
NP
5581 struct rb_node **p;
5582 struct rb_node *parent;
cef21937 5583 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4a0cc7ca 5584 u64 ino = btrfs_ino(BTRFS_I(inode));
5d4f98a2 5585
1d3382cb 5586 if (inode_unhashed(inode))
76dda93c 5587 return;
e1409cef 5588 parent = NULL;
5d4f98a2 5589 spin_lock(&root->inode_lock);
e1409cef 5590 p = &root->inode_tree.rb_node;
5d4f98a2
YZ
5591 while (*p) {
5592 parent = *p;
5593 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5594
37508515 5595 if (ino < btrfs_ino(entry))
03e860bd 5596 p = &parent->rb_left;
37508515 5597 else if (ino > btrfs_ino(entry))
03e860bd 5598 p = &parent->rb_right;
5d4f98a2
YZ
5599 else {
5600 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 5601 (I_WILL_FREE | I_FREEING)));
cef21937 5602 rb_replace_node(parent, new, &root->inode_tree);
03e860bd
NP
5603 RB_CLEAR_NODE(parent);
5604 spin_unlock(&root->inode_lock);
cef21937 5605 return;
5d4f98a2
YZ
5606 }
5607 }
cef21937
FDBM
5608 rb_link_node(new, parent, p);
5609 rb_insert_color(new, &root->inode_tree);
5d4f98a2
YZ
5610 spin_unlock(&root->inode_lock);
5611}
5612
5613static void inode_tree_del(struct inode *inode)
5614{
0b246afa 5615 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5d4f98a2 5616 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 5617 int empty = 0;
5d4f98a2 5618
03e860bd 5619 spin_lock(&root->inode_lock);
5d4f98a2 5620 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 5621 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 5622 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 5623 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 5624 }
03e860bd 5625 spin_unlock(&root->inode_lock);
76dda93c 5626
69e9c6c6 5627 if (empty && btrfs_root_refs(&root->root_item) == 0) {
0b246afa 5628 synchronize_srcu(&fs_info->subvol_srcu);
76dda93c
YZ
5629 spin_lock(&root->inode_lock);
5630 empty = RB_EMPTY_ROOT(&root->inode_tree);
5631 spin_unlock(&root->inode_lock);
5632 if (empty)
5633 btrfs_add_dead_root(root);
5634 }
5635}
5636
5d4f98a2 5637
e02119d5
CM
5638static int btrfs_init_locked_inode(struct inode *inode, void *p)
5639{
5640 struct btrfs_iget_args *args = p;
90d3e592
CM
5641 inode->i_ino = args->location->objectid;
5642 memcpy(&BTRFS_I(inode)->location, args->location,
5643 sizeof(*args->location));
e02119d5 5644 BTRFS_I(inode)->root = args->root;
39279cc3
CM
5645 return 0;
5646}
5647
5648static int btrfs_find_actor(struct inode *inode, void *opaque)
5649{
5650 struct btrfs_iget_args *args = opaque;
90d3e592 5651 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
d397712b 5652 args->root == BTRFS_I(inode)->root;
39279cc3
CM
5653}
5654
5d4f98a2 5655static struct inode *btrfs_iget_locked(struct super_block *s,
90d3e592 5656 struct btrfs_key *location,
5d4f98a2 5657 struct btrfs_root *root)
39279cc3
CM
5658{
5659 struct inode *inode;
5660 struct btrfs_iget_args args;
90d3e592 5661 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
778ba82b 5662
90d3e592 5663 args.location = location;
39279cc3
CM
5664 args.root = root;
5665
778ba82b 5666 inode = iget5_locked(s, hashval, btrfs_find_actor,
39279cc3
CM
5667 btrfs_init_locked_inode,
5668 (void *)&args);
5669 return inode;
5670}
5671
1a54ef8c
BR
5672/* Get an inode object given its location and corresponding root.
5673 * Returns in *is_new if the inode was read from disk
5674 */
4222ea71
FM
5675struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5676 struct btrfs_root *root, int *new,
5677 struct btrfs_path *path)
1a54ef8c
BR
5678{
5679 struct inode *inode;
5680
90d3e592 5681 inode = btrfs_iget_locked(s, location, root);
1a54ef8c 5682 if (!inode)
5d4f98a2 5683 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
5684
5685 if (inode->i_state & I_NEW) {
67710892
FM
5686 int ret;
5687
4222ea71 5688 ret = btrfs_read_locked_inode(inode, path);
9bc2ceff 5689 if (!ret) {
1748f843
MF
5690 inode_tree_add(inode);
5691 unlock_new_inode(inode);
5692 if (new)
5693 *new = 1;
5694 } else {
f5b3a417
AV
5695 iget_failed(inode);
5696 /*
5697 * ret > 0 can come from btrfs_search_slot called by
5698 * btrfs_read_locked_inode, this means the inode item
5699 * was not found.
5700 */
5701 if (ret > 0)
5702 ret = -ENOENT;
5703 inode = ERR_PTR(ret);
1748f843
MF
5704 }
5705 }
5706
1a54ef8c
BR
5707 return inode;
5708}
5709
4222ea71
FM
5710struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5711 struct btrfs_root *root, int *new)
5712{
5713 return btrfs_iget_path(s, location, root, new, NULL);
5714}
5715
4df27c4d
YZ
5716static struct inode *new_simple_dir(struct super_block *s,
5717 struct btrfs_key *key,
5718 struct btrfs_root *root)
5719{
5720 struct inode *inode = new_inode(s);
5721
5722 if (!inode)
5723 return ERR_PTR(-ENOMEM);
5724
4df27c4d
YZ
5725 BTRFS_I(inode)->root = root;
5726 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
72ac3c0d 5727 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4df27c4d
YZ
5728
5729 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
848cce0d 5730 inode->i_op = &btrfs_dir_ro_inode_operations;
1fdf4194 5731 inode->i_opflags &= ~IOP_XATTR;
4df27c4d
YZ
5732 inode->i_fop = &simple_dir_operations;
5733 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
c2050a45 5734 inode->i_mtime = current_time(inode);
9cc97d64 5735 inode->i_atime = inode->i_mtime;
5736 inode->i_ctime = inode->i_mtime;
d3c6be6f 5737 BTRFS_I(inode)->i_otime = inode->i_mtime;
4df27c4d
YZ
5738
5739 return inode;
5740}
5741
6bf9e4bd
QW
5742static inline u8 btrfs_inode_type(struct inode *inode)
5743{
5744 /*
5745 * Compile-time asserts that generic FT_* types still match
5746 * BTRFS_FT_* types
5747 */
5748 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5749 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5750 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5751 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5752 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5753 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5754 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5755 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5756
5757 return fs_umode_to_ftype(inode->i_mode);
5758}
5759
3de4586c 5760struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 5761{
0b246afa 5762 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
d397712b 5763 struct inode *inode;
4df27c4d 5764 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
5765 struct btrfs_root *sub_root = root;
5766 struct btrfs_key location;
6bf9e4bd 5767 u8 di_type = 0;
76dda93c 5768 int index;
b4aff1f8 5769 int ret = 0;
39279cc3
CM
5770
5771 if (dentry->d_name.len > BTRFS_NAME_LEN)
5772 return ERR_PTR(-ENAMETOOLONG);
5f39d397 5773
6bf9e4bd 5774 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
39279cc3
CM
5775 if (ret < 0)
5776 return ERR_PTR(ret);
5f39d397 5777
4df27c4d 5778 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 5779 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
6bf9e4bd
QW
5780 if (IS_ERR(inode))
5781 return inode;
5782
5783 /* Do extra check against inode mode with di_type */
5784 if (btrfs_inode_type(inode) != di_type) {
5785 btrfs_crit(fs_info,
5786"inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5787 inode->i_mode, btrfs_inode_type(inode),
5788 di_type);
5789 iput(inode);
5790 return ERR_PTR(-EUCLEAN);
5791 }
4df27c4d
YZ
5792 return inode;
5793 }
5794
0b246afa 5795 index = srcu_read_lock(&fs_info->subvol_srcu);
2ff7e61e 5796 ret = fixup_tree_root_location(fs_info, dir, dentry,
4df27c4d
YZ
5797 &location, &sub_root);
5798 if (ret < 0) {
5799 if (ret != -ENOENT)
5800 inode = ERR_PTR(ret);
5801 else
5802 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5803 } else {
73f73415 5804 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 5805 }
0b246afa 5806 srcu_read_unlock(&fs_info->subvol_srcu, index);
76dda93c 5807
34d19bad 5808 if (!IS_ERR(inode) && root != sub_root) {
0b246afa 5809 down_read(&fs_info->cleanup_work_sem);
bc98a42c 5810 if (!sb_rdonly(inode->i_sb))
66b4ffd1 5811 ret = btrfs_orphan_cleanup(sub_root);
0b246afa 5812 up_read(&fs_info->cleanup_work_sem);
01cd3367
JB
5813 if (ret) {
5814 iput(inode);
66b4ffd1 5815 inode = ERR_PTR(ret);
01cd3367 5816 }
c71bf099
YZ
5817 }
5818
3de4586c
CM
5819 return inode;
5820}
5821
fe15ce44 5822static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
5823{
5824 struct btrfs_root *root;
2b0143b5 5825 struct inode *inode = d_inode(dentry);
76dda93c 5826
848cce0d 5827 if (!inode && !IS_ROOT(dentry))
2b0143b5 5828 inode = d_inode(dentry->d_parent);
76dda93c 5829
848cce0d
LZ
5830 if (inode) {
5831 root = BTRFS_I(inode)->root;
efefb143
YZ
5832 if (btrfs_root_refs(&root->root_item) == 0)
5833 return 1;
848cce0d 5834
4a0cc7ca 5835 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
848cce0d 5836 return 1;
efefb143 5837 }
76dda93c
YZ
5838 return 0;
5839}
5840
3de4586c 5841static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
00cd8dd3 5842 unsigned int flags)
3de4586c 5843{
3837d208 5844 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5662344b 5845
3837d208
AV
5846 if (inode == ERR_PTR(-ENOENT))
5847 inode = NULL;
41d28bca 5848 return d_splice_alias(inode, dentry);
39279cc3
CM
5849}
5850
23b5ec74
JB
5851/*
5852 * All this infrastructure exists because dir_emit can fault, and we are holding
5853 * the tree lock when doing readdir. For now just allocate a buffer and copy
5854 * our information into that, and then dir_emit from the buffer. This is
5855 * similar to what NFS does, only we don't keep the buffer around in pagecache
5856 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5857 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5858 * tree lock.
5859 */
5860static int btrfs_opendir(struct inode *inode, struct file *file)
5861{
5862 struct btrfs_file_private *private;
5863
5864 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5865 if (!private)
5866 return -ENOMEM;
5867 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5868 if (!private->filldir_buf) {
5869 kfree(private);
5870 return -ENOMEM;
5871 }
5872 file->private_data = private;
5873 return 0;
5874}
5875
5876struct dir_entry {
5877 u64 ino;
5878 u64 offset;
5879 unsigned type;
5880 int name_len;
5881};
5882
5883static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5884{
5885 while (entries--) {
5886 struct dir_entry *entry = addr;
5887 char *name = (char *)(entry + 1);
5888
92d32170
DS
5889 ctx->pos = get_unaligned(&entry->offset);
5890 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5891 get_unaligned(&entry->ino),
5892 get_unaligned(&entry->type)))
23b5ec74 5893 return 1;
92d32170
DS
5894 addr += sizeof(struct dir_entry) +
5895 get_unaligned(&entry->name_len);
23b5ec74
JB
5896 ctx->pos++;
5897 }
5898 return 0;
5899}
5900
9cdda8d3 5901static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
39279cc3 5902{
9cdda8d3 5903 struct inode *inode = file_inode(file);
39279cc3 5904 struct btrfs_root *root = BTRFS_I(inode)->root;
23b5ec74 5905 struct btrfs_file_private *private = file->private_data;
39279cc3
CM
5906 struct btrfs_dir_item *di;
5907 struct btrfs_key key;
5f39d397 5908 struct btrfs_key found_key;
39279cc3 5909 struct btrfs_path *path;
23b5ec74 5910 void *addr;
16cdcec7
MX
5911 struct list_head ins_list;
5912 struct list_head del_list;
39279cc3 5913 int ret;
5f39d397 5914 struct extent_buffer *leaf;
39279cc3 5915 int slot;
5f39d397
CM
5916 char *name_ptr;
5917 int name_len;
23b5ec74
JB
5918 int entries = 0;
5919 int total_len = 0;
02dbfc99 5920 bool put = false;
c2951f32 5921 struct btrfs_key location;
5f39d397 5922
9cdda8d3
AV
5923 if (!dir_emit_dots(file, ctx))
5924 return 0;
5925
49593bfa 5926 path = btrfs_alloc_path();
16cdcec7
MX
5927 if (!path)
5928 return -ENOMEM;
ff5714cc 5929
23b5ec74 5930 addr = private->filldir_buf;
e4058b54 5931 path->reada = READA_FORWARD;
49593bfa 5932
c2951f32
JM
5933 INIT_LIST_HEAD(&ins_list);
5934 INIT_LIST_HEAD(&del_list);
5935 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
16cdcec7 5936
23b5ec74 5937again:
c2951f32 5938 key.type = BTRFS_DIR_INDEX_KEY;
9cdda8d3 5939 key.offset = ctx->pos;
4a0cc7ca 5940 key.objectid = btrfs_ino(BTRFS_I(inode));
5f39d397 5941
39279cc3
CM
5942 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5943 if (ret < 0)
5944 goto err;
49593bfa
DW
5945
5946 while (1) {
23b5ec74
JB
5947 struct dir_entry *entry;
5948
5f39d397 5949 leaf = path->nodes[0];
39279cc3 5950 slot = path->slots[0];
b9e03af0
LZ
5951 if (slot >= btrfs_header_nritems(leaf)) {
5952 ret = btrfs_next_leaf(root, path);
5953 if (ret < 0)
5954 goto err;
5955 else if (ret > 0)
5956 break;
5957 continue;
39279cc3 5958 }
3de4586c 5959
5f39d397
CM
5960 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5961
5962 if (found_key.objectid != key.objectid)
39279cc3 5963 break;
c2951f32 5964 if (found_key.type != BTRFS_DIR_INDEX_KEY)
39279cc3 5965 break;
9cdda8d3 5966 if (found_key.offset < ctx->pos)
b9e03af0 5967 goto next;
c2951f32 5968 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
16cdcec7 5969 goto next;
39279cc3 5970 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
c2951f32 5971 name_len = btrfs_dir_name_len(leaf, di);
23b5ec74
JB
5972 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5973 PAGE_SIZE) {
5974 btrfs_release_path(path);
5975 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5976 if (ret)
5977 goto nopos;
5978 addr = private->filldir_buf;
5979 entries = 0;
5980 total_len = 0;
5981 goto again;
c2951f32 5982 }
23b5ec74
JB
5983
5984 entry = addr;
92d32170 5985 put_unaligned(name_len, &entry->name_len);
23b5ec74 5986 name_ptr = (char *)(entry + 1);
c2951f32
JM
5987 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5988 name_len);
7d157c3d 5989 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
92d32170 5990 &entry->type);
c2951f32 5991 btrfs_dir_item_key_to_cpu(leaf, di, &location);
92d32170
DS
5992 put_unaligned(location.objectid, &entry->ino);
5993 put_unaligned(found_key.offset, &entry->offset);
23b5ec74
JB
5994 entries++;
5995 addr += sizeof(struct dir_entry) + name_len;
5996 total_len += sizeof(struct dir_entry) + name_len;
b9e03af0
LZ
5997next:
5998 path->slots[0]++;
39279cc3 5999 }
23b5ec74
JB
6000 btrfs_release_path(path);
6001
6002 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6003 if (ret)
6004 goto nopos;
49593bfa 6005
d2fbb2b5 6006 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
c2951f32 6007 if (ret)
bc4ef759
DS
6008 goto nopos;
6009
db62efbb
ZB
6010 /*
6011 * Stop new entries from being returned after we return the last
6012 * entry.
6013 *
6014 * New directory entries are assigned a strictly increasing
6015 * offset. This means that new entries created during readdir
6016 * are *guaranteed* to be seen in the future by that readdir.
6017 * This has broken buggy programs which operate on names as
6018 * they're returned by readdir. Until we re-use freed offsets
6019 * we have this hack to stop new entries from being returned
6020 * under the assumption that they'll never reach this huge
6021 * offset.
6022 *
6023 * This is being careful not to overflow 32bit loff_t unless the
6024 * last entry requires it because doing so has broken 32bit apps
6025 * in the past.
6026 */
c2951f32
JM
6027 if (ctx->pos >= INT_MAX)
6028 ctx->pos = LLONG_MAX;
6029 else
6030 ctx->pos = INT_MAX;
39279cc3
CM
6031nopos:
6032 ret = 0;
6033err:
02dbfc99
OS
6034 if (put)
6035 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
39279cc3 6036 btrfs_free_path(path);
39279cc3
CM
6037 return ret;
6038}
6039
39279cc3 6040/*
54aa1f4d 6041 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
6042 * inode changes. But, it is most likely to find the inode in cache.
6043 * FIXME, needs more benchmarking...there are no reasons other than performance
6044 * to keep or drop this code.
6045 */
48a3b636 6046static int btrfs_dirty_inode(struct inode *inode)
39279cc3 6047{
2ff7e61e 6048 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
6049 struct btrfs_root *root = BTRFS_I(inode)->root;
6050 struct btrfs_trans_handle *trans;
8929ecfa
YZ
6051 int ret;
6052
72ac3c0d 6053 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
22c44fe6 6054 return 0;
39279cc3 6055
7a7eaa40 6056 trans = btrfs_join_transaction(root);
22c44fe6
JB
6057 if (IS_ERR(trans))
6058 return PTR_ERR(trans);
8929ecfa
YZ
6059
6060 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
6061 if (ret && ret == -ENOSPC) {
6062 /* whoops, lets try again with the full transaction */
3a45bb20 6063 btrfs_end_transaction(trans);
94b60442 6064 trans = btrfs_start_transaction(root, 1);
22c44fe6
JB
6065 if (IS_ERR(trans))
6066 return PTR_ERR(trans);
8929ecfa 6067
94b60442 6068 ret = btrfs_update_inode(trans, root, inode);
94b60442 6069 }
3a45bb20 6070 btrfs_end_transaction(trans);
16cdcec7 6071 if (BTRFS_I(inode)->delayed_node)
2ff7e61e 6072 btrfs_balance_delayed_items(fs_info);
22c44fe6
JB
6073
6074 return ret;
6075}
6076
6077/*
6078 * This is a copy of file_update_time. We need this so we can return error on
6079 * ENOSPC for updating the inode in the case of file write and mmap writes.
6080 */
95582b00 6081static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
e41f941a 6082 int flags)
22c44fe6 6083{
2bc55652 6084 struct btrfs_root *root = BTRFS_I(inode)->root;
3a8c7231 6085 bool dirty = flags & ~S_VERSION;
2bc55652
AB
6086
6087 if (btrfs_root_readonly(root))
6088 return -EROFS;
6089
e41f941a 6090 if (flags & S_VERSION)
3a8c7231 6091 dirty |= inode_maybe_inc_iversion(inode, dirty);
e41f941a
JB
6092 if (flags & S_CTIME)
6093 inode->i_ctime = *now;
6094 if (flags & S_MTIME)
6095 inode->i_mtime = *now;
6096 if (flags & S_ATIME)
6097 inode->i_atime = *now;
3a8c7231 6098 return dirty ? btrfs_dirty_inode(inode) : 0;
39279cc3
CM
6099}
6100
d352ac68
CM
6101/*
6102 * find the highest existing sequence number in a directory
6103 * and then set the in-memory index_cnt variable to reflect
6104 * free sequence numbers
6105 */
4c570655 6106static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
aec7477b 6107{
4c570655 6108 struct btrfs_root *root = inode->root;
aec7477b
JB
6109 struct btrfs_key key, found_key;
6110 struct btrfs_path *path;
6111 struct extent_buffer *leaf;
6112 int ret;
6113
4c570655 6114 key.objectid = btrfs_ino(inode);
962a298f 6115 key.type = BTRFS_DIR_INDEX_KEY;
aec7477b
JB
6116 key.offset = (u64)-1;
6117
6118 path = btrfs_alloc_path();
6119 if (!path)
6120 return -ENOMEM;
6121
6122 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6123 if (ret < 0)
6124 goto out;
6125 /* FIXME: we should be able to handle this */
6126 if (ret == 0)
6127 goto out;
6128 ret = 0;
6129
6130 /*
6131 * MAGIC NUMBER EXPLANATION:
6132 * since we search a directory based on f_pos we have to start at 2
6133 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6134 * else has to start at 2
6135 */
6136 if (path->slots[0] == 0) {
4c570655 6137 inode->index_cnt = 2;
aec7477b
JB
6138 goto out;
6139 }
6140
6141 path->slots[0]--;
6142
6143 leaf = path->nodes[0];
6144 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6145
4c570655 6146 if (found_key.objectid != btrfs_ino(inode) ||
962a298f 6147 found_key.type != BTRFS_DIR_INDEX_KEY) {
4c570655 6148 inode->index_cnt = 2;
aec7477b
JB
6149 goto out;
6150 }
6151
4c570655 6152 inode->index_cnt = found_key.offset + 1;
aec7477b
JB
6153out:
6154 btrfs_free_path(path);
6155 return ret;
6156}
6157
d352ac68
CM
6158/*
6159 * helper to find a free sequence number in a given directory. This current
6160 * code is very simple, later versions will do smarter things in the btree
6161 */
877574e2 6162int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
aec7477b
JB
6163{
6164 int ret = 0;
6165
877574e2
NB
6166 if (dir->index_cnt == (u64)-1) {
6167 ret = btrfs_inode_delayed_dir_index_count(dir);
16cdcec7
MX
6168 if (ret) {
6169 ret = btrfs_set_inode_index_count(dir);
6170 if (ret)
6171 return ret;
6172 }
aec7477b
JB
6173 }
6174
877574e2
NB
6175 *index = dir->index_cnt;
6176 dir->index_cnt++;
aec7477b
JB
6177
6178 return ret;
6179}
6180
b0d5d10f
CM
6181static int btrfs_insert_inode_locked(struct inode *inode)
6182{
6183 struct btrfs_iget_args args;
6184 args.location = &BTRFS_I(inode)->location;
6185 args.root = BTRFS_I(inode)->root;
6186
6187 return insert_inode_locked4(inode,
6188 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6189 btrfs_find_actor, &args);
6190}
6191
19aee8de
AJ
6192/*
6193 * Inherit flags from the parent inode.
6194 *
6195 * Currently only the compression flags and the cow flags are inherited.
6196 */
6197static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6198{
6199 unsigned int flags;
6200
6201 if (!dir)
6202 return;
6203
6204 flags = BTRFS_I(dir)->flags;
6205
6206 if (flags & BTRFS_INODE_NOCOMPRESS) {
6207 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6208 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6209 } else if (flags & BTRFS_INODE_COMPRESS) {
6210 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6211 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6212 }
6213
6214 if (flags & BTRFS_INODE_NODATACOW) {
6215 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6216 if (S_ISREG(inode->i_mode))
6217 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6218 }
6219
7b6a221e 6220 btrfs_sync_inode_flags_to_i_flags(inode);
19aee8de
AJ
6221}
6222
39279cc3
CM
6223static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6224 struct btrfs_root *root,
aec7477b 6225 struct inode *dir,
9c58309d 6226 const char *name, int name_len,
175a4eb7
AV
6227 u64 ref_objectid, u64 objectid,
6228 umode_t mode, u64 *index)
39279cc3 6229{
0b246afa 6230 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 6231 struct inode *inode;
5f39d397 6232 struct btrfs_inode_item *inode_item;
39279cc3 6233 struct btrfs_key *location;
5f39d397 6234 struct btrfs_path *path;
9c58309d
CM
6235 struct btrfs_inode_ref *ref;
6236 struct btrfs_key key[2];
6237 u32 sizes[2];
ef3b9af5 6238 int nitems = name ? 2 : 1;
9c58309d 6239 unsigned long ptr;
39279cc3 6240 int ret;
39279cc3 6241
5f39d397 6242 path = btrfs_alloc_path();
d8926bb3
MF
6243 if (!path)
6244 return ERR_PTR(-ENOMEM);
5f39d397 6245
0b246afa 6246 inode = new_inode(fs_info->sb);
8fb27640
YS
6247 if (!inode) {
6248 btrfs_free_path(path);
39279cc3 6249 return ERR_PTR(-ENOMEM);
8fb27640 6250 }
39279cc3 6251
5762b5c9
FM
6252 /*
6253 * O_TMPFILE, set link count to 0, so that after this point,
6254 * we fill in an inode item with the correct link count.
6255 */
6256 if (!name)
6257 set_nlink(inode, 0);
6258
581bb050
LZ
6259 /*
6260 * we have to initialize this early, so we can reclaim the inode
6261 * number if we fail afterwards in this function.
6262 */
6263 inode->i_ino = objectid;
6264
ef3b9af5 6265 if (dir && name) {
1abe9b8a 6266 trace_btrfs_inode_request(dir);
6267
877574e2 6268 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
09771430 6269 if (ret) {
8fb27640 6270 btrfs_free_path(path);
09771430 6271 iput(inode);
aec7477b 6272 return ERR_PTR(ret);
09771430 6273 }
ef3b9af5
FM
6274 } else if (dir) {
6275 *index = 0;
aec7477b
JB
6276 }
6277 /*
6278 * index_cnt is ignored for everything but a dir,
df6703e1 6279 * btrfs_set_inode_index_count has an explanation for the magic
aec7477b
JB
6280 * number
6281 */
6282 BTRFS_I(inode)->index_cnt = 2;
67de1176 6283 BTRFS_I(inode)->dir_index = *index;
39279cc3 6284 BTRFS_I(inode)->root = root;
e02119d5 6285 BTRFS_I(inode)->generation = trans->transid;
76195853 6286 inode->i_generation = BTRFS_I(inode)->generation;
b888db2b 6287
5dc562c5
JB
6288 /*
6289 * We could have gotten an inode number from somebody who was fsynced
6290 * and then removed in this same transaction, so let's just set full
6291 * sync since it will be a full sync anyway and this will blow away the
6292 * old info in the log.
6293 */
6294 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6295
9c58309d 6296 key[0].objectid = objectid;
962a298f 6297 key[0].type = BTRFS_INODE_ITEM_KEY;
9c58309d
CM
6298 key[0].offset = 0;
6299
9c58309d 6300 sizes[0] = sizeof(struct btrfs_inode_item);
ef3b9af5
FM
6301
6302 if (name) {
6303 /*
6304 * Start new inodes with an inode_ref. This is slightly more
6305 * efficient for small numbers of hard links since they will
6306 * be packed into one item. Extended refs will kick in if we
6307 * add more hard links than can fit in the ref item.
6308 */
6309 key[1].objectid = objectid;
962a298f 6310 key[1].type = BTRFS_INODE_REF_KEY;
ef3b9af5
FM
6311 key[1].offset = ref_objectid;
6312
6313 sizes[1] = name_len + sizeof(*ref);
6314 }
9c58309d 6315
b0d5d10f
CM
6316 location = &BTRFS_I(inode)->location;
6317 location->objectid = objectid;
6318 location->offset = 0;
962a298f 6319 location->type = BTRFS_INODE_ITEM_KEY;
b0d5d10f
CM
6320
6321 ret = btrfs_insert_inode_locked(inode);
32955c54
AV
6322 if (ret < 0) {
6323 iput(inode);
b0d5d10f 6324 goto fail;
32955c54 6325 }
b0d5d10f 6326
b9473439 6327 path->leave_spinning = 1;
ef3b9af5 6328 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
9c58309d 6329 if (ret != 0)
b0d5d10f 6330 goto fail_unlock;
5f39d397 6331
ecc11fab 6332 inode_init_owner(inode, dir, mode);
a76a3cd4 6333 inode_set_bytes(inode, 0);
9cc97d64 6334
c2050a45 6335 inode->i_mtime = current_time(inode);
9cc97d64 6336 inode->i_atime = inode->i_mtime;
6337 inode->i_ctime = inode->i_mtime;
d3c6be6f 6338 BTRFS_I(inode)->i_otime = inode->i_mtime;
9cc97d64 6339
5f39d397
CM
6340 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6341 struct btrfs_inode_item);
b159fa28 6342 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
293f7e07 6343 sizeof(*inode_item));
e02119d5 6344 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d 6345
ef3b9af5
FM
6346 if (name) {
6347 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6348 struct btrfs_inode_ref);
6349 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6350 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6351 ptr = (unsigned long)(ref + 1);
6352 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6353 }
9c58309d 6354
5f39d397
CM
6355 btrfs_mark_buffer_dirty(path->nodes[0]);
6356 btrfs_free_path(path);
6357
6cbff00f
CH
6358 btrfs_inherit_iflags(inode, dir);
6359
569254b0 6360 if (S_ISREG(mode)) {
0b246afa 6361 if (btrfs_test_opt(fs_info, NODATASUM))
94272164 6362 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
0b246afa 6363 if (btrfs_test_opt(fs_info, NODATACOW))
f2bdf9a8
JB
6364 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6365 BTRFS_INODE_NODATASUM;
94272164
CM
6366 }
6367
5d4f98a2 6368 inode_tree_add(inode);
1abe9b8a 6369
6370 trace_btrfs_inode_new(inode);
1973f0fa 6371 btrfs_set_inode_last_trans(trans, inode);
1abe9b8a 6372
8ea05e3a
AB
6373 btrfs_update_root_times(trans, root);
6374
63541927
FDBM
6375 ret = btrfs_inode_inherit_props(trans, inode, dir);
6376 if (ret)
0b246afa 6377 btrfs_err(fs_info,
63541927 6378 "error inheriting props for ino %llu (root %llu): %d",
f85b7379 6379 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
63541927 6380
39279cc3 6381 return inode;
b0d5d10f
CM
6382
6383fail_unlock:
32955c54 6384 discard_new_inode(inode);
5f39d397 6385fail:
ef3b9af5 6386 if (dir && name)
aec7477b 6387 BTRFS_I(dir)->index_cnt--;
5f39d397
CM
6388 btrfs_free_path(path);
6389 return ERR_PTR(ret);
39279cc3
CM
6390}
6391
d352ac68
CM
6392/*
6393 * utility function to add 'inode' into 'parent_inode' with
6394 * a give name and a given sequence number.
6395 * if 'add_backref' is true, also insert a backref from the
6396 * inode to the parent directory.
6397 */
e02119d5 6398int btrfs_add_link(struct btrfs_trans_handle *trans,
db0a669f 6399 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
e02119d5 6400 const char *name, int name_len, int add_backref, u64 index)
39279cc3 6401{
4df27c4d 6402 int ret = 0;
39279cc3 6403 struct btrfs_key key;
db0a669f
NB
6404 struct btrfs_root *root = parent_inode->root;
6405 u64 ino = btrfs_ino(inode);
6406 u64 parent_ino = btrfs_ino(parent_inode);
5f39d397 6407
33345d01 6408 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
db0a669f 6409 memcpy(&key, &inode->root->root_key, sizeof(key));
4df27c4d 6410 } else {
33345d01 6411 key.objectid = ino;
962a298f 6412 key.type = BTRFS_INODE_ITEM_KEY;
4df27c4d
YZ
6413 key.offset = 0;
6414 }
6415
33345d01 6416 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6025c19f 6417 ret = btrfs_add_root_ref(trans, key.objectid,
0b246afa
JM
6418 root->root_key.objectid, parent_ino,
6419 index, name, name_len);
4df27c4d 6420 } else if (add_backref) {
33345d01
LZ
6421 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6422 parent_ino, index);
4df27c4d 6423 }
39279cc3 6424
79787eaa
JM
6425 /* Nothing to clean up yet */
6426 if (ret)
6427 return ret;
4df27c4d 6428
684572df 6429 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
db0a669f 6430 btrfs_inode_type(&inode->vfs_inode), index);
9c52057c 6431 if (ret == -EEXIST || ret == -EOVERFLOW)
79787eaa
JM
6432 goto fail_dir_item;
6433 else if (ret) {
66642832 6434 btrfs_abort_transaction(trans, ret);
79787eaa 6435 return ret;
39279cc3 6436 }
79787eaa 6437
db0a669f 6438 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
79787eaa 6439 name_len * 2);
db0a669f
NB
6440 inode_inc_iversion(&parent_inode->vfs_inode);
6441 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6442 current_time(&parent_inode->vfs_inode);
6443 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
79787eaa 6444 if (ret)
66642832 6445 btrfs_abort_transaction(trans, ret);
39279cc3 6446 return ret;
fe66a05a
CM
6447
6448fail_dir_item:
6449 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6450 u64 local_index;
6451 int err;
3ee1c553 6452 err = btrfs_del_root_ref(trans, key.objectid,
0b246afa
JM
6453 root->root_key.objectid, parent_ino,
6454 &local_index, name, name_len);
1690dd41
JT
6455 if (err)
6456 btrfs_abort_transaction(trans, err);
fe66a05a
CM
6457 } else if (add_backref) {
6458 u64 local_index;
6459 int err;
6460
6461 err = btrfs_del_inode_ref(trans, root, name, name_len,
6462 ino, parent_ino, &local_index);
1690dd41
JT
6463 if (err)
6464 btrfs_abort_transaction(trans, err);
fe66a05a 6465 }
1690dd41
JT
6466
6467 /* Return the original error code */
fe66a05a 6468 return ret;
39279cc3
CM
6469}
6470
6471static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
cef415af
NB
6472 struct btrfs_inode *dir, struct dentry *dentry,
6473 struct btrfs_inode *inode, int backref, u64 index)
39279cc3 6474{
a1b075d2
JB
6475 int err = btrfs_add_link(trans, dir, inode,
6476 dentry->d_name.name, dentry->d_name.len,
6477 backref, index);
39279cc3
CM
6478 if (err > 0)
6479 err = -EEXIST;
6480 return err;
6481}
6482
618e21d5 6483static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1a67aafb 6484 umode_t mode, dev_t rdev)
618e21d5 6485{
2ff7e61e 6486 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
618e21d5
JB
6487 struct btrfs_trans_handle *trans;
6488 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6489 struct inode *inode = NULL;
618e21d5 6490 int err;
618e21d5 6491 u64 objectid;
00e4e6b3 6492 u64 index = 0;
618e21d5 6493
9ed74f2d
JB
6494 /*
6495 * 2 for inode item and ref
6496 * 2 for dir items
6497 * 1 for xattr if selinux is on
6498 */
a22285a6
YZ
6499 trans = btrfs_start_transaction(root, 5);
6500 if (IS_ERR(trans))
6501 return PTR_ERR(trans);
1832a6d5 6502
581bb050
LZ
6503 err = btrfs_find_free_ino(root, &objectid);
6504 if (err)
6505 goto out_unlock;
6506
aec7477b 6507 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6508 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6509 mode, &index);
7cf96da3
TI
6510 if (IS_ERR(inode)) {
6511 err = PTR_ERR(inode);
32955c54 6512 inode = NULL;
618e21d5 6513 goto out_unlock;
7cf96da3 6514 }
618e21d5 6515
ad19db71
CS
6516 /*
6517 * If the active LSM wants to access the inode during
6518 * d_instantiate it needs these. Smack checks to see
6519 * if the filesystem supports xattrs by looking at the
6520 * ops vector.
6521 */
ad19db71 6522 inode->i_op = &btrfs_special_inode_operations;
b0d5d10f
CM
6523 init_special_inode(inode, inode->i_mode, rdev);
6524
6525 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
618e21d5 6526 if (err)
32955c54 6527 goto out_unlock;
b0d5d10f 6528
cef415af
NB
6529 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6530 0, index);
32955c54
AV
6531 if (err)
6532 goto out_unlock;
6533
6534 btrfs_update_inode(trans, root, inode);
6535 d_instantiate_new(dentry, inode);
b0d5d10f 6536
618e21d5 6537out_unlock:
3a45bb20 6538 btrfs_end_transaction(trans);
2ff7e61e 6539 btrfs_btree_balance_dirty(fs_info);
32955c54 6540 if (err && inode) {
618e21d5 6541 inode_dec_link_count(inode);
32955c54 6542 discard_new_inode(inode);
618e21d5 6543 }
618e21d5
JB
6544 return err;
6545}
6546
39279cc3 6547static int btrfs_create(struct inode *dir, struct dentry *dentry,
ebfc3b49 6548 umode_t mode, bool excl)
39279cc3 6549{
2ff7e61e 6550 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
6551 struct btrfs_trans_handle *trans;
6552 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6553 struct inode *inode = NULL;
a22285a6 6554 int err;
39279cc3 6555 u64 objectid;
00e4e6b3 6556 u64 index = 0;
39279cc3 6557
9ed74f2d
JB
6558 /*
6559 * 2 for inode item and ref
6560 * 2 for dir items
6561 * 1 for xattr if selinux is on
6562 */
a22285a6
YZ
6563 trans = btrfs_start_transaction(root, 5);
6564 if (IS_ERR(trans))
6565 return PTR_ERR(trans);
9ed74f2d 6566
581bb050
LZ
6567 err = btrfs_find_free_ino(root, &objectid);
6568 if (err)
6569 goto out_unlock;
6570
aec7477b 6571 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6572 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6573 mode, &index);
7cf96da3
TI
6574 if (IS_ERR(inode)) {
6575 err = PTR_ERR(inode);
32955c54 6576 inode = NULL;
39279cc3 6577 goto out_unlock;
7cf96da3 6578 }
ad19db71
CS
6579 /*
6580 * If the active LSM wants to access the inode during
6581 * d_instantiate it needs these. Smack checks to see
6582 * if the filesystem supports xattrs by looking at the
6583 * ops vector.
6584 */
6585 inode->i_fop = &btrfs_file_operations;
6586 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 6587 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
6588
6589 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6590 if (err)
32955c54 6591 goto out_unlock;
b0d5d10f
CM
6592
6593 err = btrfs_update_inode(trans, root, inode);
6594 if (err)
32955c54 6595 goto out_unlock;
ad19db71 6596
cef415af
NB
6597 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6598 0, index);
39279cc3 6599 if (err)
32955c54 6600 goto out_unlock;
43baa579 6601
43baa579 6602 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1e2e547a 6603 d_instantiate_new(dentry, inode);
43baa579 6604
39279cc3 6605out_unlock:
3a45bb20 6606 btrfs_end_transaction(trans);
32955c54 6607 if (err && inode) {
39279cc3 6608 inode_dec_link_count(inode);
32955c54 6609 discard_new_inode(inode);
39279cc3 6610 }
2ff7e61e 6611 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6612 return err;
6613}
6614
6615static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6616 struct dentry *dentry)
6617{
271dba45 6618 struct btrfs_trans_handle *trans = NULL;
39279cc3 6619 struct btrfs_root *root = BTRFS_I(dir)->root;
2b0143b5 6620 struct inode *inode = d_inode(old_dentry);
2ff7e61e 6621 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
00e4e6b3 6622 u64 index;
39279cc3
CM
6623 int err;
6624 int drop_inode = 0;
6625
4a8be425 6626 /* do not allow sys_link's with other subvols of the same device */
4fd786e6 6627 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
3ab3564f 6628 return -EXDEV;
4a8be425 6629
f186373f 6630 if (inode->i_nlink >= BTRFS_LINK_MAX)
c055e99e 6631 return -EMLINK;
4a8be425 6632
877574e2 6633 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
aec7477b
JB
6634 if (err)
6635 goto fail;
6636
a22285a6 6637 /*
7e6b6465 6638 * 2 items for inode and inode ref
a22285a6 6639 * 2 items for dir items
7e6b6465 6640 * 1 item for parent inode
399b0bbf 6641 * 1 item for orphan item deletion if O_TMPFILE
a22285a6 6642 */
399b0bbf 6643 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
a22285a6
YZ
6644 if (IS_ERR(trans)) {
6645 err = PTR_ERR(trans);
271dba45 6646 trans = NULL;
a22285a6
YZ
6647 goto fail;
6648 }
5f39d397 6649
67de1176
MX
6650 /* There are several dir indexes for this inode, clear the cache. */
6651 BTRFS_I(inode)->dir_index = 0ULL;
8b558c5f 6652 inc_nlink(inode);
0c4d2d95 6653 inode_inc_iversion(inode);
c2050a45 6654 inode->i_ctime = current_time(inode);
7de9c6ee 6655 ihold(inode);
e9976151 6656 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
aec7477b 6657
cef415af
NB
6658 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6659 1, index);
5f39d397 6660
a5719521 6661 if (err) {
54aa1f4d 6662 drop_inode = 1;
a5719521 6663 } else {
10d9f309 6664 struct dentry *parent = dentry->d_parent;
d4682ba0
FM
6665 int ret;
6666
a5719521 6667 err = btrfs_update_inode(trans, root, inode);
79787eaa
JM
6668 if (err)
6669 goto fail;
ef3b9af5
FM
6670 if (inode->i_nlink == 1) {
6671 /*
6672 * If new hard link count is 1, it's a file created
6673 * with open(2) O_TMPFILE flag.
6674 */
3d6ae7bb 6675 err = btrfs_orphan_del(trans, BTRFS_I(inode));
ef3b9af5
FM
6676 if (err)
6677 goto fail;
6678 }
08c422c2 6679 d_instantiate(dentry, inode);
d4682ba0
FM
6680 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6681 true, NULL);
6682 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6683 err = btrfs_commit_transaction(trans);
6684 trans = NULL;
6685 }
a5719521 6686 }
39279cc3 6687
1832a6d5 6688fail:
271dba45 6689 if (trans)
3a45bb20 6690 btrfs_end_transaction(trans);
39279cc3
CM
6691 if (drop_inode) {
6692 inode_dec_link_count(inode);
6693 iput(inode);
6694 }
2ff7e61e 6695 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6696 return err;
6697}
6698
18bb1db3 6699static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
39279cc3 6700{
2ff7e61e 6701 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
b9d86667 6702 struct inode *inode = NULL;
39279cc3
CM
6703 struct btrfs_trans_handle *trans;
6704 struct btrfs_root *root = BTRFS_I(dir)->root;
6705 int err = 0;
b9d86667 6706 u64 objectid = 0;
00e4e6b3 6707 u64 index = 0;
39279cc3 6708
9ed74f2d
JB
6709 /*
6710 * 2 items for inode and ref
6711 * 2 items for dir items
6712 * 1 for xattr if selinux is on
6713 */
a22285a6
YZ
6714 trans = btrfs_start_transaction(root, 5);
6715 if (IS_ERR(trans))
6716 return PTR_ERR(trans);
39279cc3 6717
581bb050
LZ
6718 err = btrfs_find_free_ino(root, &objectid);
6719 if (err)
6720 goto out_fail;
6721
aec7477b 6722 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6723 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6724 S_IFDIR | mode, &index);
39279cc3
CM
6725 if (IS_ERR(inode)) {
6726 err = PTR_ERR(inode);
32955c54 6727 inode = NULL;
39279cc3
CM
6728 goto out_fail;
6729 }
5f39d397 6730
b0d5d10f
CM
6731 /* these must be set before we unlock the inode */
6732 inode->i_op = &btrfs_dir_inode_operations;
6733 inode->i_fop = &btrfs_dir_file_operations;
33268eaf 6734
2a7dba39 6735 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf 6736 if (err)
32955c54 6737 goto out_fail;
39279cc3 6738
6ef06d27 6739 btrfs_i_size_write(BTRFS_I(inode), 0);
39279cc3
CM
6740 err = btrfs_update_inode(trans, root, inode);
6741 if (err)
32955c54 6742 goto out_fail;
5f39d397 6743
db0a669f
NB
6744 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6745 dentry->d_name.name,
6746 dentry->d_name.len, 0, index);
39279cc3 6747 if (err)
32955c54 6748 goto out_fail;
5f39d397 6749
1e2e547a 6750 d_instantiate_new(dentry, inode);
39279cc3
CM
6751
6752out_fail:
3a45bb20 6753 btrfs_end_transaction(trans);
32955c54 6754 if (err && inode) {
c7cfb8a5 6755 inode_dec_link_count(inode);
32955c54 6756 discard_new_inode(inode);
c7cfb8a5 6757 }
2ff7e61e 6758 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6759 return err;
6760}
6761
c8b97818 6762static noinline int uncompress_inline(struct btrfs_path *path,
e40da0e5 6763 struct page *page,
c8b97818
CM
6764 size_t pg_offset, u64 extent_offset,
6765 struct btrfs_file_extent_item *item)
6766{
6767 int ret;
6768 struct extent_buffer *leaf = path->nodes[0];
6769 char *tmp;
6770 size_t max_size;
6771 unsigned long inline_size;
6772 unsigned long ptr;
261507a0 6773 int compress_type;
c8b97818
CM
6774
6775 WARN_ON(pg_offset != 0);
261507a0 6776 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
6777 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6778 inline_size = btrfs_file_extent_inline_item_len(leaf,
dd3cc16b 6779 btrfs_item_nr(path->slots[0]));
c8b97818 6780 tmp = kmalloc(inline_size, GFP_NOFS);
8d413713
TI
6781 if (!tmp)
6782 return -ENOMEM;
c8b97818
CM
6783 ptr = btrfs_file_extent_inline_start(item);
6784
6785 read_extent_buffer(leaf, tmp, ptr, inline_size);
6786
09cbfeaf 6787 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
261507a0
LZ
6788 ret = btrfs_decompress(compress_type, tmp, page,
6789 extent_offset, inline_size, max_size);
e1699d2d
ZB
6790
6791 /*
6792 * decompression code contains a memset to fill in any space between the end
6793 * of the uncompressed data and the end of max_size in case the decompressed
6794 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6795 * the end of an inline extent and the beginning of the next block, so we
6796 * cover that region here.
6797 */
6798
6799 if (max_size + pg_offset < PAGE_SIZE) {
6800 char *map = kmap(page);
6801 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6802 kunmap(page);
6803 }
c8b97818 6804 kfree(tmp);
166ae5a4 6805 return ret;
c8b97818
CM
6806}
6807
d352ac68
CM
6808/*
6809 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
6810 * the ugly parts come from merging extents from the disk with the in-ram
6811 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
6812 * where the in-ram extents might be locked pending data=ordered completion.
6813 *
6814 * This also copies inline extents directly into the page.
6815 */
fc4f21b1 6816struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
de2c6615
LB
6817 struct page *page,
6818 size_t pg_offset, u64 start, u64 len,
6819 int create)
a52d9a80 6820{
3ffbd68c 6821 struct btrfs_fs_info *fs_info = inode->root->fs_info;
a52d9a80
CM
6822 int ret;
6823 int err = 0;
a52d9a80
CM
6824 u64 extent_start = 0;
6825 u64 extent_end = 0;
fc4f21b1 6826 u64 objectid = btrfs_ino(inode);
694c12ed 6827 u8 extent_type;
f421950f 6828 struct btrfs_path *path = NULL;
fc4f21b1 6829 struct btrfs_root *root = inode->root;
a52d9a80 6830 struct btrfs_file_extent_item *item;
5f39d397
CM
6831 struct extent_buffer *leaf;
6832 struct btrfs_key found_key;
a52d9a80 6833 struct extent_map *em = NULL;
fc4f21b1
NB
6834 struct extent_map_tree *em_tree = &inode->extent_tree;
6835 struct extent_io_tree *io_tree = &inode->io_tree;
7ffbb598 6836 const bool new_inline = !page || create;
a52d9a80 6837
890871be 6838 read_lock(&em_tree->lock);
d1310b2e 6839 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d 6840 if (em)
0b246afa 6841 em->bdev = fs_info->fs_devices->latest_bdev;
890871be 6842 read_unlock(&em_tree->lock);
d1310b2e 6843
a52d9a80 6844 if (em) {
e1c4b745
CM
6845 if (em->start > start || em->start + em->len <= start)
6846 free_extent_map(em);
6847 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
6848 free_extent_map(em);
6849 else
6850 goto out;
a52d9a80 6851 }
172ddd60 6852 em = alloc_extent_map();
a52d9a80 6853 if (!em) {
d1310b2e
CM
6854 err = -ENOMEM;
6855 goto out;
a52d9a80 6856 }
0b246afa 6857 em->bdev = fs_info->fs_devices->latest_bdev;
d1310b2e 6858 em->start = EXTENT_MAP_HOLE;
445a6944 6859 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 6860 em->len = (u64)-1;
c8b97818 6861 em->block_len = (u64)-1;
f421950f 6862
bee6ec82 6863 path = btrfs_alloc_path();
f421950f 6864 if (!path) {
bee6ec82
LB
6865 err = -ENOMEM;
6866 goto out;
f421950f
CM
6867 }
6868
bee6ec82
LB
6869 /* Chances are we'll be called again, so go ahead and do readahead */
6870 path->reada = READA_FORWARD;
6871
e49aabd9
LB
6872 /*
6873 * Unless we're going to uncompress the inline extent, no sleep would
6874 * happen.
6875 */
6876 path->leave_spinning = 1;
6877
5c9a702e 6878 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
a52d9a80
CM
6879 if (ret < 0) {
6880 err = ret;
6881 goto out;
b8eeab7f 6882 } else if (ret > 0) {
a52d9a80
CM
6883 if (path->slots[0] == 0)
6884 goto not_found;
6885 path->slots[0]--;
6886 }
6887
5f39d397
CM
6888 leaf = path->nodes[0];
6889 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 6890 struct btrfs_file_extent_item);
5f39d397 6891 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5f39d397 6892 if (found_key.objectid != objectid ||
694c12ed 6893 found_key.type != BTRFS_EXTENT_DATA_KEY) {
25a50341
JB
6894 /*
6895 * If we backup past the first extent we want to move forward
6896 * and see if there is an extent in front of us, otherwise we'll
6897 * say there is a hole for our whole search range which can
6898 * cause problems.
6899 */
6900 extent_end = start;
6901 goto next;
a52d9a80
CM
6902 }
6903
694c12ed 6904 extent_type = btrfs_file_extent_type(leaf, item);
5f39d397 6905 extent_start = found_key.offset;
694c12ed
NB
6906 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6907 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6bf9e4bd
QW
6908 /* Only regular file could have regular/prealloc extent */
6909 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6910 ret = -EUCLEAN;
6911 btrfs_crit(fs_info,
6912 "regular/prealloc extent found for non-regular inode %llu",
6913 btrfs_ino(inode));
6914 goto out;
6915 }
a52d9a80 6916 extent_end = extent_start +
db94535d 6917 btrfs_file_extent_num_bytes(leaf, item);
09ed2f16
LB
6918
6919 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6920 extent_start);
694c12ed 6921 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
9036c102 6922 size_t size;
e41ca589
QW
6923
6924 size = btrfs_file_extent_ram_bytes(leaf, item);
da17066c 6925 extent_end = ALIGN(extent_start + size,
0b246afa 6926 fs_info->sectorsize);
09ed2f16
LB
6927
6928 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6929 path->slots[0],
6930 extent_start);
9036c102 6931 }
25a50341 6932next:
9036c102
YZ
6933 if (start >= extent_end) {
6934 path->slots[0]++;
6935 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6936 ret = btrfs_next_leaf(root, path);
6937 if (ret < 0) {
6938 err = ret;
6939 goto out;
b8eeab7f 6940 } else if (ret > 0) {
9036c102 6941 goto not_found;
b8eeab7f 6942 }
9036c102 6943 leaf = path->nodes[0];
a52d9a80 6944 }
9036c102
YZ
6945 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6946 if (found_key.objectid != objectid ||
6947 found_key.type != BTRFS_EXTENT_DATA_KEY)
6948 goto not_found;
6949 if (start + len <= found_key.offset)
6950 goto not_found;
e2eca69d
WS
6951 if (start > found_key.offset)
6952 goto next;
02a033df
NB
6953
6954 /* New extent overlaps with existing one */
9036c102 6955 em->start = start;
70c8a91c 6956 em->orig_start = start;
9036c102 6957 em->len = found_key.offset - start;
02a033df
NB
6958 em->block_start = EXTENT_MAP_HOLE;
6959 goto insert;
9036c102
YZ
6960 }
6961
fc4f21b1 6962 btrfs_extent_item_to_extent_map(inode, path, item,
9cdc5124 6963 new_inline, em);
7ffbb598 6964
694c12ed
NB
6965 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6966 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 6967 goto insert;
694c12ed 6968 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 6969 unsigned long ptr;
a52d9a80 6970 char *map;
3326d1b0
CM
6971 size_t size;
6972 size_t extent_offset;
6973 size_t copy_size;
a52d9a80 6974
7ffbb598 6975 if (new_inline)
689f9346 6976 goto out;
5f39d397 6977
e41ca589 6978 size = btrfs_file_extent_ram_bytes(leaf, item);
9036c102 6979 extent_offset = page_offset(page) + pg_offset - extent_start;
09cbfeaf
KS
6980 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6981 size - extent_offset);
3326d1b0 6982 em->start = extent_start + extent_offset;
0b246afa 6983 em->len = ALIGN(copy_size, fs_info->sectorsize);
b4939680 6984 em->orig_block_len = em->len;
70c8a91c 6985 em->orig_start = em->start;
689f9346 6986 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
e49aabd9
LB
6987
6988 btrfs_set_path_blocking(path);
bf46f52d 6989 if (!PageUptodate(page)) {
261507a0
LZ
6990 if (btrfs_file_extent_compression(leaf, item) !=
6991 BTRFS_COMPRESS_NONE) {
e40da0e5 6992 ret = uncompress_inline(path, page, pg_offset,
c8b97818 6993 extent_offset, item);
166ae5a4
ZB
6994 if (ret) {
6995 err = ret;
6996 goto out;
6997 }
c8b97818
CM
6998 } else {
6999 map = kmap(page);
7000 read_extent_buffer(leaf, map + pg_offset, ptr,
7001 copy_size);
09cbfeaf 7002 if (pg_offset + copy_size < PAGE_SIZE) {
93c82d57 7003 memset(map + pg_offset + copy_size, 0,
09cbfeaf 7004 PAGE_SIZE - pg_offset -
93c82d57
CM
7005 copy_size);
7006 }
c8b97818
CM
7007 kunmap(page);
7008 }
179e29e4 7009 flush_dcache_page(page);
a52d9a80 7010 }
d1310b2e 7011 set_extent_uptodate(io_tree, em->start,
507903b8 7012 extent_map_end(em) - 1, NULL, GFP_NOFS);
a52d9a80 7013 goto insert;
a52d9a80
CM
7014 }
7015not_found:
7016 em->start = start;
70c8a91c 7017 em->orig_start = start;
d1310b2e 7018 em->len = len;
5f39d397 7019 em->block_start = EXTENT_MAP_HOLE;
a52d9a80 7020insert:
b3b4aa74 7021 btrfs_release_path(path);
d1310b2e 7022 if (em->start > start || extent_map_end(em) <= start) {
0b246afa 7023 btrfs_err(fs_info,
5d163e0e
JM
7024 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7025 em->start, em->len, start, len);
a52d9a80
CM
7026 err = -EIO;
7027 goto out;
7028 }
d1310b2e
CM
7029
7030 err = 0;
890871be 7031 write_lock(&em_tree->lock);
f46b24c9 7032 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
890871be 7033 write_unlock(&em_tree->lock);
a52d9a80 7034out:
c6414280 7035 btrfs_free_path(path);
1abe9b8a 7036
fc4f21b1 7037 trace_btrfs_get_extent(root, inode, em);
1abe9b8a 7038
a52d9a80
CM
7039 if (err) {
7040 free_extent_map(em);
a52d9a80
CM
7041 return ERR_PTR(err);
7042 }
79787eaa 7043 BUG_ON(!em); /* Error is always set */
a52d9a80
CM
7044 return em;
7045}
7046
fc4f21b1 7047struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
4ab47a8d 7048 u64 start, u64 len)
ec29ed5b
CM
7049{
7050 struct extent_map *em;
7051 struct extent_map *hole_em = NULL;
f3714ef4 7052 u64 delalloc_start = start;
ec29ed5b 7053 u64 end;
f3714ef4
NB
7054 u64 delalloc_len;
7055 u64 delalloc_end;
ec29ed5b
CM
7056 int err = 0;
7057
4ab47a8d 7058 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
ec29ed5b
CM
7059 if (IS_ERR(em))
7060 return em;
9986277e
DC
7061 /*
7062 * If our em maps to:
7063 * - a hole or
7064 * - a pre-alloc extent,
7065 * there might actually be delalloc bytes behind it.
7066 */
7067 if (em->block_start != EXTENT_MAP_HOLE &&
7068 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7069 return em;
7070 else
7071 hole_em = em;
ec29ed5b
CM
7072
7073 /* check to see if we've wrapped (len == -1 or similar) */
7074 end = start + len;
7075 if (end < start)
7076 end = (u64)-1;
7077 else
7078 end -= 1;
7079
7080 em = NULL;
7081
7082 /* ok, we didn't find anything, lets look for delalloc */
f3714ef4 7083 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
ec29ed5b 7084 end, len, EXTENT_DELALLOC, 1);
f3714ef4
NB
7085 delalloc_end = delalloc_start + delalloc_len;
7086 if (delalloc_end < delalloc_start)
7087 delalloc_end = (u64)-1;
ec29ed5b
CM
7088
7089 /*
f3714ef4
NB
7090 * We didn't find anything useful, return the original results from
7091 * get_extent()
ec29ed5b 7092 */
f3714ef4 7093 if (delalloc_start > end || delalloc_end <= start) {
ec29ed5b
CM
7094 em = hole_em;
7095 hole_em = NULL;
7096 goto out;
7097 }
7098
f3714ef4
NB
7099 /*
7100 * Adjust the delalloc_start to make sure it doesn't go backwards from
7101 * the start they passed in
ec29ed5b 7102 */
f3714ef4
NB
7103 delalloc_start = max(start, delalloc_start);
7104 delalloc_len = delalloc_end - delalloc_start;
ec29ed5b 7105
f3714ef4
NB
7106 if (delalloc_len > 0) {
7107 u64 hole_start;
02950af4 7108 u64 hole_len;
f3714ef4 7109 const u64 hole_end = extent_map_end(hole_em);
ec29ed5b 7110
172ddd60 7111 em = alloc_extent_map();
ec29ed5b
CM
7112 if (!em) {
7113 err = -ENOMEM;
7114 goto out;
7115 }
f3714ef4
NB
7116 em->bdev = NULL;
7117
7118 ASSERT(hole_em);
ec29ed5b 7119 /*
f3714ef4
NB
7120 * When btrfs_get_extent can't find anything it returns one
7121 * huge hole
ec29ed5b 7122 *
f3714ef4
NB
7123 * Make sure what it found really fits our range, and adjust to
7124 * make sure it is based on the start from the caller
ec29ed5b 7125 */
f3714ef4
NB
7126 if (hole_end <= start || hole_em->start > end) {
7127 free_extent_map(hole_em);
7128 hole_em = NULL;
7129 } else {
7130 hole_start = max(hole_em->start, start);
7131 hole_len = hole_end - hole_start;
ec29ed5b 7132 }
f3714ef4
NB
7133
7134 if (hole_em && delalloc_start > hole_start) {
7135 /*
7136 * Our hole starts before our delalloc, so we have to
7137 * return just the parts of the hole that go until the
7138 * delalloc starts
ec29ed5b 7139 */
f3714ef4 7140 em->len = min(hole_len, delalloc_start - hole_start);
ec29ed5b
CM
7141 em->start = hole_start;
7142 em->orig_start = hole_start;
7143 /*
f3714ef4
NB
7144 * Don't adjust block start at all, it is fixed at
7145 * EXTENT_MAP_HOLE
ec29ed5b
CM
7146 */
7147 em->block_start = hole_em->block_start;
7148 em->block_len = hole_len;
f9e4fb53
LB
7149 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7150 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
ec29ed5b 7151 } else {
f3714ef4
NB
7152 /*
7153 * Hole is out of passed range or it starts after
7154 * delalloc range
7155 */
7156 em->start = delalloc_start;
7157 em->len = delalloc_len;
7158 em->orig_start = delalloc_start;
ec29ed5b 7159 em->block_start = EXTENT_MAP_DELALLOC;
f3714ef4 7160 em->block_len = delalloc_len;
ec29ed5b 7161 }
bf8d32b9 7162 } else {
ec29ed5b
CM
7163 return hole_em;
7164 }
7165out:
7166
7167 free_extent_map(hole_em);
7168 if (err) {
7169 free_extent_map(em);
7170 return ERR_PTR(err);
7171 }
7172 return em;
7173}
7174
5f9a8a51
FM
7175static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7176 const u64 start,
7177 const u64 len,
7178 const u64 orig_start,
7179 const u64 block_start,
7180 const u64 block_len,
7181 const u64 orig_block_len,
7182 const u64 ram_bytes,
7183 const int type)
7184{
7185 struct extent_map *em = NULL;
7186 int ret;
7187
5f9a8a51 7188 if (type != BTRFS_ORDERED_NOCOW) {
6f9994db
LB
7189 em = create_io_em(inode, start, len, orig_start,
7190 block_start, block_len, orig_block_len,
7191 ram_bytes,
7192 BTRFS_COMPRESS_NONE, /* compress_type */
7193 type);
5f9a8a51
FM
7194 if (IS_ERR(em))
7195 goto out;
7196 }
7197 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7198 len, block_len, type);
7199 if (ret) {
7200 if (em) {
7201 free_extent_map(em);
dcdbc059 7202 btrfs_drop_extent_cache(BTRFS_I(inode), start,
5f9a8a51
FM
7203 start + len - 1, 0);
7204 }
7205 em = ERR_PTR(ret);
7206 }
7207 out:
5f9a8a51
FM
7208
7209 return em;
7210}
7211
4b46fce2
JB
7212static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7213 u64 start, u64 len)
7214{
0b246afa 7215 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 7216 struct btrfs_root *root = BTRFS_I(inode)->root;
70c8a91c 7217 struct extent_map *em;
4b46fce2
JB
7218 struct btrfs_key ins;
7219 u64 alloc_hint;
7220 int ret;
4b46fce2 7221
4b46fce2 7222 alloc_hint = get_extent_allocation_hint(inode, start, len);
0b246afa 7223 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
da17066c 7224 0, alloc_hint, &ins, 1, 1);
00361589
JB
7225 if (ret)
7226 return ERR_PTR(ret);
4b46fce2 7227
5f9a8a51
FM
7228 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7229 ins.objectid, ins.offset, ins.offset,
6288d6ea 7230 ins.offset, BTRFS_ORDERED_REGULAR);
0b246afa 7231 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
5f9a8a51 7232 if (IS_ERR(em))
2ff7e61e
JM
7233 btrfs_free_reserved_extent(fs_info, ins.objectid,
7234 ins.offset, 1);
de0ee0ed 7235
4b46fce2
JB
7236 return em;
7237}
7238
46bfbb5c
CM
7239/*
7240 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7241 * block must be cow'd
7242 */
00361589 7243noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7ee9e440
JB
7244 u64 *orig_start, u64 *orig_block_len,
7245 u64 *ram_bytes)
46bfbb5c 7246{
2ff7e61e 7247 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46bfbb5c
CM
7248 struct btrfs_path *path;
7249 int ret;
7250 struct extent_buffer *leaf;
7251 struct btrfs_root *root = BTRFS_I(inode)->root;
7b2b7085 7252 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
46bfbb5c
CM
7253 struct btrfs_file_extent_item *fi;
7254 struct btrfs_key key;
7255 u64 disk_bytenr;
7256 u64 backref_offset;
7257 u64 extent_end;
7258 u64 num_bytes;
7259 int slot;
7260 int found_type;
7ee9e440 7261 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
e77751aa 7262
46bfbb5c
CM
7263 path = btrfs_alloc_path();
7264 if (!path)
7265 return -ENOMEM;
7266
f85b7379
DS
7267 ret = btrfs_lookup_file_extent(NULL, root, path,
7268 btrfs_ino(BTRFS_I(inode)), offset, 0);
46bfbb5c
CM
7269 if (ret < 0)
7270 goto out;
7271
7272 slot = path->slots[0];
7273 if (ret == 1) {
7274 if (slot == 0) {
7275 /* can't find the item, must cow */
7276 ret = 0;
7277 goto out;
7278 }
7279 slot--;
7280 }
7281 ret = 0;
7282 leaf = path->nodes[0];
7283 btrfs_item_key_to_cpu(leaf, &key, slot);
4a0cc7ca 7284 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
46bfbb5c
CM
7285 key.type != BTRFS_EXTENT_DATA_KEY) {
7286 /* not our file or wrong item type, must cow */
7287 goto out;
7288 }
7289
7290 if (key.offset > offset) {
7291 /* Wrong offset, must cow */
7292 goto out;
7293 }
7294
7295 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7296 found_type = btrfs_file_extent_type(leaf, fi);
7297 if (found_type != BTRFS_FILE_EXTENT_REG &&
7298 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7299 /* not a regular extent, must cow */
7300 goto out;
7301 }
7ee9e440
JB
7302
7303 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7304 goto out;
7305
e77751aa
MX
7306 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7307 if (extent_end <= offset)
7308 goto out;
7309
46bfbb5c 7310 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7ee9e440
JB
7311 if (disk_bytenr == 0)
7312 goto out;
7313
7314 if (btrfs_file_extent_compression(leaf, fi) ||
7315 btrfs_file_extent_encryption(leaf, fi) ||
7316 btrfs_file_extent_other_encoding(leaf, fi))
7317 goto out;
7318
78d4295b
EL
7319 /*
7320 * Do the same check as in btrfs_cross_ref_exist but without the
7321 * unnecessary search.
7322 */
7323 if (btrfs_file_extent_generation(leaf, fi) <=
7324 btrfs_root_last_snapshot(&root->root_item))
7325 goto out;
7326
46bfbb5c
CM
7327 backref_offset = btrfs_file_extent_offset(leaf, fi);
7328
7ee9e440
JB
7329 if (orig_start) {
7330 *orig_start = key.offset - backref_offset;
7331 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7332 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7333 }
eb384b55 7334
2ff7e61e 7335 if (btrfs_extent_readonly(fs_info, disk_bytenr))
46bfbb5c 7336 goto out;
7b2b7085
MX
7337
7338 num_bytes = min(offset + *len, extent_end) - offset;
7339 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7340 u64 range_end;
7341
da17066c
JM
7342 range_end = round_up(offset + num_bytes,
7343 root->fs_info->sectorsize) - 1;
7b2b7085
MX
7344 ret = test_range_bit(io_tree, offset, range_end,
7345 EXTENT_DELALLOC, 0, NULL);
7346 if (ret) {
7347 ret = -EAGAIN;
7348 goto out;
7349 }
7350 }
7351
1bda19eb 7352 btrfs_release_path(path);
46bfbb5c
CM
7353
7354 /*
7355 * look for other files referencing this extent, if we
7356 * find any we must cow
7357 */
00361589 7358
e4c3b2dc 7359 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
00361589 7360 key.offset - backref_offset, disk_bytenr);
00361589
JB
7361 if (ret) {
7362 ret = 0;
7363 goto out;
7364 }
46bfbb5c
CM
7365
7366 /*
7367 * adjust disk_bytenr and num_bytes to cover just the bytes
7368 * in this extent we are about to write. If there
7369 * are any csums in that range we have to cow in order
7370 * to keep the csums correct
7371 */
7372 disk_bytenr += backref_offset;
7373 disk_bytenr += offset - key.offset;
2ff7e61e
JM
7374 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7375 goto out;
46bfbb5c
CM
7376 /*
7377 * all of the above have passed, it is safe to overwrite this extent
7378 * without cow
7379 */
eb384b55 7380 *len = num_bytes;
46bfbb5c
CM
7381 ret = 1;
7382out:
7383 btrfs_free_path(path);
7384 return ret;
7385}
7386
eb838e73
JB
7387static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7388 struct extent_state **cached_state, int writing)
7389{
7390 struct btrfs_ordered_extent *ordered;
7391 int ret = 0;
7392
7393 while (1) {
7394 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
ff13db41 7395 cached_state);
eb838e73
JB
7396 /*
7397 * We're concerned with the entire range that we're going to be
01327610 7398 * doing DIO to, so we need to make sure there's no ordered
eb838e73
JB
7399 * extents in this range.
7400 */
a776c6fa 7401 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
eb838e73
JB
7402 lockend - lockstart + 1);
7403
7404 /*
7405 * We need to make sure there are no buffered pages in this
7406 * range either, we could have raced between the invalidate in
7407 * generic_file_direct_write and locking the extent. The
7408 * invalidate needs to happen so that reads after a write do not
7409 * get stale data.
7410 */
fc4adbff 7411 if (!ordered &&
051c98eb
DS
7412 (!writing || !filemap_range_has_page(inode->i_mapping,
7413 lockstart, lockend)))
eb838e73
JB
7414 break;
7415
7416 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
e43bbe5e 7417 cached_state);
eb838e73
JB
7418
7419 if (ordered) {
ade77029
FM
7420 /*
7421 * If we are doing a DIO read and the ordered extent we
7422 * found is for a buffered write, we can not wait for it
7423 * to complete and retry, because if we do so we can
7424 * deadlock with concurrent buffered writes on page
7425 * locks. This happens only if our DIO read covers more
7426 * than one extent map, if at this point has already
7427 * created an ordered extent for a previous extent map
7428 * and locked its range in the inode's io tree, and a
7429 * concurrent write against that previous extent map's
7430 * range and this range started (we unlock the ranges
7431 * in the io tree only when the bios complete and
7432 * buffered writes always lock pages before attempting
7433 * to lock range in the io tree).
7434 */
7435 if (writing ||
7436 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7437 btrfs_start_ordered_extent(inode, ordered, 1);
7438 else
7439 ret = -ENOTBLK;
eb838e73
JB
7440 btrfs_put_ordered_extent(ordered);
7441 } else {
eb838e73 7442 /*
b850ae14
FM
7443 * We could trigger writeback for this range (and wait
7444 * for it to complete) and then invalidate the pages for
7445 * this range (through invalidate_inode_pages2_range()),
7446 * but that can lead us to a deadlock with a concurrent
7447 * call to readpages() (a buffered read or a defrag call
7448 * triggered a readahead) on a page lock due to an
7449 * ordered dio extent we created before but did not have
7450 * yet a corresponding bio submitted (whence it can not
7451 * complete), which makes readpages() wait for that
7452 * ordered extent to complete while holding a lock on
7453 * that page.
eb838e73 7454 */
b850ae14 7455 ret = -ENOTBLK;
eb838e73
JB
7456 }
7457
ade77029
FM
7458 if (ret)
7459 break;
7460
eb838e73
JB
7461 cond_resched();
7462 }
7463
7464 return ret;
7465}
7466
6f9994db
LB
7467/* The callers of this must take lock_extent() */
7468static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7469 u64 orig_start, u64 block_start,
7470 u64 block_len, u64 orig_block_len,
7471 u64 ram_bytes, int compress_type,
7472 int type)
69ffb543
JB
7473{
7474 struct extent_map_tree *em_tree;
7475 struct extent_map *em;
7476 struct btrfs_root *root = BTRFS_I(inode)->root;
7477 int ret;
7478
6f9994db
LB
7479 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7480 type == BTRFS_ORDERED_COMPRESSED ||
7481 type == BTRFS_ORDERED_NOCOW ||
1af4a0aa 7482 type == BTRFS_ORDERED_REGULAR);
6f9994db 7483
69ffb543
JB
7484 em_tree = &BTRFS_I(inode)->extent_tree;
7485 em = alloc_extent_map();
7486 if (!em)
7487 return ERR_PTR(-ENOMEM);
7488
7489 em->start = start;
7490 em->orig_start = orig_start;
7491 em->len = len;
7492 em->block_len = block_len;
7493 em->block_start = block_start;
7494 em->bdev = root->fs_info->fs_devices->latest_bdev;
b4939680 7495 em->orig_block_len = orig_block_len;
cc95bef6 7496 em->ram_bytes = ram_bytes;
70c8a91c 7497 em->generation = -1;
69ffb543 7498 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1af4a0aa 7499 if (type == BTRFS_ORDERED_PREALLOC) {
b11e234d 7500 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1af4a0aa 7501 } else if (type == BTRFS_ORDERED_COMPRESSED) {
6f9994db
LB
7502 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7503 em->compress_type = compress_type;
7504 }
69ffb543
JB
7505
7506 do {
dcdbc059 7507 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
69ffb543
JB
7508 em->start + em->len - 1, 0);
7509 write_lock(&em_tree->lock);
09a2a8f9 7510 ret = add_extent_mapping(em_tree, em, 1);
69ffb543 7511 write_unlock(&em_tree->lock);
6f9994db
LB
7512 /*
7513 * The caller has taken lock_extent(), who could race with us
7514 * to add em?
7515 */
69ffb543
JB
7516 } while (ret == -EEXIST);
7517
7518 if (ret) {
7519 free_extent_map(em);
7520 return ERR_PTR(ret);
7521 }
7522
6f9994db 7523 /* em got 2 refs now, callers needs to do free_extent_map once. */
69ffb543
JB
7524 return em;
7525}
7526
1c8d0175
NB
7527
7528static int btrfs_get_blocks_direct_read(struct extent_map *em,
7529 struct buffer_head *bh_result,
7530 struct inode *inode,
7531 u64 start, u64 len)
7532{
7533 if (em->block_start == EXTENT_MAP_HOLE ||
7534 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7535 return -ENOENT;
7536
7537 len = min(len, em->len - (start - em->start));
7538
7539 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7540 inode->i_blkbits;
7541 bh_result->b_size = len;
7542 bh_result->b_bdev = em->bdev;
7543 set_buffer_mapped(bh_result);
7544
7545 return 0;
7546}
7547
c5794e51
NB
7548static int btrfs_get_blocks_direct_write(struct extent_map **map,
7549 struct buffer_head *bh_result,
7550 struct inode *inode,
7551 struct btrfs_dio_data *dio_data,
7552 u64 start, u64 len)
7553{
7554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7555 struct extent_map *em = *map;
7556 int ret = 0;
7557
7558 /*
7559 * We don't allocate a new extent in the following cases
7560 *
7561 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7562 * existing extent.
7563 * 2) The extent is marked as PREALLOC. We're good to go here and can
7564 * just use the extent.
7565 *
7566 */
7567 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7568 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7569 em->block_start != EXTENT_MAP_HOLE)) {
7570 int type;
7571 u64 block_start, orig_start, orig_block_len, ram_bytes;
7572
7573 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7574 type = BTRFS_ORDERED_PREALLOC;
7575 else
7576 type = BTRFS_ORDERED_NOCOW;
7577 len = min(len, em->len - (start - em->start));
7578 block_start = em->block_start + (start - em->start);
7579
7580 if (can_nocow_extent(inode, start, &len, &orig_start,
7581 &orig_block_len, &ram_bytes) == 1 &&
7582 btrfs_inc_nocow_writers(fs_info, block_start)) {
7583 struct extent_map *em2;
7584
7585 em2 = btrfs_create_dio_extent(inode, start, len,
7586 orig_start, block_start,
7587 len, orig_block_len,
7588 ram_bytes, type);
7589 btrfs_dec_nocow_writers(fs_info, block_start);
7590 if (type == BTRFS_ORDERED_PREALLOC) {
7591 free_extent_map(em);
7592 *map = em = em2;
7593 }
7594
7595 if (em2 && IS_ERR(em2)) {
7596 ret = PTR_ERR(em2);
7597 goto out;
7598 }
7599 /*
7600 * For inode marked NODATACOW or extent marked PREALLOC,
7601 * use the existing or preallocated extent, so does not
7602 * need to adjust btrfs_space_info's bytes_may_use.
7603 */
7604 btrfs_free_reserved_data_space_noquota(inode, start,
7605 len);
7606 goto skip_cow;
7607 }
7608 }
7609
7610 /* this will cow the extent */
7611 len = bh_result->b_size;
7612 free_extent_map(em);
7613 *map = em = btrfs_new_extent_direct(inode, start, len);
7614 if (IS_ERR(em)) {
7615 ret = PTR_ERR(em);
7616 goto out;
7617 }
7618
7619 len = min(len, em->len - (start - em->start));
7620
7621skip_cow:
7622 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7623 inode->i_blkbits;
7624 bh_result->b_size = len;
7625 bh_result->b_bdev = em->bdev;
7626 set_buffer_mapped(bh_result);
7627
7628 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7629 set_buffer_new(bh_result);
7630
7631 /*
7632 * Need to update the i_size under the extent lock so buffered
7633 * readers will get the updated i_size when we unlock.
7634 */
7635 if (!dio_data->overwrite && start + len > i_size_read(inode))
7636 i_size_write(inode, start + len);
7637
7638 WARN_ON(dio_data->reserve < len);
7639 dio_data->reserve -= len;
7640 dio_data->unsubmitted_oe_range_end = start + len;
7641 current->journal_info = dio_data;
7642out:
7643 return ret;
7644}
7645
4b46fce2
JB
7646static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7647 struct buffer_head *bh_result, int create)
7648{
0b246afa 7649 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 7650 struct extent_map *em;
eb838e73 7651 struct extent_state *cached_state = NULL;
50745b0a 7652 struct btrfs_dio_data *dio_data = NULL;
4b46fce2 7653 u64 start = iblock << inode->i_blkbits;
eb838e73 7654 u64 lockstart, lockend;
4b46fce2 7655 u64 len = bh_result->b_size;
eb838e73 7656 int unlock_bits = EXTENT_LOCKED;
0934856d 7657 int ret = 0;
eb838e73 7658
172a5049 7659 if (create)
3266789f 7660 unlock_bits |= EXTENT_DIRTY;
172a5049 7661 else
0b246afa 7662 len = min_t(u64, len, fs_info->sectorsize);
eb838e73 7663
c329861d
JB
7664 lockstart = start;
7665 lockend = start + len - 1;
7666
e1cbbfa5
JB
7667 if (current->journal_info) {
7668 /*
7669 * Need to pull our outstanding extents and set journal_info to NULL so
01327610 7670 * that anything that needs to check if there's a transaction doesn't get
e1cbbfa5
JB
7671 * confused.
7672 */
50745b0a 7673 dio_data = current->journal_info;
e1cbbfa5
JB
7674 current->journal_info = NULL;
7675 }
7676
eb838e73
JB
7677 /*
7678 * If this errors out it's because we couldn't invalidate pagecache for
7679 * this range and we need to fallback to buffered.
7680 */
9c9464cc
FM
7681 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7682 create)) {
7683 ret = -ENOTBLK;
7684 goto err;
7685 }
eb838e73 7686
fc4f21b1 7687 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
eb838e73
JB
7688 if (IS_ERR(em)) {
7689 ret = PTR_ERR(em);
7690 goto unlock_err;
7691 }
4b46fce2
JB
7692
7693 /*
7694 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7695 * io. INLINE is special, and we could probably kludge it in here, but
7696 * it's still buffered so for safety lets just fall back to the generic
7697 * buffered path.
7698 *
7699 * For COMPRESSED we _have_ to read the entire extent in so we can
7700 * decompress it, so there will be buffering required no matter what we
7701 * do, so go ahead and fallback to buffered.
7702 *
01327610 7703 * We return -ENOTBLK because that's what makes DIO go ahead and go back
4b46fce2
JB
7704 * to buffered IO. Don't blame me, this is the price we pay for using
7705 * the generic code.
7706 */
7707 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7708 em->block_start == EXTENT_MAP_INLINE) {
7709 free_extent_map(em);
eb838e73
JB
7710 ret = -ENOTBLK;
7711 goto unlock_err;
4b46fce2
JB
7712 }
7713
c5794e51
NB
7714 if (create) {
7715 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7716 dio_data, start, len);
7717 if (ret < 0)
7718 goto unlock_err;
7719
7720 /* clear and unlock the entire range */
7721 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7722 unlock_bits, 1, 0, &cached_state);
7723 } else {
1c8d0175
NB
7724 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7725 start, len);
7726 /* Can be negative only if we read from a hole */
7727 if (ret < 0) {
7728 ret = 0;
7729 free_extent_map(em);
7730 goto unlock_err;
7731 }
7732 /*
7733 * We need to unlock only the end area that we aren't using.
7734 * The rest is going to be unlocked by the endio routine.
7735 */
7736 lockstart = start + bh_result->b_size;
7737 if (lockstart < lockend) {
7738 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7739 lockend, unlock_bits, 1, 0,
7740 &cached_state);
7741 } else {
7742 free_extent_state(cached_state);
7743 }
4b46fce2
JB
7744 }
7745
4b46fce2
JB
7746 free_extent_map(em);
7747
7748 return 0;
eb838e73
JB
7749
7750unlock_err:
eb838e73 7751 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
ae0f1625 7752 unlock_bits, 1, 0, &cached_state);
9c9464cc 7753err:
50745b0a 7754 if (dio_data)
7755 current->journal_info = dio_data;
eb838e73 7756 return ret;
4b46fce2
JB
7757}
7758
58efbc9f
OS
7759static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7760 struct bio *bio,
7761 int mirror_num)
8b110e39 7762{
2ff7e61e 7763 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
58efbc9f 7764 blk_status_t ret;
8b110e39 7765
37226b21 7766 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8b110e39 7767
2ff7e61e 7768 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
8b110e39 7769 if (ret)
ea057f6d 7770 return ret;
8b110e39 7771
2ff7e61e 7772 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
ea057f6d 7773
8b110e39
MX
7774 return ret;
7775}
7776
7777static int btrfs_check_dio_repairable(struct inode *inode,
7778 struct bio *failed_bio,
7779 struct io_failure_record *failrec,
7780 int failed_mirror)
7781{
ab8d0fc4 7782 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8b110e39
MX
7783 int num_copies;
7784
ab8d0fc4 7785 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
8b110e39
MX
7786 if (num_copies == 1) {
7787 /*
7788 * we only have a single copy of the data, so don't bother with
7789 * all the retry and error correction code that follows. no
7790 * matter what the error is, it is very likely to persist.
7791 */
ab8d0fc4
JM
7792 btrfs_debug(fs_info,
7793 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7794 num_copies, failrec->this_mirror, failed_mirror);
8b110e39
MX
7795 return 0;
7796 }
7797
7798 failrec->failed_mirror = failed_mirror;
7799 failrec->this_mirror++;
7800 if (failrec->this_mirror == failed_mirror)
7801 failrec->this_mirror++;
7802
7803 if (failrec->this_mirror > num_copies) {
ab8d0fc4
JM
7804 btrfs_debug(fs_info,
7805 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7806 num_copies, failrec->this_mirror, failed_mirror);
8b110e39
MX
7807 return 0;
7808 }
7809
7810 return 1;
7811}
7812
58efbc9f
OS
7813static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7814 struct page *page, unsigned int pgoff,
7815 u64 start, u64 end, int failed_mirror,
7816 bio_end_io_t *repair_endio, void *repair_arg)
8b110e39
MX
7817{
7818 struct io_failure_record *failrec;
7870d082
JB
7819 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7820 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
8b110e39
MX
7821 struct bio *bio;
7822 int isector;
f1c77c55 7823 unsigned int read_mode = 0;
17347cec 7824 int segs;
8b110e39 7825 int ret;
58efbc9f 7826 blk_status_t status;
c16a8ac3 7827 struct bio_vec bvec;
8b110e39 7828
37226b21 7829 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
8b110e39
MX
7830
7831 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7832 if (ret)
58efbc9f 7833 return errno_to_blk_status(ret);
8b110e39
MX
7834
7835 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7836 failed_mirror);
7837 if (!ret) {
7870d082 7838 free_io_failure(failure_tree, io_tree, failrec);
58efbc9f 7839 return BLK_STS_IOERR;
8b110e39
MX
7840 }
7841
17347cec 7842 segs = bio_segments(failed_bio);
c16a8ac3 7843 bio_get_first_bvec(failed_bio, &bvec);
17347cec 7844 if (segs > 1 ||
c16a8ac3 7845 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
70fd7614 7846 read_mode |= REQ_FAILFAST_DEV;
8b110e39
MX
7847
7848 isector = start - btrfs_io_bio(failed_bio)->logical;
7849 isector >>= inode->i_sb->s_blocksize_bits;
7850 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
2dabb324 7851 pgoff, isector, repair_endio, repair_arg);
ebcc3263 7852 bio->bi_opf = REQ_OP_READ | read_mode;
8b110e39
MX
7853
7854 btrfs_debug(BTRFS_I(inode)->root->fs_info,
913e1535 7855 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
8b110e39
MX
7856 read_mode, failrec->this_mirror, failrec->in_validation);
7857
58efbc9f
OS
7858 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7859 if (status) {
7870d082 7860 free_io_failure(failure_tree, io_tree, failrec);
8b110e39
MX
7861 bio_put(bio);
7862 }
7863
58efbc9f 7864 return status;
8b110e39
MX
7865}
7866
7867struct btrfs_retry_complete {
7868 struct completion done;
7869 struct inode *inode;
7870 u64 start;
7871 int uptodate;
7872};
7873
4246a0b6 7874static void btrfs_retry_endio_nocsum(struct bio *bio)
8b110e39
MX
7875{
7876 struct btrfs_retry_complete *done = bio->bi_private;
7870d082 7877 struct inode *inode = done->inode;
8b110e39 7878 struct bio_vec *bvec;
7870d082 7879 struct extent_io_tree *io_tree, *failure_tree;
8b110e39 7880 int i;
6dc4f100 7881 struct bvec_iter_all iter_all;
8b110e39 7882
4e4cbee9 7883 if (bio->bi_status)
8b110e39
MX
7884 goto end;
7885
2dabb324 7886 ASSERT(bio->bi_vcnt == 1);
7870d082
JB
7887 io_tree = &BTRFS_I(inode)->io_tree;
7888 failure_tree = &BTRFS_I(inode)->io_failure_tree;
263663cd 7889 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
2dabb324 7890
8b110e39 7891 done->uptodate = 1;
c09abff8 7892 ASSERT(!bio_flagged(bio, BIO_CLONED));
6dc4f100 7893 bio_for_each_segment_all(bvec, bio, i, iter_all)
7870d082
JB
7894 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7895 io_tree, done->start, bvec->bv_page,
7896 btrfs_ino(BTRFS_I(inode)), 0);
8b110e39
MX
7897end:
7898 complete(&done->done);
7899 bio_put(bio);
7900}
7901
58efbc9f
OS
7902static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7903 struct btrfs_io_bio *io_bio)
4b46fce2 7904{
2dabb324 7905 struct btrfs_fs_info *fs_info;
17347cec
LB
7906 struct bio_vec bvec;
7907 struct bvec_iter iter;
8b110e39 7908 struct btrfs_retry_complete done;
4b46fce2 7909 u64 start;
2dabb324
CR
7910 unsigned int pgoff;
7911 u32 sectorsize;
7912 int nr_sectors;
58efbc9f
OS
7913 blk_status_t ret;
7914 blk_status_t err = BLK_STS_OK;
4b46fce2 7915
2dabb324 7916 fs_info = BTRFS_I(inode)->root->fs_info;
da17066c 7917 sectorsize = fs_info->sectorsize;
2dabb324 7918
8b110e39
MX
7919 start = io_bio->logical;
7920 done.inode = inode;
17347cec 7921 io_bio->bio.bi_iter = io_bio->iter;
8b110e39 7922
17347cec
LB
7923 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7924 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7925 pgoff = bvec.bv_offset;
2dabb324
CR
7926
7927next_block_or_try_again:
8b110e39
MX
7928 done.uptodate = 0;
7929 done.start = start;
7930 init_completion(&done.done);
7931
17347cec 7932 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
2dabb324
CR
7933 pgoff, start, start + sectorsize - 1,
7934 io_bio->mirror_num,
7935 btrfs_retry_endio_nocsum, &done);
629ebf4f
LB
7936 if (ret) {
7937 err = ret;
7938 goto next;
7939 }
8b110e39 7940
9c17f6cd 7941 wait_for_completion_io(&done.done);
8b110e39
MX
7942
7943 if (!done.uptodate) {
7944 /* We might have another mirror, so try again */
2dabb324 7945 goto next_block_or_try_again;
8b110e39
MX
7946 }
7947
629ebf4f 7948next:
2dabb324
CR
7949 start += sectorsize;
7950
97bf5a55
LB
7951 nr_sectors--;
7952 if (nr_sectors) {
2dabb324 7953 pgoff += sectorsize;
97bf5a55 7954 ASSERT(pgoff < PAGE_SIZE);
2dabb324
CR
7955 goto next_block_or_try_again;
7956 }
8b110e39
MX
7957 }
7958
629ebf4f 7959 return err;
8b110e39
MX
7960}
7961
4246a0b6 7962static void btrfs_retry_endio(struct bio *bio)
8b110e39
MX
7963{
7964 struct btrfs_retry_complete *done = bio->bi_private;
7965 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7870d082
JB
7966 struct extent_io_tree *io_tree, *failure_tree;
7967 struct inode *inode = done->inode;
8b110e39
MX
7968 struct bio_vec *bvec;
7969 int uptodate;
7970 int ret;
7971 int i;
6dc4f100 7972 struct bvec_iter_all iter_all;
8b110e39 7973
4e4cbee9 7974 if (bio->bi_status)
8b110e39
MX
7975 goto end;
7976
7977 uptodate = 1;
2dabb324 7978
2dabb324 7979 ASSERT(bio->bi_vcnt == 1);
263663cd 7980 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
2dabb324 7981
7870d082
JB
7982 io_tree = &BTRFS_I(inode)->io_tree;
7983 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7984
c09abff8 7985 ASSERT(!bio_flagged(bio, BIO_CLONED));
6dc4f100 7986 bio_for_each_segment_all(bvec, bio, i, iter_all) {
7870d082
JB
7987 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7988 bvec->bv_offset, done->start,
7989 bvec->bv_len);
8b110e39 7990 if (!ret)
7870d082
JB
7991 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7992 failure_tree, io_tree, done->start,
7993 bvec->bv_page,
7994 btrfs_ino(BTRFS_I(inode)),
7995 bvec->bv_offset);
8b110e39
MX
7996 else
7997 uptodate = 0;
7998 }
7999
8000 done->uptodate = uptodate;
8001end:
8002 complete(&done->done);
8003 bio_put(bio);
8004}
8005
4e4cbee9
CH
8006static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8007 struct btrfs_io_bio *io_bio, blk_status_t err)
8b110e39 8008{
2dabb324 8009 struct btrfs_fs_info *fs_info;
17347cec
LB
8010 struct bio_vec bvec;
8011 struct bvec_iter iter;
8b110e39
MX
8012 struct btrfs_retry_complete done;
8013 u64 start;
8014 u64 offset = 0;
2dabb324
CR
8015 u32 sectorsize;
8016 int nr_sectors;
8017 unsigned int pgoff;
8018 int csum_pos;
ef7cdac1 8019 bool uptodate = (err == 0);
8b110e39 8020 int ret;
58efbc9f 8021 blk_status_t status;
dc380aea 8022
2dabb324 8023 fs_info = BTRFS_I(inode)->root->fs_info;
da17066c 8024 sectorsize = fs_info->sectorsize;
2dabb324 8025
58efbc9f 8026 err = BLK_STS_OK;
c1dc0896 8027 start = io_bio->logical;
8b110e39 8028 done.inode = inode;
17347cec 8029 io_bio->bio.bi_iter = io_bio->iter;
8b110e39 8030
17347cec
LB
8031 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8032 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
2dabb324 8033
17347cec 8034 pgoff = bvec.bv_offset;
2dabb324 8035next_block:
ef7cdac1
LB
8036 if (uptodate) {
8037 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8038 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8039 bvec.bv_page, pgoff, start, sectorsize);
8040 if (likely(!ret))
8041 goto next;
8042 }
8b110e39
MX
8043try_again:
8044 done.uptodate = 0;
8045 done.start = start;
8046 init_completion(&done.done);
8047
58efbc9f
OS
8048 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8049 pgoff, start, start + sectorsize - 1,
8050 io_bio->mirror_num, btrfs_retry_endio,
8051 &done);
8052 if (status) {
8053 err = status;
8b110e39
MX
8054 goto next;
8055 }
8056
9c17f6cd 8057 wait_for_completion_io(&done.done);
8b110e39
MX
8058
8059 if (!done.uptodate) {
8060 /* We might have another mirror, so try again */
8061 goto try_again;
8062 }
8063next:
2dabb324
CR
8064 offset += sectorsize;
8065 start += sectorsize;
8066
8067 ASSERT(nr_sectors);
8068
97bf5a55
LB
8069 nr_sectors--;
8070 if (nr_sectors) {
2dabb324 8071 pgoff += sectorsize;
97bf5a55 8072 ASSERT(pgoff < PAGE_SIZE);
2dabb324
CR
8073 goto next_block;
8074 }
2c30c71b 8075 }
c1dc0896
MX
8076
8077 return err;
8078}
8079
4e4cbee9
CH
8080static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8081 struct btrfs_io_bio *io_bio, blk_status_t err)
8b110e39
MX
8082{
8083 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8084
8085 if (skip_csum) {
8086 if (unlikely(err))
8087 return __btrfs_correct_data_nocsum(inode, io_bio);
8088 else
58efbc9f 8089 return BLK_STS_OK;
8b110e39
MX
8090 } else {
8091 return __btrfs_subio_endio_read(inode, io_bio, err);
8092 }
8093}
8094
4246a0b6 8095static void btrfs_endio_direct_read(struct bio *bio)
c1dc0896
MX
8096{
8097 struct btrfs_dio_private *dip = bio->bi_private;
8098 struct inode *inode = dip->inode;
8099 struct bio *dio_bio;
8100 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
4e4cbee9 8101 blk_status_t err = bio->bi_status;
c1dc0896 8102
99c4e3b9 8103 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8b110e39 8104 err = btrfs_subio_endio_read(inode, io_bio, err);
c1dc0896 8105
4b46fce2 8106 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
d0082371 8107 dip->logical_offset + dip->bytes - 1);
9be3395b 8108 dio_bio = dip->dio_bio;
4b46fce2 8109
4b46fce2 8110 kfree(dip);
c0da7aa1 8111
99c4e3b9 8112 dio_bio->bi_status = err;
4055351c 8113 dio_end_io(dio_bio);
b3a0dd50 8114 btrfs_io_bio_free_csum(io_bio);
9be3395b 8115 bio_put(bio);
4b46fce2
JB
8116}
8117
52427260
QW
8118static void __endio_write_update_ordered(struct inode *inode,
8119 const u64 offset, const u64 bytes,
8120 const bool uptodate)
4b46fce2 8121{
0b246afa 8122 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 8123 struct btrfs_ordered_extent *ordered = NULL;
52427260
QW
8124 struct btrfs_workqueue *wq;
8125 btrfs_work_func_t func;
14543774
FM
8126 u64 ordered_offset = offset;
8127 u64 ordered_bytes = bytes;
67c003f9 8128 u64 last_offset;
4b46fce2 8129
52427260
QW
8130 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8131 wq = fs_info->endio_freespace_worker;
8132 func = btrfs_freespace_write_helper;
8133 } else {
8134 wq = fs_info->endio_write_workers;
8135 func = btrfs_endio_write_helper;
8136 }
8137
b25f0d00
NB
8138 while (ordered_offset < offset + bytes) {
8139 last_offset = ordered_offset;
8140 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8141 &ordered_offset,
8142 ordered_bytes,
8143 uptodate)) {
8144 btrfs_init_work(&ordered->work, func,
8145 finish_ordered_fn,
8146 NULL, NULL);
8147 btrfs_queue_work(wq, &ordered->work);
8148 }
8149 /*
8150 * If btrfs_dec_test_ordered_pending does not find any ordered
8151 * extent in the range, we can exit.
8152 */
8153 if (ordered_offset == last_offset)
8154 return;
8155 /*
8156 * Our bio might span multiple ordered extents. In this case
52042d8e 8157 * we keep going until we have accounted the whole dio.
b25f0d00
NB
8158 */
8159 if (ordered_offset < offset + bytes) {
8160 ordered_bytes = offset + bytes - ordered_offset;
8161 ordered = NULL;
8162 }
163cf09c 8163 }
14543774
FM
8164}
8165
8166static void btrfs_endio_direct_write(struct bio *bio)
8167{
8168 struct btrfs_dio_private *dip = bio->bi_private;
8169 struct bio *dio_bio = dip->dio_bio;
8170
52427260 8171 __endio_write_update_ordered(dip->inode, dip->logical_offset,
4e4cbee9 8172 dip->bytes, !bio->bi_status);
4b46fce2 8173
4b46fce2 8174 kfree(dip);
c0da7aa1 8175
4e4cbee9 8176 dio_bio->bi_status = bio->bi_status;
4055351c 8177 dio_end_io(dio_bio);
9be3395b 8178 bio_put(bio);
4b46fce2
JB
8179}
8180
d0ee3934 8181static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
d0779291 8182 struct bio *bio, u64 offset)
eaf25d93 8183{
c6100a4b 8184 struct inode *inode = private_data;
4e4cbee9 8185 blk_status_t ret;
2ff7e61e 8186 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
79787eaa 8187 BUG_ON(ret); /* -ENOMEM */
eaf25d93
CM
8188 return 0;
8189}
8190
4246a0b6 8191static void btrfs_end_dio_bio(struct bio *bio)
e65e1535
MX
8192{
8193 struct btrfs_dio_private *dip = bio->bi_private;
4e4cbee9 8194 blk_status_t err = bio->bi_status;
e65e1535 8195
8b110e39
MX
8196 if (err)
8197 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
6296b960 8198 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
f85b7379
DS
8199 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8200 bio->bi_opf,
8b110e39
MX
8201 (unsigned long long)bio->bi_iter.bi_sector,
8202 bio->bi_iter.bi_size, err);
8203
8204 if (dip->subio_endio)
8205 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
c1dc0896
MX
8206
8207 if (err) {
e65e1535 8208 /*
de224b7c
NB
8209 * We want to perceive the errors flag being set before
8210 * decrementing the reference count. We don't need a barrier
8211 * since atomic operations with a return value are fully
8212 * ordered as per atomic_t.txt
e65e1535 8213 */
de224b7c 8214 dip->errors = 1;
e65e1535
MX
8215 }
8216
8217 /* if there are more bios still pending for this dio, just exit */
8218 if (!atomic_dec_and_test(&dip->pending_bios))
8219 goto out;
8220
9be3395b 8221 if (dip->errors) {
e65e1535 8222 bio_io_error(dip->orig_bio);
9be3395b 8223 } else {
2dbe0c77 8224 dip->dio_bio->bi_status = BLK_STS_OK;
4246a0b6 8225 bio_endio(dip->orig_bio);
e65e1535
MX
8226 }
8227out:
8228 bio_put(bio);
8229}
8230
4e4cbee9 8231static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
c1dc0896
MX
8232 struct btrfs_dio_private *dip,
8233 struct bio *bio,
8234 u64 file_offset)
8235{
8236 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8237 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
4e4cbee9 8238 blk_status_t ret;
c1dc0896
MX
8239
8240 /*
8241 * We load all the csum data we need when we submit
8242 * the first bio to reduce the csum tree search and
8243 * contention.
8244 */
8245 if (dip->logical_offset == file_offset) {
2ff7e61e 8246 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
c1dc0896
MX
8247 file_offset);
8248 if (ret)
8249 return ret;
8250 }
8251
8252 if (bio == dip->orig_bio)
8253 return 0;
8254
8255 file_offset -= dip->logical_offset;
8256 file_offset >>= inode->i_sb->s_blocksize_bits;
8257 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8258
8259 return 0;
8260}
8261
d0ee3934
DS
8262static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8263 struct inode *inode, u64 file_offset, int async_submit)
e65e1535 8264{
0b246afa 8265 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
facc8a22 8266 struct btrfs_dio_private *dip = bio->bi_private;
37226b21 8267 bool write = bio_op(bio) == REQ_OP_WRITE;
4e4cbee9 8268 blk_status_t ret;
e65e1535 8269
4c274bc6 8270 /* Check btrfs_submit_bio_hook() for rules about async submit. */
b812ce28
JB
8271 if (async_submit)
8272 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8273
5fd02043 8274 if (!write) {
0b246afa 8275 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
5fd02043
JB
8276 if (ret)
8277 goto err;
8278 }
e65e1535 8279
e6961cac 8280 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1ae39938
JB
8281 goto map;
8282
8283 if (write && async_submit) {
c6100a4b
JB
8284 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8285 file_offset, inode,
e288c080 8286 btrfs_submit_bio_start_direct_io);
e65e1535 8287 goto err;
1ae39938
JB
8288 } else if (write) {
8289 /*
8290 * If we aren't doing async submit, calculate the csum of the
8291 * bio now.
8292 */
2ff7e61e 8293 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
1ae39938
JB
8294 if (ret)
8295 goto err;
23ea8e5a 8296 } else {
2ff7e61e 8297 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
c1dc0896 8298 file_offset);
c2db1073
TI
8299 if (ret)
8300 goto err;
8301 }
1ae39938 8302map:
9b4a9b28 8303 ret = btrfs_map_bio(fs_info, bio, 0, 0);
e65e1535 8304err:
e65e1535
MX
8305 return ret;
8306}
8307
e6961cac 8308static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
e65e1535
MX
8309{
8310 struct inode *inode = dip->inode;
0b246afa 8311 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e65e1535
MX
8312 struct bio *bio;
8313 struct bio *orig_bio = dip->orig_bio;
4f024f37 8314 u64 start_sector = orig_bio->bi_iter.bi_sector;
e65e1535 8315 u64 file_offset = dip->logical_offset;
e65e1535 8316 u64 map_length;
1ae39938 8317 int async_submit = 0;
725130ba
LB
8318 u64 submit_len;
8319 int clone_offset = 0;
8320 int clone_len;
5f4dc8fc 8321 int ret;
58efbc9f 8322 blk_status_t status;
e65e1535 8323
4f024f37 8324 map_length = orig_bio->bi_iter.bi_size;
725130ba 8325 submit_len = map_length;
0b246afa
JM
8326 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8327 &map_length, NULL, 0);
7a5c3c9b 8328 if (ret)
e65e1535 8329 return -EIO;
facc8a22 8330
725130ba 8331 if (map_length >= submit_len) {
02f57c7a 8332 bio = orig_bio;
c1dc0896 8333 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
02f57c7a
JB
8334 goto submit;
8335 }
8336
53b381b3 8337 /* async crcs make it difficult to collect full stripe writes. */
1b86826d 8338 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
53b381b3
DW
8339 async_submit = 0;
8340 else
8341 async_submit = 1;
8342
725130ba
LB
8343 /* bio split */
8344 ASSERT(map_length <= INT_MAX);
02f57c7a 8345 atomic_inc(&dip->pending_bios);
3c91ee69 8346 do {
725130ba 8347 clone_len = min_t(int, submit_len, map_length);
02f57c7a 8348
725130ba
LB
8349 /*
8350 * This will never fail as it's passing GPF_NOFS and
8351 * the allocation is backed by btrfs_bioset.
8352 */
e477094f 8353 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
725130ba
LB
8354 clone_len);
8355 bio->bi_private = dip;
8356 bio->bi_end_io = btrfs_end_dio_bio;
8357 btrfs_io_bio(bio)->logical = file_offset;
8358
8359 ASSERT(submit_len >= clone_len);
8360 submit_len -= clone_len;
8361 if (submit_len == 0)
8362 break;
e65e1535 8363
725130ba
LB
8364 /*
8365 * Increase the count before we submit the bio so we know
8366 * the end IO handler won't happen before we increase the
8367 * count. Otherwise, the dip might get freed before we're
8368 * done setting it up.
8369 */
8370 atomic_inc(&dip->pending_bios);
e65e1535 8371
d0ee3934 8372 status = btrfs_submit_dio_bio(bio, inode, file_offset,
58efbc9f
OS
8373 async_submit);
8374 if (status) {
725130ba
LB
8375 bio_put(bio);
8376 atomic_dec(&dip->pending_bios);
8377 goto out_err;
8378 }
e65e1535 8379
725130ba
LB
8380 clone_offset += clone_len;
8381 start_sector += clone_len >> 9;
8382 file_offset += clone_len;
5f4dc8fc 8383
725130ba
LB
8384 map_length = submit_len;
8385 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8386 start_sector << 9, &map_length, NULL, 0);
8387 if (ret)
8388 goto out_err;
3c91ee69 8389 } while (submit_len > 0);
e65e1535 8390
02f57c7a 8391submit:
d0ee3934 8392 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
58efbc9f 8393 if (!status)
e65e1535
MX
8394 return 0;
8395
8396 bio_put(bio);
8397out_err:
8398 dip->errors = 1;
8399 /*
de224b7c
NB
8400 * Before atomic variable goto zero, we must make sure dip->errors is
8401 * perceived to be set. This ordering is ensured by the fact that an
8402 * atomic operations with a return value are fully ordered as per
8403 * atomic_t.txt
e65e1535 8404 */
e65e1535
MX
8405 if (atomic_dec_and_test(&dip->pending_bios))
8406 bio_io_error(dip->orig_bio);
8407
8408 /* bio_end_io() will handle error, so we needn't return it */
8409 return 0;
8410}
8411
8a4c1e42
MC
8412static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8413 loff_t file_offset)
4b46fce2 8414{
61de718f 8415 struct btrfs_dio_private *dip = NULL;
3892ac90
LB
8416 struct bio *bio = NULL;
8417 struct btrfs_io_bio *io_bio;
8a4c1e42 8418 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
4b46fce2
JB
8419 int ret = 0;
8420
8b6c1d56 8421 bio = btrfs_bio_clone(dio_bio);
9be3395b 8422
c1dc0896 8423 dip = kzalloc(sizeof(*dip), GFP_NOFS);
4b46fce2
JB
8424 if (!dip) {
8425 ret = -ENOMEM;
61de718f 8426 goto free_ordered;
4b46fce2 8427 }
4b46fce2 8428
9be3395b 8429 dip->private = dio_bio->bi_private;
4b46fce2
JB
8430 dip->inode = inode;
8431 dip->logical_offset = file_offset;
4f024f37
KO
8432 dip->bytes = dio_bio->bi_iter.bi_size;
8433 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
3892ac90
LB
8434 bio->bi_private = dip;
8435 dip->orig_bio = bio;
9be3395b 8436 dip->dio_bio = dio_bio;
e65e1535 8437 atomic_set(&dip->pending_bios, 0);
3892ac90
LB
8438 io_bio = btrfs_io_bio(bio);
8439 io_bio->logical = file_offset;
4b46fce2 8440
c1dc0896 8441 if (write) {
3892ac90 8442 bio->bi_end_io = btrfs_endio_direct_write;
c1dc0896 8443 } else {
3892ac90 8444 bio->bi_end_io = btrfs_endio_direct_read;
c1dc0896
MX
8445 dip->subio_endio = btrfs_subio_endio_read;
8446 }
4b46fce2 8447
f28a4928
FM
8448 /*
8449 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8450 * even if we fail to submit a bio, because in such case we do the
8451 * corresponding error handling below and it must not be done a second
8452 * time by btrfs_direct_IO().
8453 */
8454 if (write) {
8455 struct btrfs_dio_data *dio_data = current->journal_info;
8456
8457 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8458 dip->bytes;
8459 dio_data->unsubmitted_oe_range_start =
8460 dio_data->unsubmitted_oe_range_end;
8461 }
8462
e6961cac 8463 ret = btrfs_submit_direct_hook(dip);
e65e1535 8464 if (!ret)
eaf25d93 8465 return;
9be3395b 8466
b3a0dd50 8467 btrfs_io_bio_free_csum(io_bio);
9be3395b 8468
4b46fce2
JB
8469free_ordered:
8470 /*
61de718f
FM
8471 * If we arrived here it means either we failed to submit the dip
8472 * or we either failed to clone the dio_bio or failed to allocate the
8473 * dip. If we cloned the dio_bio and allocated the dip, we can just
8474 * call bio_endio against our io_bio so that we get proper resource
8475 * cleanup if we fail to submit the dip, otherwise, we must do the
8476 * same as btrfs_endio_direct_[write|read] because we can't call these
8477 * callbacks - they require an allocated dip and a clone of dio_bio.
4b46fce2 8478 */
3892ac90 8479 if (bio && dip) {
054ec2f6 8480 bio_io_error(bio);
61de718f 8481 /*
3892ac90 8482 * The end io callbacks free our dip, do the final put on bio
61de718f
FM
8483 * and all the cleanup and final put for dio_bio (through
8484 * dio_end_io()).
8485 */
8486 dip = NULL;
3892ac90 8487 bio = NULL;
61de718f 8488 } else {
14543774 8489 if (write)
52427260 8490 __endio_write_update_ordered(inode,
14543774
FM
8491 file_offset,
8492 dio_bio->bi_iter.bi_size,
52427260 8493 false);
14543774 8494 else
61de718f
FM
8495 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8496 file_offset + dio_bio->bi_iter.bi_size - 1);
14543774 8497
4e4cbee9 8498 dio_bio->bi_status = BLK_STS_IOERR;
61de718f
FM
8499 /*
8500 * Releases and cleans up our dio_bio, no need to bio_put()
8501 * nor bio_endio()/bio_io_error() against dio_bio.
8502 */
4055351c 8503 dio_end_io(dio_bio);
4b46fce2 8504 }
3892ac90
LB
8505 if (bio)
8506 bio_put(bio);
61de718f 8507 kfree(dip);
4b46fce2
JB
8508}
8509
2ff7e61e 8510static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
2ff7e61e 8511 const struct iov_iter *iter, loff_t offset)
5a5f79b5
CM
8512{
8513 int seg;
a1b75f7d 8514 int i;
0b246afa 8515 unsigned int blocksize_mask = fs_info->sectorsize - 1;
5a5f79b5 8516 ssize_t retval = -EINVAL;
5a5f79b5
CM
8517
8518 if (offset & blocksize_mask)
8519 goto out;
8520
28060d5d
AV
8521 if (iov_iter_alignment(iter) & blocksize_mask)
8522 goto out;
a1b75f7d 8523
28060d5d 8524 /* If this is a write we don't need to check anymore */
cd27e455 8525 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
28060d5d
AV
8526 return 0;
8527 /*
8528 * Check to make sure we don't have duplicate iov_base's in this
8529 * iovec, if so return EINVAL, otherwise we'll get csum errors
8530 * when reading back.
8531 */
8532 for (seg = 0; seg < iter->nr_segs; seg++) {
8533 for (i = seg + 1; i < iter->nr_segs; i++) {
8534 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
a1b75f7d
JB
8535 goto out;
8536 }
5a5f79b5
CM
8537 }
8538 retval = 0;
8539out:
8540 return retval;
8541}
eb838e73 8542
c8b8e32d 8543static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
16432985 8544{
4b46fce2
JB
8545 struct file *file = iocb->ki_filp;
8546 struct inode *inode = file->f_mapping->host;
0b246afa 8547 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50745b0a 8548 struct btrfs_dio_data dio_data = { 0 };
364ecf36 8549 struct extent_changeset *data_reserved = NULL;
c8b8e32d 8550 loff_t offset = iocb->ki_pos;
0934856d 8551 size_t count = 0;
2e60a51e 8552 int flags = 0;
38851cc1
MX
8553 bool wakeup = true;
8554 bool relock = false;
0934856d 8555 ssize_t ret;
4b46fce2 8556
8c70c9f8 8557 if (check_direct_IO(fs_info, iter, offset))
5a5f79b5 8558 return 0;
3f7c579c 8559
fe0f07d0 8560 inode_dio_begin(inode);
38851cc1 8561
0e267c44 8562 /*
41bd9ca4
MX
8563 * The generic stuff only does filemap_write_and_wait_range, which
8564 * isn't enough if we've written compressed pages to this area, so
8565 * we need to flush the dirty pages again to make absolutely sure
8566 * that any outstanding dirty pages are on disk.
0e267c44 8567 */
a6cbcd4a 8568 count = iov_iter_count(iter);
41bd9ca4
MX
8569 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8570 &BTRFS_I(inode)->runtime_flags))
9a025a08
WS
8571 filemap_fdatawrite_range(inode->i_mapping, offset,
8572 offset + count - 1);
0e267c44 8573
6f673763 8574 if (iov_iter_rw(iter) == WRITE) {
38851cc1
MX
8575 /*
8576 * If the write DIO is beyond the EOF, we need update
8577 * the isize, but it is protected by i_mutex. So we can
8578 * not unlock the i_mutex at this case.
8579 */
8580 if (offset + count <= inode->i_size) {
4aaedfb0 8581 dio_data.overwrite = 1;
5955102c 8582 inode_unlock(inode);
38851cc1 8583 relock = true;
edf064e7
GR
8584 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8585 ret = -EAGAIN;
8586 goto out;
38851cc1 8587 }
364ecf36
QW
8588 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8589 offset, count);
0934856d 8590 if (ret)
38851cc1 8591 goto out;
e1cbbfa5
JB
8592
8593 /*
8594 * We need to know how many extents we reserved so that we can
8595 * do the accounting properly if we go over the number we
8596 * originally calculated. Abuse current->journal_info for this.
8597 */
da17066c 8598 dio_data.reserve = round_up(count,
0b246afa 8599 fs_info->sectorsize);
f28a4928
FM
8600 dio_data.unsubmitted_oe_range_start = (u64)offset;
8601 dio_data.unsubmitted_oe_range_end = (u64)offset;
50745b0a 8602 current->journal_info = &dio_data;
97dcdea0 8603 down_read(&BTRFS_I(inode)->dio_sem);
ee39b432
DS
8604 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8605 &BTRFS_I(inode)->runtime_flags)) {
fe0f07d0 8606 inode_dio_end(inode);
38851cc1
MX
8607 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8608 wakeup = false;
0934856d
MX
8609 }
8610
17f8c842 8611 ret = __blockdev_direct_IO(iocb, inode,
0b246afa 8612 fs_info->fs_devices->latest_bdev,
c8b8e32d 8613 iter, btrfs_get_blocks_direct, NULL,
17f8c842 8614 btrfs_submit_direct, flags);
6f673763 8615 if (iov_iter_rw(iter) == WRITE) {
97dcdea0 8616 up_read(&BTRFS_I(inode)->dio_sem);
e1cbbfa5 8617 current->journal_info = NULL;
ddba1bfc 8618 if (ret < 0 && ret != -EIOCBQUEUED) {
50745b0a 8619 if (dio_data.reserve)
bc42bda2 8620 btrfs_delalloc_release_space(inode, data_reserved,
43b18595 8621 offset, dio_data.reserve, true);
f28a4928
FM
8622 /*
8623 * On error we might have left some ordered extents
8624 * without submitting corresponding bios for them, so
8625 * cleanup them up to avoid other tasks getting them
8626 * and waiting for them to complete forever.
8627 */
8628 if (dio_data.unsubmitted_oe_range_start <
8629 dio_data.unsubmitted_oe_range_end)
52427260 8630 __endio_write_update_ordered(inode,
f28a4928
FM
8631 dio_data.unsubmitted_oe_range_start,
8632 dio_data.unsubmitted_oe_range_end -
8633 dio_data.unsubmitted_oe_range_start,
52427260 8634 false);
ddba1bfc 8635 } else if (ret >= 0 && (size_t)ret < count)
bc42bda2 8636 btrfs_delalloc_release_space(inode, data_reserved,
43b18595
QW
8637 offset, count - (size_t)ret, true);
8638 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
0934856d 8639 }
38851cc1 8640out:
2e60a51e 8641 if (wakeup)
fe0f07d0 8642 inode_dio_end(inode);
38851cc1 8643 if (relock)
5955102c 8644 inode_lock(inode);
0934856d 8645
364ecf36 8646 extent_changeset_free(data_reserved);
0934856d 8647 return ret;
16432985
CM
8648}
8649
05dadc09
TI
8650#define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8651
1506fcc8
YS
8652static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8653 __u64 start, __u64 len)
8654{
05dadc09
TI
8655 int ret;
8656
8657 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8658 if (ret)
8659 return ret;
8660
2135fb9b 8661 return extent_fiemap(inode, fieinfo, start, len);
1506fcc8
YS
8662}
8663
a52d9a80 8664int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 8665{
d1310b2e
CM
8666 struct extent_io_tree *tree;
8667 tree = &BTRFS_I(page->mapping->host)->io_tree;
8ddc7d9c 8668 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
9ebefb18 8669}
1832a6d5 8670
a52d9a80 8671static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 8672{
be7bd730
JB
8673 struct inode *inode = page->mapping->host;
8674 int ret;
b888db2b
CM
8675
8676 if (current->flags & PF_MEMALLOC) {
8677 redirty_page_for_writepage(wbc, page);
8678 unlock_page(page);
8679 return 0;
8680 }
be7bd730
JB
8681
8682 /*
8683 * If we are under memory pressure we will call this directly from the
8684 * VM, we need to make sure we have the inode referenced for the ordered
8685 * extent. If not just return like we didn't do anything.
8686 */
8687 if (!igrab(inode)) {
8688 redirty_page_for_writepage(wbc, page);
8689 return AOP_WRITEPAGE_ACTIVATE;
8690 }
0a9b0e53 8691 ret = extent_write_full_page(page, wbc);
be7bd730
JB
8692 btrfs_add_delayed_iput(inode);
8693 return ret;
9ebefb18
CM
8694}
8695
48a3b636
ES
8696static int btrfs_writepages(struct address_space *mapping,
8697 struct writeback_control *wbc)
b293f02e 8698{
8ae225a8 8699 return extent_writepages(mapping, wbc);
b293f02e
CM
8700}
8701
3ab2fb5a
CM
8702static int
8703btrfs_readpages(struct file *file, struct address_space *mapping,
8704 struct list_head *pages, unsigned nr_pages)
8705{
2a3ff0ad 8706 return extent_readpages(mapping, pages, nr_pages);
3ab2fb5a 8707}
2a3ff0ad 8708
e6dcd2dc 8709static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 8710{
477a30ba 8711 int ret = try_release_extent_mapping(page, gfp_flags);
a52d9a80
CM
8712 if (ret == 1) {
8713 ClearPagePrivate(page);
8714 set_page_private(page, 0);
09cbfeaf 8715 put_page(page);
39279cc3 8716 }
a52d9a80 8717 return ret;
39279cc3
CM
8718}
8719
e6dcd2dc
CM
8720static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8721{
98509cfc
CM
8722 if (PageWriteback(page) || PageDirty(page))
8723 return 0;
3ba7ab22 8724 return __btrfs_releasepage(page, gfp_flags);
e6dcd2dc
CM
8725}
8726
d47992f8
LC
8727static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8728 unsigned int length)
39279cc3 8729{
5fd02043 8730 struct inode *inode = page->mapping->host;
d1310b2e 8731 struct extent_io_tree *tree;
e6dcd2dc 8732 struct btrfs_ordered_extent *ordered;
2ac55d41 8733 struct extent_state *cached_state = NULL;
e6dcd2dc 8734 u64 page_start = page_offset(page);
09cbfeaf 8735 u64 page_end = page_start + PAGE_SIZE - 1;
dbfdb6d1
CR
8736 u64 start;
8737 u64 end;
131e404a 8738 int inode_evicting = inode->i_state & I_FREEING;
39279cc3 8739
8b62b72b
CM
8740 /*
8741 * we have the page locked, so new writeback can't start,
8742 * and the dirty bit won't be cleared while we are here.
8743 *
8744 * Wait for IO on this page so that we can safely clear
8745 * the PagePrivate2 bit and do ordered accounting
8746 */
e6dcd2dc 8747 wait_on_page_writeback(page);
8b62b72b 8748
5fd02043 8749 tree = &BTRFS_I(inode)->io_tree;
e6dcd2dc
CM
8750 if (offset) {
8751 btrfs_releasepage(page, GFP_NOFS);
8752 return;
8753 }
131e404a
FDBM
8754
8755 if (!inode_evicting)
ff13db41 8756 lock_extent_bits(tree, page_start, page_end, &cached_state);
dbfdb6d1
CR
8757again:
8758 start = page_start;
a776c6fa 8759 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
dbfdb6d1 8760 page_end - start + 1);
e6dcd2dc 8761 if (ordered) {
dbfdb6d1 8762 end = min(page_end, ordered->file_offset + ordered->len - 1);
eb84ae03
CM
8763 /*
8764 * IO on this page will never be started, so we need
8765 * to account for any ordered extents now
8766 */
131e404a 8767 if (!inode_evicting)
dbfdb6d1 8768 clear_extent_bit(tree, start, end,
131e404a 8769 EXTENT_DIRTY | EXTENT_DELALLOC |
a7e3b975 8770 EXTENT_DELALLOC_NEW |
131e404a 8771 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
ae0f1625 8772 EXTENT_DEFRAG, 1, 0, &cached_state);
8b62b72b
CM
8773 /*
8774 * whoever cleared the private bit is responsible
8775 * for the finish_ordered_io
8776 */
77cef2ec
JB
8777 if (TestClearPagePrivate2(page)) {
8778 struct btrfs_ordered_inode_tree *tree;
8779 u64 new_len;
8780
8781 tree = &BTRFS_I(inode)->ordered_tree;
8782
8783 spin_lock_irq(&tree->lock);
8784 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
dbfdb6d1 8785 new_len = start - ordered->file_offset;
77cef2ec
JB
8786 if (new_len < ordered->truncated_len)
8787 ordered->truncated_len = new_len;
8788 spin_unlock_irq(&tree->lock);
8789
8790 if (btrfs_dec_test_ordered_pending(inode, &ordered,
dbfdb6d1
CR
8791 start,
8792 end - start + 1, 1))
77cef2ec 8793 btrfs_finish_ordered_io(ordered);
8b62b72b 8794 }
e6dcd2dc 8795 btrfs_put_ordered_extent(ordered);
131e404a
FDBM
8796 if (!inode_evicting) {
8797 cached_state = NULL;
dbfdb6d1 8798 lock_extent_bits(tree, start, end,
131e404a
FDBM
8799 &cached_state);
8800 }
dbfdb6d1
CR
8801
8802 start = end + 1;
8803 if (start < page_end)
8804 goto again;
131e404a
FDBM
8805 }
8806
b9d0b389
QW
8807 /*
8808 * Qgroup reserved space handler
8809 * Page here will be either
8810 * 1) Already written to disk
8811 * In this case, its reserved space is released from data rsv map
8812 * and will be freed by delayed_ref handler finally.
8813 * So even we call qgroup_free_data(), it won't decrease reserved
8814 * space.
8815 * 2) Not written to disk
0b34c261
GR
8816 * This means the reserved space should be freed here. However,
8817 * if a truncate invalidates the page (by clearing PageDirty)
8818 * and the page is accounted for while allocating extent
8819 * in btrfs_check_data_free_space() we let delayed_ref to
8820 * free the entire extent.
b9d0b389 8821 */
0b34c261 8822 if (PageDirty(page))
bc42bda2 8823 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
131e404a
FDBM
8824 if (!inode_evicting) {
8825 clear_extent_bit(tree, page_start, page_end,
8826 EXTENT_LOCKED | EXTENT_DIRTY |
a7e3b975
FM
8827 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8828 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
ae0f1625 8829 &cached_state);
131e404a
FDBM
8830
8831 __btrfs_releasepage(page, GFP_NOFS);
e6dcd2dc 8832 }
e6dcd2dc 8833
4a096752 8834 ClearPageChecked(page);
9ad6b7bc 8835 if (PagePrivate(page)) {
9ad6b7bc
CM
8836 ClearPagePrivate(page);
8837 set_page_private(page, 0);
09cbfeaf 8838 put_page(page);
9ad6b7bc 8839 }
39279cc3
CM
8840}
8841
9ebefb18
CM
8842/*
8843 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8844 * called from a page fault handler when a page is first dirtied. Hence we must
8845 * be careful to check for EOF conditions here. We set the page up correctly
8846 * for a written page which means we get ENOSPC checking when writing into
8847 * holes and correct delalloc and unwritten extent mapping on filesystems that
8848 * support these features.
8849 *
8850 * We are not allowed to take the i_mutex here so we have to play games to
8851 * protect against truncate races as the page could now be beyond EOF. Because
d1342aad
OS
8852 * truncate_setsize() writes the inode size before removing pages, once we have
8853 * the page lock we can determine safely if the page is beyond EOF. If it is not
9ebefb18
CM
8854 * beyond EOF, then the page is guaranteed safe against truncation until we
8855 * unlock the page.
8856 */
a528a241 8857vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
9ebefb18 8858{
c2ec175c 8859 struct page *page = vmf->page;
11bac800 8860 struct inode *inode = file_inode(vmf->vma->vm_file);
0b246afa 8861 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc
CM
8862 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8863 struct btrfs_ordered_extent *ordered;
2ac55d41 8864 struct extent_state *cached_state = NULL;
364ecf36 8865 struct extent_changeset *data_reserved = NULL;
e6dcd2dc
CM
8866 char *kaddr;
8867 unsigned long zero_start;
9ebefb18 8868 loff_t size;
a528a241
SJ
8869 vm_fault_t ret;
8870 int ret2;
9998eb70 8871 int reserved = 0;
d0b7da88 8872 u64 reserved_space;
a52d9a80 8873 u64 page_start;
e6dcd2dc 8874 u64 page_end;
d0b7da88
CR
8875 u64 end;
8876
09cbfeaf 8877 reserved_space = PAGE_SIZE;
9ebefb18 8878
b2b5ef5c 8879 sb_start_pagefault(inode->i_sb);
df480633 8880 page_start = page_offset(page);
09cbfeaf 8881 page_end = page_start + PAGE_SIZE - 1;
d0b7da88 8882 end = page_end;
df480633 8883
d0b7da88
CR
8884 /*
8885 * Reserving delalloc space after obtaining the page lock can lead to
8886 * deadlock. For example, if a dirty page is locked by this function
8887 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8888 * dirty page write out, then the btrfs_writepage() function could
8889 * end up waiting indefinitely to get a lock on the page currently
8890 * being processed by btrfs_page_mkwrite() function.
8891 */
a528a241 8892 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
d0b7da88 8893 reserved_space);
a528a241
SJ
8894 if (!ret2) {
8895 ret2 = file_update_time(vmf->vma->vm_file);
9998eb70
CM
8896 reserved = 1;
8897 }
a528a241
SJ
8898 if (ret2) {
8899 ret = vmf_error(ret2);
9998eb70
CM
8900 if (reserved)
8901 goto out;
8902 goto out_noreserve;
56a76f82 8903 }
1832a6d5 8904
56a76f82 8905 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 8906again:
9ebefb18 8907 lock_page(page);
9ebefb18 8908 size = i_size_read(inode);
a52d9a80 8909
9ebefb18 8910 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 8911 (page_start >= size)) {
9ebefb18
CM
8912 /* page got truncated out from underneath us */
8913 goto out_unlock;
8914 }
e6dcd2dc
CM
8915 wait_on_page_writeback(page);
8916
ff13db41 8917 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
e6dcd2dc
CM
8918 set_page_extent_mapped(page);
8919
eb84ae03
CM
8920 /*
8921 * we can't set the delalloc bits if there are pending ordered
8922 * extents. Drop our locks and wait for them to finish
8923 */
a776c6fa
NB
8924 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8925 PAGE_SIZE);
e6dcd2dc 8926 if (ordered) {
2ac55d41 8927 unlock_extent_cached(io_tree, page_start, page_end,
e43bbe5e 8928 &cached_state);
e6dcd2dc 8929 unlock_page(page);
eb84ae03 8930 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
8931 btrfs_put_ordered_extent(ordered);
8932 goto again;
8933 }
8934
09cbfeaf 8935 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
da17066c 8936 reserved_space = round_up(size - page_start,
0b246afa 8937 fs_info->sectorsize);
09cbfeaf 8938 if (reserved_space < PAGE_SIZE) {
d0b7da88 8939 end = page_start + reserved_space - 1;
bc42bda2 8940 btrfs_delalloc_release_space(inode, data_reserved,
43b18595
QW
8941 page_start, PAGE_SIZE - reserved_space,
8942 true);
d0b7da88
CR
8943 }
8944 }
8945
fbf19087 8946 /*
5416034f
LB
8947 * page_mkwrite gets called when the page is firstly dirtied after it's
8948 * faulted in, but write(2) could also dirty a page and set delalloc
8949 * bits, thus in this case for space account reason, we still need to
8950 * clear any delalloc bits within this page range since we have to
8951 * reserve data&meta space before lock_page() (see above comments).
fbf19087 8952 */
d0b7da88 8953 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9e8a4a8b
LB
8954 EXTENT_DIRTY | EXTENT_DELALLOC |
8955 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
ae0f1625 8956 0, 0, &cached_state);
fbf19087 8957
a528a241 8958 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
ba8b04c1 8959 &cached_state, 0);
a528a241 8960 if (ret2) {
2ac55d41 8961 unlock_extent_cached(io_tree, page_start, page_end,
e43bbe5e 8962 &cached_state);
9ed74f2d
JB
8963 ret = VM_FAULT_SIGBUS;
8964 goto out_unlock;
8965 }
a528a241 8966 ret2 = 0;
9ebefb18
CM
8967
8968 /* page is wholly or partially inside EOF */
09cbfeaf 8969 if (page_start + PAGE_SIZE > size)
7073017a 8970 zero_start = offset_in_page(size);
9ebefb18 8971 else
09cbfeaf 8972 zero_start = PAGE_SIZE;
9ebefb18 8973
09cbfeaf 8974 if (zero_start != PAGE_SIZE) {
e6dcd2dc 8975 kaddr = kmap(page);
09cbfeaf 8976 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
e6dcd2dc
CM
8977 flush_dcache_page(page);
8978 kunmap(page);
8979 }
247e743c 8980 ClearPageChecked(page);
e6dcd2dc 8981 set_page_dirty(page);
50a9b214 8982 SetPageUptodate(page);
5a3f23d5 8983
0b246afa 8984 BTRFS_I(inode)->last_trans = fs_info->generation;
257c62e1 8985 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
46d8bc34 8986 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
257c62e1 8987
e43bbe5e 8988 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9ebefb18 8989
a528a241 8990 if (!ret2) {
43b18595 8991 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
b2b5ef5c 8992 sb_end_pagefault(inode->i_sb);
364ecf36 8993 extent_changeset_free(data_reserved);
50a9b214 8994 return VM_FAULT_LOCKED;
b2b5ef5c 8995 }
717beb96
CM
8996
8997out_unlock:
9ebefb18 8998 unlock_page(page);
1832a6d5 8999out:
43b18595 9000 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
bc42bda2 9001 btrfs_delalloc_release_space(inode, data_reserved, page_start,
43b18595 9002 reserved_space, (ret != 0));
9998eb70 9003out_noreserve:
b2b5ef5c 9004 sb_end_pagefault(inode->i_sb);
364ecf36 9005 extent_changeset_free(data_reserved);
9ebefb18
CM
9006 return ret;
9007}
9008
213e8c55 9009static int btrfs_truncate(struct inode *inode, bool skip_writeback)
39279cc3 9010{
0b246afa 9011 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 9012 struct btrfs_root *root = BTRFS_I(inode)->root;
fcb80c2a 9013 struct btrfs_block_rsv *rsv;
ad7e1a74 9014 int ret;
39279cc3 9015 struct btrfs_trans_handle *trans;
0b246afa
JM
9016 u64 mask = fs_info->sectorsize - 1;
9017 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
39279cc3 9018
213e8c55
FM
9019 if (!skip_writeback) {
9020 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9021 (u64)-1);
9022 if (ret)
9023 return ret;
9024 }
39279cc3 9025
fcb80c2a 9026 /*
f7e9e8fc
OS
9027 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9028 * things going on here:
fcb80c2a 9029 *
f7e9e8fc 9030 * 1) We need to reserve space to update our inode.
fcb80c2a 9031 *
f7e9e8fc 9032 * 2) We need to have something to cache all the space that is going to
fcb80c2a
JB
9033 * be free'd up by the truncate operation, but also have some slack
9034 * space reserved in case it uses space during the truncate (thank you
9035 * very much snapshotting).
9036 *
f7e9e8fc 9037 * And we need these to be separate. The fact is we can use a lot of
fcb80c2a 9038 * space doing the truncate, and we have no earthly idea how much space
01327610 9039 * we will use, so we need the truncate reservation to be separate so it
f7e9e8fc
OS
9040 * doesn't end up using space reserved for updating the inode. We also
9041 * need to be able to stop the transaction and start a new one, which
9042 * means we need to be able to update the inode several times, and we
9043 * have no idea of knowing how many times that will be, so we can't just
9044 * reserve 1 item for the entirety of the operation, so that has to be
9045 * done separately as well.
fcb80c2a
JB
9046 *
9047 * So that leaves us with
9048 *
f7e9e8fc 9049 * 1) rsv - for the truncate reservation, which we will steal from the
fcb80c2a 9050 * transaction reservation.
f7e9e8fc 9051 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
fcb80c2a
JB
9052 * updating the inode.
9053 */
2ff7e61e 9054 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
fcb80c2a
JB
9055 if (!rsv)
9056 return -ENOMEM;
4a338542 9057 rsv->size = min_size;
ca7e70f5 9058 rsv->failfast = 1;
f0cd846e 9059
907cbceb 9060 /*
07127184 9061 * 1 for the truncate slack space
907cbceb
JB
9062 * 1 for updating the inode.
9063 */
f3fe820c 9064 trans = btrfs_start_transaction(root, 2);
fcb80c2a 9065 if (IS_ERR(trans)) {
ad7e1a74 9066 ret = PTR_ERR(trans);
fcb80c2a
JB
9067 goto out;
9068 }
f0cd846e 9069
907cbceb 9070 /* Migrate the slack space for the truncate to our reserve */
0b246afa 9071 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
3a584174 9072 min_size, false);
fcb80c2a 9073 BUG_ON(ret);
f0cd846e 9074
5dc562c5
JB
9075 /*
9076 * So if we truncate and then write and fsync we normally would just
9077 * write the extents that changed, which is a problem if we need to
9078 * first truncate that entire inode. So set this flag so we write out
9079 * all of the extents in the inode to the sync log so we're completely
9080 * safe.
9081 */
9082 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
ca7e70f5 9083 trans->block_rsv = rsv;
907cbceb 9084
8082510e
YZ
9085 while (1) {
9086 ret = btrfs_truncate_inode_items(trans, root, inode,
9087 inode->i_size,
9088 BTRFS_EXTENT_DATA_KEY);
ddfae63c 9089 trans->block_rsv = &fs_info->trans_block_rsv;
ad7e1a74 9090 if (ret != -ENOSPC && ret != -EAGAIN)
8082510e 9091 break;
39279cc3 9092
8082510e 9093 ret = btrfs_update_inode(trans, root, inode);
ad7e1a74 9094 if (ret)
3893e33b 9095 break;
ca7e70f5 9096
3a45bb20 9097 btrfs_end_transaction(trans);
2ff7e61e 9098 btrfs_btree_balance_dirty(fs_info);
ca7e70f5
JB
9099
9100 trans = btrfs_start_transaction(root, 2);
9101 if (IS_ERR(trans)) {
ad7e1a74 9102 ret = PTR_ERR(trans);
ca7e70f5
JB
9103 trans = NULL;
9104 break;
9105 }
9106
47b5d646 9107 btrfs_block_rsv_release(fs_info, rsv, -1);
0b246afa 9108 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
3a584174 9109 rsv, min_size, false);
ca7e70f5
JB
9110 BUG_ON(ret); /* shouldn't happen */
9111 trans->block_rsv = rsv;
8082510e
YZ
9112 }
9113
ddfae63c
JB
9114 /*
9115 * We can't call btrfs_truncate_block inside a trans handle as we could
9116 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9117 * we've truncated everything except the last little bit, and can do
9118 * btrfs_truncate_block and then update the disk_i_size.
9119 */
9120 if (ret == NEED_TRUNCATE_BLOCK) {
9121 btrfs_end_transaction(trans);
9122 btrfs_btree_balance_dirty(fs_info);
9123
9124 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9125 if (ret)
9126 goto out;
9127 trans = btrfs_start_transaction(root, 1);
9128 if (IS_ERR(trans)) {
9129 ret = PTR_ERR(trans);
9130 goto out;
9131 }
9132 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9133 }
9134
917c16b2 9135 if (trans) {
ad7e1a74
OS
9136 int ret2;
9137
0b246afa 9138 trans->block_rsv = &fs_info->trans_block_rsv;
ad7e1a74
OS
9139 ret2 = btrfs_update_inode(trans, root, inode);
9140 if (ret2 && !ret)
9141 ret = ret2;
7b128766 9142
ad7e1a74
OS
9143 ret2 = btrfs_end_transaction(trans);
9144 if (ret2 && !ret)
9145 ret = ret2;
2ff7e61e 9146 btrfs_btree_balance_dirty(fs_info);
917c16b2 9147 }
fcb80c2a 9148out:
2ff7e61e 9149 btrfs_free_block_rsv(fs_info, rsv);
fcb80c2a 9150
ad7e1a74 9151 return ret;
39279cc3
CM
9152}
9153
d352ac68
CM
9154/*
9155 * create a new subvolume directory/inode (helper for the ioctl).
9156 */
d2fb3437 9157int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
63541927
FDBM
9158 struct btrfs_root *new_root,
9159 struct btrfs_root *parent_root,
9160 u64 new_dirid)
39279cc3 9161{
39279cc3 9162 struct inode *inode;
76dda93c 9163 int err;
00e4e6b3 9164 u64 index = 0;
39279cc3 9165
12fc9d09
FA
9166 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9167 new_dirid, new_dirid,
9168 S_IFDIR | (~current_umask() & S_IRWXUGO),
9169 &index);
54aa1f4d 9170 if (IS_ERR(inode))
f46b5a66 9171 return PTR_ERR(inode);
39279cc3
CM
9172 inode->i_op = &btrfs_dir_inode_operations;
9173 inode->i_fop = &btrfs_dir_file_operations;
9174
bfe86848 9175 set_nlink(inode, 1);
6ef06d27 9176 btrfs_i_size_write(BTRFS_I(inode), 0);
b0d5d10f 9177 unlock_new_inode(inode);
3b96362c 9178
63541927
FDBM
9179 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9180 if (err)
9181 btrfs_err(new_root->fs_info,
351fd353 9182 "error inheriting subvolume %llu properties: %d",
63541927
FDBM
9183 new_root->root_key.objectid, err);
9184
76dda93c 9185 err = btrfs_update_inode(trans, new_root, inode);
cb8e7090 9186
76dda93c 9187 iput(inode);
ce598979 9188 return err;
39279cc3
CM
9189}
9190
39279cc3
CM
9191struct inode *btrfs_alloc_inode(struct super_block *sb)
9192{
69fe2d75 9193 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
39279cc3 9194 struct btrfs_inode *ei;
2ead6ae7 9195 struct inode *inode;
39279cc3 9196
712e36c5 9197 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
39279cc3
CM
9198 if (!ei)
9199 return NULL;
2ead6ae7
YZ
9200
9201 ei->root = NULL;
2ead6ae7 9202 ei->generation = 0;
15ee9bc7 9203 ei->last_trans = 0;
257c62e1 9204 ei->last_sub_trans = 0;
e02119d5 9205 ei->logged_trans = 0;
2ead6ae7 9206 ei->delalloc_bytes = 0;
a7e3b975 9207 ei->new_delalloc_bytes = 0;
47059d93 9208 ei->defrag_bytes = 0;
2ead6ae7
YZ
9209 ei->disk_i_size = 0;
9210 ei->flags = 0;
7709cde3 9211 ei->csum_bytes = 0;
2ead6ae7 9212 ei->index_cnt = (u64)-1;
67de1176 9213 ei->dir_index = 0;
2ead6ae7 9214 ei->last_unlink_trans = 0;
46d8bc34 9215 ei->last_log_commit = 0;
2ead6ae7 9216
9e0baf60
JB
9217 spin_lock_init(&ei->lock);
9218 ei->outstanding_extents = 0;
69fe2d75
JB
9219 if (sb->s_magic != BTRFS_TEST_MAGIC)
9220 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9221 BTRFS_BLOCK_RSV_DELALLOC);
72ac3c0d 9222 ei->runtime_flags = 0;
b52aa8c9 9223 ei->prop_compress = BTRFS_COMPRESS_NONE;
eec63c65 9224 ei->defrag_compress = BTRFS_COMPRESS_NONE;
2ead6ae7 9225
16cdcec7
MX
9226 ei->delayed_node = NULL;
9227
9cc97d64 9228 ei->i_otime.tv_sec = 0;
9229 ei->i_otime.tv_nsec = 0;
9230
2ead6ae7 9231 inode = &ei->vfs_inode;
a8067e02 9232 extent_map_tree_init(&ei->extent_tree);
43eb5f29
QW
9233 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
9234 extent_io_tree_init(fs_info, &ei->io_failure_tree,
9235 IO_TREE_INODE_IO_FAILURE, inode);
7b439738
DS
9236 ei->io_tree.track_uptodate = true;
9237 ei->io_failure_tree.track_uptodate = true;
b812ce28 9238 atomic_set(&ei->sync_writers, 0);
2ead6ae7 9239 mutex_init(&ei->log_mutex);
f248679e 9240 mutex_init(&ei->delalloc_mutex);
e6dcd2dc 9241 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
2ead6ae7 9242 INIT_LIST_HEAD(&ei->delalloc_inodes);
8089fe62 9243 INIT_LIST_HEAD(&ei->delayed_iput);
2ead6ae7 9244 RB_CLEAR_NODE(&ei->rb_node);
5f9a8a51 9245 init_rwsem(&ei->dio_sem);
2ead6ae7
YZ
9246
9247 return inode;
39279cc3
CM
9248}
9249
aaedb55b
JB
9250#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9251void btrfs_test_destroy_inode(struct inode *inode)
9252{
dcdbc059 9253 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
aaedb55b
JB
9254 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9255}
9256#endif
9257
fa0d7e3d
NP
9258static void btrfs_i_callback(struct rcu_head *head)
9259{
9260 struct inode *inode = container_of(head, struct inode, i_rcu);
fa0d7e3d
NP
9261 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9262}
9263
39279cc3
CM
9264void btrfs_destroy_inode(struct inode *inode)
9265{
0b246afa 9266 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc 9267 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
9268 struct btrfs_root *root = BTRFS_I(inode)->root;
9269
b3d9b7a3 9270 WARN_ON(!hlist_empty(&inode->i_dentry));
39279cc3 9271 WARN_ON(inode->i_data.nrpages);
69fe2d75
JB
9272 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9273 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9e0baf60 9274 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7709cde3 9275 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
a7e3b975 9276 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
7709cde3 9277 WARN_ON(BTRFS_I(inode)->csum_bytes);
47059d93 9278 WARN_ON(BTRFS_I(inode)->defrag_bytes);
39279cc3 9279
a6dbd429
JB
9280 /*
9281 * This can happen where we create an inode, but somebody else also
9282 * created the same inode and we need to destroy the one we already
9283 * created.
9284 */
9285 if (!root)
9286 goto free;
9287
d397712b 9288 while (1) {
e6dcd2dc
CM
9289 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9290 if (!ordered)
9291 break;
9292 else {
0b246afa 9293 btrfs_err(fs_info,
5d163e0e
JM
9294 "found ordered extent %llu %llu on inode cleanup",
9295 ordered->file_offset, ordered->len);
e6dcd2dc
CM
9296 btrfs_remove_ordered_extent(inode, ordered);
9297 btrfs_put_ordered_extent(ordered);
9298 btrfs_put_ordered_extent(ordered);
9299 }
9300 }
56fa9d07 9301 btrfs_qgroup_check_reserved_leak(inode);
5d4f98a2 9302 inode_tree_del(inode);
dcdbc059 9303 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
a6dbd429 9304free:
fa0d7e3d 9305 call_rcu(&inode->i_rcu, btrfs_i_callback);
39279cc3
CM
9306}
9307
45321ac5 9308int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
9309{
9310 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 9311
6379ef9f
NA
9312 if (root == NULL)
9313 return 1;
9314
fa6ac876 9315 /* the snap/subvol tree is on deleting */
69e9c6c6 9316 if (btrfs_root_refs(&root->root_item) == 0)
45321ac5 9317 return 1;
76dda93c 9318 else
45321ac5 9319 return generic_drop_inode(inode);
76dda93c
YZ
9320}
9321
0ee0fda0 9322static void init_once(void *foo)
39279cc3
CM
9323{
9324 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9325
9326 inode_init_once(&ei->vfs_inode);
9327}
9328
e67c718b 9329void __cold btrfs_destroy_cachep(void)
39279cc3 9330{
8c0a8537
KS
9331 /*
9332 * Make sure all delayed rcu free inodes are flushed before we
9333 * destroy cache.
9334 */
9335 rcu_barrier();
5598e900
KM
9336 kmem_cache_destroy(btrfs_inode_cachep);
9337 kmem_cache_destroy(btrfs_trans_handle_cachep);
5598e900
KM
9338 kmem_cache_destroy(btrfs_path_cachep);
9339 kmem_cache_destroy(btrfs_free_space_cachep);
39279cc3
CM
9340}
9341
f5c29bd9 9342int __init btrfs_init_cachep(void)
39279cc3 9343{
837e1972 9344 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9601e3f6 9345 sizeof(struct btrfs_inode), 0,
5d097056
VD
9346 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9347 init_once);
39279cc3
CM
9348 if (!btrfs_inode_cachep)
9349 goto fail;
9601e3f6 9350
837e1972 9351 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9601e3f6 9352 sizeof(struct btrfs_trans_handle), 0,
fba4b697 9353 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
9354 if (!btrfs_trans_handle_cachep)
9355 goto fail;
9601e3f6 9356
837e1972 9357 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9601e3f6 9358 sizeof(struct btrfs_path), 0,
fba4b697 9359 SLAB_MEM_SPREAD, NULL);
39279cc3
CM
9360 if (!btrfs_path_cachep)
9361 goto fail;
9601e3f6 9362
837e1972 9363 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
dc89e982 9364 sizeof(struct btrfs_free_space), 0,
fba4b697 9365 SLAB_MEM_SPREAD, NULL);
dc89e982
JB
9366 if (!btrfs_free_space_cachep)
9367 goto fail;
9368
39279cc3
CM
9369 return 0;
9370fail:
9371 btrfs_destroy_cachep();
9372 return -ENOMEM;
9373}
9374
a528d35e
DH
9375static int btrfs_getattr(const struct path *path, struct kstat *stat,
9376 u32 request_mask, unsigned int flags)
39279cc3 9377{
df0af1a5 9378 u64 delalloc_bytes;
a528d35e 9379 struct inode *inode = d_inode(path->dentry);
fadc0d8b 9380 u32 blocksize = inode->i_sb->s_blocksize;
04a87e34
YS
9381 u32 bi_flags = BTRFS_I(inode)->flags;
9382
9383 stat->result_mask |= STATX_BTIME;
9384 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9385 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9386 if (bi_flags & BTRFS_INODE_APPEND)
9387 stat->attributes |= STATX_ATTR_APPEND;
9388 if (bi_flags & BTRFS_INODE_COMPRESS)
9389 stat->attributes |= STATX_ATTR_COMPRESSED;
9390 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9391 stat->attributes |= STATX_ATTR_IMMUTABLE;
9392 if (bi_flags & BTRFS_INODE_NODUMP)
9393 stat->attributes |= STATX_ATTR_NODUMP;
9394
9395 stat->attributes_mask |= (STATX_ATTR_APPEND |
9396 STATX_ATTR_COMPRESSED |
9397 STATX_ATTR_IMMUTABLE |
9398 STATX_ATTR_NODUMP);
fadc0d8b 9399
39279cc3 9400 generic_fillattr(inode, stat);
0ee5dc67 9401 stat->dev = BTRFS_I(inode)->root->anon_dev;
df0af1a5
MX
9402
9403 spin_lock(&BTRFS_I(inode)->lock);
a7e3b975 9404 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
df0af1a5 9405 spin_unlock(&BTRFS_I(inode)->lock);
fadc0d8b 9406 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
df0af1a5 9407 ALIGN(delalloc_bytes, blocksize)) >> 9;
39279cc3
CM
9408 return 0;
9409}
9410
cdd1fedf
DF
9411static int btrfs_rename_exchange(struct inode *old_dir,
9412 struct dentry *old_dentry,
9413 struct inode *new_dir,
9414 struct dentry *new_dentry)
9415{
0b246afa 9416 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
cdd1fedf
DF
9417 struct btrfs_trans_handle *trans;
9418 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9419 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9420 struct inode *new_inode = new_dentry->d_inode;
9421 struct inode *old_inode = old_dentry->d_inode;
95582b00 9422 struct timespec64 ctime = current_time(old_inode);
cdd1fedf 9423 struct dentry *parent;
4a0cc7ca
NB
9424 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9425 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
cdd1fedf
DF
9426 u64 old_idx = 0;
9427 u64 new_idx = 0;
9428 u64 root_objectid;
9429 int ret;
86e8aa0e
FM
9430 bool root_log_pinned = false;
9431 bool dest_log_pinned = false;
d4682ba0
FM
9432 struct btrfs_log_ctx ctx_root;
9433 struct btrfs_log_ctx ctx_dest;
9434 bool sync_log_root = false;
9435 bool sync_log_dest = false;
9436 bool commit_transaction = false;
cdd1fedf
DF
9437
9438 /* we only allow rename subvolume link between subvolumes */
9439 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9440 return -EXDEV;
9441
d4682ba0
FM
9442 btrfs_init_log_ctx(&ctx_root, old_inode);
9443 btrfs_init_log_ctx(&ctx_dest, new_inode);
9444
cdd1fedf
DF
9445 /* close the race window with snapshot create/destroy ioctl */
9446 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9447 down_read(&fs_info->subvol_sem);
cdd1fedf 9448 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9449 down_read(&fs_info->subvol_sem);
cdd1fedf
DF
9450
9451 /*
9452 * We want to reserve the absolute worst case amount of items. So if
9453 * both inodes are subvols and we need to unlink them then that would
9454 * require 4 item modifications, but if they are both normal inodes it
9455 * would require 5 item modifications, so we'll assume their normal
9456 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9457 * should cover the worst case number of items we'll modify.
9458 */
9459 trans = btrfs_start_transaction(root, 12);
9460 if (IS_ERR(trans)) {
9461 ret = PTR_ERR(trans);
9462 goto out_notrans;
9463 }
9464
9465 /*
9466 * We need to find a free sequence number both in the source and
9467 * in the destination directory for the exchange.
9468 */
877574e2 9469 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
cdd1fedf
DF
9470 if (ret)
9471 goto out_fail;
877574e2 9472 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
cdd1fedf
DF
9473 if (ret)
9474 goto out_fail;
9475
9476 BTRFS_I(old_inode)->dir_index = 0ULL;
9477 BTRFS_I(new_inode)->dir_index = 0ULL;
9478
9479 /* Reference for the source. */
9480 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9481 /* force full log commit if subvolume involved. */
90787766 9482 btrfs_set_log_full_commit(trans);
cdd1fedf 9483 } else {
376e5a57
FM
9484 btrfs_pin_log_trans(root);
9485 root_log_pinned = true;
cdd1fedf
DF
9486 ret = btrfs_insert_inode_ref(trans, dest,
9487 new_dentry->d_name.name,
9488 new_dentry->d_name.len,
9489 old_ino,
f85b7379
DS
9490 btrfs_ino(BTRFS_I(new_dir)),
9491 old_idx);
cdd1fedf
DF
9492 if (ret)
9493 goto out_fail;
cdd1fedf
DF
9494 }
9495
9496 /* And now for the dest. */
9497 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9498 /* force full log commit if subvolume involved. */
90787766 9499 btrfs_set_log_full_commit(trans);
cdd1fedf 9500 } else {
376e5a57
FM
9501 btrfs_pin_log_trans(dest);
9502 dest_log_pinned = true;
cdd1fedf
DF
9503 ret = btrfs_insert_inode_ref(trans, root,
9504 old_dentry->d_name.name,
9505 old_dentry->d_name.len,
9506 new_ino,
f85b7379
DS
9507 btrfs_ino(BTRFS_I(old_dir)),
9508 new_idx);
cdd1fedf
DF
9509 if (ret)
9510 goto out_fail;
cdd1fedf
DF
9511 }
9512
9513 /* Update inode version and ctime/mtime. */
9514 inode_inc_iversion(old_dir);
9515 inode_inc_iversion(new_dir);
9516 inode_inc_iversion(old_inode);
9517 inode_inc_iversion(new_inode);
9518 old_dir->i_ctime = old_dir->i_mtime = ctime;
9519 new_dir->i_ctime = new_dir->i_mtime = ctime;
9520 old_inode->i_ctime = ctime;
9521 new_inode->i_ctime = ctime;
9522
9523 if (old_dentry->d_parent != new_dentry->d_parent) {
f85b7379
DS
9524 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9525 BTRFS_I(old_inode), 1);
9526 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9527 BTRFS_I(new_inode), 1);
cdd1fedf
DF
9528 }
9529
9530 /* src is a subvolume */
9531 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9532 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
401b3b19 9533 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
cdd1fedf
DF
9534 old_dentry->d_name.name,
9535 old_dentry->d_name.len);
9536 } else { /* src is an inode */
4ec5934e
NB
9537 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9538 BTRFS_I(old_dentry->d_inode),
cdd1fedf
DF
9539 old_dentry->d_name.name,
9540 old_dentry->d_name.len);
9541 if (!ret)
9542 ret = btrfs_update_inode(trans, root, old_inode);
9543 }
9544 if (ret) {
66642832 9545 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9546 goto out_fail;
9547 }
9548
9549 /* dest is a subvolume */
9550 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9551 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
401b3b19 9552 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
cdd1fedf
DF
9553 new_dentry->d_name.name,
9554 new_dentry->d_name.len);
9555 } else { /* dest is an inode */
4ec5934e
NB
9556 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9557 BTRFS_I(new_dentry->d_inode),
cdd1fedf
DF
9558 new_dentry->d_name.name,
9559 new_dentry->d_name.len);
9560 if (!ret)
9561 ret = btrfs_update_inode(trans, dest, new_inode);
9562 }
9563 if (ret) {
66642832 9564 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9565 goto out_fail;
9566 }
9567
db0a669f 9568 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
cdd1fedf
DF
9569 new_dentry->d_name.name,
9570 new_dentry->d_name.len, 0, old_idx);
9571 if (ret) {
66642832 9572 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9573 goto out_fail;
9574 }
9575
db0a669f 9576 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
cdd1fedf
DF
9577 old_dentry->d_name.name,
9578 old_dentry->d_name.len, 0, new_idx);
9579 if (ret) {
66642832 9580 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9581 goto out_fail;
9582 }
9583
9584 if (old_inode->i_nlink == 1)
9585 BTRFS_I(old_inode)->dir_index = old_idx;
9586 if (new_inode->i_nlink == 1)
9587 BTRFS_I(new_inode)->dir_index = new_idx;
9588
86e8aa0e 9589 if (root_log_pinned) {
cdd1fedf 9590 parent = new_dentry->d_parent;
d4682ba0
FM
9591 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9592 BTRFS_I(old_dir), parent,
9593 false, &ctx_root);
9594 if (ret == BTRFS_NEED_LOG_SYNC)
9595 sync_log_root = true;
9596 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9597 commit_transaction = true;
9598 ret = 0;
cdd1fedf 9599 btrfs_end_log_trans(root);
86e8aa0e 9600 root_log_pinned = false;
cdd1fedf 9601 }
86e8aa0e 9602 if (dest_log_pinned) {
d4682ba0
FM
9603 if (!commit_transaction) {
9604 parent = old_dentry->d_parent;
9605 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9606 BTRFS_I(new_dir), parent,
9607 false, &ctx_dest);
9608 if (ret == BTRFS_NEED_LOG_SYNC)
9609 sync_log_dest = true;
9610 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9611 commit_transaction = true;
9612 ret = 0;
9613 }
cdd1fedf 9614 btrfs_end_log_trans(dest);
86e8aa0e 9615 dest_log_pinned = false;
cdd1fedf
DF
9616 }
9617out_fail:
86e8aa0e
FM
9618 /*
9619 * If we have pinned a log and an error happened, we unpin tasks
9620 * trying to sync the log and force them to fallback to a transaction
9621 * commit if the log currently contains any of the inodes involved in
9622 * this rename operation (to ensure we do not persist a log with an
9623 * inconsistent state for any of these inodes or leading to any
9624 * inconsistencies when replayed). If the transaction was aborted, the
9625 * abortion reason is propagated to userspace when attempting to commit
9626 * the transaction. If the log does not contain any of these inodes, we
9627 * allow the tasks to sync it.
9628 */
9629 if (ret && (root_log_pinned || dest_log_pinned)) {
0f8939b8
NB
9630 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9631 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9632 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
86e8aa0e 9633 (new_inode &&
0f8939b8 9634 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
90787766 9635 btrfs_set_log_full_commit(trans);
86e8aa0e
FM
9636
9637 if (root_log_pinned) {
9638 btrfs_end_log_trans(root);
9639 root_log_pinned = false;
9640 }
9641 if (dest_log_pinned) {
9642 btrfs_end_log_trans(dest);
9643 dest_log_pinned = false;
9644 }
9645 }
d4682ba0
FM
9646 if (!ret && sync_log_root && !commit_transaction) {
9647 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9648 &ctx_root);
9649 if (ret)
9650 commit_transaction = true;
9651 }
9652 if (!ret && sync_log_dest && !commit_transaction) {
9653 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9654 &ctx_dest);
9655 if (ret)
9656 commit_transaction = true;
9657 }
9658 if (commit_transaction) {
9659 ret = btrfs_commit_transaction(trans);
9660 } else {
9661 int ret2;
9662
9663 ret2 = btrfs_end_transaction(trans);
9664 ret = ret ? ret : ret2;
9665 }
cdd1fedf
DF
9666out_notrans:
9667 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9668 up_read(&fs_info->subvol_sem);
cdd1fedf 9669 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9670 up_read(&fs_info->subvol_sem);
cdd1fedf
DF
9671
9672 return ret;
9673}
9674
9675static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9676 struct btrfs_root *root,
9677 struct inode *dir,
9678 struct dentry *dentry)
9679{
9680 int ret;
9681 struct inode *inode;
9682 u64 objectid;
9683 u64 index;
9684
9685 ret = btrfs_find_free_ino(root, &objectid);
9686 if (ret)
9687 return ret;
9688
9689 inode = btrfs_new_inode(trans, root, dir,
9690 dentry->d_name.name,
9691 dentry->d_name.len,
4a0cc7ca 9692 btrfs_ino(BTRFS_I(dir)),
cdd1fedf
DF
9693 objectid,
9694 S_IFCHR | WHITEOUT_MODE,
9695 &index);
9696
9697 if (IS_ERR(inode)) {
9698 ret = PTR_ERR(inode);
9699 return ret;
9700 }
9701
9702 inode->i_op = &btrfs_special_inode_operations;
9703 init_special_inode(inode, inode->i_mode,
9704 WHITEOUT_DEV);
9705
9706 ret = btrfs_init_inode_security(trans, inode, dir,
9707 &dentry->d_name);
9708 if (ret)
c9901618 9709 goto out;
cdd1fedf 9710
cef415af
NB
9711 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9712 BTRFS_I(inode), 0, index);
cdd1fedf 9713 if (ret)
c9901618 9714 goto out;
cdd1fedf
DF
9715
9716 ret = btrfs_update_inode(trans, root, inode);
c9901618 9717out:
cdd1fedf 9718 unlock_new_inode(inode);
c9901618
FM
9719 if (ret)
9720 inode_dec_link_count(inode);
cdd1fedf
DF
9721 iput(inode);
9722
c9901618 9723 return ret;
cdd1fedf
DF
9724}
9725
d397712b 9726static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
cdd1fedf
DF
9727 struct inode *new_dir, struct dentry *new_dentry,
9728 unsigned int flags)
39279cc3 9729{
0b246afa 9730 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
39279cc3 9731 struct btrfs_trans_handle *trans;
5062af35 9732 unsigned int trans_num_items;
39279cc3 9733 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 9734 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
2b0143b5
DH
9735 struct inode *new_inode = d_inode(new_dentry);
9736 struct inode *old_inode = d_inode(old_dentry);
00e4e6b3 9737 u64 index = 0;
4df27c4d 9738 u64 root_objectid;
39279cc3 9739 int ret;
4a0cc7ca 9740 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
3dc9e8f7 9741 bool log_pinned = false;
d4682ba0
FM
9742 struct btrfs_log_ctx ctx;
9743 bool sync_log = false;
9744 bool commit_transaction = false;
39279cc3 9745
4a0cc7ca 9746 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
f679a840
YZ
9747 return -EPERM;
9748
4df27c4d 9749 /* we only allow rename subvolume link between subvolumes */
33345d01 9750 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
9751 return -EXDEV;
9752
33345d01 9753 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
4a0cc7ca 9754 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 9755 return -ENOTEMPTY;
5f39d397 9756
4df27c4d
YZ
9757 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9758 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9759 return -ENOTEMPTY;
9c52057c
CM
9760
9761
9762 /* check for collisions, even if the name isn't there */
4871c158 9763 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9c52057c
CM
9764 new_dentry->d_name.name,
9765 new_dentry->d_name.len);
9766
9767 if (ret) {
9768 if (ret == -EEXIST) {
9769 /* we shouldn't get
9770 * eexist without a new_inode */
fae7f21c 9771 if (WARN_ON(!new_inode)) {
9c52057c
CM
9772 return ret;
9773 }
9774 } else {
9775 /* maybe -EOVERFLOW */
9776 return ret;
9777 }
9778 }
9779 ret = 0;
9780
5a3f23d5 9781 /*
8d875f95
CM
9782 * we're using rename to replace one file with another. Start IO on it
9783 * now so we don't add too much work to the end of the transaction
5a3f23d5 9784 */
8d875f95 9785 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
5a3f23d5
CM
9786 filemap_flush(old_inode->i_mapping);
9787
76dda93c 9788 /* close the racy window with snapshot create/destroy ioctl */
33345d01 9789 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9790 down_read(&fs_info->subvol_sem);
a22285a6
YZ
9791 /*
9792 * We want to reserve the absolute worst case amount of items. So if
9793 * both inodes are subvols and we need to unlink them then that would
9794 * require 4 item modifications, but if they are both normal inodes it
cdd1fedf 9795 * would require 5 item modifications, so we'll assume they are normal
a22285a6
YZ
9796 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9797 * should cover the worst case number of items we'll modify.
5062af35
FM
9798 * If our rename has the whiteout flag, we need more 5 units for the
9799 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9800 * when selinux is enabled).
a22285a6 9801 */
5062af35
FM
9802 trans_num_items = 11;
9803 if (flags & RENAME_WHITEOUT)
9804 trans_num_items += 5;
9805 trans = btrfs_start_transaction(root, trans_num_items);
b44c59a8 9806 if (IS_ERR(trans)) {
cdd1fedf
DF
9807 ret = PTR_ERR(trans);
9808 goto out_notrans;
9809 }
76dda93c 9810
4df27c4d
YZ
9811 if (dest != root)
9812 btrfs_record_root_in_trans(trans, dest);
5f39d397 9813
877574e2 9814 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
a5719521
YZ
9815 if (ret)
9816 goto out_fail;
5a3f23d5 9817
67de1176 9818 BTRFS_I(old_inode)->dir_index = 0ULL;
33345d01 9819 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d 9820 /* force full log commit if subvolume involved. */
90787766 9821 btrfs_set_log_full_commit(trans);
4df27c4d 9822 } else {
c4aba954
FM
9823 btrfs_pin_log_trans(root);
9824 log_pinned = true;
a5719521
YZ
9825 ret = btrfs_insert_inode_ref(trans, dest,
9826 new_dentry->d_name.name,
9827 new_dentry->d_name.len,
33345d01 9828 old_ino,
4a0cc7ca 9829 btrfs_ino(BTRFS_I(new_dir)), index);
a5719521
YZ
9830 if (ret)
9831 goto out_fail;
4df27c4d 9832 }
5a3f23d5 9833
0c4d2d95
JB
9834 inode_inc_iversion(old_dir);
9835 inode_inc_iversion(new_dir);
9836 inode_inc_iversion(old_inode);
04b285f3
DD
9837 old_dir->i_ctime = old_dir->i_mtime =
9838 new_dir->i_ctime = new_dir->i_mtime =
c2050a45 9839 old_inode->i_ctime = current_time(old_dir);
5f39d397 9840
12fcfd22 9841 if (old_dentry->d_parent != new_dentry->d_parent)
f85b7379
DS
9842 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9843 BTRFS_I(old_inode), 1);
12fcfd22 9844
33345d01 9845 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d 9846 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
401b3b19 9847 ret = btrfs_unlink_subvol(trans, old_dir, root_objectid,
4df27c4d
YZ
9848 old_dentry->d_name.name,
9849 old_dentry->d_name.len);
9850 } else {
4ec5934e
NB
9851 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9852 BTRFS_I(d_inode(old_dentry)),
92986796
AV
9853 old_dentry->d_name.name,
9854 old_dentry->d_name.len);
9855 if (!ret)
9856 ret = btrfs_update_inode(trans, root, old_inode);
4df27c4d 9857 }
79787eaa 9858 if (ret) {
66642832 9859 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9860 goto out_fail;
9861 }
39279cc3
CM
9862
9863 if (new_inode) {
0c4d2d95 9864 inode_inc_iversion(new_inode);
c2050a45 9865 new_inode->i_ctime = current_time(new_inode);
4a0cc7ca 9866 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
4df27c4d
YZ
9867 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9868 root_objectid = BTRFS_I(new_inode)->location.objectid;
401b3b19 9869 ret = btrfs_unlink_subvol(trans, new_dir, root_objectid,
4df27c4d
YZ
9870 new_dentry->d_name.name,
9871 new_dentry->d_name.len);
9872 BUG_ON(new_inode->i_nlink == 0);
9873 } else {
4ec5934e
NB
9874 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9875 BTRFS_I(d_inode(new_dentry)),
4df27c4d
YZ
9876 new_dentry->d_name.name,
9877 new_dentry->d_name.len);
9878 }
4ef31a45 9879 if (!ret && new_inode->i_nlink == 0)
73f2e545
NB
9880 ret = btrfs_orphan_add(trans,
9881 BTRFS_I(d_inode(new_dentry)));
79787eaa 9882 if (ret) {
66642832 9883 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9884 goto out_fail;
9885 }
39279cc3 9886 }
aec7477b 9887
db0a669f 9888 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
4df27c4d 9889 new_dentry->d_name.name,
a5719521 9890 new_dentry->d_name.len, 0, index);
79787eaa 9891 if (ret) {
66642832 9892 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9893 goto out_fail;
9894 }
39279cc3 9895
67de1176
MX
9896 if (old_inode->i_nlink == 1)
9897 BTRFS_I(old_inode)->dir_index = index;
9898
3dc9e8f7 9899 if (log_pinned) {
10d9f309 9900 struct dentry *parent = new_dentry->d_parent;
3dc9e8f7 9901
d4682ba0
FM
9902 btrfs_init_log_ctx(&ctx, old_inode);
9903 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9904 BTRFS_I(old_dir), parent,
9905 false, &ctx);
9906 if (ret == BTRFS_NEED_LOG_SYNC)
9907 sync_log = true;
9908 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9909 commit_transaction = true;
9910 ret = 0;
4df27c4d 9911 btrfs_end_log_trans(root);
3dc9e8f7 9912 log_pinned = false;
4df27c4d 9913 }
cdd1fedf
DF
9914
9915 if (flags & RENAME_WHITEOUT) {
9916 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9917 old_dentry);
9918
9919 if (ret) {
66642832 9920 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9921 goto out_fail;
9922 }
4df27c4d 9923 }
39279cc3 9924out_fail:
3dc9e8f7
FM
9925 /*
9926 * If we have pinned the log and an error happened, we unpin tasks
9927 * trying to sync the log and force them to fallback to a transaction
9928 * commit if the log currently contains any of the inodes involved in
9929 * this rename operation (to ensure we do not persist a log with an
9930 * inconsistent state for any of these inodes or leading to any
9931 * inconsistencies when replayed). If the transaction was aborted, the
9932 * abortion reason is propagated to userspace when attempting to commit
9933 * the transaction. If the log does not contain any of these inodes, we
9934 * allow the tasks to sync it.
9935 */
9936 if (ret && log_pinned) {
0f8939b8
NB
9937 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9938 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9939 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
3dc9e8f7 9940 (new_inode &&
0f8939b8 9941 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
90787766 9942 btrfs_set_log_full_commit(trans);
3dc9e8f7
FM
9943
9944 btrfs_end_log_trans(root);
9945 log_pinned = false;
9946 }
d4682ba0
FM
9947 if (!ret && sync_log) {
9948 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9949 if (ret)
9950 commit_transaction = true;
9951 }
9952 if (commit_transaction) {
9953 ret = btrfs_commit_transaction(trans);
9954 } else {
9955 int ret2;
9956
9957 ret2 = btrfs_end_transaction(trans);
9958 ret = ret ? ret : ret2;
9959 }
b44c59a8 9960out_notrans:
33345d01 9961 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9962 up_read(&fs_info->subvol_sem);
9ed74f2d 9963
39279cc3
CM
9964 return ret;
9965}
9966
80ace85c
MS
9967static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9968 struct inode *new_dir, struct dentry *new_dentry,
9969 unsigned int flags)
9970{
cdd1fedf 9971 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
80ace85c
MS
9972 return -EINVAL;
9973
cdd1fedf
DF
9974 if (flags & RENAME_EXCHANGE)
9975 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9976 new_dentry);
9977
9978 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
80ace85c
MS
9979}
9980
3a2f8c07
NB
9981struct btrfs_delalloc_work {
9982 struct inode *inode;
9983 struct completion completion;
9984 struct list_head list;
9985 struct btrfs_work work;
9986};
9987
8ccf6f19
MX
9988static void btrfs_run_delalloc_work(struct btrfs_work *work)
9989{
9990 struct btrfs_delalloc_work *delalloc_work;
9f23e289 9991 struct inode *inode;
8ccf6f19
MX
9992
9993 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9994 work);
9f23e289 9995 inode = delalloc_work->inode;
30424601
DS
9996 filemap_flush(inode->i_mapping);
9997 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9998 &BTRFS_I(inode)->runtime_flags))
9f23e289 9999 filemap_flush(inode->i_mapping);
8ccf6f19 10000
076da91c 10001 iput(inode);
8ccf6f19
MX
10002 complete(&delalloc_work->completion);
10003}
10004
3a2f8c07 10005static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8ccf6f19
MX
10006{
10007 struct btrfs_delalloc_work *work;
10008
100d5702 10009 work = kmalloc(sizeof(*work), GFP_NOFS);
8ccf6f19
MX
10010 if (!work)
10011 return NULL;
10012
10013 init_completion(&work->completion);
10014 INIT_LIST_HEAD(&work->list);
10015 work->inode = inode;
9e0af237
LB
10016 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10017 btrfs_run_delalloc_work, NULL, NULL);
8ccf6f19
MX
10018
10019 return work;
10020}
10021
d352ac68
CM
10022/*
10023 * some fairly slow code that needs optimization. This walks the list
10024 * of all the inodes with pending delalloc and forces them to disk.
10025 */
3cd24c69 10026static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
ea8c2819 10027{
ea8c2819 10028 struct btrfs_inode *binode;
5b21f2ed 10029 struct inode *inode;
8ccf6f19
MX
10030 struct btrfs_delalloc_work *work, *next;
10031 struct list_head works;
1eafa6c7 10032 struct list_head splice;
8ccf6f19 10033 int ret = 0;
ea8c2819 10034
8ccf6f19 10035 INIT_LIST_HEAD(&works);
1eafa6c7 10036 INIT_LIST_HEAD(&splice);
63607cc8 10037
573bfb72 10038 mutex_lock(&root->delalloc_mutex);
eb73c1b7
MX
10039 spin_lock(&root->delalloc_lock);
10040 list_splice_init(&root->delalloc_inodes, &splice);
1eafa6c7
MX
10041 while (!list_empty(&splice)) {
10042 binode = list_entry(splice.next, struct btrfs_inode,
ea8c2819 10043 delalloc_inodes);
1eafa6c7 10044
eb73c1b7
MX
10045 list_move_tail(&binode->delalloc_inodes,
10046 &root->delalloc_inodes);
5b21f2ed 10047 inode = igrab(&binode->vfs_inode);
df0af1a5 10048 if (!inode) {
eb73c1b7 10049 cond_resched_lock(&root->delalloc_lock);
1eafa6c7 10050 continue;
df0af1a5 10051 }
eb73c1b7 10052 spin_unlock(&root->delalloc_lock);
1eafa6c7 10053
3cd24c69
EL
10054 if (snapshot)
10055 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
10056 &binode->runtime_flags);
076da91c 10057 work = btrfs_alloc_delalloc_work(inode);
5d99a998 10058 if (!work) {
4fbb5147 10059 iput(inode);
1eafa6c7 10060 ret = -ENOMEM;
a1ecaabb 10061 goto out;
5b21f2ed 10062 }
1eafa6c7 10063 list_add_tail(&work->list, &works);
a44903ab
QW
10064 btrfs_queue_work(root->fs_info->flush_workers,
10065 &work->work);
6c255e67
MX
10066 ret++;
10067 if (nr != -1 && ret >= nr)
a1ecaabb 10068 goto out;
5b21f2ed 10069 cond_resched();
eb73c1b7 10070 spin_lock(&root->delalloc_lock);
ea8c2819 10071 }
eb73c1b7 10072 spin_unlock(&root->delalloc_lock);
8c8bee1d 10073
a1ecaabb 10074out:
eb73c1b7
MX
10075 list_for_each_entry_safe(work, next, &works, list) {
10076 list_del_init(&work->list);
40012f96
NB
10077 wait_for_completion(&work->completion);
10078 kfree(work);
eb73c1b7
MX
10079 }
10080
81f1d390 10081 if (!list_empty(&splice)) {
eb73c1b7
MX
10082 spin_lock(&root->delalloc_lock);
10083 list_splice_tail(&splice, &root->delalloc_inodes);
10084 spin_unlock(&root->delalloc_lock);
10085 }
573bfb72 10086 mutex_unlock(&root->delalloc_mutex);
eb73c1b7
MX
10087 return ret;
10088}
1eafa6c7 10089
3cd24c69 10090int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
eb73c1b7 10091{
0b246afa 10092 struct btrfs_fs_info *fs_info = root->fs_info;
eb73c1b7 10093 int ret;
1eafa6c7 10094
0b246afa 10095 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
10096 return -EROFS;
10097
3cd24c69 10098 ret = start_delalloc_inodes(root, -1, true);
6c255e67
MX
10099 if (ret > 0)
10100 ret = 0;
eb73c1b7
MX
10101 return ret;
10102}
10103
82b3e53b 10104int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
eb73c1b7
MX
10105{
10106 struct btrfs_root *root;
10107 struct list_head splice;
10108 int ret;
10109
2c21b4d7 10110 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
10111 return -EROFS;
10112
10113 INIT_LIST_HEAD(&splice);
10114
573bfb72 10115 mutex_lock(&fs_info->delalloc_root_mutex);
eb73c1b7
MX
10116 spin_lock(&fs_info->delalloc_root_lock);
10117 list_splice_init(&fs_info->delalloc_roots, &splice);
6c255e67 10118 while (!list_empty(&splice) && nr) {
eb73c1b7
MX
10119 root = list_first_entry(&splice, struct btrfs_root,
10120 delalloc_root);
10121 root = btrfs_grab_fs_root(root);
10122 BUG_ON(!root);
10123 list_move_tail(&root->delalloc_root,
10124 &fs_info->delalloc_roots);
10125 spin_unlock(&fs_info->delalloc_root_lock);
10126
3cd24c69 10127 ret = start_delalloc_inodes(root, nr, false);
eb73c1b7 10128 btrfs_put_fs_root(root);
6c255e67 10129 if (ret < 0)
eb73c1b7
MX
10130 goto out;
10131
6c255e67
MX
10132 if (nr != -1) {
10133 nr -= ret;
10134 WARN_ON(nr < 0);
10135 }
eb73c1b7 10136 spin_lock(&fs_info->delalloc_root_lock);
8ccf6f19 10137 }
eb73c1b7 10138 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 10139
6c255e67 10140 ret = 0;
eb73c1b7 10141out:
81f1d390 10142 if (!list_empty(&splice)) {
eb73c1b7
MX
10143 spin_lock(&fs_info->delalloc_root_lock);
10144 list_splice_tail(&splice, &fs_info->delalloc_roots);
10145 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 10146 }
573bfb72 10147 mutex_unlock(&fs_info->delalloc_root_mutex);
8ccf6f19 10148 return ret;
ea8c2819
CM
10149}
10150
39279cc3
CM
10151static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10152 const char *symname)
10153{
0b246afa 10154 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
10155 struct btrfs_trans_handle *trans;
10156 struct btrfs_root *root = BTRFS_I(dir)->root;
10157 struct btrfs_path *path;
10158 struct btrfs_key key;
1832a6d5 10159 struct inode *inode = NULL;
39279cc3 10160 int err;
39279cc3 10161 u64 objectid;
67871254 10162 u64 index = 0;
39279cc3
CM
10163 int name_len;
10164 int datasize;
5f39d397 10165 unsigned long ptr;
39279cc3 10166 struct btrfs_file_extent_item *ei;
5f39d397 10167 struct extent_buffer *leaf;
39279cc3 10168
f06becc4 10169 name_len = strlen(symname);
0b246afa 10170 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
39279cc3 10171 return -ENAMETOOLONG;
1832a6d5 10172
9ed74f2d
JB
10173 /*
10174 * 2 items for inode item and ref
10175 * 2 items for dir items
9269d12b
FM
10176 * 1 item for updating parent inode item
10177 * 1 item for the inline extent item
9ed74f2d
JB
10178 * 1 item for xattr if selinux is on
10179 */
9269d12b 10180 trans = btrfs_start_transaction(root, 7);
a22285a6
YZ
10181 if (IS_ERR(trans))
10182 return PTR_ERR(trans);
1832a6d5 10183
581bb050
LZ
10184 err = btrfs_find_free_ino(root, &objectid);
10185 if (err)
10186 goto out_unlock;
10187
aec7477b 10188 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
10189 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10190 objectid, S_IFLNK|S_IRWXUGO, &index);
7cf96da3
TI
10191 if (IS_ERR(inode)) {
10192 err = PTR_ERR(inode);
32955c54 10193 inode = NULL;
39279cc3 10194 goto out_unlock;
7cf96da3 10195 }
39279cc3 10196
ad19db71
CS
10197 /*
10198 * If the active LSM wants to access the inode during
10199 * d_instantiate it needs these. Smack checks to see
10200 * if the filesystem supports xattrs by looking at the
10201 * ops vector.
10202 */
10203 inode->i_fop = &btrfs_file_operations;
10204 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 10205 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
10206 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10207
10208 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10209 if (err)
32955c54 10210 goto out_unlock;
ad19db71 10211
39279cc3 10212 path = btrfs_alloc_path();
d8926bb3
MF
10213 if (!path) {
10214 err = -ENOMEM;
32955c54 10215 goto out_unlock;
d8926bb3 10216 }
4a0cc7ca 10217 key.objectid = btrfs_ino(BTRFS_I(inode));
39279cc3 10218 key.offset = 0;
962a298f 10219 key.type = BTRFS_EXTENT_DATA_KEY;
39279cc3
CM
10220 datasize = btrfs_file_extent_calc_inline_size(name_len);
10221 err = btrfs_insert_empty_item(trans, root, path, &key,
10222 datasize);
54aa1f4d 10223 if (err) {
b0839166 10224 btrfs_free_path(path);
32955c54 10225 goto out_unlock;
54aa1f4d 10226 }
5f39d397
CM
10227 leaf = path->nodes[0];
10228 ei = btrfs_item_ptr(leaf, path->slots[0],
10229 struct btrfs_file_extent_item);
10230 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10231 btrfs_set_file_extent_type(leaf, ei,
39279cc3 10232 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
10233 btrfs_set_file_extent_encryption(leaf, ei, 0);
10234 btrfs_set_file_extent_compression(leaf, ei, 0);
10235 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10236 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10237
39279cc3 10238 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
10239 write_extent_buffer(leaf, symname, ptr, name_len);
10240 btrfs_mark_buffer_dirty(leaf);
39279cc3 10241 btrfs_free_path(path);
5f39d397 10242
39279cc3 10243 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 10244 inode_nohighmem(inode);
d899e052 10245 inode_set_bytes(inode, name_len);
6ef06d27 10246 btrfs_i_size_write(BTRFS_I(inode), name_len);
54aa1f4d 10247 err = btrfs_update_inode(trans, root, inode);
d50866d0
FM
10248 /*
10249 * Last step, add directory indexes for our symlink inode. This is the
10250 * last step to avoid extra cleanup of these indexes if an error happens
10251 * elsewhere above.
10252 */
10253 if (!err)
cef415af
NB
10254 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10255 BTRFS_I(inode), 0, index);
32955c54
AV
10256 if (err)
10257 goto out_unlock;
b0d5d10f 10258
1e2e547a 10259 d_instantiate_new(dentry, inode);
39279cc3
CM
10260
10261out_unlock:
3a45bb20 10262 btrfs_end_transaction(trans);
32955c54 10263 if (err && inode) {
39279cc3 10264 inode_dec_link_count(inode);
32955c54 10265 discard_new_inode(inode);
39279cc3 10266 }
2ff7e61e 10267 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
10268 return err;
10269}
16432985 10270
0af3d00b
JB
10271static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10272 u64 start, u64 num_bytes, u64 min_size,
10273 loff_t actual_len, u64 *alloc_hint,
10274 struct btrfs_trans_handle *trans)
d899e052 10275{
0b246afa 10276 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5dc562c5
JB
10277 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10278 struct extent_map *em;
d899e052
YZ
10279 struct btrfs_root *root = BTRFS_I(inode)->root;
10280 struct btrfs_key ins;
d899e052 10281 u64 cur_offset = start;
55a61d1d 10282 u64 i_size;
154ea289 10283 u64 cur_bytes;
0b670dc4 10284 u64 last_alloc = (u64)-1;
d899e052 10285 int ret = 0;
0af3d00b 10286 bool own_trans = true;
18513091 10287 u64 end = start + num_bytes - 1;
d899e052 10288
0af3d00b
JB
10289 if (trans)
10290 own_trans = false;
d899e052 10291 while (num_bytes > 0) {
0af3d00b
JB
10292 if (own_trans) {
10293 trans = btrfs_start_transaction(root, 3);
10294 if (IS_ERR(trans)) {
10295 ret = PTR_ERR(trans);
10296 break;
10297 }
5a303d5d
YZ
10298 }
10299
ee22184b 10300 cur_bytes = min_t(u64, num_bytes, SZ_256M);
154ea289 10301 cur_bytes = max(cur_bytes, min_size);
0b670dc4
JB
10302 /*
10303 * If we are severely fragmented we could end up with really
10304 * small allocations, so if the allocator is returning small
10305 * chunks lets make its job easier by only searching for those
10306 * sized chunks.
10307 */
10308 cur_bytes = min(cur_bytes, last_alloc);
18513091
WX
10309 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10310 min_size, 0, *alloc_hint, &ins, 1, 0);
5a303d5d 10311 if (ret) {
0af3d00b 10312 if (own_trans)
3a45bb20 10313 btrfs_end_transaction(trans);
a22285a6 10314 break;
d899e052 10315 }
0b246afa 10316 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
5a303d5d 10317
0b670dc4 10318 last_alloc = ins.offset;
d899e052
YZ
10319 ret = insert_reserved_file_extent(trans, inode,
10320 cur_offset, ins.objectid,
10321 ins.offset, ins.offset,
920bbbfb 10322 ins.offset, 0, 0, 0,
d899e052 10323 BTRFS_FILE_EXTENT_PREALLOC);
79787eaa 10324 if (ret) {
2ff7e61e 10325 btrfs_free_reserved_extent(fs_info, ins.objectid,
e570fd27 10326 ins.offset, 0);
66642832 10327 btrfs_abort_transaction(trans, ret);
79787eaa 10328 if (own_trans)
3a45bb20 10329 btrfs_end_transaction(trans);
79787eaa
JM
10330 break;
10331 }
31193213 10332
dcdbc059 10333 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
a1ed835e 10334 cur_offset + ins.offset -1, 0);
5a303d5d 10335
5dc562c5
JB
10336 em = alloc_extent_map();
10337 if (!em) {
10338 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10339 &BTRFS_I(inode)->runtime_flags);
10340 goto next;
10341 }
10342
10343 em->start = cur_offset;
10344 em->orig_start = cur_offset;
10345 em->len = ins.offset;
10346 em->block_start = ins.objectid;
10347 em->block_len = ins.offset;
b4939680 10348 em->orig_block_len = ins.offset;
cc95bef6 10349 em->ram_bytes = ins.offset;
0b246afa 10350 em->bdev = fs_info->fs_devices->latest_bdev;
5dc562c5
JB
10351 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10352 em->generation = trans->transid;
10353
10354 while (1) {
10355 write_lock(&em_tree->lock);
09a2a8f9 10356 ret = add_extent_mapping(em_tree, em, 1);
5dc562c5
JB
10357 write_unlock(&em_tree->lock);
10358 if (ret != -EEXIST)
10359 break;
dcdbc059 10360 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
10361 cur_offset + ins.offset - 1,
10362 0);
10363 }
10364 free_extent_map(em);
10365next:
d899e052
YZ
10366 num_bytes -= ins.offset;
10367 cur_offset += ins.offset;
efa56464 10368 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 10369
0c4d2d95 10370 inode_inc_iversion(inode);
c2050a45 10371 inode->i_ctime = current_time(inode);
6cbff00f 10372 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 10373 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
10374 (actual_len > inode->i_size) &&
10375 (cur_offset > inode->i_size)) {
d1ea6a61 10376 if (cur_offset > actual_len)
55a61d1d 10377 i_size = actual_len;
d1ea6a61 10378 else
55a61d1d
JB
10379 i_size = cur_offset;
10380 i_size_write(inode, i_size);
10381 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
10382 }
10383
d899e052 10384 ret = btrfs_update_inode(trans, root, inode);
79787eaa
JM
10385
10386 if (ret) {
66642832 10387 btrfs_abort_transaction(trans, ret);
79787eaa 10388 if (own_trans)
3a45bb20 10389 btrfs_end_transaction(trans);
79787eaa
JM
10390 break;
10391 }
d899e052 10392
0af3d00b 10393 if (own_trans)
3a45bb20 10394 btrfs_end_transaction(trans);
5a303d5d 10395 }
18513091 10396 if (cur_offset < end)
bc42bda2 10397 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
18513091 10398 end - cur_offset + 1);
d899e052
YZ
10399 return ret;
10400}
10401
0af3d00b
JB
10402int btrfs_prealloc_file_range(struct inode *inode, int mode,
10403 u64 start, u64 num_bytes, u64 min_size,
10404 loff_t actual_len, u64 *alloc_hint)
10405{
10406 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10407 min_size, actual_len, alloc_hint,
10408 NULL);
10409}
10410
10411int btrfs_prealloc_file_range_trans(struct inode *inode,
10412 struct btrfs_trans_handle *trans, int mode,
10413 u64 start, u64 num_bytes, u64 min_size,
10414 loff_t actual_len, u64 *alloc_hint)
10415{
10416 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10417 min_size, actual_len, alloc_hint, trans);
10418}
10419
e6dcd2dc
CM
10420static int btrfs_set_page_dirty(struct page *page)
10421{
e6dcd2dc
CM
10422 return __set_page_dirty_nobuffers(page);
10423}
10424
10556cb2 10425static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 10426{
b83cc969 10427 struct btrfs_root *root = BTRFS_I(inode)->root;
cb6db4e5 10428 umode_t mode = inode->i_mode;
b83cc969 10429
cb6db4e5
JM
10430 if (mask & MAY_WRITE &&
10431 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10432 if (btrfs_root_readonly(root))
10433 return -EROFS;
10434 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10435 return -EACCES;
10436 }
2830ba7f 10437 return generic_permission(inode, mask);
fdebe2bd 10438}
39279cc3 10439
ef3b9af5
FM
10440static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10441{
2ff7e61e 10442 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
ef3b9af5
FM
10443 struct btrfs_trans_handle *trans;
10444 struct btrfs_root *root = BTRFS_I(dir)->root;
10445 struct inode *inode = NULL;
10446 u64 objectid;
10447 u64 index;
10448 int ret = 0;
10449
10450 /*
10451 * 5 units required for adding orphan entry
10452 */
10453 trans = btrfs_start_transaction(root, 5);
10454 if (IS_ERR(trans))
10455 return PTR_ERR(trans);
10456
10457 ret = btrfs_find_free_ino(root, &objectid);
10458 if (ret)
10459 goto out;
10460
10461 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
f85b7379 10462 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
ef3b9af5
FM
10463 if (IS_ERR(inode)) {
10464 ret = PTR_ERR(inode);
10465 inode = NULL;
10466 goto out;
10467 }
10468
ef3b9af5
FM
10469 inode->i_fop = &btrfs_file_operations;
10470 inode->i_op = &btrfs_file_inode_operations;
10471
10472 inode->i_mapping->a_ops = &btrfs_aops;
ef3b9af5
FM
10473 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10474
b0d5d10f
CM
10475 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10476 if (ret)
32955c54 10477 goto out;
b0d5d10f
CM
10478
10479 ret = btrfs_update_inode(trans, root, inode);
10480 if (ret)
32955c54 10481 goto out;
73f2e545 10482 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
ef3b9af5 10483 if (ret)
32955c54 10484 goto out;
ef3b9af5 10485
5762b5c9
FM
10486 /*
10487 * We set number of links to 0 in btrfs_new_inode(), and here we set
10488 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10489 * through:
10490 *
10491 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10492 */
10493 set_nlink(inode, 1);
ef3b9af5 10494 d_tmpfile(dentry, inode);
32955c54 10495 unlock_new_inode(inode);
ef3b9af5 10496 mark_inode_dirty(inode);
ef3b9af5 10497out:
3a45bb20 10498 btrfs_end_transaction(trans);
32955c54
AV
10499 if (ret && inode)
10500 discard_new_inode(inode);
2ff7e61e 10501 btrfs_btree_balance_dirty(fs_info);
ef3b9af5
FM
10502 return ret;
10503}
10504
5cdc84bf 10505void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
c6100a4b 10506{
5cdc84bf 10507 struct inode *inode = tree->private_data;
c6100a4b
JB
10508 unsigned long index = start >> PAGE_SHIFT;
10509 unsigned long end_index = end >> PAGE_SHIFT;
10510 struct page *page;
10511
10512 while (index <= end_index) {
10513 page = find_get_page(inode->i_mapping, index);
10514 ASSERT(page); /* Pages should be in the extent_io_tree */
10515 set_page_writeback(page);
10516 put_page(page);
10517 index++;
10518 }
10519}
10520
ed46ff3d
OS
10521#ifdef CONFIG_SWAP
10522/*
10523 * Add an entry indicating a block group or device which is pinned by a
10524 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10525 * negative errno on failure.
10526 */
10527static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10528 bool is_block_group)
10529{
10530 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10531 struct btrfs_swapfile_pin *sp, *entry;
10532 struct rb_node **p;
10533 struct rb_node *parent = NULL;
10534
10535 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10536 if (!sp)
10537 return -ENOMEM;
10538 sp->ptr = ptr;
10539 sp->inode = inode;
10540 sp->is_block_group = is_block_group;
10541
10542 spin_lock(&fs_info->swapfile_pins_lock);
10543 p = &fs_info->swapfile_pins.rb_node;
10544 while (*p) {
10545 parent = *p;
10546 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10547 if (sp->ptr < entry->ptr ||
10548 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10549 p = &(*p)->rb_left;
10550 } else if (sp->ptr > entry->ptr ||
10551 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10552 p = &(*p)->rb_right;
10553 } else {
10554 spin_unlock(&fs_info->swapfile_pins_lock);
10555 kfree(sp);
10556 return 1;
10557 }
10558 }
10559 rb_link_node(&sp->node, parent, p);
10560 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10561 spin_unlock(&fs_info->swapfile_pins_lock);
10562 return 0;
10563}
10564
10565/* Free all of the entries pinned by this swapfile. */
10566static void btrfs_free_swapfile_pins(struct inode *inode)
10567{
10568 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10569 struct btrfs_swapfile_pin *sp;
10570 struct rb_node *node, *next;
10571
10572 spin_lock(&fs_info->swapfile_pins_lock);
10573 node = rb_first(&fs_info->swapfile_pins);
10574 while (node) {
10575 next = rb_next(node);
10576 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10577 if (sp->inode == inode) {
10578 rb_erase(&sp->node, &fs_info->swapfile_pins);
10579 if (sp->is_block_group)
10580 btrfs_put_block_group(sp->ptr);
10581 kfree(sp);
10582 }
10583 node = next;
10584 }
10585 spin_unlock(&fs_info->swapfile_pins_lock);
10586}
10587
10588struct btrfs_swap_info {
10589 u64 start;
10590 u64 block_start;
10591 u64 block_len;
10592 u64 lowest_ppage;
10593 u64 highest_ppage;
10594 unsigned long nr_pages;
10595 int nr_extents;
10596};
10597
10598static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10599 struct btrfs_swap_info *bsi)
10600{
10601 unsigned long nr_pages;
10602 u64 first_ppage, first_ppage_reported, next_ppage;
10603 int ret;
10604
10605 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10606 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10607 PAGE_SIZE) >> PAGE_SHIFT;
10608
10609 if (first_ppage >= next_ppage)
10610 return 0;
10611 nr_pages = next_ppage - first_ppage;
10612
10613 first_ppage_reported = first_ppage;
10614 if (bsi->start == 0)
10615 first_ppage_reported++;
10616 if (bsi->lowest_ppage > first_ppage_reported)
10617 bsi->lowest_ppage = first_ppage_reported;
10618 if (bsi->highest_ppage < (next_ppage - 1))
10619 bsi->highest_ppage = next_ppage - 1;
10620
10621 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10622 if (ret < 0)
10623 return ret;
10624 bsi->nr_extents += ret;
10625 bsi->nr_pages += nr_pages;
10626 return 0;
10627}
10628
10629static void btrfs_swap_deactivate(struct file *file)
10630{
10631 struct inode *inode = file_inode(file);
10632
10633 btrfs_free_swapfile_pins(inode);
10634 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10635}
10636
10637static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10638 sector_t *span)
10639{
10640 struct inode *inode = file_inode(file);
10641 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10642 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10643 struct extent_state *cached_state = NULL;
10644 struct extent_map *em = NULL;
10645 struct btrfs_device *device = NULL;
10646 struct btrfs_swap_info bsi = {
10647 .lowest_ppage = (sector_t)-1ULL,
10648 };
10649 int ret = 0;
10650 u64 isize;
10651 u64 start;
10652
10653 /*
10654 * If the swap file was just created, make sure delalloc is done. If the
10655 * file changes again after this, the user is doing something stupid and
10656 * we don't really care.
10657 */
10658 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10659 if (ret)
10660 return ret;
10661
10662 /*
10663 * The inode is locked, so these flags won't change after we check them.
10664 */
10665 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10666 btrfs_warn(fs_info, "swapfile must not be compressed");
10667 return -EINVAL;
10668 }
10669 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10670 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10671 return -EINVAL;
10672 }
10673 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10674 btrfs_warn(fs_info, "swapfile must not be checksummed");
10675 return -EINVAL;
10676 }
10677
10678 /*
10679 * Balance or device remove/replace/resize can move stuff around from
10680 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10681 * concurrently while we are mapping the swap extents, and
10682 * fs_info->swapfile_pins prevents them from running while the swap file
10683 * is active and moving the extents. Note that this also prevents a
10684 * concurrent device add which isn't actually necessary, but it's not
10685 * really worth the trouble to allow it.
10686 */
10687 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10688 btrfs_warn(fs_info,
10689 "cannot activate swapfile while exclusive operation is running");
10690 return -EBUSY;
10691 }
10692 /*
10693 * Snapshots can create extents which require COW even if NODATACOW is
10694 * set. We use this counter to prevent snapshots. We must increment it
10695 * before walking the extents because we don't want a concurrent
10696 * snapshot to run after we've already checked the extents.
10697 */
10698 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10699
10700 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10701
10702 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10703 start = 0;
10704 while (start < isize) {
10705 u64 logical_block_start, physical_block_start;
10706 struct btrfs_block_group_cache *bg;
10707 u64 len = isize - start;
10708
10709 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
10710 if (IS_ERR(em)) {
10711 ret = PTR_ERR(em);
10712 goto out;
10713 }
10714
10715 if (em->block_start == EXTENT_MAP_HOLE) {
10716 btrfs_warn(fs_info, "swapfile must not have holes");
10717 ret = -EINVAL;
10718 goto out;
10719 }
10720 if (em->block_start == EXTENT_MAP_INLINE) {
10721 /*
10722 * It's unlikely we'll ever actually find ourselves
10723 * here, as a file small enough to fit inline won't be
10724 * big enough to store more than the swap header, but in
10725 * case something changes in the future, let's catch it
10726 * here rather than later.
10727 */
10728 btrfs_warn(fs_info, "swapfile must not be inline");
10729 ret = -EINVAL;
10730 goto out;
10731 }
10732 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10733 btrfs_warn(fs_info, "swapfile must not be compressed");
10734 ret = -EINVAL;
10735 goto out;
10736 }
10737
10738 logical_block_start = em->block_start + (start - em->start);
10739 len = min(len, em->len - (start - em->start));
10740 free_extent_map(em);
10741 em = NULL;
10742
10743 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10744 if (ret < 0) {
10745 goto out;
10746 } else if (ret) {
10747 ret = 0;
10748 } else {
10749 btrfs_warn(fs_info,
10750 "swapfile must not be copy-on-write");
10751 ret = -EINVAL;
10752 goto out;
10753 }
10754
10755 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10756 if (IS_ERR(em)) {
10757 ret = PTR_ERR(em);
10758 goto out;
10759 }
10760
10761 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10762 btrfs_warn(fs_info,
10763 "swapfile must have single data profile");
10764 ret = -EINVAL;
10765 goto out;
10766 }
10767
10768 if (device == NULL) {
10769 device = em->map_lookup->stripes[0].dev;
10770 ret = btrfs_add_swapfile_pin(inode, device, false);
10771 if (ret == 1)
10772 ret = 0;
10773 else if (ret)
10774 goto out;
10775 } else if (device != em->map_lookup->stripes[0].dev) {
10776 btrfs_warn(fs_info, "swapfile must be on one device");
10777 ret = -EINVAL;
10778 goto out;
10779 }
10780
10781 physical_block_start = (em->map_lookup->stripes[0].physical +
10782 (logical_block_start - em->start));
10783 len = min(len, em->len - (logical_block_start - em->start));
10784 free_extent_map(em);
10785 em = NULL;
10786
10787 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10788 if (!bg) {
10789 btrfs_warn(fs_info,
10790 "could not find block group containing swapfile");
10791 ret = -EINVAL;
10792 goto out;
10793 }
10794
10795 ret = btrfs_add_swapfile_pin(inode, bg, true);
10796 if (ret) {
10797 btrfs_put_block_group(bg);
10798 if (ret == 1)
10799 ret = 0;
10800 else
10801 goto out;
10802 }
10803
10804 if (bsi.block_len &&
10805 bsi.block_start + bsi.block_len == physical_block_start) {
10806 bsi.block_len += len;
10807 } else {
10808 if (bsi.block_len) {
10809 ret = btrfs_add_swap_extent(sis, &bsi);
10810 if (ret)
10811 goto out;
10812 }
10813 bsi.start = start;
10814 bsi.block_start = physical_block_start;
10815 bsi.block_len = len;
10816 }
10817
10818 start += len;
10819 }
10820
10821 if (bsi.block_len)
10822 ret = btrfs_add_swap_extent(sis, &bsi);
10823
10824out:
10825 if (!IS_ERR_OR_NULL(em))
10826 free_extent_map(em);
10827
10828 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10829
10830 if (ret)
10831 btrfs_swap_deactivate(file);
10832
10833 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10834
10835 if (ret)
10836 return ret;
10837
10838 if (device)
10839 sis->bdev = device->bdev;
10840 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10841 sis->max = bsi.nr_pages;
10842 sis->pages = bsi.nr_pages - 1;
10843 sis->highest_bit = bsi.nr_pages - 1;
10844 return bsi.nr_extents;
10845}
10846#else
10847static void btrfs_swap_deactivate(struct file *file)
10848{
10849}
10850
10851static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10852 sector_t *span)
10853{
10854 return -EOPNOTSUPP;
10855}
10856#endif
10857
6e1d5dcc 10858static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 10859 .getattr = btrfs_getattr,
39279cc3
CM
10860 .lookup = btrfs_lookup,
10861 .create = btrfs_create,
10862 .unlink = btrfs_unlink,
10863 .link = btrfs_link,
10864 .mkdir = btrfs_mkdir,
10865 .rmdir = btrfs_rmdir,
2773bf00 10866 .rename = btrfs_rename2,
39279cc3
CM
10867 .symlink = btrfs_symlink,
10868 .setattr = btrfs_setattr,
618e21d5 10869 .mknod = btrfs_mknod,
5103e947 10870 .listxattr = btrfs_listxattr,
fdebe2bd 10871 .permission = btrfs_permission,
4e34e719 10872 .get_acl = btrfs_get_acl,
996a710d 10873 .set_acl = btrfs_set_acl,
93fd63c2 10874 .update_time = btrfs_update_time,
ef3b9af5 10875 .tmpfile = btrfs_tmpfile,
39279cc3 10876};
6e1d5dcc 10877static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 10878 .lookup = btrfs_lookup,
fdebe2bd 10879 .permission = btrfs_permission,
93fd63c2 10880 .update_time = btrfs_update_time,
39279cc3 10881};
76dda93c 10882
828c0950 10883static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
10884 .llseek = generic_file_llseek,
10885 .read = generic_read_dir,
02dbfc99 10886 .iterate_shared = btrfs_real_readdir,
23b5ec74 10887 .open = btrfs_opendir,
34287aa3 10888 .unlocked_ioctl = btrfs_ioctl,
39279cc3 10889#ifdef CONFIG_COMPAT
4c63c245 10890 .compat_ioctl = btrfs_compat_ioctl,
39279cc3 10891#endif
6bf13c0c 10892 .release = btrfs_release_file,
e02119d5 10893 .fsync = btrfs_sync_file,
39279cc3
CM
10894};
10895
20e5506b 10896static const struct extent_io_ops btrfs_extent_io_ops = {
4d53dddb 10897 /* mandatory callbacks */
065631f6 10898 .submit_bio_hook = btrfs_submit_bio_hook,
07157aac
CM
10899 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10900};
10901
35054394
CM
10902/*
10903 * btrfs doesn't support the bmap operation because swapfiles
10904 * use bmap to make a mapping of extents in the file. They assume
10905 * these extents won't change over the life of the file and they
10906 * use the bmap result to do IO directly to the drive.
10907 *
10908 * the btrfs bmap call would return logical addresses that aren't
10909 * suitable for IO and they also will change frequently as COW
10910 * operations happen. So, swapfile + btrfs == corruption.
10911 *
10912 * For now we're avoiding this by dropping bmap.
10913 */
7f09410b 10914static const struct address_space_operations btrfs_aops = {
39279cc3
CM
10915 .readpage = btrfs_readpage,
10916 .writepage = btrfs_writepage,
b293f02e 10917 .writepages = btrfs_writepages,
3ab2fb5a 10918 .readpages = btrfs_readpages,
16432985 10919 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
10920 .invalidatepage = btrfs_invalidatepage,
10921 .releasepage = btrfs_releasepage,
e6dcd2dc 10922 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 10923 .error_remove_page = generic_error_remove_page,
ed46ff3d
OS
10924 .swap_activate = btrfs_swap_activate,
10925 .swap_deactivate = btrfs_swap_deactivate,
39279cc3
CM
10926};
10927
6e1d5dcc 10928static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
10929 .getattr = btrfs_getattr,
10930 .setattr = btrfs_setattr,
5103e947 10931 .listxattr = btrfs_listxattr,
fdebe2bd 10932 .permission = btrfs_permission,
1506fcc8 10933 .fiemap = btrfs_fiemap,
4e34e719 10934 .get_acl = btrfs_get_acl,
996a710d 10935 .set_acl = btrfs_set_acl,
e41f941a 10936 .update_time = btrfs_update_time,
39279cc3 10937};
6e1d5dcc 10938static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
10939 .getattr = btrfs_getattr,
10940 .setattr = btrfs_setattr,
fdebe2bd 10941 .permission = btrfs_permission,
33268eaf 10942 .listxattr = btrfs_listxattr,
4e34e719 10943 .get_acl = btrfs_get_acl,
996a710d 10944 .set_acl = btrfs_set_acl,
e41f941a 10945 .update_time = btrfs_update_time,
618e21d5 10946};
6e1d5dcc 10947static const struct inode_operations btrfs_symlink_inode_operations = {
6b255391 10948 .get_link = page_get_link,
f209561a 10949 .getattr = btrfs_getattr,
22c44fe6 10950 .setattr = btrfs_setattr,
fdebe2bd 10951 .permission = btrfs_permission,
0279b4cd 10952 .listxattr = btrfs_listxattr,
e41f941a 10953 .update_time = btrfs_update_time,
39279cc3 10954};
76dda93c 10955
82d339d9 10956const struct dentry_operations btrfs_dentry_operations = {
76dda93c
YZ
10957 .d_delete = btrfs_dentry_delete,
10958};