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