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