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