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