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