btrfs: make btrfs_truncate_block take btrfs_inode
[linux-block.git] / fs / btrfs / file.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
6cbd5570
CM
2/*
3 * Copyright (C) 2007 Oracle. All rights reserved.
6cbd5570
CM
4 */
5
39279cc3
CM
6#include <linux/fs.h>
7#include <linux/pagemap.h>
39279cc3
CM
8#include <linux/time.h>
9#include <linux/init.h>
10#include <linux/string.h>
39279cc3 11#include <linux/backing-dev.h>
2fe17c10 12#include <linux/falloc.h>
39279cc3 13#include <linux/writeback.h>
39279cc3 14#include <linux/compat.h>
5a0e3ad6 15#include <linux/slab.h>
55e301fd 16#include <linux/btrfs.h>
e2e40f2c 17#include <linux/uio.h>
ae5e165d 18#include <linux/iversion.h>
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;
d899e052 1098 int ret;
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
YZ
1318 btrfs_free_path(path);
1319 return 0;
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
1631 ret = btrfs_cont_expand(inode, oldsize, end_pos);
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
d352ac68
CM
2085/*
2086 * fsync call for both files and directories. This logs the inode into
2087 * the tree log instead of forcing full commits whenever possible.
2088 *
2089 * It needs to call filemap_fdatawait so that all ordered extent updates are
2090 * in the metadata btree are up to date for copying to the log.
2091 *
2092 * It drops the inode mutex before doing the tree log commit. This is an
2093 * important optimization for directories because holding the mutex prevents
2094 * new operations on the dir while we write to disk.
2095 */
02c24a82 2096int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
39279cc3 2097{
de17e793 2098 struct dentry *dentry = file_dentry(file);
2b0143b5 2099 struct inode *inode = d_inode(dentry);
0b246afa 2100 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 2101 struct btrfs_root *root = BTRFS_I(inode)->root;
39279cc3 2102 struct btrfs_trans_handle *trans;
8b050d35 2103 struct btrfs_log_ctx ctx;
333427a5 2104 int ret = 0, err;
48778179
FM
2105 u64 len;
2106 bool full_sync;
39279cc3 2107
1abe9b8a 2108 trace_btrfs_sync_file(file, datasync);
257c62e1 2109
ebb70442
LB
2110 btrfs_init_log_ctx(&ctx, inode);
2111
95418ed1 2112 /*
48778179
FM
2113 * Always set the range to a full range, otherwise we can get into
2114 * several problems, from missing file extent items to represent holes
2115 * when not using the NO_HOLES feature, to log tree corruption due to
2116 * races between hole detection during logging and completion of ordered
2117 * extents outside the range, to missing checksums due to ordered extents
2118 * for which we flushed only a subset of their pages.
95418ed1 2119 */
48778179
FM
2120 start = 0;
2121 end = LLONG_MAX;
2122 len = (u64)LLONG_MAX + 1;
95418ed1 2123
90abccf2
MX
2124 /*
2125 * We write the dirty pages in the range and wait until they complete
2126 * out of the ->i_mutex. If so, we can flush the dirty pages by
2ab28f32
JB
2127 * multi-task, and make the performance up. See
2128 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
90abccf2 2129 */
669249ee 2130 ret = start_ordered_ops(inode, start, end);
90abccf2 2131 if (ret)
333427a5 2132 goto out;
90abccf2 2133
5955102c 2134 inode_lock(inode);
c495144b 2135
2ecb7923 2136 atomic_inc(&root->log_batch);
b5e6c3e1 2137
7af59743 2138 /*
48778179
FM
2139 * Always check for the full sync flag while holding the inode's lock,
2140 * to avoid races with other tasks. The flag must be either set all the
2141 * time during logging or always off all the time while logging.
7af59743 2142 */
48778179
FM
2143 full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2144 &BTRFS_I(inode)->runtime_flags);
7af59743 2145
aab15e8e
FM
2146 /*
2147 * Before we acquired the inode's lock, someone may have dirtied more
2148 * pages in the target range. We need to make sure that writeback for
2149 * any such pages does not start while we are logging the inode, because
2150 * if it does, any of the following might happen when we are not doing a
2151 * full inode sync:
2152 *
2153 * 1) We log an extent after its writeback finishes but before its
2154 * checksums are added to the csum tree, leading to -EIO errors
2155 * when attempting to read the extent after a log replay.
2156 *
2157 * 2) We can end up logging an extent before its writeback finishes.
2158 * Therefore after the log replay we will have a file extent item
2159 * pointing to an unwritten extent (and no data checksums as well).
2160 *
2161 * So trigger writeback for any eventual new dirty pages and then we
2162 * wait for all ordered extents to complete below.
2163 */
2164 ret = start_ordered_ops(inode, start, end);
2165 if (ret) {
2166 inode_unlock(inode);
2167 goto out;
2168 }
2169
669249ee 2170 /*
b5e6c3e1 2171 * We have to do this here to avoid the priority inversion of waiting on
52042d8e 2172 * IO of a lower priority task while holding a transaction open.
ba0b084a 2173 *
48778179
FM
2174 * For a full fsync we wait for the ordered extents to complete while
2175 * for a fast fsync we wait just for writeback to complete, and then
2176 * attach the ordered extents to the transaction so that a transaction
2177 * commit waits for their completion, to avoid data loss if we fsync,
2178 * the current transaction commits before the ordered extents complete
2179 * and a power failure happens right after that.
669249ee 2180 */
48778179
FM
2181 if (full_sync) {
2182 ret = btrfs_wait_ordered_range(inode, start, len);
2183 } else {
2184 /*
2185 * Get our ordered extents as soon as possible to avoid doing
2186 * checksum lookups in the csum tree, and use instead the
2187 * checksums attached to the ordered extents.
2188 */
2189 btrfs_get_ordered_extents_for_logging(BTRFS_I(inode),
2190 &ctx.ordered_extents);
2191 ret = filemap_fdatawait_range(inode->i_mapping, start, end);
0ef8b726 2192 }
48778179
FM
2193
2194 if (ret)
2195 goto out_release_extents;
2196
2ecb7923 2197 atomic_inc(&root->log_batch);
257c62e1 2198
48778179
FM
2199 /*
2200 * If we are doing a fast fsync we can not bail out if the inode's
2201 * last_trans is <= then the last committed transaction, because we only
2202 * update the last_trans of the inode during ordered extent completion,
2203 * and for a fast fsync we don't wait for that, we only wait for the
2204 * writeback to complete.
2205 */
a4abeea4 2206 smp_mb();
0f8939b8 2207 if (btrfs_inode_in_log(BTRFS_I(inode), fs_info->generation) ||
48778179
FM
2208 (BTRFS_I(inode)->last_trans <= fs_info->last_trans_committed &&
2209 (full_sync || list_empty(&ctx.ordered_extents)))) {
5dc562c5 2210 /*
01327610 2211 * We've had everything committed since the last time we were
5dc562c5
JB
2212 * modified so clear this flag in case it was set for whatever
2213 * reason, it's no longer relevant.
2214 */
2215 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2216 &BTRFS_I(inode)->runtime_flags);
0596a904
FM
2217 /*
2218 * An ordered extent might have started before and completed
2219 * already with io errors, in which case the inode was not
2220 * updated and we end up here. So check the inode's mapping
333427a5
JL
2221 * for any errors that might have happened since we last
2222 * checked called fsync.
0596a904 2223 */
333427a5 2224 ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
48778179 2225 goto out_release_extents;
15ee9bc7 2226 }
15ee9bc7 2227
5039eddc
JB
2228 /*
2229 * We use start here because we will need to wait on the IO to complete
2230 * in btrfs_sync_log, which could require joining a transaction (for
2231 * example checking cross references in the nocow path). If we use join
2232 * here we could get into a situation where we're waiting on IO to
2233 * happen that is blocked on a transaction trying to commit. With start
2234 * we inc the extwriter counter, so we wait for all extwriters to exit
52042d8e 2235 * before we start blocking joiners. This comment is to keep somebody
5039eddc
JB
2236 * from thinking they are super smart and changing this to
2237 * btrfs_join_transaction *cough*Josef*cough*.
2238 */
a22285a6
YZ
2239 trans = btrfs_start_transaction(root, 0);
2240 if (IS_ERR(trans)) {
2241 ret = PTR_ERR(trans);
48778179 2242 goto out_release_extents;
39279cc3 2243 }
e02119d5 2244
48778179
FM
2245 ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
2246 btrfs_release_log_ctx_extents(&ctx);
02c24a82 2247 if (ret < 0) {
a0634be5
FDBM
2248 /* Fallthrough and commit/free transaction. */
2249 ret = 1;
02c24a82 2250 }
49eb7e46
CM
2251
2252 /* we've logged all the items and now have a consistent
2253 * version of the file in the log. It is possible that
2254 * someone will come in and modify the file, but that's
2255 * fine because the log is consistent on disk, and we
2256 * have references to all of the file's extents
2257 *
2258 * It is possible that someone will come in and log the
2259 * file again, but that will end up using the synchronization
2260 * inside btrfs_sync_log to keep things safe.
2261 */
5955102c 2262 inode_unlock(inode);
49eb7e46 2263
257c62e1 2264 if (ret != BTRFS_NO_LOG_SYNC) {
0ef8b726 2265 if (!ret) {
8b050d35 2266 ret = btrfs_sync_log(trans, root, &ctx);
0ef8b726 2267 if (!ret) {
3a45bb20 2268 ret = btrfs_end_transaction(trans);
0ef8b726 2269 goto out;
2ab28f32 2270 }
257c62e1 2271 }
48778179
FM
2272 if (!full_sync) {
2273 ret = btrfs_wait_ordered_range(inode, start, len);
2274 if (ret) {
2275 btrfs_end_transaction(trans);
2276 goto out;
2277 }
2278 }
3a45bb20 2279 ret = btrfs_commit_transaction(trans);
257c62e1 2280 } else {
3a45bb20 2281 ret = btrfs_end_transaction(trans);
e02119d5 2282 }
39279cc3 2283out:
ebb70442 2284 ASSERT(list_empty(&ctx.list));
333427a5
JL
2285 err = file_check_and_advance_wb_err(file);
2286 if (!ret)
2287 ret = err;
014e4ac4 2288 return ret > 0 ? -EIO : ret;
48778179
FM
2289
2290out_release_extents:
2291 btrfs_release_log_ctx_extents(&ctx);
48778179
FM
2292 inode_unlock(inode);
2293 goto out;
39279cc3
CM
2294}
2295
f0f37e2f 2296static const struct vm_operations_struct btrfs_file_vm_ops = {
92fee66d 2297 .fault = filemap_fault,
f1820361 2298 .map_pages = filemap_map_pages,
9ebefb18
CM
2299 .page_mkwrite = btrfs_page_mkwrite,
2300};
2301
2302static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
2303{
058a457e
MX
2304 struct address_space *mapping = filp->f_mapping;
2305
2306 if (!mapping->a_ops->readpage)
2307 return -ENOEXEC;
2308
9ebefb18 2309 file_accessed(filp);
058a457e 2310 vma->vm_ops = &btrfs_file_vm_ops;
058a457e 2311
9ebefb18
CM
2312 return 0;
2313}
2314
35339c24 2315static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2aaa6655
JB
2316 int slot, u64 start, u64 end)
2317{
2318 struct btrfs_file_extent_item *fi;
2319 struct btrfs_key key;
2320
2321 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2322 return 0;
2323
2324 btrfs_item_key_to_cpu(leaf, &key, slot);
35339c24 2325 if (key.objectid != btrfs_ino(inode) ||
2aaa6655
JB
2326 key.type != BTRFS_EXTENT_DATA_KEY)
2327 return 0;
2328
2329 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2330
2331 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2332 return 0;
2333
2334 if (btrfs_file_extent_disk_bytenr(leaf, fi))
2335 return 0;
2336
2337 if (key.offset == end)
2338 return 1;
2339 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2340 return 1;
2341 return 0;
2342}
2343
a012a74e
NB
2344static int fill_holes(struct btrfs_trans_handle *trans,
2345 struct btrfs_inode *inode,
2346 struct btrfs_path *path, u64 offset, u64 end)
2aaa6655 2347{
3ffbd68c 2348 struct btrfs_fs_info *fs_info = trans->fs_info;
a012a74e 2349 struct btrfs_root *root = inode->root;
2aaa6655
JB
2350 struct extent_buffer *leaf;
2351 struct btrfs_file_extent_item *fi;
2352 struct extent_map *hole_em;
a012a74e 2353 struct extent_map_tree *em_tree = &inode->extent_tree;
2aaa6655
JB
2354 struct btrfs_key key;
2355 int ret;
2356
0b246afa 2357 if (btrfs_fs_incompat(fs_info, NO_HOLES))
16e7549f
JB
2358 goto out;
2359
a012a74e 2360 key.objectid = btrfs_ino(inode);
2aaa6655
JB
2361 key.type = BTRFS_EXTENT_DATA_KEY;
2362 key.offset = offset;
2363
2aaa6655 2364 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
f94480bd
JB
2365 if (ret <= 0) {
2366 /*
2367 * We should have dropped this offset, so if we find it then
2368 * something has gone horribly wrong.
2369 */
2370 if (ret == 0)
2371 ret = -EINVAL;
2aaa6655 2372 return ret;
f94480bd 2373 }
2aaa6655
JB
2374
2375 leaf = path->nodes[0];
a012a74e 2376 if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2aaa6655
JB
2377 u64 num_bytes;
2378
2379 path->slots[0]--;
2380 fi = btrfs_item_ptr(leaf, path->slots[0],
2381 struct btrfs_file_extent_item);
2382 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2383 end - offset;
2384 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2385 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2386 btrfs_set_file_extent_offset(leaf, fi, 0);
2387 btrfs_mark_buffer_dirty(leaf);
2388 goto out;
2389 }
2390
1707e26d 2391 if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2aaa6655
JB
2392 u64 num_bytes;
2393
2aaa6655 2394 key.offset = offset;
0b246afa 2395 btrfs_set_item_key_safe(fs_info, path, &key);
2aaa6655
JB
2396 fi = btrfs_item_ptr(leaf, path->slots[0],
2397 struct btrfs_file_extent_item);
2398 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2399 offset;
2400 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2401 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2402 btrfs_set_file_extent_offset(leaf, fi, 0);
2403 btrfs_mark_buffer_dirty(leaf);
2404 goto out;
2405 }
2406 btrfs_release_path(path);
2407
a012a74e 2408 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
f85b7379 2409 offset, 0, 0, end - offset, 0, end - offset, 0, 0, 0);
2aaa6655
JB
2410 if (ret)
2411 return ret;
2412
2413out:
2414 btrfs_release_path(path);
2415
2416 hole_em = alloc_extent_map();
2417 if (!hole_em) {
2418 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
a012a74e 2419 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
2aaa6655
JB
2420 } else {
2421 hole_em->start = offset;
2422 hole_em->len = end - offset;
cc95bef6 2423 hole_em->ram_bytes = hole_em->len;
2aaa6655
JB
2424 hole_em->orig_start = offset;
2425
2426 hole_em->block_start = EXTENT_MAP_HOLE;
2427 hole_em->block_len = 0;
b4939680 2428 hole_em->orig_block_len = 0;
2aaa6655
JB
2429 hole_em->compress_type = BTRFS_COMPRESS_NONE;
2430 hole_em->generation = trans->transid;
2431
2432 do {
2433 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2434 write_lock(&em_tree->lock);
09a2a8f9 2435 ret = add_extent_mapping(em_tree, hole_em, 1);
2aaa6655
JB
2436 write_unlock(&em_tree->lock);
2437 } while (ret == -EEXIST);
2438 free_extent_map(hole_em);
2439 if (ret)
2440 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
a012a74e 2441 &inode->runtime_flags);
2aaa6655
JB
2442 }
2443
2444 return 0;
2445}
2446
d7781546
QW
2447/*
2448 * Find a hole extent on given inode and change start/len to the end of hole
2449 * extent.(hole/vacuum extent whose em->start <= start &&
2450 * em->start + em->len > start)
2451 * When a hole extent is found, return 1 and modify start/len.
2452 */
dea46d84 2453static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
d7781546 2454{
dea46d84 2455 struct btrfs_fs_info *fs_info = inode->root->fs_info;
d7781546
QW
2456 struct extent_map *em;
2457 int ret = 0;
2458
dea46d84 2459 em = btrfs_get_extent(inode, NULL, 0,
609805d8 2460 round_down(*start, fs_info->sectorsize),
39b07b5d 2461 round_up(*len, fs_info->sectorsize));
9986277e
DC
2462 if (IS_ERR(em))
2463 return PTR_ERR(em);
d7781546
QW
2464
2465 /* Hole or vacuum extent(only exists in no-hole mode) */
2466 if (em->block_start == EXTENT_MAP_HOLE) {
2467 ret = 1;
2468 *len = em->start + em->len > *start + *len ?
2469 0 : *start + *len - em->start - em->len;
2470 *start = em->start + em->len;
2471 }
2472 free_extent_map(em);
2473 return ret;
2474}
2475
f27451f2
FM
2476static int btrfs_punch_hole_lock_range(struct inode *inode,
2477 const u64 lockstart,
2478 const u64 lockend,
2479 struct extent_state **cached_state)
2480{
2481 while (1) {
2482 struct btrfs_ordered_extent *ordered;
2483 int ret;
2484
2485 truncate_pagecache_range(inode, lockstart, lockend);
2486
2487 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2488 cached_state);
6d072c8e
NB
2489 ordered = btrfs_lookup_first_ordered_extent(BTRFS_I(inode),
2490 lockend);
f27451f2
FM
2491
2492 /*
2493 * We need to make sure we have no ordered extents in this range
2494 * and nobody raced in and read a page in this range, if we did
2495 * we need to try again.
2496 */
2497 if ((!ordered ||
bffe633e 2498 (ordered->file_offset + ordered->num_bytes <= lockstart ||
f27451f2 2499 ordered->file_offset > lockend)) &&
051c98eb
DS
2500 !filemap_range_has_page(inode->i_mapping,
2501 lockstart, lockend)) {
f27451f2
FM
2502 if (ordered)
2503 btrfs_put_ordered_extent(ordered);
2504 break;
2505 }
2506 if (ordered)
2507 btrfs_put_ordered_extent(ordered);
2508 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2509 lockend, cached_state);
2510 ret = btrfs_wait_ordered_range(inode, lockstart,
2511 lockend - lockstart + 1);
2512 if (ret)
2513 return ret;
2514 }
2515 return 0;
2516}
2517
0cbb5bdf 2518static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
03fcb1ab 2519 struct btrfs_inode *inode,
690a5dbf 2520 struct btrfs_path *path,
bf385648 2521 struct btrfs_replace_extent_info *extent_info,
2766ff61
FM
2522 const u64 replace_len,
2523 const u64 bytes_to_drop)
690a5dbf 2524{
03fcb1ab
NB
2525 struct btrfs_fs_info *fs_info = trans->fs_info;
2526 struct btrfs_root *root = inode->root;
690a5dbf
FM
2527 struct btrfs_file_extent_item *extent;
2528 struct extent_buffer *leaf;
2529 struct btrfs_key key;
2530 int slot;
2531 struct btrfs_ref ref = { 0 };
690a5dbf
FM
2532 int ret;
2533
bf385648 2534 if (replace_len == 0)
690a5dbf
FM
2535 return 0;
2536
bf385648 2537 if (extent_info->disk_offset == 0 &&
2766ff61 2538 btrfs_fs_incompat(fs_info, NO_HOLES)) {
03fcb1ab 2539 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
690a5dbf 2540 return 0;
2766ff61 2541 }
690a5dbf 2542
03fcb1ab 2543 key.objectid = btrfs_ino(inode);
690a5dbf 2544 key.type = BTRFS_EXTENT_DATA_KEY;
bf385648 2545 key.offset = extent_info->file_offset;
690a5dbf 2546 ret = btrfs_insert_empty_item(trans, root, path, &key,
fb870f6c 2547 sizeof(struct btrfs_file_extent_item));
690a5dbf
FM
2548 if (ret)
2549 return ret;
2550 leaf = path->nodes[0];
2551 slot = path->slots[0];
bf385648 2552 write_extent_buffer(leaf, extent_info->extent_buf,
690a5dbf 2553 btrfs_item_ptr_offset(leaf, slot),
fb870f6c 2554 sizeof(struct btrfs_file_extent_item));
690a5dbf 2555 extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
fb870f6c 2556 ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
bf385648
FM
2557 btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
2558 btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
2559 if (extent_info->is_new_extent)
8fccebfa 2560 btrfs_set_file_extent_generation(leaf, extent, trans->transid);
690a5dbf
FM
2561 btrfs_mark_buffer_dirty(leaf);
2562 btrfs_release_path(path);
2563
03fcb1ab
NB
2564 ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
2565 replace_len);
9ddc959e
JB
2566 if (ret)
2567 return ret;
2568
690a5dbf 2569 /* If it's a hole, nothing more needs to be done. */
2766ff61 2570 if (extent_info->disk_offset == 0) {
03fcb1ab 2571 btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
690a5dbf 2572 return 0;
2766ff61 2573 }
690a5dbf 2574
03fcb1ab 2575 btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
8fccebfa 2576
bf385648
FM
2577 if (extent_info->is_new_extent && extent_info->insertions == 0) {
2578 key.objectid = extent_info->disk_offset;
8fccebfa 2579 key.type = BTRFS_EXTENT_ITEM_KEY;
bf385648 2580 key.offset = extent_info->disk_len;
8fccebfa 2581 ret = btrfs_alloc_reserved_file_extent(trans, root,
03fcb1ab 2582 btrfs_ino(inode),
bf385648
FM
2583 extent_info->file_offset,
2584 extent_info->qgroup_reserved,
8fccebfa
FM
2585 &key);
2586 } else {
2587 u64 ref_offset;
2588
2589 btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
bf385648
FM
2590 extent_info->disk_offset,
2591 extent_info->disk_len, 0);
2592 ref_offset = extent_info->file_offset - extent_info->data_offset;
8fccebfa 2593 btrfs_init_data_ref(&ref, root->root_key.objectid,
03fcb1ab 2594 btrfs_ino(inode), ref_offset);
8fccebfa
FM
2595 ret = btrfs_inc_extent_ref(trans, &ref);
2596 }
2597
bf385648 2598 extent_info->insertions++;
690a5dbf
FM
2599
2600 return ret;
2601}
2602
9cba40a6
FM
2603/*
2604 * The respective range must have been previously locked, as well as the inode.
2605 * The end offset is inclusive (last byte of the range).
bf385648
FM
2606 * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2607 * the file range with an extent.
2608 * When not punching a hole, we don't want to end up in a state where we dropped
2609 * extents without inserting a new one, so we must abort the transaction to avoid
2610 * a corruption.
9cba40a6 2611 */
306bfec0 2612int btrfs_replace_file_extents(struct inode *inode, struct btrfs_path *path,
690a5dbf 2613 const u64 start, const u64 end,
bf385648 2614 struct btrfs_replace_extent_info *extent_info,
690a5dbf 2615 struct btrfs_trans_handle **trans_out)
9cba40a6 2616{
5893dfb9 2617 struct btrfs_drop_extents_args drop_args = { 0 };
9cba40a6 2618 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2bd36e7b 2619 u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
9cba40a6
FM
2620 u64 ino_size = round_up(inode->i_size, fs_info->sectorsize);
2621 struct btrfs_root *root = BTRFS_I(inode)->root;
2622 struct btrfs_trans_handle *trans = NULL;
2623 struct btrfs_block_rsv *rsv;
2624 unsigned int rsv_count;
2625 u64 cur_offset;
9cba40a6
FM
2626 u64 len = end - start;
2627 int ret = 0;
2628
2629 if (end <= start)
2630 return -EINVAL;
2631
2632 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2633 if (!rsv) {
2634 ret = -ENOMEM;
2635 goto out;
2636 }
2bd36e7b 2637 rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
9cba40a6
FM
2638 rsv->failfast = 1;
2639
2640 /*
2641 * 1 - update the inode
2642 * 1 - removing the extents in the range
bf385648
FM
2643 * 1 - adding the hole extent if no_holes isn't set or if we are
2644 * replacing the range with a new extent
9cba40a6 2645 */
bf385648 2646 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
690a5dbf
FM
2647 rsv_count = 3;
2648 else
2649 rsv_count = 2;
2650
9cba40a6
FM
2651 trans = btrfs_start_transaction(root, rsv_count);
2652 if (IS_ERR(trans)) {
2653 ret = PTR_ERR(trans);
2654 trans = NULL;
2655 goto out_free;
2656 }
2657
2658 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2659 min_size, false);
2660 BUG_ON(ret);
2661 trans->block_rsv = rsv;
2662
2663 cur_offset = start;
5893dfb9
FM
2664 drop_args.path = path;
2665 drop_args.end = end + 1;
2666 drop_args.drop_cache = true;
9cba40a6 2667 while (cur_offset < end) {
5893dfb9
FM
2668 drop_args.start = cur_offset;
2669 ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
2766ff61
FM
2670 /* If we are punching a hole decrement the inode's byte count */
2671 if (!extent_info)
2672 btrfs_update_inode_bytes(BTRFS_I(inode), 0,
2673 drop_args.bytes_found);
690a5dbf
FM
2674 if (ret != -ENOSPC) {
2675 /*
2676 * When cloning we want to avoid transaction aborts when
2677 * nothing was done and we are attempting to clone parts
2678 * of inline extents, in such cases -EOPNOTSUPP is
2679 * returned by __btrfs_drop_extents() without having
2680 * changed anything in the file.
2681 */
bf385648 2682 if (extent_info && !extent_info->is_new_extent &&
8fccebfa 2683 ret && ret != -EOPNOTSUPP)
690a5dbf 2684 btrfs_abort_transaction(trans, ret);
9cba40a6 2685 break;
690a5dbf 2686 }
9cba40a6
FM
2687
2688 trans->block_rsv = &fs_info->trans_block_rsv;
2689
5893dfb9 2690 if (!extent_info && cur_offset < drop_args.drop_end &&
690a5dbf 2691 cur_offset < ino_size) {
9cba40a6 2692 ret = fill_holes(trans, BTRFS_I(inode), path,
5893dfb9 2693 cur_offset, drop_args.drop_end);
9cba40a6
FM
2694 if (ret) {
2695 /*
2696 * If we failed then we didn't insert our hole
2697 * entries for the area we dropped, so now the
2698 * fs is corrupted, so we must abort the
2699 * transaction.
2700 */
2701 btrfs_abort_transaction(trans, ret);
2702 break;
2703 }
5893dfb9 2704 } else if (!extent_info && cur_offset < drop_args.drop_end) {
9ddc959e
JB
2705 /*
2706 * We are past the i_size here, but since we didn't
2707 * insert holes we need to clear the mapped area so we
2708 * know to not set disk_i_size in this area until a new
2709 * file extent is inserted here.
2710 */
2711 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
5893dfb9
FM
2712 cur_offset,
2713 drop_args.drop_end - cur_offset);
9ddc959e
JB
2714 if (ret) {
2715 /*
2716 * We couldn't clear our area, so we could
2717 * presumably adjust up and corrupt the fs, so
2718 * we need to abort.
2719 */
2720 btrfs_abort_transaction(trans, ret);
2721 break;
2722 }
9cba40a6
FM
2723 }
2724
5893dfb9
FM
2725 if (extent_info &&
2726 drop_args.drop_end > extent_info->file_offset) {
2727 u64 replace_len = drop_args.drop_end -
2728 extent_info->file_offset;
690a5dbf 2729
03fcb1ab
NB
2730 ret = btrfs_insert_replace_extent(trans, BTRFS_I(inode),
2731 path, extent_info, replace_len,
2732 drop_args.bytes_found);
690a5dbf
FM
2733 if (ret) {
2734 btrfs_abort_transaction(trans, ret);
2735 break;
2736 }
bf385648
FM
2737 extent_info->data_len -= replace_len;
2738 extent_info->data_offset += replace_len;
2739 extent_info->file_offset += replace_len;
690a5dbf
FM
2740 }
2741
5893dfb9 2742 cur_offset = drop_args.drop_end;
9cba40a6 2743
9a56fcd1 2744 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9cba40a6
FM
2745 if (ret)
2746 break;
2747
2748 btrfs_end_transaction(trans);
2749 btrfs_btree_balance_dirty(fs_info);
2750
2751 trans = btrfs_start_transaction(root, rsv_count);
2752 if (IS_ERR(trans)) {
2753 ret = PTR_ERR(trans);
2754 trans = NULL;
2755 break;
2756 }
2757
2758 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2759 rsv, min_size, false);
2760 BUG_ON(ret); /* shouldn't happen */
2761 trans->block_rsv = rsv;
2762
bf385648 2763 if (!extent_info) {
dea46d84
NB
2764 ret = find_first_non_hole(BTRFS_I(inode), &cur_offset,
2765 &len);
690a5dbf
FM
2766 if (unlikely(ret < 0))
2767 break;
2768 if (ret && !len) {
2769 ret = 0;
2770 break;
2771 }
9cba40a6
FM
2772 }
2773 }
2774
690a5dbf
FM
2775 /*
2776 * If we were cloning, force the next fsync to be a full one since we
2777 * we replaced (or just dropped in the case of cloning holes when
2778 * NO_HOLES is enabled) extents and extent maps.
2779 * This is for the sake of simplicity, and cloning into files larger
2780 * than 16Mb would force the full fsync any way (when
2781 * try_release_extent_mapping() is invoked during page cache truncation.
2782 */
bf385648 2783 if (extent_info && !extent_info->is_new_extent)
690a5dbf
FM
2784 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2785 &BTRFS_I(inode)->runtime_flags);
2786
9cba40a6
FM
2787 if (ret)
2788 goto out_trans;
2789
2790 trans->block_rsv = &fs_info->trans_block_rsv;
2791 /*
2792 * If we are using the NO_HOLES feature we might have had already an
2793 * hole that overlaps a part of the region [lockstart, lockend] and
2794 * ends at (or beyond) lockend. Since we have no file extent items to
2795 * represent holes, drop_end can be less than lockend and so we must
2796 * make sure we have an extent map representing the existing hole (the
2797 * call to __btrfs_drop_extents() might have dropped the existing extent
2798 * map representing the existing hole), otherwise the fast fsync path
2799 * will not record the existence of the hole region
2800 * [existing_hole_start, lockend].
2801 */
5893dfb9
FM
2802 if (drop_args.drop_end <= end)
2803 drop_args.drop_end = end + 1;
9cba40a6
FM
2804 /*
2805 * Don't insert file hole extent item if it's for a range beyond eof
2806 * (because it's useless) or if it represents a 0 bytes range (when
2807 * cur_offset == drop_end).
2808 */
5893dfb9
FM
2809 if (!extent_info && cur_offset < ino_size &&
2810 cur_offset < drop_args.drop_end) {
9cba40a6 2811 ret = fill_holes(trans, BTRFS_I(inode), path,
5893dfb9 2812 cur_offset, drop_args.drop_end);
9cba40a6
FM
2813 if (ret) {
2814 /* Same comment as above. */
2815 btrfs_abort_transaction(trans, ret);
2816 goto out_trans;
2817 }
5893dfb9 2818 } else if (!extent_info && cur_offset < drop_args.drop_end) {
9ddc959e
JB
2819 /* See the comment in the loop above for the reasoning here. */
2820 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
5893dfb9 2821 cur_offset, drop_args.drop_end - cur_offset);
9ddc959e
JB
2822 if (ret) {
2823 btrfs_abort_transaction(trans, ret);
2824 goto out_trans;
2825 }
2826
9cba40a6 2827 }
bf385648 2828 if (extent_info) {
03fcb1ab
NB
2829 ret = btrfs_insert_replace_extent(trans, BTRFS_I(inode), path,
2830 extent_info, extent_info->data_len,
2831 drop_args.bytes_found);
690a5dbf
FM
2832 if (ret) {
2833 btrfs_abort_transaction(trans, ret);
2834 goto out_trans;
2835 }
2836 }
9cba40a6
FM
2837
2838out_trans:
2839 if (!trans)
2840 goto out_free;
2841
2842 trans->block_rsv = &fs_info->trans_block_rsv;
2843 if (ret)
2844 btrfs_end_transaction(trans);
2845 else
2846 *trans_out = trans;
2847out_free:
2848 btrfs_free_block_rsv(fs_info, rsv);
2849out:
2850 return ret;
2851}
2852
2aaa6655
JB
2853static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
2854{
0b246afa 2855 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2aaa6655
JB
2856 struct btrfs_root *root = BTRFS_I(inode)->root;
2857 struct extent_state *cached_state = NULL;
2858 struct btrfs_path *path;
9cba40a6 2859 struct btrfs_trans_handle *trans = NULL;
d7781546
QW
2860 u64 lockstart;
2861 u64 lockend;
2862 u64 tail_start;
2863 u64 tail_len;
2864 u64 orig_start = offset;
2aaa6655 2865 int ret = 0;
9703fefe 2866 bool same_block;
a1a50f60 2867 u64 ino_size;
9703fefe 2868 bool truncated_block = false;
e8c1c76e 2869 bool updated_inode = false;
2aaa6655 2870
0ef8b726
JB
2871 ret = btrfs_wait_ordered_range(inode, offset, len);
2872 if (ret)
2873 return ret;
2aaa6655 2874
5955102c 2875 inode_lock(inode);
0b246afa 2876 ino_size = round_up(inode->i_size, fs_info->sectorsize);
dea46d84 2877 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
d7781546
QW
2878 if (ret < 0)
2879 goto out_only_mutex;
2880 if (ret && !len) {
2881 /* Already in a large hole */
2882 ret = 0;
2883 goto out_only_mutex;
2884 }
2885
6fee248d 2886 lockstart = round_up(offset, btrfs_inode_sectorsize(BTRFS_I(inode)));
d7781546 2887 lockend = round_down(offset + len,
6fee248d 2888 btrfs_inode_sectorsize(BTRFS_I(inode))) - 1;
0b246afa
JM
2889 same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
2890 == (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
7426cc04 2891 /*
9703fefe 2892 * We needn't truncate any block which is beyond the end of the file
7426cc04
MX
2893 * because we are sure there is no data there.
2894 */
2aaa6655 2895 /*
9703fefe
CR
2896 * Only do this if we are in the same block and we aren't doing the
2897 * entire block.
2aaa6655 2898 */
0b246afa 2899 if (same_block && len < fs_info->sectorsize) {
e8c1c76e 2900 if (offset < ino_size) {
9703fefe 2901 truncated_block = true;
217f42eb
NB
2902 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
2903 0);
e8c1c76e
FM
2904 } else {
2905 ret = 0;
2906 }
d7781546 2907 goto out_only_mutex;
2aaa6655
JB
2908 }
2909
9703fefe 2910 /* zero back part of the first block */
12870f1c 2911 if (offset < ino_size) {
9703fefe 2912 truncated_block = true;
217f42eb 2913 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
7426cc04 2914 if (ret) {
5955102c 2915 inode_unlock(inode);
7426cc04
MX
2916 return ret;
2917 }
2aaa6655
JB
2918 }
2919
d7781546
QW
2920 /* Check the aligned pages after the first unaligned page,
2921 * if offset != orig_start, which means the first unaligned page
01327610 2922 * including several following pages are already in holes,
d7781546
QW
2923 * the extra check can be skipped */
2924 if (offset == orig_start) {
2925 /* after truncate page, check hole again */
2926 len = offset + len - lockstart;
2927 offset = lockstart;
dea46d84 2928 ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
d7781546
QW
2929 if (ret < 0)
2930 goto out_only_mutex;
2931 if (ret && !len) {
2932 ret = 0;
2933 goto out_only_mutex;
2934 }
2935 lockstart = offset;
2936 }
2937
2938 /* Check the tail unaligned part is in a hole */
2939 tail_start = lockend + 1;
2940 tail_len = offset + len - tail_start;
2941 if (tail_len) {
dea46d84 2942 ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
d7781546
QW
2943 if (unlikely(ret < 0))
2944 goto out_only_mutex;
2945 if (!ret) {
2946 /* zero the front end of the last page */
2947 if (tail_start + tail_len < ino_size) {
9703fefe 2948 truncated_block = true;
217f42eb 2949 ret = btrfs_truncate_block(BTRFS_I(inode),
9703fefe
CR
2950 tail_start + tail_len,
2951 0, 1);
d7781546
QW
2952 if (ret)
2953 goto out_only_mutex;
51f395ad 2954 }
0061280d 2955 }
2aaa6655
JB
2956 }
2957
2958 if (lockend < lockstart) {
e8c1c76e
FM
2959 ret = 0;
2960 goto out_only_mutex;
2aaa6655
JB
2961 }
2962
f27451f2
FM
2963 ret = btrfs_punch_hole_lock_range(inode, lockstart, lockend,
2964 &cached_state);
8fca9550 2965 if (ret)
f27451f2 2966 goto out_only_mutex;
2aaa6655
JB
2967
2968 path = btrfs_alloc_path();
2969 if (!path) {
2970 ret = -ENOMEM;
2971 goto out;
2972 }
2973
306bfec0 2974 ret = btrfs_replace_file_extents(inode, path, lockstart, lockend, NULL,
690a5dbf 2975 &trans);
9cba40a6
FM
2976 btrfs_free_path(path);
2977 if (ret)
2978 goto out;
2aaa6655 2979
9cba40a6 2980 ASSERT(trans != NULL);
e1f5790e 2981 inode_inc_iversion(inode);
c2050a45 2982 inode->i_mtime = inode->i_ctime = current_time(inode);
9a56fcd1 2983 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
e8c1c76e 2984 updated_inode = true;
3a45bb20 2985 btrfs_end_transaction(trans);
2ff7e61e 2986 btrfs_btree_balance_dirty(fs_info);
2aaa6655
JB
2987out:
2988 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
e43bbe5e 2989 &cached_state);
d7781546 2990out_only_mutex:
9cba40a6 2991 if (!updated_inode && truncated_block && !ret) {
e8c1c76e
FM
2992 /*
2993 * If we only end up zeroing part of a page, we still need to
2994 * update the inode item, so that all the time fields are
2995 * updated as well as the necessary btrfs inode in memory fields
2996 * for detecting, at fsync time, if the inode isn't yet in the
2997 * log tree or it's there but not up to date.
2998 */
17900668
FM
2999 struct timespec64 now = current_time(inode);
3000
3001 inode_inc_iversion(inode);
3002 inode->i_mtime = now;
3003 inode->i_ctime = now;
e8c1c76e
FM
3004 trans = btrfs_start_transaction(root, 1);
3005 if (IS_ERR(trans)) {
9cba40a6 3006 ret = PTR_ERR(trans);
e8c1c76e 3007 } else {
9cba40a6
FM
3008 int ret2;
3009
9a56fcd1 3010 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9cba40a6
FM
3011 ret2 = btrfs_end_transaction(trans);
3012 if (!ret)
3013 ret = ret2;
e8c1c76e
FM
3014 }
3015 }
5955102c 3016 inode_unlock(inode);
9cba40a6 3017 return ret;
2aaa6655
JB
3018}
3019
14524a84
QW
3020/* Helper structure to record which range is already reserved */
3021struct falloc_range {
3022 struct list_head list;
3023 u64 start;
3024 u64 len;
3025};
3026
3027/*
3028 * Helper function to add falloc range
3029 *
3030 * Caller should have locked the larger range of extent containing
3031 * [start, len)
3032 */
3033static int add_falloc_range(struct list_head *head, u64 start, u64 len)
3034{
3035 struct falloc_range *prev = NULL;
3036 struct falloc_range *range = NULL;
3037
3038 if (list_empty(head))
3039 goto insert;
3040
3041 /*
3042 * As fallocate iterate by bytenr order, we only need to check
3043 * the last range.
3044 */
3045 prev = list_entry(head->prev, struct falloc_range, list);
3046 if (prev->start + prev->len == start) {
3047 prev->len += len;
3048 return 0;
3049 }
3050insert:
32fc932e 3051 range = kmalloc(sizeof(*range), GFP_KERNEL);
14524a84
QW
3052 if (!range)
3053 return -ENOMEM;
3054 range->start = start;
3055 range->len = len;
3056 list_add_tail(&range->list, head);
3057 return 0;
3058}
3059
f27451f2
FM
3060static int btrfs_fallocate_update_isize(struct inode *inode,
3061 const u64 end,
3062 const int mode)
3063{
3064 struct btrfs_trans_handle *trans;
3065 struct btrfs_root *root = BTRFS_I(inode)->root;
3066 int ret;
3067 int ret2;
3068
3069 if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
3070 return 0;
3071
3072 trans = btrfs_start_transaction(root, 1);
3073 if (IS_ERR(trans))
3074 return PTR_ERR(trans);
3075
3076 inode->i_ctime = current_time(inode);
3077 i_size_write(inode, end);
76aea537 3078 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9a56fcd1 3079 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
f27451f2
FM
3080 ret2 = btrfs_end_transaction(trans);
3081
3082 return ret ? ret : ret2;
3083}
3084
81fdf638 3085enum {
f262fa8d
DS
3086 RANGE_BOUNDARY_WRITTEN_EXTENT,
3087 RANGE_BOUNDARY_PREALLOC_EXTENT,
3088 RANGE_BOUNDARY_HOLE,
81fdf638
FM
3089};
3090
948dfeb8 3091static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
f27451f2
FM
3092 u64 offset)
3093{
948dfeb8 3094 const u64 sectorsize = btrfs_inode_sectorsize(inode);
f27451f2 3095 struct extent_map *em;
81fdf638 3096 int ret;
f27451f2
FM
3097
3098 offset = round_down(offset, sectorsize);
948dfeb8 3099 em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize);
f27451f2
FM
3100 if (IS_ERR(em))
3101 return PTR_ERR(em);
3102
3103 if (em->block_start == EXTENT_MAP_HOLE)
81fdf638
FM
3104 ret = RANGE_BOUNDARY_HOLE;
3105 else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3106 ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
3107 else
3108 ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
f27451f2
FM
3109
3110 free_extent_map(em);
3111 return ret;
3112}
3113
3114static int btrfs_zero_range(struct inode *inode,
3115 loff_t offset,
3116 loff_t len,
3117 const int mode)
3118{
3119 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3120 struct extent_map *em;
3121 struct extent_changeset *data_reserved = NULL;
3122 int ret;
3123 u64 alloc_hint = 0;
6fee248d 3124 const u64 sectorsize = btrfs_inode_sectorsize(BTRFS_I(inode));
f27451f2
FM
3125 u64 alloc_start = round_down(offset, sectorsize);
3126 u64 alloc_end = round_up(offset + len, sectorsize);
3127 u64 bytes_to_reserve = 0;
3128 bool space_reserved = false;
3129
3130 inode_dio_wait(inode);
3131
39b07b5d
OS
3132 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3133 alloc_end - alloc_start);
f27451f2
FM
3134 if (IS_ERR(em)) {
3135 ret = PTR_ERR(em);
3136 goto out;
3137 }
3138
3139 /*
3140 * Avoid hole punching and extent allocation for some cases. More cases
3141 * could be considered, but these are unlikely common and we keep things
3142 * as simple as possible for now. Also, intentionally, if the target
3143 * range contains one or more prealloc extents together with regular
3144 * extents and holes, we drop all the existing extents and allocate a
3145 * new prealloc extent, so that we get a larger contiguous disk extent.
3146 */
3147 if (em->start <= alloc_start &&
3148 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3149 const u64 em_end = em->start + em->len;
3150
3151 if (em_end >= offset + len) {
3152 /*
3153 * The whole range is already a prealloc extent,
3154 * do nothing except updating the inode's i_size if
3155 * needed.
3156 */
3157 free_extent_map(em);
3158 ret = btrfs_fallocate_update_isize(inode, offset + len,
3159 mode);
3160 goto out;
3161 }
3162 /*
3163 * Part of the range is already a prealloc extent, so operate
3164 * only on the remaining part of the range.
3165 */
3166 alloc_start = em_end;
3167 ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3168 len = offset + len - alloc_start;
3169 offset = alloc_start;
3170 alloc_hint = em->block_start + em->len;
3171 }
3172 free_extent_map(em);
3173
3174 if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3175 BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
39b07b5d
OS
3176 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3177 sectorsize);
f27451f2
FM
3178 if (IS_ERR(em)) {
3179 ret = PTR_ERR(em);
3180 goto out;
3181 }
3182
3183 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3184 free_extent_map(em);
3185 ret = btrfs_fallocate_update_isize(inode, offset + len,
3186 mode);
3187 goto out;
3188 }
3189 if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3190 free_extent_map(em);
217f42eb
NB
3191 ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3192 0);
f27451f2
FM
3193 if (!ret)
3194 ret = btrfs_fallocate_update_isize(inode,
3195 offset + len,
3196 mode);
3197 return ret;
3198 }
3199 free_extent_map(em);
3200 alloc_start = round_down(offset, sectorsize);
3201 alloc_end = alloc_start + sectorsize;
3202 goto reserve_space;
3203 }
3204
3205 alloc_start = round_up(offset, sectorsize);
3206 alloc_end = round_down(offset + len, sectorsize);
3207
3208 /*
3209 * For unaligned ranges, check the pages at the boundaries, they might
3210 * map to an extent, in which case we need to partially zero them, or
3211 * they might map to a hole, in which case we need our allocation range
3212 * to cover them.
3213 */
3214 if (!IS_ALIGNED(offset, sectorsize)) {
948dfeb8
NB
3215 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3216 offset);
f27451f2
FM
3217 if (ret < 0)
3218 goto out;
81fdf638 3219 if (ret == RANGE_BOUNDARY_HOLE) {
f27451f2
FM
3220 alloc_start = round_down(offset, sectorsize);
3221 ret = 0;
81fdf638 3222 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
217f42eb 3223 ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
f27451f2
FM
3224 if (ret)
3225 goto out;
81fdf638
FM
3226 } else {
3227 ret = 0;
f27451f2
FM
3228 }
3229 }
3230
3231 if (!IS_ALIGNED(offset + len, sectorsize)) {
948dfeb8 3232 ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
f27451f2
FM
3233 offset + len);
3234 if (ret < 0)
3235 goto out;
81fdf638 3236 if (ret == RANGE_BOUNDARY_HOLE) {
f27451f2
FM
3237 alloc_end = round_up(offset + len, sectorsize);
3238 ret = 0;
81fdf638 3239 } else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
217f42eb
NB
3240 ret = btrfs_truncate_block(BTRFS_I(inode), offset + len,
3241 0, 1);
f27451f2
FM
3242 if (ret)
3243 goto out;
81fdf638
FM
3244 } else {
3245 ret = 0;
f27451f2
FM
3246 }
3247 }
3248
3249reserve_space:
3250 if (alloc_start < alloc_end) {
3251 struct extent_state *cached_state = NULL;
3252 const u64 lockstart = alloc_start;
3253 const u64 lockend = alloc_end - 1;
3254
3255 bytes_to_reserve = alloc_end - alloc_start;
3256 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3257 bytes_to_reserve);
3258 if (ret < 0)
3259 goto out;
3260 space_reserved = true;
f27451f2
FM
3261 ret = btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3262 &cached_state);
3263 if (ret)
3264 goto out;
7661a3e0 3265 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
a7f8b1c2
QW
3266 alloc_start, bytes_to_reserve);
3267 if (ret)
3268 goto out;
f27451f2
FM
3269 ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3270 alloc_end - alloc_start,
3271 i_blocksize(inode),
3272 offset + len, &alloc_hint);
3273 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3274 lockend, &cached_state);
3275 /* btrfs_prealloc_file_range releases reserved space on error */
9f13ce74 3276 if (ret) {
f27451f2 3277 space_reserved = false;
9f13ce74
FM
3278 goto out;
3279 }
f27451f2 3280 }
9f13ce74 3281 ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
f27451f2
FM
3282 out:
3283 if (ret && space_reserved)
25ce28ca 3284 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
f27451f2
FM
3285 alloc_start, bytes_to_reserve);
3286 extent_changeset_free(data_reserved);
3287
3288 return ret;
3289}
3290
2fe17c10
CH
3291static long btrfs_fallocate(struct file *file, int mode,
3292 loff_t offset, loff_t len)
3293{
496ad9aa 3294 struct inode *inode = file_inode(file);
2fe17c10 3295 struct extent_state *cached_state = NULL;
364ecf36 3296 struct extent_changeset *data_reserved = NULL;
14524a84
QW
3297 struct falloc_range *range;
3298 struct falloc_range *tmp;
3299 struct list_head reserve_list;
2fe17c10
CH
3300 u64 cur_offset;
3301 u64 last_byte;
3302 u64 alloc_start;
3303 u64 alloc_end;
3304 u64 alloc_hint = 0;
3305 u64 locked_end;
14524a84 3306 u64 actual_end = 0;
2fe17c10 3307 struct extent_map *em;
6fee248d 3308 int blocksize = btrfs_inode_sectorsize(BTRFS_I(inode));
2fe17c10
CH
3309 int ret;
3310
797f4277
MX
3311 alloc_start = round_down(offset, blocksize);
3312 alloc_end = round_up(offset + len, blocksize);
18513091 3313 cur_offset = alloc_start;
2fe17c10 3314
2aaa6655 3315 /* Make sure we aren't being give some crap mode */
f27451f2
FM
3316 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3317 FALLOC_FL_ZERO_RANGE))
2fe17c10
CH
3318 return -EOPNOTSUPP;
3319
2aaa6655
JB
3320 if (mode & FALLOC_FL_PUNCH_HOLE)
3321 return btrfs_punch_hole(inode, offset, len);
3322
d98456fc 3323 /*
14524a84
QW
3324 * Only trigger disk allocation, don't trigger qgroup reserve
3325 *
3326 * For qgroup space, it will be checked later.
d98456fc 3327 */
f27451f2
FM
3328 if (!(mode & FALLOC_FL_ZERO_RANGE)) {
3329 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3330 alloc_end - alloc_start);
3331 if (ret < 0)
3332 return ret;
3333 }
d98456fc 3334
a14b78ad 3335 btrfs_inode_lock(inode, 0);
2a162ce9
DI
3336
3337 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3338 ret = inode_newsize_ok(inode, offset + len);
3339 if (ret)
3340 goto out;
3341 }
2fe17c10 3342
14524a84
QW
3343 /*
3344 * TODO: Move these two operations after we have checked
3345 * accurate reserved space, or fallocate can still fail but
3346 * with page truncated or size expanded.
3347 *
3348 * But that's a minor problem and won't do much harm BTW.
3349 */
2fe17c10 3350 if (alloc_start > inode->i_size) {
a41ad394
JB
3351 ret = btrfs_cont_expand(inode, i_size_read(inode),
3352 alloc_start);
2fe17c10
CH
3353 if (ret)
3354 goto out;
0f6925fa 3355 } else if (offset + len > inode->i_size) {
a71754fc
JB
3356 /*
3357 * If we are fallocating from the end of the file onward we
9703fefe
CR
3358 * need to zero out the end of the block if i_size lands in the
3359 * middle of a block.
a71754fc 3360 */
217f42eb 3361 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
a71754fc
JB
3362 if (ret)
3363 goto out;
2fe17c10
CH
3364 }
3365
a71754fc
JB
3366 /*
3367 * wait for ordered IO before we have any locks. We'll loop again
3368 * below with the locks held.
3369 */
0ef8b726
JB
3370 ret = btrfs_wait_ordered_range(inode, alloc_start,
3371 alloc_end - alloc_start);
3372 if (ret)
3373 goto out;
a71754fc 3374
f27451f2
FM
3375 if (mode & FALLOC_FL_ZERO_RANGE) {
3376 ret = btrfs_zero_range(inode, offset, len, mode);
3377 inode_unlock(inode);
3378 return ret;
3379 }
3380
2fe17c10
CH
3381 locked_end = alloc_end - 1;
3382 while (1) {
3383 struct btrfs_ordered_extent *ordered;
3384
3385 /* the extent lock is ordered inside the running
3386 * transaction
3387 */
3388 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
ff13db41 3389 locked_end, &cached_state);
6d072c8e
NB
3390 ordered = btrfs_lookup_first_ordered_extent(BTRFS_I(inode),
3391 locked_end);
96b09dde 3392
2fe17c10 3393 if (ordered &&
bffe633e 3394 ordered->file_offset + ordered->num_bytes > alloc_start &&
2fe17c10
CH
3395 ordered->file_offset < alloc_end) {
3396 btrfs_put_ordered_extent(ordered);
3397 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
3398 alloc_start, locked_end,
e43bbe5e 3399 &cached_state);
2fe17c10
CH
3400 /*
3401 * we can't wait on the range with the transaction
3402 * running or with the extent lock held
3403 */
0ef8b726
JB
3404 ret = btrfs_wait_ordered_range(inode, alloc_start,
3405 alloc_end - alloc_start);
3406 if (ret)
3407 goto out;
2fe17c10
CH
3408 } else {
3409 if (ordered)
3410 btrfs_put_ordered_extent(ordered);
3411 break;
3412 }
3413 }
3414
14524a84
QW
3415 /* First, check if we exceed the qgroup limit */
3416 INIT_LIST_HEAD(&reserve_list);
6b7d6e93 3417 while (cur_offset < alloc_end) {
fc4f21b1 3418 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
39b07b5d 3419 alloc_end - cur_offset);
9986277e
DC
3420 if (IS_ERR(em)) {
3421 ret = PTR_ERR(em);
79787eaa
JM
3422 break;
3423 }
2fe17c10 3424 last_byte = min(extent_map_end(em), alloc_end);
f1e490a7 3425 actual_end = min_t(u64, extent_map_end(em), offset + len);
797f4277 3426 last_byte = ALIGN(last_byte, blocksize);
2fe17c10
CH
3427 if (em->block_start == EXTENT_MAP_HOLE ||
3428 (cur_offset >= inode->i_size &&
3429 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
14524a84
QW
3430 ret = add_falloc_range(&reserve_list, cur_offset,
3431 last_byte - cur_offset);
3432 if (ret < 0) {
3433 free_extent_map(em);
3434 break;
3d850dd4 3435 }
7661a3e0
NB
3436 ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
3437 &data_reserved, cur_offset,
3438 last_byte - cur_offset);
be2d253c 3439 if (ret < 0) {
39ad3173 3440 cur_offset = last_byte;
be2d253c 3441 free_extent_map(em);
14524a84 3442 break;
be2d253c 3443 }
18513091
WX
3444 } else {
3445 /*
3446 * Do not need to reserve unwritten extent for this
3447 * range, free reserved data space first, otherwise
3448 * it'll result in false ENOSPC error.
3449 */
25ce28ca
NB
3450 btrfs_free_reserved_data_space(BTRFS_I(inode),
3451 data_reserved, cur_offset,
3452 last_byte - cur_offset);
2fe17c10
CH
3453 }
3454 free_extent_map(em);
2fe17c10 3455 cur_offset = last_byte;
14524a84
QW
3456 }
3457
3458 /*
3459 * If ret is still 0, means we're OK to fallocate.
3460 * Or just cleanup the list and exit.
3461 */
3462 list_for_each_entry_safe(range, tmp, &reserve_list, list) {
3463 if (!ret)
3464 ret = btrfs_prealloc_file_range(inode, mode,
3465 range->start,
93407472 3466 range->len, i_blocksize(inode),
14524a84 3467 offset + len, &alloc_hint);
18513091 3468 else
25ce28ca 3469 btrfs_free_reserved_data_space(BTRFS_I(inode),
bc42bda2
QW
3470 data_reserved, range->start,
3471 range->len);
14524a84
QW
3472 list_del(&range->list);
3473 kfree(range);
3474 }
3475 if (ret < 0)
3476 goto out_unlock;
3477
f27451f2
FM
3478 /*
3479 * We didn't need to allocate any more space, but we still extended the
3480 * size of the file so we need to update i_size and the inode item.
3481 */
3482 ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
14524a84 3483out_unlock:
2fe17c10 3484 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
e43bbe5e 3485 &cached_state);
2fe17c10 3486out:
5955102c 3487 inode_unlock(inode);
d98456fc 3488 /* Let go of our reservation. */
f27451f2 3489 if (ret != 0 && !(mode & FALLOC_FL_ZERO_RANGE))
25ce28ca 3490 btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
39ad3173 3491 cur_offset, alloc_end - cur_offset);
364ecf36 3492 extent_changeset_free(data_reserved);
2fe17c10
CH
3493 return ret;
3494}
3495
bc80230e
NB
3496static loff_t find_desired_extent(struct inode *inode, loff_t offset,
3497 int whence)
b2675157 3498{
0b246afa 3499 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7f4ca37c 3500 struct extent_map *em = NULL;
b2675157 3501 struct extent_state *cached_state = NULL;
d79b7c26 3502 loff_t i_size = inode->i_size;
4d1a40c6
LB
3503 u64 lockstart;
3504 u64 lockend;
3505 u64 start;
3506 u64 len;
b2675157
JB
3507 int ret = 0;
3508
bc80230e 3509 if (i_size == 0 || offset >= i_size)
4d1a40c6
LB
3510 return -ENXIO;
3511
3512 /*
bc80230e 3513 * offset can be negative, in this case we start finding DATA/HOLE from
4d1a40c6
LB
3514 * the very start of the file.
3515 */
bc80230e 3516 start = max_t(loff_t, 0, offset);
4d1a40c6 3517
0b246afa 3518 lockstart = round_down(start, fs_info->sectorsize);
d79b7c26 3519 lockend = round_up(i_size, fs_info->sectorsize);
b2675157 3520 if (lockend <= lockstart)
0b246afa 3521 lockend = lockstart + fs_info->sectorsize;
1214b53f 3522 lockend--;
b2675157
JB
3523 len = lockend - lockstart + 1;
3524
ff13db41 3525 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
d0082371 3526 &cached_state);
b2675157 3527
d79b7c26 3528 while (start < i_size) {
4ab47a8d 3529 em = btrfs_get_extent_fiemap(BTRFS_I(inode), start, len);
b2675157 3530 if (IS_ERR(em)) {
6af021d8 3531 ret = PTR_ERR(em);
7f4ca37c 3532 em = NULL;
b2675157
JB
3533 break;
3534 }
3535
7f4ca37c
JB
3536 if (whence == SEEK_HOLE &&
3537 (em->block_start == EXTENT_MAP_HOLE ||
3538 test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3539 break;
3540 else if (whence == SEEK_DATA &&
3541 (em->block_start != EXTENT_MAP_HOLE &&
3542 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags)))
3543 break;
b2675157
JB
3544
3545 start = em->start + em->len;
b2675157 3546 free_extent_map(em);
7f4ca37c 3547 em = NULL;
b2675157
JB
3548 cond_resched();
3549 }
7f4ca37c 3550 free_extent_map(em);
bc80230e
NB
3551 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3552 &cached_state);
3553 if (ret) {
3554 offset = ret;
3555 } else {
d79b7c26 3556 if (whence == SEEK_DATA && start >= i_size)
bc80230e 3557 offset = -ENXIO;
7f4ca37c 3558 else
bc80230e 3559 offset = min_t(loff_t, start, i_size);
7f4ca37c 3560 }
bc80230e
NB
3561
3562 return offset;
b2675157
JB
3563}
3564
965c8e59 3565static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
b2675157
JB
3566{
3567 struct inode *inode = file->f_mapping->host;
b2675157 3568
965c8e59 3569 switch (whence) {
2034f3b4
NB
3570 default:
3571 return generic_file_llseek(file, offset, whence);
b2675157
JB
3572 case SEEK_DATA:
3573 case SEEK_HOLE:
a14b78ad 3574 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
bc80230e 3575 offset = find_desired_extent(inode, offset, whence);
a14b78ad 3576 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
bc80230e 3577 break;
b2675157
JB
3578 }
3579
bc80230e
NB
3580 if (offset < 0)
3581 return offset;
3582
2034f3b4 3583 return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
b2675157
JB
3584}
3585
edf064e7
GR
3586static int btrfs_file_open(struct inode *inode, struct file *filp)
3587{
8730f12b 3588 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
edf064e7
GR
3589 return generic_file_open(inode, filp);
3590}
3591
4e4cabec
GR
3592static int check_direct_read(struct btrfs_fs_info *fs_info,
3593 const struct iov_iter *iter, loff_t offset)
3594{
3595 int ret;
3596 int i, seg;
3597
3598 ret = check_direct_IO(fs_info, iter, offset);
3599 if (ret < 0)
3600 return ret;
3601
3602 if (!iter_is_iovec(iter))
3603 return 0;
3604
3605 for (seg = 0; seg < iter->nr_segs; seg++)
3606 for (i = seg + 1; i < iter->nr_segs; i++)
3607 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
3608 return -EINVAL;
3609 return 0;
3610}
3611
3612static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
3613{
3614 struct inode *inode = file_inode(iocb->ki_filp);
3615 ssize_t ret;
3616
3617 if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
3618 return 0;
3619
a14b78ad 3620 btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
4e4cabec
GR
3621 ret = iomap_dio_rw(iocb, to, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
3622 is_sync_kiocb(iocb));
a14b78ad 3623 btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4e4cabec
GR
3624 return ret;
3625}
3626
f85781fb
GR
3627static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
3628{
3629 ssize_t ret = 0;
3630
3631 if (iocb->ki_flags & IOCB_DIRECT) {
4e4cabec 3632 ret = btrfs_direct_read(iocb, to);
0425e7ba
JT
3633 if (ret < 0 || !iov_iter_count(to) ||
3634 iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
f85781fb
GR
3635 return ret;
3636 }
3637
3638 return generic_file_buffered_read(iocb, to, ret);
3639}
3640
828c0950 3641const struct file_operations btrfs_file_operations = {
b2675157 3642 .llseek = btrfs_file_llseek,
f85781fb 3643 .read_iter = btrfs_file_read_iter,
e9906a98 3644 .splice_read = generic_file_splice_read,
b30ac0fc 3645 .write_iter = btrfs_file_write_iter,
d7776591 3646 .splice_write = iter_file_splice_write,
9ebefb18 3647 .mmap = btrfs_file_mmap,
edf064e7 3648 .open = btrfs_file_open,
e1b81e67 3649 .release = btrfs_release_file,
39279cc3 3650 .fsync = btrfs_sync_file,
2fe17c10 3651 .fallocate = btrfs_fallocate,
34287aa3 3652 .unlocked_ioctl = btrfs_ioctl,
39279cc3 3653#ifdef CONFIG_COMPAT
4c63c245 3654 .compat_ioctl = btrfs_compat_ioctl,
39279cc3 3655#endif
2e5dfc99 3656 .remap_file_range = btrfs_remap_file_range,
39279cc3 3657};
9247f317 3658
e67c718b 3659void __cold btrfs_auto_defrag_exit(void)
9247f317 3660{
5598e900 3661 kmem_cache_destroy(btrfs_inode_defrag_cachep);
9247f317
MX
3662}
3663
f5c29bd9 3664int __init btrfs_auto_defrag_init(void)
9247f317
MX
3665{
3666 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
3667 sizeof(struct inode_defrag), 0,
fba4b697 3668 SLAB_MEM_SPREAD,
9247f317
MX
3669 NULL);
3670 if (!btrfs_inode_defrag_cachep)
3671 return -ENOMEM;
3672
3673 return 0;
3674}
728404da
FM
3675
3676int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
3677{
3678 int ret;
3679
3680 /*
3681 * So with compression we will find and lock a dirty page and clear the
3682 * first one as dirty, setup an async extent, and immediately return
3683 * with the entire range locked but with nobody actually marked with
3684 * writeback. So we can't just filemap_write_and_wait_range() and
3685 * expect it to work since it will just kick off a thread to do the
3686 * actual work. So we need to call filemap_fdatawrite_range _again_
3687 * since it will wait on the page lock, which won't be unlocked until
3688 * after the pages have been marked as writeback and so we're good to go
3689 * from there. We have to do this otherwise we'll miss the ordered
3690 * extents and that results in badness. Please Josef, do not think you
3691 * know better and pull this out at some point in the future, it is
3692 * right and you are wrong.
3693 */
3694 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
3695 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
3696 &BTRFS_I(inode)->runtime_flags))
3697 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
3698
3699 return ret;
3700}