btrfs: remove stale prototype of btrfs_write_inode
[linux-block.git] / fs / btrfs / file.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
39279cc3
CM
6#include <linux/fs.h>
7#include <linux/pagemap.h>
39279cc3
CM
8#include <linux/time.h>
9#include <linux/init.h>
10#include <linux/string.h>
39279cc3 11#include <linux/backing-dev.h>
2fe17c10 12#include <linux/falloc.h>
39279cc3 13#include <linux/writeback.h>
39279cc3 14#include <linux/compat.h>
5a0e3ad6 15#include <linux/slab.h>
55e301fd 16#include <linux/btrfs.h>
e2e40f2c 17#include <linux/uio.h>
ae5e165d 18#include <linux/iversion.h>
14605409 19#include <linux/fsverity.h>
39279cc3
CM
20#include "ctree.h"
21#include "disk-io.h"
22#include "transaction.h"
23#include "btrfs_inode.h"
39279cc3 24#include "print-tree.h"
e02119d5
CM
25#include "tree-log.h"
26#include "locking.h"
2aaa6655 27#include "volumes.h"
fcebe456 28#include "qgroup.h"
ebb8765b 29#include "compression.h"
86736342 30#include "delalloc-space.h"
6a177381 31#include "reflink.h"
f02a85d2 32#include "subpage.h"
39279cc3 33
9247f317 34static struct kmem_cache *btrfs_inode_defrag_cachep;
4cb5300b
CM
35/*
36 * when auto defrag is enabled we
37 * queue up these defrag structs to remember which
38 * inodes need defragging passes
39 */
40struct inode_defrag {
41 struct rb_node rb_node;
42 /* objectid */
43 u64 ino;
44 /*
45 * transid where the defrag was added, we search for
46 * extents newer than this
47 */
48 u64 transid;
49
50 /* root objectid */
51 u64 root;
558732df
QW
52
53 /*
54 * The extent size threshold for autodefrag.
55 *
56 * This value is different for compressed/non-compressed extents,
57 * thus needs to be passed from higher layer.
58 * (aka, inode_should_defrag())
59 */
60 u32 extent_thresh;
4cb5300b
CM
61};
62
762f2263
MX
63static int __compare_inode_defrag(struct inode_defrag *defrag1,
64 struct inode_defrag *defrag2)
65{
66 if (defrag1->root > defrag2->root)
67 return 1;
68 else if (defrag1->root < defrag2->root)
69 return -1;
70 else if (defrag1->ino > defrag2->ino)
71 return 1;
72 else if (defrag1->ino < defrag2->ino)
73 return -1;
74 else
75 return 0;
76}
77
4cb5300b
CM
78/* pop a record for an inode into the defrag tree. The lock
79 * must be held already
80 *
81 * If you're inserting a record for an older transid than an
82 * existing record, the transid already in the tree is lowered
83 *
84 * If an existing record is found the defrag item you
85 * pass in is freed
86 */
6158e1ce 87static int __btrfs_add_inode_defrag(struct btrfs_inode *inode,
4cb5300b
CM
88 struct inode_defrag *defrag)
89{
3ffbd68c 90 struct btrfs_fs_info *fs_info = inode->root->fs_info;
4cb5300b
CM
91 struct inode_defrag *entry;
92 struct rb_node **p;
93 struct rb_node *parent = NULL;
762f2263 94 int ret;
4cb5300b 95
0b246afa 96 p = &fs_info->defrag_inodes.rb_node;
4cb5300b
CM
97 while (*p) {
98 parent = *p;
99 entry = rb_entry(parent, struct inode_defrag, rb_node);
100
762f2263
MX
101 ret = __compare_inode_defrag(defrag, entry);
102 if (ret < 0)
4cb5300b 103 p = &parent->rb_left;
762f2263 104 else if (ret > 0)
4cb5300b
CM
105 p = &parent->rb_right;
106 else {
107 /* if we're reinserting an entry for
108 * an old defrag run, make sure to
109 * lower the transid of our existing record
110 */
111 if (defrag->transid < entry->transid)
112 entry->transid = defrag->transid;
558732df
QW
113 entry->extent_thresh = min(defrag->extent_thresh,
114 entry->extent_thresh);
8ddc4734 115 return -EEXIST;
4cb5300b
CM
116 }
117 }
6158e1ce 118 set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
4cb5300b 119 rb_link_node(&defrag->rb_node, parent, p);
0b246afa 120 rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
8ddc4734
MX
121 return 0;
122}
4cb5300b 123
2ff7e61e 124static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info)
8ddc4734 125{
0b246afa 126 if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
8ddc4734
MX
127 return 0;
128
0b246afa 129 if (btrfs_fs_closing(fs_info))
8ddc4734 130 return 0;
4cb5300b 131
8ddc4734 132 return 1;
4cb5300b
CM
133}
134
135/*
136 * insert a defrag record for this inode if auto defrag is
137 * enabled
138 */
139int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
558732df 140 struct btrfs_inode *inode, u32 extent_thresh)
4cb5300b 141{
6158e1ce 142 struct btrfs_root *root = inode->root;
3ffbd68c 143 struct btrfs_fs_info *fs_info = root->fs_info;
4cb5300b 144 struct inode_defrag *defrag;
4cb5300b 145 u64 transid;
8ddc4734 146 int ret;
4cb5300b 147
2ff7e61e 148 if (!__need_auto_defrag(fs_info))
4cb5300b
CM
149 return 0;
150
6158e1ce 151 if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
4cb5300b
CM
152 return 0;
153
154 if (trans)
155 transid = trans->transid;
156 else
6158e1ce 157 transid = inode->root->last_trans;
4cb5300b 158
9247f317 159 defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
4cb5300b
CM
160 if (!defrag)
161 return -ENOMEM;
162
6158e1ce 163 defrag->ino = btrfs_ino(inode);
4cb5300b
CM
164 defrag->transid = transid;
165 defrag->root = root->root_key.objectid;
558732df 166 defrag->extent_thresh = extent_thresh;
4cb5300b 167
0b246afa 168 spin_lock(&fs_info->defrag_inodes_lock);
6158e1ce 169 if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) {
8ddc4734
MX
170 /*
171 * If we set IN_DEFRAG flag and evict the inode from memory,
172 * and then re-read this inode, this new inode doesn't have
173 * IN_DEFRAG flag. At the case, we may find the existed defrag.
174 */
175 ret = __btrfs_add_inode_defrag(inode, defrag);
176 if (ret)
177 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
178 } else {
9247f317 179 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
8ddc4734 180 }
0b246afa 181 spin_unlock(&fs_info->defrag_inodes_lock);
a0f98dde 182 return 0;
4cb5300b
CM
183}
184
185/*
26176e7c
MX
186 * pick the defragable inode that we want, if it doesn't exist, we will get
187 * the next one.
4cb5300b 188 */
26176e7c
MX
189static struct inode_defrag *
190btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
4cb5300b
CM
191{
192 struct inode_defrag *entry = NULL;
762f2263 193 struct inode_defrag tmp;
4cb5300b
CM
194 struct rb_node *p;
195 struct rb_node *parent = NULL;
762f2263
MX
196 int ret;
197
198 tmp.ino = ino;
199 tmp.root = root;
4cb5300b 200
26176e7c
MX
201 spin_lock(&fs_info->defrag_inodes_lock);
202 p = fs_info->defrag_inodes.rb_node;
4cb5300b
CM
203 while (p) {
204 parent = p;
205 entry = rb_entry(parent, struct inode_defrag, rb_node);
206
762f2263
MX
207 ret = __compare_inode_defrag(&tmp, entry);
208 if (ret < 0)
4cb5300b 209 p = parent->rb_left;
762f2263 210 else if (ret > 0)
4cb5300b
CM
211 p = parent->rb_right;
212 else
26176e7c 213 goto out;
4cb5300b
CM
214 }
215
26176e7c
MX
216 if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
217 parent = rb_next(parent);
218 if (parent)
4cb5300b 219 entry = rb_entry(parent, struct inode_defrag, rb_node);
26176e7c
MX
220 else
221 entry = NULL;
4cb5300b 222 }
26176e7c
MX
223out:
224 if (entry)
225 rb_erase(parent, &fs_info->defrag_inodes);
226 spin_unlock(&fs_info->defrag_inodes_lock);
227 return entry;
4cb5300b
CM
228}
229
26176e7c 230void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
4cb5300b
CM
231{
232 struct inode_defrag *defrag;
26176e7c
MX
233 struct rb_node *node;
234
235 spin_lock(&fs_info->defrag_inodes_lock);
236 node = rb_first(&fs_info->defrag_inodes);
237 while (node) {
238 rb_erase(node, &fs_info->defrag_inodes);
239 defrag = rb_entry(node, struct inode_defrag, rb_node);
240 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
241
351810c1 242 cond_resched_lock(&fs_info->defrag_inodes_lock);
26176e7c
MX
243
244 node = rb_first(&fs_info->defrag_inodes);
245 }
246 spin_unlock(&fs_info->defrag_inodes_lock);
247}
248
249#define BTRFS_DEFRAG_BATCH 1024
250
251static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
252 struct inode_defrag *defrag)
253{
4cb5300b
CM
254 struct btrfs_root *inode_root;
255 struct inode *inode;
4cb5300b 256 struct btrfs_ioctl_defrag_range_args range;
26fbac25
QW
257 int ret = 0;
258 u64 cur = 0;
259
260again:
261 if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
262 goto cleanup;
263 if (!__need_auto_defrag(fs_info))
264 goto cleanup;
4cb5300b 265
26176e7c 266 /* get the inode */
56e9357a 267 inode_root = btrfs_get_fs_root(fs_info, defrag->root, true);
26176e7c 268 if (IS_ERR(inode_root)) {
6f1c3605
LB
269 ret = PTR_ERR(inode_root);
270 goto cleanup;
271 }
26176e7c 272
0202e83f 273 inode = btrfs_iget(fs_info->sb, defrag->ino, inode_root);
00246528 274 btrfs_put_root(inode_root);
26176e7c 275 if (IS_ERR(inode)) {
6f1c3605
LB
276 ret = PTR_ERR(inode);
277 goto cleanup;
26176e7c
MX
278 }
279
26fbac25
QW
280 if (cur >= i_size_read(inode)) {
281 iput(inode);
282 goto cleanup;
283 }
284
26176e7c
MX
285 /* do a chunk of defrag */
286 clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
4cb5300b
CM
287 memset(&range, 0, sizeof(range));
288 range.len = (u64)-1;
26fbac25 289 range.start = cur;
558732df 290 range.extent_thresh = defrag->extent_thresh;
b66f00da
MX
291
292 sb_start_write(fs_info->sb);
26fbac25 293 ret = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
26176e7c 294 BTRFS_DEFRAG_BATCH);
b66f00da 295 sb_end_write(fs_info->sb);
26176e7c 296 iput(inode);
26fbac25
QW
297
298 if (ret < 0)
299 goto cleanup;
300
301 cur = max(cur + fs_info->sectorsize, range.start);
302 goto again;
303
6f1c3605 304cleanup:
6f1c3605
LB
305 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
306 return ret;
26176e7c
MX
307}
308
309/*
310 * run through the list of inodes in the FS that need
311 * defragging
312 */
313int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
314{
315 struct inode_defrag *defrag;
316 u64 first_ino = 0;
317 u64 root_objectid = 0;
4cb5300b
CM
318
319 atomic_inc(&fs_info->defrag_running);
67871254 320 while (1) {
dc81cdc5
MX
321 /* Pause the auto defragger. */
322 if (test_bit(BTRFS_FS_STATE_REMOUNTING,
323 &fs_info->fs_state))
324 break;
325
2ff7e61e 326 if (!__need_auto_defrag(fs_info))
26176e7c 327 break;
4cb5300b
CM
328
329 /* find an inode to defrag */
26176e7c
MX
330 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
331 first_ino);
4cb5300b 332 if (!defrag) {
26176e7c 333 if (root_objectid || first_ino) {
762f2263 334 root_objectid = 0;
4cb5300b
CM
335 first_ino = 0;
336 continue;
337 } else {
338 break;
339 }
340 }
341
4cb5300b 342 first_ino = defrag->ino + 1;
762f2263 343 root_objectid = defrag->root;
4cb5300b 344
26176e7c 345 __btrfs_run_defrag_inode(fs_info, defrag);
4cb5300b 346 }
4cb5300b
CM
347 atomic_dec(&fs_info->defrag_running);
348
349 /*
350 * during unmount, we use the transaction_wait queue to
351 * wait for the defragger to stop
352 */
353 wake_up(&fs_info->transaction_wait);
354 return 0;
355}
39279cc3 356
d352ac68
CM
357/* simple helper to fault in pages and copy. This should go away
358 * and be replaced with calls into generic code.
359 */
ee22f0c4 360static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes,
a1b32a59 361 struct page **prepared_pages,
11c65dcc 362 struct iov_iter *i)
39279cc3 363{
914ee295 364 size_t copied = 0;
d0215f3e 365 size_t total_copied = 0;
11c65dcc 366 int pg = 0;
7073017a 367 int offset = offset_in_page(pos);
39279cc3 368
11c65dcc 369 while (write_bytes > 0) {
39279cc3 370 size_t count = min_t(size_t,
09cbfeaf 371 PAGE_SIZE - offset, write_bytes);
11c65dcc 372 struct page *page = prepared_pages[pg];
914ee295
XZ
373 /*
374 * Copy data from userspace to the current page
914ee295 375 */
f0b65f39 376 copied = copy_page_from_iter_atomic(page, offset, count, i);
11c65dcc 377
39279cc3
CM
378 /* Flush processor's dcache for this page */
379 flush_dcache_page(page);
31339acd
CM
380
381 /*
382 * if we get a partial write, we can end up with
383 * partially up to date pages. These add
384 * a lot of complexity, so make sure they don't
385 * happen by forcing this copy to be retried.
386 *
387 * The rest of the btrfs_file_write code will fall
388 * back to page at a time copies after we return 0.
389 */
f0b65f39
AV
390 if (unlikely(copied < count)) {
391 if (!PageUptodate(page)) {
392 iov_iter_revert(i, copied);
393 copied = 0;
394 }
395 if (!copied)
396 break;
397 }
31339acd 398
11c65dcc 399 write_bytes -= copied;
914ee295 400 total_copied += copied;
f0b65f39
AV
401 offset += copied;
402 if (offset == PAGE_SIZE) {
11c65dcc
JB
403 pg++;
404 offset = 0;
405 }
39279cc3 406 }
914ee295 407 return total_copied;
39279cc3
CM
408}
409
d352ac68
CM
410/*
411 * unlocks pages after btrfs_file_write is done with them
412 */
e4f94347
QW
413static void btrfs_drop_pages(struct btrfs_fs_info *fs_info,
414 struct page **pages, size_t num_pages,
415 u64 pos, u64 copied)
39279cc3
CM
416{
417 size_t i;
e4f94347
QW
418 u64 block_start = round_down(pos, fs_info->sectorsize);
419 u64 block_len = round_up(pos + copied, fs_info->sectorsize) - block_start;
420
421 ASSERT(block_len <= U32_MAX);
39279cc3 422 for (i = 0; i < num_pages; i++) {
d352ac68
CM
423 /* page checked is some magic around finding pages that
424 * have been modified without going through btrfs_set_page_dirty
2457aec6
MG
425 * clear it here. There should be no need to mark the pages
426 * accessed as prepare_pages should have marked them accessed
427 * in prepare_pages via find_or_create_page()
d352ac68 428 */
e4f94347
QW
429 btrfs_page_clamp_clear_checked(fs_info, pages[i], block_start,
430 block_len);
39279cc3 431 unlock_page(pages[i]);
09cbfeaf 432 put_page(pages[i]);
39279cc3
CM
433 }
434}
435
d352ac68 436/*
c0fab480
QW
437 * After btrfs_copy_from_user(), update the following things for delalloc:
438 * - Mark newly dirtied pages as DELALLOC in the io tree.
439 * Used to advise which range is to be written back.
440 * - Mark modified pages as Uptodate/Dirty and not needing COW fixup
441 * - Update inode size for past EOF write
d352ac68 442 */
088545f6 443int btrfs_dirty_pages(struct btrfs_inode *inode, struct page **pages,
2ff7e61e 444 size_t num_pages, loff_t pos, size_t write_bytes,
aa8c1a41 445 struct extent_state **cached, bool noreserve)
39279cc3 446{
088545f6 447 struct btrfs_fs_info *fs_info = inode->root->fs_info;
39279cc3 448 int err = 0;
a52d9a80 449 int i;
db94535d 450 u64 num_bytes;
a52d9a80
CM
451 u64 start_pos;
452 u64 end_of_last_block;
453 u64 end_pos = pos + write_bytes;
088545f6 454 loff_t isize = i_size_read(&inode->vfs_inode);
e3b8a485 455 unsigned int extra_bits = 0;
39279cc3 456
aa8c1a41
GR
457 if (write_bytes == 0)
458 return 0;
459
460 if (noreserve)
461 extra_bits |= EXTENT_NORESERVE;
462
13f0dd8f 463 start_pos = round_down(pos, fs_info->sectorsize);
da17066c 464 num_bytes = round_up(write_bytes + pos - start_pos,
0b246afa 465 fs_info->sectorsize);
f02a85d2 466 ASSERT(num_bytes <= U32_MAX);
39279cc3 467
db94535d 468 end_of_last_block = start_pos + num_bytes - 1;
e3b8a485 469
7703bdd8
CM
470 /*
471 * The pages may have already been dirty, clear out old accounting so
472 * we can set things up properly
473 */
088545f6 474 clear_extent_bit(&inode->io_tree, start_pos, end_of_last_block,
e182163d 475 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
bd015294 476 cached);
7703bdd8 477
088545f6 478 err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
330a5827 479 extra_bits, cached);
d0215f3e
JB
480 if (err)
481 return err;
9ed74f2d 482
c8b97818
CM
483 for (i = 0; i < num_pages; i++) {
484 struct page *p = pages[i];
f02a85d2
QW
485
486 btrfs_page_clamp_set_uptodate(fs_info, p, start_pos, num_bytes);
e4f94347 487 btrfs_page_clamp_clear_checked(fs_info, p, start_pos, num_bytes);
f02a85d2 488 btrfs_page_clamp_set_dirty(fs_info, p, start_pos, num_bytes);
a52d9a80 489 }
9f570b8d
JB
490
491 /*
492 * we've only changed i_size in ram, and we haven't updated
493 * the disk i_size. There is no need to log the inode
494 * at this time.
495 */
496 if (end_pos > isize)
088545f6 497 i_size_write(&inode->vfs_inode, end_pos);
a22285a6 498 return 0;
39279cc3
CM
499}
500
d352ac68
CM
501/*
502 * this drops all the extents in the cache that intersect the range
503 * [start, end]. Existing extents are split as required.
504 */
dcdbc059 505void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end,
7014cdb4 506 int skip_pinned)
a52d9a80
CM
507{
508 struct extent_map *em;
3b951516
CM
509 struct extent_map *split = NULL;
510 struct extent_map *split2 = NULL;
dcdbc059 511 struct extent_map_tree *em_tree = &inode->extent_tree;
39b5637f 512 u64 len = end - start + 1;
5dc562c5 513 u64 gen;
3b951516
CM
514 int ret;
515 int testend = 1;
5b21f2ed 516 unsigned long flags;
c8b97818 517 int compressed = 0;
09a2a8f9 518 bool modified;
a52d9a80 519
e6dcd2dc 520 WARN_ON(end < start);
3b951516 521 if (end == (u64)-1) {
39b5637f 522 len = (u64)-1;
3b951516
CM
523 testend = 0;
524 }
d397712b 525 while (1) {
7014cdb4
JB
526 int no_splits = 0;
527
09a2a8f9 528 modified = false;
3b951516 529 if (!split)
172ddd60 530 split = alloc_extent_map();
3b951516 531 if (!split2)
172ddd60 532 split2 = alloc_extent_map();
7014cdb4
JB
533 if (!split || !split2)
534 no_splits = 1;
3b951516 535
890871be 536 write_lock(&em_tree->lock);
39b5637f 537 em = lookup_extent_mapping(em_tree, start, len);
d1310b2e 538 if (!em) {
890871be 539 write_unlock(&em_tree->lock);
a52d9a80 540 break;
d1310b2e 541 }
5b21f2ed 542 flags = em->flags;
5dc562c5 543 gen = em->generation;
5b21f2ed 544 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
55ef6899 545 if (testend && em->start + em->len >= start + len) {
5b21f2ed 546 free_extent_map(em);
a1ed835e 547 write_unlock(&em_tree->lock);
5b21f2ed
ZY
548 break;
549 }
55ef6899
YZ
550 start = em->start + em->len;
551 if (testend)
5b21f2ed 552 len = start + len - (em->start + em->len);
5b21f2ed 553 free_extent_map(em);
a1ed835e 554 write_unlock(&em_tree->lock);
5b21f2ed
ZY
555 continue;
556 }
c8b97818 557 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
3ce7e67a 558 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
3b277594 559 clear_bit(EXTENT_FLAG_LOGGING, &flags);
09a2a8f9 560 modified = !list_empty(&em->list);
7014cdb4
JB
561 if (no_splits)
562 goto next;
3b951516 563
ee20a983 564 if (em->start < start) {
3b951516
CM
565 split->start = em->start;
566 split->len = start - em->start;
ee20a983
JB
567
568 if (em->block_start < EXTENT_MAP_LAST_BYTE) {
569 split->orig_start = em->orig_start;
570 split->block_start = em->block_start;
571
572 if (compressed)
573 split->block_len = em->block_len;
574 else
575 split->block_len = split->len;
576 split->orig_block_len = max(split->block_len,
577 em->orig_block_len);
578 split->ram_bytes = em->ram_bytes;
579 } else {
580 split->orig_start = split->start;
581 split->block_len = 0;
582 split->block_start = em->block_start;
583 split->orig_block_len = 0;
584 split->ram_bytes = split->len;
585 }
586
5dc562c5 587 split->generation = gen;
5b21f2ed 588 split->flags = flags;
261507a0 589 split->compress_type = em->compress_type;
176840b3 590 replace_extent_mapping(em_tree, em, split, modified);
3b951516
CM
591 free_extent_map(split);
592 split = split2;
593 split2 = NULL;
594 }
ee20a983 595 if (testend && em->start + em->len > start + len) {
3b951516
CM
596 u64 diff = start + len - em->start;
597
598 split->start = start + len;
599 split->len = em->start + em->len - (start + len);
5b21f2ed 600 split->flags = flags;
261507a0 601 split->compress_type = em->compress_type;
5dc562c5 602 split->generation = gen;
ee20a983
JB
603
604 if (em->block_start < EXTENT_MAP_LAST_BYTE) {
605 split->orig_block_len = max(em->block_len,
b4939680 606 em->orig_block_len);
3b951516 607
ee20a983
JB
608 split->ram_bytes = em->ram_bytes;
609 if (compressed) {
610 split->block_len = em->block_len;
611 split->block_start = em->block_start;
612 split->orig_start = em->orig_start;
613 } else {
614 split->block_len = split->len;
615 split->block_start = em->block_start
616 + diff;
617 split->orig_start = em->orig_start;
618 }
c8b97818 619 } else {
ee20a983
JB
620 split->ram_bytes = split->len;
621 split->orig_start = split->start;
622 split->block_len = 0;
623 split->block_start = em->block_start;
624 split->orig_block_len = 0;
c8b97818 625 }
3b951516 626
176840b3
FM
627 if (extent_map_in_tree(em)) {
628 replace_extent_mapping(em_tree, em, split,
629 modified);
630 } else {
631 ret = add_extent_mapping(em_tree, split,
632 modified);
633 ASSERT(ret == 0); /* Logic error */
634 }
3b951516
CM
635 free_extent_map(split);
636 split = NULL;
637 }
7014cdb4 638next:
176840b3
FM
639 if (extent_map_in_tree(em))
640 remove_extent_mapping(em_tree, em);
890871be 641 write_unlock(&em_tree->lock);
d1310b2e 642
a52d9a80
CM
643 /* once for us */
644 free_extent_map(em);
645 /* once for the tree*/
646 free_extent_map(em);
647 }
3b951516
CM
648 if (split)
649 free_extent_map(split);
650 if (split2)
651 free_extent_map(split2);
a52d9a80
CM
652}
653
39279cc3
CM
654/*
655 * this is very complex, but the basic idea is to drop all extents
656 * in the range start - end. hint_block is filled in with a block number
657 * that would be a good hint to the block allocator for this file.
658 *
659 * If an extent intersects the range but is not entirely inside the range
660 * it is either truncated or split. Anything entirely inside the range
661 * is deleted from the tree.
2766ff61
FM
662 *
663 * Note: the VFS' inode number of bytes is not updated, it's up to the caller
664 * to deal with that. We set the field 'bytes_found' of the arguments structure
665 * with the number of allocated bytes found in the target range, so that the
666 * caller can update the inode's number of bytes in an atomic way when
667 * replacing extents in a range to avoid races with stat(2).
39279cc3 668 */
5893dfb9
FM
669int btrfs_drop_extents(struct btrfs_trans_handle *trans,
670 struct btrfs_root *root, struct btrfs_inode *inode,
671 struct btrfs_drop_extents_args *args)
39279cc3 672{
0b246afa 673 struct btrfs_fs_info *fs_info = root->fs_info;
5f39d397 674 struct extent_buffer *leaf;
920bbbfb 675 struct btrfs_file_extent_item *fi;
82fa113f 676 struct btrfs_ref ref = { 0 };
00f5c795 677 struct btrfs_key key;
920bbbfb 678 struct btrfs_key new_key;
906c448c 679 u64 ino = btrfs_ino(inode);
5893dfb9 680 u64 search_start = args->start;
920bbbfb
YZ
681 u64 disk_bytenr = 0;
682 u64 num_bytes = 0;
683 u64 extent_offset = 0;
684 u64 extent_end = 0;
5893dfb9 685 u64 last_end = args->start;
920bbbfb
YZ
686 int del_nr = 0;
687 int del_slot = 0;
688 int extent_type;
ccd467d6 689 int recow;
00f5c795 690 int ret;
dc7fdde3 691 int modify_tree = -1;
27cdeb70 692 int update_refs;
c3308f84 693 int found = 0;
5893dfb9
FM
694 struct btrfs_path *path = args->path;
695
2766ff61 696 args->bytes_found = 0;
5893dfb9
FM
697 args->extent_inserted = false;
698
699 /* Must always have a path if ->replace_extent is true */
700 ASSERT(!(args->replace_extent && !args->path));
701
702 if (!path) {
703 path = btrfs_alloc_path();
704 if (!path) {
705 ret = -ENOMEM;
706 goto out;
707 }
708 }
39279cc3 709
5893dfb9
FM
710 if (args->drop_cache)
711 btrfs_drop_extent_cache(inode, args->start, args->end - 1, 0);
a52d9a80 712
5893dfb9 713 if (args->start >= inode->disk_i_size && !args->replace_extent)
dc7fdde3
CM
714 modify_tree = 0;
715
d175209b 716 update_refs = (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID);
d397712b 717 while (1) {
ccd467d6 718 recow = 0;
33345d01 719 ret = btrfs_lookup_file_extent(trans, root, path, ino,
dc7fdde3 720 search_start, modify_tree);
39279cc3 721 if (ret < 0)
920bbbfb 722 break;
5893dfb9 723 if (ret > 0 && path->slots[0] > 0 && search_start == args->start) {
920bbbfb
YZ
724 leaf = path->nodes[0];
725 btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
33345d01 726 if (key.objectid == ino &&
920bbbfb
YZ
727 key.type == BTRFS_EXTENT_DATA_KEY)
728 path->slots[0]--;
39279cc3 729 }
920bbbfb 730 ret = 0;
8c2383c3 731next_slot:
5f39d397 732 leaf = path->nodes[0];
920bbbfb
YZ
733 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
734 BUG_ON(del_nr > 0);
735 ret = btrfs_next_leaf(root, path);
736 if (ret < 0)
737 break;
738 if (ret > 0) {
739 ret = 0;
740 break;
8c2383c3 741 }
920bbbfb
YZ
742 leaf = path->nodes[0];
743 recow = 1;
744 }
745
746 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
aeafbf84
FM
747
748 if (key.objectid > ino)
749 break;
750 if (WARN_ON_ONCE(key.objectid < ino) ||
751 key.type < BTRFS_EXTENT_DATA_KEY) {
752 ASSERT(del_nr == 0);
753 path->slots[0]++;
754 goto next_slot;
755 }
5893dfb9 756 if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end)
920bbbfb
YZ
757 break;
758
759 fi = btrfs_item_ptr(leaf, path->slots[0],
760 struct btrfs_file_extent_item);
761 extent_type = btrfs_file_extent_type(leaf, fi);
762
763 if (extent_type == BTRFS_FILE_EXTENT_REG ||
764 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
765 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
766 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
767 extent_offset = btrfs_file_extent_offset(leaf, fi);
768 extent_end = key.offset +
769 btrfs_file_extent_num_bytes(leaf, fi);
770 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
771 extent_end = key.offset +
e41ca589 772 btrfs_file_extent_ram_bytes(leaf, fi);
8c2383c3 773 } else {
aeafbf84
FM
774 /* can't happen */
775 BUG();
39279cc3
CM
776 }
777
fc19c5e7
FM
778 /*
779 * Don't skip extent items representing 0 byte lengths. They
780 * used to be created (bug) if while punching holes we hit
781 * -ENOSPC condition. So if we find one here, just ensure we
782 * delete it, otherwise we would insert a new file extent item
783 * with the same key (offset) as that 0 bytes length file
784 * extent item in the call to setup_items_for_insert() later
785 * in this function.
786 */
62fe51c1
JB
787 if (extent_end == key.offset && extent_end >= search_start) {
788 last_end = extent_end;
fc19c5e7 789 goto delete_extent_item;
62fe51c1 790 }
fc19c5e7 791
920bbbfb
YZ
792 if (extent_end <= search_start) {
793 path->slots[0]++;
8c2383c3 794 goto next_slot;
39279cc3
CM
795 }
796
c3308f84 797 found = 1;
5893dfb9 798 search_start = max(key.offset, args->start);
dc7fdde3
CM
799 if (recow || !modify_tree) {
800 modify_tree = -1;
b3b4aa74 801 btrfs_release_path(path);
920bbbfb 802 continue;
39279cc3 803 }
6643558d 804
920bbbfb
YZ
805 /*
806 * | - range to drop - |
807 * | -------- extent -------- |
808 */
5893dfb9 809 if (args->start > key.offset && args->end < extent_end) {
920bbbfb 810 BUG_ON(del_nr > 0);
00fdf13a 811 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3f9e3df8 812 ret = -EOPNOTSUPP;
00fdf13a
LB
813 break;
814 }
920bbbfb
YZ
815
816 memcpy(&new_key, &key, sizeof(new_key));
5893dfb9 817 new_key.offset = args->start;
920bbbfb
YZ
818 ret = btrfs_duplicate_item(trans, root, path,
819 &new_key);
820 if (ret == -EAGAIN) {
b3b4aa74 821 btrfs_release_path(path);
920bbbfb 822 continue;
6643558d 823 }
920bbbfb
YZ
824 if (ret < 0)
825 break;
826
827 leaf = path->nodes[0];
828 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
829 struct btrfs_file_extent_item);
830 btrfs_set_file_extent_num_bytes(leaf, fi,
5893dfb9 831 args->start - key.offset);
920bbbfb
YZ
832
833 fi = btrfs_item_ptr(leaf, path->slots[0],
834 struct btrfs_file_extent_item);
835
5893dfb9 836 extent_offset += args->start - key.offset;
920bbbfb
YZ
837 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
838 btrfs_set_file_extent_num_bytes(leaf, fi,
5893dfb9 839 extent_end - args->start);
920bbbfb
YZ
840 btrfs_mark_buffer_dirty(leaf);
841
5dc562c5 842 if (update_refs && disk_bytenr > 0) {
82fa113f
QW
843 btrfs_init_generic_ref(&ref,
844 BTRFS_ADD_DELAYED_REF,
845 disk_bytenr, num_bytes, 0);
846 btrfs_init_data_ref(&ref,
920bbbfb
YZ
847 root->root_key.objectid,
848 new_key.objectid,
f42c5da6
NB
849 args->start - extent_offset,
850 0, false);
82fa113f 851 ret = btrfs_inc_extent_ref(trans, &ref);
79787eaa 852 BUG_ON(ret); /* -ENOMEM */
771ed689 853 }
5893dfb9 854 key.offset = args->start;
6643558d 855 }
62fe51c1
JB
856 /*
857 * From here on out we will have actually dropped something, so
858 * last_end can be updated.
859 */
860 last_end = extent_end;
861
920bbbfb
YZ
862 /*
863 * | ---- range to drop ----- |
864 * | -------- extent -------- |
865 */
5893dfb9 866 if (args->start <= key.offset && args->end < extent_end) {
00fdf13a 867 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3f9e3df8 868 ret = -EOPNOTSUPP;
00fdf13a
LB
869 break;
870 }
6643558d 871
920bbbfb 872 memcpy(&new_key, &key, sizeof(new_key));
5893dfb9 873 new_key.offset = args->end;
0b246afa 874 btrfs_set_item_key_safe(fs_info, path, &new_key);
6643558d 875
5893dfb9 876 extent_offset += args->end - key.offset;
920bbbfb
YZ
877 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
878 btrfs_set_file_extent_num_bytes(leaf, fi,
5893dfb9 879 extent_end - args->end);
920bbbfb 880 btrfs_mark_buffer_dirty(leaf);
2671485d 881 if (update_refs && disk_bytenr > 0)
2766ff61 882 args->bytes_found += args->end - key.offset;
920bbbfb 883 break;
39279cc3 884 }
771ed689 885
920bbbfb
YZ
886 search_start = extent_end;
887 /*
888 * | ---- range to drop ----- |
889 * | -------- extent -------- |
890 */
5893dfb9 891 if (args->start > key.offset && args->end >= extent_end) {
920bbbfb 892 BUG_ON(del_nr > 0);
00fdf13a 893 if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3f9e3df8 894 ret = -EOPNOTSUPP;
00fdf13a
LB
895 break;
896 }
8c2383c3 897
920bbbfb 898 btrfs_set_file_extent_num_bytes(leaf, fi,
5893dfb9 899 args->start - key.offset);
920bbbfb 900 btrfs_mark_buffer_dirty(leaf);
2671485d 901 if (update_refs && disk_bytenr > 0)
2766ff61 902 args->bytes_found += extent_end - args->start;
5893dfb9 903 if (args->end == extent_end)
920bbbfb 904 break;
c8b97818 905
920bbbfb
YZ
906 path->slots[0]++;
907 goto next_slot;
31840ae1
ZY
908 }
909
920bbbfb
YZ
910 /*
911 * | ---- range to drop ----- |
912 * | ------ extent ------ |
913 */
5893dfb9 914 if (args->start <= key.offset && args->end >= extent_end) {
fc19c5e7 915delete_extent_item:
920bbbfb
YZ
916 if (del_nr == 0) {
917 del_slot = path->slots[0];
918 del_nr = 1;
919 } else {
920 BUG_ON(del_slot + del_nr != path->slots[0]);
921 del_nr++;
922 }
31840ae1 923
5dc562c5
JB
924 if (update_refs &&
925 extent_type == BTRFS_FILE_EXTENT_INLINE) {
2766ff61 926 args->bytes_found += extent_end - key.offset;
920bbbfb 927 extent_end = ALIGN(extent_end,
0b246afa 928 fs_info->sectorsize);
5dc562c5 929 } else if (update_refs && disk_bytenr > 0) {
ffd4bb2a
QW
930 btrfs_init_generic_ref(&ref,
931 BTRFS_DROP_DELAYED_REF,
932 disk_bytenr, num_bytes, 0);
933 btrfs_init_data_ref(&ref,
920bbbfb 934 root->root_key.objectid,
ffd4bb2a 935 key.objectid,
f42c5da6
NB
936 key.offset - extent_offset, 0,
937 false);
ffd4bb2a 938 ret = btrfs_free_extent(trans, &ref);
79787eaa 939 BUG_ON(ret); /* -ENOMEM */
2766ff61 940 args->bytes_found += extent_end - key.offset;
31840ae1 941 }
31840ae1 942
5893dfb9 943 if (args->end == extent_end)
920bbbfb
YZ
944 break;
945
946 if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
947 path->slots[0]++;
948 goto next_slot;
949 }
950
951 ret = btrfs_del_items(trans, root, path, del_slot,
952 del_nr);
79787eaa 953 if (ret) {
66642832 954 btrfs_abort_transaction(trans, ret);
5dc562c5 955 break;
79787eaa 956 }
920bbbfb
YZ
957
958 del_nr = 0;
959 del_slot = 0;
960
b3b4aa74 961 btrfs_release_path(path);
920bbbfb 962 continue;
39279cc3 963 }
920bbbfb 964
290342f6 965 BUG();
39279cc3 966 }
920bbbfb 967
79787eaa 968 if (!ret && del_nr > 0) {
1acae57b
FDBM
969 /*
970 * Set path->slots[0] to first slot, so that after the delete
971 * if items are move off from our leaf to its immediate left or
972 * right neighbor leafs, we end up with a correct and adjusted
5893dfb9 973 * path->slots[0] for our insertion (if args->replace_extent).
1acae57b
FDBM
974 */
975 path->slots[0] = del_slot;
920bbbfb 976 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
79787eaa 977 if (ret)
66642832 978 btrfs_abort_transaction(trans, ret);
d5f37527 979 }
1acae57b 980
d5f37527
FDBM
981 leaf = path->nodes[0];
982 /*
983 * If btrfs_del_items() was called, it might have deleted a leaf, in
984 * which case it unlocked our path, so check path->locks[0] matches a
985 * write lock.
986 */
7ecb4c31 987 if (!ret && args->replace_extent &&
ac5887c8 988 path->locks[0] == BTRFS_WRITE_LOCK &&
e902baac 989 btrfs_leaf_free_space(leaf) >=
5893dfb9 990 sizeof(struct btrfs_item) + args->extent_item_size) {
d5f37527
FDBM
991
992 key.objectid = ino;
993 key.type = BTRFS_EXTENT_DATA_KEY;
5893dfb9 994 key.offset = args->start;
d5f37527
FDBM
995 if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
996 struct btrfs_key slot_key;
997
998 btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
999 if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
1000 path->slots[0]++;
1acae57b 1001 }
f0641656 1002 btrfs_setup_item_for_insert(root, path, &key, args->extent_item_size);
5893dfb9 1003 args->extent_inserted = true;
6643558d 1004 }
920bbbfb 1005
5893dfb9
FM
1006 if (!args->path)
1007 btrfs_free_path(path);
1008 else if (!args->extent_inserted)
1acae57b 1009 btrfs_release_path(path);
5893dfb9
FM
1010out:
1011 args->drop_end = found ? min(args->end, last_end) : args->end;
5dc562c5 1012
39279cc3
CM
1013 return ret;
1014}
1015
d899e052 1016static int extent_mergeable(struct extent_buffer *leaf, int slot,
6c7d54ac
YZ
1017 u64 objectid, u64 bytenr, u64 orig_offset,
1018 u64 *start, u64 *end)
d899e052
YZ
1019{
1020 struct btrfs_file_extent_item *fi;
1021 struct btrfs_key key;
1022 u64 extent_end;
1023
1024 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1025 return 0;
1026
1027 btrfs_item_key_to_cpu(leaf, &key, slot);
1028 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
1029 return 0;
1030
1031 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1032 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
1033 btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
6c7d54ac 1034 btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
d899e052
YZ
1035 btrfs_file_extent_compression(leaf, fi) ||
1036 btrfs_file_extent_encryption(leaf, fi) ||
1037 btrfs_file_extent_other_encoding(leaf, fi))
1038 return 0;
1039
1040 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1041 if ((*start && *start != key.offset) || (*end && *end != extent_end))
1042 return 0;
1043
1044 *start = key.offset;
1045 *end = extent_end;
1046 return 1;
1047}
1048
1049/*
1050 * Mark extent in the range start - end as written.
1051 *
1052 * This changes extent type from 'pre-allocated' to 'regular'. If only
1053 * part of extent is marked as written, the extent will be split into
1054 * two or three.
1055 */
1056int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
7a6d7067 1057 struct btrfs_inode *inode, u64 start, u64 end)
d899e052 1058{
3ffbd68c 1059 struct btrfs_fs_info *fs_info = trans->fs_info;
7a6d7067 1060 struct btrfs_root *root = inode->root;
d899e052
YZ
1061 struct extent_buffer *leaf;
1062 struct btrfs_path *path;
1063 struct btrfs_file_extent_item *fi;
82fa113f 1064 struct btrfs_ref ref = { 0 };
d899e052 1065 struct btrfs_key key;
920bbbfb 1066 struct btrfs_key new_key;
d899e052
YZ
1067 u64 bytenr;
1068 u64 num_bytes;
1069 u64 extent_end;
5d4f98a2 1070 u64 orig_offset;
d899e052
YZ
1071 u64 other_start;
1072 u64 other_end;
920bbbfb
YZ
1073 u64 split;
1074 int del_nr = 0;
1075 int del_slot = 0;
6c7d54ac 1076 int recow;
e7b2ec3d 1077 int ret = 0;
7a6d7067 1078 u64 ino = btrfs_ino(inode);
d899e052 1079
d899e052 1080 path = btrfs_alloc_path();
d8926bb3
MF
1081 if (!path)
1082 return -ENOMEM;
d899e052 1083again:
6c7d54ac 1084 recow = 0;
920bbbfb 1085 split = start;
33345d01 1086 key.objectid = ino;
d899e052 1087 key.type = BTRFS_EXTENT_DATA_KEY;
920bbbfb 1088 key.offset = split;
d899e052
YZ
1089
1090 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
41415730
JB
1091 if (ret < 0)
1092 goto out;
d899e052
YZ
1093 if (ret > 0 && path->slots[0] > 0)
1094 path->slots[0]--;
1095
1096 leaf = path->nodes[0];
1097 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
9c8e63db
JB
1098 if (key.objectid != ino ||
1099 key.type != BTRFS_EXTENT_DATA_KEY) {
1100 ret = -EINVAL;
1101 btrfs_abort_transaction(trans, ret);
1102 goto out;
1103 }
d899e052
YZ
1104 fi = btrfs_item_ptr(leaf, path->slots[0],
1105 struct btrfs_file_extent_item);
9c8e63db
JB
1106 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
1107 ret = -EINVAL;
1108 btrfs_abort_transaction(trans, ret);
1109 goto out;
1110 }
d899e052 1111 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
9c8e63db
JB
1112 if (key.offset > start || extent_end < end) {
1113 ret = -EINVAL;
1114 btrfs_abort_transaction(trans, ret);
1115 goto out;
1116 }
d899e052
YZ
1117
1118 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1119 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
5d4f98a2 1120 orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
6c7d54ac
YZ
1121 memcpy(&new_key, &key, sizeof(new_key));
1122
1123 if (start == key.offset && end < extent_end) {
1124 other_start = 0;
1125 other_end = start;
1126 if (extent_mergeable(leaf, path->slots[0] - 1,
33345d01 1127 ino, bytenr, orig_offset,
6c7d54ac
YZ
1128 &other_start, &other_end)) {
1129 new_key.offset = end;
0b246afa 1130 btrfs_set_item_key_safe(fs_info, path, &new_key);
6c7d54ac
YZ
1131 fi = btrfs_item_ptr(leaf, path->slots[0],
1132 struct btrfs_file_extent_item);
224ecce5
JB
1133 btrfs_set_file_extent_generation(leaf, fi,
1134 trans->transid);
6c7d54ac
YZ
1135 btrfs_set_file_extent_num_bytes(leaf, fi,
1136 extent_end - end);
1137 btrfs_set_file_extent_offset(leaf, fi,
1138 end - orig_offset);
1139 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1140 struct btrfs_file_extent_item);
224ecce5
JB
1141 btrfs_set_file_extent_generation(leaf, fi,
1142 trans->transid);
6c7d54ac
YZ
1143 btrfs_set_file_extent_num_bytes(leaf, fi,
1144 end - other_start);
1145 btrfs_mark_buffer_dirty(leaf);
1146 goto out;
1147 }
1148 }
1149
1150 if (start > key.offset && end == extent_end) {
1151 other_start = end;
1152 other_end = 0;
1153 if (extent_mergeable(leaf, path->slots[0] + 1,
33345d01 1154 ino, bytenr, orig_offset,
6c7d54ac
YZ
1155 &other_start, &other_end)) {
1156 fi = btrfs_item_ptr(leaf, path->slots[0],
1157 struct btrfs_file_extent_item);
1158 btrfs_set_file_extent_num_bytes(leaf, fi,
1159 start - key.offset);
224ecce5
JB
1160 btrfs_set_file_extent_generation(leaf, fi,
1161 trans->transid);
6c7d54ac
YZ
1162 path->slots[0]++;
1163 new_key.offset = start;
0b246afa 1164 btrfs_set_item_key_safe(fs_info, path, &new_key);
6c7d54ac
YZ
1165
1166 fi = btrfs_item_ptr(leaf, path->slots[0],
1167 struct btrfs_file_extent_item);
224ecce5
JB
1168 btrfs_set_file_extent_generation(leaf, fi,
1169 trans->transid);
6c7d54ac
YZ
1170 btrfs_set_file_extent_num_bytes(leaf, fi,
1171 other_end - start);
1172 btrfs_set_file_extent_offset(leaf, fi,
1173 start - orig_offset);
1174 btrfs_mark_buffer_dirty(leaf);
1175 goto out;
1176 }
1177 }
d899e052 1178
920bbbfb
YZ
1179 while (start > key.offset || end < extent_end) {
1180 if (key.offset == start)
1181 split = end;
1182
920bbbfb
YZ
1183 new_key.offset = split;
1184 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1185 if (ret == -EAGAIN) {
b3b4aa74 1186 btrfs_release_path(path);
920bbbfb 1187 goto again;
d899e052 1188 }
79787eaa 1189 if (ret < 0) {
66642832 1190 btrfs_abort_transaction(trans, ret);
79787eaa
JM
1191 goto out;
1192 }
d899e052 1193
920bbbfb
YZ
1194 leaf = path->nodes[0];
1195 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
d899e052 1196 struct btrfs_file_extent_item);
224ecce5 1197 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
d899e052 1198 btrfs_set_file_extent_num_bytes(leaf, fi,
920bbbfb
YZ
1199 split - key.offset);
1200
1201 fi = btrfs_item_ptr(leaf, path->slots[0],
1202 struct btrfs_file_extent_item);
1203
224ecce5 1204 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
920bbbfb
YZ
1205 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1206 btrfs_set_file_extent_num_bytes(leaf, fi,
1207 extent_end - split);
d899e052
YZ
1208 btrfs_mark_buffer_dirty(leaf);
1209
82fa113f
QW
1210 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr,
1211 num_bytes, 0);
1212 btrfs_init_data_ref(&ref, root->root_key.objectid, ino,
f42c5da6 1213 orig_offset, 0, false);
82fa113f 1214 ret = btrfs_inc_extent_ref(trans, &ref);
9c8e63db
JB
1215 if (ret) {
1216 btrfs_abort_transaction(trans, ret);
1217 goto out;
1218 }
d899e052 1219
920bbbfb
YZ
1220 if (split == start) {
1221 key.offset = start;
1222 } else {
9c8e63db
JB
1223 if (start != key.offset) {
1224 ret = -EINVAL;
1225 btrfs_abort_transaction(trans, ret);
1226 goto out;
1227 }
d899e052 1228 path->slots[0]--;
920bbbfb 1229 extent_end = end;
d899e052 1230 }
6c7d54ac 1231 recow = 1;
d899e052
YZ
1232 }
1233
920bbbfb
YZ
1234 other_start = end;
1235 other_end = 0;
ffd4bb2a
QW
1236 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1237 num_bytes, 0);
f42c5da6
NB
1238 btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset,
1239 0, false);
6c7d54ac 1240 if (extent_mergeable(leaf, path->slots[0] + 1,
33345d01 1241 ino, bytenr, orig_offset,
6c7d54ac
YZ
1242 &other_start, &other_end)) {
1243 if (recow) {
b3b4aa74 1244 btrfs_release_path(path);
6c7d54ac
YZ
1245 goto again;
1246 }
920bbbfb
YZ
1247 extent_end = other_end;
1248 del_slot = path->slots[0] + 1;
1249 del_nr++;
ffd4bb2a 1250 ret = btrfs_free_extent(trans, &ref);
9c8e63db
JB
1251 if (ret) {
1252 btrfs_abort_transaction(trans, ret);
1253 goto out;
1254 }
d899e052 1255 }
920bbbfb
YZ
1256 other_start = 0;
1257 other_end = start;
6c7d54ac 1258 if (extent_mergeable(leaf, path->slots[0] - 1,
33345d01 1259 ino, bytenr, orig_offset,
6c7d54ac
YZ
1260 &other_start, &other_end)) {
1261 if (recow) {
b3b4aa74 1262 btrfs_release_path(path);
6c7d54ac
YZ
1263 goto again;
1264 }
920bbbfb
YZ
1265 key.offset = other_start;
1266 del_slot = path->slots[0];
1267 del_nr++;
ffd4bb2a 1268 ret = btrfs_free_extent(trans, &ref);
9c8e63db
JB
1269 if (ret) {
1270 btrfs_abort_transaction(trans, ret);
1271 goto out;
1272 }
920bbbfb
YZ
1273 }
1274 if (del_nr == 0) {
3f6fae95
SL
1275 fi = btrfs_item_ptr(leaf, path->slots[0],
1276 struct btrfs_file_extent_item);
920bbbfb
YZ
1277 btrfs_set_file_extent_type(leaf, fi,
1278 BTRFS_FILE_EXTENT_REG);
224ecce5 1279 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
920bbbfb 1280 btrfs_mark_buffer_dirty(leaf);
6c7d54ac 1281 } else {
3f6fae95
SL
1282 fi = btrfs_item_ptr(leaf, del_slot - 1,
1283 struct btrfs_file_extent_item);
6c7d54ac
YZ
1284 btrfs_set_file_extent_type(leaf, fi,
1285 BTRFS_FILE_EXTENT_REG);
224ecce5 1286 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
6c7d54ac
YZ
1287 btrfs_set_file_extent_num_bytes(leaf, fi,
1288 extent_end - key.offset);
1289 btrfs_mark_buffer_dirty(leaf);
920bbbfb 1290
6c7d54ac 1291 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
79787eaa 1292 if (ret < 0) {
66642832 1293 btrfs_abort_transaction(trans, ret);
79787eaa
JM
1294 goto out;
1295 }
6c7d54ac 1296 }
920bbbfb 1297out:
d899e052 1298 btrfs_free_path(path);
e7b2ec3d 1299 return ret;
d899e052
YZ
1300}
1301
b1bf862e
CM
1302/*
1303 * on error we return an unlocked page and the error value
1304 * on success we return a locked page and 0
1305 */
bb1591b4
CM
1306static int prepare_uptodate_page(struct inode *inode,
1307 struct page *page, u64 pos,
b6316429 1308 bool force_uptodate)
b1bf862e 1309{
fb12489b 1310 struct folio *folio = page_folio(page);
b1bf862e
CM
1311 int ret = 0;
1312
09cbfeaf 1313 if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
b6316429 1314 !PageUptodate(page)) {
fb12489b 1315 ret = btrfs_read_folio(NULL, folio);
b1bf862e
CM
1316 if (ret)
1317 return ret;
1318 lock_page(page);
1319 if (!PageUptodate(page)) {
1320 unlock_page(page);
1321 return -EIO;
1322 }
e0467866
QW
1323
1324 /*
fb12489b 1325 * Since btrfs_read_folio() will unlock the folio before it
f913cff3 1326 * returns, there is a window where btrfs_release_folio() can be
7c11d0ae
QW
1327 * called to release the page. Here we check both inode
1328 * mapping and PagePrivate() to make sure the page was not
1329 * released.
e0467866
QW
1330 *
1331 * The private flag check is essential for subpage as we need
1332 * to store extra bitmap using page->private.
1333 */
1334 if (page->mapping != inode->i_mapping || !PagePrivate(page)) {
bb1591b4
CM
1335 unlock_page(page);
1336 return -EAGAIN;
1337 }
b1bf862e
CM
1338 }
1339 return 0;
1340}
1341
fc226000
SR
1342static unsigned int get_prepare_fgp_flags(bool nowait)
1343{
1344 unsigned int fgp_flags = FGP_LOCK | FGP_ACCESSED | FGP_CREAT;
1345
1346 if (nowait)
1347 fgp_flags |= FGP_NOWAIT;
1348
1349 return fgp_flags;
1350}
1351
1352static gfp_t get_prepare_gfp_flags(struct inode *inode, bool nowait)
1353{
1354 gfp_t gfp;
1355
1356 gfp = btrfs_alloc_write_mask(inode->i_mapping);
1357 if (nowait) {
1358 gfp &= ~__GFP_DIRECT_RECLAIM;
1359 gfp |= GFP_NOWAIT;
1360 }
1361
1362 return gfp;
1363}
1364
39279cc3 1365/*
376cc685 1366 * this just gets pages into the page cache and locks them down.
39279cc3 1367 */
b37392ea
MX
1368static noinline int prepare_pages(struct inode *inode, struct page **pages,
1369 size_t num_pages, loff_t pos,
fc226000
SR
1370 size_t write_bytes, bool force_uptodate,
1371 bool nowait)
39279cc3
CM
1372{
1373 int i;
09cbfeaf 1374 unsigned long index = pos >> PAGE_SHIFT;
fc226000
SR
1375 gfp_t mask = get_prepare_gfp_flags(inode, nowait);
1376 unsigned int fgp_flags = get_prepare_fgp_flags(nowait);
fc28b62d 1377 int err = 0;
376cc685 1378 int faili;
8c2383c3 1379
39279cc3 1380 for (i = 0; i < num_pages; i++) {
bb1591b4 1381again:
fc226000
SR
1382 pages[i] = pagecache_get_page(inode->i_mapping, index + i,
1383 fgp_flags, mask | __GFP_WRITE);
39279cc3 1384 if (!pages[i]) {
b1bf862e 1385 faili = i - 1;
fc226000
SR
1386 if (nowait)
1387 err = -EAGAIN;
1388 else
1389 err = -ENOMEM;
b1bf862e
CM
1390 goto fail;
1391 }
1392
32443de3
QW
1393 err = set_page_extent_mapped(pages[i]);
1394 if (err < 0) {
1395 faili = i;
1396 goto fail;
1397 }
1398
b1bf862e 1399 if (i == 0)
bb1591b4 1400 err = prepare_uptodate_page(inode, pages[i], pos,
b6316429 1401 force_uptodate);
bb1591b4
CM
1402 if (!err && i == num_pages - 1)
1403 err = prepare_uptodate_page(inode, pages[i],
b6316429 1404 pos + write_bytes, false);
b1bf862e 1405 if (err) {
09cbfeaf 1406 put_page(pages[i]);
fc226000 1407 if (!nowait && err == -EAGAIN) {
bb1591b4
CM
1408 err = 0;
1409 goto again;
1410 }
b1bf862e
CM
1411 faili = i - 1;
1412 goto fail;
39279cc3 1413 }
ccd467d6 1414 wait_on_page_writeback(pages[i]);
39279cc3 1415 }
376cc685
MX
1416
1417 return 0;
1418fail:
1419 while (faili >= 0) {
1420 unlock_page(pages[faili]);
09cbfeaf 1421 put_page(pages[faili]);
376cc685
MX
1422 faili--;
1423 }
1424 return err;
1425
1426}
1427
1428/*
1429 * This function locks the extent and properly waits for data=ordered extents
1430 * to finish before allowing the pages to be modified if need.
1431 *
1432 * The return value:
1433 * 1 - the extent is locked
1434 * 0 - the extent is not locked, and everything is OK
1435 * -EAGAIN - need re-prepare the pages
1436 * the other < 0 number - Something wrong happens
1437 */
1438static noinline int
2cff578c 1439lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
376cc685 1440 size_t num_pages, loff_t pos,
2e78c927 1441 size_t write_bytes,
2fcab928 1442 u64 *lockstart, u64 *lockend, bool nowait,
376cc685
MX
1443 struct extent_state **cached_state)
1444{
3ffbd68c 1445 struct btrfs_fs_info *fs_info = inode->root->fs_info;
376cc685
MX
1446 u64 start_pos;
1447 u64 last_pos;
1448 int i;
1449 int ret = 0;
1450
0b246afa 1451 start_pos = round_down(pos, fs_info->sectorsize);
e21139c6 1452 last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1;
376cc685 1453
e3b8a485 1454 if (start_pos < inode->vfs_inode.i_size) {
e6dcd2dc 1455 struct btrfs_ordered_extent *ordered;
a7e3b975 1456
2fcab928
SR
1457 if (nowait) {
1458 if (!try_lock_extent(&inode->io_tree, start_pos, last_pos)) {
1459 for (i = 0; i < num_pages; i++) {
1460 unlock_page(pages[i]);
1461 put_page(pages[i]);
1462 pages[i] = NULL;
1463 }
1464
1465 return -EAGAIN;
1466 }
1467 } else {
1468 lock_extent(&inode->io_tree, start_pos, last_pos, cached_state);
1469 }
1470
b88935bf
MX
1471 ordered = btrfs_lookup_ordered_range(inode, start_pos,
1472 last_pos - start_pos + 1);
e6dcd2dc 1473 if (ordered &&
bffe633e 1474 ordered->file_offset + ordered->num_bytes > start_pos &&
376cc685 1475 ordered->file_offset <= last_pos) {
570eb97b
JB
1476 unlock_extent(&inode->io_tree, start_pos, last_pos,
1477 cached_state);
e6dcd2dc
CM
1478 for (i = 0; i < num_pages; i++) {
1479 unlock_page(pages[i]);
09cbfeaf 1480 put_page(pages[i]);
e6dcd2dc 1481 }
c0a43603 1482 btrfs_start_ordered_extent(ordered, 1);
b88935bf
MX
1483 btrfs_put_ordered_extent(ordered);
1484 return -EAGAIN;
e6dcd2dc
CM
1485 }
1486 if (ordered)
1487 btrfs_put_ordered_extent(ordered);
7703bdd8 1488
376cc685
MX
1489 *lockstart = start_pos;
1490 *lockend = last_pos;
1491 ret = 1;
0762704b 1492 }
376cc685 1493
7703bdd8 1494 /*
32443de3
QW
1495 * We should be called after prepare_pages() which should have locked
1496 * all pages in the range.
7703bdd8 1497 */
32443de3 1498 for (i = 0; i < num_pages; i++)
e6dcd2dc 1499 WARN_ON(!PageLocked(pages[i]));
b1bf862e 1500
376cc685 1501 return ret;
39279cc3
CM
1502}
1503
d7a8ab4e
FM
1504/*
1505 * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
1506 *
1507 * @pos: File offset.
1508 * @write_bytes: The length to write, will be updated to the nocow writeable
1509 * range.
1510 *
1511 * This function will flush ordered extents in the range to ensure proper
1512 * nocow checks.
1513 *
1514 * Return:
1515 * > 0 If we can nocow, and updates @write_bytes.
1516 * 0 If we can't do a nocow write.
1517 * -EAGAIN If we can't do a nocow write because snapshoting of the inode's
1518 * root is in progress.
1519 * < 0 If an error happened.
1520 *
1521 * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0.
1522 */
1523int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos,
80f9d241 1524 size_t *write_bytes, bool nowait)
7ee9e440 1525{
3ffbd68c 1526 struct btrfs_fs_info *fs_info = inode->root->fs_info;
85b7ab67 1527 struct btrfs_root *root = inode->root;
7ee9e440
JB
1528 u64 lockstart, lockend;
1529 u64 num_bytes;
1530 int ret;
1531
38d37aa9
QW
1532 if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1533 return 0;
1534
d7a8ab4e 1535 if (!btrfs_drew_try_write_lock(&root->snapshot_lock))
5f791ec3 1536 return -EAGAIN;
8257b2dc 1537
0b246afa 1538 lockstart = round_down(pos, fs_info->sectorsize);
da17066c 1539 lockend = round_up(pos + *write_bytes,
0b246afa 1540 fs_info->sectorsize) - 1;
5dbb75ed 1541 num_bytes = lockend - lockstart + 1;
7ee9e440 1542
80f9d241
JB
1543 if (nowait) {
1544 if (!btrfs_try_lock_ordered_range(inode, lockstart, lockend)) {
1545 btrfs_drew_write_unlock(&root->snapshot_lock);
1546 return -EAGAIN;
1547 }
1548 } else {
1549 btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend, NULL);
1550 }
85b7ab67 1551 ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
80f9d241
JB
1552 NULL, NULL, NULL, nowait, false);
1553 if (ret <= 0)
d7a8ab4e 1554 btrfs_drew_write_unlock(&root->snapshot_lock);
80f9d241 1555 else
c933956d
MX
1556 *write_bytes = min_t(size_t, *write_bytes ,
1557 num_bytes - pos + lockstart);
570eb97b 1558 unlock_extent(&inode->io_tree, lockstart, lockend, NULL);
7ee9e440
JB
1559
1560 return ret;
1561}
1562
38d37aa9
QW
1563void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
1564{
1565 btrfs_drew_write_unlock(&inode->root->snapshot_lock);
1566}
1567
b8d8e1fd
GR
1568static void update_time_for_write(struct inode *inode)
1569{
1570 struct timespec64 now;
1571
1572 if (IS_NOCMTIME(inode))
1573 return;
1574
1575 now = current_time(inode);
1576 if (!timespec64_equal(&inode->i_mtime, &now))
1577 inode->i_mtime = now;
1578
1579 if (!timespec64_equal(&inode->i_ctime, &now))
1580 inode->i_ctime = now;
1581
1582 if (IS_I_VERSION(inode))
1583 inode_inc_iversion(inode);
1584}
1585
1586static int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from,
1587 size_t count)
1588{
1589 struct file *file = iocb->ki_filp;
1590 struct inode *inode = file_inode(file);
1591 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1592 loff_t pos = iocb->ki_pos;
1593 int ret;
1594 loff_t oldsize;
1595 loff_t start_pos;
1596
d7a8ab4e
FM
1597 /*
1598 * Quickly bail out on NOWAIT writes if we don't have the nodatacow or
1599 * prealloc flags, as without those flags we always have to COW. We will
1600 * later check if we can really COW into the target range (using
1601 * can_nocow_extent() at btrfs_get_blocks_direct_write()).
1602 */
1603 if ((iocb->ki_flags & IOCB_NOWAIT) &&
1604 !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1605 return -EAGAIN;
b8d8e1fd
GR
1606
1607 current->backing_dev_info = inode_to_bdi(inode);
1608 ret = file_remove_privs(file);
1609 if (ret)
1610 return ret;
1611
1612 /*
1613 * We reserve space for updating the inode when we reserve space for the
1614 * extent we are going to write, so we will enospc out there. We don't
1615 * need to start yet another transaction to update the inode as we will
1616 * update the inode when we finish writing whatever data we write.
1617 */
1618 update_time_for_write(inode);
1619
1620 start_pos = round_down(pos, fs_info->sectorsize);
1621 oldsize = i_size_read(inode);
1622 if (start_pos > oldsize) {
1623 /* Expand hole size to cover write data, preventing empty gap */
1624 loff_t end_pos = round_up(pos + count, fs_info->sectorsize);
1625
b06359a3 1626 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos);
b8d8e1fd
GR
1627 if (ret) {
1628 current->backing_dev_info = NULL;
1629 return ret;
1630 }
1631 }
1632
1633 return 0;
1634}
1635
e4af400a
GR
1636static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb,
1637 struct iov_iter *i)
4b46fce2 1638{
e4af400a 1639 struct file *file = iocb->ki_filp;
c3523706 1640 loff_t pos;
496ad9aa 1641 struct inode *inode = file_inode(file);
0b246afa 1642 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
11c65dcc 1643 struct page **pages = NULL;
364ecf36 1644 struct extent_changeset *data_reserved = NULL;
7ee9e440 1645 u64 release_bytes = 0;
376cc685
MX
1646 u64 lockstart;
1647 u64 lockend;
d0215f3e
JB
1648 size_t num_written = 0;
1649 int nrptrs;
c3523706 1650 ssize_t ret;
7ee9e440 1651 bool only_release_metadata = false;
b6316429 1652 bool force_page_uptodate = false;
5e8b9ef3 1653 loff_t old_isize = i_size_read(inode);
c3523706 1654 unsigned int ilock_flags = 0;
304e45ac 1655 const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
965f47ae 1656 unsigned int bdp_flags = (nowait ? BDP_ASYNC : 0);
c3523706 1657
304e45ac 1658 if (nowait)
c3523706
GR
1659 ilock_flags |= BTRFS_ILOCK_TRY;
1660
1661 ret = btrfs_inode_lock(inode, ilock_flags);
1662 if (ret < 0)
1663 return ret;
4b46fce2 1664
c3523706
GR
1665 ret = generic_write_checks(iocb, i);
1666 if (ret <= 0)
1667 goto out;
1668
1669 ret = btrfs_write_check(iocb, i, ret);
1670 if (ret < 0)
1671 goto out;
1672
1673 pos = iocb->ki_pos;
09cbfeaf
KS
1674 nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
1675 PAGE_SIZE / (sizeof(struct page *)));
142349f5
WF
1676 nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1677 nrptrs = max(nrptrs, 8);
31e818fe 1678 pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
c3523706
GR
1679 if (!pages) {
1680 ret = -ENOMEM;
1681 goto out;
1682 }
ab93dbec 1683
d0215f3e 1684 while (iov_iter_count(i) > 0) {
c67d970f 1685 struct extent_state *cached_state = NULL;
7073017a 1686 size_t offset = offset_in_page(pos);
2e78c927 1687 size_t sector_offset;
d0215f3e 1688 size_t write_bytes = min(iov_iter_count(i),
09cbfeaf 1689 nrptrs * (size_t)PAGE_SIZE -
8c2383c3 1690 offset);
eefa45f5 1691 size_t num_pages;
7ee9e440 1692 size_t reserve_bytes;
d0215f3e
JB
1693 size_t dirty_pages;
1694 size_t copied;
2e78c927
CR
1695 size_t dirty_sectors;
1696 size_t num_sectors;
79f015f2 1697 int extents_locked;
39279cc3 1698
914ee295
XZ
1699 /*
1700 * Fault pages before locking them in prepare_pages
1701 * to avoid recursive lock
1702 */
a6294593 1703 if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) {
914ee295 1704 ret = -EFAULT;
d0215f3e 1705 break;
914ee295
XZ
1706 }
1707
a0e248bb 1708 only_release_metadata = false;
da17066c 1709 sector_offset = pos & (fs_info->sectorsize - 1);
d9d8b2a5 1710
364ecf36 1711 extent_changeset_release(data_reserved);
36ea6f3e
NB
1712 ret = btrfs_check_data_free_space(BTRFS_I(inode),
1713 &data_reserved, pos,
304e45ac 1714 write_bytes, nowait);
c6887cd1 1715 if (ret < 0) {
80f9d241
JB
1716 int can_nocow;
1717
304e45ac
SR
1718 if (nowait && (ret == -ENOSPC || ret == -EAGAIN)) {
1719 ret = -EAGAIN;
1720 break;
1721 }
1722
eefa45f5
GR
1723 /*
1724 * If we don't have to COW at the offset, reserve
1725 * metadata only. write_bytes may get smaller than
1726 * requested here.
1727 */
80f9d241 1728 can_nocow = btrfs_check_nocow_lock(BTRFS_I(inode), pos,
304e45ac 1729 &write_bytes, nowait);
80f9d241
JB
1730 if (can_nocow < 0)
1731 ret = can_nocow;
1732 if (can_nocow > 0)
1733 ret = 0;
1734 if (ret)
c6887cd1 1735 break;
80f9d241 1736 only_release_metadata = true;
c6887cd1 1737 }
1832a6d5 1738
eefa45f5
GR
1739 num_pages = DIV_ROUND_UP(write_bytes + offset, PAGE_SIZE);
1740 WARN_ON(num_pages > nrptrs);
1741 reserve_bytes = round_up(write_bytes + sector_offset,
1742 fs_info->sectorsize);
8b62f87b 1743 WARN_ON(reserve_bytes == 0);
9f3db423 1744 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
28c9b1e7 1745 reserve_bytes,
304e45ac 1746 reserve_bytes, nowait);
7ee9e440
JB
1747 if (ret) {
1748 if (!only_release_metadata)
25ce28ca 1749 btrfs_free_reserved_data_space(BTRFS_I(inode),
bc42bda2
QW
1750 data_reserved, pos,
1751 write_bytes);
8257b2dc 1752 else
38d37aa9 1753 btrfs_check_nocow_unlock(BTRFS_I(inode));
7ee9e440
JB
1754 break;
1755 }
1756
1757 release_bytes = reserve_bytes;
376cc685 1758again:
965f47ae
SR
1759 ret = balance_dirty_pages_ratelimited_flags(inode->i_mapping, bdp_flags);
1760 if (ret)
1761 break;
1762
4a64001f
JB
1763 /*
1764 * This is going to setup the pages array with the number of
1765 * pages we want, so we don't really need to worry about the
1766 * contents of pages from loop to loop
1767 */
b37392ea 1768 ret = prepare_pages(inode, pages, num_pages,
fc226000 1769 pos, write_bytes, force_page_uptodate, false);
8b62f87b
JB
1770 if (ret) {
1771 btrfs_delalloc_release_extents(BTRFS_I(inode),
8702ba93 1772 reserve_bytes);
d0215f3e 1773 break;
8b62f87b 1774 }
39279cc3 1775
79f015f2
GR
1776 extents_locked = lock_and_cleanup_extent_if_need(
1777 BTRFS_I(inode), pages,
2cff578c 1778 num_pages, pos, write_bytes, &lockstart,
304e45ac 1779 &lockend, nowait, &cached_state);
79f015f2 1780 if (extents_locked < 0) {
304e45ac 1781 if (!nowait && extents_locked == -EAGAIN)
376cc685 1782 goto again;
304e45ac 1783
8b62f87b 1784 btrfs_delalloc_release_extents(BTRFS_I(inode),
8702ba93 1785 reserve_bytes);
79f015f2 1786 ret = extents_locked;
376cc685 1787 break;
376cc685
MX
1788 }
1789
ee22f0c4 1790 copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
b1bf862e 1791
0b246afa 1792 num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
56244ef1 1793 dirty_sectors = round_up(copied + sector_offset,
0b246afa
JM
1794 fs_info->sectorsize);
1795 dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
56244ef1 1796
b1bf862e
CM
1797 /*
1798 * if we have trouble faulting in the pages, fall
1799 * back to one page at a time
1800 */
1801 if (copied < write_bytes)
1802 nrptrs = 1;
1803
b6316429
JB
1804 if (copied == 0) {
1805 force_page_uptodate = true;
56244ef1 1806 dirty_sectors = 0;
b1bf862e 1807 dirty_pages = 0;
b6316429
JB
1808 } else {
1809 force_page_uptodate = false;
ed6078f7 1810 dirty_pages = DIV_ROUND_UP(copied + offset,
09cbfeaf 1811 PAGE_SIZE);
b6316429 1812 }
914ee295 1813
2e78c927 1814 if (num_sectors > dirty_sectors) {
8b8b08cb 1815 /* release everything except the sectors we dirtied */
265fdfa6 1816 release_bytes -= dirty_sectors << fs_info->sectorsize_bits;
485290a7 1817 if (only_release_metadata) {
691fa059 1818 btrfs_delalloc_release_metadata(BTRFS_I(inode),
43b18595 1819 release_bytes, true);
485290a7
QW
1820 } else {
1821 u64 __pos;
1822
da17066c 1823 __pos = round_down(pos,
0b246afa 1824 fs_info->sectorsize) +
09cbfeaf 1825 (dirty_pages << PAGE_SHIFT);
86d52921 1826 btrfs_delalloc_release_space(BTRFS_I(inode),
bc42bda2 1827 data_reserved, __pos,
43b18595 1828 release_bytes, true);
485290a7 1829 }
914ee295
XZ
1830 }
1831
2e78c927 1832 release_bytes = round_up(copied + sector_offset,
0b246afa 1833 fs_info->sectorsize);
376cc685 1834
aa8c1a41
GR
1835 ret = btrfs_dirty_pages(BTRFS_I(inode), pages,
1836 dirty_pages, pos, copied,
1837 &cached_state, only_release_metadata);
c67d970f
FM
1838
1839 /*
1840 * If we have not locked the extent range, because the range's
1841 * start offset is >= i_size, we might still have a non-NULL
1842 * cached extent state, acquired while marking the extent range
1843 * as delalloc through btrfs_dirty_pages(). Therefore free any
1844 * possible cached extent state to avoid a memory leak.
1845 */
79f015f2 1846 if (extents_locked)
570eb97b
JB
1847 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart,
1848 lockend, &cached_state);
c67d970f
FM
1849 else
1850 free_extent_state(cached_state);
1851
8702ba93 1852 btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
f1de9683 1853 if (ret) {
e4f94347 1854 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
376cc685 1855 break;
f1de9683 1856 }
39279cc3 1857
376cc685 1858 release_bytes = 0;
8257b2dc 1859 if (only_release_metadata)
38d37aa9 1860 btrfs_check_nocow_unlock(BTRFS_I(inode));
8257b2dc 1861
e4f94347 1862 btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
f1de9683 1863
d0215f3e
JB
1864 cond_resched();
1865
914ee295
XZ
1866 pos += copied;
1867 num_written += copied;
d0215f3e 1868 }
39279cc3 1869
d0215f3e
JB
1870 kfree(pages);
1871
7ee9e440 1872 if (release_bytes) {
8257b2dc 1873 if (only_release_metadata) {
38d37aa9 1874 btrfs_check_nocow_unlock(BTRFS_I(inode));
691fa059 1875 btrfs_delalloc_release_metadata(BTRFS_I(inode),
43b18595 1876 release_bytes, true);
8257b2dc 1877 } else {
86d52921
NB
1878 btrfs_delalloc_release_space(BTRFS_I(inode),
1879 data_reserved,
bc42bda2 1880 round_down(pos, fs_info->sectorsize),
43b18595 1881 release_bytes, true);
8257b2dc 1882 }
7ee9e440
JB
1883 }
1884
364ecf36 1885 extent_changeset_free(data_reserved);
5e8b9ef3
GR
1886 if (num_written > 0) {
1887 pagecache_isize_extended(inode, old_isize, iocb->ki_pos);
1888 iocb->ki_pos += num_written;
1889 }
c3523706
GR
1890out:
1891 btrfs_inode_unlock(inode, ilock_flags);
d0215f3e
JB
1892 return num_written ? num_written : ret;
1893}
1894
4e4cabec
GR
1895static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
1896 const struct iov_iter *iter, loff_t offset)
1897{
1898 const u32 blocksize_mask = fs_info->sectorsize - 1;
1899
1900 if (offset & blocksize_mask)
1901 return -EINVAL;
1902
1903 if (iov_iter_alignment(iter) & blocksize_mask)
1904 return -EINVAL;
1905
1906 return 0;
1907}
1908
1909static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
d0215f3e
JB
1910{
1911 struct file *file = iocb->ki_filp;
728404da 1912 struct inode *inode = file_inode(file);
4e4cabec 1913 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
c3523706 1914 loff_t pos;
4e4cabec 1915 ssize_t written = 0;
d0215f3e 1916 ssize_t written_buffered;
51bd9563 1917 size_t prev_left = 0;
d0215f3e 1918 loff_t endbyte;
c3523706
GR
1919 ssize_t err;
1920 unsigned int ilock_flags = 0;
1921
1922 if (iocb->ki_flags & IOCB_NOWAIT)
1923 ilock_flags |= BTRFS_ILOCK_TRY;
1924
e9adabb9
GR
1925 /* If the write DIO is within EOF, use a shared lock */
1926 if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode))
1927 ilock_flags |= BTRFS_ILOCK_SHARED;
1928
1929relock:
c3523706
GR
1930 err = btrfs_inode_lock(inode, ilock_flags);
1931 if (err < 0)
1932 return err;
1933
1934 err = generic_write_checks(iocb, from);
1935 if (err <= 0) {
1936 btrfs_inode_unlock(inode, ilock_flags);
1937 return err;
1938 }
d0215f3e 1939
c3523706
GR
1940 err = btrfs_write_check(iocb, from, err);
1941 if (err < 0) {
1942 btrfs_inode_unlock(inode, ilock_flags);
1943 goto out;
1944 }
1945
1946 pos = iocb->ki_pos;
e9adabb9
GR
1947 /*
1948 * Re-check since file size may have changed just before taking the
1949 * lock or pos may have changed because of O_APPEND in generic_write_check()
1950 */
1951 if ((ilock_flags & BTRFS_ILOCK_SHARED) &&
1952 pos + iov_iter_count(from) > i_size_read(inode)) {
1953 btrfs_inode_unlock(inode, ilock_flags);
1954 ilock_flags &= ~BTRFS_ILOCK_SHARED;
1955 goto relock;
1956 }
c3523706
GR
1957
1958 if (check_direct_IO(fs_info, from, pos)) {
1959 btrfs_inode_unlock(inode, ilock_flags);
4e4cabec 1960 goto buffered;
c3523706 1961 }
4e4cabec 1962
51bd9563
FM
1963 /*
1964 * The iov_iter can be mapped to the same file range we are writing to.
1965 * If that's the case, then we will deadlock in the iomap code, because
1966 * it first calls our callback btrfs_dio_iomap_begin(), which will create
1967 * an ordered extent, and after that it will fault in the pages that the
1968 * iov_iter refers to. During the fault in we end up in the readahead
1969 * pages code (starting at btrfs_readahead()), which will lock the range,
1970 * find that ordered extent and then wait for it to complete (at
1971 * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since
1972 * obviously the ordered extent can never complete as we didn't submit
1973 * yet the respective bio(s). This always happens when the buffer is
1974 * memory mapped to the same file range, since the iomap DIO code always
1975 * invalidates pages in the target file range (after starting and waiting
1976 * for any writeback).
1977 *
1978 * So here we disable page faults in the iov_iter and then retry if we
1979 * got -EFAULT, faulting in the pages before the retry.
1980 */
1981again:
1982 from->nofault = true;
36e8c622 1983 err = btrfs_dio_rw(iocb, from, written);
51bd9563 1984 from->nofault = false;
d0215f3e 1985
51bd9563
FM
1986 /* No increment (+=) because iomap returns a cumulative value. */
1987 if (err > 0)
1988 written = err;
1989
1990 if (iov_iter_count(from) > 0 && (err == -EFAULT || err > 0)) {
1991 const size_t left = iov_iter_count(from);
1992 /*
1993 * We have more data left to write. Try to fault in as many as
1994 * possible of the remainder pages and retry. We do this without
1995 * releasing and locking again the inode, to prevent races with
1996 * truncate.
1997 *
1998 * Also, in case the iov refers to pages in the file range of the
1999 * file we want to write to (due to a mmap), we could enter an
2000 * infinite loop if we retry after faulting the pages in, since
2001 * iomap will invalidate any pages in the range early on, before
2002 * it tries to fault in the pages of the iov. So we keep track of
2003 * how much was left of iov in the previous EFAULT and fallback
2004 * to buffered IO in case we haven't made any progress.
2005 */
2006 if (left == prev_left) {
2007 err = -ENOTBLK;
2008 } else {
2009 fault_in_iov_iter_readable(from, left);
2010 prev_left = left;
2011 goto again;
2012 }
a42fa643
GR
2013 }
2014
51bd9563
FM
2015 btrfs_inode_unlock(inode, ilock_flags);
2016
ac5e6669
FM
2017 /*
2018 * If 'err' is -ENOTBLK or we have not written all data, then it means
2019 * we must fallback to buffered IO.
2020 */
51bd9563 2021 if ((err < 0 && err != -ENOTBLK) || !iov_iter_count(from))
c3523706 2022 goto out;
d0215f3e 2023
4e4cabec 2024buffered:
ac5e6669
FM
2025 /*
2026 * If we are in a NOWAIT context, then return -EAGAIN to signal the caller
2027 * it must retry the operation in a context where blocking is acceptable,
2028 * since we currently don't have NOWAIT semantics support for buffered IO
2029 * and may block there for many reasons (reserving space for example).
2030 */
2031 if (iocb->ki_flags & IOCB_NOWAIT) {
2032 err = -EAGAIN;
2033 goto out;
2034 }
2035
e4af400a
GR
2036 pos = iocb->ki_pos;
2037 written_buffered = btrfs_buffered_write(iocb, from);
d0215f3e
JB
2038 if (written_buffered < 0) {
2039 err = written_buffered;
2040 goto out;
39279cc3 2041 }
075bdbdb
FM
2042 /*
2043 * Ensure all data is persisted. We want the next direct IO read to be
2044 * able to read what was just written.
2045 */
d0215f3e 2046 endbyte = pos + written_buffered - 1;
728404da 2047 err = btrfs_fdatawrite_range(inode, pos, endbyte);
075bdbdb
FM
2048 if (err)
2049 goto out;
728404da 2050 err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
d0215f3e
JB
2051 if (err)
2052 goto out;
2053 written += written_buffered;
867c4f93 2054 iocb->ki_pos = pos + written_buffered;
09cbfeaf
KS
2055 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
2056 endbyte >> PAGE_SHIFT);
39279cc3 2057out:
51bd9563 2058 return err < 0 ? err : written;
d0215f3e 2059}
5b92ee72 2060
7c0c7269
OS
2061static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from,
2062 const struct btrfs_ioctl_encoded_io_args *encoded)
2063{
2064 struct file *file = iocb->ki_filp;
2065 struct inode *inode = file_inode(file);
2066 loff_t count;
2067 ssize_t ret;
2068
2069 btrfs_inode_lock(inode, 0);
2070 count = encoded->len;
2071 ret = generic_write_checks_count(iocb, &count);
2072 if (ret == 0 && count != encoded->len) {
2073 /*
2074 * The write got truncated by generic_write_checks_count(). We
2075 * can't do a partial encoded write.
2076 */
2077 ret = -EFBIG;
2078 }
2079 if (ret || encoded->len == 0)
2080 goto out;
2081
2082 ret = btrfs_write_check(iocb, from, encoded->len);
2083 if (ret < 0)
2084 goto out;
2085
2086 ret = btrfs_do_encoded_write(iocb, from, encoded);
2087out:
2088 btrfs_inode_unlock(inode, 0);
2089 return ret;
2090}
2091
2092ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from,
2093 const struct btrfs_ioctl_encoded_io_args *encoded)
d0215f3e
JB
2094{
2095 struct file *file = iocb->ki_filp;
14971657 2096 struct btrfs_inode *inode = BTRFS_I(file_inode(file));
7c0c7269 2097 ssize_t num_written, num_sync;
91b94c5d 2098 const bool sync = iocb_is_dsync(iocb);
d0215f3e 2099
c86537a4
GR
2100 /*
2101 * If the fs flips readonly due to some impossible error, although we
2102 * have opened a file as writable, we have to stop this write operation
2103 * to ensure consistency.
2104 */
84961539 2105 if (BTRFS_FS_ERROR(inode->root->fs_info))
c86537a4
GR
2106 return -EROFS;
2107
926078b2 2108 if (encoded && (iocb->ki_flags & IOCB_NOWAIT))
91f9943e
CH
2109 return -EOPNOTSUPP;
2110
b812ce28 2111 if (sync)
14971657 2112 atomic_inc(&inode->sync_writers);
b812ce28 2113
7c0c7269
OS
2114 if (encoded) {
2115 num_written = btrfs_encoded_write(iocb, from, encoded);
2116 num_sync = encoded->len;
2117 } else if (iocb->ki_flags & IOCB_DIRECT) {
c1867eb3
DS
2118 num_written = btrfs_direct_write(iocb, from);
2119 num_sync = num_written;
7c0c7269 2120 } else {
c1867eb3
DS
2121 num_written = btrfs_buffered_write(iocb, from);
2122 num_sync = num_written;
7c0c7269 2123 }
d0215f3e 2124
bc0939fc
FM
2125 btrfs_set_inode_last_sub_trans(inode);
2126
7c0c7269
OS
2127 if (num_sync > 0) {
2128 num_sync = generic_write_sync(iocb, num_sync);
2129 if (num_sync < 0)
2130 num_written = num_sync;
2131 }
0a3404dc 2132
b812ce28 2133 if (sync)
14971657 2134 atomic_dec(&inode->sync_writers);
b8d8e1fd 2135
39279cc3 2136 current->backing_dev_info = NULL;
c3523706 2137 return num_written;
39279cc3
CM
2138}
2139
7c0c7269
OS
2140static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2141{
2142 return btrfs_do_write_iter(iocb, from, NULL);
2143}
2144
d397712b 2145int btrfs_release_file(struct inode *inode, struct file *filp)
e1b81e67 2146{
23b5ec74
JB
2147 struct btrfs_file_private *private = filp->private_data;
2148
23b5ec74
JB
2149 if (private && private->filldir_buf)
2150 kfree(private->filldir_buf);
2151 kfree(private);
2152 filp->private_data = NULL;
2153
f6dc45c7 2154 /*
1fd4033d
NB
2155 * Set by setattr when we are about to truncate a file from a non-zero
2156 * size to a zero size. This tries to flush down new bytes that may
2157 * have been written if the application were using truncate to replace
2158 * a file in place.
f6dc45c7 2159 */
1fd4033d 2160 if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
f6dc45c7
CM
2161 &BTRFS_I(inode)->runtime_flags))
2162 filemap_flush(inode->i_mapping);
e1b81e67
M
2163 return 0;
2164}
2165
669249ee
FM
2166static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
2167{
2168 int ret;
343e4fc1 2169 struct blk_plug plug;
669249ee 2170
343e4fc1
LB
2171 /*
2172 * This is only called in fsync, which would do synchronous writes, so
2173 * a plug can merge adjacent IOs as much as possible. Esp. in case of
2174 * multiple disks using raid profile, a large IO can be split to
2175 * several segments of stripe length (currently 64K).
2176 */
2177 blk_start_plug(&plug);
669249ee 2178 atomic_inc(&BTRFS_I(inode)->sync_writers);
728404da 2179 ret = btrfs_fdatawrite_range(inode, start, end);
669249ee 2180 atomic_dec(&BTRFS_I(inode)->sync_writers);
343e4fc1 2181 blk_finish_plug(&plug);
669249ee
FM
2182
2183 return ret;
2184}
2185
626e9f41
FM
2186static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx)
2187{
2188 struct btrfs_inode *inode = BTRFS_I(ctx->inode);
2189 struct btrfs_fs_info *fs_info = inode->root->fs_info;
2190
2191 if (btrfs_inode_in_log(inode, fs_info->generation) &&
2192 list_empty(&ctx->ordered_extents))
2193 return true;
2194
2195 /*
2196 * If we are doing a fast fsync we can not bail out if the inode's
2197 * last_trans is <= then the last committed transaction, because we only
2198 * update the last_trans of the inode during ordered extent completion,
2199 * and for a fast fsync we don't wait for that, we only wait for the
2200 * writeback to complete.
2201 */
2202 if (inode->last_trans <= fs_info->last_trans_committed &&
2203 (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) ||
2204 list_empty(&ctx->ordered_extents)))
2205 return true;
2206
2207 return false;
2208}
2209
d352ac68
CM
2210/*
2211 * fsync call for both files and directories. This logs the inode into
2212 * the tree log instead of forcing full commits whenever possible.
2213 *
2214 * It needs to call filemap_fdatawait so that all ordered extent updates are
2215 * in the metadata btree are up to date for copying to the log.
2216 *
2217 * It drops the inode mutex before doing the tree log commit. This is an
2218 * important optimization for directories because holding the mutex prevents
2219 * new operations on the dir while we write to disk.
2220 */
02c24a82 2221int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
39279cc3 2222{
de17e793 2223 struct dentry *dentry = file_dentry(file);
2b0143b5 2224 struct inode *inode = d_inode(dentry);
0b246afa 2225 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 2226 struct btrfs_root *root = BTRFS_I(inode)->root;
39279cc3 2227 struct btrfs_trans_handle *trans;
8b050d35 2228 struct btrfs_log_ctx ctx;
333427a5 2229 int ret = 0, err;
48778179
FM
2230 u64 len;
2231 bool full_sync;
39279cc3 2232
1abe9b8a 2233 trace_btrfs_sync_file(file, datasync);
257c62e1 2234
ebb70442
LB
2235 btrfs_init_log_ctx(&ctx, inode);
2236
95418ed1 2237 /*
48778179
FM
2238 * Always set the range to a full range, otherwise we can get into
2239 * several problems, from missing file extent items to represent holes
2240 * when not using the NO_HOLES feature, to log tree corruption due to
2241 * races between hole detection during logging and completion of ordered
2242 * extents outside the range, to missing checksums due to ordered extents
2243 * for which we flushed only a subset of their pages.
95418ed1 2244 */
48778179
FM
2245 start = 0;
2246 end = LLONG_MAX;
2247 len = (u64)LLONG_MAX + 1;
95418ed1 2248
90abccf2
MX
2249 /*
2250 * We write the dirty pages in the range and wait until they complete
2251 * out of the ->i_mutex. If so, we can flush the dirty pages by
2ab28f32
JB
2252 * multi-task, and make the performance up. See
2253 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
90abccf2 2254 */
669249ee 2255 ret = start_ordered_ops(inode, start, end);
90abccf2 2256 if (ret)
333427a5 2257 goto out;
90abccf2 2258
885f46d8 2259 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
c495144b 2260
2ecb7923 2261 atomic_inc(&root->log_batch);
b5e6c3e1 2262
7af59743 2263 /*
48778179
FM
2264 * Always check for the full sync flag while holding the inode's lock,
2265 * to avoid races with other tasks. The flag must be either set all the
2266 * time during logging or always off all the time while logging.
7af59743 2267 */
48778179
FM
2268 full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2269 &BTRFS_I(inode)->runtime_flags);
7af59743 2270
aab15e8e 2271 /*
885f46d8
FM
2272 * Before we acquired the inode's lock and the mmap lock, someone may
2273 * have dirtied more pages in the target range. We need to make sure
2274 * that writeback for any such pages does not start while we are logging
2275 * the inode, because if it does, any of the following might happen when
2276 * we are not doing a full inode sync:
aab15e8e
FM
2277 *
2278 * 1) We log an extent after its writeback finishes but before its
2279 * checksums are added to the csum tree, leading to -EIO errors
2280 * when attempting to read the extent after a log replay.
2281 *
2282 * 2) We can end up logging an extent before its writeback finishes.
2283 * Therefore after the log replay we will have a file extent item
2284 * pointing to an unwritten extent (and no data checksums as well).
2285 *
2286 * So trigger writeback for any eventual new dirty pages and then we
2287 * wait for all ordered extents to complete below.
2288 */
2289 ret = start_ordered_ops(inode, start, end);
2290 if (ret) {
885f46d8 2291 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
aab15e8e
FM
2292 goto out;
2293 }
2294
669249ee 2295 /*
b5e6c3e1 2296 * We have to do this here to avoid the priority inversion of waiting on
52042d8e 2297 * IO of a lower priority task while holding a transaction open.
ba0b084a 2298 *
48778179
FM
2299 * For a full fsync we wait for the ordered extents to complete while
2300 * for a fast fsync we wait just for writeback to complete, and then
2301 * attach the ordered extents to the transaction so that a transaction
2302 * commit waits for their completion, to avoid data loss if we fsync,
2303 * the current transaction commits before the ordered extents complete
2304 * and a power failure happens right after that.
d8e3fb10
NA
2305 *
2306 * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the
2307 * logical address recorded in the ordered extent may change. We need
2308 * to wait for the IO to stabilize the logical address.
669249ee 2309 */
d8e3fb10 2310 if (full_sync || btrfs_is_zoned(fs_info)) {
48778179
FM
2311 ret = btrfs_wait_ordered_range(inode, start, len);
2312 } else {
2313 /*
2314 * Get our ordered extents as soon as possible to avoid doing
2315 * checksum lookups in the csum tree, and use instead the
2316 * checksums attached to the ordered extents.
2317 */
2318 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode),
2319 &ctx.ordered_extents);
2320 ret = filemap_fdatawait_range(inode->i_mapping, start, end);
0ef8b726 2321 }
48778179
FM
2322
2323 if (ret)
2324 goto out_release_extents;
2325
2ecb7923 2326 atomic_inc(&root->log_batch);
257c62e1 2327
a4abeea4 2328 smp_mb();
626e9f41 2329 if (skip_inode_logging(&ctx)) {
5dc562c5 2330 /*
01327610 2331 * We've had everything committed since the last time we were
5dc562c5
JB
2332 * modified so clear this flag in case it was set for whatever
2333 * reason, it's no longer relevant.
2334 */
2335 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2336 &BTRFS_I(inode)->runtime_flags);
0596a904
FM
2337 /*
2338 * An ordered extent might have started before and completed
2339 * already with io errors, in which case the inode was not
2340 * updated and we end up here. So check the inode's mapping
333427a5
JL
2341 * for any errors that might have happened since we last
2342 * checked called fsync.
0596a904 2343 */
333427a5 2344 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
48778179 2345 goto out_release_extents;
15ee9bc7 2346 }
15ee9bc7 2347
5039eddc
JB
2348 /*
2349 * We use start here because we will need to wait on the IO to complete
2350 * in btrfs_sync_log, which could require joining a transaction (for
2351 * example checking cross references in the nocow path). If we use join
2352 * here we could get into a situation where we're waiting on IO to
2353 * happen that is blocked on a transaction trying to commit. With start
2354 * we inc the extwriter counter, so we wait for all extwriters to exit
52042d8e 2355 * before we start blocking joiners. This comment is to keep somebody
5039eddc
JB
2356 * from thinking they are super smart and changing this to
2357 * btrfs_join_transaction *cough*Josef*cough*.
2358 */
a22285a6
YZ
2359 trans = btrfs_start_transaction(root, 0);
2360 if (IS_ERR(trans)) {
2361 ret = PTR_ERR(trans);
48778179 2362 goto out_release_extents;
39279cc3 2363 }
d0c2f4fa 2364 trans->in_fsync = true;
e02119d5 2365
48778179
FM
2366 ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
2367 btrfs_release_log_ctx_extents(&ctx);
02c24a82 2368 if (ret < 0) {
a0634be5 2369 /* Fallthrough and commit/free transaction. */
f31f09f6 2370 ret = BTRFS_LOG_FORCE_COMMIT;
02c24a82 2371 }
49eb7e46
CM
2372
2373 /* we've logged all the items and now have a consistent
2374 * version of the file in the log. It is possible that
2375 * someone will come in and modify the file, but that's
2376 * fine because the log is consistent on disk, and we
2377 * have references to all of the file's extents
2378 *
2379 * It is possible that someone will come in and log the
2380 * file again, but that will end up using the synchronization
2381 * inside btrfs_sync_log to keep things safe.
2382 */
885f46d8 2383 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
49eb7e46 2384
bf7ba8ee
JB
2385 if (ret == BTRFS_NO_LOG_SYNC) {
2386 ret = btrfs_end_transaction(trans);
2387 goto out;
2388 }
2389
2390 /* We successfully logged the inode, attempt to sync the log. */
2391 if (!ret) {
2392 ret = btrfs_sync_log(trans, root, &ctx);
0ef8b726 2393 if (!ret) {
bf7ba8ee
JB
2394 ret = btrfs_end_transaction(trans);
2395 goto out;
48778179 2396 }
bf7ba8ee
JB
2397 }
2398
2399 /*
2400 * At this point we need to commit the transaction because we had
2401 * btrfs_need_log_full_commit() or some other error.
2402 *
2403 * If we didn't do a full sync we have to stop the trans handle, wait on
2404 * the ordered extents, start it again and commit the transaction. If
2405 * we attempt to wait on the ordered extents here we could deadlock with
2406 * something like fallocate() that is holding the extent lock trying to
2407 * start a transaction while some other thread is trying to commit the
2408 * transaction while we (fsync) are currently holding the transaction
2409 * open.
2410 */
2411 if (!full_sync) {
3a45bb20 2412 ret = btrfs_end_transaction(trans);
bf7ba8ee
JB
2413 if (ret)
2414 goto out;
2415 ret = btrfs_wait_ordered_range(inode, start, len);
2416 if (ret)
2417 goto out;
2418
2419 /*
2420 * This is safe to use here because we're only interested in
2421 * making sure the transaction that had the ordered extents is
2422 * committed. We aren't waiting on anything past this point,
2423 * we're purely getting the transaction and committing it.
2424 */
2425 trans = btrfs_attach_transaction_barrier(root);
2426 if (IS_ERR(trans)) {
2427 ret = PTR_ERR(trans);
2428
2429 /*
2430 * We committed the transaction and there's no currently
2431 * running transaction, this means everything we care
2432 * about made it to disk and we are done.
2433 */
2434 if (ret == -ENOENT)
2435 ret = 0;
2436 goto out;
2437 }
e02119d5 2438 }
bf7ba8ee
JB
2439
2440 ret = btrfs_commit_transaction(trans);
39279cc3 2441out:
ebb70442 2442 ASSERT(list_empty(&ctx.list));
e09d94c9 2443 ASSERT(list_empty(&ctx.conflict_inodes));
333427a5
JL
2444 err = file_check_and_advance_wb_err(file);
2445 if (!ret)
2446 ret = err;
014e4ac4 2447 return ret > 0 ? -EIO : ret;
48778179
FM
2448
2449out_release_extents:
2450 btrfs_release_log_ctx_extents(&ctx);
885f46d8 2451 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
48778179 2452 goto out;
39279cc3
CM
2453}
2454
f0f37e2f 2455static const struct vm_operations_struct btrfs_file_vm_ops = {
92fee66d 2456 .fault = filemap_fault,
f1820361 2457 .map_pages = filemap_map_pages,
9ebefb18
CM
2458 .page_mkwrite = btrfs_page_mkwrite,
2459};
2460
2461static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
2462{
058a457e
MX
2463 struct address_space *mapping = filp->f_mapping;
2464
7e0a1265 2465 if (!mapping->a_ops->read_folio)
058a457e
MX
2466 return -ENOEXEC;
2467
9ebefb18 2468 file_accessed(filp);
058a457e 2469 vma->vm_ops = &btrfs_file_vm_ops;
058a457e 2470
9ebefb18
CM
2471 return 0;
2472}
2473
35339c24 2474static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2aaa6655
JB
2475 int slot, u64 start, u64 end)
2476{
2477 struct btrfs_file_extent_item *fi;
2478 struct btrfs_key key;
2479
2480 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2481 return 0;
2482
2483 btrfs_item_key_to_cpu(leaf, &key, slot);
35339c24 2484 if (key.objectid != btrfs_ino(inode) ||
2aaa6655
JB
2485 key.type != BTRFS_EXTENT_DATA_KEY)
2486 return 0;
2487
2488 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2489
2490 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2491 return 0;
2492
2493 if (btrfs_file_extent_disk_bytenr(leaf, fi))
2494 return 0;
2495
2496 if (key.offset == end)
2497 return 1;
2498 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2499 return 1;
2500 return 0;
2501}
2502
a012a74e
NB
2503static int fill_holes(struct btrfs_trans_handle *trans,
2504 struct btrfs_inode *inode,
2505 struct btrfs_path *path, u64 offset, u64 end)
2aaa6655 2506{
3ffbd68c 2507 struct btrfs_fs_info *fs_info = trans->fs_info;
a012a74e 2508 struct btrfs_root *root = inode->root;
2aaa6655
JB
2509 struct extent_buffer *leaf;
2510 struct btrfs_file_extent_item *fi;
2511 struct extent_map *hole_em;
a012a74e 2512 struct extent_map_tree *em_tree = &inode->extent_tree;
2aaa6655
JB
2513 struct btrfs_key key;
2514 int ret;
2515
0b246afa 2516 if (btrfs_fs_incompat(fs_info, NO_HOLES))
16e7549f
JB
2517 goto out;
2518
a012a74e 2519 key.objectid = btrfs_ino(inode);
2aaa6655
JB
2520 key.type = BTRFS_EXTENT_DATA_KEY;
2521 key.offset = offset;
2522
2aaa6655 2523 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
f94480bd
JB
2524 if (ret <= 0) {
2525 /*
2526 * We should have dropped this offset, so if we find it then
2527 * something has gone horribly wrong.
2528 */
2529 if (ret == 0)
2530 ret = -EINVAL;
2aaa6655 2531 return ret;
f94480bd 2532 }
2aaa6655
JB
2533
2534 leaf = path->nodes[0];
a012a74e 2535 if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2aaa6655
JB
2536 u64 num_bytes;
2537
2538 path->slots[0]--;
2539 fi = btrfs_item_ptr(leaf, path->slots[0],
2540 struct btrfs_file_extent_item);
2541 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2542 end - offset;
2543 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2544 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2545 btrfs_set_file_extent_offset(leaf, fi, 0);
e6e3dec6 2546 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2aaa6655
JB
2547 btrfs_mark_buffer_dirty(leaf);
2548 goto out;
2549 }
2550
1707e26d 2551 if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2aaa6655
JB
2552 u64 num_bytes;
2553
2aaa6655 2554 key.offset = offset;
0b246afa 2555 btrfs_set_item_key_safe(fs_info, path, &key);
2aaa6655
JB
2556 fi = btrfs_item_ptr(leaf, path->slots[0],
2557 struct btrfs_file_extent_item);
2558 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2559 offset;
2560 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2561 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2562 btrfs_set_file_extent_offset(leaf, fi, 0);
e6e3dec6 2563 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2aaa6655
JB
2564 btrfs_mark_buffer_dirty(leaf);
2565 goto out;
2566 }
2567 btrfs_release_path(path);
2568
d1f68ba0
OS
2569 ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset,
2570 end - offset);
2aaa6655
JB
2571 if (ret)
2572 return ret;
2573
2574out:
2575 btrfs_release_path(path);
2576
2577 hole_em = alloc_extent_map();
2578 if (!hole_em) {
2579 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
23e3337f 2580 btrfs_set_inode_full_sync(inode);
2aaa6655
JB
2581 } else {
2582 hole_em->start = offset;
2583 hole_em->len = end - offset;
cc95bef6 2584 hole_em->ram_bytes = hole_em->len;
2aaa6655
JB
2585 hole_em->orig_start = offset;
2586
2587 hole_em->block_start = EXTENT_MAP_HOLE;
2588 hole_em->block_len = 0;
b4939680 2589 hole_em->orig_block_len = 0;
2aaa6655
JB
2590 hole_em->compress_type = BTRFS_COMPRESS_NONE;
2591 hole_em->generation = trans->transid;
2592
2593 do {
2594 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2595 write_lock(&em_tree->lock);
09a2a8f9 2596 ret = add_extent_mapping(em_tree, hole_em, 1);
2aaa6655
JB
2597 write_unlock(&em_tree->lock);
2598 } while (ret == -EEXIST);
2599 free_extent_map(hole_em);
2600 if (ret)
23e3337f 2601 btrfs_set_inode_full_sync(inode);
2aaa6655
JB
2602 }
2603
2604 return 0;
2605}
2606
d7781546
QW
2607/*
2608 * Find a hole extent on given inode and change start/len to the end of hole
2609 * extent.(hole/vacuum extent whose em->start <= start &&
2610 * em->start + em->len > start)
2611 * When a hole extent is found, return 1 and modify start/len.
2612 */
dea46d84 2613static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
d7781546 2614{
dea46d84 2615 struct btrfs_fs_info *fs_info = inode->root->fs_info;
d7781546
QW
2616 struct extent_map *em;
2617 int ret = 0;
2618
dea46d84 2619 em = btrfs_get_extent(inode, NULL, 0,
609805d8 2620 round_down(*start, fs_info->sectorsize),
39b07b5d 2621 round_up(*len, fs_info->sectorsize));
9986277e
DC
2622 if (IS_ERR(em))
2623 return PTR_ERR(em);
d7781546
QW
2624
2625 /* Hole or vacuum extent(only exists in no-hole mode) */
2626 if (em->block_start == EXTENT_MAP_HOLE) {
2627 ret = 1;
2628 *len = em->start + em->len > *start + *len ?
2629 0 : *start + *len - em->start - em->len;
2630 *start = em->start + em->len;
2631 }
2632 free_extent_map(em);
2633 return ret;
2634}
2635
55961c8a
FM
2636static void btrfs_punch_hole_lock_range(struct inode *inode,
2637 const u64 lockstart,
2638 const u64 lockend,
2639 struct extent_state **cached_state)
f27451f2 2640{
0528476b
QW
2641 /*
2642 * For subpage case, if the range is not at page boundary, we could
2643 * have pages at the leading/tailing part of the range.
2644 * This could lead to dead loop since filemap_range_has_page()
2645 * will always return true.
2646 * So here we need to do extra page alignment for
2647 * filemap_range_has_page().
2648 */
2649 const u64 page_lockstart = round_up(lockstart, PAGE_SIZE);
2650 const u64 page_lockend = round_down(lockend + 1, PAGE_SIZE) - 1;
2651
f27451f2 2652 while (1) {
f27451f2
FM
2653 truncate_pagecache_range(inode, lockstart, lockend);
2654
570eb97b
JB
2655 lock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2656 cached_state);
f27451f2 2657 /*
55961c8a
FM
2658 * We can't have ordered extents in the range, nor dirty/writeback
2659 * pages, because we have locked the inode's VFS lock in exclusive
2660 * mode, we have locked the inode's i_mmap_lock in exclusive mode,
2661 * we have flushed all delalloc in the range and we have waited
2662 * for any ordered extents in the range to complete.
2663 * We can race with anyone reading pages from this range, so after
2664 * locking the range check if we have pages in the range, and if
2665 * we do, unlock the range and retry.
f27451f2 2666 */
55961c8a
FM
2667 if (!filemap_range_has_page(inode->i_mapping, page_lockstart,
2668 page_lockend))
f27451f2 2669 break;
55961c8a 2670
570eb97b
JB
2671 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2672 cached_state);
f27451f2 2673 }
63c34cb4
FM
2674
2675 btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend);
f27451f2
FM
2676}
2677
0cbb5bdf 2678static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
03fcb1ab 2679 struct btrfs_inode *inode,
690a5dbf 2680 struct btrfs_path *path,
bf385648 2681 struct btrfs_replace_extent_info *extent_info,
2766ff61
FM
2682 const u64 replace_len,
2683 const u64 bytes_to_drop)
690a5dbf 2684{
03fcb1ab
NB
2685 struct btrfs_fs_info *fs_info = trans->fs_info;
2686 struct btrfs_root *root = inode->root;
690a5dbf
FM
2687 struct btrfs_file_extent_item *extent;
2688 struct extent_buffer *leaf;
2689 struct btrfs_key key;
2690 int slot;
2691 struct btrfs_ref ref = { 0 };
690a5dbf
FM
2692 int ret;
2693
bf385648 2694 if (replace_len == 0)
690a5dbf
FM
2695 return 0;
2696
bf385648 2697 if (extent_info->disk_offset == 0 &&
2766ff61 2698 btrfs_fs_incompat(fs_info, NO_HOLES)) {
03fcb1ab 2699 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
690a5dbf 2700 return 0;
2766ff61 2701 }
690a5dbf 2702
03fcb1ab 2703 key.objectid = btrfs_ino(inode);
690a5dbf 2704 key.type = BTRFS_EXTENT_DATA_KEY;
bf385648 2705 key.offset = extent_info->file_offset;
690a5dbf 2706 ret = btrfs_insert_empty_item(trans, root, path, &key,
fb870f6c 2707 sizeof(struct btrfs_file_extent_item));
690a5dbf
FM
2708 if (ret)
2709 return ret;
2710 leaf = path->nodes[0];
2711 slot = path->slots[0];
bf385648 2712 write_extent_buffer(leaf, extent_info->extent_buf,
690a5dbf 2713 btrfs_item_ptr_offset(leaf, slot),
fb870f6c 2714 sizeof(struct btrfs_file_extent_item));
690a5dbf 2715 extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
fb870f6c 2716 ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
bf385648
FM
2717 btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
2718 btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
2719 if (extent_info->is_new_extent)
8fccebfa 2720 btrfs_set_file_extent_generation(leaf, extent, trans->transid);
690a5dbf
FM
2721 btrfs_mark_buffer_dirty(leaf);
2722 btrfs_release_path(path);
2723
03fcb1ab
NB
2724 ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
2725 replace_len);
9ddc959e
JB
2726 if (ret)
2727 return ret;
2728
690a5dbf 2729 /* If it's a hole, nothing more needs to be done. */
2766ff61 2730 if (extent_info->disk_offset == 0) {
03fcb1ab 2731 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
690a5dbf 2732 return 0;
2766ff61 2733 }
690a5dbf 2734
03fcb1ab 2735 btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
8fccebfa 2736
bf385648
FM
2737 if (extent_info->is_new_extent && extent_info->insertions == 0) {
2738 key.objectid = extent_info->disk_offset;
8fccebfa 2739 key.type = BTRFS_EXTENT_ITEM_KEY;
bf385648 2740 key.offset = extent_info->disk_len;
8fccebfa 2741 ret = btrfs_alloc_reserved_file_extent(trans, root,
03fcb1ab 2742 btrfs_ino(inode),
bf385648
FM
2743 extent_info->file_offset,
2744 extent_info->qgroup_reserved,
8fccebfa
FM
2745 &key);
2746 } else {
2747 u64 ref_offset;
2748
2749 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
bf385648
FM
2750 extent_info->disk_offset,
2751 extent_info->disk_len, 0);
2752 ref_offset = extent_info->file_offset - extent_info->data_offset;
8fccebfa 2753 btrfs_init_data_ref(&ref, root->root_key.objectid,
f42c5da6 2754 btrfs_ino(inode), ref_offset, 0, false);
8fccebfa
FM
2755 ret = btrfs_inc_extent_ref(trans, &ref);
2756 }
2757
bf385648 2758 extent_info->insertions++;
690a5dbf
FM
2759
2760 return ret;
2761}
2762
9cba40a6
FM
2763/*
2764 * The respective range must have been previously locked, as well as the inode.
2765 * The end offset is inclusive (last byte of the range).
bf385648
FM
2766 * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2767 * the file range with an extent.
2768 * When not punching a hole, we don't want to end up in a state where we dropped
2769 * extents without inserting a new one, so we must abort the transaction to avoid
2770 * a corruption.
9cba40a6 2771 */
bfc78479
NB
2772int btrfs_replace_file_extents(struct btrfs_inode *inode,
2773 struct btrfs_path *path, const u64 start,
2774 const u64 end,
2775 struct btrfs_replace_extent_info *extent_info,
2776 struct btrfs_trans_handle **trans_out)
9cba40a6 2777{
5893dfb9 2778 struct btrfs_drop_extents_args drop_args = { 0 };
bfc78479
NB
2779 struct btrfs_root *root = inode->root;
2780 struct btrfs_fs_info *fs_info = root->fs_info;
2bd36e7b 2781 u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
bfc78479 2782 u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
9cba40a6
FM
2783 struct btrfs_trans_handle *trans = NULL;
2784 struct btrfs_block_rsv *rsv;
2785 unsigned int rsv_count;
2786 u64 cur_offset;
9cba40a6
FM
2787 u64 len = end - start;
2788 int ret = 0;
2789
2790 if (end <= start)
2791 return -EINVAL;
2792
2793 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2794 if (!rsv) {
2795 ret = -ENOMEM;
2796 goto out;
2797 }
2bd36e7b 2798 rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
710d5921 2799 rsv->failfast = true;
9cba40a6
FM
2800
2801 /*
2802 * 1 - update the inode
2803 * 1 - removing the extents in the range
bf385648
FM
2804 * 1 - adding the hole extent if no_holes isn't set or if we are
2805 * replacing the range with a new extent
9cba40a6 2806 */
bf385648 2807 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
690a5dbf
FM
2808 rsv_count = 3;
2809 else
2810 rsv_count = 2;
2811
9cba40a6
FM
2812 trans = btrfs_start_transaction(root, rsv_count);
2813 if (IS_ERR(trans)) {
2814 ret = PTR_ERR(trans);
2815 trans = NULL;
2816 goto out_free;
2817 }
2818
2819 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2820 min_size, false);
650c9cab
FM
2821 if (WARN_ON(ret))
2822 goto out_trans;
9cba40a6
FM
2823 trans->block_rsv = rsv;
2824
2825 cur_offset = start;
5893dfb9
FM
2826 drop_args.path = path;
2827 drop_args.end = end + 1;
2828 drop_args.drop_cache = true;
9cba40a6 2829 while (cur_offset < end) {
5893dfb9 2830 drop_args.start = cur_offset;
bfc78479 2831 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2766ff61
FM
2832 /* If we are punching a hole decrement the inode's byte count */
2833 if (!extent_info)
bfc78479 2834 btrfs_update_inode_bytes(inode, 0,
2766ff61 2835 drop_args.bytes_found);
690a5dbf
FM
2836 if (ret != -ENOSPC) {
2837 /*
4afb912f
JB
2838 * The only time we don't want to abort is if we are
2839 * attempting to clone a partial inline extent, in which
2840 * case we'll get EOPNOTSUPP. However if we aren't
2841 * clone we need to abort no matter what, because if we
2842 * got EOPNOTSUPP via prealloc then we messed up and
2843 * need to abort.
690a5dbf 2844 */
4afb912f
JB
2845 if (ret &&
2846 (ret != -EOPNOTSUPP ||
2847 (extent_info && extent_info->is_new_extent)))
690a5dbf 2848 btrfs_abort_transaction(trans, ret);
9cba40a6 2849 break;
690a5dbf 2850 }
9cba40a6
FM
2851
2852 trans->block_rsv = &fs_info->trans_block_rsv;
2853
5893dfb9 2854 if (!extent_info && cur_offset < drop_args.drop_end &&
690a5dbf 2855 cur_offset < ino_size) {
bfc78479
NB
2856 ret = fill_holes(trans, inode, path, cur_offset,
2857 drop_args.drop_end);
9cba40a6
FM
2858 if (ret) {
2859 /*
2860 * If we failed then we didn't insert our hole
2861 * entries for the area we dropped, so now the
2862 * fs is corrupted, so we must abort the
2863 * transaction.
2864 */
2865 btrfs_abort_transaction(trans, ret);
2866 break;
2867 }
5893dfb9 2868 } else if (!extent_info && cur_offset < drop_args.drop_end) {
9ddc959e
JB
2869 /*
2870 * We are past the i_size here, but since we didn't
2871 * insert holes we need to clear the mapped area so we
2872 * know to not set disk_i_size in this area until a new
2873 * file extent is inserted here.
2874 */
bfc78479 2875 ret = btrfs_inode_clear_file_extent_range(inode,
5893dfb9
FM
2876 cur_offset,
2877 drop_args.drop_end - cur_offset);
9ddc959e
JB
2878 if (ret) {
2879 /*
2880 * We couldn't clear our area, so we could
2881 * presumably adjust up and corrupt the fs, so
2882 * we need to abort.
2883 */
2884 btrfs_abort_transaction(trans, ret);
2885 break;
2886 }
9cba40a6
FM
2887 }
2888
5893dfb9
FM
2889 if (extent_info &&
2890 drop_args.drop_end > extent_info->file_offset) {
2891 u64 replace_len = drop_args.drop_end -
2892 extent_info->file_offset;
690a5dbf 2893
bfc78479
NB
2894 ret = btrfs_insert_replace_extent(trans, inode, path,
2895 extent_info, replace_len,
03fcb1ab 2896 drop_args.bytes_found);
690a5dbf
FM
2897 if (ret) {
2898 btrfs_abort_transaction(trans, ret);
2899 break;
2900 }
bf385648
FM
2901 extent_info->data_len -= replace_len;
2902 extent_info->data_offset += replace_len;
2903 extent_info->file_offset += replace_len;
690a5dbf
FM
2904 }
2905
983d8209
FM
2906 /*
2907 * We are releasing our handle on the transaction, balance the
2908 * dirty pages of the btree inode and flush delayed items, and
2909 * then get a new transaction handle, which may now point to a
2910 * new transaction in case someone else may have committed the
2911 * transaction we used to replace/drop file extent items. So
2912 * bump the inode's iversion and update mtime and ctime except
2913 * if we are called from a dedupe context. This is because a
2914 * power failure/crash may happen after the transaction is
2915 * committed and before we finish replacing/dropping all the
2916 * file extent items we need.
2917 */
2918 inode_inc_iversion(&inode->vfs_inode);
2919
2920 if (!extent_info || extent_info->update_times) {
2921 inode->vfs_inode.i_mtime = current_time(&inode->vfs_inode);
2922 inode->vfs_inode.i_ctime = inode->vfs_inode.i_mtime;
2923 }
2924
bfc78479 2925 ret = btrfs_update_inode(trans, root, inode);
9cba40a6
FM
2926 if (ret)
2927 break;
2928
2929 btrfs_end_transaction(trans);
2930 btrfs_btree_balance_dirty(fs_info);
2931
2932 trans = btrfs_start_transaction(root, rsv_count);
2933 if (IS_ERR(trans)) {
2934 ret = PTR_ERR(trans);
2935 trans = NULL;
2936 break;
2937 }
2938
2939 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2940 rsv, min_size, false);
650c9cab
FM
2941 if (WARN_ON(ret))
2942 break;
9cba40a6
FM
2943 trans->block_rsv = rsv;
2944
3227788c
BC
2945 cur_offset = drop_args.drop_end;
2946 len = end - cur_offset;
2947 if (!extent_info && len) {
bfc78479 2948 ret = find_first_non_hole(inode, &cur_offset, &len);
690a5dbf
FM
2949 if (unlikely(ret < 0))
2950 break;
2951 if (ret && !len) {
2952 ret = 0;
2953 break;
2954 }
9cba40a6
FM
2955 }
2956 }
2957
690a5dbf
FM
2958 /*
2959 * If we were cloning, force the next fsync to be a full one since we
2960 * we replaced (or just dropped in the case of cloning holes when
e2b84217
FM
2961 * NO_HOLES is enabled) file extent items and did not setup new extent
2962 * maps for the replacement extents (or holes).
690a5dbf 2963 */
bf385648 2964 if (extent_info && !extent_info->is_new_extent)
23e3337f 2965 btrfs_set_inode_full_sync(inode);
690a5dbf 2966
9cba40a6
FM
2967 if (ret)
2968 goto out_trans;
2969
2970 trans->block_rsv = &fs_info->trans_block_rsv;
2971 /*
2972 * If we are using the NO_HOLES feature we might have had already an
2973 * hole that overlaps a part of the region [lockstart, lockend] and
2974 * ends at (or beyond) lockend. Since we have no file extent items to
2975 * represent holes, drop_end can be less than lockend and so we must
2976 * make sure we have an extent map representing the existing hole (the
2977 * call to __btrfs_drop_extents() might have dropped the existing extent
2978 * map representing the existing hole), otherwise the fast fsync path
2979 * will not record the existence of the hole region
2980 * [existing_hole_start, lockend].
2981 */
5893dfb9
FM
2982 if (drop_args.drop_end <= end)
2983 drop_args.drop_end = end + 1;
9cba40a6
FM
2984 /*
2985 * Don't insert file hole extent item if it's for a range beyond eof
2986 * (because it's useless) or if it represents a 0 bytes range (when
2987 * cur_offset == drop_end).
2988 */
5893dfb9
FM
2989 if (!extent_info && cur_offset < ino_size &&
2990 cur_offset < drop_args.drop_end) {
bfc78479
NB
2991 ret = fill_holes(trans, inode, path, cur_offset,
2992 drop_args.drop_end);
9cba40a6
FM
2993 if (ret) {
2994 /* Same comment as above. */
2995 btrfs_abort_transaction(trans, ret);
2996 goto out_trans;
2997 }
5893dfb9 2998 } else if (!extent_info && cur_offset < drop_args.drop_end) {
9ddc959e 2999 /* See the comment in the loop above for the reasoning here. */
bfc78479
NB
3000 ret = btrfs_inode_clear_file_extent_range(inode, cur_offset,
3001 drop_args.drop_end - cur_offset);
9ddc959e
JB
3002 if (ret) {
3003 btrfs_abort_transaction(trans, ret);
3004 goto out_trans;
3005 }
3006
9cba40a6 3007 }
bf385648 3008 if (extent_info) {
bfc78479 3009 ret = btrfs_insert_replace_extent(trans, inode, path,
03fcb1ab
NB
3010 extent_info, extent_info->data_len,
3011 drop_args.bytes_found);
690a5dbf
FM
3012 if (ret) {
3013 btrfs_abort_transaction(trans, ret);
3014 goto out_trans;
3015 }
3016 }
9cba40a6
FM
3017
3018out_trans:
3019 if (!trans)
3020 goto out_free;
3021
3022 trans->block_rsv = &fs_info->trans_block_rsv;
3023 if (ret)
3024 btrfs_end_transaction(trans);
3025 else
3026 *trans_out = trans;
3027out_free:
3028 btrfs_free_block_rsv(fs_info, rsv);
3029out:
3030 return ret;
3031}
3032
05fd9564 3033static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len)
2aaa6655 3034{
05fd9564 3035 struct inode *inode = file_inode(file);
0b246afa 3036 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2aaa6655
JB
3037 struct btrfs_root *root = BTRFS_I(inode)->root;
3038 struct extent_state *cached_state = NULL;
3039 struct btrfs_path *path;
9cba40a6 3040 struct btrfs_trans_handle *trans = NULL;
d7781546
QW
3041 u64 lockstart;
3042 u64 lockend;
3043 u64 tail_start;
3044 u64 tail_len;
3045 u64 orig_start = offset;
2aaa6655 3046 int ret = 0;
9703fefe 3047 bool same_block;
a1a50f60 3048 u64 ino_size;
9703fefe 3049 bool truncated_block = false;
e8c1c76e 3050 bool updated_inode = false;
2aaa6655 3051
bd6526d0
FM
3052 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
3053
0ef8b726
JB
3054 ret = btrfs_wait_ordered_range(inode, offset, len);
3055 if (ret)
bd6526d0 3056 goto out_only_mutex;
2aaa6655 3057
0b246afa 3058 ino_size = round_up(inode->i_size, fs_info->sectorsize);
dea46d84 3059 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
d7781546
QW
3060 if (ret < 0)
3061 goto out_only_mutex;
3062 if (ret && !len) {
3063 /* Already in a large hole */
3064 ret = 0;
3065 goto out_only_mutex;
3066 }
3067
05fd9564
DW
3068 ret = file_modified(file);
3069 if (ret)
3070 goto out_only_mutex;
3071
ee8ba05c
JB
3072 lockstart = round_up(offset, fs_info->sectorsize);
3073 lockend = round_down(offset + len, fs_info->sectorsize) - 1;
0b246afa
JM
3074 same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
3075 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
7426cc04 3076 /*
9703fefe 3077 * We needn't truncate any block which is beyond the end of the file
7426cc04
MX
3078 * because we are sure there is no data there.
3079 */
2aaa6655 3080 /*
9703fefe
CR
3081 * Only do this if we are in the same block and we aren't doing the
3082 * entire block.
2aaa6655 3083 */
0b246afa 3084 if (same_block && len < fs_info->sectorsize) {
e8c1c76e 3085 if (offset < ino_size) {
9703fefe 3086 truncated_block = true;
217f42eb
NB
3087 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3088 0);
e8c1c76e
FM
3089 } else {
3090 ret = 0;
3091 }
d7781546 3092 goto out_only_mutex;
2aaa6655
JB
3093 }
3094
9703fefe 3095 /* zero back part of the first block */
12870f1c 3096 if (offset < ino_size) {
9703fefe 3097 truncated_block = true;
217f42eb 3098 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
7426cc04 3099 if (ret) {
8d9b4a16 3100 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
7426cc04
MX
3101 return ret;
3102 }
2aaa6655
JB
3103 }
3104
d7781546
QW
3105 /* Check the aligned pages after the first unaligned page,
3106 * if offset != orig_start, which means the first unaligned page
01327610 3107 * including several following pages are already in holes,
d7781546
QW
3108 * the extra check can be skipped */
3109 if (offset == orig_start) {
3110 /* after truncate page, check hole again */
3111 len = offset + len - lockstart;
3112 offset = lockstart;
dea46d84 3113 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
d7781546
QW
3114 if (ret < 0)
3115 goto out_only_mutex;
3116 if (ret && !len) {
3117 ret = 0;
3118 goto out_only_mutex;
3119 }
3120 lockstart = offset;
3121 }
3122
3123 /* Check the tail unaligned part is in a hole */
3124 tail_start = lockend + 1;
3125 tail_len = offset + len - tail_start;
3126 if (tail_len) {
dea46d84 3127 ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
d7781546
QW
3128 if (unlikely(ret < 0))
3129 goto out_only_mutex;
3130 if (!ret) {
3131 /* zero the front end of the last page */
3132 if (tail_start + tail_len < ino_size) {
9703fefe 3133 truncated_block = true;
217f42eb 3134 ret = btrfs_truncate_block(BTRFS_I(inode),
9703fefe
CR
3135 tail_start + tail_len,
3136 0, 1);
d7781546
QW
3137 if (ret)
3138 goto out_only_mutex;
51f395ad 3139 }
0061280d 3140 }
2aaa6655
JB
3141 }
3142
3143 if (lockend < lockstart) {
e8c1c76e
FM
3144 ret = 0;
3145 goto out_only_mutex;
2aaa6655
JB
3146 }
3147
55961c8a 3148 btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state);
2aaa6655
JB
3149
3150 path = btrfs_alloc_path();
3151 if (!path) {
3152 ret = -ENOMEM;
3153 goto out;
3154 }
3155
bfc78479
NB
3156 ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart,
3157 lockend, NULL, &trans);
9cba40a6
FM
3158 btrfs_free_path(path);
3159 if (ret)
3160 goto out;
2aaa6655 3161
9cba40a6 3162 ASSERT(trans != NULL);
e1f5790e 3163 inode_inc_iversion(inode);
c1867eb3
DS
3164 inode->i_mtime = current_time(inode);
3165 inode->i_ctime = inode->i_mtime;
9a56fcd1 3166 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
e8c1c76e 3167 updated_inode = true;
3a45bb20 3168 btrfs_end_transaction(trans);
2ff7e61e 3169 btrfs_btree_balance_dirty(fs_info);
2aaa6655 3170out:
570eb97b
JB
3171 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3172 &cached_state);
d7781546 3173out_only_mutex:
9cba40a6 3174 if (!updated_inode && truncated_block && !ret) {
e8c1c76e
FM
3175 /*
3176 * If we only end up zeroing part of a page, we still need to
3177 * update the inode item, so that all the time fields are
3178 * updated as well as the necessary btrfs inode in memory fields
3179 * for detecting, at fsync time, if the inode isn't yet in the
3180 * log tree or it's there but not up to date.
3181 */
17900668
FM
3182 struct timespec64 now = current_time(inode);
3183
3184 inode_inc_iversion(inode);
3185 inode->i_mtime = now;
3186 inode->i_ctime = now;
e8c1c76e
FM
3187 trans = btrfs_start_transaction(root, 1);
3188 if (IS_ERR(trans)) {
9cba40a6 3189 ret = PTR_ERR(trans);
e8c1c76e 3190 } else {
9cba40a6
FM
3191 int ret2;
3192
9a56fcd1 3193 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9cba40a6
FM
3194 ret2 = btrfs_end_transaction(trans);
3195 if (!ret)
3196 ret = ret2;
e8c1c76e
FM
3197 }
3198 }
8d9b4a16 3199 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
9cba40a6 3200 return ret;
2aaa6655
JB
3201}
3202
14524a84
QW
3203/* Helper structure to record which range is already reserved */
3204struct falloc_range {
3205 struct list_head list;
3206 u64 start;
3207 u64 len;
3208};
3209
3210/*
3211 * Helper function to add falloc range
3212 *
3213 * Caller should have locked the larger range of extent containing
3214 * [start, len)
3215 */
3216static int add_falloc_range(struct list_head *head, u64 start, u64 len)
3217{
14524a84
QW
3218 struct falloc_range *range = NULL;
3219
77d25534
NB
3220 if (!list_empty(head)) {
3221 /*
3222 * As fallocate iterates by bytenr order, we only need to check
3223 * the last range.
3224 */
3225 range = list_last_entry(head, struct falloc_range, list);
3226 if (range->start + range->len == start) {
3227 range->len += len;
3228 return 0;
3229 }
14524a84 3230 }
77d25534 3231
32fc932e 3232 range = kmalloc(sizeof(*range), GFP_KERNEL);
14524a84
QW
3233 if (!range)
3234 return -ENOMEM;
3235 range->start = start;
3236 range->len = len;
3237 list_add_tail(&range->list, head);
3238 return 0;
3239}
3240
f27451f2
FM
3241static int btrfs_fallocate_update_isize(struct inode *inode,
3242 const u64 end,
3243 const int mode)
3244{
3245 struct btrfs_trans_handle *trans;
3246 struct btrfs_root *root = BTRFS_I(inode)->root;
3247 int ret;
3248 int ret2;
3249
3250 if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
3251 return 0;
3252
3253 trans = btrfs_start_transaction(root, 1);
3254 if (IS_ERR(trans))
3255 return PTR_ERR(trans);
3256
3257 inode->i_ctime = current_time(inode);
3258 i_size_write(inode, end);
76aea537 3259 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9a56fcd1 3260 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
f27451f2
FM
3261 ret2 = btrfs_end_transaction(trans);
3262
3263 return ret ? ret : ret2;
3264}
3265
81fdf638 3266enum {
f262fa8d
DS
3267 RANGE_BOUNDARY_WRITTEN_EXTENT,
3268 RANGE_BOUNDARY_PREALLOC_EXTENT,
3269 RANGE_BOUNDARY_HOLE,
81fdf638
FM
3270};
3271
948dfeb8 3272static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
f27451f2
FM
3273 u64 offset)
3274{
ee8ba05c 3275 const u64 sectorsize = inode->root->fs_info->sectorsize;
f27451f2 3276 struct extent_map *em;
81fdf638 3277 int ret;
f27451f2
FM
3278
3279 offset = round_down(offset, sectorsize);
948dfeb8 3280 em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize);
f27451f2
FM
3281 if (IS_ERR(em))
3282 return PTR_ERR(em);
3283
3284 if (em->block_start == EXTENT_MAP_HOLE)
81fdf638
FM
3285 ret = RANGE_BOUNDARY_HOLE;
3286 else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3287 ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
3288 else
3289 ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
f27451f2
FM
3290
3291 free_extent_map(em);
3292 return ret;
3293}
3294
3295static int btrfs_zero_range(struct inode *inode,
3296 loff_t offset,
3297 loff_t len,
3298 const int mode)
3299{
3300 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3301 struct extent_map *em;
3302 struct extent_changeset *data_reserved = NULL;
3303 int ret;
3304 u64 alloc_hint = 0;
ee8ba05c 3305 const u64 sectorsize = fs_info->sectorsize;
f27451f2
FM
3306 u64 alloc_start = round_down(offset, sectorsize);
3307 u64 alloc_end = round_up(offset + len, sectorsize);
3308 u64 bytes_to_reserve = 0;
3309 bool space_reserved = false;
3310
39b07b5d
OS
3311 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3312 alloc_end - alloc_start);
f27451f2
FM
3313 if (IS_ERR(em)) {
3314 ret = PTR_ERR(em);
3315 goto out;
3316 }
3317
3318 /*
3319 * Avoid hole punching and extent allocation for some cases. More cases
3320 * could be considered, but these are unlikely common and we keep things
3321 * as simple as possible for now. Also, intentionally, if the target
3322 * range contains one or more prealloc extents together with regular
3323 * extents and holes, we drop all the existing extents and allocate a
3324 * new prealloc extent, so that we get a larger contiguous disk extent.
3325 */
3326 if (em->start <= alloc_start &&
3327 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3328 const u64 em_end = em->start + em->len;
3329
3330 if (em_end >= offset + len) {
3331 /*
3332 * The whole range is already a prealloc extent,
3333 * do nothing except updating the inode's i_size if
3334 * needed.
3335 */
3336 free_extent_map(em);
3337 ret = btrfs_fallocate_update_isize(inode, offset + len,
3338 mode);
3339 goto out;
3340 }
3341 /*
3342 * Part of the range is already a prealloc extent, so operate
3343 * only on the remaining part of the range.
3344 */
3345 alloc_start = em_end;
3346 ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3347 len = offset + len - alloc_start;
3348 offset = alloc_start;
3349 alloc_hint = em->block_start + em->len;
3350 }
3351 free_extent_map(em);
3352
3353 if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3354 BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
39b07b5d
OS
3355 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3356 sectorsize);
f27451f2
FM
3357 if (IS_ERR(em)) {
3358 ret = PTR_ERR(em);
3359 goto out;
3360 }
3361
3362 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3363 free_extent_map(em);
3364 ret = btrfs_fallocate_update_isize(inode, offset + len,
3365 mode);
3366 goto out;
3367 }
3368 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3369 free_extent_map(em);
217f42eb
NB
3370 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3371 0);
f27451f2
FM
3372 if (!ret)
3373 ret = btrfs_fallocate_update_isize(inode,
3374 offset + len,
3375 mode);
3376 return ret;
3377 }
3378 free_extent_map(em);
3379 alloc_start = round_down(offset, sectorsize);
3380 alloc_end = alloc_start + sectorsize;
3381 goto reserve_space;
3382 }
3383
3384 alloc_start = round_up(offset, sectorsize);
3385 alloc_end = round_down(offset + len, sectorsize);
3386
3387 /*
3388 * For unaligned ranges, check the pages at the boundaries, they might
3389 * map to an extent, in which case we need to partially zero them, or
3390 * they might map to a hole, in which case we need our allocation range
3391 * to cover them.
3392 */
3393 if (!IS_ALIGNED(offset, sectorsize)) {
948dfeb8
NB
3394 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3395 offset);
f27451f2
FM
3396 if (ret < 0)
3397 goto out;
81fdf638 3398 if (ret == RANGE_BOUNDARY_HOLE) {
f27451f2
FM
3399 alloc_start = round_down(offset, sectorsize);
3400 ret = 0;
81fdf638 3401 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
217f42eb 3402 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
f27451f2
FM
3403 if (ret)
3404 goto out;
81fdf638
FM
3405 } else {
3406 ret = 0;
f27451f2
FM
3407 }
3408 }
3409
3410 if (!IS_ALIGNED(offset + len, sectorsize)) {
948dfeb8 3411 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
f27451f2
FM
3412 offset + len);
3413 if (ret < 0)
3414 goto out;
81fdf638 3415 if (ret == RANGE_BOUNDARY_HOLE) {
f27451f2
FM
3416 alloc_end = round_up(offset + len, sectorsize);
3417 ret = 0;
81fdf638 3418 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
217f42eb
NB
3419 ret = btrfs_truncate_block(BTRFS_I(inode), offset + len,
3420 0, 1);
f27451f2
FM
3421 if (ret)
3422 goto out;
81fdf638
FM
3423 } else {
3424 ret = 0;
f27451f2
FM
3425 }
3426 }
3427
3428reserve_space:
3429 if (alloc_start < alloc_end) {
3430 struct extent_state *cached_state = NULL;
3431 const u64 lockstart = alloc_start;
3432 const u64 lockend = alloc_end - 1;
3433
3434 bytes_to_reserve = alloc_end - alloc_start;
3435 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3436 bytes_to_reserve);
3437 if (ret < 0)
3438 goto out;
3439 space_reserved = true;
55961c8a
FM
3440 btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3441 &cached_state);
7661a3e0 3442 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
a7f8b1c2 3443 alloc_start, bytes_to_reserve);
4f6a49de 3444 if (ret) {
570eb97b
JB
3445 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart,
3446 lockend, &cached_state);
a7f8b1c2 3447 goto out;
4f6a49de 3448 }
f27451f2
FM
3449 ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3450 alloc_end - alloc_start,
3451 i_blocksize(inode),
3452 offset + len, &alloc_hint);
570eb97b
JB
3453 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3454 &cached_state);
f27451f2 3455 /* btrfs_prealloc_file_range releases reserved space on error */
9f13ce74 3456 if (ret) {
f27451f2 3457 space_reserved = false;
9f13ce74
FM
3458 goto out;
3459 }
f27451f2 3460 }
9f13ce74 3461 ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
f27451f2
FM
3462 out:
3463 if (ret && space_reserved)
25ce28ca 3464 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
f27451f2
FM
3465 alloc_start, bytes_to_reserve);
3466 extent_changeset_free(data_reserved);
3467
3468 return ret;
3469}
3470
2fe17c10
CH
3471static long btrfs_fallocate(struct file *file, int mode,
3472 loff_t offset, loff_t len)
3473{
496ad9aa 3474 struct inode *inode = file_inode(file);
2fe17c10 3475 struct extent_state *cached_state = NULL;
364ecf36 3476 struct extent_changeset *data_reserved = NULL;
14524a84
QW
3477 struct falloc_range *range;
3478 struct falloc_range *tmp;
3479 struct list_head reserve_list;
2fe17c10
CH
3480 u64 cur_offset;
3481 u64 last_byte;
3482 u64 alloc_start;
3483 u64 alloc_end;
3484 u64 alloc_hint = 0;
3485 u64 locked_end;
14524a84 3486 u64 actual_end = 0;
47e1d1c7
FM
3487 u64 data_space_needed = 0;
3488 u64 data_space_reserved = 0;
3489 u64 qgroup_reserved = 0;
2fe17c10 3490 struct extent_map *em;
ee8ba05c 3491 int blocksize = BTRFS_I(inode)->root->fs_info->sectorsize;
2fe17c10
CH
3492 int ret;
3493
f1569c4c
NA
3494 /* Do not allow fallocate in ZONED mode */
3495 if (btrfs_is_zoned(btrfs_sb(inode->i_sb)))
3496 return -EOPNOTSUPP;
3497
797f4277
MX
3498 alloc_start = round_down(offset, blocksize);
3499 alloc_end = round_up(offset + len, blocksize);
18513091 3500 cur_offset = alloc_start;
2fe17c10 3501
2aaa6655 3502 /* Make sure we aren't being give some crap mode */
f27451f2
FM
3503 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3504 FALLOC_FL_ZERO_RANGE))
2fe17c10
CH
3505 return -EOPNOTSUPP;
3506
2aaa6655 3507 if (mode & FALLOC_FL_PUNCH_HOLE)
05fd9564 3508 return btrfs_punch_hole(file, offset, len);
2aaa6655 3509
8d9b4a16 3510 btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2a162ce9
DI
3511
3512 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3513 ret = inode_newsize_ok(inode, offset + len);
3514 if (ret)
3515 goto out;
3516 }
2fe17c10 3517
05fd9564
DW
3518 ret = file_modified(file);
3519 if (ret)
3520 goto out;
3521
14524a84
QW
3522 /*
3523 * TODO: Move these two operations after we have checked
3524 * accurate reserved space, or fallocate can still fail but
3525 * with page truncated or size expanded.
3526 *
3527 * But that's a minor problem and won't do much harm BTW.
3528 */
2fe17c10 3529 if (alloc_start > inode->i_size) {
b06359a3 3530 ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode),
a41ad394 3531 alloc_start);
2fe17c10
CH
3532 if (ret)
3533 goto out;
0f6925fa 3534 } else if (offset + len > inode->i_size) {
a71754fc
JB
3535 /*
3536 * If we are fallocating from the end of the file onward we
9703fefe
CR
3537 * need to zero out the end of the block if i_size lands in the
3538 * middle of a block.
a71754fc 3539 */
217f42eb 3540 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
a71754fc
JB
3541 if (ret)
3542 goto out;
2fe17c10
CH
3543 }
3544
a71754fc 3545 /*
ffa8fc60
FM
3546 * We have locked the inode at the VFS level (in exclusive mode) and we
3547 * have locked the i_mmap_lock lock (in exclusive mode). Now before
3548 * locking the file range, flush all dealloc in the range and wait for
3549 * all ordered extents in the range to complete. After this we can lock
3550 * the file range and, due to the previous locking we did, we know there
3551 * can't be more delalloc or ordered extents in the range.
a71754fc 3552 */
0ef8b726
JB
3553 ret = btrfs_wait_ordered_range(inode, alloc_start,
3554 alloc_end - alloc_start);
3555 if (ret)
3556 goto out;
a71754fc 3557
f27451f2
FM
3558 if (mode & FALLOC_FL_ZERO_RANGE) {
3559 ret = btrfs_zero_range(inode, offset, len, mode);
8d9b4a16 3560 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
f27451f2
FM
3561 return ret;
3562 }
3563
2fe17c10 3564 locked_end = alloc_end - 1;
570eb97b
JB
3565 lock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3566 &cached_state);
2fe17c10 3567
63c34cb4
FM
3568 btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end);
3569
14524a84
QW
3570 /* First, check if we exceed the qgroup limit */
3571 INIT_LIST_HEAD(&reserve_list);
6b7d6e93 3572 while (cur_offset < alloc_end) {
fc4f21b1 3573 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
39b07b5d 3574 alloc_end - cur_offset);
9986277e
DC
3575 if (IS_ERR(em)) {
3576 ret = PTR_ERR(em);
79787eaa
JM
3577 break;
3578 }
2fe17c10 3579 last_byte = min(extent_map_end(em), alloc_end);
f1e490a7 3580 actual_end = min_t(u64, extent_map_end(em), offset + len);
797f4277 3581 last_byte = ALIGN(last_byte, blocksize);
2fe17c10
CH
3582 if (em->block_start == EXTENT_MAP_HOLE ||
3583 (cur_offset >= inode->i_size &&
3584 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
47e1d1c7
FM
3585 const u64 range_len = last_byte - cur_offset;
3586
3587 ret = add_falloc_range(&reserve_list, cur_offset, range_len);
14524a84
QW
3588 if (ret < 0) {
3589 free_extent_map(em);
3590 break;
3d850dd4 3591 }
7661a3e0 3592 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
47e1d1c7 3593 &data_reserved, cur_offset, range_len);
be2d253c
FM
3594 if (ret < 0) {
3595 free_extent_map(em);
14524a84 3596 break;
be2d253c 3597 }
47e1d1c7
FM
3598 qgroup_reserved += range_len;
3599 data_space_needed += range_len;
2fe17c10
CH
3600 }
3601 free_extent_map(em);
2fe17c10 3602 cur_offset = last_byte;
14524a84
QW
3603 }
3604
47e1d1c7
FM
3605 if (!ret && data_space_needed > 0) {
3606 /*
3607 * We are safe to reserve space here as we can't have delalloc
3608 * in the range, see above.
3609 */
3610 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3611 data_space_needed);
3612 if (!ret)
3613 data_space_reserved = data_space_needed;
3614 }
3615
14524a84
QW
3616 /*
3617 * If ret is still 0, means we're OK to fallocate.
3618 * Or just cleanup the list and exit.
3619 */
3620 list_for_each_entry_safe(range, tmp, &reserve_list, list) {
47e1d1c7 3621 if (!ret) {
14524a84
QW
3622 ret = btrfs_prealloc_file_range(inode, mode,
3623 range->start,
93407472 3624 range->len, i_blocksize(inode),
14524a84 3625 offset + len, &alloc_hint);
47e1d1c7
FM
3626 /*
3627 * btrfs_prealloc_file_range() releases space even
3628 * if it returns an error.
3629 */
3630 data_space_reserved -= range->len;
3631 qgroup_reserved -= range->len;
3632 } else if (data_space_reserved > 0) {
25ce28ca 3633 btrfs_free_reserved_data_space(BTRFS_I(inode),
47e1d1c7
FM
3634 data_reserved, range->start,
3635 range->len);
3636 data_space_reserved -= range->len;
3637 qgroup_reserved -= range->len;
3638 } else if (qgroup_reserved > 0) {
3639 btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved,
3640 range->start, range->len);
3641 qgroup_reserved -= range->len;
3642 }
14524a84
QW
3643 list_del(&range->list);
3644 kfree(range);
3645 }
3646 if (ret < 0)
3647 goto out_unlock;
3648
f27451f2
FM
3649 /*
3650 * We didn't need to allocate any more space, but we still extended the
3651 * size of the file so we need to update i_size and the inode item.
3652 */
3653 ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
14524a84 3654out_unlock:
570eb97b
JB
3655 unlock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3656 &cached_state);
2fe17c10 3657out:
8d9b4a16 3658 btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
364ecf36 3659 extent_changeset_free(data_reserved);
2fe17c10
CH
3660 return ret;
3661}
3662
b6e83356 3663/*
ac3c0d36
FM
3664 * Helper for btrfs_find_delalloc_in_range(). Find a subrange in a given range
3665 * that has unflushed and/or flushing delalloc. There might be other adjacent
3666 * subranges after the one it found, so btrfs_find_delalloc_in_range() keeps
3667 * looping while it gets adjacent subranges, and merging them together.
b6e83356
FM
3668 */
3669static bool find_delalloc_subrange(struct btrfs_inode *inode, u64 start, u64 end,
3670 u64 *delalloc_start_ret, u64 *delalloc_end_ret)
3671{
3672 const u64 len = end + 1 - start;
3673 struct extent_map_tree *em_tree = &inode->extent_tree;
3674 struct extent_map *em;
3675 u64 em_end;
3676 u64 delalloc_len;
3677
3678 /*
3679 * Search the io tree first for EXTENT_DELALLOC. If we find any, it
3680 * means we have delalloc (dirty pages) for which writeback has not
3681 * started yet.
3682 */
3683 *delalloc_start_ret = start;
3684 delalloc_len = count_range_bits(&inode->io_tree, delalloc_start_ret, end,
3685 len, EXTENT_DELALLOC, 1);
3686 /*
3687 * If delalloc was found then *delalloc_start_ret has a sector size
3688 * aligned value (rounded down).
3689 */
3690 if (delalloc_len > 0)
3691 *delalloc_end_ret = *delalloc_start_ret + delalloc_len - 1;
3692
3693 /*
3694 * Now also check if there's any extent map in the range that does not
3695 * map to a hole or prealloc extent. We do this because:
3696 *
3697 * 1) When delalloc is flushed, the file range is locked, we clear the
3698 * EXTENT_DELALLOC bit from the io tree and create an extent map for
3699 * an allocated extent. So we might just have been called after
3700 * delalloc is flushed and before the ordered extent completes and
3701 * inserts the new file extent item in the subvolume's btree;
3702 *
3703 * 2) We may have an extent map created by flushing delalloc for a
3704 * subrange that starts before the subrange we found marked with
3705 * EXTENT_DELALLOC in the io tree.
3706 */
3707 read_lock(&em_tree->lock);
3708 em = lookup_extent_mapping(em_tree, start, len);
3709 read_unlock(&em_tree->lock);
3710
3711 /* extent_map_end() returns a non-inclusive end offset. */
3712 em_end = em ? extent_map_end(em) : 0;
3713
3714 /*
3715 * If we have a hole/prealloc extent map, check the next one if this one
3716 * ends before our range's end.
3717 */
3718 if (em && (em->block_start == EXTENT_MAP_HOLE ||
3719 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) && em_end < end) {
3720 struct extent_map *next_em;
3721
3722 read_lock(&em_tree->lock);
3723 next_em = lookup_extent_mapping(em_tree, em_end, len - em_end);
3724 read_unlock(&em_tree->lock);
3725
3726 free_extent_map(em);
3727 em_end = next_em ? extent_map_end(next_em) : 0;
3728 em = next_em;
3729 }
3730
3731 if (em && (em->block_start == EXTENT_MAP_HOLE ||
3732 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3733 free_extent_map(em);
3734 em = NULL;
3735 }
3736
3737 /*
3738 * No extent map or one for a hole or prealloc extent. Use the delalloc
3739 * range we found in the io tree if we have one.
3740 */
3741 if (!em)
3742 return (delalloc_len > 0);
3743
3744 /*
3745 * We don't have any range as EXTENT_DELALLOC in the io tree, so the
3746 * extent map is the only subrange representing delalloc.
3747 */
3748 if (delalloc_len == 0) {
3749 *delalloc_start_ret = em->start;
3750 *delalloc_end_ret = min(end, em_end - 1);
3751 free_extent_map(em);
3752 return true;
3753 }
3754
3755 /*
3756 * The extent map represents a delalloc range that starts before the
3757 * delalloc range we found in the io tree.
3758 */
3759 if (em->start < *delalloc_start_ret) {
3760 *delalloc_start_ret = em->start;
3761 /*
3762 * If the ranges are adjacent, return a combined range.
3763 * Otherwise return the extent map's range.
3764 */
3765 if (em_end < *delalloc_start_ret)
3766 *delalloc_end_ret = min(end, em_end - 1);
3767
3768 free_extent_map(em);
3769 return true;
3770 }
3771
3772 /*
3773 * The extent map starts after the delalloc range we found in the io
3774 * tree. If it's adjacent, return a combined range, otherwise return
3775 * the range found in the io tree.
3776 */
3777 if (*delalloc_end_ret + 1 == em->start)
3778 *delalloc_end_ret = min(end, em_end - 1);
3779
3780 free_extent_map(em);
3781 return true;
3782}
3783
3784/*
3785 * Check if there's delalloc in a given range.
3786 *
3787 * @inode: The inode.
3788 * @start: The start offset of the range. It does not need to be
3789 * sector size aligned.
3790 * @end: The end offset (inclusive value) of the search range.
3791 * It does not need to be sector size aligned.
3792 * @delalloc_start_ret: Output argument, set to the start offset of the
3793 * subrange found with delalloc (may not be sector size
3794 * aligned).
3795 * @delalloc_end_ret: Output argument, set to he end offset (inclusive value)
3796 * of the subrange found with delalloc.
3797 *
3798 * Returns true if a subrange with delalloc is found within the given range, and
3799 * if so it sets @delalloc_start_ret and @delalloc_end_ret with the start and
3800 * end offsets of the subrange.
3801 */
ac3c0d36
FM
3802bool btrfs_find_delalloc_in_range(struct btrfs_inode *inode, u64 start, u64 end,
3803 u64 *delalloc_start_ret, u64 *delalloc_end_ret)
b6e83356
FM
3804{
3805 u64 cur_offset = round_down(start, inode->root->fs_info->sectorsize);
3806 u64 prev_delalloc_end = 0;
3807 bool ret = false;
3808
3809 while (cur_offset < end) {
3810 u64 delalloc_start;
3811 u64 delalloc_end;
3812 bool delalloc;
3813
3814 delalloc = find_delalloc_subrange(inode, cur_offset, end,
3815 &delalloc_start,
3816 &delalloc_end);
3817 if (!delalloc)
3818 break;
3819
3820 if (prev_delalloc_end == 0) {
3821 /* First subrange found. */
3822 *delalloc_start_ret = max(delalloc_start, start);
3823 *delalloc_end_ret = delalloc_end;
3824 ret = true;
3825 } else if (delalloc_start == prev_delalloc_end + 1) {
3826 /* Subrange adjacent to the previous one, merge them. */
3827 *delalloc_end_ret = delalloc_end;
3828 } else {
3829 /* Subrange not adjacent to the previous one, exit. */
3830 break;
3831 }
3832
3833 prev_delalloc_end = delalloc_end;
3834 cur_offset = delalloc_end + 1;
3835 cond_resched();
3836 }
3837
3838 return ret;
3839}
3840
3841/*
3842 * Check if there's a hole or delalloc range in a range representing a hole (or
3843 * prealloc extent) found in the inode's subvolume btree.
3844 *
3845 * @inode: The inode.
3846 * @whence: Seek mode (SEEK_DATA or SEEK_HOLE).
3847 * @start: Start offset of the hole region. It does not need to be sector
3848 * size aligned.
3849 * @end: End offset (inclusive value) of the hole region. It does not
3850 * need to be sector size aligned.
3851 * @start_ret: Return parameter, used to set the start of the subrange in the
3852 * hole that matches the search criteria (seek mode), if such
3853 * subrange is found (return value of the function is true).
3854 * The value returned here may not be sector size aligned.
3855 *
3856 * Returns true if a subrange matching the given seek mode is found, and if one
3857 * is found, it updates @start_ret with the start of the subrange.
3858 */
3859static bool find_desired_extent_in_hole(struct btrfs_inode *inode, int whence,
3860 u64 start, u64 end, u64 *start_ret)
3861{
3862 u64 delalloc_start;
3863 u64 delalloc_end;
3864 bool delalloc;
3865
ac3c0d36
FM
3866 delalloc = btrfs_find_delalloc_in_range(inode, start, end,
3867 &delalloc_start, &delalloc_end);
b6e83356
FM
3868 if (delalloc && whence == SEEK_DATA) {
3869 *start_ret = delalloc_start;
3870 return true;
3871 }
3872
3873 if (delalloc && whence == SEEK_HOLE) {
3874 /*
3875 * We found delalloc but it starts after out start offset. So we
3876 * have a hole between our start offset and the delalloc start.
3877 */
3878 if (start < delalloc_start) {
3879 *start_ret = start;
3880 return true;
3881 }
3882 /*
3883 * Delalloc range starts at our start offset.
3884 * If the delalloc range's length is smaller than our range,
3885 * then it means we have a hole that starts where the delalloc
3886 * subrange ends.
3887 */
3888 if (delalloc_end < end) {
3889 *start_ret = delalloc_end + 1;
3890 return true;
3891 }
3892
3893 /* There's delalloc for the whole range. */
3894 return false;
3895 }
3896
3897 if (!delalloc && whence == SEEK_HOLE) {
3898 *start_ret = start;
3899 return true;
3900 }
3901
3902 /*
3903 * No delalloc in the range and we are seeking for data. The caller has
3904 * to iterate to the next extent item in the subvolume btree.
3905 */
3906 return false;
3907}
3908
cca5de97 3909static loff_t find_desired_extent(struct btrfs_inode *inode, loff_t offset,
bc80230e 3910 int whence)
b2675157 3911{
cca5de97 3912 struct btrfs_fs_info *fs_info = inode->root->fs_info;
b2675157 3913 struct extent_state *cached_state = NULL;
b6e83356
FM
3914 const loff_t i_size = i_size_read(&inode->vfs_inode);
3915 const u64 ino = btrfs_ino(inode);
3916 struct btrfs_root *root = inode->root;
3917 struct btrfs_path *path;
3918 struct btrfs_key key;
3919 u64 last_extent_end;
4d1a40c6
LB
3920 u64 lockstart;
3921 u64 lockend;
3922 u64 start;
b6e83356
FM
3923 int ret;
3924 bool found = false;
b2675157 3925
bc80230e 3926 if (i_size == 0 || offset >= i_size)
4d1a40c6
LB
3927 return -ENXIO;
3928
b6e83356
FM
3929 /*
3930 * Quick path. If the inode has no prealloc extents and its number of
3931 * bytes used matches its i_size, then it can not have holes.
3932 */
3933 if (whence == SEEK_HOLE &&
3934 !(inode->flags & BTRFS_INODE_PREALLOC) &&
3935 inode_get_bytes(&inode->vfs_inode) == i_size)
3936 return i_size;
3937
4d1a40c6 3938 /*
bc80230e 3939 * offset can be negative, in this case we start finding DATA/HOLE from
4d1a40c6
LB
3940 * the very start of the file.
3941 */
bc80230e 3942 start = max_t(loff_t, 0, offset);
4d1a40c6 3943
0b246afa 3944 lockstart = round_down(start, fs_info->sectorsize);
d79b7c26 3945 lockend = round_up(i_size, fs_info->sectorsize);
b2675157 3946 if (lockend <= lockstart)
0b246afa 3947 lockend = lockstart + fs_info->sectorsize;
1214b53f 3948 lockend--;
b6e83356
FM
3949
3950 path = btrfs_alloc_path();
3951 if (!path)
3952 return -ENOMEM;
3953 path->reada = READA_FORWARD;
3954
3955 key.objectid = ino;
3956 key.type = BTRFS_EXTENT_DATA_KEY;
3957 key.offset = start;
3958
3959 last_extent_end = lockstart;
b2675157 3960
570eb97b 3961 lock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
b2675157 3962
b6e83356
FM
3963 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3964 if (ret < 0) {
3965 goto out;
3966 } else if (ret > 0 && path->slots[0] > 0) {
3967 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3968 if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3969 path->slots[0]--;
3970 }
3971
d79b7c26 3972 while (start < i_size) {
b6e83356
FM
3973 struct extent_buffer *leaf = path->nodes[0];
3974 struct btrfs_file_extent_item *extent;
3975 u64 extent_end;
3976
3977 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3978 ret = btrfs_next_leaf(root, path);
3979 if (ret < 0)
3980 goto out;
3981 else if (ret > 0)
3982 break;
3983
3984 leaf = path->nodes[0];
b2675157
JB
3985 }
3986
b6e83356
FM
3987 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3988 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
7f4ca37c 3989 break;
b2675157 3990
b6e83356
FM
3991 extent_end = btrfs_file_extent_end(path);
3992
3993 /*
3994 * In the first iteration we may have a slot that points to an
3995 * extent that ends before our start offset, so skip it.
3996 */
3997 if (extent_end <= start) {
3998 path->slots[0]++;
3999 continue;
4000 }
4001
4002 /* We have an implicit hole, NO_HOLES feature is likely set. */
4003 if (last_extent_end < key.offset) {
4004 u64 search_start = last_extent_end;
4005 u64 found_start;
4006
4007 /*
4008 * First iteration, @start matches @offset and it's
4009 * within the hole.
4010 */
4011 if (start == offset)
4012 search_start = offset;
4013
4014 found = find_desired_extent_in_hole(inode, whence,
4015 search_start,
4016 key.offset - 1,
4017 &found_start);
4018 if (found) {
4019 start = found_start;
4020 break;
4021 }
4022 /*
4023 * Didn't find data or a hole (due to delalloc) in the
4024 * implicit hole range, so need to analyze the extent.
4025 */
4026 }
4027
4028 extent = btrfs_item_ptr(leaf, path->slots[0],
4029 struct btrfs_file_extent_item);
4030
4031 if (btrfs_file_extent_disk_bytenr(leaf, extent) == 0 ||
4032 btrfs_file_extent_type(leaf, extent) ==
4033 BTRFS_FILE_EXTENT_PREALLOC) {
4034 /*
4035 * Explicit hole or prealloc extent, search for delalloc.
4036 * A prealloc extent is treated like a hole.
4037 */
4038 u64 search_start = key.offset;
4039 u64 found_start;
4040
4041 /*
4042 * First iteration, @start matches @offset and it's
4043 * within the hole.
4044 */
4045 if (start == offset)
4046 search_start = offset;
4047
4048 found = find_desired_extent_in_hole(inode, whence,
4049 search_start,
4050 extent_end - 1,
4051 &found_start);
4052 if (found) {
4053 start = found_start;
4054 break;
4055 }
4056 /*
4057 * Didn't find data or a hole (due to delalloc) in the
4058 * implicit hole range, so need to analyze the next
4059 * extent item.
4060 */
4061 } else {
4062 /*
4063 * Found a regular or inline extent.
4064 * If we are seeking for data, adjust the start offset
4065 * and stop, we're done.
4066 */
4067 if (whence == SEEK_DATA) {
4068 start = max_t(u64, key.offset, offset);
4069 found = true;
4070 break;
4071 }
4072 /*
4073 * Else, we are seeking for a hole, check the next file
4074 * extent item.
4075 */
4076 }
4077
4078 start = extent_end;
4079 last_extent_end = extent_end;
4080 path->slots[0]++;
aed0ca18
FM
4081 if (fatal_signal_pending(current)) {
4082 ret = -EINTR;
b6e83356 4083 goto out;
aed0ca18 4084 }
b2675157
JB
4085 cond_resched();
4086 }
b6e83356
FM
4087
4088 /* We have an implicit hole from the last extent found up to i_size. */
4089 if (!found && start < i_size) {
4090 found = find_desired_extent_in_hole(inode, whence, start,
4091 i_size - 1, &start);
4092 if (!found)
4093 start = i_size;
4094 }
4095
4096out:
570eb97b 4097 unlock_extent(&inode->io_tree, lockstart, lockend, &cached_state);
b6e83356
FM
4098 btrfs_free_path(path);
4099
4100 if (ret < 0)
4101 return ret;
4102
4103 if (whence == SEEK_DATA && start >= i_size)
4104 return -ENXIO;
bc80230e 4105
b6e83356 4106 return min_t(loff_t, start, i_size);
b2675157
JB
4107}
4108
965c8e59 4109static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
b2675157
JB
4110{
4111 struct inode *inode = file->f_mapping->host;
b2675157 4112
965c8e59 4113 switch (whence) {
2034f3b4
NB
4114 default:
4115 return generic_file_llseek(file, offset, whence);
b2675157
JB
4116 case SEEK_DATA:
4117 case SEEK_HOLE:
a14b78ad 4118 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
cca5de97 4119 offset = find_desired_extent(BTRFS_I(inode), offset, whence);
a14b78ad 4120 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
bc80230e 4121 break;
b2675157
JB
4122 }
4123
bc80230e
NB
4124 if (offset < 0)
4125 return offset;
4126
2034f3b4 4127 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
b2675157
JB
4128}
4129
edf064e7
GR
4130static int btrfs_file_open(struct inode *inode, struct file *filp)
4131{
14605409
BB
4132 int ret;
4133
926078b2 4134 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC | FMODE_BUF_WASYNC;
14605409
BB
4135
4136 ret = fsverity_file_open(inode, filp);
4137 if (ret)
4138 return ret;
edf064e7
GR
4139 return generic_file_open(inode, filp);
4140}
4141
4e4cabec
GR
4142static int check_direct_read(struct btrfs_fs_info *fs_info,
4143 const struct iov_iter *iter, loff_t offset)
4144{
4145 int ret;
4146 int i, seg;
4147
4148 ret = check_direct_IO(fs_info, iter, offset);
4149 if (ret < 0)
4150 return ret;
4151
4152 if (!iter_is_iovec(iter))
4153 return 0;
4154
4155 for (seg = 0; seg < iter->nr_segs; seg++)
4156 for (i = seg + 1; i < iter->nr_segs; i++)
4157 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
4158 return -EINVAL;
4159 return 0;
4160}
4161
4162static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
4163{
4164 struct inode *inode = file_inode(iocb->ki_filp);
51bd9563
FM
4165 size_t prev_left = 0;
4166 ssize_t read = 0;
4e4cabec
GR
4167 ssize_t ret;
4168
14605409
BB
4169 if (fsverity_active(inode))
4170 return 0;
4171
4e4cabec
GR
4172 if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
4173 return 0;
4174
a14b78ad 4175 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
51bd9563
FM
4176again:
4177 /*
4178 * This is similar to what we do for direct IO writes, see the comment
4179 * at btrfs_direct_write(), but we also disable page faults in addition
4180 * to disabling them only at the iov_iter level. This is because when
4181 * reading from a hole or prealloc extent, iomap calls iov_iter_zero(),
4182 * which can still trigger page fault ins despite having set ->nofault
4183 * to true of our 'to' iov_iter.
4184 *
4185 * The difference to direct IO writes is that we deadlock when trying
4186 * to lock the extent range in the inode's tree during he page reads
4187 * triggered by the fault in (while for writes it is due to waiting for
4188 * our own ordered extent). This is because for direct IO reads,
4189 * btrfs_dio_iomap_begin() returns with the extent range locked, which
4190 * is only unlocked in the endio callback (end_bio_extent_readpage()).
4191 */
4192 pagefault_disable();
4193 to->nofault = true;
36e8c622 4194 ret = btrfs_dio_rw(iocb, to, read);
51bd9563
FM
4195 to->nofault = false;
4196 pagefault_enable();
4197
4198 /* No increment (+=) because iomap returns a cumulative value. */
4199 if (ret > 0)
4200 read = ret;
4201
4202 if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) {
4203 const size_t left = iov_iter_count(to);
4204
4205 if (left == prev_left) {
4206 /*
4207 * We didn't make any progress since the last attempt,
4208 * fallback to a buffered read for the remainder of the
4209 * range. This is just to avoid any possibility of looping
4210 * for too long.
4211 */
4212 ret = read;
4213 } else {
4214 /*
4215 * We made some progress since the last retry or this is
4216 * the first time we are retrying. Fault in as many pages
4217 * as possible and retry.
4218 */
4219 fault_in_iov_iter_writeable(to, left);
4220 prev_left = left;
4221 goto again;
4222 }
4223 }
a14b78ad 4224 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
51bd9563 4225 return ret < 0 ? ret : read;
4e4cabec
GR
4226}
4227
f85781fb
GR
4228static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
4229{
4230 ssize_t ret = 0;
4231
4232 if (iocb->ki_flags & IOCB_DIRECT) {
4e4cabec 4233 ret = btrfs_direct_read(iocb, to);
0425e7ba
JT
4234 if (ret < 0 || !iov_iter_count(to) ||
4235 iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
f85781fb
GR
4236 return ret;
4237 }
4238
87fa0f3e 4239 return filemap_read(iocb, to, ret);
f85781fb
GR
4240}
4241
828c0950 4242const struct file_operations btrfs_file_operations = {
b2675157 4243 .llseek = btrfs_file_llseek,
f85781fb 4244 .read_iter = btrfs_file_read_iter,
e9906a98 4245 .splice_read = generic_file_splice_read,
b30ac0fc 4246 .write_iter = btrfs_file_write_iter,
d7776591 4247 .splice_write = iter_file_splice_write,
9ebefb18 4248 .mmap = btrfs_file_mmap,
edf064e7 4249 .open = btrfs_file_open,
e1b81e67 4250 .release = btrfs_release_file,
b0c58223 4251 .get_unmapped_area = thp_get_unmapped_area,
39279cc3 4252 .fsync = btrfs_sync_file,
2fe17c10 4253 .fallocate = btrfs_fallocate,
34287aa3 4254 .unlocked_ioctl = btrfs_ioctl,
39279cc3 4255#ifdef CONFIG_COMPAT
4c63c245 4256 .compat_ioctl = btrfs_compat_ioctl,
39279cc3 4257#endif
2e5dfc99 4258 .remap_file_range = btrfs_remap_file_range,
39279cc3 4259};
9247f317 4260
e67c718b 4261void __cold btrfs_auto_defrag_exit(void)
9247f317 4262{
5598e900 4263 kmem_cache_destroy(btrfs_inode_defrag_cachep);
9247f317
MX
4264}
4265
f5c29bd9 4266int __init btrfs_auto_defrag_init(void)
9247f317
MX
4267{
4268 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
4269 sizeof(struct inode_defrag), 0,
fba4b697 4270 SLAB_MEM_SPREAD,
9247f317
MX
4271 NULL);
4272 if (!btrfs_inode_defrag_cachep)
4273 return -ENOMEM;
4274
4275 return 0;
4276}
728404da
FM
4277
4278int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
4279{
4280 int ret;
4281
4282 /*
4283 * So with compression we will find and lock a dirty page and clear the
4284 * first one as dirty, setup an async extent, and immediately return
4285 * with the entire range locked but with nobody actually marked with
4286 * writeback. So we can't just filemap_write_and_wait_range() and
4287 * expect it to work since it will just kick off a thread to do the
4288 * actual work. So we need to call filemap_fdatawrite_range _again_
4289 * since it will wait on the page lock, which won't be unlocked until
4290 * after the pages have been marked as writeback and so we're good to go
4291 * from there. We have to do this otherwise we'll miss the ordered
4292 * extents and that results in badness. Please Josef, do not think you
4293 * know better and pull this out at some point in the future, it is
4294 * right and you are wrong.
4295 */
4296 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4297 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
4298 &BTRFS_I(inode)->runtime_flags))
4299 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4300
4301 return ret;
4302}