xref: /linux/fs/btrfs/inode.c (revision d9d80a859bc45ca022abc13afdd11d1c812a1034)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/blk-cgroup.h>
9 #include <linux/file.h>
10 #include <linux/filelock.h>
11 #include <linux/fs.h>
12 #include <linux/fs_struct.h>
13 #include <linux/pagemap.h>
14 #include <linux/highmem.h>
15 #include <linux/time.h>
16 #include <linux/init.h>
17 #include <linux/string.h>
18 #include <linux/backing-dev.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/xattr.h>
22 #include <linux/posix_acl.h>
23 #include <linux/falloc.h>
24 #include <linux/slab.h>
25 #include <linux/ratelimit.h>
26 #include <linux/btrfs.h>
27 #include <linux/blkdev.h>
28 #include <linux/posix_acl_xattr.h>
29 #include <linux/uio.h>
30 #include <linux/magic.h>
31 #include <linux/iversion.h>
32 #include <linux/swap.h>
33 #include <linux/migrate.h>
34 #include <linux/sched/mm.h>
35 #include <linux/iomap.h>
36 #include <linux/unaligned.h>
37 #include "misc.h"
38 #include "ctree.h"
39 #include "disk-io.h"
40 #include "transaction.h"
41 #include "btrfs_inode.h"
42 #include "ordered-data.h"
43 #include "xattr.h"
44 #include "tree-log.h"
45 #include "bio.h"
46 #include "compression.h"
47 #include "locking.h"
48 #include "props.h"
49 #include "qgroup.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
53 #include "zoned.h"
54 #include "subpage.h"
55 #include "inode-item.h"
56 #include "fs.h"
57 #include "accessors.h"
58 #include "extent-tree.h"
59 #include "root-tree.h"
60 #include "defrag.h"
61 #include "dir-item.h"
62 #include "file-item.h"
63 #include "uuid-tree.h"
64 #include "ioctl.h"
65 #include "file.h"
66 #include "acl.h"
67 #include "relocation.h"
68 #include "verity.h"
69 #include "super.h"
70 #include "orphan.h"
71 #include "backref.h"
72 #include "raid-stripe-tree.h"
73 #include "fiemap.h"
74 #include "delayed-inode.h"
75 
76 #define COW_FILE_RANGE_KEEP_LOCKED	(1UL << 0)
77 
78 struct btrfs_iget_args {
79 	u64 ino;
80 	struct btrfs_root *root;
81 };
82 
83 struct btrfs_rename_ctx {
84 	/* Output field. Stores the index number of the old directory entry. */
85 	u64 index;
86 };
87 
88 /*
89  * Used by data_reloc_print_warning_inode() to pass needed info for filename
90  * resolution and output of error message.
91  */
92 struct data_reloc_warn {
93 	struct btrfs_path path;
94 	struct btrfs_fs_info *fs_info;
95 	u64 extent_item_size;
96 	u64 logical;
97 	int mirror_num;
98 };
99 
100 /*
101  * For the file_extent_tree, we want to hold the inode lock when we lookup and
102  * update the disk_i_size, but lockdep will complain because our io_tree we hold
103  * the tree lock and get the inode lock when setting delalloc. These two things
104  * are unrelated, so make a class for the file_extent_tree so we don't get the
105  * two locking patterns mixed up.
106  */
107 static struct lock_class_key file_extent_tree_class;
108 
109 static const struct inode_operations btrfs_dir_inode_operations;
110 static const struct inode_operations btrfs_symlink_inode_operations;
111 static const struct inode_operations btrfs_special_inode_operations;
112 static const struct inode_operations btrfs_file_inode_operations;
113 static const struct address_space_operations btrfs_aops;
114 static const struct file_operations btrfs_dir_file_operations;
115 
116 static struct kmem_cache *btrfs_inode_cachep;
117 
118 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
119 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
120 
121 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
122 				     struct folio *locked_folio, u64 start,
123 				     u64 end, struct writeback_control *wbc,
124 				     bool pages_dirty);
125 
data_reloc_print_warning_inode(u64 inum,u64 offset,u64 num_bytes,u64 root,void * warn_ctx)126 static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
127 					  u64 root, void *warn_ctx)
128 {
129 	struct data_reloc_warn *warn = warn_ctx;
130 	struct btrfs_fs_info *fs_info = warn->fs_info;
131 	struct extent_buffer *eb;
132 	struct btrfs_inode_item *inode_item;
133 	struct inode_fs_paths *ipath __free(inode_fs_paths) = NULL;
134 	struct btrfs_root *local_root;
135 	struct btrfs_key key;
136 	unsigned int nofs_flag;
137 	u32 nlink;
138 	int ret;
139 
140 	local_root = btrfs_get_fs_root(fs_info, root, true);
141 	if (IS_ERR(local_root)) {
142 		ret = PTR_ERR(local_root);
143 		goto err;
144 	}
145 
146 	/* This makes the path point to (inum INODE_ITEM ioff). */
147 	key.objectid = inum;
148 	key.type = BTRFS_INODE_ITEM_KEY;
149 	key.offset = 0;
150 
151 	ret = btrfs_search_slot(NULL, local_root, &key, &warn->path, 0, 0);
152 	if (ret) {
153 		btrfs_put_root(local_root);
154 		btrfs_release_path(&warn->path);
155 		goto err;
156 	}
157 
158 	eb = warn->path.nodes[0];
159 	inode_item = btrfs_item_ptr(eb, warn->path.slots[0], struct btrfs_inode_item);
160 	nlink = btrfs_inode_nlink(eb, inode_item);
161 	btrfs_release_path(&warn->path);
162 
163 	nofs_flag = memalloc_nofs_save();
164 	ipath = init_ipath(4096, local_root, &warn->path);
165 	memalloc_nofs_restore(nofs_flag);
166 	if (IS_ERR(ipath)) {
167 		btrfs_put_root(local_root);
168 		ret = PTR_ERR(ipath);
169 		ipath = NULL;
170 		/*
171 		 * -ENOMEM, not a critical error, just output an generic error
172 		 * without filename.
173 		 */
174 		btrfs_warn(fs_info,
175 "checksum error at logical %llu mirror %u root %llu, inode %llu offset %llu",
176 			   warn->logical, warn->mirror_num, root, inum, offset);
177 		return ret;
178 	}
179 	ret = paths_from_inode(inum, ipath);
180 	if (ret < 0) {
181 		btrfs_put_root(local_root);
182 		goto err;
183 	}
184 
185 	/*
186 	 * We deliberately ignore the bit ipath might have been too small to
187 	 * hold all of the paths here
188 	 */
189 	for (int i = 0; i < ipath->fspath->elem_cnt; i++) {
190 		btrfs_warn(fs_info,
191 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu length %u links %u (path: %s)",
192 			   warn->logical, warn->mirror_num, root, inum, offset,
193 			   fs_info->sectorsize, nlink,
194 			   (char *)(unsigned long)ipath->fspath->val[i]);
195 	}
196 
197 	btrfs_put_root(local_root);
198 	return 0;
199 
200 err:
201 	btrfs_warn(fs_info,
202 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu, path resolving failed with ret=%d",
203 		   warn->logical, warn->mirror_num, root, inum, offset, ret);
204 
205 	return ret;
206 }
207 
208 /*
209  * Do extra user-friendly error output (e.g. lookup all the affected files).
210  *
211  * Return true if we succeeded doing the backref lookup.
212  * Return false if such lookup failed, and has to fallback to the old error message.
213  */
print_data_reloc_error(const struct btrfs_inode * inode,u64 file_off,const u8 * csum,const u8 * csum_expected,int mirror_num)214 static void print_data_reloc_error(const struct btrfs_inode *inode, u64 file_off,
215 				   const u8 *csum, const u8 *csum_expected,
216 				   int mirror_num)
217 {
218 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
219 	BTRFS_PATH_AUTO_RELEASE(path);
220 	struct btrfs_key found_key = { 0 };
221 	struct extent_buffer *eb;
222 	struct btrfs_extent_item *ei;
223 	const u32 csum_size = fs_info->csum_size;
224 	u64 logical;
225 	u64 flags;
226 	u32 item_size;
227 	int ret;
228 
229 	logical = btrfs_get_reloc_bg_bytenr(fs_info);
230 
231 	if (logical == U64_MAX) {
232 		btrfs_warn_rl(fs_info, "has data reloc tree but no running relocation");
233 		btrfs_warn_rl(fs_info,
234 "csum failed root %lld ino %llu off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
235 			btrfs_root_id(inode->root), btrfs_ino(inode), file_off,
236 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
237 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
238 			mirror_num);
239 		return;
240 	}
241 
242 	logical += file_off;
243 	btrfs_warn_rl(fs_info,
244 "csum failed root %lld ino %llu off %llu logical %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
245 			btrfs_root_id(inode->root),
246 			btrfs_ino(inode), file_off, logical,
247 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
248 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
249 			mirror_num);
250 
251 	ret = extent_from_logical(fs_info, logical, &path, &found_key, &flags);
252 	if (ret < 0) {
253 		btrfs_err_rl(fs_info, "failed to lookup extent item for logical %llu: %pe",
254 			     logical, ERR_PTR(ret));
255 		return;
256 	}
257 	eb = path.nodes[0];
258 	ei = btrfs_item_ptr(eb, path.slots[0], struct btrfs_extent_item);
259 	item_size = btrfs_item_size(eb, path.slots[0]);
260 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
261 		unsigned long ptr = 0;
262 		u64 ref_root;
263 		u8 ref_level;
264 
265 		while (true) {
266 			ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
267 						      item_size, &ref_root,
268 						      &ref_level);
269 			if (ret < 0) {
270 				btrfs_warn_rl(fs_info,
271 				"failed to resolve tree backref for logical %llu: %d",
272 					      logical, ret);
273 				break;
274 			}
275 			if (ret > 0)
276 				break;
277 
278 			btrfs_warn_rl(fs_info,
279 "csum error at logical %llu mirror %u: metadata %s (level %d) in tree %llu",
280 				logical, mirror_num,
281 				(ref_level ? "node" : "leaf"),
282 				ref_level, ref_root);
283 		}
284 	} else {
285 		struct btrfs_backref_walk_ctx ctx = { 0 };
286 		struct data_reloc_warn reloc_warn = { 0 };
287 
288 		/*
289 		 * Do not hold the path as later iterate_extent_inodes() call
290 		 * can be time consuming.
291 		 */
292 		btrfs_release_path(&path);
293 
294 		ctx.bytenr = found_key.objectid;
295 		ctx.extent_item_pos = logical - found_key.objectid;
296 		ctx.fs_info = fs_info;
297 
298 		reloc_warn.logical = logical;
299 		reloc_warn.extent_item_size = found_key.offset;
300 		reloc_warn.mirror_num = mirror_num;
301 		reloc_warn.fs_info = fs_info;
302 
303 		iterate_extent_inodes(&ctx, true,
304 				      data_reloc_print_warning_inode, &reloc_warn);
305 	}
306 }
307 
btrfs_print_data_csum_error(struct btrfs_inode * inode,u64 logical_start,u8 * csum,u8 * csum_expected,int mirror_num)308 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
309 		u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
310 {
311 	struct btrfs_root *root = inode->root;
312 	const u32 csum_size = root->fs_info->csum_size;
313 
314 	/* For data reloc tree, it's better to do a backref lookup instead. */
315 	if (btrfs_is_data_reloc_root(root))
316 		return print_data_reloc_error(inode, logical_start, csum,
317 					      csum_expected, mirror_num);
318 
319 	/* Output without objectid, which is more meaningful */
320 	if (btrfs_root_id(root) >= BTRFS_LAST_FREE_OBJECTID) {
321 		btrfs_warn_rl(root->fs_info,
322 "csum failed root %lld ino %lld off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
323 			btrfs_root_id(root), btrfs_ino(inode),
324 			logical_start,
325 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
326 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
327 			mirror_num);
328 	} else {
329 		btrfs_warn_rl(root->fs_info,
330 "csum failed root %llu ino %llu off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
331 			btrfs_root_id(root), btrfs_ino(inode),
332 			logical_start,
333 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
334 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
335 			mirror_num);
336 	}
337 }
338 
339 /*
340  * Lock inode i_rwsem based on arguments passed.
341  *
342  * ilock_flags can have the following bit set:
343  *
344  * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
345  * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
346  *		     return -EAGAIN
347  * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
348  */
btrfs_inode_lock(struct btrfs_inode * inode,unsigned int ilock_flags)349 int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
350 {
351 	if (ilock_flags & BTRFS_ILOCK_SHARED) {
352 		if (ilock_flags & BTRFS_ILOCK_TRY) {
353 			if (!inode_trylock_shared(&inode->vfs_inode))
354 				return -EAGAIN;
355 			else
356 				return 0;
357 		}
358 		inode_lock_shared(&inode->vfs_inode);
359 	} else {
360 		if (ilock_flags & BTRFS_ILOCK_TRY) {
361 			if (!inode_trylock(&inode->vfs_inode))
362 				return -EAGAIN;
363 			else
364 				return 0;
365 		}
366 		inode_lock(&inode->vfs_inode);
367 	}
368 	if (ilock_flags & BTRFS_ILOCK_MMAP)
369 		down_write(&inode->i_mmap_lock);
370 	return 0;
371 }
372 
373 /*
374  * Unlock inode i_rwsem.
375  *
376  * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
377  * to decide whether the lock acquired is shared or exclusive.
378  */
btrfs_inode_unlock(struct btrfs_inode * inode,unsigned int ilock_flags)379 void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
380 {
381 	if (ilock_flags & BTRFS_ILOCK_MMAP)
382 		up_write(&inode->i_mmap_lock);
383 	if (ilock_flags & BTRFS_ILOCK_SHARED)
384 		inode_unlock_shared(&inode->vfs_inode);
385 	else
386 		inode_unlock(&inode->vfs_inode);
387 }
388 
389 /*
390  * Cleanup all submitted ordered extents in specified range to handle errors
391  * from the btrfs_run_delalloc_range() callback.
392  *
393  * NOTE: caller must ensure that when an error happens, it can not call
394  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
395  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
396  * to be released, which we want to happen only when finishing the ordered
397  * extent (btrfs_finish_ordered_io()).
398  */
btrfs_cleanup_ordered_extents(struct btrfs_inode * inode,u64 offset,u64 bytes)399 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
400 						 u64 offset, u64 bytes)
401 {
402 	return btrfs_mark_ordered_io_finished(inode, offset, bytes, false);
403 }
404 
405 static int btrfs_dirty_inode(struct btrfs_inode *inode);
406 
btrfs_init_inode_security(struct btrfs_trans_handle * trans,struct btrfs_new_inode_args * args)407 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
408 				     struct btrfs_new_inode_args *args)
409 {
410 	int ret;
411 
412 	if (args->default_acl) {
413 		ret = __btrfs_set_acl(trans, args->inode, args->default_acl,
414 				      ACL_TYPE_DEFAULT);
415 		if (ret)
416 			return ret;
417 	}
418 	if (args->acl) {
419 		ret = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
420 		if (ret)
421 			return ret;
422 	}
423 	if (!args->default_acl && !args->acl)
424 		cache_no_acl(args->inode);
425 	return btrfs_xattr_security_init(trans, args->inode, args->dir,
426 					 &args->dentry->d_name);
427 }
428 
429 /*
430  * this does all the hard work for inserting an inline extent into
431  * the btree.  The caller should have done a btrfs_drop_extents so that
432  * no overlapping inline items exist in the btree
433  */
insert_inline_extent(struct btrfs_trans_handle * trans,struct btrfs_path * path,struct btrfs_inode * inode,bool extent_inserted,size_t size,size_t compressed_size,int compress_type,struct folio * compressed_folio,bool update_i_size)434 static int insert_inline_extent(struct btrfs_trans_handle *trans,
435 				struct btrfs_path *path,
436 				struct btrfs_inode *inode, bool extent_inserted,
437 				size_t size, size_t compressed_size,
438 				int compress_type,
439 				struct folio *compressed_folio,
440 				bool update_i_size)
441 {
442 	struct btrfs_root *root = inode->root;
443 	struct extent_buffer *leaf;
444 	const u32 sectorsize = trans->fs_info->sectorsize;
445 	char *kaddr;
446 	unsigned long ptr;
447 	struct btrfs_file_extent_item *ei;
448 	int ret;
449 	size_t cur_size = size;
450 	u64 i_size;
451 
452 	/*
453 	 * The decompressed size must still be no larger than a sector.  Under
454 	 * heavy race, we can have size == 0 passed in, but that shouldn't be a
455 	 * big deal and we can continue the insertion.
456 	 */
457 	ASSERT(size <= sectorsize);
458 
459 	/*
460 	 * The compressed size also needs to be no larger than a page.
461 	 * That's also why we only need one folio as the parameter.
462 	 */
463 	if (compressed_folio) {
464 		ASSERT(compressed_size <= sectorsize);
465 		ASSERT(compressed_size <= PAGE_SIZE);
466 	} else {
467 		ASSERT(compressed_size == 0);
468 	}
469 
470 	if (compressed_size && compressed_folio)
471 		cur_size = compressed_size;
472 
473 	if (!extent_inserted) {
474 		struct btrfs_key key;
475 		size_t datasize;
476 
477 		key.objectid = btrfs_ino(inode);
478 		key.type = BTRFS_EXTENT_DATA_KEY;
479 		key.offset = 0;
480 
481 		datasize = btrfs_file_extent_calc_inline_size(cur_size);
482 		ret = btrfs_insert_empty_item(trans, root, path, &key,
483 					      datasize);
484 		if (ret)
485 			return ret;
486 	}
487 	leaf = path->nodes[0];
488 	ei = btrfs_item_ptr(leaf, path->slots[0],
489 			    struct btrfs_file_extent_item);
490 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
491 	btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
492 	btrfs_set_file_extent_encryption(leaf, ei, 0);
493 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
494 	btrfs_set_file_extent_ram_bytes(leaf, ei, size);
495 	ptr = btrfs_file_extent_inline_start(ei);
496 
497 	if (compress_type != BTRFS_COMPRESS_NONE) {
498 		kaddr = kmap_local_folio(compressed_folio, 0);
499 		write_extent_buffer(leaf, kaddr, ptr, compressed_size);
500 		kunmap_local(kaddr);
501 
502 		btrfs_set_file_extent_compression(leaf, ei,
503 						  compress_type);
504 	} else {
505 		struct folio *folio;
506 
507 		folio = filemap_get_folio(inode->vfs_inode.i_mapping, 0);
508 		ASSERT(!IS_ERR(folio));
509 		btrfs_set_file_extent_compression(leaf, ei, 0);
510 		kaddr = kmap_local_folio(folio, 0);
511 		write_extent_buffer(leaf, kaddr, ptr, size);
512 		kunmap_local(kaddr);
513 		folio_put(folio);
514 	}
515 	btrfs_release_path(path);
516 
517 	/*
518 	 * We align size to sectorsize for inline extents just for simplicity
519 	 * sake.
520 	 */
521 	ret = btrfs_inode_set_file_extent_range(inode, 0,
522 					ALIGN(size, root->fs_info->sectorsize));
523 	if (ret)
524 		return ret;
525 
526 	/*
527 	 * We're an inline extent, so nobody can extend the file past i_size
528 	 * without locking a page we already have locked.
529 	 *
530 	 * We must do any i_size and inode updates before we unlock the pages.
531 	 * Otherwise we could end up racing with unlink.
532 	 */
533 	i_size = i_size_read(&inode->vfs_inode);
534 	if (update_i_size && size > i_size) {
535 		i_size_write(&inode->vfs_inode, size);
536 		i_size = size;
537 	}
538 	inode->disk_i_size = i_size;
539 
540 	return 0;
541 }
542 
can_cow_file_range_inline(struct btrfs_inode * inode,u64 offset,u64 size,size_t compressed_size)543 static bool can_cow_file_range_inline(struct btrfs_inode *inode,
544 				      u64 offset, u64 size,
545 				      size_t compressed_size)
546 {
547 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
548 	u64 data_len = (compressed_size ?: size);
549 
550 	/* Inline extents must start at offset 0. */
551 	if (offset != 0)
552 		return false;
553 
554 	/*
555 	 * Even for bs > ps cases, cow_file_range_inline() can only accept a
556 	 * single folio.
557 	 *
558 	 * This can be problematic and cause access beyond page boundary if a
559 	 * page sized folio is passed into that function.
560 	 * And encoded write is doing exactly that.
561 	 * So here limits the inlined extent size to PAGE_SIZE.
562 	 */
563 	if (size > PAGE_SIZE || compressed_size > PAGE_SIZE)
564 		return false;
565 
566 	/* Inline extents are limited to sectorsize. */
567 	if (size > fs_info->sectorsize)
568 		return false;
569 
570 	/* We do not allow a non-compressed extent to be as large as block size. */
571 	if (data_len >= fs_info->sectorsize)
572 		return false;
573 
574 	/* We cannot exceed the maximum inline data size. */
575 	if (data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
576 		return false;
577 
578 	/* We cannot exceed the user specified max_inline size. */
579 	if (data_len > fs_info->max_inline)
580 		return false;
581 
582 	/* Inline extents must be the entirety of the file. */
583 	if (size < i_size_read(&inode->vfs_inode))
584 		return false;
585 
586 	/* Encrypted file cannot be inlined. */
587 	if (IS_ENCRYPTED(&inode->vfs_inode))
588 		return false;
589 
590 	return true;
591 }
592 
593 /*
594  * conditionally insert an inline extent into the file.  This
595  * does the checks required to make sure the data is small enough
596  * to fit as an inline extent.
597  *
598  * If being used directly, you must have already checked we're allowed to cow
599  * the range by getting true from can_cow_file_range_inline().
600  *
601  * Return 0 if the inlined extent is created successfully.
602  * Return <0 for critical error, and should be considered as an writeback error.
603  * Return >0 if can not create an inlined extent (mostly due to lack of meta space).
604  */
__cow_file_range_inline(struct btrfs_inode * inode,u64 size,size_t compressed_size,int compress_type,struct folio * compressed_folio,bool update_i_size)605 static noinline int __cow_file_range_inline(struct btrfs_inode *inode,
606 					    u64 size, size_t compressed_size,
607 					    int compress_type,
608 					    struct folio *compressed_folio,
609 					    bool update_i_size)
610 {
611 	struct btrfs_drop_extents_args drop_args = { 0 };
612 	struct btrfs_root *root = inode->root;
613 	struct btrfs_fs_info *fs_info = root->fs_info;
614 	struct btrfs_trans_handle *trans = NULL;
615 	u64 data_len = (compressed_size ?: size);
616 	int ret;
617 	struct btrfs_path *path;
618 
619 	path = btrfs_alloc_path();
620 	if (!path) {
621 		ret = -ENOMEM;
622 		goto out;
623 	}
624 
625 	trans = btrfs_join_transaction(root);
626 	if (IS_ERR(trans)) {
627 		ret = PTR_ERR(trans);
628 		trans = NULL;
629 		goto out;
630 	}
631 	trans->block_rsv = &inode->block_rsv;
632 
633 	drop_args.path = path;
634 	drop_args.start = 0;
635 	drop_args.end = fs_info->sectorsize;
636 	drop_args.drop_cache = true;
637 	drop_args.replace_extent = true;
638 	drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
639 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
640 	if (unlikely(ret)) {
641 		btrfs_abort_transaction(trans, ret);
642 		goto out;
643 	}
644 
645 	ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
646 				   size, compressed_size, compress_type,
647 				   compressed_folio, update_i_size);
648 	if (unlikely(ret && ret != -ENOSPC)) {
649 		btrfs_abort_transaction(trans, ret);
650 		goto out;
651 	} else if (ret == -ENOSPC) {
652 		ret = 1;
653 		goto out;
654 	}
655 
656 	btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
657 	ret = btrfs_update_inode(trans, inode);
658 	if (unlikely(ret && ret != -ENOSPC)) {
659 		btrfs_abort_transaction(trans, ret);
660 		goto out;
661 	} else if (ret == -ENOSPC) {
662 		ret = 1;
663 		goto out;
664 	}
665 
666 	btrfs_set_inode_full_sync(inode);
667 out:
668 	/*
669 	 * Don't forget to free the reserved space, as for inlined extent
670 	 * it won't count as data extent, free them directly here.
671 	 * And at reserve time, it's always aligned to sector size, so
672 	 * just free one sector here.
673 	 *
674 	 * If we fallback to non-inline (ret == 1) due to -ENOSPC, then we need
675 	 * to keep the data reservation.
676 	 */
677 	if (ret <= 0)
678 		btrfs_qgroup_free_data(inode, NULL, 0, fs_info->sectorsize, NULL);
679 	btrfs_free_path(path);
680 	if (trans)
681 		btrfs_end_transaction(trans);
682 	return ret;
683 }
684 
685 struct async_extent {
686 	u64 start;
687 	u64 ram_size;
688 	struct compressed_bio *cb;
689 	struct list_head list;
690 };
691 
692 struct async_chunk {
693 	struct btrfs_inode *inode;
694 	struct folio *locked_folio;
695 	u64 start;
696 	u64 end;
697 	blk_opf_t write_flags;
698 	struct list_head extents;
699 	struct cgroup_subsys_state *blkcg_css;
700 	struct btrfs_work work;
701 	struct async_cow *async_cow;
702 };
703 
704 struct async_cow {
705 	atomic_t num_chunks;
706 	struct async_chunk chunks[];
707 };
708 
add_async_extent(struct async_chunk * cow,u64 start,u64 ram_size,struct compressed_bio * cb)709 static int add_async_extent(struct async_chunk *cow, u64 start, u64 ram_size,
710 			    struct compressed_bio *cb)
711 {
712 	struct async_extent *async_extent;
713 
714 	async_extent = kmalloc_obj(*async_extent, GFP_NOFS);
715 	if (!async_extent)
716 		return -ENOMEM;
717 	ASSERT(ram_size < U32_MAX);
718 	async_extent->start = start;
719 	async_extent->ram_size = ram_size;
720 	async_extent->cb = cb;
721 	list_add_tail(&async_extent->list, &cow->extents);
722 	return 0;
723 }
724 
725 /*
726  * Check if the inode needs to be submitted to compression, based on mount
727  * options, defragmentation, properties or heuristics.
728  */
inode_need_compress(struct btrfs_inode * inode,u64 start,u64 end,bool check_inline)729 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
730 				      u64 end, bool check_inline)
731 {
732 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
733 
734 	if (unlikely(!btrfs_inode_can_compress(inode))) {
735 		DEBUG_WARN("BTRFS: unexpected compression for ino %llu", btrfs_ino(inode));
736 		return 0;
737 	}
738 
739 	/*
740 	 * If the delalloc range is only one fs block and can not be inlined,
741 	 * do not even bother try compression, as there will be no space saving
742 	 * and will always fallback to regular write later.
743 	 */
744 	if (end + 1 - start <= fs_info->sectorsize &&
745 	    (!check_inline || (start > 0 || end + 1 < inode->disk_i_size)))
746 		return 0;
747 
748 	/* Defrag ioctl takes precedence over mount options and properties. */
749 	if (inode->defrag_compress == BTRFS_DEFRAG_DONT_COMPRESS)
750 		return 0;
751 	if (BTRFS_COMPRESS_NONE < inode->defrag_compress &&
752 	    inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES)
753 		return 1;
754 	/* force compress */
755 	if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
756 		return 1;
757 	/* bad compression ratios */
758 	if (inode->flags & BTRFS_INODE_NOCOMPRESS)
759 		return 0;
760 	if (btrfs_test_opt(fs_info, COMPRESS) ||
761 	    inode->flags & BTRFS_INODE_COMPRESS ||
762 	    inode->prop_compress)
763 		return btrfs_compress_heuristic(inode, start, end);
764 	return 0;
765 }
766 
inode_should_defrag(struct btrfs_inode * inode,u64 start,u64 end,u64 num_bytes,u32 small_write)767 static inline void inode_should_defrag(struct btrfs_inode *inode,
768 		u64 start, u64 end, u64 num_bytes, u32 small_write)
769 {
770 	/* If this is a small write inside eof, kick off a defrag */
771 	if (num_bytes < small_write &&
772 	    (start > 0 || end + 1 < inode->disk_i_size))
773 		btrfs_add_inode_defrag(inode, small_write);
774 }
775 
extent_range_clear_dirty_for_io(struct btrfs_inode * inode,u64 start,u64 end)776 static int extent_range_clear_dirty_for_io(struct btrfs_inode *inode, u64 start, u64 end)
777 {
778 	pgoff_t index = start >> PAGE_SHIFT;
779 	const pgoff_t end_index = end >> PAGE_SHIFT;
780 	struct folio *folio;
781 	int ret = 0;
782 
783 	while (index <= end_index) {
784 		folio = filemap_get_folio(inode->vfs_inode.i_mapping, index);
785 		if (IS_ERR(folio)) {
786 			if (!ret)
787 				ret = PTR_ERR(folio);
788 			index++;
789 			continue;
790 		}
791 		/*
792 		 * We are about to compress the folio, so it must not be mmap
793 		 * writeable or we could corrupt the data as we attempt to
794 		 * compress it.
795 		 */
796 		btrfs_check_folio_write_protected(folio);
797 		btrfs_folio_clamp_clear_dirty(inode->root->fs_info, folio, start,
798 					      end + 1 - start);
799 		index = folio_next_index(folio);
800 		folio_put(folio);
801 	}
802 	return ret;
803 }
804 
compressed_bio_last_folio(struct compressed_bio * cb)805 static struct folio *compressed_bio_last_folio(struct compressed_bio *cb)
806 {
807 	struct bio *bio = &cb->bbio.bio;
808 	struct bio_vec *bvec;
809 	phys_addr_t paddr;
810 
811 	/*
812 	 * Make sure all folios have the same min_folio_size.
813 	 *
814 	 * Otherwise we cannot simply use offset_in_offset(folio, bi_size) to
815 	 * calculate the end of the last folio.
816 	 */
817 	if (IS_ENABLED(CONFIG_BTRFS_ASSERT)) {
818 		struct btrfs_fs_info *fs_info = cb_to_fs_info(cb);
819 		const u32 min_folio_size = btrfs_min_folio_size(fs_info);
820 		struct folio_iter fi;
821 
822 		bio_for_each_folio_all(fi, bio)
823 			ASSERT(folio_size(fi.folio) == min_folio_size);
824 	}
825 
826 	/* The bio must not be empty. */
827 	ASSERT(bio->bi_vcnt);
828 
829 	bvec = &bio->bi_io_vec[bio->bi_vcnt - 1];
830 	paddr = bvec_phys(bvec) + bvec->bv_len - 1;
831 	return page_folio(phys_to_page(paddr));
832 }
833 
round_up_last_block(struct compressed_bio * cb,u32 blocksize)834 static void round_up_last_block(struct compressed_bio *cb, u32 blocksize)
835 {
836 	struct bio *bio = &cb->bbio.bio;
837 	struct folio *last_folio = compressed_bio_last_folio(cb);
838 	const u32 bio_size = bio->bi_iter.bi_size;
839 	const u32 foffset = offset_in_folio(last_folio, bio_size);
840 	const u32 padding_len = round_up(foffset, blocksize) - foffset;
841 	bool ret;
842 
843 	if (IS_ALIGNED(bio_size, blocksize))
844 		return;
845 
846 	folio_zero_range(last_folio, foffset, padding_len);
847 	ret = bio_add_folio(bio, last_folio, padding_len, foffset);
848 	/* The remaining part should be merged thus never fail. */
849 	ASSERT(ret);
850 }
851 
852 /*
853  * Work queue call back to started compression on a file and pages.
854  *
855  * This is done inside an ordered work queue, and the compression is spread
856  * across many cpus.  The actual IO submission is step two, and the ordered work
857  * queue takes care of making sure that happens in the same order things were
858  * put onto the queue by writepages and friends.
859  *
860  * If this code finds it can't get good compression, it puts an entry onto the
861  * work queue to write the uncompressed bytes.  This makes sure that both
862  * compressed inodes and uncompressed inodes are written in the same order that
863  * the flusher thread sent them down.
864  */
compress_file_range(struct btrfs_work * work)865 static void compress_file_range(struct btrfs_work *work)
866 {
867 	struct async_chunk *async_chunk =
868 		container_of(work, struct async_chunk, work);
869 	struct btrfs_inode *inode = async_chunk->inode;
870 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
871 	struct compressed_bio *cb = NULL;
872 	const u32 blocksize = fs_info->sectorsize;
873 	u64 start = async_chunk->start;
874 	u64 end = async_chunk->end;
875 	u64 actual_end;
876 	u64 i_size;
877 	u32 cur_len;
878 	int ret = 0;
879 	unsigned long total_compressed = 0;
880 	unsigned long total_in = 0;
881 	int compress_type = fs_info->compress_type;
882 	int compress_level = fs_info->compress_level;
883 
884 	if (btrfs_is_shutdown(fs_info))
885 		goto cleanup_and_bail_uncompressed;
886 
887 	inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
888 
889 	ret = extent_range_clear_dirty_for_io(inode, start, end);
890 
891 	/*
892 	 * All the folios should have been locked thus no failure.
893 	 *
894 	 * And even if some folios are missing, btrfs_compress_bio()
895 	 * would handle them correctly, so here just do an ASSERT() check for
896 	 * early logic errors.
897 	 */
898 	ASSERT(ret == 0);
899 
900 	/*
901 	 * We need to save i_size before now because it could change in between
902 	 * us evaluating the size and assigning it.  This is because we lock and
903 	 * unlock the page in truncate and fallocate, and then modify the i_size
904 	 * later on.
905 	 *
906 	 * The barriers are to emulate READ_ONCE, remove that once i_size_read
907 	 * does that for us.
908 	 */
909 	barrier();
910 	i_size = i_size_read(&inode->vfs_inode);
911 	barrier();
912 	actual_end = min_t(u64, i_size, end + 1);
913 again:
914 	total_in = 0;
915 	cur_len = min(end + 1 - start, BTRFS_MAX_UNCOMPRESSED);
916 	ret = 0;
917 	cb = NULL;
918 
919 	/*
920 	 * we don't want to send crud past the end of i_size through
921 	 * compression, that's just a waste of CPU time.  So, if the
922 	 * end of the file is before the start of our current
923 	 * requested range of bytes, we bail out to the uncompressed
924 	 * cleanup code that can deal with all of this.
925 	 *
926 	 * It isn't really the fastest way to fix things, but this is a
927 	 * very uncommon corner.
928 	 */
929 	if (actual_end <= start)
930 		goto cleanup_and_bail_uncompressed;
931 
932 	/*
933 	 * We do compression for mount -o compress and when the inode has not
934 	 * been flagged as NOCOMPRESS.  This flag can change at any time if we
935 	 * discover bad compression ratios.
936 	 */
937 	if (!inode_need_compress(inode, start, end, false))
938 		goto cleanup_and_bail_uncompressed;
939 
940 	if (0 < inode->defrag_compress && inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES) {
941 		compress_type = inode->defrag_compress;
942 		compress_level = inode->defrag_compress_level;
943 	} else if (inode->prop_compress) {
944 		compress_type = inode->prop_compress;
945 	}
946 
947 	/* Compression level is applied here. */
948 	cb = btrfs_compress_bio(inode, start, cur_len, compress_type,
949 				 compress_level, async_chunk->write_flags);
950 	if (IS_ERR(cb)) {
951 		cb = NULL;
952 		goto mark_incompressible;
953 	}
954 
955 	total_compressed = cb->bbio.bio.bi_iter.bi_size;
956 	total_in = cur_len;
957 
958 	/*
959 	 * We aren't doing an inline extent. Round the compressed size up to a
960 	 * block size boundary so the allocator does sane things.
961 	 */
962 	round_up_last_block(cb, blocksize);
963 	total_compressed = cb->bbio.bio.bi_iter.bi_size;
964 	ASSERT(IS_ALIGNED(total_compressed, blocksize));
965 
966 	/*
967 	 * One last check to make sure the compression is really a win, compare
968 	 * the page count read with the blocks on disk, compression must free at
969 	 * least one sector.
970 	 */
971 	total_in = round_up(total_in, fs_info->sectorsize);
972 	if (total_compressed + blocksize > total_in)
973 		goto mark_incompressible;
974 
975 
976 	/*
977 	 * The async work queues will take care of doing actual allocation on
978 	 * disk for these compressed pages, and will submit the bios.
979 	 */
980 	ret = add_async_extent(async_chunk, start, total_in, cb);
981 	BUG_ON(ret);
982 	if (start + total_in < end) {
983 		start += total_in;
984 		cond_resched();
985 		goto again;
986 	}
987 	return;
988 
989 mark_incompressible:
990 	if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) && !inode->prop_compress)
991 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
992 cleanup_and_bail_uncompressed:
993 	ret = add_async_extent(async_chunk, start, end - start + 1, NULL);
994 	BUG_ON(ret);
995 	if (cb)
996 		cleanup_compressed_bio(cb);
997 }
998 
submit_uncompressed_range(struct btrfs_inode * inode,struct async_extent * async_extent,struct folio * locked_folio)999 static void submit_uncompressed_range(struct btrfs_inode *inode,
1000 				      struct async_extent *async_extent,
1001 				      struct folio *locked_folio)
1002 {
1003 	u64 start = async_extent->start;
1004 	u64 end = async_extent->start + async_extent->ram_size - 1;
1005 	int ret;
1006 	struct writeback_control wbc = {
1007 		.sync_mode		= WB_SYNC_ALL,
1008 		.range_start		= start,
1009 		.range_end		= end,
1010 		.no_cgroup_owner	= 1,
1011 	};
1012 
1013 	wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode);
1014 	ret = run_delalloc_cow(inode, locked_folio, start, end,
1015 			       &wbc, false);
1016 	wbc_detach_inode(&wbc);
1017 	if (ret < 0) {
1018 		if (locked_folio)
1019 			btrfs_folio_end_lock(inode->root->fs_info, locked_folio,
1020 					     start, async_extent->ram_size);
1021 		btrfs_err_rl(inode->root->fs_info,
1022 			"%s failed, root=%llu inode=%llu start=%llu len=%llu: %pe",
1023 			     __func__, btrfs_root_id(inode->root),
1024 			     btrfs_ino(inode), start, async_extent->ram_size,
1025 			     ERR_PTR(ret));
1026 	}
1027 }
1028 
submit_one_async_extent(struct async_chunk * async_chunk,struct async_extent * async_extent,u64 * alloc_hint)1029 static void submit_one_async_extent(struct async_chunk *async_chunk,
1030 				    struct async_extent *async_extent,
1031 				    u64 *alloc_hint)
1032 {
1033 	struct btrfs_inode *inode = async_chunk->inode;
1034 	struct extent_io_tree *io_tree = &inode->io_tree;
1035 	struct btrfs_root *root = inode->root;
1036 	struct btrfs_fs_info *fs_info = root->fs_info;
1037 	struct btrfs_ordered_extent *ordered;
1038 	struct btrfs_file_extent file_extent;
1039 	struct btrfs_key ins;
1040 	struct folio *locked_folio = NULL;
1041 	struct extent_state *cached = NULL;
1042 	struct extent_map *em;
1043 	int ret = 0;
1044 	u32 compressed_size;
1045 	u64 start = async_extent->start;
1046 	u64 end = async_extent->start + async_extent->ram_size - 1;
1047 
1048 	if (async_chunk->blkcg_css)
1049 		kthread_associate_blkcg(async_chunk->blkcg_css);
1050 
1051 	/*
1052 	 * If async_chunk->locked_folio is in the async_extent range, we need to
1053 	 * handle it.
1054 	 */
1055 	if (async_chunk->locked_folio) {
1056 		u64 locked_folio_start = folio_pos(async_chunk->locked_folio);
1057 		u64 locked_folio_end = locked_folio_start +
1058 			folio_size(async_chunk->locked_folio) - 1;
1059 
1060 		if (!(start >= locked_folio_end || end <= locked_folio_start))
1061 			locked_folio = async_chunk->locked_folio;
1062 	}
1063 
1064 	if (!async_extent->cb) {
1065 		submit_uncompressed_range(inode, async_extent, locked_folio);
1066 		goto done;
1067 	}
1068 
1069 	compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
1070 	ret = btrfs_reserve_extent(root, async_extent->ram_size,
1071 				   compressed_size, compressed_size,
1072 				   0, *alloc_hint, &ins, true, true);
1073 	if (ret) {
1074 		/*
1075 		 * We can't reserve contiguous space for the compressed size.
1076 		 * Unlikely, but it's possible that we could have enough
1077 		 * non-contiguous space for the uncompressed size instead.  So
1078 		 * fall back to uncompressed.
1079 		 */
1080 		submit_uncompressed_range(inode, async_extent, locked_folio);
1081 		cleanup_compressed_bio(async_extent->cb);
1082 		async_extent->cb = NULL;
1083 		goto done;
1084 	}
1085 
1086 	btrfs_lock_extent(io_tree, start, end, &cached);
1087 
1088 	/* Here we're doing allocation and writeback of the compressed pages */
1089 	file_extent.disk_bytenr = ins.objectid;
1090 	file_extent.disk_num_bytes = ins.offset;
1091 	file_extent.ram_bytes = async_extent->ram_size;
1092 	file_extent.num_bytes = async_extent->ram_size;
1093 	file_extent.offset = 0;
1094 	file_extent.compression = async_extent->cb->compress_type;
1095 
1096 	async_extent->cb->bbio.bio.bi_iter.bi_sector = ins.objectid >> SECTOR_SHIFT;
1097 
1098 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
1099 	if (IS_ERR(em)) {
1100 		ret = PTR_ERR(em);
1101 		goto out_free_reserve;
1102 	}
1103 	btrfs_free_extent_map(em);
1104 
1105 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
1106 					     1U << BTRFS_ORDERED_COMPRESSED);
1107 	if (IS_ERR(ordered)) {
1108 		btrfs_drop_extent_map_range(inode, start, end, false);
1109 		ret = PTR_ERR(ordered);
1110 		goto out_free_reserve;
1111 	}
1112 	async_extent->cb->bbio.ordered = ordered;
1113 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1114 
1115 	/* Clear dirty, set writeback and unlock the pages. */
1116 	extent_clear_unlock_delalloc(inode, start, end,
1117 			NULL, &cached, EXTENT_LOCKED | EXTENT_DELALLOC,
1118 			PAGE_UNLOCK | PAGE_START_WRITEBACK);
1119 	btrfs_submit_bbio(&async_extent->cb->bbio, 0);
1120 	async_extent->cb = NULL;
1121 
1122 	*alloc_hint = ins.objectid + ins.offset;
1123 done:
1124 	if (async_chunk->blkcg_css)
1125 		kthread_associate_blkcg(NULL);
1126 	kfree(async_extent);
1127 	return;
1128 
1129 out_free_reserve:
1130 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1131 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
1132 	mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1133 	extent_clear_unlock_delalloc(inode, start, end,
1134 				     NULL, &cached,
1135 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1136 				     EXTENT_DELALLOC_NEW |
1137 				     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV,
1138 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1139 				     PAGE_END_WRITEBACK);
1140 	if (async_extent->cb)
1141 		cleanup_compressed_bio(async_extent->cb);
1142 	if (async_chunk->blkcg_css)
1143 		kthread_associate_blkcg(NULL);
1144 	btrfs_debug(fs_info,
1145 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1146 		    btrfs_root_id(root), btrfs_ino(inode), start,
1147 		    async_extent->ram_size, ret);
1148 	kfree(async_extent);
1149 }
1150 
btrfs_get_extent_allocation_hint(struct btrfs_inode * inode,u64 start,u64 num_bytes)1151 u64 btrfs_get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1152 				     u64 num_bytes)
1153 {
1154 	struct extent_map_tree *em_tree = &inode->extent_tree;
1155 	struct extent_map *em;
1156 	u64 alloc_hint = 0;
1157 
1158 	read_lock(&em_tree->lock);
1159 	em = btrfs_search_extent_mapping(em_tree, start, num_bytes);
1160 	if (em) {
1161 		/*
1162 		 * if block start isn't an actual block number then find the
1163 		 * first block in this inode and use that as a hint.  If that
1164 		 * block is also bogus then just don't worry about it.
1165 		 */
1166 		if (em->disk_bytenr >= EXTENT_MAP_LAST_BYTE) {
1167 			btrfs_free_extent_map(em);
1168 			em = btrfs_search_extent_mapping(em_tree, 0, 0);
1169 			if (em && em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
1170 				alloc_hint = btrfs_extent_map_block_start(em);
1171 			if (em)
1172 				btrfs_free_extent_map(em);
1173 		} else {
1174 			alloc_hint = btrfs_extent_map_block_start(em);
1175 			btrfs_free_extent_map(em);
1176 		}
1177 	}
1178 	read_unlock(&em_tree->lock);
1179 
1180 	return alloc_hint;
1181 }
1182 
1183 /*
1184  * Handle COW for one range.
1185  *
1186  * @ins:		The key representing the allocated range.
1187  * @file_offset:	The file offset of the COW range
1188  * @num_bytes:		The expected length of the COW range
1189  *			The actually allocated length can be smaller than it.
1190  * @min_alloc_size:	The minimal extent size.
1191  * @alloc_hint:		The hint for the extent allocator.
1192  * @ret_alloc_size:	The COW range handles by this function.
1193  *
1194  * Return 0 if everything is fine and update @ret_alloc_size updated.  The
1195  * range is still locked, and caller should unlock the range after everything
1196  * is done or for error handling.
1197  *
1198  * Return <0 for error and @is updated for where the extra cleanup should
1199  * happen. The range [file_offset, file_offset + ret_alloc_size) will be
1200  * cleaned up by this function.
1201  */
cow_one_range(struct btrfs_inode * inode,struct folio * locked_folio,struct btrfs_key * ins,struct extent_state ** cached,u64 file_offset,u32 num_bytes,u32 min_alloc_size,u64 alloc_hint,u32 * ret_alloc_size)1202 static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
1203 			 struct btrfs_key *ins, struct extent_state **cached,
1204 			 u64 file_offset, u32 num_bytes, u32 min_alloc_size,
1205 			 u64 alloc_hint, u32 *ret_alloc_size)
1206 {
1207 	struct btrfs_root *root = inode->root;
1208 	struct btrfs_fs_info *fs_info = root->fs_info;
1209 	struct btrfs_ordered_extent *ordered;
1210 	struct btrfs_file_extent file_extent;
1211 	struct extent_map *em;
1212 	u32 cur_len = 0;
1213 	u64 cur_end;
1214 	int ret;
1215 
1216 	ret = btrfs_reserve_extent(root, num_bytes, num_bytes, min_alloc_size,
1217 				   0, alloc_hint, ins, true, true);
1218 	if (ret < 0) {
1219 		*ret_alloc_size = cur_len;
1220 		return ret;
1221 	}
1222 
1223 	cur_len = ins->offset;
1224 	cur_end = file_offset + cur_len - 1;
1225 
1226 	file_extent.disk_bytenr = ins->objectid;
1227 	file_extent.disk_num_bytes = ins->offset;
1228 	file_extent.num_bytes = ins->offset;
1229 	file_extent.ram_bytes = ins->offset;
1230 	file_extent.offset = 0;
1231 	file_extent.compression = BTRFS_COMPRESS_NONE;
1232 
1233 	/*
1234 	 * Locked range will be released either during error clean up (inside
1235 	 * this function or by the caller for previously successful ranges) or
1236 	 * after the whole range is finished.
1237 	 */
1238 	btrfs_lock_extent(&inode->io_tree, file_offset, cur_end, cached);
1239 	em = btrfs_create_io_em(inode, file_offset, &file_extent, BTRFS_ORDERED_REGULAR);
1240 	if (IS_ERR(em)) {
1241 		ret = PTR_ERR(em);
1242 		goto free_reserved;
1243 	}
1244 	btrfs_free_extent_map(em);
1245 
1246 	ordered = btrfs_alloc_ordered_extent(inode, file_offset, &file_extent,
1247 					     1U << BTRFS_ORDERED_REGULAR);
1248 	if (IS_ERR(ordered)) {
1249 		btrfs_drop_extent_map_range(inode, file_offset, cur_end, false);
1250 		ret = PTR_ERR(ordered);
1251 		goto free_reserved;
1252 	}
1253 
1254 	if (btrfs_is_data_reloc_root(root)) {
1255 		ret = btrfs_reloc_clone_csums(ordered);
1256 
1257 		/*
1258 		 * Only drop cache here, and process as normal.
1259 		 *
1260 		 * We must not allow extent_clear_unlock_delalloc() at
1261 		 * free_reserved label to free meta of this ordered extent, as
1262 		 * its meta should be freed by btrfs_finish_ordered_io().
1263 		 *
1264 		 * So we must continue until @start is increased to
1265 		 * skip current ordered extent.
1266 		 */
1267 		if (ret)
1268 			btrfs_drop_extent_map_range(inode, file_offset,
1269 						    cur_end, false);
1270 	}
1271 	btrfs_put_ordered_extent(ordered);
1272 	btrfs_dec_block_group_reservations(fs_info, ins->objectid);
1273 	/*
1274 	 * Error handling for btrfs_reloc_clone_csums().
1275 	 *
1276 	 * Treat the range as finished, thus only clear EXTENT_LOCKED | EXTENT_DELALLOC.
1277 	 * The accounting will be done by ordered extents.
1278 	 */
1279 	if (unlikely(ret < 0)) {
1280 		btrfs_cleanup_ordered_extents(inode, file_offset, cur_len);
1281 		extent_clear_unlock_delalloc(inode, file_offset, cur_end, locked_folio, cached,
1282 					     EXTENT_LOCKED | EXTENT_DELALLOC,
1283 					     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1284 					     PAGE_END_WRITEBACK);
1285 		mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1286 	}
1287 	*ret_alloc_size = cur_len;
1288 	return ret;
1289 
1290 free_reserved:
1291 	/*
1292 	 * If we have reserved an extent for the current range and failed to
1293 	 * create the respective extent map or ordered extent, it means that
1294 	 * when we reserved the extent we decremented the extent's size from
1295 	 * the data space_info's bytes_may_use counter and
1296 	 * incremented the space_info's bytes_reserved counter by the same
1297 	 * amount.
1298 	 *
1299 	 * We must make sure extent_clear_unlock_delalloc() does not try
1300 	 * to decrement again the data space_info's bytes_may_use counter, which
1301 	 * will be handled by btrfs_free_reserved_extent().
1302 	 *
1303 	 * Therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV, but only
1304 	 * EXTENT_CLEAR_META_RESV.
1305 	 */
1306 	extent_clear_unlock_delalloc(inode, file_offset, cur_end, locked_folio, cached,
1307 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1308 				     EXTENT_DELALLOC_NEW |
1309 				     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV,
1310 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1311 				     PAGE_END_WRITEBACK);
1312 	btrfs_qgroup_free_data(inode, NULL, file_offset, cur_len, NULL);
1313 	btrfs_dec_block_group_reservations(fs_info, ins->objectid);
1314 	btrfs_free_reserved_extent(fs_info, ins->objectid, ins->offset, true);
1315 	mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1316 	*ret_alloc_size = cur_len;
1317 	/*
1318 	 * We should not return -EAGAIN where it's a special return code for
1319 	 * zoned to catch btrfs_reserved_extent().
1320 	 */
1321 	ASSERT(ret != -EAGAIN);
1322 	return ret;
1323 }
1324 
1325 /*
1326  * when extent_io.c finds a delayed allocation range in the file,
1327  * the call backs end up in this code.  The basic idea is to
1328  * allocate extents on disk for the range, and create ordered data structs
1329  * in ram to track those extents.
1330  *
1331  * locked_folio is the folio that writepage had locked already.  We use
1332  * it to make sure we don't do extra locks or unlocks.
1333  *
1334  * When this function fails, it unlocks all folios except @locked_folio.
1335  *
1336  * When this function succeed and creates a normal extent, the folio locking
1337  * status depends on the passed in flags:
1338  *
1339  * - If COW_FILE_RANGE_KEEP_LOCKED flag is set, all folios are kept locked.
1340  * - Else all folios except for @locked_folio are unlocked.
1341  *
1342  * When a failure happens in the second or later iteration of the
1343  * while-loop, the ordered extents created in previous iterations are cleaned up.
1344  */
cow_file_range(struct btrfs_inode * inode,struct folio * locked_folio,u64 start,u64 end,u64 * done_offset,unsigned long flags)1345 static noinline int cow_file_range(struct btrfs_inode *inode,
1346 				   struct folio *locked_folio, u64 start,
1347 				   u64 end, u64 *done_offset,
1348 				   unsigned long flags)
1349 {
1350 	struct btrfs_root *root = inode->root;
1351 	struct btrfs_fs_info *fs_info = root->fs_info;
1352 	struct extent_state *cached = NULL;
1353 	u64 alloc_hint = 0;
1354 	u64 orig_start = start;
1355 	u64 num_bytes;
1356 	u32 min_alloc_size;
1357 	u32 blocksize = fs_info->sectorsize;
1358 	u32 cur_alloc_size = 0;
1359 	struct btrfs_key ins;
1360 	unsigned clear_bits;
1361 	unsigned long page_ops;
1362 	int ret = 0;
1363 
1364 	if (btrfs_is_shutdown(fs_info)) {
1365 		ret = -EIO;
1366 		goto out_unlock;
1367 	}
1368 
1369 	if (btrfs_is_free_space_inode(inode)) {
1370 		ret = -EINVAL;
1371 		goto out_unlock;
1372 	}
1373 
1374 	num_bytes = ALIGN(end - start + 1, blocksize);
1375 	num_bytes = max(blocksize,  num_bytes);
1376 	ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1377 
1378 	inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1379 	alloc_hint = btrfs_get_extent_allocation_hint(inode, start, num_bytes);
1380 
1381 	/*
1382 	 * We're not doing compressed IO, don't unlock the first page (which
1383 	 * the caller expects to stay locked), don't clear any dirty bits and
1384 	 * don't set any writeback bits.
1385 	 *
1386 	 * Do set the Ordered (Private2) bit so we know this page was properly
1387 	 * setup for writepage.
1388 	 */
1389 	page_ops = ((flags & COW_FILE_RANGE_KEEP_LOCKED) ? 0 : PAGE_UNLOCK);
1390 
1391 	/*
1392 	 * Relocation relies on the relocated extents to have exactly the same
1393 	 * size as the original extents. Normally writeback for relocation data
1394 	 * extents follows a NOCOW path because relocation preallocates the
1395 	 * extents. However, due to an operation such as scrub turning a block
1396 	 * group to RO mode, it may fallback to COW mode, so we must make sure
1397 	 * an extent allocated during COW has exactly the requested size and can
1398 	 * not be split into smaller extents, otherwise relocation breaks and
1399 	 * fails during the stage where it updates the bytenr of file extent
1400 	 * items.
1401 	 */
1402 	if (btrfs_is_data_reloc_root(root))
1403 		min_alloc_size = num_bytes;
1404 	else
1405 		min_alloc_size = fs_info->sectorsize;
1406 
1407 	while (num_bytes > 0) {
1408 		ret = cow_one_range(inode, locked_folio, &ins, &cached, start,
1409 				    num_bytes, min_alloc_size, alloc_hint, &cur_alloc_size);
1410 
1411 		if (ret == -EAGAIN) {
1412 			/*
1413 			 * cow_one_range() only returns -EAGAIN for zoned
1414 			 * file systems (from btrfs_reserve_extent()), which
1415 			 * is an indication that there are
1416 			 * no active zones to allocate from at the moment.
1417 			 *
1418 			 * If this is the first loop iteration, wait for at
1419 			 * least one zone to finish before retrying the
1420 			 * allocation.  Otherwise ask the caller to write out
1421 			 * the already allocated blocks before coming back to
1422 			 * us, or return -ENOSPC if it can't handle retries.
1423 			 */
1424 			ASSERT(btrfs_is_zoned(fs_info));
1425 			if (start == orig_start) {
1426 				wait_on_bit_io(&inode->root->fs_info->flags,
1427 					       BTRFS_FS_NEED_ZONE_FINISH,
1428 					       TASK_UNINTERRUPTIBLE);
1429 				continue;
1430 			}
1431 			if (done_offset) {
1432 				/*
1433 				 * Move @end to the end of the processed range,
1434 				 * and exit the loop to unlock the processed extents.
1435 				 */
1436 				end = start - 1;
1437 				ret = 0;
1438 				break;
1439 			}
1440 			ret = -ENOSPC;
1441 		}
1442 		if (ret < 0)
1443 			goto out_unlock;
1444 
1445 		/* We should not allocate an extent larger than requested.*/
1446 		ASSERT(cur_alloc_size <= num_bytes);
1447 
1448 		num_bytes -= cur_alloc_size;
1449 		alloc_hint = ins.objectid + ins.offset;
1450 		start += cur_alloc_size;
1451 		cur_alloc_size = 0;
1452 	}
1453 	extent_clear_unlock_delalloc(inode, orig_start, end, locked_folio, &cached,
1454 				     EXTENT_LOCKED | EXTENT_DELALLOC, page_ops);
1455 	if (done_offset)
1456 		*done_offset = end;
1457 	return ret;
1458 
1459 out_unlock:
1460 	/*
1461 	 * Now, we have three regions to clean up:
1462 	 *
1463 	 * |-------(1)----|---(2)---|-------------(3)----------|
1464 	 * `- orig_start  `- start  `- start + cur_alloc_size  `- end
1465 	 *
1466 	 * We process each region below.
1467 	 */
1468 
1469 	/*
1470 	 * For the range (1). We have already instantiated the ordered extents
1471 	 * for this region, thus we need to cleanup those ordered extents.
1472 	 * EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV
1473 	 * are also handled by the ordered extents cleanup.
1474 	 *
1475 	 * So here we only clear EXTENT_LOCKED and EXTENT_DELALLOC flag, and
1476 	 * finish the writeback of the involved folios, which will be never submitted.
1477 	 */
1478 	if (orig_start < start) {
1479 		clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC;
1480 		page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1481 
1482 		if (!locked_folio)
1483 			mapping_set_error(inode->vfs_inode.i_mapping, ret);
1484 
1485 		btrfs_cleanup_ordered_extents(inode, orig_start, start - orig_start);
1486 		extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1487 					     locked_folio, NULL, clear_bits, page_ops);
1488 	}
1489 
1490 	clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1491 		     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1492 	page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1493 
1494 	/*
1495 	 * For the range (2) the error handling is done by cow_one_range() itself.
1496 	 * Nothing needs to be done.
1497 	 *
1498 	 * For the range (3). We never touched the region. In addition to the
1499 	 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1500 	 * space_info's bytes_may_use counter, reserved in
1501 	 * btrfs_check_data_free_space().
1502 	 */
1503 	if (start + cur_alloc_size < end) {
1504 		clear_bits |= EXTENT_CLEAR_DATA_RESV;
1505 		extent_clear_unlock_delalloc(inode, start + cur_alloc_size,
1506 					     end, locked_folio,
1507 					     &cached, clear_bits, page_ops);
1508 		btrfs_qgroup_free_data(inode, NULL, start + cur_alloc_size,
1509 				       end - start - cur_alloc_size + 1, NULL);
1510 	}
1511 	btrfs_err(fs_info,
1512 "%s failed, root=%llu inode=%llu start=%llu len=%llu cur_offset=%llu cur_alloc_size=%u: %pe",
1513 		  __func__, btrfs_root_id(inode->root),
1514 		  btrfs_ino(inode), orig_start, end + 1 - orig_start,
1515 		  start, cur_alloc_size, ERR_PTR(ret));
1516 	return ret;
1517 }
1518 
1519 /*
1520  * Phase two of compressed writeback.  This is the ordered portion of the code,
1521  * which only gets called in the order the work was queued.  We walk all the
1522  * async extents created by compress_file_range and send them down to the disk.
1523  *
1524  * If called with @do_free == true then it'll try to finish the work and free
1525  * the work struct eventually.
1526  */
submit_compressed_extents(struct btrfs_work * work,bool do_free)1527 static noinline void submit_compressed_extents(struct btrfs_work *work, bool do_free)
1528 {
1529 	struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1530 						     work);
1531 	struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1532 	struct async_extent *async_extent;
1533 	unsigned long nr_pages;
1534 	u64 alloc_hint = 0;
1535 
1536 	if (do_free) {
1537 		struct async_cow *async_cow;
1538 
1539 		btrfs_add_delayed_iput(async_chunk->inode);
1540 		if (async_chunk->blkcg_css)
1541 			css_put(async_chunk->blkcg_css);
1542 
1543 		async_cow = async_chunk->async_cow;
1544 		if (atomic_dec_and_test(&async_cow->num_chunks))
1545 			kvfree(async_cow);
1546 		return;
1547 	}
1548 
1549 	nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1550 		PAGE_SHIFT;
1551 
1552 	while (!list_empty(&async_chunk->extents)) {
1553 		async_extent = list_first_entry(&async_chunk->extents,
1554 						struct async_extent, list);
1555 		list_del(&async_extent->list);
1556 		submit_one_async_extent(async_chunk, async_extent, &alloc_hint);
1557 	}
1558 
1559 	/* atomic_sub_return implies a barrier */
1560 	if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1561 	    5 * SZ_1M)
1562 		cond_wake_up_nomb(&fs_info->async_submit_wait);
1563 }
1564 
run_delalloc_compressed(struct btrfs_inode * inode,struct folio * locked_folio,u64 start,u64 end,struct writeback_control * wbc)1565 static bool run_delalloc_compressed(struct btrfs_inode *inode,
1566 				    struct folio *locked_folio, u64 start,
1567 				    u64 end, struct writeback_control *wbc)
1568 {
1569 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1570 	struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1571 	struct async_cow *ctx;
1572 	struct async_chunk *async_chunk;
1573 	unsigned long nr_pages;
1574 	u64 num_chunks = DIV_ROUND_UP(end - start, BTRFS_COMPRESSION_CHUNK_SIZE);
1575 	int i;
1576 	unsigned nofs_flag;
1577 	const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1578 
1579 	nofs_flag = memalloc_nofs_save();
1580 	ctx = kvmalloc_flex(*ctx, chunks, num_chunks);
1581 	memalloc_nofs_restore(nofs_flag);
1582 	if (!ctx)
1583 		return false;
1584 
1585 	set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1586 
1587 	async_chunk = ctx->chunks;
1588 	atomic_set(&ctx->num_chunks, num_chunks);
1589 
1590 	for (i = 0; i < num_chunks; i++) {
1591 		u64 cur_end = min(end, start + BTRFS_COMPRESSION_CHUNK_SIZE - 1);
1592 
1593 		/*
1594 		 * igrab is called higher up in the call chain, take only the
1595 		 * lightweight reference for the callback lifetime
1596 		 */
1597 		ihold(&inode->vfs_inode);
1598 		async_chunk[i].async_cow = ctx;
1599 		async_chunk[i].inode = inode;
1600 		async_chunk[i].start = start;
1601 		async_chunk[i].end = cur_end;
1602 		async_chunk[i].write_flags = write_flags;
1603 		INIT_LIST_HEAD(&async_chunk[i].extents);
1604 
1605 		/*
1606 		 * The locked_folio comes all the way from writepage and its
1607 		 * the original folio we were actually given.  As we spread
1608 		 * this large delalloc region across multiple async_chunk
1609 		 * structs, only the first struct needs a pointer to
1610 		 * locked_folio.
1611 		 *
1612 		 * This way we don't need racey decisions about who is supposed
1613 		 * to unlock it.
1614 		 */
1615 		if (locked_folio) {
1616 			/*
1617 			 * Depending on the compressibility, the pages might or
1618 			 * might not go through async.  We want all of them to
1619 			 * be accounted against wbc once.  Let's do it here
1620 			 * before the paths diverge.  wbc accounting is used
1621 			 * only for foreign writeback detection and doesn't
1622 			 * need full accuracy.  Just account the whole thing
1623 			 * against the first page.
1624 			 */
1625 			wbc_account_cgroup_owner(wbc, locked_folio,
1626 						 cur_end - start);
1627 			async_chunk[i].locked_folio = locked_folio;
1628 			locked_folio = NULL;
1629 		} else {
1630 			async_chunk[i].locked_folio = NULL;
1631 		}
1632 
1633 		if (blkcg_css != blkcg_root_css) {
1634 			css_get(blkcg_css);
1635 			async_chunk[i].blkcg_css = blkcg_css;
1636 			async_chunk[i].write_flags |= REQ_BTRFS_CGROUP_PUNT;
1637 		} else {
1638 			async_chunk[i].blkcg_css = NULL;
1639 		}
1640 
1641 		btrfs_init_work(&async_chunk[i].work, compress_file_range,
1642 				submit_compressed_extents);
1643 
1644 		nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1645 		atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1646 
1647 		btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1648 
1649 		start = cur_end + 1;
1650 	}
1651 	return true;
1652 }
1653 
1654 /*
1655  * Run the delalloc range from start to end, and write back any dirty pages
1656  * covered by the range.
1657  */
run_delalloc_cow(struct btrfs_inode * inode,struct folio * locked_folio,u64 start,u64 end,struct writeback_control * wbc,bool pages_dirty)1658 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
1659 				     struct folio *locked_folio, u64 start,
1660 				     u64 end, struct writeback_control *wbc,
1661 				     bool pages_dirty)
1662 {
1663 	u64 done_offset = end;
1664 	int ret;
1665 
1666 	while (start <= end) {
1667 		ret = cow_file_range(inode, locked_folio, start, end,
1668 				     &done_offset, COW_FILE_RANGE_KEEP_LOCKED);
1669 		if (ret)
1670 			return ret;
1671 		extent_write_locked_range(&inode->vfs_inode, locked_folio,
1672 					  start, done_offset, wbc, pages_dirty);
1673 		start = done_offset + 1;
1674 	}
1675 
1676 	return 1;
1677 }
1678 
fallback_to_cow(struct btrfs_inode * inode,struct folio * locked_folio,const u64 start,const u64 end)1679 static int fallback_to_cow(struct btrfs_inode *inode,
1680 			   struct folio *locked_folio, const u64 start,
1681 			   const u64 end)
1682 {
1683 	const bool is_space_ino = btrfs_is_free_space_inode(inode);
1684 	const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1685 	const u64 range_bytes = end + 1 - start;
1686 	struct extent_io_tree *io_tree = &inode->io_tree;
1687 	struct extent_state *cached_state = NULL;
1688 	u64 range_start = start;
1689 	u64 count;
1690 	int ret;
1691 
1692 	/*
1693 	 * If EXTENT_NORESERVE is set it means that when the buffered write was
1694 	 * made we had not enough available data space and therefore we did not
1695 	 * reserve data space for it, since we though we could do NOCOW for the
1696 	 * respective file range (either there is prealloc extent or the inode
1697 	 * has the NOCOW bit set).
1698 	 *
1699 	 * However when we need to fallback to COW mode (because for example the
1700 	 * block group for the corresponding extent was turned to RO mode by a
1701 	 * scrub or relocation) we need to do the following:
1702 	 *
1703 	 * 1) We increment the bytes_may_use counter of the data space info.
1704 	 *    If COW succeeds, it allocates a new data extent and after doing
1705 	 *    that it decrements the space info's bytes_may_use counter and
1706 	 *    increments its bytes_reserved counter by the same amount (we do
1707 	 *    this at btrfs_add_reserved_bytes()). So we need to increment the
1708 	 *    bytes_may_use counter to compensate (when space is reserved at
1709 	 *    buffered write time, the bytes_may_use counter is incremented);
1710 	 *
1711 	 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1712 	 *    that if the COW path fails for any reason, it decrements (through
1713 	 *    extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1714 	 *    data space info, which we incremented in the step above.
1715 	 *
1716 	 * If we need to fallback to cow and the inode corresponds to a free
1717 	 * space cache inode or an inode of the data relocation tree, we must
1718 	 * also increment bytes_may_use of the data space_info for the same
1719 	 * reason. Space caches and relocated data extents always get a prealloc
1720 	 * extent for them, however scrub or balance may have set the block
1721 	 * group that contains that extent to RO mode and therefore force COW
1722 	 * when starting writeback.
1723 	 */
1724 	btrfs_lock_extent(io_tree, start, end, &cached_state);
1725 	count = btrfs_count_range_bits(io_tree, &range_start, end, range_bytes,
1726 				       EXTENT_NORESERVE, false, NULL);
1727 	if (count > 0 || is_space_ino || is_reloc_ino) {
1728 		u64 bytes = count;
1729 		struct btrfs_fs_info *fs_info = inode->root->fs_info;
1730 		struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1731 
1732 		if (is_space_ino || is_reloc_ino)
1733 			bytes = range_bytes;
1734 
1735 		spin_lock(&sinfo->lock);
1736 		btrfs_space_info_update_bytes_may_use(sinfo, bytes);
1737 		spin_unlock(&sinfo->lock);
1738 
1739 		if (count > 0)
1740 			btrfs_clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1741 					       &cached_state);
1742 	}
1743 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
1744 
1745 	/*
1746 	 * Don't try to create inline extents, as a mix of inline extent that
1747 	 * is written out and unlocked directly and a normal NOCOW extent
1748 	 * doesn't work.
1749 	 *
1750 	 * And here we do not unlock the folio after a successful run.
1751 	 * The folios will be unlocked after everything is finished, or by error handling.
1752 	 *
1753 	 * This is to ensure error handling won't need to clear dirty/ordered flags without
1754 	 * a locked folio, which can race with writeback.
1755 	 */
1756 	ret = cow_file_range(inode, locked_folio, start, end, NULL,
1757 			     COW_FILE_RANGE_KEEP_LOCKED);
1758 	ASSERT(ret != 1);
1759 	return ret;
1760 }
1761 
1762 struct can_nocow_file_extent_args {
1763 	/* Input fields. */
1764 
1765 	/* Start file offset of the range we want to NOCOW. */
1766 	u64 start;
1767 	/* End file offset (inclusive) of the range we want to NOCOW. */
1768 	u64 end;
1769 	bool writeback_path;
1770 	/*
1771 	 * Free the path passed to can_nocow_file_extent() once it's not needed
1772 	 * anymore.
1773 	 */
1774 	bool free_path;
1775 
1776 	/*
1777 	 * Output fields. Only set when can_nocow_file_extent() returns 1.
1778 	 * The expected file extent for the NOCOW write.
1779 	 */
1780 	struct btrfs_file_extent file_extent;
1781 };
1782 
1783 /*
1784  * Check if we can NOCOW the file extent that the path points to.
1785  * This function may return with the path released, so the caller should check
1786  * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1787  *
1788  * Returns: < 0 on error
1789  *            0 if we can not NOCOW
1790  *            1 if we can NOCOW
1791  */
can_nocow_file_extent(struct btrfs_path * path,struct btrfs_key * key,struct btrfs_inode * inode,struct can_nocow_file_extent_args * args)1792 static int can_nocow_file_extent(struct btrfs_path *path,
1793 				 struct btrfs_key *key,
1794 				 struct btrfs_inode *inode,
1795 				 struct can_nocow_file_extent_args *args)
1796 {
1797 	const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1798 	struct extent_buffer *leaf = path->nodes[0];
1799 	struct btrfs_root *root = inode->root;
1800 	struct btrfs_file_extent_item *fi;
1801 	struct btrfs_root *csum_root;
1802 	u64 io_start;
1803 	u64 extent_end;
1804 	u8 extent_type;
1805 	int can_nocow = 0;
1806 	int ret = 0;
1807 	bool nowait = path->nowait;
1808 
1809 	/* If there are pending snapshots for this root, we must do COW. */
1810 	if (args->writeback_path && !is_freespace_inode &&
1811 	    atomic_read(&root->snapshot_force_cow))
1812 		goto out;
1813 
1814 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1815 	extent_type = btrfs_file_extent_type(leaf, fi);
1816 
1817 	if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1818 		goto out;
1819 
1820 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1821 	    extent_type == BTRFS_FILE_EXTENT_REG)
1822 		goto out;
1823 
1824 	/*
1825 	 * If the extent was created before the generation where the last snapshot
1826 	 * for its subvolume was created, then this implies the extent is shared,
1827 	 * hence we must COW.
1828 	 */
1829 	if (btrfs_file_extent_generation(leaf, fi) <=
1830 	    btrfs_root_last_snapshot(&root->root_item))
1831 		goto out;
1832 
1833 	/* An explicit hole, must COW. */
1834 	if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
1835 		goto out;
1836 
1837 	/* Compressed/encrypted/encoded extents must be COWed. */
1838 	if (btrfs_file_extent_compression(leaf, fi) ||
1839 	    btrfs_file_extent_encryption(leaf, fi) ||
1840 	    btrfs_file_extent_other_encoding(leaf, fi))
1841 		goto out;
1842 
1843 	extent_end = btrfs_file_extent_end(path);
1844 
1845 	args->file_extent.disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1846 	args->file_extent.disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1847 	args->file_extent.ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1848 	args->file_extent.offset = btrfs_file_extent_offset(leaf, fi);
1849 	args->file_extent.compression = btrfs_file_extent_compression(leaf, fi);
1850 
1851 	/*
1852 	 * The following checks can be expensive, as they need to take other
1853 	 * locks and do btree or rbtree searches, so release the path to avoid
1854 	 * blocking other tasks for too long.
1855 	 */
1856 	btrfs_release_path(path);
1857 
1858 	ret = btrfs_cross_ref_exist(inode, key->offset - args->file_extent.offset,
1859 				    args->file_extent.disk_bytenr, path);
1860 	WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1861 	if (ret != 0)
1862 		goto out;
1863 
1864 	if (args->free_path) {
1865 		/*
1866 		 * We don't need the path anymore, plus through the
1867 		 * btrfs_lookup_csums_list() call below we will end up allocating
1868 		 * another path. So free the path to avoid unnecessary extra
1869 		 * memory usage.
1870 		 */
1871 		btrfs_free_path(path);
1872 		path = NULL;
1873 	}
1874 
1875 	args->file_extent.num_bytes = min(args->end + 1, extent_end) - args->start;
1876 	args->file_extent.offset += args->start - key->offset;
1877 	io_start = args->file_extent.disk_bytenr + args->file_extent.offset;
1878 
1879 	/*
1880 	 * Force COW if csums exist in the range. This ensures that csums for a
1881 	 * given extent are either valid or do not exist.
1882 	 */
1883 
1884 	csum_root = btrfs_csum_root(root->fs_info, io_start);
1885 	if (unlikely(!csum_root)) {
1886 		btrfs_err(root->fs_info,
1887 			  "missing csum root for extent at bytenr %llu", io_start);
1888 		ret = -EUCLEAN;
1889 		goto out;
1890 	}
1891 
1892 	ret = btrfs_lookup_csums_list(csum_root, io_start,
1893 				      io_start + args->file_extent.num_bytes - 1,
1894 				      NULL, nowait);
1895 	WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1896 	if (ret != 0)
1897 		goto out;
1898 
1899 	can_nocow = 1;
1900  out:
1901 	if (args->free_path && path)
1902 		btrfs_free_path(path);
1903 
1904 	return ret < 0 ? ret : can_nocow;
1905 }
1906 
nocow_one_range(struct btrfs_inode * inode,struct folio * locked_folio,struct extent_state ** cached,struct can_nocow_file_extent_args * nocow_args,u64 file_pos,bool is_prealloc)1907 static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
1908 			   struct extent_state **cached,
1909 			   struct can_nocow_file_extent_args *nocow_args,
1910 			   u64 file_pos, bool is_prealloc)
1911 {
1912 	struct btrfs_ordered_extent *ordered;
1913 	const u64 len = nocow_args->file_extent.num_bytes;
1914 	const u64 end = file_pos + len - 1;
1915 	int ret = 0;
1916 
1917 	btrfs_lock_extent(&inode->io_tree, file_pos, end, cached);
1918 
1919 	if (is_prealloc) {
1920 		struct extent_map *em;
1921 
1922 		em = btrfs_create_io_em(inode, file_pos, &nocow_args->file_extent,
1923 					BTRFS_ORDERED_PREALLOC);
1924 		if (IS_ERR(em)) {
1925 			ret = PTR_ERR(em);
1926 			goto error;
1927 		}
1928 		btrfs_free_extent_map(em);
1929 	}
1930 
1931 	ordered = btrfs_alloc_ordered_extent(inode, file_pos, &nocow_args->file_extent,
1932 					     is_prealloc
1933 					     ? (1U << BTRFS_ORDERED_PREALLOC)
1934 					     : (1U << BTRFS_ORDERED_NOCOW));
1935 	if (IS_ERR(ordered)) {
1936 		if (is_prealloc)
1937 			btrfs_drop_extent_map_range(inode, file_pos, end, false);
1938 		ret = PTR_ERR(ordered);
1939 		goto error;
1940 	}
1941 
1942 	if (btrfs_is_data_reloc_root(inode->root))
1943 		/*
1944 		 * Errors are handled later, as we must prevent
1945 		 * extent_clear_unlock_delalloc() in error handler from freeing
1946 		 * metadata of the created ordered extent.
1947 		 */
1948 		ret = btrfs_reloc_clone_csums(ordered);
1949 	btrfs_put_ordered_extent(ordered);
1950 
1951 	if (ret < 0)
1952 		goto error;
1953 	extent_clear_unlock_delalloc(inode, file_pos, end, locked_folio, cached,
1954 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1955 				     EXTENT_CLEAR_DATA_RESV, 0);
1956 	return ret;
1957 
1958 error:
1959 	btrfs_cleanup_ordered_extents(inode, file_pos, len);
1960 	extent_clear_unlock_delalloc(inode, file_pos, end, locked_folio, cached,
1961 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1962 				     EXTENT_CLEAR_DATA_RESV,
1963 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1964 				     PAGE_END_WRITEBACK);
1965 	btrfs_err(inode->root->fs_info,
1966 		  "%s failed, root=%lld inode=%llu start=%llu len=%llu: %pe",
1967 		  __func__, btrfs_root_id(inode->root), btrfs_ino(inode),
1968 		  file_pos, len, ERR_PTR(ret));
1969 	return ret;
1970 }
1971 
1972 /*
1973  * When nocow writeback calls back.  This checks for snapshots or COW copies
1974  * of the extents that exist in the file, and COWs the file as required.
1975  *
1976  * If no cow copies or snapshots exist, we write directly to the existing
1977  * blocks on disk
1978  */
run_delalloc_nocow(struct btrfs_inode * inode,struct folio * locked_folio,const u64 start,const u64 end)1979 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1980 				       struct folio *locked_folio,
1981 				       const u64 start, const u64 end)
1982 {
1983 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1984 	struct btrfs_root *root = inode->root;
1985 	struct btrfs_path *path = NULL;
1986 	u64 cow_start = (u64)-1;
1987 	/*
1988 	 * If not 0, represents the inclusive end of the last fallback_to_cow()
1989 	 * range. Only for error handling.
1990 	 *
1991 	 * The same for nocow_end, it's to avoid double cleaning up the range
1992 	 * already cleaned by nocow_one_range().
1993 	 */
1994 	u64 cow_end = 0;
1995 	u64 nocow_end = 0;
1996 	u64 cur_offset = start;
1997 	int ret;
1998 	bool check_prev = true;
1999 	u64 ino = btrfs_ino(inode);
2000 	struct can_nocow_file_extent_args nocow_args = { 0 };
2001 	/* The range that has ordered extent(s). */
2002 	u64 oe_cleanup_start;
2003 	u64 oe_cleanup_len = 0;
2004 	/* The range that is untouched. */
2005 	u64 untouched_start;
2006 	u64 untouched_len = 0;
2007 
2008 	/*
2009 	 * Normally on a zoned device we're only doing COW writes, but in case
2010 	 * of relocation on a zoned filesystem serializes I/O so that we're only
2011 	 * writing sequentially and can end up here as well.
2012 	 */
2013 	ASSERT(!btrfs_is_zoned(fs_info) || btrfs_is_data_reloc_root(root));
2014 
2015 	if (btrfs_is_shutdown(fs_info)) {
2016 		ret = -EIO;
2017 		goto error;
2018 	}
2019 	path = btrfs_alloc_path();
2020 	if (!path) {
2021 		ret = -ENOMEM;
2022 		goto error;
2023 	}
2024 
2025 	nocow_args.end = end;
2026 	nocow_args.writeback_path = true;
2027 
2028 	while (cur_offset <= end) {
2029 		struct btrfs_block_group *nocow_bg = NULL;
2030 		struct btrfs_key found_key;
2031 		struct btrfs_file_extent_item *fi;
2032 		struct extent_buffer *leaf;
2033 		struct extent_state *cached_state = NULL;
2034 		u64 extent_end;
2035 		int extent_type;
2036 
2037 		ret = btrfs_lookup_file_extent(NULL, root, path, ino,
2038 					       cur_offset, 0);
2039 		if (ret < 0)
2040 			goto error;
2041 
2042 		/*
2043 		 * If there is no extent for our range when doing the initial
2044 		 * search, then go back to the previous slot as it will be the
2045 		 * one containing the search offset
2046 		 */
2047 		if (ret > 0 && path->slots[0] > 0 && check_prev) {
2048 			leaf = path->nodes[0];
2049 			btrfs_item_key_to_cpu(leaf, &found_key,
2050 					      path->slots[0] - 1);
2051 			if (found_key.objectid == ino &&
2052 			    found_key.type == BTRFS_EXTENT_DATA_KEY)
2053 				path->slots[0]--;
2054 		}
2055 		check_prev = false;
2056 next_slot:
2057 		/* Go to next leaf if we have exhausted the current one */
2058 		leaf = path->nodes[0];
2059 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2060 			ret = btrfs_next_leaf(root, path);
2061 			if (ret < 0)
2062 				goto error;
2063 			if (ret > 0)
2064 				break;
2065 			leaf = path->nodes[0];
2066 		}
2067 
2068 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2069 
2070 		/* Didn't find anything for our INO */
2071 		if (found_key.objectid > ino)
2072 			break;
2073 		/*
2074 		 * Keep searching until we find an EXTENT_ITEM or there are no
2075 		 * more extents for this inode
2076 		 */
2077 		if (WARN_ON_ONCE(found_key.objectid < ino) ||
2078 		    found_key.type < BTRFS_EXTENT_DATA_KEY) {
2079 			path->slots[0]++;
2080 			goto next_slot;
2081 		}
2082 
2083 		/* Found key is not EXTENT_DATA_KEY or starts after req range */
2084 		if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2085 		    found_key.offset > end)
2086 			break;
2087 
2088 		/*
2089 		 * If the found extent starts after requested offset, then
2090 		 * adjust cur_offset to be right before this extent begins.
2091 		 */
2092 		if (found_key.offset > cur_offset) {
2093 			if (cow_start == (u64)-1)
2094 				cow_start = cur_offset;
2095 			cur_offset = found_key.offset;
2096 			goto next_slot;
2097 		}
2098 
2099 		/*
2100 		 * Found extent which begins before our range and potentially
2101 		 * intersect it
2102 		 */
2103 		fi = btrfs_item_ptr(leaf, path->slots[0],
2104 				    struct btrfs_file_extent_item);
2105 		extent_type = btrfs_file_extent_type(leaf, fi);
2106 		/* If this is triggered then we have a memory corruption. */
2107 		ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2108 		if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2109 			ret = -EUCLEAN;
2110 			goto error;
2111 		}
2112 		extent_end = btrfs_file_extent_end(path);
2113 
2114 		/*
2115 		 * If the extent we got ends before our current offset, skip to
2116 		 * the next extent.
2117 		 */
2118 		if (extent_end <= cur_offset) {
2119 			path->slots[0]++;
2120 			goto next_slot;
2121 		}
2122 
2123 		nocow_args.start = cur_offset;
2124 		ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2125 		if (ret < 0)
2126 			goto error;
2127 		if (ret == 0)
2128 			goto must_cow;
2129 
2130 		ret = 0;
2131 		nocow_bg = btrfs_inc_nocow_writers(fs_info,
2132 				nocow_args.file_extent.disk_bytenr +
2133 				nocow_args.file_extent.offset);
2134 		if (!nocow_bg) {
2135 must_cow:
2136 			/*
2137 			 * If we can't perform NOCOW writeback for the range,
2138 			 * then record the beginning of the range that needs to
2139 			 * be COWed.  It will be written out before the next
2140 			 * NOCOW range if we find one, or when exiting this
2141 			 * loop.
2142 			 */
2143 			if (cow_start == (u64)-1)
2144 				cow_start = cur_offset;
2145 			cur_offset = extent_end;
2146 			if (cur_offset > end)
2147 				break;
2148 			if (!path->nodes[0])
2149 				continue;
2150 			path->slots[0]++;
2151 			goto next_slot;
2152 		}
2153 
2154 		/*
2155 		 * COW range from cow_start to found_key.offset - 1. As the key
2156 		 * will contain the beginning of the first extent that can be
2157 		 * NOCOW, following one which needs to be COW'ed
2158 		 */
2159 		if (cow_start != (u64)-1) {
2160 			ret = fallback_to_cow(inode, locked_folio, cow_start,
2161 					      found_key.offset - 1);
2162 			if (ret) {
2163 				cow_end = found_key.offset - 1;
2164 				btrfs_dec_nocow_writers(nocow_bg);
2165 				goto error;
2166 			}
2167 			cow_start = (u64)-1;
2168 		}
2169 
2170 		ret = nocow_one_range(inode, locked_folio, &cached_state,
2171 				      &nocow_args, cur_offset,
2172 				      extent_type == BTRFS_FILE_EXTENT_PREALLOC);
2173 		btrfs_dec_nocow_writers(nocow_bg);
2174 		if (ret < 0) {
2175 			nocow_end = cur_offset + nocow_args.file_extent.num_bytes - 1;
2176 			goto error;
2177 		}
2178 		cur_offset = extent_end;
2179 	}
2180 	btrfs_release_path(path);
2181 
2182 	if (cur_offset <= end && cow_start == (u64)-1)
2183 		cow_start = cur_offset;
2184 
2185 	if (cow_start != (u64)-1) {
2186 		ret = fallback_to_cow(inode, locked_folio, cow_start, end);
2187 		if (ret) {
2188 			cow_end = end;
2189 			goto error;
2190 		}
2191 		cow_start = (u64)-1;
2192 	}
2193 
2194 	/*
2195 	 * Everything is finished without an error, can unlock the folios now.
2196 	 *
2197 	 * No need to touch the io tree range nor set folio ordered flag, as
2198 	 * fallback_to_cow() and nocow_one_range() have already handled them.
2199 	 */
2200 	extent_clear_unlock_delalloc(inode, start, end, locked_folio, NULL, 0, PAGE_UNLOCK);
2201 
2202 	btrfs_free_path(path);
2203 	return 0;
2204 
2205 error:
2206 	if (cow_start == (u64)-1) {
2207 		/*
2208 		 * case a)
2209 		 *    start           cur_offset               end
2210 		 *    |   OE cleanup  |       Untouched        |
2211 		 *
2212 		 * We finished a fallback_to_cow() or nocow_one_range() call,
2213 		 * but failed to check the next range.
2214 		 *
2215 		 * or
2216 		 *    start           cur_offset   nocow_end   end
2217 		 *    |   OE cleanup  |   Skip     | Untouched |
2218 		 *
2219 		 * nocow_one_range() failed, the range [cur_offset, nocow_end] is
2220 		 * already cleaned up.
2221 		 */
2222 		oe_cleanup_start = start;
2223 		oe_cleanup_len = cur_offset - start;
2224 		if (nocow_end)
2225 			untouched_start = nocow_end + 1;
2226 		else
2227 			untouched_start = cur_offset;
2228 		untouched_len = end + 1 - untouched_start;
2229 	} else if (cow_start != (u64)-1 && cow_end == 0) {
2230 		/*
2231 		 * case b)
2232 		 *    start        cow_start    cur_offset   end
2233 		 *    | OE cleanup |        Untouched        |
2234 		 *
2235 		 * We got a range that needs COW, but before we hit the next NOCOW range,
2236 		 * thus [cow_start, cur_offset) doesn't yet have any OE.
2237 		 */
2238 		oe_cleanup_start = start;
2239 		oe_cleanup_len = cow_start - start;
2240 		untouched_start = cow_start;
2241 		untouched_len = end + 1 - untouched_start;
2242 	} else {
2243 		/*
2244 		 * case c)
2245 		 *    start        cow_start    cow_end      end
2246 		 *    | OE cleanup |   Skip     |  Untouched |
2247 		 *
2248 		 * fallback_to_cow() failed, and fallback_to_cow() will do the
2249 		 * cleanup for its range, we shouldn't touch the range
2250 		 * [cow_start, cow_end].
2251 		 */
2252 		ASSERT(cow_start != (u64)-1 && cow_end != 0);
2253 		oe_cleanup_start = start;
2254 		oe_cleanup_len = cow_start - start;
2255 		untouched_start = cow_end + 1;
2256 		untouched_len = end + 1 - untouched_start;
2257 	}
2258 
2259 	if (oe_cleanup_len) {
2260 		const u64 oe_cleanup_end = oe_cleanup_start + oe_cleanup_len - 1;
2261 		btrfs_cleanup_ordered_extents(inode, oe_cleanup_start, oe_cleanup_len);
2262 		extent_clear_unlock_delalloc(inode, oe_cleanup_start, oe_cleanup_end,
2263 					     locked_folio, NULL,
2264 					     EXTENT_LOCKED | EXTENT_DELALLOC,
2265 					     PAGE_UNLOCK | PAGE_START_WRITEBACK |
2266 					     PAGE_END_WRITEBACK);
2267 	}
2268 
2269 	if (untouched_len) {
2270 		struct extent_state *cached = NULL;
2271 		const u64 untouched_end = untouched_start + untouched_len - 1;
2272 
2273 		/*
2274 		 * We need to lock the extent here because we're clearing DELALLOC and
2275 		 * we're not locked at this point.
2276 		 */
2277 		btrfs_lock_extent(&inode->io_tree, untouched_start, untouched_end, &cached);
2278 		extent_clear_unlock_delalloc(inode, untouched_start, untouched_end,
2279 					     locked_folio, &cached,
2280 					     EXTENT_LOCKED | EXTENT_DELALLOC |
2281 					     EXTENT_DEFRAG |
2282 					     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2283 					     PAGE_START_WRITEBACK |
2284 					     PAGE_END_WRITEBACK);
2285 		btrfs_qgroup_free_data(inode, NULL, untouched_start, untouched_len, NULL);
2286 	}
2287 	btrfs_free_path(path);
2288 	btrfs_err(fs_info,
2289 "%s failed, root=%llu inode=%llu start=%llu len=%llu cur_offset=%llu oe_cleanup=%llu oe_cleanup_len=%llu untouched_start=%llu untouched_len=%llu: %pe",
2290 		  __func__, btrfs_root_id(inode->root), btrfs_ino(inode),
2291 		  start, end + 1 - start, cur_offset, oe_cleanup_start, oe_cleanup_len,
2292 		  untouched_start, untouched_len, ERR_PTR(ret));
2293 	return ret;
2294 }
2295 
should_nocow(struct btrfs_inode * inode,u64 start,u64 end)2296 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2297 {
2298 	if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2299 		if (data_race(inode->defrag_bytes) &&
2300 		    btrfs_test_range_bit_exists(&inode->io_tree, start, end, EXTENT_DEFRAG))
2301 			return false;
2302 		return true;
2303 	}
2304 	return false;
2305 }
2306 
2307 /*
2308  * Return 0 if an inlined extent is created successfully.
2309  * Return <0 if critical error happened.
2310  * Return >0 if an inline extent can not be created.
2311  */
run_delalloc_inline(struct btrfs_inode * inode,struct folio * locked_folio)2312 static int run_delalloc_inline(struct btrfs_inode *inode, struct folio *locked_folio)
2313 {
2314 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2315 	struct compressed_bio *cb = NULL;
2316 	struct extent_state *cached = NULL;
2317 	const u64 i_size = i_size_read(&inode->vfs_inode);
2318 	const u32 blocksize = fs_info->sectorsize;
2319 	int compress_type = fs_info->compress_type;
2320 	int compress_level = fs_info->compress_level;
2321 	u32 compressed_size = 0;
2322 	int ret;
2323 
2324 	ASSERT(folio_pos(locked_folio) == 0);
2325 	/*
2326 	 * If an mmap writer could modify the folio while we copy it into an
2327 	 * inline extent we might see only part of their modification then
2328 	 * wrongly mark it clean again after copying, losing that write. So the
2329 	 * folio must be write protected here.
2330 	 */
2331 	btrfs_check_folio_write_protected(locked_folio);
2332 
2333 	if (btrfs_inode_can_compress(inode) &&
2334 	    inode_need_compress(inode, 0, blocksize, true)) {
2335 		if (inode->defrag_compress > 0 &&
2336 		    inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES) {
2337 			compress_type = inode->defrag_compress;
2338 			compress_level = inode->defrag_compress_level;
2339 		} else if (inode->prop_compress) {
2340 			compress_type = inode->prop_compress;
2341 		}
2342 		cb = btrfs_compress_bio(inode, 0, blocksize, compress_type, compress_level, 0);
2343 		if (IS_ERR(cb)) {
2344 			cb = NULL;
2345 			/* Just fall back to non-compressed case. */
2346 		} else {
2347 			compressed_size = cb->bbio.bio.bi_iter.bi_size;
2348 		}
2349 	}
2350 	if (!can_cow_file_range_inline(inode, 0, i_size, compressed_size)) {
2351 		if (cb)
2352 			cleanup_compressed_bio(cb);
2353 		return 1;
2354 	}
2355 
2356 	btrfs_lock_extent(&inode->io_tree, 0, blocksize - 1, &cached);
2357 	if (cb) {
2358 		ret = __cow_file_range_inline(inode, i_size, compressed_size, compress_type,
2359 					      bio_first_folio_all(&cb->bbio.bio), false);
2360 		cleanup_compressed_bio(cb);
2361 		cb = NULL;
2362 	} else {
2363 		ret = __cow_file_range_inline(inode, i_size, 0, BTRFS_COMPRESS_NONE,
2364 					      NULL, false);
2365 	}
2366 	/*
2367 	 * We failed to insert inline extent due to lack of meta space.
2368 	 * Just unlock the extent io range and fallback to regular COW/NOCOW path.
2369 	 */
2370 	if (ret > 0) {
2371 		btrfs_unlock_extent(&inode->io_tree, 0, blocksize - 1, &cached);
2372 		return ret;
2373 	}
2374 
2375 	/*
2376 	 * In the successful case (ret == 0 here), btrfs_run_delalloc_range()
2377 	 * will return 1.
2378 	 *
2379 	 * Quite a bit further up the callstack in extent_writepage(), ret == 1
2380 	 * is treated as a short circuited success and does not unlock the folio,
2381 	 * so we must do it here.
2382 	 *
2383 	 * For failure case, the @locked_folio does get unlocked by
2384 	 * btrfs_folio_end_lock_bitmap(), so we must *not* unlock it here.
2385 	 *
2386 	 * So if ret == 0, we let extent_clear_unlock_delalloc() to unlock the
2387 	 * folio by passing NULL as @locked_folio.
2388 	 * Otherwise pass @locked_folio as usual.
2389 	 */
2390 	if (ret == 0)
2391 		locked_folio = NULL;
2392 	extent_clear_unlock_delalloc(inode, 0, blocksize - 1, locked_folio, &cached,
2393 				     EXTENT_DELALLOC | EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
2394 				     EXTENT_DO_ACCOUNTING | EXTENT_LOCKED,
2395 				     PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
2396 	return ret;
2397 }
2398 
2399 /*
2400  * Function to process delayed allocation (create CoW) for ranges which are
2401  * being touched for the first time.
2402  */
btrfs_run_delalloc_range(struct btrfs_inode * inode,struct folio * locked_folio,u64 start,u64 end,struct writeback_control * wbc)2403 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_folio,
2404 			     u64 start, u64 end, struct writeback_control *wbc)
2405 {
2406 	const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2407 
2408 	/*
2409 	 * The range must cover part of the @locked_folio, or a return of 1
2410 	 * can confuse the caller.
2411 	 */
2412 	ASSERT(!(end <= folio_pos(locked_folio) ||
2413 		 start >= folio_next_pos(locked_folio)));
2414 
2415 	if (start == 0 && end + 1 <= inode->root->fs_info->sectorsize &&
2416 	    end + 1 >= inode->disk_i_size) {
2417 		int ret;
2418 
2419 		ret = run_delalloc_inline(inode, locked_folio);
2420 		if (ret < 0)
2421 			return ret;
2422 		if (ret == 0)
2423 			return 1;
2424 		/*
2425 		 * Continue regular handling if we can not create an
2426 		 * inlined extent.
2427 		 */
2428 	}
2429 
2430 	if (should_nocow(inode, start, end))
2431 		return run_delalloc_nocow(inode, locked_folio, start, end);
2432 
2433 	if (btrfs_inode_can_compress(inode) &&
2434 	    inode_need_compress(inode, start, end, false) &&
2435 	    run_delalloc_compressed(inode, locked_folio, start, end, wbc))
2436 		return 1;
2437 
2438 	if (zoned)
2439 		return run_delalloc_cow(inode, locked_folio, start, end, wbc, true);
2440 	else
2441 		return cow_file_range(inode, locked_folio, start, end, NULL, 0);
2442 }
2443 
btrfs_split_delalloc_extent(struct btrfs_inode * inode,struct extent_state * orig,u64 split)2444 void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
2445 				 struct extent_state *orig, u64 split)
2446 {
2447 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2448 	u64 size;
2449 
2450 	lockdep_assert_held(&inode->io_tree.lock);
2451 
2452 	/* not delalloc, ignore it */
2453 	if (!(orig->state & EXTENT_DELALLOC))
2454 		return;
2455 
2456 	size = orig->end - orig->start + 1;
2457 	if (size > fs_info->max_extent_size) {
2458 		u32 num_extents;
2459 		u64 new_size;
2460 
2461 		/*
2462 		 * See the explanation in btrfs_merge_delalloc_extent, the same
2463 		 * applies here, just in reverse.
2464 		 */
2465 		new_size = orig->end - split + 1;
2466 		num_extents = count_max_extents(fs_info, new_size);
2467 		new_size = split - orig->start;
2468 		num_extents += count_max_extents(fs_info, new_size);
2469 		if (count_max_extents(fs_info, size) >= num_extents)
2470 			return;
2471 	}
2472 
2473 	spin_lock(&inode->lock);
2474 	btrfs_mod_outstanding_extents(inode, 1);
2475 	spin_unlock(&inode->lock);
2476 }
2477 
2478 /*
2479  * Handle merged delayed allocation extents so we can keep track of new extents
2480  * that are just merged onto old extents, such as when we are doing sequential
2481  * writes, so we can properly account for the metadata space we'll need.
2482  */
btrfs_merge_delalloc_extent(struct btrfs_inode * inode,struct extent_state * new,struct extent_state * other)2483 void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
2484 				 struct extent_state *other)
2485 {
2486 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2487 	u64 new_size, old_size;
2488 	u32 num_extents;
2489 
2490 	lockdep_assert_held(&inode->io_tree.lock);
2491 
2492 	/* not delalloc, ignore it */
2493 	if (!(other->state & EXTENT_DELALLOC))
2494 		return;
2495 
2496 	if (new->start > other->start)
2497 		new_size = new->end - other->start + 1;
2498 	else
2499 		new_size = other->end - new->start + 1;
2500 
2501 	/* we're not bigger than the max, unreserve the space and go */
2502 	if (new_size <= fs_info->max_extent_size) {
2503 		spin_lock(&inode->lock);
2504 		btrfs_mod_outstanding_extents(inode, -1);
2505 		spin_unlock(&inode->lock);
2506 		return;
2507 	}
2508 
2509 	/*
2510 	 * We have to add up either side to figure out how many extents were
2511 	 * accounted for before we merged into one big extent.  If the number of
2512 	 * extents we accounted for is <= the amount we need for the new range
2513 	 * then we can return, otherwise drop.  Think of it like this
2514 	 *
2515 	 * [ 4k][MAX_SIZE]
2516 	 *
2517 	 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2518 	 * need 2 outstanding extents, on one side we have 1 and the other side
2519 	 * we have 1 so they are == and we can return.  But in this case
2520 	 *
2521 	 * [MAX_SIZE+4k][MAX_SIZE+4k]
2522 	 *
2523 	 * Each range on their own accounts for 2 extents, but merged together
2524 	 * they are only 3 extents worth of accounting, so we need to drop in
2525 	 * this case.
2526 	 */
2527 	old_size = other->end - other->start + 1;
2528 	num_extents = count_max_extents(fs_info, old_size);
2529 	old_size = new->end - new->start + 1;
2530 	num_extents += count_max_extents(fs_info, old_size);
2531 	if (count_max_extents(fs_info, new_size) >= num_extents)
2532 		return;
2533 
2534 	spin_lock(&inode->lock);
2535 	btrfs_mod_outstanding_extents(inode, -1);
2536 	spin_unlock(&inode->lock);
2537 }
2538 
btrfs_add_delalloc_inode(struct btrfs_inode * inode)2539 static void btrfs_add_delalloc_inode(struct btrfs_inode *inode)
2540 {
2541 	struct btrfs_root *root = inode->root;
2542 	struct btrfs_fs_info *fs_info = root->fs_info;
2543 
2544 	spin_lock(&root->delalloc_lock);
2545 	ASSERT(list_empty(&inode->delalloc_inodes));
2546 	list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
2547 	root->nr_delalloc_inodes++;
2548 	if (root->nr_delalloc_inodes == 1) {
2549 		spin_lock(&fs_info->delalloc_root_lock);
2550 		ASSERT(list_empty(&root->delalloc_root));
2551 		list_add_tail(&root->delalloc_root, &fs_info->delalloc_roots);
2552 		spin_unlock(&fs_info->delalloc_root_lock);
2553 	}
2554 	spin_unlock(&root->delalloc_lock);
2555 }
2556 
btrfs_del_delalloc_inode(struct btrfs_inode * inode)2557 void btrfs_del_delalloc_inode(struct btrfs_inode *inode)
2558 {
2559 	struct btrfs_root *root = inode->root;
2560 	struct btrfs_fs_info *fs_info = root->fs_info;
2561 
2562 	lockdep_assert_held(&root->delalloc_lock);
2563 
2564 	/*
2565 	 * We may be called after the inode was already deleted from the list,
2566 	 * namely in the transaction abort path btrfs_destroy_delalloc_inodes(),
2567 	 * and then later through btrfs_clear_delalloc_extent() while the inode
2568 	 * still has ->delalloc_bytes > 0.
2569 	 */
2570 	if (!list_empty(&inode->delalloc_inodes)) {
2571 		list_del_init(&inode->delalloc_inodes);
2572 		root->nr_delalloc_inodes--;
2573 		if (!root->nr_delalloc_inodes) {
2574 			ASSERT(list_empty(&root->delalloc_inodes));
2575 			spin_lock(&fs_info->delalloc_root_lock);
2576 			ASSERT(!list_empty(&root->delalloc_root));
2577 			list_del_init(&root->delalloc_root);
2578 			spin_unlock(&fs_info->delalloc_root_lock);
2579 		}
2580 	}
2581 }
2582 
2583 /*
2584  * Properly track delayed allocation bytes in the inode and to maintain the
2585  * list of inodes that have pending delalloc work to be done.
2586  */
btrfs_set_delalloc_extent(struct btrfs_inode * inode,struct extent_state * state,u32 bits)2587 void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
2588 			       u32 bits)
2589 {
2590 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2591 
2592 	lockdep_assert_held(&inode->io_tree.lock);
2593 
2594 	WARN_ON((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC));
2595 	/*
2596 	 * set_bit and clear bit hooks normally require _irqsave/restore
2597 	 * but in this case, we are only testing for the DELALLOC
2598 	 * bit, which is only set or cleared with irqs on
2599 	 */
2600 	if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2601 		u64 len = state->end + 1 - state->start;
2602 		u64 prev_delalloc_bytes;
2603 		u32 num_extents = count_max_extents(fs_info, len);
2604 
2605 		spin_lock(&inode->lock);
2606 		btrfs_mod_outstanding_extents(inode, num_extents);
2607 		spin_unlock(&inode->lock);
2608 
2609 		/* For sanity tests */
2610 		if (btrfs_is_testing(fs_info))
2611 			return;
2612 
2613 		percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2614 					 fs_info->delalloc_batch);
2615 		spin_lock(&inode->lock);
2616 		prev_delalloc_bytes = inode->delalloc_bytes;
2617 		inode->delalloc_bytes += len;
2618 		if (bits & EXTENT_DEFRAG)
2619 			inode->defrag_bytes += len;
2620 		spin_unlock(&inode->lock);
2621 
2622 		/*
2623 		 * We don't need to be under the protection of the inode's lock,
2624 		 * because we are called while holding the inode's io_tree lock
2625 		 * and are therefore protected against concurrent calls of this
2626 		 * function and btrfs_clear_delalloc_extent().
2627 		 */
2628 		if (!btrfs_is_free_space_inode(inode) && prev_delalloc_bytes == 0)
2629 			btrfs_add_delalloc_inode(inode);
2630 	}
2631 
2632 	if (!(state->state & EXTENT_DELALLOC_NEW) &&
2633 	    (bits & EXTENT_DELALLOC_NEW)) {
2634 		spin_lock(&inode->lock);
2635 		inode->new_delalloc_bytes += state->end + 1 - state->start;
2636 		spin_unlock(&inode->lock);
2637 	}
2638 }
2639 
2640 /*
2641  * Once a range is no longer delalloc this function ensures that proper
2642  * accounting happens.
2643  */
btrfs_clear_delalloc_extent(struct btrfs_inode * inode,struct extent_state * state,u32 bits)2644 void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
2645 				 struct extent_state *state, u32 bits)
2646 {
2647 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2648 	u64 len = state->end + 1 - state->start;
2649 	u32 num_extents = count_max_extents(fs_info, len);
2650 
2651 	lockdep_assert_held(&inode->io_tree.lock);
2652 
2653 	if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2654 		spin_lock(&inode->lock);
2655 		inode->defrag_bytes -= len;
2656 		spin_unlock(&inode->lock);
2657 	}
2658 
2659 	/*
2660 	 * set_bit and clear bit hooks normally require _irqsave/restore
2661 	 * but in this case, we are only testing for the DELALLOC
2662 	 * bit, which is only set or cleared with irqs on
2663 	 */
2664 	if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2665 		struct btrfs_root *root = inode->root;
2666 		u64 new_delalloc_bytes;
2667 
2668 		spin_lock(&inode->lock);
2669 		btrfs_mod_outstanding_extents(inode, -num_extents);
2670 		spin_unlock(&inode->lock);
2671 
2672 		/*
2673 		 * We don't reserve metadata space for space cache inodes so we
2674 		 * don't need to call delalloc_release_metadata if there is an
2675 		 * error.
2676 		 */
2677 		if (bits & EXTENT_CLEAR_META_RESV &&
2678 		    root != fs_info->tree_root)
2679 			btrfs_delalloc_release_metadata(inode, len, true);
2680 
2681 		/* For sanity tests. */
2682 		if (btrfs_is_testing(fs_info))
2683 			return;
2684 
2685 		if (!btrfs_is_data_reloc_root(root) &&
2686 		    !btrfs_is_free_space_inode(inode) &&
2687 		    !(state->state & EXTENT_NORESERVE) &&
2688 		    (bits & EXTENT_CLEAR_DATA_RESV))
2689 			btrfs_free_reserved_data_space_noquota(inode, len);
2690 
2691 		percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2692 					 fs_info->delalloc_batch);
2693 		spin_lock(&inode->lock);
2694 		inode->delalloc_bytes -= len;
2695 		new_delalloc_bytes = inode->delalloc_bytes;
2696 		spin_unlock(&inode->lock);
2697 
2698 		/*
2699 		 * We don't need to be under the protection of the inode's lock,
2700 		 * because we are called while holding the inode's io_tree lock
2701 		 * and are therefore protected against concurrent calls of this
2702 		 * function and btrfs_set_delalloc_extent().
2703 		 */
2704 		if (!btrfs_is_free_space_inode(inode) && new_delalloc_bytes == 0) {
2705 			spin_lock(&root->delalloc_lock);
2706 			btrfs_del_delalloc_inode(inode);
2707 			spin_unlock(&root->delalloc_lock);
2708 		}
2709 	}
2710 
2711 	if ((state->state & EXTENT_DELALLOC_NEW) &&
2712 	    (bits & EXTENT_DELALLOC_NEW)) {
2713 		spin_lock(&inode->lock);
2714 		ASSERT(inode->new_delalloc_bytes >= len);
2715 		inode->new_delalloc_bytes -= len;
2716 		if (bits & EXTENT_ADD_INODE_BYTES)
2717 			inode_add_bytes(&inode->vfs_inode, len);
2718 		spin_unlock(&inode->lock);
2719 	}
2720 }
2721 
2722 /*
2723  * Given an ordered extent and insert all its checksums into the csum tree.
2724  *
2725  * This happens at IO completion time based on sums calculated at bio
2726  * submission time.
2727  */
add_pending_csums(struct btrfs_trans_handle * trans,struct btrfs_ordered_extent * oe)2728 static int add_pending_csums(struct btrfs_trans_handle *trans,
2729 			     struct btrfs_ordered_extent *oe)
2730 {
2731 	struct btrfs_ordered_sum *sum;
2732 	struct btrfs_root *csum_root = NULL;
2733 	int ret;
2734 
2735 	list_for_each_entry(sum, &oe->csum_list, list) {
2736 		if (!csum_root) {
2737 			csum_root = btrfs_csum_root(trans->fs_info,
2738 						    sum->logical);
2739 			if (unlikely(!csum_root)) {
2740 				btrfs_err(trans->fs_info,
2741 				  "missing csum root for extent at bytenr %llu",
2742 					  sum->logical);
2743 				return -EUCLEAN;
2744 			}
2745 		}
2746 		trans->adding_csums = true;
2747 		ret = btrfs_insert_data_csums(trans, csum_root, sum);
2748 		trans->adding_csums = false;
2749 		if (ret)
2750 			return ret;
2751 	}
2752 	return 0;
2753 }
2754 
btrfs_find_new_delalloc_bytes(struct btrfs_inode * inode,const u64 start,const u64 len,struct extent_state ** cached_state)2755 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2756 					 const u64 start,
2757 					 const u64 len,
2758 					 struct extent_state **cached_state)
2759 {
2760 	u64 search_start = start;
2761 	const u64 end = start + len - 1;
2762 
2763 	while (search_start < end) {
2764 		const u64 search_len = end - search_start + 1;
2765 		struct extent_map *em;
2766 		u64 em_len;
2767 		int ret = 0;
2768 
2769 		em = btrfs_get_extent(inode, NULL, search_start, search_len);
2770 		if (IS_ERR(em))
2771 			return PTR_ERR(em);
2772 
2773 		if (em->disk_bytenr != EXTENT_MAP_HOLE)
2774 			goto next;
2775 
2776 		em_len = em->len;
2777 		if (em->start < search_start)
2778 			em_len -= search_start - em->start;
2779 		if (em_len > search_len)
2780 			em_len = search_len;
2781 
2782 		ret = btrfs_set_extent_bit(&inode->io_tree, search_start,
2783 					   search_start + em_len - 1,
2784 					   EXTENT_DELALLOC_NEW, cached_state);
2785 next:
2786 		search_start = btrfs_extent_map_end(em);
2787 		btrfs_free_extent_map(em);
2788 		if (ret)
2789 			return ret;
2790 	}
2791 	return 0;
2792 }
2793 
btrfs_set_extent_delalloc(struct btrfs_inode * inode,u64 start,u64 end,unsigned int extra_bits,struct extent_state ** cached_state)2794 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2795 			      unsigned int extra_bits,
2796 			      struct extent_state **cached_state)
2797 {
2798 	const u32 blocksize = inode->root->fs_info->sectorsize;
2799 
2800 	/* Basic alignment check. */
2801 	ASSERT(IS_ALIGNED(start, blocksize), "start=%llu blocksize=%u",
2802 	       start, blocksize);
2803 	ASSERT(IS_ALIGNED(end + 1, blocksize), "inclusive end=%llu blocksize=%u",
2804 	       end, blocksize);
2805 
2806 	if (start >= i_size_read(&inode->vfs_inode) &&
2807 	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
2808 		/*
2809 		 * There can't be any extents following eof in this case so just
2810 		 * set the delalloc new bit for the range directly.
2811 		 */
2812 		extra_bits |= EXTENT_DELALLOC_NEW;
2813 	} else {
2814 		int ret;
2815 
2816 		ret = btrfs_find_new_delalloc_bytes(inode, start,
2817 						    end + 1 - start,
2818 						    cached_state);
2819 		if (ret)
2820 			return ret;
2821 	}
2822 
2823 	return btrfs_set_extent_bit(&inode->io_tree, start, end,
2824 				    EXTENT_DELALLOC | extra_bits, cached_state);
2825 }
2826 
2827 struct btrfs_writepage_fixup {
2828 	struct folio *folio;
2829 	struct btrfs_inode *inode;
2830 	struct work_struct work;
2831 };
2832 
2833 /*
2834  * Do the real fixup work of reserving space for the blocks a folio's fixup
2835  * state records. Queued by writepage_fixup() when writeback found the bits set.
2836  *
2837  * Since the fixup can be cancelled by a task dirtying with a reservation, we must
2838  * re-check the state of fixup under the folio lock.
2839  */
btrfs_writepage_fixup_worker(struct work_struct * work)2840 static void btrfs_writepage_fixup_worker(struct work_struct *work)
2841 {
2842 	struct btrfs_writepage_fixup *fixup =
2843 		container_of(work, struct btrfs_writepage_fixup, work);
2844 	struct extent_state *cached_state = NULL;
2845 	struct extent_changeset *data_reserved = NULL;
2846 	unsigned long delalloc_bitmap[BITS_TO_LONGS(BTRFS_MAX_BLOCKS_PER_FOLIO)] = { 0 };
2847 	struct folio *folio = fixup->folio;
2848 	struct btrfs_inode *inode = fixup->inode;
2849 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2850 	const unsigned int blocks_per_folio = btrfs_blocks_per_folio(fs_info, folio);
2851 	const u32 sectorsize = fs_info->sectorsize;
2852 	const u64 page_start = folio_pos(folio);
2853 	const u64 page_end = folio_next_pos(folio) - 1;
2854 	unsigned int start_bit;
2855 	unsigned int end_bit;
2856 	unsigned int bit;
2857 	bool reserved;
2858 	int ret;
2859 
2860 	/*
2861 	 * We would prefer to reserve under the folio lock when we know exactly
2862 	 * which blocks need a reservation. Unfortunately, since the reservation
2863 	 * can go into flushers which can go into writeback, which takes folio
2864 	 * locks, that is not possible. Therefore, we have to reserve for the
2865 	 * whole folio here, then release what we didn't end up needing once we
2866 	 * figure it out.
2867 	 *
2868 	 * Also note the slightly strange error checking. If fixup is actually
2869 	 * not set, we don't need to mark an error on the mapping. So hang on to
2870 	 * ret until after we lock and find out if we actually care.
2871 	 */
2872 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2873 					   folio_size(folio));
2874 	reserved = (ret == 0);
2875 again:
2876 	folio_lock(folio);
2877 
2878 	if (!folio->mapping || !folio_test_fixup_pending(folio)) {
2879 		ret = 0;
2880 		goto out;
2881 	}
2882 	if (ret)
2883 		goto out;
2884 
2885 	btrfs_lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2886 
2887 	for (bit = 0; bit < blocks_per_folio; bit++) {
2888 		struct btrfs_ordered_extent *ordered;
2889 		const u64 start = page_start + (bit << fs_info->sectorsize_bits);
2890 
2891 		if (test_bit(bit, delalloc_bitmap))
2892 			continue;
2893 		if (!btrfs_folio_test_fixup(fs_info, folio, start, sectorsize))
2894 			continue;
2895 		/*
2896 		 * Any task that sets EXTENT_DELALLOC clears the fixup bits
2897 		 * under the folio lock, so it should be impossible to observe
2898 		 * both under the lock. Setting delalloc twice would wrongly
2899 		 * double account the space.
2900 		 */
2901 		if (IS_ENABLED(CONFIG_BTRFS_DEBUG) &&
2902 		    unlikely(btrfs_test_range_bit_exists(&inode->io_tree, start,
2903 							 start + sectorsize - 1,
2904 							 EXTENT_DELALLOC))) {
2905 			DEBUG_WARN("fixup worker: delalloc and fixup conflict. ino %llu start %llu",
2906 				   btrfs_ino(inode), start);
2907 			btrfs_folio_clear_fixup(fs_info, folio, start, sectorsize);
2908 			continue;
2909 		}
2910 		ordered = btrfs_lookup_ordered_range(inode, start, sectorsize);
2911 		if (ordered) {
2912 			trace_btrfs_writepage_fixup_defer(inode, ordered);
2913 			btrfs_unlock_extent(&inode->io_tree, page_start,
2914 					    page_end, &cached_state);
2915 			folio_unlock(folio);
2916 			btrfs_start_ordered_extent(ordered);
2917 			btrfs_put_ordered_extent(ordered);
2918 			goto again;
2919 		}
2920 		ret = btrfs_set_extent_delalloc(inode, start,
2921 						start + sectorsize - 1, 0,
2922 						&cached_state);
2923 		if (ret)
2924 			break;
2925 		trace_btrfs_writepage_fixup_reserve(inode, start, sectorsize);
2926 		btrfs_folio_clear_fixup(fs_info, folio, start, sectorsize);
2927 		set_bit(bit, delalloc_bitmap);
2928 	}
2929 
2930 	btrfs_unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2931 out:
2932 	if (ret < 0) {
2933 		/* Failure here is analogous to failure in writeback. */
2934 		mapping_set_error(folio->mapping, ret);
2935 		btrfs_folio_clear_fixup_dirty(fs_info, folio, page_start,
2936 					      folio_size(folio));
2937 	}
2938 	if (reserved) {
2939 		btrfs_delalloc_release_extents(inode, folio_size(folio));
2940 		for_each_clear_bitrange(start_bit, end_bit, delalloc_bitmap,
2941 					blocks_per_folio)
2942 			btrfs_delalloc_release_space(inode, data_reserved,
2943 				page_start + (start_bit << fs_info->sectorsize_bits),
2944 				(end_bit - start_bit) << fs_info->sectorsize_bits,
2945 				true);
2946 	}
2947 	folio_unlock(folio);
2948 	folio_put(folio);
2949 	kfree(fixup);
2950 	extent_changeset_free(data_reserved);
2951 	btrfs_add_delayed_iput(inode);
2952 }
2953 
2954 /*
2955  * Queue space reservation fixup work for blocks dirtied without a space reservation.
2956  *
2957  * Should be used by writeback while holding the folio locked.
2958  *
2959  * If we fail to queue fixup, then the folio state is unchanged and a future
2960  * writeback pass will still see it.
2961  */
btrfs_queue_writepage_fixup(struct btrfs_inode * inode,struct folio * folio)2962 void btrfs_queue_writepage_fixup(struct btrfs_inode *inode, struct folio *folio)
2963 {
2964 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2965 	struct btrfs_writepage_fixup *fixup;
2966 
2967 	/*
2968 	 * Disallow queueing more fixup during unmount to break the cycle
2969 	 * of writeback queuing fixup queuing writeback etc.
2970 	 *
2971 	 * If it actually hit, then something which was fixup wasn't written
2972 	 * which we should warn about.
2973 	 */
2974 	if (btrfs_fs_closing(fs_info)) {
2975 		btrfs_warn_rl(fs_info,
2976 	"dropping unqueued fixup blocks at unmount. root %lld ino %llu folio %llu",
2977 			      btrfs_root_id(inode->root), btrfs_ino(inode),
2978 			      folio_pos(folio));
2979 		btrfs_folio_clear_fixup_dirty(fs_info, folio,
2980 					      folio_pos(folio), folio_size(folio));
2981 		return;
2982 	}
2983 
2984 	fixup = kzalloc_obj(*fixup, GFP_NOFS);
2985 	if (!fixup)
2986 		return;
2987 
2988 	/*
2989 	 * This is called from within extent_write_cache_pages() which
2990 	 * has successfully done an igrab(). But that will be released at the
2991 	 * end of the writeback pass. We need to extend it for the worker as well.
2992 	 */
2993 	ihold(&inode->vfs_inode);
2994 	folio_get(folio);
2995 	INIT_WORK(&fixup->work, btrfs_writepage_fixup_worker);
2996 	fixup->folio = folio;
2997 	fixup->inode = inode;
2998 	queue_work(fs_info->fixup_workers, &fixup->work);
2999 }
3000 
3001 /*
3002  * Clear the old accounting flags and set EXTENT_DELALLOC for the range.
3003  *
3004  * Return <0 for error, in that case no range has EXTENT_DELALLOC bit cleared or set.
3005  */
btrfs_reset_extent_delalloc(struct btrfs_inode * inode,u64 start,u64 end,unsigned int extra_bits,struct extent_state ** cached_state)3006 int btrfs_reset_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
3007 				unsigned int extra_bits, struct extent_state **cached_state)
3008 {
3009 	const u32 blocksize = inode->root->fs_info->sectorsize;
3010 
3011 	/* The @extra_bits can only be EXTENT_NORESERVE for now. */
3012 	ASSERT(!(extra_bits & ~EXTENT_NORESERVE), "extra_bits=0x%x", extra_bits);
3013 
3014 	/* Basic alignment check. */
3015 	ASSERT(IS_ALIGNED(start, blocksize), "start=%llu blocksize=%u",
3016 	       start, blocksize);
3017 	ASSERT(IS_ALIGNED(end + 1, blocksize), "inclusive end=%llu blocksize=%u",
3018 	       end, blocksize);
3019 
3020 	/*
3021 	 * Check and set DELALLOC_NEW flag, this needs to search tree thus can
3022 	 * fail early.  Thus we want to do this before clearing EXTENT_DELALLOC.
3023 	 */
3024 	if (start >= i_size_read(&inode->vfs_inode) &&
3025 	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
3026 		/*
3027 		 * There can't be any extents following EOF in this case so just
3028 		 * set the delalloc new bit for the range directly.
3029 		 */
3030 		extra_bits |= EXTENT_DELALLOC_NEW;
3031 	} else {
3032 		int ret;
3033 
3034 		ret = btrfs_find_new_delalloc_bytes(inode, start, end + 1 - start,
3035 						    NULL);
3036 		if (unlikely(ret))
3037 			return ret;
3038 	}
3039 	/* Clear the old accounting as the range may already be dirty. */
3040 	btrfs_clear_extent_bit(&inode->io_tree, start, end,
3041 			       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
3042 			       EXTENT_DEFRAG, cached_state);
3043 	return btrfs_set_extent_bit(&inode->io_tree, start, end,
3044 				    EXTENT_DELALLOC | extra_bits, cached_state);
3045 }
3046 
insert_reserved_file_extent(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,u64 file_pos,struct btrfs_file_extent_item * stack_fi,const bool update_inode_bytes,u64 qgroup_reserved)3047 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
3048 				       struct btrfs_inode *inode, u64 file_pos,
3049 				       struct btrfs_file_extent_item *stack_fi,
3050 				       const bool update_inode_bytes,
3051 				       u64 qgroup_reserved)
3052 {
3053 	struct btrfs_root *root = inode->root;
3054 	const u32 sectorsize = root->fs_info->sectorsize;
3055 	BTRFS_PATH_AUTO_FREE(path);
3056 	struct extent_buffer *leaf;
3057 	struct btrfs_key ins;
3058 	u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
3059 	u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
3060 	u64 offset = btrfs_stack_file_extent_offset(stack_fi);
3061 	u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
3062 	u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
3063 	struct btrfs_drop_extents_args drop_args = { 0 };
3064 	int ret;
3065 
3066 	path = btrfs_alloc_path();
3067 	if (!path)
3068 		return -ENOMEM;
3069 
3070 	/*
3071 	 * we may be replacing one extent in the tree with another.
3072 	 * The new extent is pinned in the extent map, and we don't want
3073 	 * to drop it from the cache until it is completely in the btree.
3074 	 *
3075 	 * So, tell btrfs_drop_extents to leave this extent in the cache.
3076 	 * the caller is expected to unpin it and allow it to be merged
3077 	 * with the others.
3078 	 */
3079 	drop_args.path = path;
3080 	drop_args.start = file_pos;
3081 	drop_args.end = file_pos + num_bytes;
3082 	drop_args.replace_extent = true;
3083 	drop_args.extent_item_size = sizeof(*stack_fi);
3084 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3085 	if (ret)
3086 		return ret;
3087 
3088 	if (!drop_args.extent_inserted) {
3089 		ins.objectid = btrfs_ino(inode);
3090 		ins.type = BTRFS_EXTENT_DATA_KEY;
3091 		ins.offset = file_pos;
3092 
3093 		ret = btrfs_insert_empty_item(trans, root, path, &ins,
3094 					      sizeof(*stack_fi));
3095 		if (ret)
3096 			return ret;
3097 	}
3098 	leaf = path->nodes[0];
3099 	btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3100 	write_extent_buffer(leaf, stack_fi,
3101 			btrfs_item_ptr_offset(leaf, path->slots[0]),
3102 			sizeof(struct btrfs_file_extent_item));
3103 
3104 	btrfs_release_path(path);
3105 
3106 	/*
3107 	 * If we dropped an inline extent here, we know the range where it is
3108 	 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3109 	 * number of bytes only for that range containing the inline extent.
3110 	 * The remaining of the range will be processed when clearing the
3111 	 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3112 	 */
3113 	if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3114 		u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3115 
3116 		inline_size = drop_args.bytes_found - inline_size;
3117 		btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3118 		drop_args.bytes_found -= inline_size;
3119 		num_bytes -= sectorsize;
3120 	}
3121 
3122 	if (update_inode_bytes)
3123 		btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3124 
3125 	ins.objectid = disk_bytenr;
3126 	ins.type = BTRFS_EXTENT_ITEM_KEY;
3127 	ins.offset = disk_num_bytes;
3128 
3129 	ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3130 	if (ret)
3131 		return ret;
3132 
3133 	return btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3134 						file_pos - offset,
3135 						qgroup_reserved, &ins);
3136 }
3137 
btrfs_release_delalloc_bytes(struct btrfs_fs_info * fs_info,u64 start,u64 len)3138 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3139 					 u64 start, u64 len)
3140 {
3141 	struct btrfs_block_group *cache;
3142 
3143 	cache = btrfs_lookup_block_group(fs_info, start);
3144 	ASSERT(cache);
3145 
3146 	spin_lock(&cache->lock);
3147 	cache->delalloc_bytes -= len;
3148 	spin_unlock(&cache->lock);
3149 
3150 	btrfs_put_block_group(cache);
3151 }
3152 
insert_ordered_extent_file_extent(struct btrfs_trans_handle * trans,struct btrfs_ordered_extent * oe)3153 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3154 					     struct btrfs_ordered_extent *oe)
3155 {
3156 	struct btrfs_file_extent_item stack_fi;
3157 	bool update_inode_bytes;
3158 	u64 num_bytes = oe->num_bytes;
3159 	u64 ram_bytes = oe->ram_bytes;
3160 
3161 	memset(&stack_fi, 0, sizeof(stack_fi));
3162 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3163 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3164 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3165 						   oe->disk_num_bytes);
3166 	btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3167 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
3168 		num_bytes = oe->truncated_len;
3169 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3170 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3171 	btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3172 	/* Encryption and other encoding is reserved and all 0 */
3173 
3174 	/*
3175 	 * For delalloc, when completing an ordered extent we update the inode's
3176 	 * bytes when clearing the range in the inode's io tree, so pass false
3177 	 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3178 	 * except if the ordered extent was truncated.
3179 	 */
3180 	update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3181 			     test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3182 			     test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3183 
3184 	return insert_reserved_file_extent(trans, oe->inode,
3185 					   oe->file_offset, &stack_fi,
3186 					   update_inode_bytes, oe->qgroup_rsv);
3187 }
3188 
3189 /*
3190  * As ordered data IO finishes, this gets called so we can finish
3191  * an ordered extent if the range of bytes in the file it covers are
3192  * fully written.
3193  */
btrfs_finish_one_ordered(struct btrfs_ordered_extent * ordered_extent)3194 int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
3195 {
3196 	struct btrfs_inode *inode = ordered_extent->inode;
3197 	struct btrfs_root *root = inode->root;
3198 	struct btrfs_fs_info *fs_info = root->fs_info;
3199 	struct btrfs_trans_handle *trans = NULL;
3200 	struct extent_io_tree *io_tree = &inode->io_tree;
3201 	struct extent_state *cached_state = NULL;
3202 	u64 start, end;
3203 	int compress_type = 0;
3204 	int ret = 0;
3205 	u64 logical_len = ordered_extent->num_bytes;
3206 	bool freespace_inode;
3207 	bool truncated = false;
3208 	bool clear_reserved_extent = true;
3209 	unsigned int clear_bits = 0;
3210 
3211 	start = ordered_extent->file_offset;
3212 	end = start + ordered_extent->num_bytes - 1;
3213 
3214 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3215 	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3216 	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3217 	    !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3218 		clear_bits |= EXTENT_DELALLOC_NEW;
3219 
3220 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags))
3221 		clear_bits |= EXTENT_DEFRAG;
3222 
3223 	freespace_inode = btrfs_is_free_space_inode(inode);
3224 	if (!freespace_inode)
3225 		btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3226 
3227 	if (unlikely(test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags))) {
3228 		ret = -EIO;
3229 		goto out;
3230 	}
3231 
3232 	ret = btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3233 				      ordered_extent->disk_num_bytes);
3234 	if (ret)
3235 		goto out;
3236 
3237 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3238 		truncated = true;
3239 		logical_len = ordered_extent->truncated_len;
3240 		/* Truncated the entire extent, don't bother adding */
3241 		if (!logical_len)
3242 			goto out;
3243 	}
3244 
3245 	/*
3246 	 * If it's a COW write we need to lock the extent range as we will be
3247 	 * inserting/replacing file extent items and unpinning an extent map.
3248 	 * This must be taken before joining a transaction, as it's a higher
3249 	 * level lock (like the inode's VFS lock), otherwise we can run into an
3250 	 * ABBA deadlock with other tasks (transactions work like a lock,
3251 	 * depending on their current state).
3252 	 */
3253 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3254 		clear_bits |= EXTENT_LOCKED | EXTENT_FINISHING_ORDERED;
3255 		btrfs_lock_extent_bits(io_tree, start, end,
3256 				       EXTENT_LOCKED | EXTENT_FINISHING_ORDERED,
3257 				       &cached_state);
3258 	}
3259 
3260 	if (freespace_inode)
3261 		trans = btrfs_join_transaction_spacecache(root);
3262 	else
3263 		trans = btrfs_join_transaction(root);
3264 	if (IS_ERR(trans)) {
3265 		ret = PTR_ERR(trans);
3266 		trans = NULL;
3267 		goto out;
3268 	}
3269 
3270 	trans->block_rsv = &inode->block_rsv;
3271 
3272 	ret = btrfs_insert_raid_extent(trans, ordered_extent);
3273 	if (unlikely(ret)) {
3274 		btrfs_abort_transaction(trans, ret);
3275 		goto out;
3276 	}
3277 
3278 	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3279 		/* Logic error */
3280 		ASSERT(list_empty(&ordered_extent->csum_list));
3281 		if (unlikely(!list_empty(&ordered_extent->csum_list))) {
3282 			ret = -EINVAL;
3283 			btrfs_abort_transaction(trans, ret);
3284 			goto out;
3285 		}
3286 
3287 		btrfs_inode_safe_disk_i_size_write(inode, 0);
3288 		ret = btrfs_update_inode_fallback(trans, inode);
3289 		if (unlikely(ret)) {
3290 			/* -ENOMEM or corruption */
3291 			btrfs_abort_transaction(trans, ret);
3292 		}
3293 		goto out;
3294 	}
3295 
3296 	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3297 		compress_type = ordered_extent->compress_type;
3298 	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3299 		BUG_ON(compress_type);
3300 		ret = btrfs_mark_extent_written(trans, inode,
3301 						ordered_extent->file_offset,
3302 						ordered_extent->file_offset +
3303 						logical_len);
3304 		btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3305 						  ordered_extent->disk_num_bytes);
3306 		if (unlikely(ret < 0)) {
3307 			btrfs_abort_transaction(trans, ret);
3308 			goto out;
3309 		}
3310 	} else {
3311 		BUG_ON(root == fs_info->tree_root);
3312 		ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3313 		if (unlikely(ret < 0)) {
3314 			btrfs_abort_transaction(trans, ret);
3315 			goto out;
3316 		}
3317 		clear_reserved_extent = false;
3318 		btrfs_release_delalloc_bytes(fs_info,
3319 					     ordered_extent->disk_bytenr,
3320 					     ordered_extent->disk_num_bytes);
3321 	}
3322 
3323 	ret = btrfs_unpin_extent_cache(inode, ordered_extent->file_offset,
3324 				       ordered_extent->num_bytes, trans->transid);
3325 	if (unlikely(ret < 0)) {
3326 		btrfs_abort_transaction(trans, ret);
3327 		goto out;
3328 	}
3329 
3330 	ret = add_pending_csums(trans, ordered_extent);
3331 	if (unlikely(ret)) {
3332 		btrfs_abort_transaction(trans, ret);
3333 		goto out;
3334 	}
3335 
3336 	/*
3337 	 * If this is a new delalloc range, clear its new delalloc flag to
3338 	 * update the inode's number of bytes. This needs to be done first
3339 	 * before updating the inode item.
3340 	 */
3341 	if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3342 	    !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3343 		btrfs_clear_extent_bit(&inode->io_tree, start, end,
3344 				       EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3345 				       &cached_state);
3346 
3347 	btrfs_inode_safe_disk_i_size_write(inode, 0);
3348 	ret = btrfs_update_inode_fallback(trans, inode);
3349 	if (unlikely(ret)) { /* -ENOMEM or corruption */
3350 		btrfs_abort_transaction(trans, ret);
3351 		goto out;
3352 	}
3353 out:
3354 	if (clear_bits)
3355 		btrfs_clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3356 				       &cached_state);
3357 
3358 	if (trans)
3359 		btrfs_end_transaction(trans);
3360 
3361 	if (ret || truncated) {
3362 		/*
3363 		 * If we failed to finish this ordered extent for any reason we
3364 		 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3365 		 * extent, and mark the inode with the error if it wasn't
3366 		 * already set.  Any error during writeback would have already
3367 		 * set the mapping error, so we need to set it if we're the ones
3368 		 * marking this ordered extent as failed.
3369 		 */
3370 		if (ret)
3371 			btrfs_mark_ordered_extent_error(ordered_extent);
3372 
3373 		/*
3374 		 * Drop extent maps for the part of the extent we didn't write.
3375 		 *
3376 		 * We have an exception here for the free_space_inode, this is
3377 		 * because when we do btrfs_get_extent() on the free space inode
3378 		 * we will search the commit root.  If this is a new block group
3379 		 * we won't find anything, and we will trip over the assert in
3380 		 * writepage where we do ASSERT(em->block_start !=
3381 		 * EXTENT_MAP_HOLE).
3382 		 *
3383 		 * Theoretically we could also skip this for any NOCOW extent as
3384 		 * we don't mess with the extent map tree in the NOCOW case, but
3385 		 * for now simply skip this if we are the free space inode.
3386 		 */
3387 		if (!btrfs_is_free_space_inode(inode)) {
3388 			u64 unwritten_start = start;
3389 
3390 			if (truncated)
3391 				unwritten_start += logical_len;
3392 
3393 			btrfs_drop_extent_map_range(inode, unwritten_start,
3394 						    end, false);
3395 		}
3396 
3397 		/*
3398 		 * If the ordered extent had an IOERR or something else went
3399 		 * wrong we need to return the space for this ordered extent
3400 		 * back to the allocator.  We only free the extent in the
3401 		 * truncated case if we didn't write out the extent at all.
3402 		 *
3403 		 * If we made it past insert_reserved_file_extent before we
3404 		 * errored out then we don't need to do this as the accounting
3405 		 * has already been done.
3406 		 */
3407 		if ((ret || !logical_len) &&
3408 		    clear_reserved_extent &&
3409 		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3410 		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3411 			/*
3412 			 * Discard the range before returning it back to the
3413 			 * free space pool
3414 			 */
3415 			if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3416 				btrfs_discard_extent(fs_info,
3417 						ordered_extent->disk_bytenr,
3418 						ordered_extent->disk_num_bytes,
3419 						NULL, true);
3420 			btrfs_free_reserved_extent(fs_info,
3421 					ordered_extent->disk_bytenr,
3422 					ordered_extent->disk_num_bytes, true);
3423 			/*
3424 			 * Actually free the qgroup rsv which was released when
3425 			 * the ordered extent was created.
3426 			 */
3427 			btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(inode->root),
3428 						  ordered_extent->qgroup_rsv,
3429 						  BTRFS_QGROUP_RSV_DATA);
3430 		}
3431 	}
3432 
3433 	/*
3434 	 * This needs to be done to make sure anybody waiting knows we are done
3435 	 * updating everything for this ordered extent.
3436 	 */
3437 	btrfs_remove_ordered_extent(ordered_extent);
3438 
3439 	/* Cleanup any remaining biocs attached to the OE. */
3440 	btrfs_cleanup_ordered_bioc_list(ordered_extent);
3441 
3442 	/* once for us */
3443 	btrfs_put_ordered_extent(ordered_extent);
3444 	/* once for the tree */
3445 	btrfs_put_ordered_extent(ordered_extent);
3446 
3447 	return ret;
3448 }
3449 
btrfs_finish_ordered_io(struct btrfs_ordered_extent * ordered)3450 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
3451 {
3452 	if (btrfs_is_zoned(ordered->inode->root->fs_info) &&
3453 	    !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
3454 	    list_empty(&ordered->bioc_list))
3455 		btrfs_finish_ordered_zoned(ordered);
3456 	return btrfs_finish_one_ordered(ordered);
3457 }
3458 
3459 /*
3460  * Calculate the checksum of an fs block at physical memory address @paddr,
3461  * and save the result to @dest.
3462  *
3463  * The folio containing @paddr must be large enough to contain a full fs block.
3464  */
btrfs_calculate_block_csum_folio(struct btrfs_fs_info * fs_info,const phys_addr_t paddr,u8 * dest)3465 void btrfs_calculate_block_csum_folio(struct btrfs_fs_info *fs_info,
3466 				      const phys_addr_t paddr, u8 *dest)
3467 {
3468 	struct folio *folio = page_folio(phys_to_page(paddr));
3469 	const u32 blocksize = fs_info->sectorsize;
3470 	const u32 step = min(blocksize, PAGE_SIZE);
3471 	const u32 nr_steps = blocksize / step;
3472 	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
3473 
3474 	/* The full block must be inside the folio. */
3475 	ASSERT(offset_in_folio(folio, paddr) + blocksize <= folio_size(folio));
3476 
3477 	for (int i = 0; i < nr_steps; i++) {
3478 		u32 pindex = offset_in_folio(folio, paddr + i * step) >> PAGE_SHIFT;
3479 
3480 		/*
3481 		 * For bs <= ps cases, we will only run the loop once, so the offset
3482 		 * inside the page will only added to paddrs[0].
3483 		 *
3484 		 * For bs > ps cases, the block must be page aligned, thus offset
3485 		 * inside the page will always be 0.
3486 		 */
3487 		paddrs[i] = page_to_phys(folio_page(folio, pindex)) + offset_in_page(paddr);
3488 	}
3489 	return btrfs_calculate_block_csum_pages(fs_info, paddrs, dest);
3490 }
3491 
3492 /*
3493  * Calculate the checksum of a fs block backed by multiple noncontiguous pages
3494  * at @paddrs[] and save the result to @dest.
3495  *
3496  * The folio containing @paddr must be large enough to contain a full fs block.
3497  */
btrfs_calculate_block_csum_pages(struct btrfs_fs_info * fs_info,const phys_addr_t paddrs[],u8 * dest)3498 void btrfs_calculate_block_csum_pages(struct btrfs_fs_info *fs_info,
3499 				      const phys_addr_t paddrs[], u8 *dest)
3500 {
3501 	const u32 blocksize = fs_info->sectorsize;
3502 	const u32 step = min(blocksize, PAGE_SIZE);
3503 	const u32 nr_steps = blocksize / step;
3504 	struct btrfs_csum_ctx csum;
3505 
3506 	btrfs_csum_init(&csum, fs_info->csum_type);
3507 	for (int i = 0; i < nr_steps; i++) {
3508 		const phys_addr_t paddr = paddrs[i];
3509 		void *kaddr;
3510 
3511 		ASSERT(offset_in_page(paddr) + step <= PAGE_SIZE);
3512 		kaddr = kmap_local_page(phys_to_page(paddr)) + offset_in_page(paddr);
3513 		btrfs_csum_update(&csum, kaddr, step);
3514 		kunmap_local(kaddr);
3515 	}
3516 	btrfs_csum_final(&csum, dest);
3517 }
3518 
3519 /*
3520  * Verify the checksum for a single sector without any extra action that depend
3521  * on the type of I/O.
3522  *
3523  * @kaddr must be a properly kmapped address.
3524  */
btrfs_check_block_csum(struct btrfs_fs_info * fs_info,phys_addr_t paddr,u8 * csum,const u8 * const csum_expected)3525 int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 *csum,
3526 			   const u8 * const csum_expected)
3527 {
3528 	btrfs_calculate_block_csum_folio(fs_info, paddr, csum);
3529 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3530 		return -EIO;
3531 	return 0;
3532 }
3533 
3534 /*
3535  * Verify the checksum of a single data sector, which can be scattered at
3536  * different noncontiguous pages.
3537  *
3538  * @bbio:	btrfs_io_bio which contains the csum
3539  * @dev:	device the sector is on
3540  * @bio_offset:	offset to the beginning of the bio (in bytes)
3541  * @paddrs:	physical addresses which back the fs block
3542  *
3543  * Check if the checksum on a data block is valid.  When a checksum mismatch is
3544  * detected, report the error and fill the corrupted range with zero.
3545  *
3546  * Return %true if the sector is ok or had no checksum to start with, else %false.
3547  */
btrfs_data_csum_ok(struct btrfs_bio * bbio,struct btrfs_device * dev,u32 bio_offset,const phys_addr_t paddrs[])3548 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3549 			u32 bio_offset, const phys_addr_t paddrs[])
3550 {
3551 	struct btrfs_inode *inode = bbio->inode;
3552 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3553 	const u32 blocksize = fs_info->sectorsize;
3554 	const u32 step = min(blocksize, PAGE_SIZE);
3555 	const u32 nr_steps = blocksize / step;
3556 	u64 file_offset = bbio->file_offset + bio_offset;
3557 	u64 end = file_offset + blocksize - 1;
3558 	u8 *csum_expected;
3559 	u8 csum[BTRFS_CSUM_SIZE];
3560 
3561 	if (!bbio->csum)
3562 		return true;
3563 
3564 	if (btrfs_is_data_reloc_root(inode->root) &&
3565 	    btrfs_test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3566 				 NULL)) {
3567 		/* Skip the range without csum for data reloc inode */
3568 		btrfs_clear_extent_bit(&inode->io_tree, file_offset, end,
3569 				       EXTENT_NODATASUM, NULL);
3570 		return true;
3571 	}
3572 
3573 	csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
3574 				fs_info->csum_size;
3575 	btrfs_calculate_block_csum_pages(fs_info, paddrs, csum);
3576 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3577 		goto zeroit;
3578 	return true;
3579 
3580 zeroit:
3581 	btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3582 				    bbio->mirror_num);
3583 	if (dev)
3584 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3585 	for (int i = 0; i < nr_steps; i++)
3586 		memzero_page(phys_to_page(paddrs[i]), offset_in_page(paddrs[i]), step);
3587 	return false;
3588 }
3589 
3590 /*
3591  * Perform a delayed iput on @inode.
3592  *
3593  * @inode: The inode we want to perform iput on
3594  *
3595  * This function uses the generic vfs_inode::i_count to track whether we should
3596  * just decrement it (in case it's > 1) or if this is the last iput then link
3597  * the inode to the delayed iput machinery. Delayed iputs are processed at
3598  * transaction commit time/superblock commit/cleaner kthread.
3599  */
btrfs_add_delayed_iput(struct btrfs_inode * inode)3600 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3601 {
3602 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3603 	unsigned long flags;
3604 
3605 	if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3606 		return;
3607 
3608 	WARN_ON_ONCE(test_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state));
3609 	atomic_inc(&fs_info->nr_delayed_iputs);
3610 	/*
3611 	 * Need to be irq safe here because we can be called from either an irq
3612 	 * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
3613 	 * context.
3614 	 */
3615 	spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
3616 	ASSERT(list_empty(&inode->delayed_iput));
3617 	list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3618 	spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
3619 	if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3620 		wake_up_process(fs_info->cleaner_kthread);
3621 }
3622 
run_delayed_iput_locked(struct btrfs_fs_info * fs_info,struct btrfs_inode * inode)3623 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3624 				    struct btrfs_inode *inode)
3625 {
3626 	list_del_init(&inode->delayed_iput);
3627 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3628 	iput(&inode->vfs_inode);
3629 	if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3630 		wake_up(&fs_info->delayed_iputs_wait);
3631 	spin_lock_irq(&fs_info->delayed_iput_lock);
3632 }
3633 
btrfs_run_delayed_iput(struct btrfs_fs_info * fs_info,struct btrfs_inode * inode)3634 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3635 				   struct btrfs_inode *inode)
3636 {
3637 	if (!list_empty(&inode->delayed_iput)) {
3638 		spin_lock_irq(&fs_info->delayed_iput_lock);
3639 		if (!list_empty(&inode->delayed_iput))
3640 			run_delayed_iput_locked(fs_info, inode);
3641 		spin_unlock_irq(&fs_info->delayed_iput_lock);
3642 	}
3643 }
3644 
btrfs_run_delayed_iputs(struct btrfs_fs_info * fs_info)3645 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3646 {
3647 	/*
3648 	 * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
3649 	 * calls btrfs_add_delayed_iput() and that needs to lock
3650 	 * fs_info->delayed_iput_lock. So we need to disable irqs here to
3651 	 * prevent a deadlock.
3652 	 */
3653 	spin_lock_irq(&fs_info->delayed_iput_lock);
3654 	while (!list_empty(&fs_info->delayed_iputs)) {
3655 		struct btrfs_inode *inode;
3656 
3657 		inode = list_first_entry(&fs_info->delayed_iputs,
3658 				struct btrfs_inode, delayed_iput);
3659 		run_delayed_iput_locked(fs_info, inode);
3660 		if (need_resched()) {
3661 			spin_unlock_irq(&fs_info->delayed_iput_lock);
3662 			cond_resched();
3663 			spin_lock_irq(&fs_info->delayed_iput_lock);
3664 		}
3665 	}
3666 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3667 }
3668 
3669 /*
3670  * Wait for flushing all delayed iputs
3671  *
3672  * @fs_info:  the filesystem
3673  *
3674  * This will wait on any delayed iputs that are currently running with KILLABLE
3675  * set.  Once they are all done running we will return, unless we are killed in
3676  * which case we return EINTR. This helps in user operations like fallocate etc
3677  * that might get blocked on the iputs.
3678  *
3679  * Return EINTR if we were killed, 0 if nothing's pending
3680  */
btrfs_wait_on_delayed_iputs(struct btrfs_fs_info * fs_info)3681 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3682 {
3683 	int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3684 			atomic_read(&fs_info->nr_delayed_iputs) == 0);
3685 	if (ret)
3686 		return -EINTR;
3687 	return 0;
3688 }
3689 
3690 /*
3691  * This creates an orphan entry for the given inode in case something goes wrong
3692  * in the middle of an unlink.
3693  */
btrfs_orphan_add(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)3694 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3695 		     struct btrfs_inode *inode)
3696 {
3697 	int ret;
3698 
3699 	ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3700 	if (unlikely(ret && ret != -EEXIST)) {
3701 		btrfs_abort_transaction(trans, ret);
3702 		return ret;
3703 	}
3704 
3705 	return 0;
3706 }
3707 
3708 /*
3709  * We have done the delete so we can go ahead and remove the orphan item for
3710  * this particular inode.
3711  */
btrfs_orphan_del(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)3712 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3713 			    struct btrfs_inode *inode)
3714 {
3715 	return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3716 }
3717 
3718 /*
3719  * this cleans up any orphans that may be left on the list from the last use
3720  * of this root.
3721  */
btrfs_orphan_cleanup(struct btrfs_root * root)3722 int btrfs_orphan_cleanup(struct btrfs_root *root)
3723 {
3724 	struct btrfs_fs_info *fs_info = root->fs_info;
3725 	BTRFS_PATH_AUTO_FREE(path);
3726 	struct extent_buffer *leaf;
3727 	struct btrfs_key key, found_key;
3728 	struct btrfs_trans_handle *trans;
3729 	u64 last_objectid = 0;
3730 	int ret = 0, nr_unlink = 0;
3731 
3732 	if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3733 		return 0;
3734 
3735 	path = btrfs_alloc_path();
3736 	if (!path) {
3737 		ret = -ENOMEM;
3738 		goto out;
3739 	}
3740 	path->reada = READA_BACK;
3741 
3742 	key.objectid = BTRFS_ORPHAN_OBJECTID;
3743 	key.type = BTRFS_ORPHAN_ITEM_KEY;
3744 	key.offset = (u64)-1;
3745 
3746 	while (1) {
3747 		struct btrfs_inode *inode;
3748 
3749 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3750 		if (ret < 0)
3751 			goto out;
3752 
3753 		/*
3754 		 * if ret == 0 means we found what we were searching for, which
3755 		 * is weird, but possible, so only screw with path if we didn't
3756 		 * find the key and see if we have stuff that matches
3757 		 */
3758 		if (ret > 0) {
3759 			ret = 0;
3760 			if (path->slots[0] == 0)
3761 				break;
3762 			path->slots[0]--;
3763 		}
3764 
3765 		/* pull out the item */
3766 		leaf = path->nodes[0];
3767 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3768 
3769 		/* make sure the item matches what we want */
3770 		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3771 			break;
3772 		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3773 			break;
3774 
3775 		/* release the path since we're done with it */
3776 		btrfs_release_path(path);
3777 
3778 		/*
3779 		 * this is where we are basically btrfs_lookup, without the
3780 		 * crossing root thing.  we store the inode number in the
3781 		 * offset of the orphan item.
3782 		 */
3783 
3784 		if (found_key.offset == last_objectid) {
3785 			/*
3786 			 * We found the same inode as before. This means we were
3787 			 * not able to remove its items via eviction triggered
3788 			 * by an iput(). A transaction abort may have happened,
3789 			 * due to -ENOSPC for example, so try to grab the error
3790 			 * that lead to a transaction abort, if any.
3791 			 */
3792 			btrfs_err(fs_info,
3793 				  "Error removing orphan entry, stopping orphan cleanup");
3794 			ret = BTRFS_FS_ERROR(fs_info) ?: -EINVAL;
3795 			goto out;
3796 		}
3797 
3798 		last_objectid = found_key.offset;
3799 
3800 		found_key.objectid = found_key.offset;
3801 		found_key.type = BTRFS_INODE_ITEM_KEY;
3802 		found_key.offset = 0;
3803 		inode = btrfs_iget(last_objectid, root);
3804 		if (IS_ERR(inode)) {
3805 			ret = PTR_ERR(inode);
3806 			inode = NULL;
3807 			if (ret != -ENOENT)
3808 				goto out;
3809 		}
3810 
3811 		if (!inode && root == fs_info->tree_root) {
3812 			struct btrfs_root *dead_root;
3813 			bool is_dead_root = false;
3814 
3815 			/*
3816 			 * This is an orphan in the tree root. Currently these
3817 			 * could come from 2 sources:
3818 			 *  a) a root (snapshot/subvolume) deletion in progress
3819 			 *  b) a free space cache inode
3820 			 * We need to distinguish those two, as the orphan item
3821 			 * for a root must not get deleted before the deletion
3822 			 * of the snapshot/subvolume's tree completes.
3823 			 *
3824 			 * btrfs_find_orphan_roots() ran before us, which has
3825 			 * found all deleted roots and loaded them into
3826 			 * fs_info->fs_roots_radix. So here we can find if an
3827 			 * orphan item corresponds to a deleted root by looking
3828 			 * up the root from that radix tree.
3829 			 */
3830 
3831 			spin_lock(&fs_info->fs_roots_radix_lock);
3832 			dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3833 							 (unsigned long)found_key.objectid);
3834 			if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3835 				is_dead_root = true;
3836 			spin_unlock(&fs_info->fs_roots_radix_lock);
3837 
3838 			if (is_dead_root) {
3839 				/* prevent this orphan from being found again */
3840 				key.offset = found_key.objectid - 1;
3841 				continue;
3842 			}
3843 
3844 		}
3845 
3846 		/*
3847 		 * If we have an inode with links, there are a couple of
3848 		 * possibilities:
3849 		 *
3850 		 * 1. We were halfway through creating fsverity metadata for the
3851 		 * file. In that case, the orphan item represents incomplete
3852 		 * fsverity metadata which must be cleaned up with
3853 		 * btrfs_drop_verity_items and deleting the orphan item.
3854 
3855 		 * 2. Old kernels (before v3.12) used to create an
3856 		 * orphan item for truncate indicating that there were possibly
3857 		 * extent items past i_size that needed to be deleted. In v3.12,
3858 		 * truncate was changed to update i_size in sync with the extent
3859 		 * items, but the (useless) orphan item was still created. Since
3860 		 * v4.18, we don't create the orphan item for truncate at all.
3861 		 *
3862 		 * So, this item could mean that we need to do a truncate, but
3863 		 * only if this filesystem was last used on a pre-v3.12 kernel
3864 		 * and was not cleanly unmounted. The odds of that are quite
3865 		 * slim, and it's a pain to do the truncate now, so just delete
3866 		 * the orphan item.
3867 		 *
3868 		 * It's also possible that this orphan item was supposed to be
3869 		 * deleted but wasn't. The inode number may have been reused,
3870 		 * but either way, we can delete the orphan item.
3871 		 */
3872 		if (!inode || inode->vfs_inode.i_nlink) {
3873 			if (inode) {
3874 				ret = btrfs_drop_verity_items(inode);
3875 				iput(&inode->vfs_inode);
3876 				inode = NULL;
3877 				if (ret)
3878 					goto out;
3879 			}
3880 			trans = btrfs_start_transaction(root, 1);
3881 			if (IS_ERR(trans)) {
3882 				ret = PTR_ERR(trans);
3883 				goto out;
3884 			}
3885 			btrfs_debug(fs_info, "auto deleting %Lu",
3886 				    found_key.objectid);
3887 			ret = btrfs_del_orphan_item(trans, root,
3888 						    found_key.objectid);
3889 			btrfs_end_transaction(trans);
3890 			if (ret)
3891 				goto out;
3892 			continue;
3893 		}
3894 
3895 		nr_unlink++;
3896 
3897 		/* this will do delete_inode and everything for us */
3898 		iput(&inode->vfs_inode);
3899 	}
3900 	/* release the path since we're done with it */
3901 	btrfs_release_path(path);
3902 
3903 	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3904 		trans = btrfs_join_transaction(root);
3905 		if (!IS_ERR(trans))
3906 			btrfs_end_transaction(trans);
3907 	}
3908 
3909 	if (nr_unlink)
3910 		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3911 
3912 out:
3913 	if (ret)
3914 		btrfs_err(fs_info, "could not do orphan cleanup %pe", ERR_PTR(ret));
3915 	return ret;
3916 }
3917 
3918 /*
3919  * Look ahead in the leaf for xattrs. If we don't find any then we know there
3920  * can't be any ACLs.
3921  *
3922  * @leaf:       the eb leaf where to search
3923  * @slot:       the slot the inode is in
3924  * @objectid:   the objectid of the inode
3925  *
3926  * Return true if there is xattr/ACL, false otherwise.
3927  */
acls_after_inode_item(struct extent_buffer * leaf,int slot,u64 objectid,int * first_xattr_slot)3928 static noinline bool acls_after_inode_item(struct extent_buffer *leaf,
3929 					   int slot, u64 objectid,
3930 					   int *first_xattr_slot)
3931 {
3932 	u32 nritems = btrfs_header_nritems(leaf);
3933 	struct btrfs_key found_key;
3934 	static u64 xattr_access = 0;
3935 	static u64 xattr_default = 0;
3936 	int scanned = 0;
3937 
3938 	if (!xattr_access) {
3939 		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3940 					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3941 		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3942 					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3943 	}
3944 
3945 	slot++;
3946 	*first_xattr_slot = -1;
3947 	while (slot < nritems) {
3948 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3949 
3950 		/* We found a different objectid, there must be no ACLs. */
3951 		if (found_key.objectid != objectid)
3952 			return false;
3953 
3954 		/* We found an xattr, assume we've got an ACL. */
3955 		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3956 			if (*first_xattr_slot == -1)
3957 				*first_xattr_slot = slot;
3958 			if (found_key.offset == xattr_access ||
3959 			    found_key.offset == xattr_default)
3960 				return true;
3961 		}
3962 
3963 		/*
3964 		 * We found a key greater than an xattr key, there can't be any
3965 		 * ACLs later on.
3966 		 */
3967 		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3968 			return false;
3969 
3970 		slot++;
3971 		scanned++;
3972 
3973 		/*
3974 		 * The item order goes like:
3975 		 * - inode
3976 		 * - inode backrefs
3977 		 * - xattrs
3978 		 * - extents,
3979 		 *
3980 		 * so if there are lots of hard links to an inode there can be
3981 		 * a lot of backrefs.  Don't waste time searching too hard,
3982 		 * this is just an optimization.
3983 		 */
3984 		if (scanned >= 8)
3985 			break;
3986 	}
3987 	/*
3988 	 * We hit the end of the leaf before we found an xattr or something
3989 	 * larger than an xattr.  We have to assume the inode has ACLs.
3990 	 */
3991 	if (*first_xattr_slot == -1)
3992 		*first_xattr_slot = slot;
3993 	return true;
3994 }
3995 
btrfs_init_file_extent_tree(struct btrfs_inode * inode)3996 static int btrfs_init_file_extent_tree(struct btrfs_inode *inode)
3997 {
3998 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3999 
4000 	if (WARN_ON_ONCE(inode->file_extent_tree))
4001 		return 0;
4002 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
4003 		return 0;
4004 	if (!S_ISREG(inode->vfs_inode.i_mode))
4005 		return 0;
4006 	if (btrfs_is_free_space_inode(inode))
4007 		return 0;
4008 
4009 	inode->file_extent_tree = kmalloc_obj(struct extent_io_tree);
4010 	if (!inode->file_extent_tree)
4011 		return -ENOMEM;
4012 
4013 	btrfs_extent_io_tree_init(fs_info, inode->file_extent_tree,
4014 				  IO_TREE_INODE_FILE_EXTENT);
4015 	/* Lockdep class is set only for the file extent tree. */
4016 	lockdep_set_class(&inode->file_extent_tree->lock, &file_extent_tree_class);
4017 
4018 	return 0;
4019 }
4020 
btrfs_add_inode_to_root(struct btrfs_inode * inode,bool prealloc)4021 static int btrfs_add_inode_to_root(struct btrfs_inode *inode, bool prealloc)
4022 {
4023 	struct btrfs_root *root = inode->root;
4024 	struct btrfs_inode *existing;
4025 	const u64 ino = btrfs_ino(inode);
4026 	int ret;
4027 
4028 	if (inode_unhashed(&inode->vfs_inode))
4029 		return 0;
4030 
4031 	if (prealloc) {
4032 		ret = xa_reserve(&root->inodes, ino, GFP_NOFS);
4033 		if (ret)
4034 			return ret;
4035 	}
4036 
4037 	existing = xa_store(&root->inodes, ino, inode, GFP_ATOMIC);
4038 
4039 	if (xa_is_err(existing)) {
4040 		ret = xa_err(existing);
4041 		ASSERT(ret != -EINVAL);
4042 		ASSERT(ret != -ENOMEM);
4043 		return ret;
4044 	} else if (existing) {
4045 		WARN_ON(!(inode_state_read_once(&existing->vfs_inode) & (I_WILL_FREE | I_FREEING)));
4046 	}
4047 
4048 	return 0;
4049 }
4050 
4051 /*
4052  * Read a locked inode from the btree into the in-memory inode and add it to
4053  * its root list/tree.
4054  *
4055  * On failure clean up the inode.
4056  */
btrfs_read_locked_inode(struct btrfs_inode * inode,struct btrfs_path * path)4057 static int btrfs_read_locked_inode(struct btrfs_inode *inode, struct btrfs_path *path)
4058 {
4059 	struct btrfs_root *root = inode->root;
4060 	struct btrfs_fs_info *fs_info = root->fs_info;
4061 	struct extent_buffer *leaf;
4062 	struct btrfs_inode_item *inode_item;
4063 	struct inode *vfs_inode = &inode->vfs_inode;
4064 	struct btrfs_key location;
4065 	unsigned long ptr;
4066 	int maybe_acls;
4067 	u32 rdev;
4068 	int ret;
4069 	bool filled = false;
4070 	int first_xattr_slot;
4071 
4072 	ret = btrfs_fill_inode(inode, &rdev);
4073 	if (!ret)
4074 		filled = true;
4075 
4076 	ASSERT(path);
4077 
4078 	btrfs_get_inode_key(inode, &location);
4079 
4080 	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
4081 	if (ret) {
4082 		/*
4083 		 * ret > 0 can come from btrfs_search_slot called by
4084 		 * btrfs_lookup_inode(), this means the inode was not found.
4085 		 */
4086 		if (ret > 0)
4087 			ret = -ENOENT;
4088 		goto out;
4089 	}
4090 
4091 	leaf = path->nodes[0];
4092 
4093 	if (filled)
4094 		goto cache_index;
4095 
4096 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4097 				    struct btrfs_inode_item);
4098 	vfs_inode->i_mode = btrfs_inode_mode(leaf, inode_item);
4099 	set_nlink(vfs_inode, btrfs_inode_nlink(leaf, inode_item));
4100 	i_uid_write(vfs_inode, btrfs_inode_uid(leaf, inode_item));
4101 	i_gid_write(vfs_inode, btrfs_inode_gid(leaf, inode_item));
4102 	btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
4103 
4104 	inode_set_atime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->atime),
4105 			btrfs_timespec_nsec(leaf, &inode_item->atime));
4106 
4107 	inode_set_mtime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->mtime),
4108 			btrfs_timespec_nsec(leaf, &inode_item->mtime));
4109 
4110 	inode_set_ctime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->ctime),
4111 			btrfs_timespec_nsec(leaf, &inode_item->ctime));
4112 
4113 	inode->i_otime_sec = btrfs_timespec_sec(leaf, &inode_item->otime);
4114 	inode->i_otime_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime);
4115 
4116 	inode_set_bytes(vfs_inode, btrfs_inode_nbytes(leaf, inode_item));
4117 	inode->generation = btrfs_inode_generation(leaf, inode_item);
4118 	inode->last_trans = btrfs_inode_transid(leaf, inode_item);
4119 
4120 	inode_set_iversion_queried(vfs_inode, btrfs_inode_sequence(leaf, inode_item));
4121 	vfs_inode->i_generation = inode->generation;
4122 	vfs_inode->i_rdev = 0;
4123 	rdev = btrfs_inode_rdev(leaf, inode_item);
4124 
4125 	if (S_ISDIR(vfs_inode->i_mode))
4126 		inode->index_cnt = (u64)-1;
4127 
4128 	btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
4129 				&inode->flags, &inode->ro_flags);
4130 
4131 cache_index:
4132 	btrfs_update_inode_mapping_flags(inode);
4133 	btrfs_set_inode_mapping_order(inode);
4134 
4135 	/*
4136 	 * If we were modified in the current generation and evicted from memory
4137 	 * and then re-read we need to do a full sync since we don't have any
4138 	 * idea about which extents were modified before we were evicted from
4139 	 * cache.
4140 	 *
4141 	 * This is required for both inode re-read from disk and delayed inode
4142 	 * in the delayed_nodes xarray.
4143 	 */
4144 	if (inode->last_trans == btrfs_get_fs_generation(fs_info))
4145 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
4146 
4147 	/*
4148 	 * We don't persist the id of the transaction where an unlink operation
4149 	 * against the inode was last made. So here we assume the inode might
4150 	 * have been evicted, and therefore the exact value of last_unlink_trans
4151 	 * lost, and set it to last_trans to avoid metadata inconsistencies
4152 	 * between the inode and its parent if the inode is fsync'ed and the log
4153 	 * replayed. For example, in the scenario:
4154 	 *
4155 	 * touch mydir/foo
4156 	 * ln mydir/foo mydir/bar
4157 	 * sync
4158 	 * unlink mydir/bar
4159 	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
4160 	 * xfs_io -c fsync mydir/foo
4161 	 * <power failure>
4162 	 * mount fs, triggers fsync log replay
4163 	 *
4164 	 * We must make sure that when we fsync our inode foo we also log its
4165 	 * parent inode, otherwise after log replay the parent still has the
4166 	 * dentry with the "bar" name but our inode foo has a link count of 1
4167 	 * and doesn't have an inode ref with the name "bar" anymore.
4168 	 *
4169 	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
4170 	 * but it guarantees correctness at the expense of occasional full
4171 	 * transaction commits on fsync if our inode is a directory, or if our
4172 	 * inode is not a directory, logging its parent unnecessarily.
4173 	 */
4174 	inode->last_unlink_trans = inode->last_trans;
4175 
4176 	/*
4177 	 * Same logic as for last_unlink_trans. We don't persist the generation
4178 	 * of the last transaction where this inode was used for a reflink
4179 	 * operation, so after eviction and reloading the inode we must be
4180 	 * pessimistic and assume the last transaction that modified the inode.
4181 	 */
4182 	inode->last_reflink_trans = inode->last_trans;
4183 
4184 	path->slots[0]++;
4185 	if (vfs_inode->i_nlink != 1 ||
4186 	    path->slots[0] >= btrfs_header_nritems(leaf))
4187 		goto cache_acl;
4188 
4189 	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4190 	if (location.objectid != btrfs_ino(inode))
4191 		goto cache_acl;
4192 
4193 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4194 	if (location.type == BTRFS_INODE_REF_KEY) {
4195 		struct btrfs_inode_ref *ref;
4196 
4197 		ref = (struct btrfs_inode_ref *)ptr;
4198 		inode->dir_index = btrfs_inode_ref_index(leaf, ref);
4199 	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4200 		struct btrfs_inode_extref *extref;
4201 
4202 		extref = (struct btrfs_inode_extref *)ptr;
4203 		inode->dir_index = btrfs_inode_extref_index(leaf, extref);
4204 	}
4205 cache_acl:
4206 	/*
4207 	 * try to precache a NULL acl entry for files that don't have
4208 	 * any xattrs or acls
4209 	 */
4210 	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4211 					   btrfs_ino(inode), &first_xattr_slot);
4212 	if (first_xattr_slot != -1) {
4213 		path->slots[0] = first_xattr_slot;
4214 		ret = btrfs_load_inode_props(inode, path);
4215 		if (ret)
4216 			btrfs_err(fs_info,
4217 				  "error loading props for ino %llu (root %llu): %pe",
4218 				  btrfs_ino(inode), btrfs_root_id(root), ERR_PTR(ret));
4219 	}
4220 
4221 	/*
4222 	 * We don't need the path anymore, so release it to avoid holding a read
4223 	 * lock on a leaf while calling btrfs_init_file_extent_tree(), which can
4224 	 * allocate memory that triggers reclaim (GFP_KERNEL) and cause a locking
4225 	 * dependency.
4226 	 */
4227 	btrfs_release_path(path);
4228 
4229 	ret = btrfs_init_file_extent_tree(inode);
4230 	if (ret)
4231 		goto out;
4232 	btrfs_inode_set_file_extent_range(inode, 0,
4233 			  round_up(i_size_read(vfs_inode), fs_info->sectorsize));
4234 
4235 	if (!maybe_acls)
4236 		cache_no_acl(vfs_inode);
4237 
4238 	switch (vfs_inode->i_mode & S_IFMT) {
4239 	case S_IFREG:
4240 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4241 		vfs_inode->i_fop = &btrfs_file_operations;
4242 		vfs_inode->i_op = &btrfs_file_inode_operations;
4243 		break;
4244 	case S_IFDIR:
4245 		vfs_inode->i_fop = &btrfs_dir_file_operations;
4246 		vfs_inode->i_op = &btrfs_dir_inode_operations;
4247 		break;
4248 	case S_IFLNK:
4249 		vfs_inode->i_op = &btrfs_symlink_inode_operations;
4250 		inode_nohighmem(vfs_inode);
4251 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4252 		break;
4253 	default:
4254 		vfs_inode->i_op = &btrfs_special_inode_operations;
4255 		init_special_inode(vfs_inode, vfs_inode->i_mode, rdev);
4256 		break;
4257 	}
4258 
4259 	btrfs_sync_inode_flags_to_i_flags(inode);
4260 
4261 	ret = btrfs_add_inode_to_root(inode, true);
4262 	if (ret)
4263 		goto out;
4264 
4265 	return 0;
4266 out:
4267 	/*
4268 	 * We may have a read locked leaf and iget_failed() triggers inode
4269 	 * eviction which needs to release the delayed inode and that needs
4270 	 * to lock the delayed inode's mutex. This can cause a ABBA deadlock
4271 	 * with a task running delayed items, as that require first locking
4272 	 * the delayed inode's mutex and then modifying its subvolume btree.
4273 	 * So release the path before iget_failed().
4274 	 */
4275 	btrfs_release_path(path);
4276 	iget_failed(vfs_inode);
4277 	return ret;
4278 }
4279 
4280 /*
4281  * given a leaf and an inode, copy the inode fields into the leaf
4282  */
fill_inode_item(struct btrfs_trans_handle * trans,struct extent_buffer * leaf,struct btrfs_inode_item * item,struct inode * inode)4283 static void fill_inode_item(struct btrfs_trans_handle *trans,
4284 			    struct extent_buffer *leaf,
4285 			    struct btrfs_inode_item *item,
4286 			    struct inode *inode)
4287 {
4288 	u64 flags;
4289 
4290 	btrfs_set_inode_uid(leaf, item, i_uid_read(inode));
4291 	btrfs_set_inode_gid(leaf, item, i_gid_read(inode));
4292 	btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
4293 	btrfs_set_inode_mode(leaf, item, inode->i_mode);
4294 	btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
4295 
4296 	btrfs_set_timespec_sec(leaf, &item->atime, inode_get_atime_sec(inode));
4297 	btrfs_set_timespec_nsec(leaf, &item->atime, inode_get_atime_nsec(inode));
4298 
4299 	btrfs_set_timespec_sec(leaf, &item->mtime, inode_get_mtime_sec(inode));
4300 	btrfs_set_timespec_nsec(leaf, &item->mtime, inode_get_mtime_nsec(inode));
4301 
4302 	btrfs_set_timespec_sec(leaf, &item->ctime, inode_get_ctime_sec(inode));
4303 	btrfs_set_timespec_nsec(leaf, &item->ctime, inode_get_ctime_nsec(inode));
4304 
4305 	btrfs_set_timespec_sec(leaf, &item->otime, BTRFS_I(inode)->i_otime_sec);
4306 	btrfs_set_timespec_nsec(leaf, &item->otime, BTRFS_I(inode)->i_otime_nsec);
4307 
4308 	btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
4309 	btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
4310 	btrfs_set_inode_sequence(leaf, item, inode_peek_iversion(inode));
4311 	btrfs_set_inode_transid(leaf, item, trans->transid);
4312 	btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
4313 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4314 					  BTRFS_I(inode)->ro_flags);
4315 	btrfs_set_inode_flags(leaf, item, flags);
4316 	btrfs_set_inode_block_group(leaf, item, 0);
4317 }
4318 
4319 /*
4320  * copy everything in the in-memory inode into the btree.
4321  */
btrfs_update_inode_item(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)4322 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4323 					    struct btrfs_inode *inode)
4324 {
4325 	struct btrfs_inode_item *inode_item;
4326 	BTRFS_PATH_AUTO_FREE(path);
4327 	struct extent_buffer *leaf;
4328 	struct btrfs_key key;
4329 	int ret;
4330 
4331 	path = btrfs_alloc_path();
4332 	if (!path)
4333 		return -ENOMEM;
4334 
4335 	btrfs_get_inode_key(inode, &key);
4336 	ret = btrfs_lookup_inode(trans, inode->root, path, &key, 1);
4337 	if (ret) {
4338 		if (ret > 0)
4339 			ret = -ENOENT;
4340 		return ret;
4341 	}
4342 
4343 	leaf = path->nodes[0];
4344 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4345 				    struct btrfs_inode_item);
4346 
4347 	fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4348 	btrfs_set_inode_last_trans(trans, inode);
4349 	return 0;
4350 }
4351 
4352 /*
4353  * copy everything in the in-memory inode into the btree.
4354  */
btrfs_update_inode(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)4355 int btrfs_update_inode(struct btrfs_trans_handle *trans,
4356 		       struct btrfs_inode *inode)
4357 {
4358 	struct btrfs_root *root = inode->root;
4359 	struct btrfs_fs_info *fs_info = root->fs_info;
4360 	int ret;
4361 
4362 	/*
4363 	 * If the inode is a free space inode, we can deadlock during commit
4364 	 * if we put it into the delayed code.
4365 	 *
4366 	 * The data relocation inode should also be directly updated
4367 	 * without delay
4368 	 */
4369 	if (!btrfs_is_free_space_inode(inode)
4370 	    && !btrfs_is_data_reloc_root(root)
4371 	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4372 		btrfs_update_root_times(trans, root);
4373 
4374 		ret = btrfs_delayed_update_inode(trans, inode);
4375 		if (!ret)
4376 			btrfs_set_inode_last_trans(trans, inode);
4377 		return ret;
4378 	}
4379 
4380 	return btrfs_update_inode_item(trans, inode);
4381 }
4382 
btrfs_update_inode_fallback(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)4383 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4384 				struct btrfs_inode *inode)
4385 {
4386 	int ret;
4387 
4388 	ret = btrfs_update_inode(trans, inode);
4389 	if (ret == -ENOSPC)
4390 		return btrfs_update_inode_item(trans, inode);
4391 	return ret;
4392 }
4393 
update_time_after_link_or_unlink(struct btrfs_inode * dir)4394 static void update_time_after_link_or_unlink(struct btrfs_inode *dir)
4395 {
4396 	struct timespec64 now;
4397 
4398 	/*
4399 	 * If we are replaying a log tree, we do not want to update the mtime
4400 	 * and ctime of the parent directory with the current time, since the
4401 	 * log replay procedure is responsible for setting them to their correct
4402 	 * values (the ones it had when the fsync was done).
4403 	 */
4404 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &dir->root->fs_info->flags))
4405 		return;
4406 
4407 	now = inode_set_ctime_current(&dir->vfs_inode);
4408 	inode_set_mtime_to_ts(&dir->vfs_inode, now);
4409 }
4410 
4411 /*
4412  * unlink helper that gets used here in inode.c and in the tree logging
4413  * recovery code.  It remove a link in a directory with a given name, and
4414  * also drops the back refs in the inode to the directory
4415  */
__btrfs_unlink_inode(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct btrfs_inode * inode,const struct fscrypt_str * name,struct btrfs_rename_ctx * rename_ctx)4416 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4417 				struct btrfs_inode *dir,
4418 				struct btrfs_inode *inode,
4419 				const struct fscrypt_str *name,
4420 				struct btrfs_rename_ctx *rename_ctx)
4421 {
4422 	struct btrfs_root *root = dir->root;
4423 	struct btrfs_fs_info *fs_info = root->fs_info;
4424 	struct btrfs_path *path;
4425 	int ret = 0;
4426 	struct btrfs_dir_item *di;
4427 	u64 index;
4428 	u64 ino = btrfs_ino(inode);
4429 	u64 dir_ino = btrfs_ino(dir);
4430 
4431 	path = btrfs_alloc_path();
4432 	if (!path)
4433 		return -ENOMEM;
4434 
4435 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4436 	if (IS_ERR_OR_NULL(di)) {
4437 		btrfs_free_path(path);
4438 		return di ? PTR_ERR(di) : -ENOENT;
4439 	}
4440 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4441 	/*
4442 	 * Down the call chains below we'll also need to allocate a path, so no
4443 	 * need to hold on to this one for longer than necessary.
4444 	 */
4445 	btrfs_free_path(path);
4446 	if (ret)
4447 		return ret;
4448 
4449 	/*
4450 	 * If we don't have dir index, we have to get it by looking up
4451 	 * the inode ref, since we get the inode ref, remove it directly,
4452 	 * it is unnecessary to do delayed deletion.
4453 	 *
4454 	 * But if we have dir index, needn't search inode ref to get it.
4455 	 * Since the inode ref is close to the inode item, it is better
4456 	 * that we delay to delete it, and just do this deletion when
4457 	 * we update the inode item.
4458 	 */
4459 	if (inode->dir_index) {
4460 		ret = btrfs_delayed_delete_inode_ref(inode);
4461 		if (!ret) {
4462 			index = inode->dir_index;
4463 			goto skip_backref;
4464 		}
4465 	}
4466 
4467 	ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4468 	if (unlikely(ret)) {
4469 		btrfs_crit(fs_info,
4470 	   "failed to delete reference to %.*s, root %llu inode %llu parent %llu",
4471 			   name->len, name->name, btrfs_root_id(root), ino, dir_ino);
4472 		btrfs_abort_transaction(trans, ret);
4473 		return ret;
4474 	}
4475 skip_backref:
4476 	if (rename_ctx)
4477 		rename_ctx->index = index;
4478 
4479 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4480 	if (unlikely(ret)) {
4481 		btrfs_abort_transaction(trans, ret);
4482 		return ret;
4483 	}
4484 
4485 	/*
4486 	 * If we are in a rename context, we don't need to update anything in the
4487 	 * log. That will be done later during the rename by btrfs_log_new_name().
4488 	 * Besides that, doing it here would only cause extra unnecessary btree
4489 	 * operations on the log tree, increasing latency for applications.
4490 	 */
4491 	if (!rename_ctx) {
4492 		btrfs_del_inode_ref_in_log(trans, name, inode, dir);
4493 		btrfs_del_dir_entries_in_log(trans, name, dir, index);
4494 	}
4495 
4496 	/*
4497 	 * If we have a pending delayed iput we could end up with the final iput
4498 	 * being run in btrfs-cleaner context.  If we have enough of these built
4499 	 * up we can end up burning a lot of time in btrfs-cleaner without any
4500 	 * way to throttle the unlinks.  Since we're currently holding a ref on
4501 	 * the inode we can run the delayed iput here without any issues as the
4502 	 * final iput won't be done until after we drop the ref we're currently
4503 	 * holding.
4504 	 */
4505 	btrfs_run_delayed_iput(fs_info, inode);
4506 
4507 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4508 	inode_inc_iversion(&inode->vfs_inode);
4509 	inode_set_ctime_current(&inode->vfs_inode);
4510 	inode_inc_iversion(&dir->vfs_inode);
4511 	update_time_after_link_or_unlink(dir);
4512 
4513 	return btrfs_update_inode(trans, dir);
4514 }
4515 
btrfs_unlink_inode(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct btrfs_inode * inode,const struct fscrypt_str * name)4516 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4517 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4518 		       const struct fscrypt_str *name)
4519 {
4520 	int ret;
4521 
4522 	ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4523 	if (!ret) {
4524 		drop_nlink(&inode->vfs_inode);
4525 		ret = btrfs_update_inode(trans, inode);
4526 	}
4527 	return ret;
4528 }
4529 
4530 /*
4531  * helper to start transaction for unlink and rmdir.
4532  *
4533  * unlink and rmdir are special in btrfs, they do not always free space, so
4534  * if we cannot make our reservations the normal way try and see if there is
4535  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4536  * allow the unlink to occur.
4537  */
__unlink_start_trans(struct btrfs_inode * dir)4538 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4539 {
4540 	struct btrfs_root *root = dir->root;
4541 
4542 	return btrfs_start_transaction_fallback_global_rsv(root,
4543 						   BTRFS_UNLINK_METADATA_UNITS);
4544 }
4545 
btrfs_unlink(struct inode * dir,struct dentry * dentry)4546 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4547 {
4548 	struct btrfs_trans_handle *trans;
4549 	struct inode *inode = d_inode(dentry);
4550 	int ret;
4551 	struct fscrypt_name fname;
4552 
4553 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4554 	if (ret)
4555 		return ret;
4556 
4557 	/* This needs to handle no-key deletions later on */
4558 
4559 	trans = __unlink_start_trans(BTRFS_I(dir));
4560 	if (IS_ERR(trans)) {
4561 		ret = PTR_ERR(trans);
4562 		goto fscrypt_free;
4563 	}
4564 
4565 	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4566 				false);
4567 
4568 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4569 				 &fname.disk_name);
4570 	if (ret)
4571 		goto end_trans;
4572 
4573 	if (inode->i_nlink == 0) {
4574 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4575 		if (ret)
4576 			goto end_trans;
4577 	}
4578 
4579 end_trans:
4580 	btrfs_end_transaction(trans);
4581 	btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4582 fscrypt_free:
4583 	fscrypt_free_filename(&fname);
4584 	return ret;
4585 }
4586 
btrfs_unlink_subvol(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct dentry * dentry)4587 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4588 			       struct btrfs_inode *dir, struct dentry *dentry)
4589 {
4590 	struct btrfs_root *root = dir->root;
4591 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4592 	BTRFS_PATH_AUTO_FREE(path);
4593 	struct extent_buffer *leaf;
4594 	struct btrfs_dir_item *di;
4595 	struct btrfs_key key;
4596 	u64 index;
4597 	int ret;
4598 	u64 objectid;
4599 	u64 dir_ino = btrfs_ino(dir);
4600 	struct fscrypt_name fname;
4601 
4602 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4603 	if (ret)
4604 		return ret;
4605 
4606 	/* This needs to handle no-key deletions later on */
4607 
4608 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4609 		objectid = btrfs_root_id(inode->root);
4610 	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4611 		objectid = inode->ref_root_id;
4612 	} else {
4613 		WARN_ON(1);
4614 		fscrypt_free_filename(&fname);
4615 		return -EINVAL;
4616 	}
4617 
4618 	path = btrfs_alloc_path();
4619 	if (!path) {
4620 		ret = -ENOMEM;
4621 		goto out;
4622 	}
4623 
4624 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4625 				   &fname.disk_name, -1);
4626 	if (IS_ERR_OR_NULL(di)) {
4627 		ret = di ? PTR_ERR(di) : -ENOENT;
4628 		goto out;
4629 	}
4630 
4631 	leaf = path->nodes[0];
4632 	btrfs_dir_item_key_to_cpu(leaf, di, &key);
4633 	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4634 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4635 	if (unlikely(ret)) {
4636 		btrfs_abort_transaction(trans, ret);
4637 		goto out;
4638 	}
4639 	btrfs_release_path(path);
4640 
4641 	/*
4642 	 * This is a placeholder inode for a subvolume we didn't have a
4643 	 * reference to at the time of the snapshot creation.  In the meantime
4644 	 * we could have renamed the real subvol link into our snapshot, so
4645 	 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4646 	 * Instead simply lookup the dir_index_item for this entry so we can
4647 	 * remove it.  Otherwise we know we have a ref to the root and we can
4648 	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4649 	 */
4650 	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4651 		di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4652 		if (IS_ERR(di)) {
4653 			ret = PTR_ERR(di);
4654 			btrfs_abort_transaction(trans, ret);
4655 			goto out;
4656 		}
4657 
4658 		leaf = path->nodes[0];
4659 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4660 		index = key.offset;
4661 		btrfs_release_path(path);
4662 	} else {
4663 		ret = btrfs_del_root_ref(trans, objectid,
4664 					 btrfs_root_id(root), dir_ino,
4665 					 &index, &fname.disk_name);
4666 		if (unlikely(ret)) {
4667 			btrfs_abort_transaction(trans, ret);
4668 			goto out;
4669 		}
4670 	}
4671 
4672 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4673 	if (unlikely(ret)) {
4674 		btrfs_abort_transaction(trans, ret);
4675 		goto out;
4676 	}
4677 
4678 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4679 	inode_inc_iversion(&dir->vfs_inode);
4680 	inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4681 	ret = btrfs_update_inode_fallback(trans, dir);
4682 	if (ret)
4683 		btrfs_abort_transaction(trans, ret);
4684 out:
4685 	fscrypt_free_filename(&fname);
4686 	return ret;
4687 }
4688 
4689 /*
4690  * Helper to check if the subvolume references other subvolumes or if it's
4691  * default.
4692  */
may_destroy_subvol(struct btrfs_root * root)4693 static noinline int may_destroy_subvol(struct btrfs_root *root)
4694 {
4695 	struct btrfs_fs_info *fs_info = root->fs_info;
4696 	BTRFS_PATH_AUTO_FREE(path);
4697 	struct btrfs_dir_item *di;
4698 	struct btrfs_key key;
4699 	struct fscrypt_str name = FSTR_INIT("default", 7);
4700 	u64 dir_id;
4701 	int ret;
4702 
4703 	path = btrfs_alloc_path();
4704 	if (!path)
4705 		return -ENOMEM;
4706 
4707 	/* Make sure this root isn't set as the default subvol */
4708 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4709 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4710 				   dir_id, &name, 0);
4711 	if (!IS_ERR_OR_NULL(di)) {
4712 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4713 		if (key.objectid == btrfs_root_id(root)) {
4714 			ret = -EPERM;
4715 			btrfs_err(fs_info,
4716 				  "deleting default subvolume %llu is not allowed",
4717 				  key.objectid);
4718 			return ret;
4719 		}
4720 		btrfs_release_path(path);
4721 	}
4722 
4723 	key.objectid = btrfs_root_id(root);
4724 	key.type = BTRFS_ROOT_REF_KEY;
4725 	key.offset = (u64)-1;
4726 
4727 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4728 	if (ret < 0)
4729 		return ret;
4730 	if (unlikely(ret == 0)) {
4731 		/*
4732 		 * Key with offset -1 found, there would have to exist a root
4733 		 * with such id, but this is out of valid range.
4734 		 */
4735 		return -EUCLEAN;
4736 	}
4737 
4738 	ret = 0;
4739 	if (path->slots[0] > 0) {
4740 		path->slots[0]--;
4741 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4742 		if (key.objectid == btrfs_root_id(root) && key.type == BTRFS_ROOT_REF_KEY)
4743 			ret = -ENOTEMPTY;
4744 	}
4745 
4746 	return ret;
4747 }
4748 
4749 /* Delete all dentries for inodes belonging to the root */
btrfs_prune_dentries(struct btrfs_root * root)4750 static void btrfs_prune_dentries(struct btrfs_root *root)
4751 {
4752 	struct btrfs_fs_info *fs_info = root->fs_info;
4753 	struct btrfs_inode *inode;
4754 	u64 min_ino = 0;
4755 
4756 	if (!BTRFS_FS_ERROR(fs_info))
4757 		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4758 
4759 	inode = btrfs_find_first_inode(root, min_ino);
4760 	while (inode) {
4761 		if (icount_read_once(&inode->vfs_inode) > 1)
4762 			d_prune_aliases(&inode->vfs_inode);
4763 
4764 		min_ino = btrfs_ino(inode) + 1;
4765 		/*
4766 		 * btrfs_drop_inode() will have it removed from the inode
4767 		 * cache when its usage count hits zero.
4768 		 */
4769 		iput(&inode->vfs_inode);
4770 		cond_resched();
4771 		inode = btrfs_find_first_inode(root, min_ino);
4772 	}
4773 }
4774 
btrfs_delete_subvolume(struct btrfs_inode * dir,struct dentry * dentry)4775 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4776 {
4777 	struct btrfs_root *root = dir->root;
4778 	struct btrfs_fs_info *fs_info = root->fs_info;
4779 	struct inode *inode = d_inode(dentry);
4780 	struct btrfs_root *dest = BTRFS_I(inode)->root;
4781 	struct btrfs_trans_handle *trans;
4782 	struct btrfs_block_rsv block_rsv;
4783 	u64 root_flags;
4784 	u64 qgroup_reserved = 0;
4785 	int ret;
4786 
4787 	down_write(&fs_info->subvol_sem);
4788 
4789 	/*
4790 	 * Don't allow to delete a subvolume with send in progress. This is
4791 	 * inside the inode lock so the error handling that has to drop the bit
4792 	 * again is not run concurrently.
4793 	 */
4794 	spin_lock(&dest->root_item_lock);
4795 	if (dest->send_in_progress) {
4796 		spin_unlock(&dest->root_item_lock);
4797 		btrfs_warn(fs_info,
4798 			   "attempt to delete subvolume %llu during send",
4799 			   btrfs_root_id(dest));
4800 		ret = -EPERM;
4801 		goto out_up_write;
4802 	}
4803 	if (atomic_read(&dest->nr_swapfiles)) {
4804 		spin_unlock(&dest->root_item_lock);
4805 		btrfs_warn(fs_info,
4806 			   "attempt to delete subvolume %llu with active swapfile",
4807 			   btrfs_root_id(dest));
4808 		ret = -EPERM;
4809 		goto out_up_write;
4810 	}
4811 	root_flags = btrfs_root_flags(&dest->root_item);
4812 	btrfs_set_root_flags(&dest->root_item,
4813 			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4814 	spin_unlock(&dest->root_item_lock);
4815 
4816 	ret = may_destroy_subvol(dest);
4817 	if (ret)
4818 		goto out_undead;
4819 
4820 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4821 	/*
4822 	 * One for dir inode,
4823 	 * two for dir entries,
4824 	 * two for root ref/backref.
4825 	 */
4826 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4827 	if (ret)
4828 		goto out_undead;
4829 	qgroup_reserved = block_rsv.qgroup_rsv_reserved;
4830 
4831 	trans = btrfs_start_transaction(root, 0);
4832 	if (IS_ERR(trans)) {
4833 		ret = PTR_ERR(trans);
4834 		goto out_release;
4835 	}
4836 	btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
4837 	qgroup_reserved = 0;
4838 	trans->block_rsv = &block_rsv;
4839 	trans->bytes_reserved = block_rsv.size;
4840 
4841 	btrfs_record_snapshot_destroy(trans, dir);
4842 
4843 	ret = btrfs_unlink_subvol(trans, dir, dentry);
4844 	if (unlikely(ret)) {
4845 		btrfs_abort_transaction(trans, ret);
4846 		goto out_end_trans;
4847 	}
4848 
4849 	ret = btrfs_record_root_in_trans(trans, dest);
4850 	if (unlikely(ret)) {
4851 		btrfs_abort_transaction(trans, ret);
4852 		goto out_end_trans;
4853 	}
4854 
4855 	memset(&dest->root_item.drop_progress, 0,
4856 		sizeof(dest->root_item.drop_progress));
4857 	btrfs_set_root_drop_level(&dest->root_item, 0);
4858 	btrfs_set_root_refs(&dest->root_item, 0);
4859 
4860 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4861 		ret = btrfs_insert_orphan_item(trans,
4862 					fs_info->tree_root,
4863 					btrfs_root_id(dest));
4864 		if (unlikely(ret)) {
4865 			btrfs_abort_transaction(trans, ret);
4866 			goto out_end_trans;
4867 		}
4868 	}
4869 
4870 	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4871 				     BTRFS_UUID_KEY_SUBVOL, btrfs_root_id(dest));
4872 	if (unlikely(ret && ret != -ENOENT)) {
4873 		btrfs_abort_transaction(trans, ret);
4874 		goto out_end_trans;
4875 	}
4876 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4877 		ret = btrfs_uuid_tree_remove(trans,
4878 					  dest->root_item.received_uuid,
4879 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4880 					  btrfs_root_id(dest));
4881 		if (unlikely(ret && ret != -ENOENT)) {
4882 			btrfs_abort_transaction(trans, ret);
4883 			goto out_end_trans;
4884 		}
4885 	}
4886 
4887 	free_anon_bdev(dest->anon_dev);
4888 	dest->anon_dev = 0;
4889 out_end_trans:
4890 	trans->block_rsv = NULL;
4891 	trans->bytes_reserved = 0;
4892 	ret = btrfs_end_transaction(trans);
4893 	inode->i_flags |= S_DEAD;
4894 out_release:
4895 	btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
4896 	if (qgroup_reserved)
4897 		btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
4898 out_undead:
4899 	if (ret) {
4900 		spin_lock(&dest->root_item_lock);
4901 		root_flags = btrfs_root_flags(&dest->root_item);
4902 		btrfs_set_root_flags(&dest->root_item,
4903 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4904 		spin_unlock(&dest->root_item_lock);
4905 	}
4906 out_up_write:
4907 	up_write(&fs_info->subvol_sem);
4908 	if (!ret) {
4909 		d_invalidate(dentry);
4910 		btrfs_prune_dentries(dest);
4911 		ASSERT(dest->send_in_progress == 0);
4912 	}
4913 
4914 	return ret;
4915 }
4916 
btrfs_rmdir(struct inode * vfs_dir,struct dentry * dentry)4917 static int btrfs_rmdir(struct inode *vfs_dir, struct dentry *dentry)
4918 {
4919 	struct btrfs_inode *dir = BTRFS_I(vfs_dir);
4920 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4921 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4922 	int ret = 0;
4923 	struct btrfs_trans_handle *trans;
4924 	struct fscrypt_name fname;
4925 
4926 	if (inode->vfs_inode.i_size > BTRFS_EMPTY_DIR_SIZE)
4927 		return -ENOTEMPTY;
4928 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4929 		if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4930 			btrfs_err(fs_info,
4931 			"extent tree v2 doesn't support snapshot deletion yet");
4932 			return -EOPNOTSUPP;
4933 		}
4934 		return btrfs_delete_subvolume(dir, dentry);
4935 	}
4936 
4937 	ret = fscrypt_setup_filename(vfs_dir, &dentry->d_name, 1, &fname);
4938 	if (ret)
4939 		return ret;
4940 
4941 	/* This needs to handle no-key deletions later on */
4942 
4943 	trans = __unlink_start_trans(dir);
4944 	if (IS_ERR(trans)) {
4945 		ret = PTR_ERR(trans);
4946 		goto out_notrans;
4947 	}
4948 
4949 	/*
4950 	 * Propagate the last_unlink_trans value of the deleted dir to its
4951 	 * parent directory. This is to prevent an unrecoverable log tree in the
4952 	 * case we do something like this:
4953 	 * 1) create dir foo
4954 	 * 2) create snapshot under dir foo
4955 	 * 3) delete the snapshot
4956 	 * 4) rmdir foo
4957 	 * 5) mkdir foo
4958 	 * 6) fsync foo or some file inside foo
4959 	 *
4960 	 * This is because we can't unlink other roots when replaying the dir
4961 	 * deletes for directory foo.
4962 	 */
4963 	if (inode->last_unlink_trans >= trans->transid)
4964 		btrfs_record_snapshot_destroy(trans, dir);
4965 
4966 	if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4967 		ret = btrfs_unlink_subvol(trans, dir, dentry);
4968 		goto out;
4969 	}
4970 
4971 	ret = btrfs_orphan_add(trans, inode);
4972 	if (ret)
4973 		goto out;
4974 
4975 	btrfs_record_unlink_dir(trans, dir, inode, false);
4976 
4977 	/* now the directory is empty */
4978 	ret = btrfs_unlink_inode(trans, dir, inode, &fname.disk_name);
4979 	if (!ret)
4980 		btrfs_i_size_write(inode, 0);
4981 out:
4982 	btrfs_end_transaction(trans);
4983 out_notrans:
4984 	btrfs_btree_balance_dirty(fs_info);
4985 	fscrypt_free_filename(&fname);
4986 
4987 	return ret;
4988 }
4989 
is_inside_block(u64 bytenr,u64 blockstart,u32 blocksize)4990 static bool is_inside_block(u64 bytenr, u64 blockstart, u32 blocksize)
4991 {
4992 	ASSERT(IS_ALIGNED(blockstart, blocksize), "blockstart=%llu blocksize=%u",
4993 		blockstart, blocksize);
4994 
4995 	if (blockstart <= bytenr && bytenr <= blockstart + blocksize - 1)
4996 		return true;
4997 	return false;
4998 }
4999 
truncate_block_zero_beyond_eof(struct btrfs_inode * inode,u64 start)5000 static int truncate_block_zero_beyond_eof(struct btrfs_inode *inode, u64 start)
5001 {
5002 	const pgoff_t index = (start >> PAGE_SHIFT);
5003 	struct address_space *mapping = inode->vfs_inode.i_mapping;
5004 	struct folio *folio;
5005 	u64 zero_start;
5006 	u64 zero_end;
5007 	int ret = 0;
5008 
5009 again:
5010 	folio = filemap_lock_folio(mapping, index);
5011 	/* No folio present. */
5012 	if (IS_ERR(folio))
5013 		return 0;
5014 
5015 	if (!folio_test_uptodate(folio)) {
5016 		ret = btrfs_read_folio(NULL, folio);
5017 		folio_lock(folio);
5018 		if (folio->mapping != mapping) {
5019 			folio_unlock(folio);
5020 			folio_put(folio);
5021 			goto again;
5022 		}
5023 		if (unlikely(!folio_test_uptodate(folio))) {
5024 			ret = -EIO;
5025 			goto out_unlock;
5026 		}
5027 	}
5028 	folio_wait_writeback(folio);
5029 
5030 	/*
5031 	 * We do not need to lock extents nor wait for OE, as it's already
5032 	 * beyond EOF.
5033 	 */
5034 
5035 	zero_start = max_t(u64, folio_pos(folio), start);
5036 	zero_end = folio_next_pos(folio);
5037 	folio_zero_range(folio, zero_start - folio_pos(folio),
5038 			 zero_end - zero_start);
5039 
5040 out_unlock:
5041 	folio_unlock(folio);
5042 	folio_put(folio);
5043 	return ret;
5044 }
5045 
5046 /*
5047  * Handle the truncation of a fs block.
5048  *
5049  * @inode  - inode that we're zeroing
5050  * @offset - the file offset of the block to truncate
5051  *           The value must be inside [@start, @end], and the function will do
5052  *           extra checks if the block that covers @offset needs to be zeroed.
5053  * @start  - the start file offset of the range we want to zero
5054  * @end    - the end (inclusive) file offset of the range we want to zero.
5055  *
5056  * If the range is not block aligned, read out the folio that covers @offset,
5057  * and if needed zero blocks that are inside the folio and covered by [@start, @end).
5058  * If @start or @end + 1 lands inside a block, that block will be marked dirty
5059  * for writeback.
5060  *
5061  * This is utilized by hole punch, zero range, file expansion.
5062  */
btrfs_truncate_block(struct btrfs_inode * inode,u64 offset,u64 start,u64 end)5063 int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 end)
5064 {
5065 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5066 	struct address_space *mapping = inode->vfs_inode.i_mapping;
5067 	struct extent_io_tree *io_tree = &inode->io_tree;
5068 	struct btrfs_ordered_extent *ordered;
5069 	struct extent_state *cached_state = NULL;
5070 	struct extent_changeset *data_reserved = NULL;
5071 	bool only_release_metadata = false;
5072 	u32 blocksize = fs_info->sectorsize;
5073 	pgoff_t index = (offset >> PAGE_SHIFT);
5074 	struct folio *folio;
5075 	gfp_t mask = btrfs_alloc_write_mask(mapping);
5076 	int ret = 0;
5077 	const bool in_head_block = is_inside_block(offset, round_down(start, blocksize),
5078 						   blocksize);
5079 	const bool in_tail_block = is_inside_block(offset, round_down(end, blocksize),
5080 						   blocksize);
5081 	bool need_truncate_head = false;
5082 	bool need_truncate_tail = false;
5083 	u64 zero_start;
5084 	u64 zero_end;
5085 	u64 block_start;
5086 	u64 block_end;
5087 
5088 	/* @offset should be inside the range. */
5089 	ASSERT(start <= offset && offset <= end, "offset=%llu start=%llu end=%llu",
5090 	       offset, start, end);
5091 
5092 	/* The range is aligned at both ends. */
5093 	if (IS_ALIGNED(start, blocksize) && IS_ALIGNED(end + 1, blocksize)) {
5094 		/*
5095 		 * For block size < page size case, we may have polluted blocks
5096 		 * beyond EOF. So we also need to zero them out.
5097 		 */
5098 		if (end == (u64)-1 && blocksize < PAGE_SIZE)
5099 			ret = truncate_block_zero_beyond_eof(inode, start);
5100 		goto out;
5101 	}
5102 
5103 	/*
5104 	 * @offset may not be inside the head nor tail block. In that case we
5105 	 * don't need to do anything.
5106 	 */
5107 	if (!in_head_block && !in_tail_block)
5108 		goto out;
5109 
5110 	/*
5111 	 * Skip the truncation if the range in the target block is already aligned.
5112 	 * The seemingly complex check will also handle the same block case.
5113 	 */
5114 	if (in_head_block && !IS_ALIGNED(start, blocksize))
5115 		need_truncate_head = true;
5116 	if (in_tail_block && !IS_ALIGNED(end + 1, blocksize))
5117 		need_truncate_tail = true;
5118 	if (!need_truncate_head && !need_truncate_tail)
5119 		goto out;
5120 
5121 	block_start = round_down(offset, blocksize);
5122 	block_end = block_start + blocksize - 1;
5123 
5124 	ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
5125 					  blocksize, false);
5126 	if (ret < 0) {
5127 		size_t write_bytes = blocksize;
5128 
5129 		if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
5130 			/* For nocow case, no need to reserve data space. */
5131 			ASSERT(write_bytes == blocksize, "write_bytes=%zu blocksize=%u",
5132 			       write_bytes, blocksize);
5133 			only_release_metadata = true;
5134 		} else {
5135 			goto out;
5136 		}
5137 	}
5138 	ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
5139 	if (ret < 0) {
5140 		if (!only_release_metadata)
5141 			btrfs_free_reserved_data_space(inode, data_reserved,
5142 						       block_start, blocksize);
5143 		goto out;
5144 	}
5145 again:
5146 	folio = __filemap_get_folio(mapping, index,
5147 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
5148 	if (IS_ERR(folio)) {
5149 		if (only_release_metadata)
5150 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5151 		else
5152 			btrfs_delalloc_release_space(inode, data_reserved,
5153 						     block_start, blocksize, true);
5154 		btrfs_delalloc_release_extents(inode, blocksize);
5155 		ret = PTR_ERR(folio);
5156 		goto out;
5157 	}
5158 
5159 	if (!folio_test_uptodate(folio)) {
5160 		ret = btrfs_read_folio(NULL, folio);
5161 		folio_lock(folio);
5162 		if (folio->mapping != mapping) {
5163 			folio_unlock(folio);
5164 			folio_put(folio);
5165 			goto again;
5166 		}
5167 		if (unlikely(!folio_test_uptodate(folio))) {
5168 			ret = -EIO;
5169 			goto out_unlock;
5170 		}
5171 	}
5172 
5173 	/*
5174 	 * We unlock the page after the io is completed and then re-lock it
5175 	 * above.  release_folio() could have come in between that and cleared
5176 	 * folio private, but left the page in the mapping.  Set the page mapped
5177 	 * here to make sure it's properly set for the subpage stuff.
5178 	 */
5179 	ret = set_folio_extent_mapped(folio);
5180 	if (ret < 0)
5181 		goto out_unlock;
5182 
5183 	folio_wait_writeback(folio);
5184 
5185 	btrfs_lock_extent(io_tree, block_start, block_end, &cached_state);
5186 
5187 	ordered = btrfs_lookup_ordered_extent(inode, block_start);
5188 	if (ordered) {
5189 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5190 		folio_unlock(folio);
5191 		folio_put(folio);
5192 		btrfs_start_ordered_extent(ordered);
5193 		btrfs_put_ordered_extent(ordered);
5194 		goto again;
5195 	}
5196 
5197 	ret = btrfs_reset_extent_delalloc(inode, block_start, block_end, 0, &cached_state);
5198 	if (ret) {
5199 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5200 		goto out_unlock;
5201 	}
5202 
5203 	if (end == (u64)-1) {
5204 		/*
5205 		 * We're truncating beyond EOF, the remaining blocks normally are
5206 		 * already holes thus no need to zero again, but it's possible for
5207 		 * fs block size < page size cases to have memory mapped writes
5208 		 * to pollute ranges beyond EOF.
5209 		 *
5210 		 * In that case although such polluted blocks beyond EOF will
5211 		 * not reach disk, it still affects our page caches.
5212 		 */
5213 		zero_start = max_t(u64, folio_pos(folio), start);
5214 		zero_end = min_t(u64, folio_next_pos(folio) - 1, end);
5215 	} else {
5216 		zero_start = max_t(u64, block_start, start);
5217 		zero_end = min_t(u64, block_end, end);
5218 	}
5219 	folio_zero_range(folio, zero_start - folio_pos(folio),
5220 			 zero_end - zero_start + 1);
5221 
5222 	btrfs_folio_set_dirty(fs_info, folio, block_start,
5223 			      block_end + 1 - block_start);
5224 
5225 	if (only_release_metadata)
5226 		btrfs_set_extent_bit(&inode->io_tree, block_start, block_end,
5227 				     EXTENT_NORESERVE, &cached_state);
5228 
5229 	btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5230 
5231 out_unlock:
5232 	if (ret) {
5233 		if (only_release_metadata)
5234 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5235 		else
5236 			btrfs_delalloc_release_space(inode, data_reserved,
5237 					block_start, blocksize, true);
5238 	}
5239 	btrfs_delalloc_release_extents(inode, blocksize);
5240 	folio_unlock(folio);
5241 	folio_put(folio);
5242 out:
5243 	if (only_release_metadata)
5244 		btrfs_check_nocow_unlock(inode);
5245 	extent_changeset_free(data_reserved);
5246 	return ret;
5247 }
5248 
maybe_insert_hole(struct btrfs_inode * inode,u64 offset,u64 len)5249 static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
5250 {
5251 	struct btrfs_root *root = inode->root;
5252 	struct btrfs_fs_info *fs_info = root->fs_info;
5253 	struct btrfs_trans_handle *trans;
5254 	struct btrfs_drop_extents_args drop_args = { 0 };
5255 	int ret;
5256 
5257 	/*
5258 	 * If NO_HOLES is enabled, we don't need to do anything.
5259 	 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5260 	 * or btrfs_update_inode() will be called, which guarantee that the next
5261 	 * fsync will know this inode was changed and needs to be logged.
5262 	 */
5263 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
5264 		return 0;
5265 
5266 	/*
5267 	 * 1 - for the one we're dropping
5268 	 * 1 - for the one we're adding
5269 	 * 1 - for updating the inode.
5270 	 */
5271 	trans = btrfs_start_transaction(root, 3);
5272 	if (IS_ERR(trans))
5273 		return PTR_ERR(trans);
5274 
5275 	drop_args.start = offset;
5276 	drop_args.end = offset + len;
5277 	drop_args.drop_cache = true;
5278 
5279 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5280 	if (unlikely(ret)) {
5281 		btrfs_abort_transaction(trans, ret);
5282 		btrfs_end_transaction(trans);
5283 		return ret;
5284 	}
5285 
5286 	ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5287 	if (ret) {
5288 		btrfs_abort_transaction(trans, ret);
5289 	} else {
5290 		btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5291 		btrfs_update_inode(trans, inode);
5292 	}
5293 	btrfs_end_transaction(trans);
5294 	return ret;
5295 }
5296 
5297 /*
5298  * This function puts in dummy file extents for the area we're creating a hole
5299  * for.  So if we are truncating this file to a larger size we need to insert
5300  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5301  * the range between oldsize and size
5302  */
btrfs_cont_expand(struct btrfs_inode * inode,loff_t oldsize,loff_t size)5303 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5304 {
5305 	struct btrfs_root *root = inode->root;
5306 	struct btrfs_fs_info *fs_info = root->fs_info;
5307 	struct extent_io_tree *io_tree = &inode->io_tree;
5308 	struct extent_map *em = NULL;
5309 	struct extent_state *cached_state = NULL;
5310 	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5311 	u64 block_end = ALIGN(size, fs_info->sectorsize);
5312 	u64 last_byte;
5313 	u64 cur_offset;
5314 	u64 hole_size;
5315 	int ret = 0;
5316 
5317 	/*
5318 	 * If our size started in the middle of a block we need to zero out the
5319 	 * rest of the block before we expand the i_size, otherwise we could
5320 	 * expose stale data.
5321 	 */
5322 	ret = btrfs_truncate_block(inode, oldsize, oldsize, -1);
5323 	if (ret)
5324 		return ret;
5325 
5326 	if (size <= hole_start)
5327 		return 0;
5328 
5329 	btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5330 					   &cached_state);
5331 	cur_offset = hole_start;
5332 	while (1) {
5333 		em = btrfs_get_extent(inode, NULL, cur_offset, block_end - cur_offset);
5334 		if (IS_ERR(em)) {
5335 			ret = PTR_ERR(em);
5336 			em = NULL;
5337 			break;
5338 		}
5339 		last_byte = min(btrfs_extent_map_end(em), block_end);
5340 		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5341 		hole_size = last_byte - cur_offset;
5342 
5343 		if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
5344 			struct extent_map *hole_em;
5345 
5346 			ret = maybe_insert_hole(inode, cur_offset, hole_size);
5347 			if (ret)
5348 				break;
5349 
5350 			ret = btrfs_inode_set_file_extent_range(inode,
5351 							cur_offset, hole_size);
5352 			if (ret)
5353 				break;
5354 
5355 			hole_em = btrfs_alloc_extent_map();
5356 			if (!hole_em) {
5357 				btrfs_drop_extent_map_range(inode, cur_offset,
5358 						    cur_offset + hole_size - 1,
5359 						    false);
5360 				btrfs_set_inode_full_sync(inode);
5361 				goto next;
5362 			}
5363 			hole_em->start = cur_offset;
5364 			hole_em->len = hole_size;
5365 
5366 			hole_em->disk_bytenr = EXTENT_MAP_HOLE;
5367 			hole_em->disk_num_bytes = 0;
5368 			hole_em->ram_bytes = hole_size;
5369 			hole_em->generation = btrfs_get_fs_generation(fs_info);
5370 
5371 			ret = btrfs_replace_extent_map_range(inode, hole_em, true);
5372 			btrfs_free_extent_map(hole_em);
5373 		} else {
5374 			ret = btrfs_inode_set_file_extent_range(inode,
5375 							cur_offset, hole_size);
5376 			if (ret)
5377 				break;
5378 		}
5379 next:
5380 		btrfs_free_extent_map(em);
5381 		em = NULL;
5382 		cur_offset = last_byte;
5383 		if (cur_offset >= block_end)
5384 			break;
5385 	}
5386 	btrfs_free_extent_map(em);
5387 	btrfs_unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5388 	return ret;
5389 }
5390 
btrfs_setsize(struct inode * inode,struct iattr * attr)5391 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5392 {
5393 	struct btrfs_root *root = BTRFS_I(inode)->root;
5394 	struct btrfs_trans_handle *trans;
5395 	loff_t oldsize = i_size_read(inode);
5396 	loff_t newsize = attr->ia_size;
5397 	int mask = attr->ia_valid;
5398 	int ret;
5399 
5400 	/*
5401 	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5402 	 * special case where we need to update the times despite not having
5403 	 * these flags set.  For all other operations the VFS set these flags
5404 	 * explicitly if it wants a timestamp update.
5405 	 */
5406 	if (newsize != oldsize) {
5407 		inode_inc_iversion(inode);
5408 		if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5409 			inode_set_mtime_to_ts(inode,
5410 					      inode_set_ctime_current(inode));
5411 		}
5412 	}
5413 
5414 	if (newsize > oldsize) {
5415 		/*
5416 		 * Don't do an expanding truncate while snapshotting is ongoing.
5417 		 * This is to ensure the snapshot captures a fully consistent
5418 		 * state of this file - if the snapshot captures this expanding
5419 		 * truncation, it must capture all writes that happened before
5420 		 * this truncation.
5421 		 */
5422 		btrfs_drew_write_lock(&root->snapshot_lock);
5423 		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5424 		if (ret) {
5425 			btrfs_drew_write_unlock(&root->snapshot_lock);
5426 			return ret;
5427 		}
5428 
5429 		trans = btrfs_start_transaction(root, 1);
5430 		if (IS_ERR(trans)) {
5431 			btrfs_drew_write_unlock(&root->snapshot_lock);
5432 			return PTR_ERR(trans);
5433 		}
5434 
5435 		i_size_write(inode, newsize);
5436 		btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5437 		pagecache_isize_extended(inode, oldsize, newsize);
5438 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
5439 		btrfs_drew_write_unlock(&root->snapshot_lock);
5440 		btrfs_end_transaction(trans);
5441 	} else {
5442 		struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
5443 
5444 		if (btrfs_is_zoned(fs_info)) {
5445 			ret = btrfs_wait_ordered_range(BTRFS_I(inode),
5446 					ALIGN(newsize, fs_info->sectorsize),
5447 					(u64)-1);
5448 			if (ret)
5449 				return ret;
5450 		}
5451 
5452 		/*
5453 		 * We're truncating a file that used to have good data down to
5454 		 * zero. Make sure any new writes to the file get on disk
5455 		 * on close.
5456 		 */
5457 		if (newsize == 0 && oldsize != 0)
5458 			set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5459 				&BTRFS_I(inode)->runtime_flags);
5460 
5461 		truncate_setsize(inode, newsize);
5462 
5463 		inode_dio_wait(inode);
5464 
5465 		ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5466 		if (ret && inode->i_nlink) {
5467 			int ret2;
5468 
5469 			/*
5470 			 * Truncate failed, so fix up the in-memory size. We
5471 			 * adjusted disk_i_size down as we removed extents, so
5472 			 * wait for disk_i_size to be stable and then update the
5473 			 * in-memory size to match.
5474 			 */
5475 			ret2 = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
5476 			if (ret2)
5477 				return ret2;
5478 			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5479 		}
5480 	}
5481 
5482 	return ret;
5483 }
5484 
btrfs_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * attr)5485 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5486 			 struct iattr *attr)
5487 {
5488 	struct inode *inode = d_inode(dentry);
5489 	struct btrfs_root *root = BTRFS_I(inode)->root;
5490 	int ret;
5491 
5492 	if (btrfs_root_readonly(root))
5493 		return -EROFS;
5494 
5495 	ret = setattr_prepare(idmap, dentry, attr);
5496 	if (ret)
5497 		return ret;
5498 
5499 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5500 		ret = btrfs_setsize(inode, attr);
5501 		if (ret)
5502 			return ret;
5503 	}
5504 
5505 	if (attr->ia_valid) {
5506 		setattr_copy(idmap, inode, attr);
5507 		inode_inc_iversion(inode);
5508 		ret = btrfs_dirty_inode(BTRFS_I(inode));
5509 
5510 		if (!ret && attr->ia_valid & ATTR_MODE)
5511 			ret = posix_acl_chmod(idmap, dentry, inode->i_mode);
5512 	}
5513 
5514 	return ret;
5515 }
5516 
5517 /*
5518  * While truncating the inode pages during eviction, we get the VFS
5519  * calling btrfs_invalidate_folio() against each folio of the inode. This
5520  * is slow because the calls to btrfs_invalidate_folio() result in a
5521  * huge amount of calls to lock_extent() and clear_extent_bit(),
5522  * which keep merging and splitting extent_state structures over and over,
5523  * wasting lots of time.
5524  *
5525  * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5526  * skip all those expensive operations on a per folio basis and do only
5527  * the ordered io finishing, while we release here the extent_map and
5528  * extent_state structures, without the excessive merging and splitting.
5529  */
evict_inode_truncate_pages(struct inode * inode)5530 static void evict_inode_truncate_pages(struct inode *inode)
5531 {
5532 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5533 	struct rb_node *node;
5534 
5535 	ASSERT(inode_state_read_once(inode) & I_FREEING);
5536 	truncate_inode_pages_final(&inode->i_data);
5537 
5538 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5539 
5540 	/*
5541 	 * Keep looping until we have no more ranges in the io tree.
5542 	 * We can have ongoing bios started by readahead that have
5543 	 * their endio callback (extent_io.c:end_bio_extent_readpage)
5544 	 * still in progress (unlocked the pages in the bio but did not yet
5545 	 * unlocked the ranges in the io tree). Therefore this means some
5546 	 * ranges can still be locked and eviction started because before
5547 	 * submitting those bios, which are executed by a separate task (work
5548 	 * queue kthread), inode references (inode->i_count) were not taken
5549 	 * (which would be dropped in the end io callback of each bio).
5550 	 * Therefore here we effectively end up waiting for those bios and
5551 	 * anyone else holding locked ranges without having bumped the inode's
5552 	 * reference count - if we don't do it, when they access the inode's
5553 	 * io_tree to unlock a range it may be too late, leading to an
5554 	 * use-after-free issue.
5555 	 */
5556 	spin_lock(&io_tree->lock);
5557 	while (!RB_EMPTY_ROOT(&io_tree->state)) {
5558 		struct extent_state *state;
5559 		struct extent_state *cached_state = NULL;
5560 		u64 start;
5561 		u64 end;
5562 		unsigned state_flags;
5563 
5564 		node = rb_first(&io_tree->state);
5565 		state = rb_entry(node, struct extent_state, rb_node);
5566 		start = state->start;
5567 		end = state->end;
5568 		state_flags = state->state;
5569 		spin_unlock(&io_tree->lock);
5570 
5571 		btrfs_lock_extent(io_tree, start, end, &cached_state);
5572 
5573 		/*
5574 		 * If still has DELALLOC flag, the extent didn't reach disk,
5575 		 * and its reserved space won't be freed by delayed_ref.
5576 		 * So we need to free its reserved space here.
5577 		 * (Refer to comment in btrfs_invalidate_folio, case 2)
5578 		 *
5579 		 * Note, end is the bytenr of last byte, so we need + 1 here.
5580 		 */
5581 		if (state_flags & EXTENT_DELALLOC)
5582 			btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5583 					       end - start + 1, NULL);
5584 
5585 		btrfs_clear_extent_bit(io_tree, start, end,
5586 				       EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5587 				       &cached_state);
5588 
5589 		cond_resched();
5590 		spin_lock(&io_tree->lock);
5591 	}
5592 	spin_unlock(&io_tree->lock);
5593 }
5594 
evict_refill_and_join(struct btrfs_root * root,struct btrfs_block_rsv * rsv)5595 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5596 							struct btrfs_block_rsv *rsv)
5597 {
5598 	struct btrfs_fs_info *fs_info = root->fs_info;
5599 	struct btrfs_trans_handle *trans;
5600 	u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5601 	int ret;
5602 
5603 	/*
5604 	 * Eviction should be taking place at some place safe because of our
5605 	 * delayed iputs.  However the normal flushing code will run delayed
5606 	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5607 	 *
5608 	 * We reserve the delayed_refs_extra here again because we can't use
5609 	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5610 	 * above.  We reserve our extra bit here because we generate a ton of
5611 	 * delayed refs activity by truncating.
5612 	 *
5613 	 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5614 	 * if we fail to make this reservation we can re-try without the
5615 	 * delayed_refs_extra so we can make some forward progress.
5616 	 */
5617 	ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5618 				     BTRFS_RESERVE_FLUSH_EVICT);
5619 	if (ret) {
5620 		ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5621 					     BTRFS_RESERVE_FLUSH_EVICT);
5622 		if (ret) {
5623 			btrfs_warn(fs_info,
5624 				   "could not allocate space for delete; will truncate on mount");
5625 			return ERR_PTR(-ENOSPC);
5626 		}
5627 		delayed_refs_extra = 0;
5628 	}
5629 
5630 	trans = btrfs_join_transaction(root);
5631 	if (IS_ERR(trans))
5632 		return trans;
5633 
5634 	if (delayed_refs_extra) {
5635 		trans->block_rsv = &fs_info->trans_block_rsv;
5636 		trans->bytes_reserved = delayed_refs_extra;
5637 		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5638 					delayed_refs_extra, true);
5639 	}
5640 	return trans;
5641 }
5642 
btrfs_evict_inode(struct inode * inode)5643 void btrfs_evict_inode(struct inode *inode)
5644 {
5645 	struct btrfs_fs_info *fs_info;
5646 	struct btrfs_trans_handle *trans;
5647 	struct btrfs_root *root = BTRFS_I(inode)->root;
5648 	struct btrfs_block_rsv rsv;
5649 	int ret;
5650 
5651 	trace_btrfs_inode_evict(inode);
5652 
5653 	if (!root)
5654 		goto clear_inode;
5655 
5656 	fs_info = inode_to_fs_info(inode);
5657 	evict_inode_truncate_pages(inode);
5658 
5659 	if (inode->i_nlink &&
5660 	    ((btrfs_root_refs(&root->root_item) != 0 &&
5661 	      btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID) ||
5662 	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5663 		goto out;
5664 
5665 	if (is_bad_inode(inode))
5666 		goto out;
5667 
5668 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5669 		goto out;
5670 
5671 	if (inode->i_nlink > 0) {
5672 		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5673 		       btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID);
5674 		goto out;
5675 	}
5676 
5677 	/*
5678 	 * This makes sure the inode item in tree is uptodate and the space for
5679 	 * the inode update is released.
5680 	 */
5681 	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5682 	if (ret)
5683 		goto out;
5684 
5685 	/*
5686 	 * This drops any pending insert or delete operations we have for this
5687 	 * inode.  We could have a delayed dir index deletion queued up, but
5688 	 * we're removing the inode completely so that'll be taken care of in
5689 	 * the truncate.
5690 	 */
5691 	btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5692 
5693 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
5694 	rsv.size = btrfs_calc_metadata_size(fs_info, 1);
5695 	rsv.failfast = true;
5696 
5697 	btrfs_i_size_write(BTRFS_I(inode), 0);
5698 
5699 	while (1) {
5700 		struct btrfs_truncate_control control = {
5701 			.inode = BTRFS_I(inode),
5702 			.ino = btrfs_ino(BTRFS_I(inode)),
5703 			.new_size = 0,
5704 			.min_type = 0,
5705 		};
5706 
5707 		trans = evict_refill_and_join(root, &rsv);
5708 		if (IS_ERR(trans))
5709 			goto out_release;
5710 
5711 		trans->block_rsv = &rsv;
5712 
5713 		ret = btrfs_truncate_inode_items(trans, root, &control);
5714 		trans->block_rsv = &fs_info->trans_block_rsv;
5715 		btrfs_end_transaction(trans);
5716 		/*
5717 		 * We have not added new delayed items for our inode after we
5718 		 * have flushed its delayed items, so no need to throttle on
5719 		 * delayed items. However we have modified extent buffers.
5720 		 */
5721 		btrfs_btree_balance_dirty_nodelay(fs_info);
5722 		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5723 			goto out_release;
5724 		else if (!ret)
5725 			break;
5726 	}
5727 
5728 	/*
5729 	 * Errors here aren't a big deal, it just means we leave orphan items in
5730 	 * the tree. They will be cleaned up on the next mount. If the inode
5731 	 * number gets reused, cleanup deletes the orphan item without doing
5732 	 * anything, and unlink reuses the existing orphan item.
5733 	 *
5734 	 * If it turns out that we are dropping too many of these, we might want
5735 	 * to add a mechanism for retrying these after a commit.
5736 	 */
5737 	trans = evict_refill_and_join(root, &rsv);
5738 	if (!IS_ERR(trans)) {
5739 		trans->block_rsv = &rsv;
5740 		btrfs_orphan_del(trans, BTRFS_I(inode));
5741 		trans->block_rsv = &fs_info->trans_block_rsv;
5742 		btrfs_end_transaction(trans);
5743 	}
5744 
5745 out_release:
5746 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
5747 out:
5748 	/*
5749 	 * If we didn't successfully delete, the orphan item will still be in
5750 	 * the tree and we'll retry on the next mount. Again, we might also want
5751 	 * to retry these periodically in the future.
5752 	 */
5753 	btrfs_remove_delayed_node(BTRFS_I(inode));
5754 clear_inode:
5755 	clear_inode(inode);
5756 }
5757 
5758 /*
5759  * Return the key found in the dir entry in the location pointer, fill @type
5760  * with BTRFS_FT_*, and return 0.
5761  *
5762  * If no dir entries were found, returns -ENOENT.
5763  * If found a corrupted location in dir entry, returns -EUCLEAN.
5764  */
btrfs_inode_by_name(struct btrfs_inode * dir,struct dentry * dentry,struct btrfs_key * location,u8 * type)5765 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5766 			       struct btrfs_key *location, u8 *type)
5767 {
5768 	struct btrfs_dir_item *di;
5769 	BTRFS_PATH_AUTO_FREE(path);
5770 	struct btrfs_root *root = dir->root;
5771 	int ret = 0;
5772 	struct fscrypt_name fname;
5773 
5774 	path = btrfs_alloc_path();
5775 	if (!path)
5776 		return -ENOMEM;
5777 
5778 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5779 	if (ret < 0)
5780 		return ret;
5781 	/*
5782 	 * fscrypt_setup_filename() should never return a positive value, but
5783 	 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5784 	 */
5785 	ASSERT(ret == 0);
5786 
5787 	/* This needs to handle no-key deletions later on */
5788 
5789 	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5790 				   &fname.disk_name, 0);
5791 	if (IS_ERR_OR_NULL(di)) {
5792 		ret = di ? PTR_ERR(di) : -ENOENT;
5793 		goto out;
5794 	}
5795 
5796 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5797 	if (unlikely(location->type != BTRFS_INODE_ITEM_KEY &&
5798 		     location->type != BTRFS_ROOT_ITEM_KEY)) {
5799 		ret = -EUCLEAN;
5800 		btrfs_warn(root->fs_info,
5801 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location " BTRFS_KEY_FMT ")",
5802 			   __func__, fname.disk_name.name, btrfs_ino(dir),
5803 			   BTRFS_KEY_FMT_VALUE(location));
5804 	}
5805 	if (!ret)
5806 		*type = btrfs_dir_ftype(path->nodes[0], di);
5807 out:
5808 	fscrypt_free_filename(&fname);
5809 	return ret;
5810 }
5811 
5812 /*
5813  * when we hit a tree root in a directory, the btrfs part of the inode
5814  * needs to be changed to reflect the root directory of the tree root.  This
5815  * is kind of like crossing a mount point.
5816  */
fixup_tree_root_location(struct btrfs_fs_info * fs_info,struct btrfs_inode * dir,struct dentry * dentry,struct btrfs_key * location,struct btrfs_root ** sub_root)5817 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5818 				    struct btrfs_inode *dir,
5819 				    struct dentry *dentry,
5820 				    struct btrfs_key *location,
5821 				    struct btrfs_root **sub_root)
5822 {
5823 	BTRFS_PATH_AUTO_FREE(path);
5824 	struct btrfs_root *new_root;
5825 	struct btrfs_root_ref *ref;
5826 	struct extent_buffer *leaf;
5827 	struct btrfs_key key;
5828 	int ret;
5829 	int err = 0;
5830 	struct fscrypt_name fname;
5831 
5832 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5833 	if (ret)
5834 		return ret;
5835 
5836 	path = btrfs_alloc_path();
5837 	if (!path) {
5838 		err = -ENOMEM;
5839 		goto out;
5840 	}
5841 
5842 	err = -ENOENT;
5843 	key.objectid = btrfs_root_id(dir->root);
5844 	key.type = BTRFS_ROOT_REF_KEY;
5845 	key.offset = location->objectid;
5846 
5847 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5848 	if (ret) {
5849 		if (ret < 0)
5850 			err = ret;
5851 		goto out;
5852 	}
5853 
5854 	leaf = path->nodes[0];
5855 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5856 	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5857 	    btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5858 		goto out;
5859 
5860 	ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5861 				   (unsigned long)(ref + 1), fname.disk_name.len);
5862 	if (ret)
5863 		goto out;
5864 
5865 	btrfs_release_path(path);
5866 
5867 	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5868 	if (IS_ERR(new_root)) {
5869 		err = PTR_ERR(new_root);
5870 		goto out;
5871 	}
5872 
5873 	*sub_root = new_root;
5874 	location->objectid = btrfs_root_dirid(&new_root->root_item);
5875 	location->type = BTRFS_INODE_ITEM_KEY;
5876 	location->offset = 0;
5877 	err = 0;
5878 out:
5879 	fscrypt_free_filename(&fname);
5880 	return err;
5881 }
5882 
5883 
5884 
btrfs_del_inode_from_root(struct btrfs_inode * inode)5885 static void btrfs_del_inode_from_root(struct btrfs_inode *inode)
5886 {
5887 	struct btrfs_root *root = inode->root;
5888 	struct btrfs_inode *entry;
5889 	bool empty = false;
5890 
5891 	xa_lock(&root->inodes);
5892 	/*
5893 	 * This btrfs_inode is being freed and has already been unhashed at this
5894 	 * point. It's possible that another btrfs_inode has already been
5895 	 * allocated for the same inode and inserted itself into the root, so
5896 	 * don't delete it in that case.
5897 	 *
5898 	 * Note that this shouldn't need to allocate memory, so the gfp flags
5899 	 * don't really matter.
5900 	 */
5901 	entry = __xa_cmpxchg(&root->inodes, btrfs_ino(inode), inode, NULL,
5902 			     GFP_ATOMIC);
5903 	if (entry == inode)
5904 		empty = xa_empty(&root->inodes);
5905 	xa_unlock(&root->inodes);
5906 
5907 	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5908 		xa_lock(&root->inodes);
5909 		empty = xa_empty(&root->inodes);
5910 		xa_unlock(&root->inodes);
5911 		if (empty)
5912 			btrfs_add_dead_root(root);
5913 	}
5914 }
5915 
5916 
btrfs_init_locked_inode(struct inode * inode,void * p)5917 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5918 {
5919 	struct btrfs_iget_args *args = p;
5920 
5921 	btrfs_set_inode_number(BTRFS_I(inode), args->ino);
5922 	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5923 
5924 	if (args->root && args->root == args->root->fs_info->tree_root &&
5925 	    args->ino != BTRFS_BTREE_INODE_OBJECTID)
5926 		set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5927 			&BTRFS_I(inode)->runtime_flags);
5928 	return 0;
5929 }
5930 
btrfs_find_actor(struct inode * inode,void * opaque)5931 static int btrfs_find_actor(struct inode *inode, void *opaque)
5932 {
5933 	struct btrfs_iget_args *args = opaque;
5934 
5935 	return args->ino == btrfs_ino(BTRFS_I(inode)) &&
5936 		args->root == BTRFS_I(inode)->root;
5937 }
5938 
btrfs_iget_locked(u64 ino,struct btrfs_root * root)5939 static struct btrfs_inode *btrfs_iget_locked(u64 ino, struct btrfs_root *root)
5940 {
5941 	struct inode *inode;
5942 	struct btrfs_iget_args args;
5943 	unsigned long hashval = btrfs_inode_hash(ino, root);
5944 
5945 	args.ino = ino;
5946 	args.root = root;
5947 
5948 	inode = iget5_locked_rcu(root->fs_info->sb, hashval, btrfs_find_actor,
5949 			     btrfs_init_locked_inode,
5950 			     (void *)&args);
5951 	if (!inode)
5952 		return NULL;
5953 	return BTRFS_I(inode);
5954 }
5955 
5956 /*
5957  * Get an inode object given its inode number and corresponding root.  Path is
5958  * preallocated to prevent recursing back to iget through allocator.
5959  */
btrfs_iget_path(u64 ino,struct btrfs_root * root,struct btrfs_path * path)5960 struct btrfs_inode *btrfs_iget_path(u64 ino, struct btrfs_root *root,
5961 				    struct btrfs_path *path)
5962 {
5963 	struct btrfs_inode *inode;
5964 	int ret;
5965 
5966 	inode = btrfs_iget_locked(ino, root);
5967 	if (!inode)
5968 		return ERR_PTR(-ENOMEM);
5969 
5970 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5971 		return inode;
5972 
5973 	ret = btrfs_read_locked_inode(inode, path);
5974 	if (ret)
5975 		return ERR_PTR(ret);
5976 
5977 	unlock_new_inode(&inode->vfs_inode);
5978 	return inode;
5979 }
5980 
5981 /*
5982  * Get an inode object given its inode number and corresponding root.
5983  */
btrfs_iget(u64 ino,struct btrfs_root * root)5984 struct btrfs_inode *btrfs_iget(u64 ino, struct btrfs_root *root)
5985 {
5986 	struct btrfs_inode *inode;
5987 	struct btrfs_path *path;
5988 	int ret;
5989 
5990 	inode = btrfs_iget_locked(ino, root);
5991 	if (!inode)
5992 		return ERR_PTR(-ENOMEM);
5993 
5994 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5995 		return inode;
5996 
5997 	path = btrfs_alloc_path();
5998 	if (!path) {
5999 		iget_failed(&inode->vfs_inode);
6000 		return ERR_PTR(-ENOMEM);
6001 	}
6002 
6003 	ret = btrfs_read_locked_inode(inode, path);
6004 	btrfs_free_path(path);
6005 	if (ret)
6006 		return ERR_PTR(ret);
6007 
6008 	if (S_ISDIR(inode->vfs_inode.i_mode))
6009 		inode->vfs_inode.i_opflags |= IOP_FASTPERM_MAY_EXEC;
6010 	unlock_new_inode(&inode->vfs_inode);
6011 	return inode;
6012 }
6013 
new_simple_dir(struct inode * dir,struct btrfs_key * key,struct btrfs_root * root)6014 static struct btrfs_inode *new_simple_dir(struct inode *dir,
6015 					  struct btrfs_key *key,
6016 					  struct btrfs_root *root)
6017 {
6018 	struct timespec64 ts;
6019 	struct inode *vfs_inode;
6020 	struct btrfs_inode *inode;
6021 
6022 	vfs_inode = new_inode(dir->i_sb);
6023 	if (!vfs_inode)
6024 		return ERR_PTR(-ENOMEM);
6025 
6026 	inode = BTRFS_I(vfs_inode);
6027 	inode->root = btrfs_grab_root(root);
6028 	inode->ref_root_id = key->objectid;
6029 	set_bit(BTRFS_INODE_ROOT_STUB, &inode->runtime_flags);
6030 	set_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags);
6031 
6032 	btrfs_set_inode_number(inode, BTRFS_EMPTY_SUBVOL_DIR_OBJECTID);
6033 	/*
6034 	 * We only need lookup, the rest is read-only and there's no inode
6035 	 * associated with the dentry
6036 	 */
6037 	vfs_inode->i_op = &simple_dir_inode_operations;
6038 	vfs_inode->i_opflags &= ~IOP_XATTR;
6039 	vfs_inode->i_fop = &simple_dir_operations;
6040 	vfs_inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
6041 
6042 	ts = inode_set_ctime_current(vfs_inode);
6043 	inode_set_mtime_to_ts(vfs_inode, ts);
6044 	inode_set_atime_to_ts(vfs_inode, inode_get_atime(dir));
6045 	inode->i_otime_sec = ts.tv_sec;
6046 	inode->i_otime_nsec = ts.tv_nsec;
6047 
6048 	vfs_inode->i_uid = dir->i_uid;
6049 	vfs_inode->i_gid = dir->i_gid;
6050 
6051 	return inode;
6052 }
6053 
6054 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
6055 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
6056 static_assert(BTRFS_FT_DIR == FT_DIR);
6057 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
6058 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
6059 static_assert(BTRFS_FT_FIFO == FT_FIFO);
6060 static_assert(BTRFS_FT_SOCK == FT_SOCK);
6061 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
6062 
btrfs_inode_type(const struct btrfs_inode * inode)6063 static inline u8 btrfs_inode_type(const struct btrfs_inode *inode)
6064 {
6065 	return fs_umode_to_ftype(inode->vfs_inode.i_mode);
6066 }
6067 
btrfs_lookup_dentry(struct inode * dir,struct dentry * dentry)6068 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
6069 {
6070 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6071 	struct btrfs_inode *inode;
6072 	struct btrfs_root *root = BTRFS_I(dir)->root;
6073 	struct btrfs_root *sub_root = root;
6074 	struct btrfs_key location = { 0 };
6075 	u8 di_type = 0;
6076 	int ret = 0;
6077 
6078 	if (dentry->d_name.len > BTRFS_NAME_LEN)
6079 		return ERR_PTR(-ENAMETOOLONG);
6080 
6081 	ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
6082 	if (ret < 0)
6083 		return ERR_PTR(ret);
6084 
6085 	if (location.type == BTRFS_INODE_ITEM_KEY) {
6086 		inode = btrfs_iget(location.objectid, root);
6087 		if (IS_ERR(inode))
6088 			return ERR_CAST(inode);
6089 
6090 		/* Do extra check against inode mode with di_type */
6091 		if (unlikely(btrfs_inode_type(inode) != di_type)) {
6092 			btrfs_crit(fs_info,
6093 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
6094 				  inode->vfs_inode.i_mode, btrfs_inode_type(inode),
6095 				  di_type);
6096 			iput(&inode->vfs_inode);
6097 			return ERR_PTR(-EUCLEAN);
6098 		}
6099 		return &inode->vfs_inode;
6100 	}
6101 
6102 	ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
6103 				       &location, &sub_root);
6104 	if (ret < 0) {
6105 		if (ret != -ENOENT)
6106 			inode = ERR_PTR(ret);
6107 		else
6108 			inode = new_simple_dir(dir, &location, root);
6109 	} else {
6110 		inode = btrfs_iget(location.objectid, sub_root);
6111 		btrfs_put_root(sub_root);
6112 
6113 		if (IS_ERR(inode))
6114 			return ERR_CAST(inode);
6115 
6116 		down_read(&fs_info->cleanup_work_sem);
6117 		if (!sb_rdonly(inode->vfs_inode.i_sb))
6118 			ret = btrfs_orphan_cleanup(sub_root);
6119 		up_read(&fs_info->cleanup_work_sem);
6120 		if (ret) {
6121 			iput(&inode->vfs_inode);
6122 			inode = ERR_PTR(ret);
6123 		}
6124 	}
6125 
6126 	if (IS_ERR(inode))
6127 		return ERR_CAST(inode);
6128 
6129 	return &inode->vfs_inode;
6130 }
6131 
btrfs_dentry_delete(const struct dentry * dentry)6132 static int btrfs_dentry_delete(const struct dentry *dentry)
6133 {
6134 	struct btrfs_root *root;
6135 	struct inode *inode = d_inode(dentry);
6136 
6137 	if (!inode && !IS_ROOT(dentry))
6138 		inode = d_inode(dentry->d_parent);
6139 
6140 	if (inode) {
6141 		root = BTRFS_I(inode)->root;
6142 		if (btrfs_root_refs(&root->root_item) == 0)
6143 			return 1;
6144 
6145 		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6146 			return 1;
6147 	}
6148 	return 0;
6149 }
6150 
btrfs_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)6151 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
6152 				   unsigned int flags)
6153 {
6154 	struct inode *inode = btrfs_lookup_dentry(dir, dentry);
6155 
6156 	if (inode == ERR_PTR(-ENOENT))
6157 		inode = NULL;
6158 	return d_splice_alias(inode, dentry);
6159 }
6160 
6161 /*
6162  * Find the highest existing sequence number in a directory and then set the
6163  * in-memory index_cnt variable to the first free sequence number.
6164  */
btrfs_set_inode_index_count(struct btrfs_inode * inode)6165 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6166 {
6167 	struct btrfs_root *root = inode->root;
6168 	struct btrfs_key key, found_key;
6169 	BTRFS_PATH_AUTO_FREE(path);
6170 	struct extent_buffer *leaf;
6171 	int ret;
6172 
6173 	key.objectid = btrfs_ino(inode);
6174 	key.type = BTRFS_DIR_INDEX_KEY;
6175 	key.offset = (u64)-1;
6176 
6177 	path = btrfs_alloc_path();
6178 	if (!path)
6179 		return -ENOMEM;
6180 
6181 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6182 	if (ret < 0)
6183 		return ret;
6184 
6185 	if (unlikely(ret == 0)) {
6186 		/*
6187 		 * Key with offset -1 found, there would have to exist a dir
6188 		 * index item with such offset, but this is out of the valid
6189 		 * range.
6190 		 */
6191 		btrfs_err(root->fs_info,
6192 			  "unexpected exact match for DIR_INDEX key, inode %llu",
6193 			  btrfs_ino(inode));
6194 		return -EUCLEAN;
6195 	}
6196 
6197 	if (path->slots[0] == 0) {
6198 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6199 		return 0;
6200 	}
6201 
6202 	path->slots[0]--;
6203 
6204 	leaf = path->nodes[0];
6205 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6206 
6207 	if (found_key.objectid != btrfs_ino(inode) ||
6208 	    found_key.type != BTRFS_DIR_INDEX_KEY) {
6209 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6210 		return 0;
6211 	}
6212 
6213 	inode->index_cnt = found_key.offset + 1;
6214 
6215 	return 0;
6216 }
6217 
btrfs_get_dir_last_index(struct btrfs_inode * dir,u64 * index)6218 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
6219 {
6220 	int ret = 0;
6221 
6222 	btrfs_inode_lock(dir, 0);
6223 	if (dir->index_cnt == (u64)-1) {
6224 		ret = btrfs_inode_delayed_dir_index_count(dir);
6225 		if (ret) {
6226 			ret = btrfs_set_inode_index_count(dir);
6227 			if (ret)
6228 				goto out;
6229 		}
6230 	}
6231 
6232 	/* index_cnt is the index number of next new entry, so decrement it. */
6233 	*index = dir->index_cnt - 1;
6234 out:
6235 	btrfs_inode_unlock(dir, 0);
6236 
6237 	return ret;
6238 }
6239 
6240 /*
6241  * All this infrastructure exists because dir_emit can fault, and we are holding
6242  * the tree lock when doing readdir.  For now just allocate a buffer and copy
6243  * our information into that, and then dir_emit from the buffer.  This is
6244  * similar to what NFS does, only we don't keep the buffer around in pagecache
6245  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
6246  * copy_to_user_inatomic so we don't have to worry about page faulting under the
6247  * tree lock.
6248  */
btrfs_opendir(struct inode * inode,struct file * file)6249 static int btrfs_opendir(struct inode *inode, struct file *file)
6250 {
6251 	struct btrfs_file_private *private;
6252 	u64 last_index;
6253 	int ret;
6254 
6255 	ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
6256 	if (ret)
6257 		return ret;
6258 
6259 	private = kzalloc_obj(struct btrfs_file_private);
6260 	if (!private)
6261 		return -ENOMEM;
6262 	private->last_index = last_index;
6263 	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6264 	if (!private->filldir_buf) {
6265 		kfree(private);
6266 		return -ENOMEM;
6267 	}
6268 	file->private_data = private;
6269 	return 0;
6270 }
6271 
btrfs_dir_llseek(struct file * file,loff_t offset,int whence)6272 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
6273 {
6274 	struct btrfs_file_private *private = file->private_data;
6275 	int ret;
6276 
6277 	ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
6278 				       &private->last_index);
6279 	if (ret)
6280 		return ret;
6281 
6282 	return generic_file_llseek(file, offset, whence);
6283 }
6284 
6285 struct dir_entry {
6286 	u64 ino;
6287 	u64 offset;
6288 	unsigned type;
6289 	int name_len;
6290 };
6291 
btrfs_filldir(void * addr,int entries,struct dir_context * ctx)6292 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6293 {
6294 	while (entries--) {
6295 		struct dir_entry *entry = addr;
6296 		char *name = (char *)(entry + 1);
6297 
6298 		ctx->pos = get_unaligned(&entry->offset);
6299 		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6300 					 get_unaligned(&entry->ino),
6301 					 get_unaligned(&entry->type)))
6302 			return 1;
6303 		addr += sizeof(struct dir_entry) +
6304 			get_unaligned(&entry->name_len);
6305 		ctx->pos++;
6306 	}
6307 	return 0;
6308 }
6309 
btrfs_real_readdir(struct file * file,struct dir_context * ctx)6310 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6311 {
6312 	struct inode *inode = file_inode(file);
6313 	struct btrfs_root *root = BTRFS_I(inode)->root;
6314 	struct btrfs_file_private *private = file->private_data;
6315 	struct btrfs_dir_item *di;
6316 	struct btrfs_key key;
6317 	struct btrfs_key found_key;
6318 	BTRFS_PATH_AUTO_FREE(path);
6319 	void *addr;
6320 	LIST_HEAD(ins_list);
6321 	LIST_HEAD(del_list);
6322 	int ret;
6323 	char *name_ptr;
6324 	int name_len;
6325 	int entries = 0;
6326 	int total_len = 0;
6327 	bool put = false;
6328 	struct btrfs_key location;
6329 
6330 	if (!dir_emit_dots(file, ctx))
6331 		return 0;
6332 
6333 	path = btrfs_alloc_path();
6334 	if (!path)
6335 		return -ENOMEM;
6336 
6337 	addr = private->filldir_buf;
6338 	path->reada = READA_FORWARD;
6339 
6340 	put = btrfs_readdir_get_delayed_items(BTRFS_I(inode), private->last_index,
6341 					      &ins_list, &del_list);
6342 
6343 again:
6344 	key.type = BTRFS_DIR_INDEX_KEY;
6345 	key.offset = ctx->pos;
6346 	key.objectid = btrfs_ino(BTRFS_I(inode));
6347 
6348 	btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6349 		struct dir_entry *entry;
6350 		struct extent_buffer *leaf = path->nodes[0];
6351 		u8 ftype;
6352 
6353 		if (found_key.objectid != key.objectid)
6354 			break;
6355 		if (found_key.type != BTRFS_DIR_INDEX_KEY)
6356 			break;
6357 		if (found_key.offset < ctx->pos)
6358 			continue;
6359 		if (found_key.offset > private->last_index)
6360 			break;
6361 		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6362 			continue;
6363 		di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6364 		name_len = btrfs_dir_name_len(leaf, di);
6365 		if ((total_len + sizeof(struct dir_entry) + name_len) >=
6366 		    PAGE_SIZE) {
6367 			btrfs_release_path(path);
6368 			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6369 			if (ret)
6370 				goto nopos;
6371 			addr = private->filldir_buf;
6372 			entries = 0;
6373 			total_len = 0;
6374 			goto again;
6375 		}
6376 
6377 		ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6378 		entry = addr;
6379 		name_ptr = (char *)(entry + 1);
6380 		read_extent_buffer(leaf, name_ptr,
6381 				   (unsigned long)(di + 1), name_len);
6382 		put_unaligned(name_len, &entry->name_len);
6383 		put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6384 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
6385 		put_unaligned(location.objectid, &entry->ino);
6386 		put_unaligned(found_key.offset, &entry->offset);
6387 		entries++;
6388 		addr += sizeof(struct dir_entry) + name_len;
6389 		total_len += sizeof(struct dir_entry) + name_len;
6390 	}
6391 	/* Catch error encountered during iteration */
6392 	if (ret < 0)
6393 		goto err;
6394 
6395 	btrfs_release_path(path);
6396 
6397 	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6398 	if (ret)
6399 		goto nopos;
6400 
6401 	if (btrfs_readdir_delayed_dir_index(ctx, &ins_list))
6402 		goto nopos;
6403 
6404 	/*
6405 	 * Stop new entries from being returned after we return the last
6406 	 * entry.
6407 	 *
6408 	 * New directory entries are assigned a strictly increasing
6409 	 * offset.  This means that new entries created during readdir
6410 	 * are *guaranteed* to be seen in the future by that readdir.
6411 	 * This has broken buggy programs which operate on names as
6412 	 * they're returned by readdir.  Until we reuse freed offsets
6413 	 * we have this hack to stop new entries from being returned
6414 	 * under the assumption that they'll never reach this huge
6415 	 * offset.
6416 	 *
6417 	 * This is being careful not to overflow 32bit loff_t unless the
6418 	 * last entry requires it because doing so has broken 32bit apps
6419 	 * in the past.
6420 	 */
6421 	if (ctx->pos >= INT_MAX)
6422 		ctx->pos = LLONG_MAX;
6423 	else
6424 		ctx->pos = INT_MAX;
6425 nopos:
6426 	ret = 0;
6427 err:
6428 	if (put)
6429 		btrfs_readdir_put_delayed_items(BTRFS_I(inode), &ins_list, &del_list);
6430 	return ret;
6431 }
6432 
6433 /*
6434  * This is somewhat expensive, updating the tree every time the
6435  * inode changes.  But, it is most likely to find the inode in cache.
6436  * FIXME, needs more benchmarking...there are no reasons other than performance
6437  * to keep or drop this code.
6438  */
btrfs_dirty_inode(struct btrfs_inode * inode)6439 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6440 {
6441 	struct btrfs_root *root = inode->root;
6442 	struct btrfs_fs_info *fs_info = root->fs_info;
6443 	struct btrfs_trans_handle *trans;
6444 	int ret;
6445 
6446 	if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6447 		return 0;
6448 
6449 	trans = btrfs_join_transaction(root);
6450 	if (IS_ERR(trans))
6451 		return PTR_ERR(trans);
6452 
6453 	ret = btrfs_update_inode(trans, inode);
6454 	if (ret == -ENOSPC || ret == -EDQUOT) {
6455 		/* whoops, lets try again with the full transaction */
6456 		btrfs_end_transaction(trans);
6457 		trans = btrfs_start_transaction(root, 1);
6458 		if (IS_ERR(trans))
6459 			return PTR_ERR(trans);
6460 
6461 		ret = btrfs_update_inode(trans, inode);
6462 	}
6463 	btrfs_end_transaction(trans);
6464 	if (inode->delayed_node)
6465 		btrfs_balance_delayed_items(fs_info);
6466 
6467 	return ret;
6468 }
6469 
6470 /*
6471  * We need our own ->update_time so that we can return error on ENOSPC for
6472  * updating the inode in the case of file write and mmap writes.
6473  */
btrfs_update_time(struct inode * inode,enum fs_update_time type,unsigned int flags)6474 static int btrfs_update_time(struct inode *inode, enum fs_update_time type,
6475 		unsigned int flags)
6476 {
6477 	struct btrfs_root *root = BTRFS_I(inode)->root;
6478 	int dirty;
6479 
6480 	if (btrfs_root_readonly(root))
6481 		return -EROFS;
6482 	if (flags & IOCB_NOWAIT)
6483 		return -EAGAIN;
6484 
6485 	dirty = inode_update_time(inode, type, flags);
6486 	if (dirty <= 0)
6487 		return dirty;
6488 	return btrfs_dirty_inode(BTRFS_I(inode));
6489 }
6490 
6491 /*
6492  * helper to find a free sequence number in a given directory.  This current
6493  * code is very simple, later versions will do smarter things in the btree
6494  */
btrfs_set_inode_index(struct btrfs_inode * dir,u64 * index)6495 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6496 {
6497 	int ret = 0;
6498 
6499 	if (dir->index_cnt == (u64)-1) {
6500 		ret = btrfs_inode_delayed_dir_index_count(dir);
6501 		if (ret) {
6502 			ret = btrfs_set_inode_index_count(dir);
6503 			if (ret)
6504 				return ret;
6505 		}
6506 	}
6507 
6508 	*index = dir->index_cnt;
6509 	dir->index_cnt++;
6510 
6511 	return ret;
6512 }
6513 
btrfs_insert_inode_locked(struct inode * inode)6514 static int btrfs_insert_inode_locked(struct inode *inode)
6515 {
6516 	struct btrfs_iget_args args;
6517 
6518 	args.ino = btrfs_ino(BTRFS_I(inode));
6519 	args.root = BTRFS_I(inode)->root;
6520 
6521 	return insert_inode_locked4(inode,
6522 		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6523 		   btrfs_find_actor, &args);
6524 }
6525 
btrfs_new_inode_prepare(struct btrfs_new_inode_args * args,unsigned int * trans_num_items)6526 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6527 			    unsigned int *trans_num_items)
6528 {
6529 	struct inode *dir = args->dir;
6530 	struct inode *inode = args->inode;
6531 	int ret;
6532 
6533 	if (!args->orphan) {
6534 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6535 					     &args->fname);
6536 		if (ret)
6537 			return ret;
6538 	}
6539 
6540 	ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6541 	if (ret) {
6542 		fscrypt_free_filename(&args->fname);
6543 		return ret;
6544 	}
6545 
6546 	/* 1 to add inode item */
6547 	*trans_num_items = 1;
6548 	/* 1 to add compression property */
6549 	if (BTRFS_I(dir)->prop_compress)
6550 		(*trans_num_items)++;
6551 	/* 1 to add default ACL xattr */
6552 	if (args->default_acl)
6553 		(*trans_num_items)++;
6554 	/* 1 to add access ACL xattr */
6555 	if (args->acl)
6556 		(*trans_num_items)++;
6557 #ifdef CONFIG_SECURITY
6558 	/* 1 to add LSM xattr */
6559 	if (dir->i_security)
6560 		(*trans_num_items)++;
6561 #endif
6562 	if (args->orphan) {
6563 		/* 1 to add orphan item */
6564 		(*trans_num_items)++;
6565 	} else {
6566 		/*
6567 		 * 1 to add dir item
6568 		 * 1 to add dir index
6569 		 * 1 to update parent inode item
6570 		 *
6571 		 * No need for 1 unit for the inode ref item because it is
6572 		 * inserted in a batch together with the inode item at
6573 		 * btrfs_create_new_inode().
6574 		 */
6575 		*trans_num_items += 3;
6576 	}
6577 	return 0;
6578 }
6579 
btrfs_new_inode_args_destroy(struct btrfs_new_inode_args * args)6580 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6581 {
6582 	posix_acl_release(args->acl);
6583 	posix_acl_release(args->default_acl);
6584 	fscrypt_free_filename(&args->fname);
6585 }
6586 
6587 /*
6588  * Inherit flags from the parent inode.
6589  *
6590  * Currently only the compression flags and the cow flags are inherited.
6591  */
btrfs_inherit_iflags(struct btrfs_inode * inode,struct btrfs_inode * dir)6592 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6593 {
6594 	unsigned int flags;
6595 
6596 	flags = dir->flags;
6597 
6598 	if (flags & BTRFS_INODE_NOCOMPRESS) {
6599 		inode->flags &= ~BTRFS_INODE_COMPRESS;
6600 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
6601 	} else if (flags & BTRFS_INODE_COMPRESS) {
6602 		inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6603 		inode->flags |= BTRFS_INODE_COMPRESS;
6604 	}
6605 
6606 	if (flags & BTRFS_INODE_NODATACOW) {
6607 		inode->flags |= BTRFS_INODE_NODATACOW;
6608 		if (S_ISREG(inode->vfs_inode.i_mode))
6609 			inode->flags |= BTRFS_INODE_NODATASUM;
6610 	}
6611 
6612 	btrfs_sync_inode_flags_to_i_flags(inode);
6613 }
6614 
btrfs_create_new_inode(struct btrfs_trans_handle * trans,struct btrfs_new_inode_args * args)6615 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6616 			   struct btrfs_new_inode_args *args)
6617 {
6618 	struct timespec64 ts;
6619 	struct inode *dir = args->dir;
6620 	struct inode *inode = args->inode;
6621 	const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6622 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6623 	struct btrfs_root *root;
6624 	struct btrfs_inode_item *inode_item;
6625 	struct btrfs_path *path;
6626 	u64 objectid;
6627 	struct btrfs_inode_ref *ref;
6628 	struct btrfs_key key[2];
6629 	u32 sizes[2];
6630 	struct btrfs_item_batch batch;
6631 	unsigned long ptr;
6632 	int ret;
6633 	bool xa_reserved = false;
6634 
6635 	if (!args->orphan && !args->subvol) {
6636 		/*
6637 		 * Before anything else, check if we can add the name to the
6638 		 * parent directory. We want to avoid a dir item overflow in
6639 		 * case we have an existing dir item due to existing name
6640 		 * hash collisions. We do this check here before we call
6641 		 * btrfs_add_link() down below so that we can avoid a
6642 		 * transaction abort (which could be exploited by malicious
6643 		 * users).
6644 		 *
6645 		 * For subvolumes we already do this in btrfs_mksubvol().
6646 		 */
6647 		ret = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
6648 						     btrfs_ino(BTRFS_I(dir)),
6649 						     name);
6650 		if (ret < 0)
6651 			return ret;
6652 	}
6653 
6654 	path = btrfs_alloc_path();
6655 	if (!path)
6656 		return -ENOMEM;
6657 
6658 	if (!args->subvol)
6659 		BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6660 	root = BTRFS_I(inode)->root;
6661 
6662 	ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
6663 	if (ret)
6664 		goto out;
6665 
6666 	ret = btrfs_get_free_objectid(root, &objectid);
6667 	if (ret)
6668 		goto out;
6669 	btrfs_set_inode_number(BTRFS_I(inode), objectid);
6670 
6671 	ret = xa_reserve(&root->inodes, objectid, GFP_NOFS);
6672 	if (ret)
6673 		goto out;
6674 	xa_reserved = true;
6675 
6676 	if (args->orphan) {
6677 		/*
6678 		 * O_TMPFILE, set link count to 0, so that after this point, we
6679 		 * fill in an inode item with the correct link count.
6680 		 */
6681 		set_nlink(inode, 0);
6682 	} else {
6683 		trace_btrfs_inode_request(dir);
6684 
6685 		ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6686 		if (ret)
6687 			goto out;
6688 	}
6689 
6690 	if (S_ISDIR(inode->i_mode))
6691 		BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6692 
6693 	BTRFS_I(inode)->generation = trans->transid;
6694 	inode->i_generation = BTRFS_I(inode)->generation;
6695 
6696 	/*
6697 	 * We don't have any capability xattrs set here yet, shortcut any
6698 	 * queries for the xattrs here.  If we add them later via the inode
6699 	 * security init path or any other path this flag will be cleared.
6700 	 */
6701 	set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
6702 
6703 	/*
6704 	 * Subvolumes don't inherit flags from their parent directory.
6705 	 * Originally this was probably by accident, but we probably can't
6706 	 * change it now without compatibility issues.
6707 	 */
6708 	if (!args->subvol)
6709 		btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6710 
6711 	btrfs_set_inode_mapping_order(BTRFS_I(inode));
6712 	if (S_ISREG(inode->i_mode)) {
6713 		if (btrfs_test_opt(fs_info, NODATASUM))
6714 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6715 		if (btrfs_test_opt(fs_info, NODATACOW))
6716 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6717 				BTRFS_INODE_NODATASUM;
6718 		btrfs_update_inode_mapping_flags(BTRFS_I(inode));
6719 	}
6720 
6721 	ret = btrfs_insert_inode_locked(inode);
6722 	if (ret < 0) {
6723 		if (!args->orphan)
6724 			BTRFS_I(dir)->index_cnt--;
6725 		goto out;
6726 	}
6727 
6728 	/*
6729 	 * We could have gotten an inode number from somebody who was fsynced
6730 	 * and then removed in this same transaction, so let's just set full
6731 	 * sync since it will be a full sync anyway and this will blow away the
6732 	 * old info in the log.
6733 	 */
6734 	btrfs_set_inode_full_sync(BTRFS_I(inode));
6735 
6736 	key[0].objectid = objectid;
6737 	key[0].type = BTRFS_INODE_ITEM_KEY;
6738 	key[0].offset = 0;
6739 
6740 	sizes[0] = sizeof(struct btrfs_inode_item);
6741 
6742 	if (!args->orphan) {
6743 		/*
6744 		 * Start new inodes with an inode_ref. This is slightly more
6745 		 * efficient for small numbers of hard links since they will
6746 		 * be packed into one item. Extended refs will kick in if we
6747 		 * add more hard links than can fit in the ref item.
6748 		 */
6749 		key[1].objectid = objectid;
6750 		key[1].type = BTRFS_INODE_REF_KEY;
6751 		if (args->subvol) {
6752 			key[1].offset = objectid;
6753 			sizes[1] = 2 + sizeof(*ref);
6754 		} else {
6755 			key[1].offset = btrfs_ino(BTRFS_I(dir));
6756 			sizes[1] = name->len + sizeof(*ref);
6757 		}
6758 	}
6759 
6760 	batch.keys = &key[0];
6761 	batch.data_sizes = &sizes[0];
6762 	batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6763 	batch.nr = args->orphan ? 1 : 2;
6764 	ret = btrfs_insert_empty_items(trans, root, path, &batch);
6765 	if (unlikely(ret != 0)) {
6766 		btrfs_abort_transaction(trans, ret);
6767 		goto discard;
6768 	}
6769 
6770 	ts = simple_inode_init_ts(inode);
6771 	BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
6772 	BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
6773 
6774 	/*
6775 	 * We're going to fill the inode item now, so at this point the inode
6776 	 * must be fully initialized.
6777 	 */
6778 
6779 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6780 				  struct btrfs_inode_item);
6781 	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6782 			     sizeof(*inode_item));
6783 	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6784 
6785 	if (!args->orphan) {
6786 		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6787 				     struct btrfs_inode_ref);
6788 		ptr = (unsigned long)(ref + 1);
6789 		if (args->subvol) {
6790 			btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6791 			btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6792 			write_extent_buffer(path->nodes[0], "..", ptr, 2);
6793 		} else {
6794 			btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6795 						     name->len);
6796 			btrfs_set_inode_ref_index(path->nodes[0], ref,
6797 						  BTRFS_I(inode)->dir_index);
6798 			write_extent_buffer(path->nodes[0], name->name, ptr,
6799 					    name->len);
6800 		}
6801 	}
6802 
6803 	/*
6804 	 * We don't need the path anymore, plus inheriting properties, adding
6805 	 * ACLs, security xattrs, orphan item or adding the link, will result in
6806 	 * allocating yet another path. So just free our path.
6807 	 */
6808 	btrfs_free_path(path);
6809 	path = NULL;
6810 
6811 	if (args->subvol) {
6812 		struct btrfs_inode *parent;
6813 
6814 		/*
6815 		 * Subvolumes inherit properties from their parent subvolume,
6816 		 * not the directory they were created in.
6817 		 */
6818 		parent = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, BTRFS_I(dir)->root);
6819 		if (IS_ERR(parent)) {
6820 			ret = PTR_ERR(parent);
6821 		} else {
6822 			ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6823 							parent);
6824 			iput(&parent->vfs_inode);
6825 		}
6826 	} else {
6827 		ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6828 						BTRFS_I(dir));
6829 	}
6830 	if (ret) {
6831 		btrfs_err(fs_info,
6832 			  "error inheriting props for ino %llu (root %llu): %pe",
6833 			  btrfs_ino(BTRFS_I(inode)), btrfs_root_id(root), ERR_PTR(ret));
6834 	}
6835 
6836 	/*
6837 	 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6838 	 * probably a bug.
6839 	 */
6840 	if (!args->subvol) {
6841 		ret = btrfs_init_inode_security(trans, args);
6842 		if (unlikely(ret)) {
6843 			btrfs_abort_transaction(trans, ret);
6844 			goto discard;
6845 		}
6846 	}
6847 
6848 	ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
6849 	if (WARN_ON(ret)) {
6850 		/* Shouldn't happen, we used xa_reserve() before. */
6851 		btrfs_abort_transaction(trans, ret);
6852 		goto discard;
6853 	}
6854 
6855 	trace_btrfs_inode_new(inode);
6856 	btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6857 
6858 	btrfs_update_root_times(trans, root);
6859 
6860 	if (args->orphan) {
6861 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6862 		if (unlikely(ret)) {
6863 			btrfs_abort_transaction(trans, ret);
6864 			goto discard;
6865 		}
6866 	} else {
6867 		ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6868 				     false, BTRFS_I(inode)->dir_index);
6869 		if (unlikely(ret)) {
6870 			btrfs_abort_transaction(trans, ret);
6871 			goto discard;
6872 		}
6873 	}
6874 
6875 	return 0;
6876 
6877 discard:
6878 	/*
6879 	 * discard_new_inode() calls iput(), but the caller owns the reference
6880 	 * to the inode.
6881 	 */
6882 	ihold(inode);
6883 	discard_new_inode(inode);
6884 out:
6885 	if (xa_reserved)
6886 		xa_release(&root->inodes, objectid);
6887 
6888 	btrfs_free_path(path);
6889 	return ret;
6890 }
6891 
6892 /*
6893  * utility function to add 'inode' into 'parent_inode' with
6894  * a give name and a given sequence number.
6895  * if 'add_backref' is true, also insert a backref from the
6896  * inode to the parent directory.
6897  */
btrfs_add_link(struct btrfs_trans_handle * trans,struct btrfs_inode * parent_inode,struct btrfs_inode * inode,const struct fscrypt_str * name,bool add_backref,u64 index)6898 int btrfs_add_link(struct btrfs_trans_handle *trans,
6899 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6900 		   const struct fscrypt_str *name, bool add_backref, u64 index)
6901 {
6902 	int ret = 0;
6903 	struct btrfs_key key;
6904 	struct btrfs_root *root = parent_inode->root;
6905 	u64 ino = btrfs_ino(inode);
6906 	u64 parent_ino = btrfs_ino(parent_inode);
6907 
6908 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6909 		memcpy(&key, &inode->root->root_key, sizeof(key));
6910 	} else {
6911 		key.objectid = ino;
6912 		key.type = BTRFS_INODE_ITEM_KEY;
6913 		key.offset = 0;
6914 	}
6915 
6916 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6917 		ret = btrfs_add_root_ref(trans, key.objectid,
6918 					 btrfs_root_id(root), parent_ino,
6919 					 index, name);
6920 	} else if (add_backref) {
6921 		ret = btrfs_insert_inode_ref(trans, root, name,
6922 					     ino, parent_ino, index);
6923 	}
6924 
6925 	/* Nothing to clean up yet */
6926 	if (ret)
6927 		return ret;
6928 
6929 	ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6930 				    btrfs_inode_type(inode), index);
6931 	if (ret == -EEXIST || ret == -EOVERFLOW)
6932 		goto fail_dir_item;
6933 	else if (unlikely(ret)) {
6934 		btrfs_abort_transaction(trans, ret);
6935 		return ret;
6936 	}
6937 
6938 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6939 			   name->len * 2);
6940 	inode_inc_iversion(&parent_inode->vfs_inode);
6941 	update_time_after_link_or_unlink(parent_inode);
6942 
6943 	ret = btrfs_update_inode(trans, parent_inode);
6944 	if (ret)
6945 		btrfs_abort_transaction(trans, ret);
6946 	return ret;
6947 
6948 fail_dir_item:
6949 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6950 		u64 local_index;
6951 		int ret2;
6952 
6953 		ret2 = btrfs_del_root_ref(trans, key.objectid, btrfs_root_id(root),
6954 					  parent_ino, &local_index, name);
6955 		if (ret2)
6956 			btrfs_abort_transaction(trans, ret2);
6957 	} else if (add_backref) {
6958 		int ret2;
6959 
6960 		ret2 = btrfs_del_inode_ref(trans, root, name, ino, parent_ino, NULL);
6961 		if (ret2)
6962 			btrfs_abort_transaction(trans, ret2);
6963 	}
6964 
6965 	/* Return the original error code */
6966 	return ret;
6967 }
6968 
btrfs_create_common(struct inode * dir,struct dentry * dentry,struct inode * inode)6969 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6970 			       struct inode *inode)
6971 {
6972 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6973 	struct btrfs_root *root = BTRFS_I(dir)->root;
6974 	struct btrfs_new_inode_args new_inode_args = {
6975 		.dir = dir,
6976 		.dentry = dentry,
6977 		.inode = inode,
6978 	};
6979 	unsigned int trans_num_items;
6980 	struct btrfs_trans_handle *trans;
6981 	int ret;
6982 
6983 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6984 	if (ret)
6985 		goto out_inode;
6986 
6987 	trans = btrfs_start_transaction(root, trans_num_items);
6988 	if (IS_ERR(trans)) {
6989 		ret = PTR_ERR(trans);
6990 		goto out_new_inode_args;
6991 	}
6992 
6993 	ret = btrfs_create_new_inode(trans, &new_inode_args);
6994 	if (!ret) {
6995 		if (S_ISDIR(inode->i_mode))
6996 			inode->i_opflags |= IOP_FASTPERM_MAY_EXEC;
6997 		d_instantiate_new(dentry, inode);
6998 	}
6999 
7000 	btrfs_end_transaction(trans);
7001 	btrfs_btree_balance_dirty(fs_info);
7002 out_new_inode_args:
7003 	btrfs_new_inode_args_destroy(&new_inode_args);
7004 out_inode:
7005 	if (ret)
7006 		iput(inode);
7007 	return ret;
7008 }
7009 
btrfs_mknod(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,dev_t rdev)7010 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
7011 		       struct dentry *dentry, umode_t mode, dev_t rdev)
7012 {
7013 	struct inode *inode;
7014 
7015 	inode = new_inode(dir->i_sb);
7016 	if (!inode)
7017 		return -ENOMEM;
7018 	inode_init_owner(idmap, inode, dir, mode);
7019 	inode->i_op = &btrfs_special_inode_operations;
7020 	init_special_inode(inode, inode->i_mode, rdev);
7021 	return btrfs_create_common(dir, dentry, inode);
7022 }
7023 
btrfs_create(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode)7024 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
7025 			struct dentry *dentry, umode_t mode)
7026 {
7027 	struct inode *inode;
7028 
7029 	inode = new_inode(dir->i_sb);
7030 	if (!inode)
7031 		return -ENOMEM;
7032 	inode_init_owner(idmap, inode, dir, mode);
7033 	inode->i_fop = &btrfs_file_operations;
7034 	inode->i_op = &btrfs_file_inode_operations;
7035 	inode->i_mapping->a_ops = &btrfs_aops;
7036 	return btrfs_create_common(dir, dentry, inode);
7037 }
7038 
btrfs_link(struct dentry * old_dentry,struct inode * dir,struct dentry * dentry)7039 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
7040 		      struct dentry *dentry)
7041 {
7042 	struct btrfs_trans_handle *trans = NULL;
7043 	struct btrfs_root *root = BTRFS_I(dir)->root;
7044 	struct inode *inode = d_inode(old_dentry);
7045 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
7046 	struct fscrypt_name fname;
7047 	u64 index;
7048 	int ret;
7049 
7050 	/* do not allow sys_link's with other subvols of the same device */
7051 	if (btrfs_root_id(root) != btrfs_root_id(BTRFS_I(inode)->root))
7052 		return -EXDEV;
7053 
7054 	if (inode->i_nlink >= BTRFS_LINK_MAX)
7055 		return -EMLINK;
7056 
7057 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
7058 	if (ret)
7059 		goto fail;
7060 
7061 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
7062 	if (ret)
7063 		goto fail;
7064 
7065 	/*
7066 	 * 2 items for inode and inode ref
7067 	 * 2 items for dir items
7068 	 * 1 item for parent inode
7069 	 * 1 item for orphan item deletion if O_TMPFILE
7070 	 */
7071 	trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
7072 	if (IS_ERR(trans)) {
7073 		ret = PTR_ERR(trans);
7074 		trans = NULL;
7075 		goto fail;
7076 	}
7077 
7078 	/* There are several dir indexes for this inode, clear the cache. */
7079 	BTRFS_I(inode)->dir_index = 0ULL;
7080 	inode_inc_iversion(inode);
7081 	inode_set_ctime_current(inode);
7082 
7083 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
7084 			     &fname.disk_name, true, index);
7085 	if (ret)
7086 		goto fail;
7087 
7088 	/* Link added now we update the inode item with the new link count. */
7089 	inc_nlink(inode);
7090 	ret = btrfs_update_inode(trans, BTRFS_I(inode));
7091 	if (unlikely(ret)) {
7092 		btrfs_abort_transaction(trans, ret);
7093 		goto fail;
7094 	}
7095 
7096 	if (inode->i_nlink == 1) {
7097 		/*
7098 		 * If the new hard link count is 1, it's a file created with the
7099 		 * open(2) O_TMPFILE flag.
7100 		 */
7101 		ret = btrfs_orphan_del(trans, BTRFS_I(inode));
7102 		if (unlikely(ret)) {
7103 			btrfs_abort_transaction(trans, ret);
7104 			goto fail;
7105 		}
7106 	}
7107 
7108 	/* Grab reference for the new dentry passed to d_instantiate(). */
7109 	ihold(inode);
7110 	d_instantiate(dentry, inode);
7111 	btrfs_log_new_name(trans, old_dentry, NULL, 0, dentry->d_parent);
7112 
7113 fail:
7114 	fscrypt_free_filename(&fname);
7115 	if (trans)
7116 		btrfs_end_transaction(trans);
7117 	btrfs_btree_balance_dirty(fs_info);
7118 	return ret;
7119 }
7120 
btrfs_mkdir(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode)7121 static struct dentry *btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
7122 				  struct dentry *dentry, umode_t mode)
7123 {
7124 	struct inode *inode;
7125 
7126 	inode = new_inode(dir->i_sb);
7127 	if (!inode)
7128 		return ERR_PTR(-ENOMEM);
7129 	inode_init_owner(idmap, inode, dir, mode);
7130 	inode->i_op = &btrfs_dir_inode_operations;
7131 	inode->i_fop = &btrfs_dir_file_operations;
7132 	return ERR_PTR(btrfs_create_common(dir, dentry, inode));
7133 }
7134 
uncompress_inline(struct btrfs_path * path,struct folio * folio,struct btrfs_file_extent_item * item)7135 static noinline int uncompress_inline(struct btrfs_path *path,
7136 				      struct folio *folio,
7137 				      struct btrfs_file_extent_item *item)
7138 {
7139 	int ret;
7140 	struct extent_buffer *leaf = path->nodes[0];
7141 	const u32 blocksize = leaf->fs_info->sectorsize;
7142 	char *tmp;
7143 	size_t max_size;
7144 	unsigned long inline_size;
7145 	unsigned long ptr;
7146 	int compress_type;
7147 
7148 	compress_type = btrfs_file_extent_compression(leaf, item);
7149 	max_size = btrfs_file_extent_ram_bytes(leaf, item);
7150 	inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
7151 	tmp = kmalloc(inline_size, GFP_NOFS);
7152 	if (!tmp)
7153 		return -ENOMEM;
7154 	ptr = btrfs_file_extent_inline_start(item);
7155 
7156 	read_extent_buffer(leaf, tmp, ptr, inline_size);
7157 
7158 	max_size = min_t(unsigned long, blocksize, max_size);
7159 	ret = btrfs_decompress(compress_type, tmp, folio, 0, inline_size,
7160 			       max_size);
7161 
7162 	/*
7163 	 * decompression code contains a memset to fill in any space between the end
7164 	 * of the uncompressed data and the end of max_size in case the decompressed
7165 	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
7166 	 * the end of an inline extent and the beginning of the next block, so we
7167 	 * cover that region here.
7168 	 */
7169 
7170 	if (max_size < blocksize)
7171 		folio_zero_range(folio, max_size, blocksize - max_size);
7172 	kfree(tmp);
7173 	return ret;
7174 }
7175 
read_inline_extent(struct btrfs_path * path,struct folio * folio)7176 static int read_inline_extent(struct btrfs_path *path, struct folio *folio)
7177 {
7178 	const u32 blocksize = path->nodes[0]->fs_info->sectorsize;
7179 	struct btrfs_file_extent_item *fi;
7180 	void *kaddr;
7181 	size_t copy_size;
7182 
7183 	if (!folio || folio_test_uptodate(folio))
7184 		return 0;
7185 
7186 	ASSERT(folio_pos(folio) == 0);
7187 
7188 	fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
7189 			    struct btrfs_file_extent_item);
7190 	if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
7191 		return uncompress_inline(path, folio, fi);
7192 
7193 	copy_size = min_t(u64, blocksize,
7194 			  btrfs_file_extent_ram_bytes(path->nodes[0], fi));
7195 	kaddr = kmap_local_folio(folio, 0);
7196 	read_extent_buffer(path->nodes[0], kaddr,
7197 			   btrfs_file_extent_inline_start(fi), copy_size);
7198 	kunmap_local(kaddr);
7199 	if (copy_size < blocksize)
7200 		folio_zero_range(folio, copy_size, blocksize - copy_size);
7201 	return 0;
7202 }
7203 
7204 /*
7205  * Lookup the first extent overlapping a range in a file.
7206  *
7207  * @inode:	file to search in
7208  * @page:	page to read extent data into if the extent is inline
7209  * @start:	file offset
7210  * @len:	length of range starting at @start
7211  *
7212  * Return the first &struct extent_map which overlaps the given range, reading
7213  * it from the B-tree and caching it if necessary. Note that there may be more
7214  * extents which overlap the given range after the returned extent_map.
7215  *
7216  * If @page is not NULL and the extent is inline, this also reads the extent
7217  * data directly into the page and marks the extent up to date in the io_tree.
7218  *
7219  * Return: ERR_PTR on error, non-NULL extent_map on success.
7220  */
btrfs_get_extent(struct btrfs_inode * inode,struct folio * folio,u64 start,u64 len)7221 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7222 				    struct folio *folio, u64 start, u64 len)
7223 {
7224 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7225 	int ret = 0;
7226 	u64 extent_start = 0;
7227 	u64 extent_end = 0;
7228 	u64 objectid = btrfs_ino(inode);
7229 	int extent_type = -1;
7230 	struct btrfs_path *path = NULL;
7231 	struct btrfs_root *root = inode->root;
7232 	struct btrfs_file_extent_item *item;
7233 	struct extent_buffer *leaf;
7234 	struct btrfs_key found_key;
7235 	struct extent_map *em = NULL;
7236 	struct extent_map_tree *em_tree = &inode->extent_tree;
7237 
7238 	read_lock(&em_tree->lock);
7239 	em = btrfs_lookup_extent_mapping(em_tree, start, len);
7240 	read_unlock(&em_tree->lock);
7241 
7242 	if (em) {
7243 		if (em->start > start || btrfs_extent_map_end(em) <= start)
7244 			btrfs_free_extent_map(em);
7245 		else if (em->disk_bytenr == EXTENT_MAP_INLINE && folio)
7246 			btrfs_free_extent_map(em);
7247 		else
7248 			goto out;
7249 	}
7250 	em = btrfs_alloc_extent_map();
7251 	if (!em) {
7252 		ret = -ENOMEM;
7253 		goto out;
7254 	}
7255 	em->start = EXTENT_MAP_HOLE;
7256 	em->disk_bytenr = EXTENT_MAP_HOLE;
7257 	em->len = (u64)-1;
7258 
7259 	path = btrfs_alloc_path();
7260 	if (!path) {
7261 		ret = -ENOMEM;
7262 		goto out;
7263 	}
7264 
7265 	/* Chances are we'll be called again, so go ahead and do readahead */
7266 	path->reada = READA_FORWARD;
7267 
7268 	/*
7269 	 * The same explanation in load_free_space_cache applies here as well,
7270 	 * we only read when we're loading the free space cache, and at that
7271 	 * point the commit_root has everything we need.
7272 	 */
7273 	if (btrfs_is_free_space_inode(inode)) {
7274 		path->search_commit_root = true;
7275 		path->skip_locking = true;
7276 	}
7277 
7278 	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7279 	if (ret < 0) {
7280 		goto out;
7281 	} else if (ret > 0) {
7282 		if (path->slots[0] == 0)
7283 			goto not_found;
7284 		path->slots[0]--;
7285 		ret = 0;
7286 	}
7287 
7288 	leaf = path->nodes[0];
7289 	item = btrfs_item_ptr(leaf, path->slots[0],
7290 			      struct btrfs_file_extent_item);
7291 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7292 	if (found_key.objectid != objectid ||
7293 	    found_key.type != BTRFS_EXTENT_DATA_KEY) {
7294 		/*
7295 		 * If we backup past the first extent we want to move forward
7296 		 * and see if there is an extent in front of us, otherwise we'll
7297 		 * say there is a hole for our whole search range which can
7298 		 * cause problems.
7299 		 */
7300 		extent_end = start;
7301 		goto next;
7302 	}
7303 
7304 	extent_type = btrfs_file_extent_type(leaf, item);
7305 	extent_start = found_key.offset;
7306 	extent_end = btrfs_file_extent_end(path);
7307 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7308 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7309 		/* Only regular file could have regular/prealloc extent */
7310 		if (unlikely(!S_ISREG(inode->vfs_inode.i_mode))) {
7311 			ret = -EUCLEAN;
7312 			btrfs_crit(fs_info,
7313 		"regular/prealloc extent found for non-regular inode %llu",
7314 				   btrfs_ino(inode));
7315 			goto out;
7316 		}
7317 		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7318 						       extent_start);
7319 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7320 		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7321 						      path->slots[0],
7322 						      extent_start);
7323 	}
7324 next:
7325 	if (start >= extent_end) {
7326 		path->slots[0]++;
7327 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7328 			ret = btrfs_next_leaf(root, path);
7329 			if (ret < 0)
7330 				goto out;
7331 			else if (ret > 0)
7332 				goto not_found;
7333 
7334 			leaf = path->nodes[0];
7335 		}
7336 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7337 		if (found_key.objectid != objectid ||
7338 		    found_key.type != BTRFS_EXTENT_DATA_KEY)
7339 			goto not_found;
7340 		if (start + len <= found_key.offset)
7341 			goto not_found;
7342 		if (start > found_key.offset)
7343 			goto next;
7344 
7345 		/* New extent overlaps with existing one */
7346 		em->start = start;
7347 		em->len = found_key.offset - start;
7348 		em->disk_bytenr = EXTENT_MAP_HOLE;
7349 		goto insert;
7350 	}
7351 
7352 	btrfs_extent_item_to_extent_map(inode, path, item, em);
7353 
7354 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7355 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7356 		goto insert;
7357 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7358 		/*
7359 		 * Inline extent can only exist at file offset 0. This is
7360 		 * ensured by tree-checker and inline extent creation path.
7361 		 * Thus all members representing file offsets should be zero.
7362 		 */
7363 		ASSERT(extent_start == 0);
7364 		ASSERT(em->start == 0);
7365 
7366 		/*
7367 		 * btrfs_extent_item_to_extent_map() should have properly
7368 		 * initialized em members already.
7369 		 *
7370 		 * Other members are not utilized for inline extents.
7371 		 */
7372 		ASSERT(em->disk_bytenr == EXTENT_MAP_INLINE);
7373 		ASSERT(em->len == fs_info->sectorsize);
7374 
7375 		ret = read_inline_extent(path, folio);
7376 		if (ret < 0)
7377 			goto out;
7378 		goto insert;
7379 	}
7380 not_found:
7381 	em->start = start;
7382 	em->len = len;
7383 	em->disk_bytenr = EXTENT_MAP_HOLE;
7384 insert:
7385 	ret = 0;
7386 	btrfs_release_path(path);
7387 	if (unlikely(em->start > start || btrfs_extent_map_end(em) <= start)) {
7388 		btrfs_err(fs_info,
7389 			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
7390 			  em->start, em->len, start, len);
7391 		ret = -EIO;
7392 		goto out;
7393 	}
7394 
7395 	write_lock(&em_tree->lock);
7396 	ret = btrfs_add_extent_mapping(inode, &em, start, len);
7397 	write_unlock(&em_tree->lock);
7398 out:
7399 	btrfs_free_path(path);
7400 
7401 	trace_btrfs_get_extent(root, inode, em);
7402 
7403 	if (ret) {
7404 		btrfs_free_extent_map(em);
7405 		return ERR_PTR(ret);
7406 	}
7407 	return em;
7408 }
7409 
btrfs_extent_readonly(struct btrfs_fs_info * fs_info,u64 bytenr)7410 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7411 {
7412 	struct btrfs_block_group *block_group;
7413 	bool readonly = false;
7414 
7415 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
7416 	if (!block_group || block_group->ro)
7417 		readonly = true;
7418 	if (block_group)
7419 		btrfs_put_block_group(block_group);
7420 	return readonly;
7421 }
7422 
7423 /*
7424  * Check if we can do nocow write into the range [@offset, @offset + @len)
7425  *
7426  * @offset:	File offset
7427  * @len:	The length to write, will be updated to the nocow writeable
7428  *		range
7429  * @orig_start:	(optional) Return the original file offset of the file extent
7430  * @orig_len:	(optional) Return the original on-disk length of the file extent
7431  * @ram_bytes:	(optional) Return the ram_bytes of the file extent
7432  *
7433  * Return:
7434  * >0	and update @len if we can do nocow write
7435  *  0	if we can't do nocow write
7436  * <0	if error happened
7437  *
7438  * NOTE: This only checks the file extents, caller is responsible to wait for
7439  *	 any ordered extents.
7440  */
can_nocow_extent(struct btrfs_inode * inode,u64 offset,u64 * len,struct btrfs_file_extent * file_extent,bool nowait)7441 noinline int can_nocow_extent(struct btrfs_inode *inode, u64 offset, u64 *len,
7442 			      struct btrfs_file_extent *file_extent,
7443 			      bool nowait)
7444 {
7445 	struct btrfs_root *root = inode->root;
7446 	struct btrfs_fs_info *fs_info = root->fs_info;
7447 	struct can_nocow_file_extent_args nocow_args = { 0 };
7448 	BTRFS_PATH_AUTO_FREE(path);
7449 	int ret;
7450 	struct extent_buffer *leaf;
7451 	struct extent_io_tree *io_tree = &inode->io_tree;
7452 	struct btrfs_file_extent_item *fi;
7453 	struct btrfs_key key;
7454 	int found_type;
7455 
7456 	path = btrfs_alloc_path();
7457 	if (!path)
7458 		return -ENOMEM;
7459 	path->nowait = nowait;
7460 
7461 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7462 				       offset, 0);
7463 	if (ret < 0)
7464 		return ret;
7465 
7466 	if (ret == 1) {
7467 		if (path->slots[0] == 0) {
7468 			/* Can't find the item, must COW. */
7469 			return 0;
7470 		}
7471 		path->slots[0]--;
7472 	}
7473 	ret = 0;
7474 	leaf = path->nodes[0];
7475 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7476 	if (key.objectid != btrfs_ino(inode) ||
7477 	    key.type != BTRFS_EXTENT_DATA_KEY) {
7478 		/* Not our file or wrong item type, must COW. */
7479 		return 0;
7480 	}
7481 
7482 	if (key.offset > offset) {
7483 		/* Wrong offset, must COW. */
7484 		return 0;
7485 	}
7486 
7487 	if (btrfs_file_extent_end(path) <= offset)
7488 		return 0;
7489 
7490 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7491 	found_type = btrfs_file_extent_type(leaf, fi);
7492 
7493 	nocow_args.start = offset;
7494 	nocow_args.end = offset + *len - 1;
7495 	nocow_args.free_path = true;
7496 
7497 	ret = can_nocow_file_extent(path, &key, inode, &nocow_args);
7498 	/* can_nocow_file_extent() has freed the path. */
7499 	path = NULL;
7500 
7501 	if (ret != 1) {
7502 		/* Treat errors as not being able to NOCOW. */
7503 		return 0;
7504 	}
7505 
7506 	if (btrfs_extent_readonly(fs_info,
7507 				  nocow_args.file_extent.disk_bytenr +
7508 				  nocow_args.file_extent.offset))
7509 		return 0;
7510 
7511 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
7512 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7513 		u64 range_end;
7514 
7515 		range_end = round_up(offset + nocow_args.file_extent.num_bytes,
7516 				     root->fs_info->sectorsize) - 1;
7517 		ret = btrfs_test_range_bit_exists(io_tree, offset, range_end,
7518 						  EXTENT_DELALLOC);
7519 		if (ret)
7520 			return -EAGAIN;
7521 	}
7522 
7523 	if (file_extent)
7524 		memcpy(file_extent, &nocow_args.file_extent, sizeof(*file_extent));
7525 
7526 	*len = nocow_args.file_extent.num_bytes;
7527 
7528 	return 1;
7529 }
7530 
7531 /* The callers of this must take lock_extent() */
btrfs_create_io_em(struct btrfs_inode * inode,u64 start,const struct btrfs_file_extent * file_extent,int type)7532 struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
7533 				      const struct btrfs_file_extent *file_extent,
7534 				      int type)
7535 {
7536 	struct extent_map *em;
7537 	int ret;
7538 
7539 	/*
7540 	 * Note the missing NOCOW type.
7541 	 *
7542 	 * For pure NOCOW writes, we should not create an io extent map, but
7543 	 * just reusing the existing one.
7544 	 * Only PREALLOC writes (NOCOW write into preallocated range) can
7545 	 * create an io extent map.
7546 	 */
7547 	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7548 	       type == BTRFS_ORDERED_COMPRESSED ||
7549 	       type == BTRFS_ORDERED_REGULAR);
7550 
7551 	switch (type) {
7552 	case BTRFS_ORDERED_PREALLOC:
7553 		/* We're only referring part of a larger preallocated extent. */
7554 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7555 		break;
7556 	case BTRFS_ORDERED_REGULAR:
7557 		/* COW results a new extent matching our file extent size. */
7558 		ASSERT(file_extent->disk_num_bytes == file_extent->num_bytes);
7559 		ASSERT(file_extent->ram_bytes == file_extent->num_bytes);
7560 
7561 		/* Since it's a new extent, we should not have any offset. */
7562 		ASSERT(file_extent->offset == 0);
7563 		break;
7564 	case BTRFS_ORDERED_COMPRESSED:
7565 		/* Must be compressed. */
7566 		ASSERT(file_extent->compression != BTRFS_COMPRESS_NONE);
7567 
7568 		/*
7569 		 * Encoded write can make us to refer to part of the
7570 		 * uncompressed extent.
7571 		 */
7572 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7573 		break;
7574 	}
7575 
7576 	em = btrfs_alloc_extent_map();
7577 	if (!em)
7578 		return ERR_PTR(-ENOMEM);
7579 
7580 	em->start = start;
7581 	em->len = file_extent->num_bytes;
7582 	em->disk_bytenr = file_extent->disk_bytenr;
7583 	em->disk_num_bytes = file_extent->disk_num_bytes;
7584 	em->ram_bytes = file_extent->ram_bytes;
7585 	em->generation = -1;
7586 	em->offset = file_extent->offset;
7587 	em->flags |= EXTENT_FLAG_PINNED;
7588 	if (type == BTRFS_ORDERED_COMPRESSED)
7589 		btrfs_extent_map_set_compression(em, file_extent->compression);
7590 
7591 	ret = btrfs_replace_extent_map_range(inode, em, true);
7592 	if (ret) {
7593 		btrfs_free_extent_map(em);
7594 		return ERR_PTR(ret);
7595 	}
7596 
7597 	/* em got 2 refs now, callers needs to do btrfs_free_extent_map once. */
7598 	return em;
7599 }
7600 
7601 /*
7602  * For release_folio() and invalidate_folio() we have a race window where
7603  * folio_end_writeback() is called but the subpage spinlock is not yet released.
7604  * If we continue to release/invalidate the page, we could cause use-after-free
7605  * for subpage spinlock.  So this function is to spin and wait for subpage
7606  * spinlock.
7607  */
wait_subpage_spinlock(struct folio * folio)7608 static void wait_subpage_spinlock(struct folio *folio)
7609 {
7610 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
7611 	struct btrfs_folio_state *bfs;
7612 
7613 	if (!btrfs_is_subpage(fs_info, folio))
7614 		return;
7615 
7616 	ASSERT(folio_test_private(folio) && folio_get_private(folio));
7617 	bfs = folio_get_private(folio);
7618 
7619 	/*
7620 	 * This may look insane as we just acquire the spinlock and release it,
7621 	 * without doing anything.  But we just want to make sure no one is
7622 	 * still holding the subpage spinlock.
7623 	 * And since the page is not dirty nor writeback, and we have page
7624 	 * locked, the only possible way to hold a spinlock is from the endio
7625 	 * function to clear page writeback.
7626 	 *
7627 	 * Here we just acquire the spinlock so that all existing callers
7628 	 * should exit and we're safe to release/invalidate the page.
7629 	 */
7630 	spin_lock_irq(&bfs->lock);
7631 	spin_unlock_irq(&bfs->lock);
7632 }
7633 
btrfs_launder_folio(struct folio * folio)7634 static int btrfs_launder_folio(struct folio *folio)
7635 {
7636 	return btrfs_qgroup_free_data(folio_to_inode(folio), NULL, folio_pos(folio),
7637 				      folio_size(folio), NULL);
7638 }
7639 
__btrfs_release_folio(struct folio * folio,gfp_t gfp_flags)7640 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7641 {
7642 	if (try_release_extent_mapping(folio, gfp_flags)) {
7643 		wait_subpage_spinlock(folio);
7644 		clear_folio_extent_mapped(folio);
7645 		return true;
7646 	}
7647 	return false;
7648 }
7649 
btrfs_release_folio(struct folio * folio,gfp_t gfp_flags)7650 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7651 {
7652 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
7653 		return false;
7654 	return __btrfs_release_folio(folio, gfp_flags);
7655 }
7656 
7657 #ifdef CONFIG_MIGRATION
btrfs_migrate_folio(struct address_space * mapping,struct folio * dst,struct folio * src,enum migrate_mode mode)7658 static int btrfs_migrate_folio(struct address_space *mapping,
7659 			     struct folio *dst, struct folio *src,
7660 			     enum migrate_mode mode)
7661 {
7662 	int ret = filemap_migrate_folio(mapping, dst, src, mode);
7663 
7664 	if (ret)
7665 		return ret;
7666 	return 0;
7667 }
7668 #else
7669 #define btrfs_migrate_folio NULL
7670 #endif
7671 
btrfs_invalidate_folio(struct folio * folio,size_t offset,size_t length)7672 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7673 				 size_t length)
7674 {
7675 	struct btrfs_inode *inode = folio_to_inode(folio);
7676 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7677 	struct extent_io_tree *tree = &inode->io_tree;
7678 	struct extent_state *cached_state = NULL;
7679 	u64 page_start = folio_pos(folio);
7680 	u64 page_end = page_start + folio_size(folio) - 1;
7681 	u64 cur;
7682 	int inode_evicting = inode_state_read_once(&inode->vfs_inode) & I_FREEING;
7683 
7684 	/*
7685 	 * We have folio locked so no new ordered extent can be created on this
7686 	 * page, nor bio can be submitted for this folio.
7687 	 *
7688 	 * But already submitted bio can still be finished on this folio.
7689 	 * Furthermore, endio function won't skip folio which has Ordered
7690 	 * already cleared, so it's possible for endio and
7691 	 * invalidate_folio to do the same ordered extent accounting twice
7692 	 * on one folio.
7693 	 *
7694 	 * So here we wait for any submitted bios to finish, so that we won't
7695 	 * do double ordered extent accounting on the same folio.
7696 	 */
7697 	folio_wait_writeback(folio);
7698 	wait_subpage_spinlock(folio);
7699 
7700 	/*
7701 	 * The invalidated blocks are going away; drop any fixup blocks among
7702 	 * them, data included, as they have no space reservation.
7703 	 */
7704 	btrfs_folio_clear_fixup_dirty(fs_info, folio, page_start + offset, length);
7705 
7706 	/*
7707 	 * For subpage case, we have call sites like
7708 	 * btrfs_punch_hole_lock_range() which passes range not aligned to
7709 	 * sectorsize.
7710 	 * If the range doesn't cover the full folio, we don't need to and
7711 	 * shouldn't clear page extent mapped, as folio->private can still
7712 	 * record subpage dirty bits for other part of the range.
7713 	 *
7714 	 * For cases that invalidate the full folio even the range doesn't
7715 	 * cover the full folio, like invalidating the last folio, we're
7716 	 * still safe to wait for ordered extent to finish.
7717 	 */
7718 	if (!(offset == 0 && length == folio_size(folio))) {
7719 		btrfs_release_folio(folio, GFP_NOFS);
7720 		return;
7721 	}
7722 
7723 	if (!inode_evicting)
7724 		btrfs_lock_extent(tree, page_start, page_end, &cached_state);
7725 
7726 	cur = page_start;
7727 	while (cur < page_end) {
7728 		struct btrfs_ordered_extent *ordered;
7729 		u64 range_end;
7730 		u32 range_len;
7731 		u32 extra_flags = 0;
7732 
7733 		ordered = btrfs_lookup_first_ordered_range(inode, cur,
7734 							   page_end + 1 - cur);
7735 		if (!ordered) {
7736 			range_end = page_end;
7737 			/*
7738 			 * No ordered extent covering this range, we are safe
7739 			 * to delete all extent states in the range.
7740 			 */
7741 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7742 			goto next;
7743 		}
7744 		if (ordered->file_offset > cur) {
7745 			/*
7746 			 * There is a range between [cur, oe->file_offset) not
7747 			 * covered by any ordered extent.
7748 			 * We are safe to delete all extent states, and handle
7749 			 * the ordered extent in the next iteration.
7750 			 */
7751 			range_end = ordered->file_offset - 1;
7752 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7753 			goto next;
7754 		}
7755 
7756 		range_end = min(ordered->file_offset + ordered->num_bytes - 1,
7757 				page_end);
7758 		ASSERT(range_end + 1 - cur < U32_MAX);
7759 		range_len = range_end + 1 - cur;
7760 		/*
7761 		 * If the range is not dirty, the range has been submitted and
7762 		 * since we have waited for the writeback, endio has been
7763 		 * executed, thus we must skip the range to avoid double
7764 		 * accounting for the ordered extent.
7765 		 */
7766 		if (!btrfs_folio_test_dirty(fs_info, folio, cur, range_len))
7767 			goto next;
7768 
7769 		/*
7770 		 * The range is dirty meaning it has not been submitted.
7771 		 * Here we need to truncate the OE range as the range will never
7772 		 * be submitted.
7773 		 *
7774 		 * IO on this page will never be started, so we need to account
7775 		 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
7776 		 * here, must leave that up for the ordered extent completion.
7777 		 *
7778 		 * This will also unlock the range for incoming
7779 		 * btrfs_finish_ordered_io().
7780 		 */
7781 		if (!inode_evicting)
7782 			btrfs_clear_extent_bit(tree, cur, range_end,
7783 					       EXTENT_DELALLOC |
7784 					       EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7785 					       EXTENT_DEFRAG, &cached_state);
7786 
7787 		btrfs_mark_ordered_extent_truncated(ordered, cur - ordered->file_offset);
7788 
7789 		/*
7790 		 * If the ordered extent has finished, we're safe to delete all
7791 		 * the extent states of the range, otherwise
7792 		 * btrfs_finish_ordered_io() will get executed by endio for
7793 		 * other pages, so we can't delete extent states.
7794 		 */
7795 		if (btrfs_dec_test_ordered_pending(inode, &ordered,
7796 						   cur, range_end + 1 - cur)) {
7797 			btrfs_finish_ordered_io(ordered);
7798 			/*
7799 			 * The ordered extent has finished, now we're again
7800 			 * safe to delete all extent states of the range.
7801 			 */
7802 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7803 		}
7804 next:
7805 		if (ordered)
7806 			btrfs_put_ordered_extent(ordered);
7807 		/*
7808 		 * Qgroup reserved space handler
7809 		 * Sector(s) here will be either:
7810 		 *
7811 		 * 1) Already written to disk or bio already finished
7812 		 *    Then its QGROUP_RESERVED bit in io_tree is already cleared.
7813 		 *    Qgroup will be handled by its qgroup_record then.
7814 		 *    btrfs_qgroup_free_data() call will do nothing here.
7815 		 *
7816 		 * 2) Not written to disk yet
7817 		 *    Then btrfs_qgroup_free_data() call will clear the
7818 		 *    QGROUP_RESERVED bit of its io_tree, and free the qgroup
7819 		 *    reserved data space.
7820 		 *    Since the IO will never happen for this page.
7821 		 */
7822 		btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
7823 		if (!inode_evicting)
7824 			btrfs_clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
7825 					       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7826 					       EXTENT_DEFRAG | extra_flags,
7827 					       &cached_state);
7828 		cur = range_end + 1;
7829 	}
7830 	btrfs_folio_clear_dirty(fs_info, folio, page_start, folio_size(folio));
7831 	btrfs_clear_folio_dirty_tag(folio);
7832 	if (!inode_evicting)
7833 		__btrfs_release_folio(folio, GFP_NOFS);
7834 	clear_folio_extent_mapped(folio);
7835 }
7836 
btrfs_truncate(struct btrfs_inode * inode,bool skip_writeback)7837 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
7838 {
7839 	struct btrfs_truncate_control control = {
7840 		.inode = inode,
7841 		.ino = btrfs_ino(inode),
7842 		.min_type = BTRFS_EXTENT_DATA_KEY,
7843 		.clear_extent_range = true,
7844 		.new_size = inode->vfs_inode.i_size,
7845 	};
7846 	struct btrfs_root *root = inode->root;
7847 	struct btrfs_fs_info *fs_info = root->fs_info;
7848 	struct btrfs_block_rsv rsv;
7849 	int ret;
7850 	struct btrfs_trans_handle *trans;
7851 	const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
7852 	const u64 lock_start = round_down(inode->vfs_inode.i_size, fs_info->sectorsize);
7853 	const u64 i_size_up = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
7854 
7855 	/* Our inode is locked and the i_size can't be changed concurrently. */
7856 	btrfs_assert_inode_locked(inode);
7857 
7858 	if (!skip_writeback) {
7859 		ret = btrfs_wait_ordered_range(inode, lock_start, (u64)-1);
7860 		if (ret)
7861 			return ret;
7862 	}
7863 
7864 	/*
7865 	 * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
7866 	 * things going on here:
7867 	 *
7868 	 * 1) We need to reserve space to update our inode.
7869 	 *
7870 	 * 2) We need to have something to cache all the space that is going to
7871 	 * be free'd up by the truncate operation, but also have some slack
7872 	 * space reserved in case it uses space during the truncate (thank you
7873 	 * very much snapshotting).
7874 	 *
7875 	 * And we need these to be separate.  The fact is we can use a lot of
7876 	 * space doing the truncate, and we have no earthly idea how much space
7877 	 * we will use, so we need the truncate reservation to be separate so it
7878 	 * doesn't end up using space reserved for updating the inode.  We also
7879 	 * need to be able to stop the transaction and start a new one, which
7880 	 * means we need to be able to update the inode several times, and we
7881 	 * have no idea of knowing how many times that will be, so we can't just
7882 	 * reserve 1 item for the entirety of the operation, so that has to be
7883 	 * done separately as well.
7884 	 *
7885 	 * So that leaves us with
7886 	 *
7887 	 * 1) rsv - for the truncate reservation, which we will steal from the
7888 	 * transaction reservation.
7889 	 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
7890 	 * updating the inode.
7891 	 */
7892 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
7893 	rsv.size = min_size;
7894 	rsv.failfast = true;
7895 
7896 	/*
7897 	 * 1 for the truncate slack space
7898 	 * 1 for updating the inode.
7899 	 */
7900 	trans = btrfs_start_transaction(root, 2);
7901 	if (IS_ERR(trans)) {
7902 		ret = PTR_ERR(trans);
7903 		goto out;
7904 	}
7905 
7906 	/* Migrate the slack space for the truncate to our reserve */
7907 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, &rsv,
7908 				      min_size, false);
7909 	/*
7910 	 * We have reserved 2 metadata units when we started the transaction and
7911 	 * min_size matches 1 unit, so this should never fail, but if it does,
7912 	 * it's not critical we just fail truncation.
7913 	 */
7914 	if (WARN_ON(ret)) {
7915 		btrfs_end_transaction(trans);
7916 		goto out;
7917 	}
7918 
7919 	trans->block_rsv = &rsv;
7920 
7921 	while (1) {
7922 		struct extent_state *cached_state = NULL;
7923 
7924 		btrfs_lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7925 		/*
7926 		 * We want to drop from the next block forward in case this new
7927 		 * size is not block aligned since we will be keeping the last
7928 		 * block of the extent just the way it is.
7929 		 */
7930 		btrfs_drop_extent_map_range(inode, i_size_up, (u64)-1, false);
7931 
7932 		ret = btrfs_truncate_inode_items(trans, root, &control);
7933 
7934 		inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
7935 		btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
7936 
7937 		btrfs_unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7938 
7939 		trans->block_rsv = &fs_info->trans_block_rsv;
7940 		if (ret != -ENOSPC && ret != -EAGAIN)
7941 			break;
7942 
7943 		ret = btrfs_update_inode(trans, inode);
7944 		if (ret)
7945 			break;
7946 
7947 		btrfs_end_transaction(trans);
7948 		btrfs_btree_balance_dirty(fs_info);
7949 
7950 		trans = btrfs_start_transaction(root, 2);
7951 		if (IS_ERR(trans)) {
7952 			ret = PTR_ERR(trans);
7953 			trans = NULL;
7954 			break;
7955 		}
7956 
7957 		btrfs_block_rsv_release(fs_info, &rsv, -1, NULL);
7958 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
7959 					      &rsv, min_size, false);
7960 		/*
7961 		 * We have reserved 2 metadata units when we started the
7962 		 * transaction and min_size matches 1 unit, so this should never
7963 		 * fail, but if it does, it's not critical we just fail truncation.
7964 		 */
7965 		if (WARN_ON(ret))
7966 			break;
7967 
7968 		trans->block_rsv = &rsv;
7969 	}
7970 
7971 	/*
7972 	 * We can't call btrfs_truncate_block inside a trans handle as we could
7973 	 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
7974 	 * know we've truncated everything except the last little bit, and can
7975 	 * do btrfs_truncate_block and then update the disk_i_size.
7976 	 */
7977 	if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
7978 		btrfs_end_transaction(trans);
7979 		btrfs_btree_balance_dirty(fs_info);
7980 
7981 		ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size,
7982 					   inode->vfs_inode.i_size, (u64)-1);
7983 		if (ret)
7984 			goto out;
7985 		trans = btrfs_start_transaction(root, 1);
7986 		if (IS_ERR(trans)) {
7987 			ret = PTR_ERR(trans);
7988 			goto out;
7989 		}
7990 		btrfs_inode_safe_disk_i_size_write(inode, 0);
7991 	}
7992 
7993 	if (trans) {
7994 		int ret2;
7995 
7996 		trans->block_rsv = &fs_info->trans_block_rsv;
7997 		ret2 = btrfs_update_inode(trans, inode);
7998 		if (ret2 && !ret)
7999 			ret = ret2;
8000 
8001 		ret2 = btrfs_end_transaction(trans);
8002 		if (ret2 && !ret)
8003 			ret = ret2;
8004 		btrfs_btree_balance_dirty(fs_info);
8005 	}
8006 out:
8007 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
8008 	/*
8009 	 * So if we truncate and then write and fsync we normally would just
8010 	 * write the extents that changed, which is a problem if we need to
8011 	 * first truncate that entire inode.  So set this flag so we write out
8012 	 * all of the extents in the inode to the sync log so we're completely
8013 	 * safe.
8014 	 *
8015 	 * If no extents were dropped or trimmed we don't need to force the next
8016 	 * fsync to truncate all the inode's items from the log and re-log them
8017 	 * all. This means the truncate operation did not change the file size,
8018 	 * or changed it to a smaller size but there was only an implicit hole
8019 	 * between the old i_size and the new i_size, and there were no prealloc
8020 	 * extents beyond i_size to drop.
8021 	 */
8022 	if (control.extents_found > 0)
8023 		btrfs_set_inode_full_sync(inode);
8024 
8025 	return ret;
8026 }
8027 
btrfs_new_subvol_inode(struct mnt_idmap * idmap,struct inode * dir)8028 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8029 				     struct inode *dir)
8030 {
8031 	struct inode *inode;
8032 
8033 	inode = new_inode(dir->i_sb);
8034 	if (inode) {
8035 		/*
8036 		 * Subvolumes don't inherit the sgid bit or the parent's gid if
8037 		 * the parent's sgid bit is set. This is probably a bug.
8038 		 */
8039 		inode_init_owner(idmap, inode, NULL,
8040 				 S_IFDIR | (~current_umask() & S_IRWXUGO));
8041 		inode->i_op = &btrfs_dir_inode_operations;
8042 		inode->i_fop = &btrfs_dir_file_operations;
8043 	}
8044 	return inode;
8045 }
8046 
btrfs_alloc_inode(struct super_block * sb)8047 struct inode *btrfs_alloc_inode(struct super_block *sb)
8048 {
8049 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8050 	struct btrfs_inode *ei;
8051 	struct inode *inode;
8052 
8053 	ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8054 	if (!ei)
8055 		return NULL;
8056 
8057 	ei->root = NULL;
8058 	ei->generation = 0;
8059 	ei->last_trans = 0;
8060 	ei->last_sub_trans = 0;
8061 	ei->logged_trans = 0;
8062 	ei->delalloc_bytes = 0;
8063 	/* new_delalloc_bytes and last_dir_index_offset are in a union. */
8064 	ei->new_delalloc_bytes = 0;
8065 	ei->defrag_bytes = 0;
8066 	ei->disk_i_size = 0;
8067 	ei->flags = 0;
8068 	ei->ro_flags = 0;
8069 	/*
8070 	 * ->index_cnt will be properly initialized later when creating a new
8071 	 * inode (btrfs_create_new_inode()) or when reading an existing inode
8072 	 * from disk (btrfs_read_locked_inode()).
8073 	 */
8074 	ei->csum_bytes = 0;
8075 	ei->dir_index = 0;
8076 	ei->last_unlink_trans = 0;
8077 	ei->last_reflink_trans = 0;
8078 	ei->last_log_commit = 0;
8079 
8080 	spin_lock_init(&ei->lock);
8081 	ei->outstanding_extents = 0;
8082 	if (sb->s_magic != BTRFS_TEST_MAGIC)
8083 		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8084 					      BTRFS_BLOCK_RSV_DELALLOC);
8085 	ei->runtime_flags = 0;
8086 	ei->prop_compress = BTRFS_COMPRESS_NONE;
8087 	ei->defrag_compress = BTRFS_COMPRESS_NONE;
8088 
8089 	ei->delayed_node = NULL;
8090 
8091 	ei->i_otime_sec = 0;
8092 	ei->i_otime_nsec = 0;
8093 
8094 	inode = &ei->vfs_inode;
8095 	btrfs_extent_map_tree_init(&ei->extent_tree);
8096 
8097 	/* This io tree sets the valid inode. */
8098 	btrfs_extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8099 	ei->io_tree.inode = ei;
8100 
8101 	ei->file_extent_tree = NULL;
8102 
8103 	mutex_init(&ei->log_mutex);
8104 	spin_lock_init(&ei->ordered_tree_lock);
8105 	ei->ordered_tree = RB_ROOT;
8106 	ei->ordered_tree_last = NULL;
8107 	INIT_LIST_HEAD(&ei->delalloc_inodes);
8108 	INIT_LIST_HEAD(&ei->delayed_iput);
8109 	init_rwsem(&ei->i_mmap_lock);
8110 
8111 	return inode;
8112 }
8113 
8114 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
btrfs_test_destroy_inode(struct inode * inode)8115 void btrfs_test_destroy_inode(struct inode *inode)
8116 {
8117 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8118 	kfree(BTRFS_I(inode)->file_extent_tree);
8119 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8120 }
8121 #endif
8122 
btrfs_free_inode(struct inode * inode)8123 void btrfs_free_inode(struct inode *inode)
8124 {
8125 	kfree(BTRFS_I(inode)->file_extent_tree);
8126 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8127 }
8128 
btrfs_destroy_inode(struct inode * vfs_inode)8129 void btrfs_destroy_inode(struct inode *vfs_inode)
8130 {
8131 	struct btrfs_ordered_extent *ordered;
8132 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8133 	struct btrfs_root *root = inode->root;
8134 	bool freespace_inode;
8135 
8136 	WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8137 	WARN_ON(vfs_inode->i_data.nrpages);
8138 	WARN_ON(inode->block_rsv.reserved);
8139 	WARN_ON(inode->block_rsv.size);
8140 	WARN_ON(inode->outstanding_extents);
8141 	if (!S_ISDIR(vfs_inode->i_mode)) {
8142 		WARN_ON(inode->delalloc_bytes);
8143 		WARN_ON(inode->new_delalloc_bytes);
8144 		WARN_ON(inode->csum_bytes);
8145 	}
8146 	if (!root || !btrfs_is_data_reloc_root(root))
8147 		WARN_ON(inode->defrag_bytes);
8148 
8149 	/*
8150 	 * This can happen where we create an inode, but somebody else also
8151 	 * created the same inode and we need to destroy the one we already
8152 	 * created.
8153 	 */
8154 	if (!root)
8155 		return;
8156 
8157 	/*
8158 	 * If this is a free space inode do not take the ordered extents lockdep
8159 	 * map.
8160 	 */
8161 	freespace_inode = btrfs_is_free_space_inode(inode);
8162 
8163 	while (1) {
8164 		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8165 		if (!ordered)
8166 			break;
8167 		else {
8168 			btrfs_err(root->fs_info,
8169 				  "found ordered extent %llu %llu on inode cleanup",
8170 				  ordered->file_offset, ordered->num_bytes);
8171 
8172 			if (!freespace_inode)
8173 				btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8174 
8175 			btrfs_remove_ordered_extent(ordered);
8176 			btrfs_put_ordered_extent(ordered);
8177 			btrfs_put_ordered_extent(ordered);
8178 		}
8179 	}
8180 	btrfs_qgroup_check_reserved_leak(inode);
8181 	btrfs_del_inode_from_root(inode);
8182 	btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8183 	btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8184 	btrfs_put_root(inode->root);
8185 }
8186 
btrfs_drop_inode(struct inode * inode)8187 int btrfs_drop_inode(struct inode *inode)
8188 {
8189 	struct btrfs_root *root = BTRFS_I(inode)->root;
8190 
8191 	if (root == NULL)
8192 		return 1;
8193 
8194 	/* the snap/subvol tree is on deleting */
8195 	if (btrfs_root_refs(&root->root_item) == 0)
8196 		return 1;
8197 	else
8198 		return inode_generic_drop(inode);
8199 }
8200 
init_once(void * foo)8201 static void init_once(void *foo)
8202 {
8203 	struct btrfs_inode *ei = foo;
8204 
8205 	inode_init_once(&ei->vfs_inode);
8206 }
8207 
btrfs_destroy_cachep(void)8208 void __cold btrfs_destroy_cachep(void)
8209 {
8210 	/*
8211 	 * Make sure all delayed rcu free inodes are flushed before we
8212 	 * destroy cache.
8213 	 */
8214 	rcu_barrier();
8215 	kmem_cache_destroy(btrfs_inode_cachep);
8216 }
8217 
btrfs_init_cachep(void)8218 int __init btrfs_init_cachep(void)
8219 {
8220 	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8221 			sizeof(struct btrfs_inode), 0,
8222 			SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
8223 			init_once);
8224 	if (!btrfs_inode_cachep)
8225 		return -ENOMEM;
8226 
8227 	return 0;
8228 }
8229 
btrfs_getattr(struct mnt_idmap * idmap,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int flags)8230 static int btrfs_getattr(struct mnt_idmap *idmap,
8231 			 const struct path *path, struct kstat *stat,
8232 			 u32 request_mask, unsigned int flags)
8233 {
8234 	u64 delalloc_bytes;
8235 	u64 inode_bytes;
8236 	struct inode *inode = d_inode(path->dentry);
8237 	u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
8238 	u32 bi_flags = BTRFS_I(inode)->flags;
8239 	u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8240 
8241 	stat->result_mask |= STATX_BTIME;
8242 	stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
8243 	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
8244 	if (bi_flags & BTRFS_INODE_APPEND)
8245 		stat->attributes |= STATX_ATTR_APPEND;
8246 	if (bi_flags & BTRFS_INODE_COMPRESS)
8247 		stat->attributes |= STATX_ATTR_COMPRESSED;
8248 	if (bi_flags & BTRFS_INODE_IMMUTABLE)
8249 		stat->attributes |= STATX_ATTR_IMMUTABLE;
8250 	if (bi_flags & BTRFS_INODE_NODUMP)
8251 		stat->attributes |= STATX_ATTR_NODUMP;
8252 	if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8253 		stat->attributes |= STATX_ATTR_VERITY;
8254 
8255 	stat->attributes_mask |= (STATX_ATTR_APPEND |
8256 				  STATX_ATTR_COMPRESSED |
8257 				  STATX_ATTR_IMMUTABLE |
8258 				  STATX_ATTR_NODUMP);
8259 
8260 	generic_fillattr(idmap, request_mask, inode, stat);
8261 	stat->dev = BTRFS_I(inode)->root->anon_dev;
8262 
8263 	stat->subvol = btrfs_root_id(BTRFS_I(inode)->root);
8264 	stat->result_mask |= STATX_SUBVOL;
8265 
8266 	spin_lock(&BTRFS_I(inode)->lock);
8267 	delalloc_bytes = S_ISREG(inode->i_mode) ?
8268 			 BTRFS_I(inode)->new_delalloc_bytes : 0;
8269 	inode_bytes = inode_get_bytes(inode);
8270 	spin_unlock(&BTRFS_I(inode)->lock);
8271 	stat->blocks = (ALIGN(inode_bytes, blocksize) +
8272 			ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8273 	return 0;
8274 }
8275 
btrfs_rename_exchange(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)8276 static int btrfs_rename_exchange(struct inode *old_dir,
8277 			      struct dentry *old_dentry,
8278 			      struct inode *new_dir,
8279 			      struct dentry *new_dentry)
8280 {
8281 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8282 	struct btrfs_trans_handle *trans;
8283 	unsigned int trans_num_items;
8284 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8285 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8286 	struct inode *new_inode = new_dentry->d_inode;
8287 	struct inode *old_inode = old_dentry->d_inode;
8288 	struct btrfs_rename_ctx old_rename_ctx;
8289 	struct btrfs_rename_ctx new_rename_ctx;
8290 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8291 	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8292 	u64 old_idx = 0;
8293 	u64 new_idx = 0;
8294 	int ret;
8295 	int ret2;
8296 	bool need_abort = false;
8297 	bool logs_pinned = false;
8298 	struct fscrypt_name old_fname, new_fname;
8299 	struct fscrypt_str *old_name, *new_name;
8300 
8301 	/*
8302 	 * For non-subvolumes allow exchange only within one subvolume, in the
8303 	 * same inode namespace. Two subvolumes (represented as directory) can
8304 	 * be exchanged as they're a logical link and have a fixed inode number.
8305 	 */
8306 	if (root != dest &&
8307 	    (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8308 	     new_ino != BTRFS_FIRST_FREE_OBJECTID))
8309 		return -EXDEV;
8310 
8311 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8312 	if (ret)
8313 		return ret;
8314 
8315 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8316 	if (ret) {
8317 		fscrypt_free_filename(&old_fname);
8318 		return ret;
8319 	}
8320 
8321 	old_name = &old_fname.disk_name;
8322 	new_name = &new_fname.disk_name;
8323 
8324 	/* close the race window with snapshot create/destroy ioctl */
8325 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8326 	    new_ino == BTRFS_FIRST_FREE_OBJECTID)
8327 		down_read(&fs_info->subvol_sem);
8328 
8329 	/*
8330 	 * For each inode:
8331 	 * 1 to remove old dir item
8332 	 * 1 to remove old dir index
8333 	 * 1 to add new dir item
8334 	 * 1 to add new dir index
8335 	 * 1 to update parent inode
8336 	 *
8337 	 * If the parents are the same, we only need to account for one
8338 	 */
8339 	trans_num_items = (old_dir == new_dir ? 9 : 10);
8340 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8341 		/*
8342 		 * 1 to remove old root ref
8343 		 * 1 to remove old root backref
8344 		 * 1 to add new root ref
8345 		 * 1 to add new root backref
8346 		 */
8347 		trans_num_items += 4;
8348 	} else {
8349 		/*
8350 		 * 1 to update inode item
8351 		 * 1 to remove old inode ref
8352 		 * 1 to add new inode ref
8353 		 */
8354 		trans_num_items += 3;
8355 	}
8356 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8357 		trans_num_items += 4;
8358 	else
8359 		trans_num_items += 3;
8360 	trans = btrfs_start_transaction(root, trans_num_items);
8361 	if (IS_ERR(trans)) {
8362 		ret = PTR_ERR(trans);
8363 		goto out_notrans;
8364 	}
8365 
8366 	if (dest != root) {
8367 		ret = btrfs_record_root_in_trans(trans, dest);
8368 		if (ret)
8369 			goto out_fail;
8370 	}
8371 
8372 	/*
8373 	 * We need to find a free sequence number both in the source and
8374 	 * in the destination directory for the exchange.
8375 	 */
8376 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8377 	if (ret)
8378 		goto out_fail;
8379 	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8380 	if (ret)
8381 		goto out_fail;
8382 
8383 	BTRFS_I(old_inode)->dir_index = 0ULL;
8384 	BTRFS_I(new_inode)->dir_index = 0ULL;
8385 
8386 	/* Reference for the source. */
8387 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8388 		/* force full log commit if subvolume involved. */
8389 		btrfs_set_log_full_commit(trans);
8390 	} else {
8391 		ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8392 					     btrfs_ino(BTRFS_I(new_dir)),
8393 					     old_idx);
8394 		if (ret)
8395 			goto out_fail;
8396 		need_abort = true;
8397 	}
8398 
8399 	/* And now for the dest. */
8400 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8401 		/* force full log commit if subvolume involved. */
8402 		btrfs_set_log_full_commit(trans);
8403 	} else {
8404 		ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8405 					     btrfs_ino(BTRFS_I(old_dir)),
8406 					     new_idx);
8407 		if (ret) {
8408 			if (unlikely(need_abort))
8409 				btrfs_abort_transaction(trans, ret);
8410 			goto out_fail;
8411 		}
8412 	}
8413 
8414 	/* Update inode version and ctime/mtime. */
8415 	inode_inc_iversion(old_dir);
8416 	inode_inc_iversion(new_dir);
8417 	inode_inc_iversion(old_inode);
8418 	inode_inc_iversion(new_inode);
8419 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8420 
8421 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID &&
8422 	    new_ino != BTRFS_FIRST_FREE_OBJECTID) {
8423 		/*
8424 		 * If we are renaming in the same directory (and it's not for
8425 		 * root entries) pin the log early to prevent any concurrent
8426 		 * task from logging the directory after we removed the old
8427 		 * entries and before we add the new entries, otherwise that
8428 		 * task can sync a log without any entry for the inodes we are
8429 		 * renaming and therefore replaying that log, if a power failure
8430 		 * happens after syncing the log, would result in deleting the
8431 		 * inodes.
8432 		 *
8433 		 * If the rename affects two different directories, we want to
8434 		 * make sure the that there's no log commit that contains
8435 		 * updates for only one of the directories but not for the
8436 		 * other.
8437 		 *
8438 		 * If we are renaming an entry for a root, we don't care about
8439 		 * log updates since we called btrfs_set_log_full_commit().
8440 		 */
8441 		btrfs_pin_log_trans(root);
8442 		btrfs_pin_log_trans(dest);
8443 		logs_pinned = true;
8444 	}
8445 
8446 	if (old_dentry->d_parent != new_dentry->d_parent) {
8447 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8448 					BTRFS_I(old_inode), true);
8449 		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8450 					BTRFS_I(new_inode), true);
8451 	}
8452 
8453 	/* src is a subvolume */
8454 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8455 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8456 		if (unlikely(ret)) {
8457 			btrfs_abort_transaction(trans, ret);
8458 			goto out_fail;
8459 		}
8460 	} else { /* src is an inode */
8461 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8462 					   BTRFS_I(old_dentry->d_inode),
8463 					   old_name, &old_rename_ctx);
8464 		if (unlikely(ret)) {
8465 			btrfs_abort_transaction(trans, ret);
8466 			goto out_fail;
8467 		}
8468 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8469 		if (unlikely(ret)) {
8470 			btrfs_abort_transaction(trans, ret);
8471 			goto out_fail;
8472 		}
8473 	}
8474 
8475 	/* dest is a subvolume */
8476 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8477 		ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8478 		if (unlikely(ret)) {
8479 			btrfs_abort_transaction(trans, ret);
8480 			goto out_fail;
8481 		}
8482 	} else { /* dest is an inode */
8483 		ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8484 					   BTRFS_I(new_dentry->d_inode),
8485 					   new_name, &new_rename_ctx);
8486 		if (unlikely(ret)) {
8487 			btrfs_abort_transaction(trans, ret);
8488 			goto out_fail;
8489 		}
8490 		ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
8491 		if (unlikely(ret)) {
8492 			btrfs_abort_transaction(trans, ret);
8493 			goto out_fail;
8494 		}
8495 	}
8496 
8497 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8498 			     new_name, false, old_idx);
8499 	if (unlikely(ret)) {
8500 		btrfs_abort_transaction(trans, ret);
8501 		goto out_fail;
8502 	}
8503 
8504 	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8505 			     old_name, false, new_idx);
8506 	if (unlikely(ret)) {
8507 		btrfs_abort_transaction(trans, ret);
8508 		goto out_fail;
8509 	}
8510 
8511 	if (old_inode->i_nlink == 1)
8512 		BTRFS_I(old_inode)->dir_index = old_idx;
8513 	if (new_inode->i_nlink == 1)
8514 		BTRFS_I(new_inode)->dir_index = new_idx;
8515 
8516 	/*
8517 	 * Do the log updates for all inodes.
8518 	 *
8519 	 * If either entry is for a root we don't need to update the logs since
8520 	 * we've called btrfs_set_log_full_commit() before.
8521 	 */
8522 	if (logs_pinned) {
8523 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8524 				   old_rename_ctx.index, new_dentry->d_parent);
8525 		btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8526 				   new_rename_ctx.index, old_dentry->d_parent);
8527 	}
8528 
8529 out_fail:
8530 	if (logs_pinned) {
8531 		btrfs_end_log_trans(root);
8532 		btrfs_end_log_trans(dest);
8533 	}
8534 	ret2 = btrfs_end_transaction(trans);
8535 	ret = ret ? ret : ret2;
8536 out_notrans:
8537 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8538 	    old_ino == BTRFS_FIRST_FREE_OBJECTID)
8539 		up_read(&fs_info->subvol_sem);
8540 
8541 	fscrypt_free_filename(&new_fname);
8542 	fscrypt_free_filename(&old_fname);
8543 	return ret;
8544 }
8545 
new_whiteout_inode(struct mnt_idmap * idmap,struct inode * dir)8546 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8547 					struct inode *dir)
8548 {
8549 	struct inode *inode;
8550 
8551 	inode = new_inode(dir->i_sb);
8552 	if (inode) {
8553 		inode_init_owner(idmap, inode, dir,
8554 				 S_IFCHR | WHITEOUT_MODE);
8555 		inode->i_op = &btrfs_special_inode_operations;
8556 		init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8557 	}
8558 	return inode;
8559 }
8560 
btrfs_rename(struct mnt_idmap * idmap,struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry,unsigned int flags)8561 static int btrfs_rename(struct mnt_idmap *idmap,
8562 			struct inode *old_dir, struct dentry *old_dentry,
8563 			struct inode *new_dir, struct dentry *new_dentry,
8564 			unsigned int flags)
8565 {
8566 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8567 	struct btrfs_new_inode_args whiteout_args = {
8568 		.dir = old_dir,
8569 		.dentry = old_dentry,
8570 	};
8571 	struct btrfs_trans_handle *trans;
8572 	unsigned int trans_num_items;
8573 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8574 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8575 	struct inode *new_inode = d_inode(new_dentry);
8576 	struct inode *old_inode = d_inode(old_dentry);
8577 	struct btrfs_rename_ctx rename_ctx;
8578 	u64 index = 0;
8579 	int ret;
8580 	int ret2;
8581 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8582 	struct fscrypt_name old_fname, new_fname;
8583 	bool logs_pinned = false;
8584 
8585 	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8586 		return -EPERM;
8587 
8588 	/* we only allow rename subvolume link between subvolumes */
8589 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8590 		return -EXDEV;
8591 
8592 	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8593 	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8594 		return -ENOTEMPTY;
8595 
8596 	if (S_ISDIR(old_inode->i_mode) && new_inode &&
8597 	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8598 		return -ENOTEMPTY;
8599 
8600 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8601 	if (ret)
8602 		return ret;
8603 
8604 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8605 	if (ret) {
8606 		fscrypt_free_filename(&old_fname);
8607 		return ret;
8608 	}
8609 
8610 	/* check for collisions, even if the  name isn't there */
8611 	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8612 	if (ret) {
8613 		if (ret == -EEXIST) {
8614 			/* we shouldn't get
8615 			 * eexist without a new_inode */
8616 			if (WARN_ON(!new_inode)) {
8617 				goto out_fscrypt_names;
8618 			}
8619 		} else {
8620 			/* maybe -EOVERFLOW */
8621 			goto out_fscrypt_names;
8622 		}
8623 	}
8624 	ret = 0;
8625 
8626 	/*
8627 	 * we're using rename to replace one file with another.  Start IO on it
8628 	 * now so  we don't add too much work to the end of the transaction
8629 	 */
8630 	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8631 		filemap_flush(old_inode->i_mapping);
8632 
8633 	if (flags & RENAME_WHITEOUT) {
8634 		whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
8635 		if (!whiteout_args.inode) {
8636 			ret = -ENOMEM;
8637 			goto out_fscrypt_names;
8638 		}
8639 		ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
8640 		if (ret)
8641 			goto out_whiteout_inode;
8642 	} else {
8643 		/* 1 to update the old parent inode. */
8644 		trans_num_items = 1;
8645 	}
8646 
8647 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8648 		/* Close the race window with snapshot create/destroy ioctl */
8649 		down_read(&fs_info->subvol_sem);
8650 		/*
8651 		 * 1 to remove old root ref
8652 		 * 1 to remove old root backref
8653 		 * 1 to add new root ref
8654 		 * 1 to add new root backref
8655 		 */
8656 		trans_num_items += 4;
8657 	} else {
8658 		/*
8659 		 * 1 to update inode
8660 		 * 1 to remove old inode ref
8661 		 * 1 to add new inode ref
8662 		 */
8663 		trans_num_items += 3;
8664 	}
8665 	/*
8666 	 * 1 to remove old dir item
8667 	 * 1 to remove old dir index
8668 	 * 1 to add new dir item
8669 	 * 1 to add new dir index
8670 	 */
8671 	trans_num_items += 4;
8672 	/* 1 to update new parent inode if it's not the same as the old parent */
8673 	if (new_dir != old_dir)
8674 		trans_num_items++;
8675 	if (new_inode) {
8676 		/*
8677 		 * 1 to update inode
8678 		 * 1 to remove inode ref
8679 		 * 1 to remove dir item
8680 		 * 1 to remove dir index
8681 		 * 1 to possibly add orphan item
8682 		 */
8683 		trans_num_items += 5;
8684 	}
8685 	trans = btrfs_start_transaction(root, trans_num_items);
8686 	if (IS_ERR(trans)) {
8687 		ret = PTR_ERR(trans);
8688 		goto out_notrans;
8689 	}
8690 
8691 	if (dest != root) {
8692 		ret = btrfs_record_root_in_trans(trans, dest);
8693 		if (ret)
8694 			goto out_fail;
8695 	}
8696 
8697 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
8698 	if (ret)
8699 		goto out_fail;
8700 
8701 	BTRFS_I(old_inode)->dir_index = 0ULL;
8702 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8703 		/* force full log commit if subvolume involved. */
8704 		btrfs_set_log_full_commit(trans);
8705 	} else {
8706 		ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
8707 					     old_ino, btrfs_ino(BTRFS_I(new_dir)),
8708 					     index);
8709 		if (ret)
8710 			goto out_fail;
8711 	}
8712 
8713 	inode_inc_iversion(old_dir);
8714 	inode_inc_iversion(new_dir);
8715 	inode_inc_iversion(old_inode);
8716 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8717 
8718 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8719 		/*
8720 		 * If we are renaming in the same directory (and it's not a
8721 		 * root entry) pin the log to prevent any concurrent task from
8722 		 * logging the directory after we removed the old entry and
8723 		 * before we add the new entry, otherwise that task can sync
8724 		 * a log without any entry for the inode we are renaming and
8725 		 * therefore replaying that log, if a power failure happens
8726 		 * after syncing the log, would result in deleting the inode.
8727 		 *
8728 		 * If the rename affects two different directories, we want to
8729 		 * make sure the that there's no log commit that contains
8730 		 * updates for only one of the directories but not for the
8731 		 * other.
8732 		 *
8733 		 * If we are renaming an entry for a root, we don't care about
8734 		 * log updates since we called btrfs_set_log_full_commit().
8735 		 */
8736 		btrfs_pin_log_trans(root);
8737 		btrfs_pin_log_trans(dest);
8738 		logs_pinned = true;
8739 	}
8740 
8741 	if (old_dentry->d_parent != new_dentry->d_parent)
8742 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8743 					BTRFS_I(old_inode), true);
8744 
8745 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8746 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8747 		if (unlikely(ret)) {
8748 			btrfs_abort_transaction(trans, ret);
8749 			goto out_fail;
8750 		}
8751 	} else {
8752 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8753 					   BTRFS_I(d_inode(old_dentry)),
8754 					   &old_fname.disk_name, &rename_ctx);
8755 		if (unlikely(ret)) {
8756 			btrfs_abort_transaction(trans, ret);
8757 			goto out_fail;
8758 		}
8759 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8760 		if (unlikely(ret)) {
8761 			btrfs_abort_transaction(trans, ret);
8762 			goto out_fail;
8763 		}
8764 	}
8765 
8766 	if (new_inode) {
8767 		inode_inc_iversion(new_inode);
8768 		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
8769 			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8770 			ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8771 			if (unlikely(ret)) {
8772 				btrfs_abort_transaction(trans, ret);
8773 				goto out_fail;
8774 			}
8775 			BUG_ON(new_inode->i_nlink == 0);
8776 		} else {
8777 			ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8778 						 BTRFS_I(d_inode(new_dentry)),
8779 						 &new_fname.disk_name);
8780 			if (unlikely(ret)) {
8781 				btrfs_abort_transaction(trans, ret);
8782 				goto out_fail;
8783 			}
8784 		}
8785 		if (new_inode->i_nlink == 0) {
8786 			ret = btrfs_orphan_add(trans,
8787 					BTRFS_I(d_inode(new_dentry)));
8788 			if (unlikely(ret)) {
8789 				btrfs_abort_transaction(trans, ret);
8790 				goto out_fail;
8791 			}
8792 		}
8793 	}
8794 
8795 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8796 			     &new_fname.disk_name, false, index);
8797 	if (unlikely(ret)) {
8798 		btrfs_abort_transaction(trans, ret);
8799 		goto out_fail;
8800 	}
8801 
8802 	if (old_inode->i_nlink == 1)
8803 		BTRFS_I(old_inode)->dir_index = index;
8804 
8805 	if (logs_pinned)
8806 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8807 				   rename_ctx.index, new_dentry->d_parent);
8808 
8809 	if (flags & RENAME_WHITEOUT) {
8810 		ret = btrfs_create_new_inode(trans, &whiteout_args);
8811 		if (unlikely(ret)) {
8812 			btrfs_abort_transaction(trans, ret);
8813 			goto out_fail;
8814 		} else {
8815 			unlock_new_inode(whiteout_args.inode);
8816 			iput(whiteout_args.inode);
8817 			whiteout_args.inode = NULL;
8818 		}
8819 	}
8820 out_fail:
8821 	if (logs_pinned) {
8822 		btrfs_end_log_trans(root);
8823 		btrfs_end_log_trans(dest);
8824 	}
8825 	ret2 = btrfs_end_transaction(trans);
8826 	ret = ret ? ret : ret2;
8827 out_notrans:
8828 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8829 		up_read(&fs_info->subvol_sem);
8830 	if (flags & RENAME_WHITEOUT)
8831 		btrfs_new_inode_args_destroy(&whiteout_args);
8832 out_whiteout_inode:
8833 	if (flags & RENAME_WHITEOUT)
8834 		iput(whiteout_args.inode);
8835 out_fscrypt_names:
8836 	fscrypt_free_filename(&old_fname);
8837 	fscrypt_free_filename(&new_fname);
8838 	return ret;
8839 }
8840 
btrfs_rename2(struct mnt_idmap * idmap,struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry,unsigned int flags)8841 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
8842 			 struct dentry *old_dentry, struct inode *new_dir,
8843 			 struct dentry *new_dentry, unsigned int flags)
8844 {
8845 	int ret;
8846 
8847 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
8848 		return -EINVAL;
8849 
8850 	if (flags & RENAME_EXCHANGE)
8851 		ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
8852 					    new_dentry);
8853 	else
8854 		ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
8855 				   new_dentry, flags);
8856 
8857 	btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
8858 
8859 	return ret;
8860 }
8861 
8862 struct btrfs_delalloc_work {
8863 	struct inode *inode;
8864 	struct completion completion;
8865 	struct list_head list;
8866 	struct btrfs_work work;
8867 };
8868 
btrfs_run_delalloc_work(struct btrfs_work * work)8869 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8870 {
8871 	struct btrfs_delalloc_work *delalloc_work;
8872 	struct inode *inode;
8873 
8874 	delalloc_work = container_of(work, struct btrfs_delalloc_work,
8875 				     work);
8876 	inode = delalloc_work->inode;
8877 	filemap_flush(inode->i_mapping);
8878 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8879 				&BTRFS_I(inode)->runtime_flags))
8880 		filemap_flush(inode->i_mapping);
8881 
8882 	iput(inode);
8883 	complete(&delalloc_work->completion);
8884 }
8885 
btrfs_alloc_delalloc_work(struct inode * inode)8886 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8887 {
8888 	struct btrfs_delalloc_work *work;
8889 
8890 	work = kmalloc_obj(*work, GFP_NOFS);
8891 	if (!work)
8892 		return NULL;
8893 
8894 	init_completion(&work->completion);
8895 	INIT_LIST_HEAD(&work->list);
8896 	work->inode = inode;
8897 	btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
8898 
8899 	return work;
8900 }
8901 
8902 /*
8903  * some fairly slow code that needs optimization. This walks the list
8904  * of all the inodes with pending delalloc and forces them to disk.
8905  */
start_delalloc_inodes(struct btrfs_root * root,long * nr_to_write,bool snapshot,bool in_reclaim_context)8906 static int start_delalloc_inodes(struct btrfs_root *root, long *nr_to_write,
8907 				 bool snapshot, bool in_reclaim_context)
8908 {
8909 	struct btrfs_delalloc_work *work, *next;
8910 	LIST_HEAD(works);
8911 	LIST_HEAD(splice);
8912 	int ret = 0;
8913 
8914 	mutex_lock(&root->delalloc_mutex);
8915 	spin_lock(&root->delalloc_lock);
8916 	list_splice_init(&root->delalloc_inodes, &splice);
8917 	while (!list_empty(&splice)) {
8918 		struct btrfs_inode *inode;
8919 		struct inode *tmp_inode;
8920 
8921 		inode = list_first_entry(&splice, struct btrfs_inode, delalloc_inodes);
8922 
8923 		list_move_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
8924 
8925 		if (in_reclaim_context &&
8926 		    test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags))
8927 			continue;
8928 
8929 		tmp_inode = igrab(&inode->vfs_inode);
8930 		if (!tmp_inode) {
8931 			cond_resched_lock(&root->delalloc_lock);
8932 			continue;
8933 		}
8934 		spin_unlock(&root->delalloc_lock);
8935 
8936 		if (snapshot)
8937 			set_bit(BTRFS_INODE_SNAPSHOT_FLUSH, &inode->runtime_flags);
8938 		if (nr_to_write == NULL) {
8939 			work = btrfs_alloc_delalloc_work(tmp_inode);
8940 			if (!work) {
8941 				iput(tmp_inode);
8942 				ret = -ENOMEM;
8943 				goto out;
8944 			}
8945 			list_add_tail(&work->list, &works);
8946 			btrfs_queue_work(root->fs_info->flush_workers,
8947 					 &work->work);
8948 		} else {
8949 			ret = filemap_flush_nr(tmp_inode->i_mapping,
8950 					nr_to_write);
8951 			btrfs_add_delayed_iput(inode);
8952 
8953 			if (ret || *nr_to_write <= 0)
8954 				goto out;
8955 		}
8956 		cond_resched();
8957 		spin_lock(&root->delalloc_lock);
8958 	}
8959 	spin_unlock(&root->delalloc_lock);
8960 
8961 out:
8962 	list_for_each_entry_safe(work, next, &works, list) {
8963 		list_del_init(&work->list);
8964 		wait_for_completion(&work->completion);
8965 		kfree(work);
8966 	}
8967 
8968 	if (!list_empty(&splice)) {
8969 		spin_lock(&root->delalloc_lock);
8970 		list_splice_tail(&splice, &root->delalloc_inodes);
8971 		spin_unlock(&root->delalloc_lock);
8972 	}
8973 	mutex_unlock(&root->delalloc_mutex);
8974 	return ret;
8975 }
8976 
btrfs_start_delalloc_snapshot(struct btrfs_root * root,bool in_reclaim_context)8977 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
8978 {
8979 	struct btrfs_fs_info *fs_info = root->fs_info;
8980 
8981 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8982 		return -EROFS;
8983 	return start_delalloc_inodes(root, NULL, true, in_reclaim_context);
8984 }
8985 
btrfs_start_delalloc_roots(struct btrfs_fs_info * fs_info,long nr,bool in_reclaim_context)8986 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
8987 			       bool in_reclaim_context)
8988 {
8989 	long *nr_to_write = nr == LONG_MAX ? NULL : &nr;
8990 	struct btrfs_root *root;
8991 	LIST_HEAD(splice);
8992 	int ret;
8993 
8994 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8995 		return -EROFS;
8996 
8997 	mutex_lock(&fs_info->delalloc_root_mutex);
8998 	spin_lock(&fs_info->delalloc_root_lock);
8999 	list_splice_init(&fs_info->delalloc_roots, &splice);
9000 	while (!list_empty(&splice)) {
9001 		root = list_first_entry(&splice, struct btrfs_root,
9002 					delalloc_root);
9003 		root = btrfs_grab_root(root);
9004 		BUG_ON(!root);
9005 		list_move_tail(&root->delalloc_root,
9006 			       &fs_info->delalloc_roots);
9007 		spin_unlock(&fs_info->delalloc_root_lock);
9008 
9009 		ret = start_delalloc_inodes(root, nr_to_write, false,
9010 				in_reclaim_context);
9011 		btrfs_put_root(root);
9012 		if (ret < 0 || nr <= 0)
9013 			goto out;
9014 		spin_lock(&fs_info->delalloc_root_lock);
9015 	}
9016 	spin_unlock(&fs_info->delalloc_root_lock);
9017 
9018 	ret = 0;
9019 out:
9020 	if (!list_empty(&splice)) {
9021 		spin_lock(&fs_info->delalloc_root_lock);
9022 		list_splice_tail(&splice, &fs_info->delalloc_roots);
9023 		spin_unlock(&fs_info->delalloc_root_lock);
9024 	}
9025 	mutex_unlock(&fs_info->delalloc_root_mutex);
9026 	return ret;
9027 }
9028 
btrfs_symlink(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,const char * symname)9029 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9030 			 struct dentry *dentry, const char *symname)
9031 {
9032 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9033 	struct btrfs_trans_handle *trans;
9034 	struct btrfs_root *root = BTRFS_I(dir)->root;
9035 	struct btrfs_path *path;
9036 	struct btrfs_key key;
9037 	struct inode *inode;
9038 	struct btrfs_new_inode_args new_inode_args = {
9039 		.dir = dir,
9040 		.dentry = dentry,
9041 	};
9042 	unsigned int trans_num_items;
9043 	int ret;
9044 	int name_len;
9045 	int datasize;
9046 	unsigned long ptr;
9047 	struct btrfs_file_extent_item *ei;
9048 	struct extent_buffer *leaf;
9049 
9050 	name_len = strlen(symname);
9051 	/*
9052 	 * Symlinks utilize uncompressed inline extent data, which should not
9053 	 * reach block size.
9054 	 */
9055 	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
9056 	    name_len >= fs_info->sectorsize)
9057 		return -ENAMETOOLONG;
9058 
9059 	inode = new_inode(dir->i_sb);
9060 	if (!inode)
9061 		return -ENOMEM;
9062 	inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9063 	inode->i_op = &btrfs_symlink_inode_operations;
9064 	inode_nohighmem(inode);
9065 	inode->i_mapping->a_ops = &btrfs_aops;
9066 	btrfs_i_size_write(BTRFS_I(inode), name_len);
9067 	inode_set_bytes(inode, name_len);
9068 
9069 	new_inode_args.inode = inode;
9070 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9071 	if (ret)
9072 		goto out_inode;
9073 	/* 1 additional item for the inline extent */
9074 	trans_num_items++;
9075 
9076 	trans = btrfs_start_transaction(root, trans_num_items);
9077 	if (IS_ERR(trans)) {
9078 		ret = PTR_ERR(trans);
9079 		goto out_new_inode_args;
9080 	}
9081 
9082 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9083 	if (ret)
9084 		goto out;
9085 
9086 	path = btrfs_alloc_path();
9087 	if (unlikely(!path)) {
9088 		ret = -ENOMEM;
9089 		btrfs_abort_transaction(trans, ret);
9090 		discard_new_inode(inode);
9091 		inode = NULL;
9092 		goto out;
9093 	}
9094 	key.objectid = btrfs_ino(BTRFS_I(inode));
9095 	key.type = BTRFS_EXTENT_DATA_KEY;
9096 	key.offset = 0;
9097 	datasize = btrfs_file_extent_calc_inline_size(name_len);
9098 	ret = btrfs_insert_empty_item(trans, root, path, &key, datasize);
9099 	if (unlikely(ret)) {
9100 		btrfs_abort_transaction(trans, ret);
9101 		btrfs_free_path(path);
9102 		discard_new_inode(inode);
9103 		inode = NULL;
9104 		goto out;
9105 	}
9106 	leaf = path->nodes[0];
9107 	ei = btrfs_item_ptr(leaf, path->slots[0],
9108 			    struct btrfs_file_extent_item);
9109 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9110 	btrfs_set_file_extent_type(leaf, ei,
9111 				   BTRFS_FILE_EXTENT_INLINE);
9112 	btrfs_set_file_extent_encryption(leaf, ei, 0);
9113 	btrfs_set_file_extent_compression(leaf, ei, 0);
9114 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9115 	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9116 
9117 	ptr = btrfs_file_extent_inline_start(ei);
9118 	write_extent_buffer(leaf, symname, ptr, name_len);
9119 	btrfs_free_path(path);
9120 
9121 	d_instantiate_new(dentry, inode);
9122 	ret = 0;
9123 out:
9124 	btrfs_end_transaction(trans);
9125 	btrfs_btree_balance_dirty(fs_info);
9126 out_new_inode_args:
9127 	btrfs_new_inode_args_destroy(&new_inode_args);
9128 out_inode:
9129 	if (ret)
9130 		iput(inode);
9131 	return ret;
9132 }
9133 
insert_prealloc_file_extent(struct btrfs_trans_handle * trans_in,struct btrfs_inode * inode,struct btrfs_key * ins,u64 file_offset)9134 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9135 				       struct btrfs_trans_handle *trans_in,
9136 				       struct btrfs_inode *inode,
9137 				       struct btrfs_key *ins,
9138 				       u64 file_offset)
9139 {
9140 	struct btrfs_file_extent_item stack_fi;
9141 	struct btrfs_replace_extent_info extent_info;
9142 	struct btrfs_trans_handle *trans = trans_in;
9143 	struct btrfs_path *path;
9144 	u64 start = ins->objectid;
9145 	u64 len = ins->offset;
9146 	u64 qgroup_released = 0;
9147 	int ret;
9148 
9149 	memset(&stack_fi, 0, sizeof(stack_fi));
9150 
9151 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9152 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9153 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9154 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9155 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9156 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9157 	/* Encryption and other encoding is reserved and all 0 */
9158 
9159 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
9160 	if (ret < 0)
9161 		return ERR_PTR(ret);
9162 
9163 	if (trans) {
9164 		ret = insert_reserved_file_extent(trans, inode,
9165 						  file_offset, &stack_fi,
9166 						  true, qgroup_released);
9167 		if (ret)
9168 			goto free_qgroup;
9169 		return trans;
9170 	}
9171 
9172 	extent_info.disk_offset = start;
9173 	extent_info.disk_len = len;
9174 	extent_info.data_offset = 0;
9175 	extent_info.data_len = len;
9176 	extent_info.file_offset = file_offset;
9177 	extent_info.extent_buf = (char *)&stack_fi;
9178 	extent_info.is_new_extent = true;
9179 	extent_info.update_times = true;
9180 	extent_info.qgroup_reserved = qgroup_released;
9181 	extent_info.insertions = 0;
9182 
9183 	path = btrfs_alloc_path();
9184 	if (!path) {
9185 		ret = -ENOMEM;
9186 		goto free_qgroup;
9187 	}
9188 
9189 	ret = btrfs_replace_file_extents(inode, path, file_offset,
9190 				     file_offset + len - 1, &extent_info,
9191 				     &trans);
9192 	btrfs_free_path(path);
9193 	if (ret)
9194 		goto free_qgroup;
9195 	return trans;
9196 
9197 free_qgroup:
9198 	/*
9199 	 * We have released qgroup data range at the beginning of the function,
9200 	 * and normally qgroup_released bytes will be freed when committing
9201 	 * transaction.
9202 	 * But if we error out early, we have to free what we have released
9203 	 * or we leak qgroup data reservation.
9204 	 */
9205 	btrfs_qgroup_free_refroot(inode->root->fs_info,
9206 			btrfs_root_id(inode->root), qgroup_released,
9207 			BTRFS_QGROUP_RSV_DATA);
9208 	return ERR_PTR(ret);
9209 }
9210 
__btrfs_prealloc_file_range(struct inode * inode,int mode,u64 start,u64 num_bytes,u64 min_size,loff_t actual_len,u64 * alloc_hint,struct btrfs_trans_handle * trans)9211 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9212 				       u64 start, u64 num_bytes, u64 min_size,
9213 				       loff_t actual_len, u64 *alloc_hint,
9214 				       struct btrfs_trans_handle *trans)
9215 {
9216 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
9217 	struct extent_map *em;
9218 	struct btrfs_root *root = BTRFS_I(inode)->root;
9219 	struct btrfs_key ins;
9220 	u64 cur_offset = start;
9221 	u64 clear_offset = start;
9222 	u64 i_size;
9223 	u64 cur_bytes;
9224 	u64 last_alloc = (u64)-1;
9225 	int ret = 0;
9226 	bool own_trans = true;
9227 	u64 end = start + num_bytes - 1;
9228 
9229 	if (trans)
9230 		own_trans = false;
9231 	while (num_bytes > 0) {
9232 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
9233 		cur_bytes = max(cur_bytes, min_size);
9234 		/*
9235 		 * If we are severely fragmented we could end up with really
9236 		 * small allocations, so if the allocator is returning small
9237 		 * chunks lets make its job easier by only searching for those
9238 		 * sized chunks.
9239 		 */
9240 		cur_bytes = min(cur_bytes, last_alloc);
9241 		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9242 				min_size, 0, *alloc_hint, &ins, true, false);
9243 		if (ret)
9244 			break;
9245 
9246 		/*
9247 		 * We've reserved this space, and thus converted it from
9248 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9249 		 * from here on out we will only need to clear our reservation
9250 		 * for the remaining unreserved area, so advance our
9251 		 * clear_offset by our extent size.
9252 		 */
9253 		clear_offset += ins.offset;
9254 
9255 		last_alloc = ins.offset;
9256 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9257 						    &ins, cur_offset);
9258 		/*
9259 		 * Now that we inserted the prealloc extent we can finally
9260 		 * decrement the number of reservations in the block group.
9261 		 * If we did it before, we could race with relocation and have
9262 		 * relocation miss the reserved extent, making it fail later.
9263 		 */
9264 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9265 		if (IS_ERR(trans)) {
9266 			ret = PTR_ERR(trans);
9267 			btrfs_free_reserved_extent(fs_info, ins.objectid,
9268 						   ins.offset, false);
9269 			break;
9270 		}
9271 
9272 		em = btrfs_alloc_extent_map();
9273 		if (!em) {
9274 			btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9275 					    cur_offset + ins.offset - 1, false);
9276 			btrfs_set_inode_full_sync(BTRFS_I(inode));
9277 			goto next;
9278 		}
9279 
9280 		em->start = cur_offset;
9281 		em->len = ins.offset;
9282 		em->disk_bytenr = ins.objectid;
9283 		em->offset = 0;
9284 		em->disk_num_bytes = ins.offset;
9285 		em->ram_bytes = ins.offset;
9286 		em->flags |= EXTENT_FLAG_PREALLOC;
9287 		em->generation = trans->transid;
9288 
9289 		ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9290 		btrfs_free_extent_map(em);
9291 next:
9292 		num_bytes -= ins.offset;
9293 		cur_offset += ins.offset;
9294 		*alloc_hint = ins.objectid + ins.offset;
9295 
9296 		inode_inc_iversion(inode);
9297 		inode_set_ctime_current(inode);
9298 		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9299 		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9300 		    (actual_len > inode->i_size) &&
9301 		    (cur_offset > inode->i_size)) {
9302 			u64 range_start;
9303 			u64 range_end;
9304 
9305 			if (cur_offset > actual_len)
9306 				i_size = actual_len;
9307 			else
9308 				i_size = cur_offset;
9309 
9310 			/*
9311 			 * Make sure the file_extent_tree covers the entire
9312 			 * range [old_i_size, new_i_size) before we update
9313 			 * disk_i_size. Without this, a previous KEEP_SIZE
9314 			 * prealloc that extended past i_size (and was lost
9315 			 * across umount/mount because file_extent_tree is
9316 			 * only populated up to round_up(i_size) on inode
9317 			 * load) can leave a gap inside this range. That gap
9318 			 * would cause btrfs_inode_safe_disk_i_size_write()
9319 			 * (via find_contiguous_extent_bit() starting at 0)
9320 			 * to truncate disk_i_size to the start of the gap,
9321 			 * making the persisted size smaller than i_size.
9322 			 */
9323 			range_start = round_down(inode->i_size, fs_info->sectorsize);
9324 			range_end = round_up(i_size, fs_info->sectorsize);
9325 			ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
9326 					range_start, range_end - range_start);
9327 			if (ret) {
9328 				btrfs_abort_transaction(trans, ret);
9329 				if (own_trans)
9330 					btrfs_end_transaction(trans);
9331 				break;
9332 			}
9333 
9334 			i_size_write(inode, i_size);
9335 			btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9336 		}
9337 
9338 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
9339 
9340 		if (unlikely(ret)) {
9341 			btrfs_abort_transaction(trans, ret);
9342 			if (own_trans)
9343 				btrfs_end_transaction(trans);
9344 			break;
9345 		}
9346 
9347 		if (own_trans) {
9348 			btrfs_end_transaction(trans);
9349 			trans = NULL;
9350 		}
9351 	}
9352 	if (clear_offset < end)
9353 		btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9354 			end - clear_offset + 1);
9355 	return ret;
9356 }
9357 
btrfs_prealloc_file_range(struct inode * inode,int mode,u64 start,u64 num_bytes,u64 min_size,loff_t actual_len,u64 * alloc_hint)9358 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9359 			      u64 start, u64 num_bytes, u64 min_size,
9360 			      loff_t actual_len, u64 *alloc_hint)
9361 {
9362 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9363 					   min_size, actual_len, alloc_hint,
9364 					   NULL);
9365 }
9366 
btrfs_prealloc_file_range_trans(struct inode * inode,struct btrfs_trans_handle * trans,int mode,u64 start,u64 num_bytes,u64 min_size,loff_t actual_len,u64 * alloc_hint)9367 int btrfs_prealloc_file_range_trans(struct inode *inode,
9368 				    struct btrfs_trans_handle *trans, int mode,
9369 				    u64 start, u64 num_bytes, u64 min_size,
9370 				    loff_t actual_len, u64 *alloc_hint)
9371 {
9372 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9373 					   min_size, actual_len, alloc_hint, trans);
9374 }
9375 
9376 /*
9377  * NOTE: in case you are adding MAY_EXEC check for directories:
9378  * we are marking them with IOP_FASTPERM_MAY_EXEC, allowing path lookup to
9379  * elide calls here.
9380  */
btrfs_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)9381 static int btrfs_permission(struct mnt_idmap *idmap,
9382 			    struct inode *inode, int mask)
9383 {
9384 	struct btrfs_root *root = BTRFS_I(inode)->root;
9385 	umode_t mode = inode->i_mode;
9386 
9387 	if (mask & MAY_WRITE &&
9388 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9389 		if (btrfs_root_readonly(root))
9390 			return -EROFS;
9391 		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9392 			return -EACCES;
9393 	}
9394 	return generic_permission(idmap, inode, mask);
9395 }
9396 
btrfs_tmpfile(struct mnt_idmap * idmap,struct inode * dir,struct file * file,umode_t mode)9397 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9398 			 struct file *file, umode_t mode)
9399 {
9400 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9401 	struct btrfs_trans_handle *trans;
9402 	struct btrfs_root *root = BTRFS_I(dir)->root;
9403 	struct inode *inode;
9404 	struct btrfs_new_inode_args new_inode_args = {
9405 		.dir = dir,
9406 		.dentry = file->f_path.dentry,
9407 		.orphan = true,
9408 	};
9409 	unsigned int trans_num_items;
9410 	int ret;
9411 
9412 	inode = new_inode(dir->i_sb);
9413 	if (!inode)
9414 		return -ENOMEM;
9415 	inode_init_owner(idmap, inode, dir, mode);
9416 	inode->i_fop = &btrfs_file_operations;
9417 	inode->i_op = &btrfs_file_inode_operations;
9418 	inode->i_mapping->a_ops = &btrfs_aops;
9419 
9420 	new_inode_args.inode = inode;
9421 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9422 	if (ret)
9423 		goto out_inode;
9424 
9425 	trans = btrfs_start_transaction(root, trans_num_items);
9426 	if (IS_ERR(trans)) {
9427 		ret = PTR_ERR(trans);
9428 		goto out_new_inode_args;
9429 	}
9430 
9431 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9432 
9433 	/*
9434 	 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9435 	 * set it to 1 because d_tmpfile() will issue a warning if the count is
9436 	 * 0, through:
9437 	 *
9438 	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9439 	 */
9440 	set_nlink(inode, 1);
9441 
9442 	if (!ret) {
9443 		d_tmpfile(file, inode);
9444 		unlock_new_inode(inode);
9445 		mark_inode_dirty(inode);
9446 	}
9447 
9448 	btrfs_end_transaction(trans);
9449 	btrfs_btree_balance_dirty(fs_info);
9450 out_new_inode_args:
9451 	btrfs_new_inode_args_destroy(&new_inode_args);
9452 out_inode:
9453 	if (ret)
9454 		iput(inode);
9455 	return finish_open_simple(file, ret);
9456 }
9457 
btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info * fs_info,int compress_type)9458 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9459 					     int compress_type)
9460 {
9461 	switch (compress_type) {
9462 	case BTRFS_COMPRESS_NONE:
9463 		return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9464 	case BTRFS_COMPRESS_ZLIB:
9465 		return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9466 	case BTRFS_COMPRESS_LZO:
9467 		/*
9468 		 * The LZO format depends on the sector size. 64K is the maximum
9469 		 * sector size that we support.
9470 		 */
9471 		if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9472 			return -EINVAL;
9473 		return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9474 		       (fs_info->sectorsize_bits - 12);
9475 	case BTRFS_COMPRESS_ZSTD:
9476 		return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9477 	default:
9478 		return -EUCLEAN;
9479 	}
9480 }
9481 
btrfs_encoded_read_inline(struct kiocb * iocb,struct iov_iter * iter,u64 start,u64 lockend,struct extent_state ** cached_state,u64 extent_start,size_t count,struct btrfs_ioctl_encoded_io_args * encoded,bool * unlocked)9482 static ssize_t btrfs_encoded_read_inline(
9483 				struct kiocb *iocb,
9484 				struct iov_iter *iter, u64 start,
9485 				u64 lockend,
9486 				struct extent_state **cached_state,
9487 				u64 extent_start, size_t count,
9488 				struct btrfs_ioctl_encoded_io_args *encoded,
9489 				bool *unlocked)
9490 {
9491 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9492 	struct btrfs_root *root = inode->root;
9493 	struct btrfs_fs_info *fs_info = root->fs_info;
9494 	struct extent_io_tree *io_tree = &inode->io_tree;
9495 	BTRFS_PATH_AUTO_FREE(path);
9496 	struct extent_buffer *leaf;
9497 	struct btrfs_file_extent_item *item;
9498 	u64 ram_bytes;
9499 	unsigned long ptr;
9500 	void *tmp;
9501 	ssize_t ret;
9502 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9503 
9504 	path = btrfs_alloc_path();
9505 	if (!path)
9506 		return -ENOMEM;
9507 
9508 	path->nowait = nowait;
9509 
9510 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9511 				       extent_start, 0);
9512 	if (ret) {
9513 		if (unlikely(ret > 0)) {
9514 			/* The extent item disappeared? */
9515 			return -EIO;
9516 		}
9517 		return ret;
9518 	}
9519 	leaf = path->nodes[0];
9520 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9521 
9522 	ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9523 	ptr = btrfs_file_extent_inline_start(item);
9524 
9525 	encoded->len = min_t(u64, extent_start + ram_bytes,
9526 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9527 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
9528 				 btrfs_file_extent_compression(leaf, item));
9529 	if (ret < 0)
9530 		return ret;
9531 	encoded->compression = ret;
9532 	if (encoded->compression) {
9533 		size_t inline_size;
9534 
9535 		inline_size = btrfs_file_extent_inline_item_len(leaf,
9536 								path->slots[0]);
9537 		if (inline_size > count)
9538 			return -ENOBUFS;
9539 
9540 		count = inline_size;
9541 		encoded->unencoded_len = ram_bytes;
9542 		encoded->unencoded_offset = iocb->ki_pos - extent_start;
9543 	} else {
9544 		count = min_t(u64, count, encoded->len);
9545 		encoded->len = count;
9546 		encoded->unencoded_len = count;
9547 		ptr += iocb->ki_pos - extent_start;
9548 	}
9549 
9550 	tmp = kmalloc(count, GFP_NOFS);
9551 	if (!tmp)
9552 		return -ENOMEM;
9553 
9554 	read_extent_buffer(leaf, tmp, ptr, count);
9555 	btrfs_release_path(path);
9556 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9557 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9558 	*unlocked = true;
9559 
9560 	ret = copy_to_iter(tmp, count, iter);
9561 	if (ret != count)
9562 		ret = -EFAULT;
9563 	kfree(tmp);
9564 
9565 	return ret;
9566 }
9567 
9568 struct btrfs_encoded_read_private {
9569 	struct completion *sync_reads;
9570 	void *uring_ctx;
9571 	refcount_t pending_refs;
9572 	blk_status_t status;
9573 };
9574 
btrfs_encoded_read_endio(struct btrfs_bio * bbio)9575 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9576 {
9577 	struct btrfs_encoded_read_private *priv = bbio->private;
9578 
9579 	if (bbio->bio.bi_status) {
9580 		/*
9581 		 * The memory barrier implied by the refcount_dec_and_test() here
9582 		 * pairs with the memory barrier implied by the refcount_dec_and_test()
9583 		 * in btrfs_encoded_read_regular_fill_pages() to ensure that
9584 		 * this write is observed before the load of status in
9585 		 * btrfs_encoded_read_regular_fill_pages().
9586 		 */
9587 		WRITE_ONCE(priv->status, bbio->bio.bi_status);
9588 	}
9589 	if (refcount_dec_and_test(&priv->pending_refs)) {
9590 		int err = blk_status_to_errno(READ_ONCE(priv->status));
9591 
9592 		if (priv->uring_ctx) {
9593 			btrfs_uring_read_extent_endio(priv->uring_ctx, err);
9594 			kfree(priv);
9595 		} else {
9596 			complete(priv->sync_reads);
9597 		}
9598 	}
9599 	bio_put(&bbio->bio);
9600 }
9601 
btrfs_encoded_read_regular_fill_pages(struct btrfs_inode * inode,u64 disk_bytenr,u64 disk_io_size,struct page ** pages,void * uring_ctx)9602 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9603 					  u64 disk_bytenr, u64 disk_io_size,
9604 					  struct page **pages, void *uring_ctx)
9605 {
9606 	struct btrfs_encoded_read_private *priv, sync_priv;
9607 	struct completion sync_reads;
9608 	unsigned long i = 0;
9609 	struct btrfs_bio *bbio;
9610 	int ret;
9611 
9612 	/*
9613 	 * Fast path for synchronous reads which completes in this call, io_uring
9614 	 * needs longer time span.
9615 	 */
9616 	if (uring_ctx) {
9617 		priv = kmalloc_obj(struct btrfs_encoded_read_private, GFP_NOFS);
9618 		if (!priv)
9619 			return -ENOMEM;
9620 	} else {
9621 		priv = &sync_priv;
9622 		init_completion(&sync_reads);
9623 		priv->sync_reads = &sync_reads;
9624 	}
9625 
9626 	refcount_set(&priv->pending_refs, 1);
9627 	priv->status = 0;
9628 	priv->uring_ctx = uring_ctx;
9629 
9630 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9631 			       btrfs_encoded_read_endio, priv);
9632 	bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9633 
9634 	do {
9635 		size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
9636 
9637 		if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
9638 			refcount_inc(&priv->pending_refs);
9639 			btrfs_submit_bbio(bbio, 0);
9640 
9641 			bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9642 					       btrfs_encoded_read_endio, priv);
9643 			bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9644 			continue;
9645 		}
9646 
9647 		i++;
9648 		disk_bytenr += bytes;
9649 		disk_io_size -= bytes;
9650 	} while (disk_io_size);
9651 
9652 	refcount_inc(&priv->pending_refs);
9653 	btrfs_submit_bbio(bbio, 0);
9654 
9655 	if (uring_ctx) {
9656 		if (refcount_dec_and_test(&priv->pending_refs)) {
9657 			ret = blk_status_to_errno(READ_ONCE(priv->status));
9658 			btrfs_uring_read_extent_endio(uring_ctx, ret);
9659 			kfree(priv);
9660 			return ret;
9661 		}
9662 
9663 		return -EIOCBQUEUED;
9664 	} else {
9665 		if (!refcount_dec_and_test(&priv->pending_refs))
9666 			wait_for_completion_io(&sync_reads);
9667 		/* See btrfs_encoded_read_endio() for ordering. */
9668 		return blk_status_to_errno(READ_ONCE(priv->status));
9669 	}
9670 }
9671 
btrfs_encoded_read_regular(struct kiocb * iocb,struct iov_iter * iter,u64 start,u64 lockend,struct extent_state ** cached_state,u64 disk_bytenr,u64 disk_io_size,size_t count,bool compressed,bool * unlocked)9672 ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter,
9673 				   u64 start, u64 lockend,
9674 				   struct extent_state **cached_state,
9675 				   u64 disk_bytenr, u64 disk_io_size,
9676 				   size_t count, bool compressed, bool *unlocked)
9677 {
9678 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9679 	struct extent_io_tree *io_tree = &inode->io_tree;
9680 	struct page **pages;
9681 	unsigned long nr_pages, i;
9682 	u64 cur;
9683 	size_t page_offset;
9684 	ssize_t ret;
9685 
9686 	nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
9687 	pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
9688 	if (!pages)
9689 		return -ENOMEM;
9690 	ret = btrfs_alloc_page_array(nr_pages, pages, GFP_NOFS);
9691 	if (ret) {
9692 		ret = -ENOMEM;
9693 		goto out;
9694 		}
9695 
9696 	ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
9697 						    disk_io_size, pages, NULL);
9698 	if (ret)
9699 		goto out;
9700 
9701 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9702 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9703 	*unlocked = true;
9704 
9705 	if (compressed) {
9706 		i = 0;
9707 		page_offset = 0;
9708 	} else {
9709 		i = (iocb->ki_pos - start) >> PAGE_SHIFT;
9710 		page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
9711 	}
9712 	cur = 0;
9713 	while (cur < count) {
9714 		size_t bytes = min_t(size_t, count - cur,
9715 				     PAGE_SIZE - page_offset);
9716 
9717 		if (copy_page_to_iter(pages[i], page_offset, bytes,
9718 				      iter) != bytes) {
9719 			ret = -EFAULT;
9720 			goto out;
9721 		}
9722 		i++;
9723 		cur += bytes;
9724 		page_offset = 0;
9725 	}
9726 	ret = count;
9727 out:
9728 	for (i = 0; i < nr_pages; i++) {
9729 		if (pages[i])
9730 			__free_page(pages[i]);
9731 	}
9732 	kfree(pages);
9733 	return ret;
9734 }
9735 
btrfs_encoded_read(struct kiocb * iocb,struct iov_iter * iter,struct btrfs_ioctl_encoded_io_args * encoded,struct extent_state ** cached_state,u64 * disk_bytenr,u64 * disk_io_size)9736 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
9737 			   struct btrfs_ioctl_encoded_io_args *encoded,
9738 			   struct extent_state **cached_state,
9739 			   u64 *disk_bytenr, u64 *disk_io_size)
9740 {
9741 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9742 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
9743 	struct extent_io_tree *io_tree = &inode->io_tree;
9744 	ssize_t ret;
9745 	size_t count = iov_iter_count(iter);
9746 	u64 start, lockend;
9747 	struct extent_map *em;
9748 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9749 	bool unlocked = false;
9750 
9751 	file_accessed(iocb->ki_filp);
9752 
9753 	ret = btrfs_inode_lock(inode,
9754 			       BTRFS_ILOCK_SHARED | (nowait ? BTRFS_ILOCK_TRY : 0));
9755 	if (ret)
9756 		return ret;
9757 
9758 	if (iocb->ki_pos >= inode->vfs_inode.i_size) {
9759 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9760 		return 0;
9761 	}
9762 	start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
9763 	/*
9764 	 * We don't know how long the extent containing iocb->ki_pos is, but if
9765 	 * it's compressed we know that it won't be longer than this.
9766 	 */
9767 	lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
9768 
9769 	if (nowait) {
9770 		struct btrfs_ordered_extent *ordered;
9771 
9772 		if (filemap_range_needs_writeback(inode->vfs_inode.i_mapping,
9773 						  start, lockend)) {
9774 			ret = -EAGAIN;
9775 			goto out_unlock_inode;
9776 		}
9777 
9778 		if (!btrfs_try_lock_extent(io_tree, start, lockend, cached_state)) {
9779 			ret = -EAGAIN;
9780 			goto out_unlock_inode;
9781 		}
9782 
9783 		ordered = btrfs_lookup_ordered_range(inode, start,
9784 						     lockend - start + 1);
9785 		if (ordered) {
9786 			btrfs_put_ordered_extent(ordered);
9787 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9788 			ret = -EAGAIN;
9789 			goto out_unlock_inode;
9790 		}
9791 	} else {
9792 		for (;;) {
9793 			struct btrfs_ordered_extent *ordered;
9794 
9795 			ret = btrfs_wait_ordered_range(inode, start,
9796 						       lockend - start + 1);
9797 			if (ret)
9798 				goto out_unlock_inode;
9799 
9800 			btrfs_lock_extent(io_tree, start, lockend, cached_state);
9801 			ordered = btrfs_lookup_ordered_range(inode, start,
9802 							     lockend - start + 1);
9803 			if (!ordered)
9804 				break;
9805 			btrfs_put_ordered_extent(ordered);
9806 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9807 			cond_resched();
9808 		}
9809 	}
9810 
9811 	em = btrfs_get_extent(inode, NULL, start, lockend - start + 1);
9812 	if (IS_ERR(em)) {
9813 		ret = PTR_ERR(em);
9814 		goto out_unlock_extent;
9815 	}
9816 
9817 	if (em->disk_bytenr == EXTENT_MAP_INLINE) {
9818 		u64 extent_start = em->start;
9819 
9820 		/*
9821 		 * For inline extents we get everything we need out of the
9822 		 * extent item.
9823 		 */
9824 		btrfs_free_extent_map(em);
9825 		em = NULL;
9826 		ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
9827 						cached_state, extent_start,
9828 						count, encoded, &unlocked);
9829 		goto out_unlock_extent;
9830 	}
9831 
9832 	/*
9833 	 * We only want to return up to EOF even if the extent extends beyond
9834 	 * that.
9835 	 */
9836 	encoded->len = min_t(u64, btrfs_extent_map_end(em),
9837 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9838 	if (em->disk_bytenr == EXTENT_MAP_HOLE ||
9839 	    (em->flags & EXTENT_FLAG_PREALLOC)) {
9840 		*disk_bytenr = EXTENT_MAP_HOLE;
9841 		count = min_t(u64, count, encoded->len);
9842 		encoded->len = count;
9843 		encoded->unencoded_len = count;
9844 	} else if (btrfs_extent_map_is_compressed(em)) {
9845 		*disk_bytenr = em->disk_bytenr;
9846 		/*
9847 		 * Bail if the buffer isn't large enough to return the whole
9848 		 * compressed extent.
9849 		 */
9850 		if (em->disk_num_bytes > count) {
9851 			ret = -ENOBUFS;
9852 			goto out_em;
9853 		}
9854 		*disk_io_size = em->disk_num_bytes;
9855 		count = em->disk_num_bytes;
9856 		encoded->unencoded_len = em->ram_bytes;
9857 		encoded->unencoded_offset = iocb->ki_pos - (em->start - em->offset);
9858 		ret = btrfs_encoded_io_compression_from_extent(fs_info,
9859 					       btrfs_extent_map_compression(em));
9860 		if (ret < 0)
9861 			goto out_em;
9862 		encoded->compression = ret;
9863 	} else {
9864 		*disk_bytenr = btrfs_extent_map_block_start(em) + (start - em->start);
9865 		if (encoded->len > count)
9866 			encoded->len = count;
9867 		/*
9868 		 * Don't read beyond what we locked. This also limits the page
9869 		 * allocations that we'll do.
9870 		 */
9871 		*disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
9872 		count = start + *disk_io_size - iocb->ki_pos;
9873 		encoded->len = count;
9874 		encoded->unencoded_len = count;
9875 		*disk_io_size = ALIGN(*disk_io_size, fs_info->sectorsize);
9876 	}
9877 	btrfs_free_extent_map(em);
9878 	em = NULL;
9879 
9880 	if (*disk_bytenr == EXTENT_MAP_HOLE) {
9881 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9882 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9883 		unlocked = true;
9884 		ret = iov_iter_zero(count, iter);
9885 		if (ret != count)
9886 			ret = -EFAULT;
9887 	} else {
9888 		ret = -EIOCBQUEUED;
9889 		goto out_unlock_extent;
9890 	}
9891 
9892 out_em:
9893 	btrfs_free_extent_map(em);
9894 out_unlock_extent:
9895 	/* Leave inode and extent locked if we need to do a read. */
9896 	if (!unlocked && ret != -EIOCBQUEUED)
9897 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9898 out_unlock_inode:
9899 	if (!unlocked && ret != -EIOCBQUEUED)
9900 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9901 	return ret;
9902 }
9903 
btrfs_do_encoded_write(struct kiocb * iocb,struct iov_iter * from,const struct btrfs_ioctl_encoded_io_args * encoded)9904 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
9905 			       const struct btrfs_ioctl_encoded_io_args *encoded)
9906 {
9907 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9908 	struct btrfs_root *root = inode->root;
9909 	struct btrfs_fs_info *fs_info = root->fs_info;
9910 	struct extent_io_tree *io_tree = &inode->io_tree;
9911 	struct extent_changeset *data_reserved = NULL;
9912 	struct extent_state *cached_state = NULL;
9913 	struct btrfs_ordered_extent *ordered;
9914 	struct btrfs_file_extent file_extent;
9915 	struct compressed_bio *cb = NULL;
9916 	int compression;
9917 	size_t orig_count;
9918 	const u32 min_folio_size = btrfs_min_folio_size(fs_info);
9919 	const u32 blocksize = fs_info->sectorsize;
9920 	u64 start, end;
9921 	u64 num_bytes, ram_bytes, disk_num_bytes;
9922 	struct btrfs_key ins;
9923 	bool extent_reserved = false;
9924 	struct extent_map *em;
9925 	ssize_t ret;
9926 
9927 	switch (encoded->compression) {
9928 	case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
9929 		compression = BTRFS_COMPRESS_ZLIB;
9930 		break;
9931 	case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
9932 		compression = BTRFS_COMPRESS_ZSTD;
9933 		break;
9934 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
9935 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
9936 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
9937 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
9938 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
9939 		/* The sector size must match for LZO. */
9940 		if (encoded->compression -
9941 		    BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
9942 		    fs_info->sectorsize_bits)
9943 			return -EINVAL;
9944 		compression = BTRFS_COMPRESS_LZO;
9945 		break;
9946 	default:
9947 		return -EINVAL;
9948 	}
9949 	if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
9950 		return -EINVAL;
9951 
9952 	/*
9953 	 * Compressed extents should always have checksums, so error out if we
9954 	 * have a NOCOW file or inode was created while mounted with NODATASUM.
9955 	 */
9956 	if (inode->flags & BTRFS_INODE_NODATASUM)
9957 		return -EINVAL;
9958 
9959 	orig_count = iov_iter_count(from);
9960 
9961 	/* The extent size must be sane. */
9962 	if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
9963 	    orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
9964 		return -EINVAL;
9965 
9966 	/*
9967 	 * The compressed data must be smaller than the decompressed data.
9968 	 *
9969 	 * It's of course possible for data to compress to larger or the same
9970 	 * size, but the buffered I/O path falls back to no compression for such
9971 	 * data, and we don't want to break any assumptions by creating these
9972 	 * extents.
9973 	 *
9974 	 * Note that this is less strict than the current check we have that the
9975 	 * compressed data must be at least one sector smaller than the
9976 	 * decompressed data. We only want to enforce the weaker requirement
9977 	 * from old kernels that it is at least one byte smaller.
9978 	 */
9979 	if (orig_count >= encoded->unencoded_len)
9980 		return -EINVAL;
9981 
9982 	/* The extent must start on a sector boundary. */
9983 	start = iocb->ki_pos;
9984 	if (!IS_ALIGNED(start, fs_info->sectorsize))
9985 		return -EINVAL;
9986 
9987 	/*
9988 	 * The extent must end on a sector boundary. However, we allow a write
9989 	 * which ends at or extends i_size to have an unaligned length; we round
9990 	 * up the extent size and set i_size to the unaligned end.
9991 	 */
9992 	if (start + encoded->len < inode->vfs_inode.i_size &&
9993 	    !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
9994 		return -EINVAL;
9995 
9996 	/* Finally, the offset in the unencoded data must be sector-aligned. */
9997 	if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
9998 		return -EINVAL;
9999 
10000 	num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10001 	ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10002 	end = start + num_bytes - 1;
10003 
10004 	/*
10005 	 * If the extent cannot be inline, the compressed data on disk must be
10006 	 * sector-aligned. For convenience, we extend it with zeroes if it
10007 	 * isn't.
10008 	 */
10009 	disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10010 
10011 	cb = btrfs_alloc_compressed_write(inode, start, num_bytes);
10012 	for (int i = 0; i * min_folio_size < disk_num_bytes; i++) {
10013 		struct folio *folio;
10014 		size_t bytes = min(min_folio_size, iov_iter_count(from));
10015 		char *kaddr;
10016 
10017 		folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
10018 		if (!folio) {
10019 			ret = -ENOMEM;
10020 			goto out_cb;
10021 		}
10022 		kaddr = kmap_local_folio(folio, 0);
10023 		ret = copy_from_iter(kaddr, bytes, from);
10024 		kunmap_local(kaddr);
10025 		if (ret != bytes) {
10026 			folio_put(folio);
10027 			ret = -EFAULT;
10028 			goto out_cb;
10029 		}
10030 		if (!IS_ALIGNED(bytes, blocksize))
10031 			folio_zero_range(folio, bytes, round_up(bytes, blocksize) - bytes);
10032 		ret = bio_add_folio(&cb->bbio.bio, folio, round_up(bytes, blocksize), 0);
10033 		if (unlikely(!ret)) {
10034 			folio_put(folio);
10035 			ret = -EINVAL;
10036 			goto out_cb;
10037 		}
10038 	}
10039 	ASSERT(cb->bbio.bio.bi_iter.bi_size == disk_num_bytes);
10040 
10041 	for (;;) {
10042 		ret = btrfs_wait_ordered_range(inode, start, num_bytes);
10043 		if (ret)
10044 			goto out_cb;
10045 		ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10046 						    start >> PAGE_SHIFT,
10047 						    end >> PAGE_SHIFT);
10048 		if (ret)
10049 			goto out_cb;
10050 		btrfs_lock_extent(io_tree, start, end, &cached_state);
10051 		ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10052 		if (!ordered &&
10053 		    !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10054 			break;
10055 		if (ordered)
10056 			btrfs_put_ordered_extent(ordered);
10057 		btrfs_unlock_extent(io_tree, start, end, &cached_state);
10058 		cond_resched();
10059 	}
10060 
10061 	/*
10062 	 * We don't use the higher-level delalloc space functions because our
10063 	 * num_bytes and disk_num_bytes are different.
10064 	 */
10065 	ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10066 	if (ret)
10067 		goto out_unlock;
10068 	ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10069 	if (ret)
10070 		goto out_free_data_space;
10071 	ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10072 					      false);
10073 	if (ret)
10074 		goto out_qgroup_free_data;
10075 
10076 	/* Try an inline extent first. */
10077 	if (encoded->unencoded_len == encoded->len &&
10078 	    encoded->unencoded_offset == 0 &&
10079 	    can_cow_file_range_inline(inode, start, encoded->len, orig_count)) {
10080 		ret = __cow_file_range_inline(inode, encoded->len,
10081 					      orig_count, compression,
10082 					      bio_first_folio_all(&cb->bbio.bio),
10083 					      true);
10084 		if (ret <= 0) {
10085 			if (ret == 0)
10086 				ret = orig_count;
10087 			goto out_delalloc_release;
10088 		}
10089 	}
10090 
10091 	ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10092 				   disk_num_bytes, 0, 0, &ins, true, true);
10093 	if (ret)
10094 		goto out_delalloc_release;
10095 	extent_reserved = true;
10096 
10097 	file_extent.disk_bytenr = ins.objectid;
10098 	file_extent.disk_num_bytes = ins.offset;
10099 	file_extent.num_bytes = num_bytes;
10100 	file_extent.ram_bytes = ram_bytes;
10101 	file_extent.offset = encoded->unencoded_offset;
10102 	file_extent.compression = compression;
10103 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
10104 	if (IS_ERR(em)) {
10105 		ret = PTR_ERR(em);
10106 		goto out_free_reserved;
10107 	}
10108 	btrfs_free_extent_map(em);
10109 
10110 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
10111 				       (1U << BTRFS_ORDERED_ENCODED) |
10112 				       (1U << BTRFS_ORDERED_COMPRESSED));
10113 	if (IS_ERR(ordered)) {
10114 		btrfs_drop_extent_map_range(inode, start, end, false);
10115 		ret = PTR_ERR(ordered);
10116 		goto out_free_reserved;
10117 	}
10118 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10119 
10120 	if (start + encoded->len > inode->vfs_inode.i_size)
10121 		i_size_write(&inode->vfs_inode, start + encoded->len);
10122 
10123 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
10124 
10125 	btrfs_delalloc_release_extents(inode, num_bytes);
10126 
10127 	btrfs_submit_compressed_write(ordered, cb);
10128 	ret = orig_count;
10129 	goto out;
10130 
10131 out_free_reserved:
10132 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10133 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
10134 out_delalloc_release:
10135 	btrfs_delalloc_release_extents(inode, num_bytes);
10136 	btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10137 out_qgroup_free_data:
10138 	if (ret < 0)
10139 		btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
10140 out_free_data_space:
10141 	/*
10142 	 * If btrfs_reserve_extent() succeeded, then we already decremented
10143 	 * bytes_may_use.
10144 	 */
10145 	if (!extent_reserved)
10146 		btrfs_free_reserved_data_space_noquota(inode, disk_num_bytes);
10147 out_unlock:
10148 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
10149 out_cb:
10150 	if (cb)
10151 		cleanup_compressed_bio(cb);
10152 out:
10153 	extent_changeset_free(data_reserved);
10154 	if (ret >= 0)
10155 		iocb->ki_pos += encoded->len;
10156 	return ret;
10157 }
10158 
10159 #ifdef CONFIG_SWAP
10160 /*
10161  * Add an entry indicating a block group or device which is pinned by a
10162  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10163  * negative errno on failure.
10164  */
btrfs_add_swapfile_pin(struct inode * inode,void * ptr,bool is_block_group)10165 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10166 				  bool is_block_group)
10167 {
10168 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10169 	struct btrfs_swapfile_pin *sp, *entry;
10170 	struct rb_node **p;
10171 	struct rb_node *parent = NULL;
10172 
10173 	sp = kmalloc_obj(*sp, GFP_NOFS);
10174 	if (!sp)
10175 		return -ENOMEM;
10176 	sp->ptr = ptr;
10177 	sp->inode = inode;
10178 	sp->is_block_group = is_block_group;
10179 	sp->bg_extent_count = 1;
10180 
10181 	spin_lock(&fs_info->swapfile_pins_lock);
10182 	p = &fs_info->swapfile_pins.rb_node;
10183 	while (*p) {
10184 		parent = *p;
10185 		entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10186 		if (sp->ptr < entry->ptr ||
10187 		    (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10188 			p = &(*p)->rb_left;
10189 		} else if (sp->ptr > entry->ptr ||
10190 			   (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10191 			p = &(*p)->rb_right;
10192 		} else {
10193 			if (is_block_group)
10194 				entry->bg_extent_count++;
10195 			spin_unlock(&fs_info->swapfile_pins_lock);
10196 			kfree(sp);
10197 			return 1;
10198 		}
10199 	}
10200 	rb_link_node(&sp->node, parent, p);
10201 	rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10202 	spin_unlock(&fs_info->swapfile_pins_lock);
10203 	return 0;
10204 }
10205 
10206 /* Free all of the entries pinned by this swapfile. */
btrfs_free_swapfile_pins(struct inode * inode)10207 static void btrfs_free_swapfile_pins(struct inode *inode)
10208 {
10209 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10210 	struct btrfs_swapfile_pin *sp;
10211 	struct rb_node *node, *next;
10212 	u64 bg_bytes_released = 0;
10213 	u32 bg_nr_released = 0;
10214 
10215 	spin_lock(&fs_info->swapfile_pins_lock);
10216 	node = rb_first(&fs_info->swapfile_pins);
10217 	while (node) {
10218 		next = rb_next(node);
10219 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10220 		if (sp->inode == inode) {
10221 			rb_erase(&sp->node, &fs_info->swapfile_pins);
10222 			if (sp->is_block_group) {
10223 				struct btrfs_block_group *bg = sp->ptr;
10224 
10225 				bg_bytes_released += bg->length;
10226 				bg_nr_released++;
10227 				btrfs_dec_block_group_swap_extents(bg,
10228 							   sp->bg_extent_count);
10229 				btrfs_put_block_group(bg);
10230 			}
10231 			kfree(sp);
10232 		}
10233 		node = next;
10234 	}
10235 	spin_unlock(&fs_info->swapfile_pins_lock);
10236 	btrfs_info(fs_info,
10237 "swapfile deactivated on root %llu ino %llu, released %llu bytes from %u block group(s)",
10238 		   btrfs_root_id(BTRFS_I(inode)->root),
10239 		   btrfs_ino(BTRFS_I(inode)), bg_bytes_released,
10240 		   bg_nr_released);
10241 }
10242 
10243 struct btrfs_swap_info {
10244 	u64 start;
10245 	u64 block_start;
10246 	u64 block_len;
10247 	u64 lowest_ppage;
10248 	u64 highest_ppage;
10249 	unsigned long nr_pages;
10250 	int nr_extents;
10251 };
10252 
btrfs_add_swap_extent(struct swap_info_struct * sis,struct btrfs_swap_info * bsi)10253 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10254 				 struct btrfs_swap_info *bsi)
10255 {
10256 	unsigned long nr_pages;
10257 	unsigned long max_pages;
10258 	u64 first_ppage, first_ppage_reported, next_ppage;
10259 	int ret;
10260 
10261 	/*
10262 	 * Our swapfile may have had its size extended after the swap header was
10263 	 * written. In that case activating the swapfile should not go beyond
10264 	 * the max size set in the swap header.
10265 	 */
10266 	if (bsi->nr_pages >= sis->max)
10267 		return 0;
10268 
10269 	max_pages = sis->max - bsi->nr_pages;
10270 	first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10271 	next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10272 
10273 	if (first_ppage >= next_ppage)
10274 		return 0;
10275 	nr_pages = next_ppage - first_ppage;
10276 	nr_pages = min(nr_pages, max_pages);
10277 
10278 	first_ppage_reported = first_ppage;
10279 	if (bsi->start == 0)
10280 		first_ppage_reported++;
10281 	if (bsi->lowest_ppage > first_ppage_reported)
10282 		bsi->lowest_ppage = first_ppage_reported;
10283 	if (bsi->highest_ppage < (next_ppage - 1))
10284 		bsi->highest_ppage = next_ppage - 1;
10285 
10286 	ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10287 	if (ret < 0)
10288 		return ret;
10289 	bsi->nr_extents += ret;
10290 	bsi->nr_pages += nr_pages;
10291 	return 0;
10292 }
10293 
btrfs_swap_deactivate(struct file * file)10294 static void btrfs_swap_deactivate(struct file *file)
10295 {
10296 	struct inode *inode = file_inode(file);
10297 
10298 	btrfs_free_swapfile_pins(inode);
10299 	atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10300 }
10301 
btrfs_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)10302 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10303 			       sector_t *span)
10304 {
10305 	struct inode *inode = file_inode(file);
10306 	struct btrfs_root *root = BTRFS_I(inode)->root;
10307 	struct btrfs_fs_info *fs_info = root->fs_info;
10308 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10309 	struct extent_state *cached_state = NULL;
10310 	struct btrfs_chunk_map *map = NULL;
10311 	struct btrfs_device *device = NULL;
10312 	struct btrfs_swap_info bsi = {
10313 		.lowest_ppage = (sector_t)-1ULL,
10314 	};
10315 	struct btrfs_backref_share_check_ctx *backref_ctx = NULL;
10316 	struct btrfs_path *path = NULL;
10317 	int ret = 0;
10318 	u32 pinned_bg_nr = 0;
10319 	u64 isize;
10320 	u64 prev_extent_end = 0;
10321 	u64 pinned_bg_size = 0;
10322 
10323 	/*
10324 	 * Acquire the inode's mmap lock to prevent races with memory mapped
10325 	 * writes, as they could happen after we flush delalloc below and before
10326 	 * we lock the extent range further below. The inode was already locked
10327 	 * up in the call chain.
10328 	 */
10329 	btrfs_assert_inode_locked(BTRFS_I(inode));
10330 	down_write(&BTRFS_I(inode)->i_mmap_lock);
10331 
10332 	/*
10333 	 * If the swap file was just created, make sure delalloc is done. If the
10334 	 * file changes again after this, the user is doing something stupid and
10335 	 * we don't really care.
10336 	 */
10337 	ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
10338 	if (ret)
10339 		goto out_unlock_mmap;
10340 
10341 	/*
10342 	 * The inode is locked, so these flags won't change after we check them.
10343 	 */
10344 	if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10345 		btrfs_warn(fs_info, "swapfile must not be compressed");
10346 		ret = -EINVAL;
10347 		goto out_unlock_mmap;
10348 	}
10349 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10350 		btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10351 		ret = -EINVAL;
10352 		goto out_unlock_mmap;
10353 	}
10354 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10355 		btrfs_warn(fs_info, "swapfile must not be checksummed");
10356 		ret = -EINVAL;
10357 		goto out_unlock_mmap;
10358 	}
10359 
10360 	path = btrfs_alloc_path();
10361 	backref_ctx = btrfs_alloc_backref_share_check_ctx();
10362 	if (!path || !backref_ctx) {
10363 		ret = -ENOMEM;
10364 		goto out_unlock_mmap;
10365 	}
10366 
10367 	/*
10368 	 * Balance or device remove/replace/resize can move stuff around from
10369 	 * under us. The exclop protection makes sure they aren't running/won't
10370 	 * run concurrently while we are mapping the swap extents, and
10371 	 * fs_info->swapfile_pins prevents them from running while the swap
10372 	 * file is active and moving the extents. Note that this also prevents
10373 	 * a concurrent device add which isn't actually necessary, but it's not
10374 	 * really worth the trouble to allow it.
10375 	 */
10376 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10377 		btrfs_warn(fs_info,
10378 	   "cannot activate swapfile while exclusive operation is running");
10379 		ret = -EBUSY;
10380 		goto out_unlock_mmap;
10381 	}
10382 
10383 	/*
10384 	 * Prevent snapshot creation while we are activating the swap file.
10385 	 * We do not want to race with snapshot creation. If snapshot creation
10386 	 * already started before we bumped nr_swapfiles from 0 to 1 and
10387 	 * completes before the first write into the swap file after it is
10388 	 * activated, than that write would fallback to COW.
10389 	 */
10390 	if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10391 		btrfs_exclop_finish(fs_info);
10392 		btrfs_warn(fs_info,
10393 	   "cannot activate swapfile because snapshot creation is in progress");
10394 		ret = -EINVAL;
10395 		goto out_unlock_mmap;
10396 	}
10397 	/*
10398 	 * Snapshots can create extents which require COW even if NODATACOW is
10399 	 * set. We use this counter to prevent snapshots. We must increment it
10400 	 * before walking the extents because we don't want a concurrent
10401 	 * snapshot to run after we've already checked the extents.
10402 	 *
10403 	 * It is possible that subvolume is marked for deletion but still not
10404 	 * removed yet. To prevent this race, we check the root status before
10405 	 * activating the swapfile.
10406 	 */
10407 	spin_lock(&root->root_item_lock);
10408 	if (btrfs_root_dead(root)) {
10409 		spin_unlock(&root->root_item_lock);
10410 
10411 		btrfs_drew_write_unlock(&root->snapshot_lock);
10412 		btrfs_exclop_finish(fs_info);
10413 		btrfs_warn(fs_info,
10414 		"cannot activate swapfile because subvolume %llu is being deleted",
10415 			btrfs_root_id(root));
10416 		ret = -EPERM;
10417 		goto out_unlock_mmap;
10418 	}
10419 	atomic_inc(&root->nr_swapfiles);
10420 	spin_unlock(&root->root_item_lock);
10421 
10422 	isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10423 
10424 	btrfs_lock_extent(io_tree, 0, isize - 1, &cached_state);
10425 	while (prev_extent_end < isize) {
10426 		struct btrfs_key key;
10427 		struct extent_buffer *leaf;
10428 		struct btrfs_file_extent_item *ei;
10429 		struct btrfs_block_group *bg;
10430 		u64 logical_block_start;
10431 		u64 physical_block_start;
10432 		u64 extent_gen;
10433 		u64 disk_bytenr;
10434 		u64 len;
10435 
10436 		key.objectid = btrfs_ino(BTRFS_I(inode));
10437 		key.type = BTRFS_EXTENT_DATA_KEY;
10438 		key.offset = prev_extent_end;
10439 
10440 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
10441 		if (ret < 0)
10442 			goto out;
10443 
10444 		/*
10445 		 * If key not found it means we have an implicit hole (NO_HOLES
10446 		 * is enabled).
10447 		 */
10448 		if (ret > 0) {
10449 			btrfs_warn(fs_info, "swapfile must not have holes");
10450 			ret = -EINVAL;
10451 			goto out;
10452 		}
10453 
10454 		leaf = path->nodes[0];
10455 		ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10456 
10457 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
10458 			/*
10459 			 * It's unlikely we'll ever actually find ourselves
10460 			 * here, as a file small enough to fit inline won't be
10461 			 * big enough to store more than the swap header, but in
10462 			 * case something changes in the future, let's catch it
10463 			 * here rather than later.
10464 			 */
10465 			btrfs_warn(fs_info, "swapfile must not be inline");
10466 			ret = -EINVAL;
10467 			goto out;
10468 		}
10469 
10470 		if (btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
10471 			btrfs_warn(fs_info, "swapfile must not be compressed");
10472 			ret = -EINVAL;
10473 			goto out;
10474 		}
10475 
10476 		disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
10477 		if (disk_bytenr == 0) {
10478 			btrfs_warn(fs_info, "swapfile must not have holes");
10479 			ret = -EINVAL;
10480 			goto out;
10481 		}
10482 
10483 		logical_block_start = disk_bytenr + btrfs_file_extent_offset(leaf, ei);
10484 		extent_gen = btrfs_file_extent_generation(leaf, ei);
10485 		prev_extent_end = btrfs_file_extent_end(path);
10486 
10487 		if (prev_extent_end > isize)
10488 			len = isize - key.offset;
10489 		else
10490 			len = btrfs_file_extent_num_bytes(leaf, ei);
10491 
10492 		backref_ctx->curr_leaf_bytenr = leaf->start;
10493 
10494 		/*
10495 		 * Don't need the path anymore, release to avoid deadlocks when
10496 		 * calling btrfs_is_data_extent_shared() because when joining a
10497 		 * transaction it can block waiting for the current one's commit
10498 		 * which in turn may be trying to lock the same leaf to flush
10499 		 * delayed items for example.
10500 		 */
10501 		btrfs_release_path(path);
10502 
10503 		ret = btrfs_is_data_extent_shared(BTRFS_I(inode), disk_bytenr,
10504 						  extent_gen, backref_ctx);
10505 		if (ret < 0) {
10506 			goto out;
10507 		} else if (ret > 0) {
10508 			btrfs_warn(fs_info,
10509 				   "swapfile must not be copy-on-write");
10510 			ret = -EINVAL;
10511 			goto out;
10512 		}
10513 
10514 		map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10515 		if (IS_ERR(map)) {
10516 			ret = PTR_ERR(map);
10517 			goto out;
10518 		}
10519 
10520 		if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10521 			btrfs_warn(fs_info,
10522 				   "swapfile must have single data profile");
10523 			ret = -EINVAL;
10524 			goto out;
10525 		}
10526 
10527 		if (device == NULL) {
10528 			device = map->stripes[0].dev;
10529 			ret = btrfs_add_swapfile_pin(inode, device, false);
10530 			if (ret == 1)
10531 				ret = 0;
10532 			else if (ret)
10533 				goto out;
10534 		} else if (device != map->stripes[0].dev) {
10535 			btrfs_warn(fs_info, "swapfile must be on one device");
10536 			ret = -EINVAL;
10537 			goto out;
10538 		}
10539 
10540 		physical_block_start = (map->stripes[0].physical +
10541 					(logical_block_start - map->start));
10542 		btrfs_free_chunk_map(map);
10543 		map = NULL;
10544 
10545 		bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10546 		if (!bg) {
10547 			btrfs_warn(fs_info,
10548 			   "could not find block group containing swapfile");
10549 			ret = -EINVAL;
10550 			goto out;
10551 		}
10552 
10553 		if (!btrfs_inc_block_group_swap_extents(bg)) {
10554 			btrfs_warn(fs_info,
10555 			   "block group for swapfile at %llu is read-only%s",
10556 			   bg->start,
10557 			   atomic_read(&fs_info->scrubs_running) ?
10558 				       " (scrub running)" : "");
10559 			btrfs_put_block_group(bg);
10560 			ret = -EINVAL;
10561 			goto out;
10562 		}
10563 
10564 		ret = btrfs_add_swapfile_pin(inode, bg, true);
10565 		if (ret) {
10566 			btrfs_put_block_group(bg);
10567 			if (ret == 1)
10568 				ret = 0;
10569 			else
10570 				goto out;
10571 		} else {
10572 			pinned_bg_size += bg->length;
10573 			pinned_bg_nr++;
10574 		}
10575 
10576 		if (bsi.block_len &&
10577 		    bsi.block_start + bsi.block_len == physical_block_start) {
10578 			bsi.block_len += len;
10579 		} else {
10580 			if (bsi.block_len) {
10581 				ret = btrfs_add_swap_extent(sis, &bsi);
10582 				if (ret)
10583 					goto out;
10584 			}
10585 			bsi.start = key.offset;
10586 			bsi.block_start = physical_block_start;
10587 			bsi.block_len = len;
10588 		}
10589 
10590 		if (fatal_signal_pending(current)) {
10591 			ret = -EINTR;
10592 			goto out;
10593 		}
10594 
10595 		cond_resched();
10596 	}
10597 
10598 	if (bsi.block_len)
10599 		ret = btrfs_add_swap_extent(sis, &bsi);
10600 
10601 out:
10602 	if (!IS_ERR_OR_NULL(map))
10603 		btrfs_free_chunk_map(map);
10604 
10605 	btrfs_unlock_extent(io_tree, 0, isize - 1, &cached_state);
10606 
10607 	if (ret)
10608 		btrfs_swap_deactivate(file);
10609 
10610 	btrfs_drew_write_unlock(&root->snapshot_lock);
10611 
10612 	btrfs_exclop_finish(fs_info);
10613 
10614 out_unlock_mmap:
10615 	up_write(&BTRFS_I(inode)->i_mmap_lock);
10616 	btrfs_free_backref_share_ctx(backref_ctx);
10617 	btrfs_free_path(path);
10618 	if (ret)
10619 		return ret;
10620 
10621 	btrfs_info(fs_info,
10622 "swapfile activated on root %llu ino %llu, pinned down %llu bytes from %u block group(s)",
10623 		   btrfs_root_id(BTRFS_I(inode)->root),
10624 		   btrfs_ino(BTRFS_I(inode)),
10625 		   pinned_bg_size, pinned_bg_nr);
10626 	btrfs_warn(fs_info,
10627 "block groups with swapfile extents will not be scrubbed or balanced");
10628 
10629 	if (device)
10630 		sis->bdev = device->bdev;
10631 	*span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10632 	sis->max = bsi.nr_pages;
10633 	sis->pages = bsi.nr_pages - 1;
10634 	return bsi.nr_extents;
10635 }
10636 #else
btrfs_swap_deactivate(struct file * file)10637 static void btrfs_swap_deactivate(struct file *file)
10638 {
10639 }
10640 
btrfs_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)10641 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10642 			       sector_t *span)
10643 {
10644 	return -EOPNOTSUPP;
10645 }
10646 #endif
10647 
10648 /*
10649  * Update the number of bytes used in the VFS' inode. When we replace extents in
10650  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10651  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10652  * always get a correct value.
10653  */
btrfs_update_inode_bytes(struct btrfs_inode * inode,const u64 add_bytes,const u64 del_bytes)10654 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10655 			      const u64 add_bytes,
10656 			      const u64 del_bytes)
10657 {
10658 	if (add_bytes == del_bytes)
10659 		return;
10660 
10661 	spin_lock(&inode->lock);
10662 	if (del_bytes > 0)
10663 		inode_sub_bytes(&inode->vfs_inode, del_bytes);
10664 	if (add_bytes > 0)
10665 		inode_add_bytes(&inode->vfs_inode, add_bytes);
10666 	spin_unlock(&inode->lock);
10667 }
10668 
10669 /*
10670  * Verify that there are no ordered extents for a given file range.
10671  *
10672  * @inode:   The target inode.
10673  * @start:   Start offset of the file range, should be sector size aligned.
10674  * @end:     End offset (inclusive) of the file range, its value +1 should be
10675  *           sector size aligned.
10676  *
10677  * This should typically be used for cases where we locked an inode's VFS lock in
10678  * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10679  * we have flushed all delalloc in the range, we have waited for all ordered
10680  * extents in the range to complete and finally we have locked the file range in
10681  * the inode's io_tree.
10682  */
btrfs_assert_inode_range_clean(struct btrfs_inode * inode,u64 start,u64 end)10683 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10684 {
10685 	struct btrfs_root *root = inode->root;
10686 	struct btrfs_ordered_extent *ordered;
10687 
10688 	if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10689 		return;
10690 
10691 	ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10692 	if (ordered) {
10693 		btrfs_err(root->fs_info,
10694 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10695 			  start, end, btrfs_ino(inode), btrfs_root_id(root),
10696 			  ordered->file_offset,
10697 			  ordered->file_offset + ordered->num_bytes - 1);
10698 		btrfs_put_ordered_extent(ordered);
10699 	}
10700 
10701 	ASSERT(ordered == NULL);
10702 }
10703 
10704 /*
10705  * Find the first inode with a minimum number.
10706  *
10707  * @root:	The root to search for.
10708  * @min_ino:	The minimum inode number.
10709  *
10710  * Find the first inode in the @root with a number >= @min_ino and return it.
10711  * Returns NULL if no such inode found.
10712  */
btrfs_find_first_inode(struct btrfs_root * root,u64 min_ino)10713 struct btrfs_inode *btrfs_find_first_inode(struct btrfs_root *root, u64 min_ino)
10714 {
10715 	struct btrfs_inode *inode;
10716 	unsigned long from = min_ino;
10717 
10718 	xa_lock(&root->inodes);
10719 	while (true) {
10720 		inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
10721 		if (!inode)
10722 			break;
10723 		if (igrab(&inode->vfs_inode))
10724 			break;
10725 
10726 		from = btrfs_ino(inode) + 1;
10727 		xa_unlock(&root->inodes);
10728 		cond_resched();
10729 		xa_lock(&root->inodes);
10730 	}
10731 	xa_unlock(&root->inodes);
10732 
10733 	return inode;
10734 }
10735 
10736 static const struct inode_operations btrfs_dir_inode_operations = {
10737 	.getattr	= btrfs_getattr,
10738 	.lookup		= btrfs_lookup,
10739 	.create		= btrfs_create,
10740 	.unlink		= btrfs_unlink,
10741 	.link		= btrfs_link,
10742 	.mkdir		= btrfs_mkdir,
10743 	.rmdir		= btrfs_rmdir,
10744 	.rename		= btrfs_rename2,
10745 	.symlink	= btrfs_symlink,
10746 	.setattr	= btrfs_setattr,
10747 	.mknod		= btrfs_mknod,
10748 	.listxattr	= btrfs_listxattr,
10749 	.permission	= btrfs_permission,
10750 	.get_inode_acl	= btrfs_get_acl,
10751 	.set_acl	= btrfs_set_acl,
10752 	.update_time	= btrfs_update_time,
10753 	.tmpfile        = btrfs_tmpfile,
10754 	.fileattr_get	= btrfs_fileattr_get,
10755 	.fileattr_set	= btrfs_fileattr_set,
10756 };
10757 
10758 static const struct file_operations btrfs_dir_file_operations = {
10759 	.llseek		= btrfs_dir_llseek,
10760 	.read		= generic_read_dir,
10761 	.iterate_shared	= btrfs_real_readdir,
10762 	.open		= btrfs_opendir,
10763 	.unlocked_ioctl	= btrfs_ioctl,
10764 #ifdef CONFIG_COMPAT
10765 	.compat_ioctl	= btrfs_compat_ioctl,
10766 #endif
10767 	.release        = btrfs_release_file,
10768 	.fsync		= btrfs_sync_file,
10769 	.setlease	= generic_setlease,
10770 };
10771 
10772 /*
10773  * The folio is going dirty without a btrfs delalloc space reservation.
10774  * This requires a fixup before writeback which we might sleep so cannot
10775  * run in this context, so we merely set state on the folio indicating it
10776  * needs fixup before writeback.
10777  *
10778  * Note that there is no range in the input, so the whole folio is marked
10779  * dirty and fixup.
10780  *
10781  * We believe that all callers of dirty_folio either:
10782  * - take the folio lock (e.g. pinned folio release notification).
10783  * - take the pte lock but must be running on a dirty pte which means
10784  *   page_mkwrite() ran on it and reserved the space. zap_pte_range() cannot
10785  *   race with writeback cleaning the folio because writeback runs
10786  *   folio_mkclean() which also uses the pte lock and revokes outstanding
10787  *   writable mappings.
10788  * Therefore, an additional folio private lock (a la bfs->lock for all cases,
10789  * not just subpage) is not necessary.
10790  */
btrfs_data_dirty_folio(struct address_space * mapping,struct folio * folio)10791 static bool btrfs_data_dirty_folio(struct address_space *mapping,
10792 				   struct folio *folio)
10793 {
10794 	struct btrfs_inode *inode = BTRFS_I(mapping->host);
10795 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
10796 	const u64 page_start = folio_pos(folio);
10797 	const u64 range_end = min_t(u64, folio_next_pos(folio),
10798 				    round_up(i_size_read(&inode->vfs_inode),
10799 					     fs_info->sectorsize));
10800 
10801 	if (range_end > page_start)
10802 		btrfs_folio_set_fixup_dirty(fs_info, folio, page_start,
10803 					    range_end - page_start);
10804 	return filemap_dirty_folio(mapping, folio);
10805 }
10806 
10807 /*
10808  * btrfs doesn't support the bmap operation because swapfiles
10809  * use bmap to make a mapping of extents in the file.  They assume
10810  * these extents won't change over the life of the file and they
10811  * use the bmap result to do IO directly to the drive.
10812  *
10813  * the btrfs bmap call would return logical addresses that aren't
10814  * suitable for IO and they also will change frequently as COW
10815  * operations happen.  So, swapfile + btrfs == corruption.
10816  *
10817  * For now we're avoiding this by dropping bmap.
10818  */
10819 static const struct address_space_operations btrfs_aops = {
10820 	.read_folio	= btrfs_read_folio,
10821 	.writepages	= btrfs_writepages,
10822 	.readahead	= btrfs_readahead,
10823 	.invalidate_folio = btrfs_invalidate_folio,
10824 	.launder_folio	= btrfs_launder_folio,
10825 	.release_folio	= btrfs_release_folio,
10826 	.migrate_folio	= btrfs_migrate_folio,
10827 	.dirty_folio	= btrfs_data_dirty_folio,
10828 	.error_remove_folio = generic_error_remove_folio,
10829 	.swap_activate	= btrfs_swap_activate,
10830 	.swap_deactivate = btrfs_swap_deactivate,
10831 };
10832 
10833 static const struct inode_operations btrfs_file_inode_operations = {
10834 	.getattr	= btrfs_getattr,
10835 	.setattr	= btrfs_setattr,
10836 	.listxattr      = btrfs_listxattr,
10837 	.permission	= btrfs_permission,
10838 	.fiemap		= btrfs_fiemap,
10839 	.get_inode_acl	= btrfs_get_acl,
10840 	.set_acl	= btrfs_set_acl,
10841 	.update_time	= btrfs_update_time,
10842 	.fileattr_get	= btrfs_fileattr_get,
10843 	.fileattr_set	= btrfs_fileattr_set,
10844 };
10845 static const struct inode_operations btrfs_special_inode_operations = {
10846 	.getattr	= btrfs_getattr,
10847 	.setattr	= btrfs_setattr,
10848 	.permission	= btrfs_permission,
10849 	.listxattr	= btrfs_listxattr,
10850 	.get_inode_acl	= btrfs_get_acl,
10851 	.set_acl	= btrfs_set_acl,
10852 	.update_time	= btrfs_update_time,
10853 };
10854 static const struct inode_operations btrfs_symlink_inode_operations = {
10855 	.get_link	= page_get_link,
10856 	.getattr	= btrfs_getattr,
10857 	.setattr	= btrfs_setattr,
10858 	.permission	= btrfs_permission,
10859 	.listxattr	= btrfs_listxattr,
10860 	.update_time	= btrfs_update_time,
10861 };
10862 
10863 const struct dentry_operations btrfs_dentry_operations = {
10864 	.d_delete	= btrfs_dentry_delete,
10865 };
10866