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