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