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