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