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