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