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