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