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