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