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