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