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