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