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