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