xref: /linux/fs/btrfs/inode.c (revision 0e39a731820ad26533eb988cef27ad2506063b5b) !
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 
4192 /*
4193  * unlink helper that gets used here in inode.c and in the tree logging
4194  * recovery code.  It remove a link in a directory with a given name, and
4195  * also drops the back refs in the inode to the directory
4196  */
__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)4197 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4198 				struct btrfs_inode *dir,
4199 				struct btrfs_inode *inode,
4200 				const struct fscrypt_str *name,
4201 				struct btrfs_rename_ctx *rename_ctx)
4202 {
4203 	struct btrfs_root *root = dir->root;
4204 	struct btrfs_fs_info *fs_info = root->fs_info;
4205 	struct btrfs_path *path;
4206 	int ret = 0;
4207 	struct btrfs_dir_item *di;
4208 	u64 index;
4209 	u64 ino = btrfs_ino(inode);
4210 	u64 dir_ino = btrfs_ino(dir);
4211 
4212 	path = btrfs_alloc_path();
4213 	if (!path)
4214 		return -ENOMEM;
4215 
4216 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4217 	if (IS_ERR_OR_NULL(di)) {
4218 		btrfs_free_path(path);
4219 		return di ? PTR_ERR(di) : -ENOENT;
4220 	}
4221 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4222 	/*
4223 	 * Down the call chains below we'll also need to allocate a path, so no
4224 	 * need to hold on to this one for longer than necessary.
4225 	 */
4226 	btrfs_free_path(path);
4227 	if (ret)
4228 		return ret;
4229 
4230 	/*
4231 	 * If we don't have dir index, we have to get it by looking up
4232 	 * the inode ref, since we get the inode ref, remove it directly,
4233 	 * it is unnecessary to do delayed deletion.
4234 	 *
4235 	 * But if we have dir index, needn't search inode ref to get it.
4236 	 * Since the inode ref is close to the inode item, it is better
4237 	 * that we delay to delete it, and just do this deletion when
4238 	 * we update the inode item.
4239 	 */
4240 	if (inode->dir_index) {
4241 		ret = btrfs_delayed_delete_inode_ref(inode);
4242 		if (!ret) {
4243 			index = inode->dir_index;
4244 			goto skip_backref;
4245 		}
4246 	}
4247 
4248 	ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4249 	if (ret) {
4250 		btrfs_crit(fs_info,
4251 	   "failed to delete reference to %.*s, root %llu inode %llu parent %llu",
4252 			   name->len, name->name, btrfs_root_id(root), ino, dir_ino);
4253 		btrfs_abort_transaction(trans, ret);
4254 		return ret;
4255 	}
4256 skip_backref:
4257 	if (rename_ctx)
4258 		rename_ctx->index = index;
4259 
4260 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4261 	if (ret) {
4262 		btrfs_abort_transaction(trans, ret);
4263 		return ret;
4264 	}
4265 
4266 	/*
4267 	 * If we are in a rename context, we don't need to update anything in the
4268 	 * log. That will be done later during the rename by btrfs_log_new_name().
4269 	 * Besides that, doing it here would only cause extra unnecessary btree
4270 	 * operations on the log tree, increasing latency for applications.
4271 	 */
4272 	if (!rename_ctx) {
4273 		btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4274 		btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4275 	}
4276 
4277 	/*
4278 	 * If we have a pending delayed iput we could end up with the final iput
4279 	 * being run in btrfs-cleaner context.  If we have enough of these built
4280 	 * up we can end up burning a lot of time in btrfs-cleaner without any
4281 	 * way to throttle the unlinks.  Since we're currently holding a ref on
4282 	 * the inode we can run the delayed iput here without any issues as the
4283 	 * final iput won't be done until after we drop the ref we're currently
4284 	 * holding.
4285 	 */
4286 	btrfs_run_delayed_iput(fs_info, inode);
4287 
4288 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4289 	inode_inc_iversion(&inode->vfs_inode);
4290 	inode_set_ctime_current(&inode->vfs_inode);
4291 	inode_inc_iversion(&dir->vfs_inode);
4292  	inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4293 
4294 	return btrfs_update_inode(trans, dir);
4295 }
4296 
btrfs_unlink_inode(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct btrfs_inode * inode,const struct fscrypt_str * name)4297 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4298 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4299 		       const struct fscrypt_str *name)
4300 {
4301 	int ret;
4302 
4303 	ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4304 	if (!ret) {
4305 		drop_nlink(&inode->vfs_inode);
4306 		ret = btrfs_update_inode(trans, inode);
4307 	}
4308 	return ret;
4309 }
4310 
4311 /*
4312  * helper to start transaction for unlink and rmdir.
4313  *
4314  * unlink and rmdir are special in btrfs, they do not always free space, so
4315  * if we cannot make our reservations the normal way try and see if there is
4316  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4317  * allow the unlink to occur.
4318  */
__unlink_start_trans(struct btrfs_inode * dir)4319 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4320 {
4321 	struct btrfs_root *root = dir->root;
4322 
4323 	return btrfs_start_transaction_fallback_global_rsv(root,
4324 						   BTRFS_UNLINK_METADATA_UNITS);
4325 }
4326 
btrfs_unlink(struct inode * dir,struct dentry * dentry)4327 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4328 {
4329 	struct btrfs_trans_handle *trans;
4330 	struct inode *inode = d_inode(dentry);
4331 	int ret;
4332 	struct fscrypt_name fname;
4333 
4334 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4335 	if (ret)
4336 		return ret;
4337 
4338 	/* This needs to handle no-key deletions later on */
4339 
4340 	trans = __unlink_start_trans(BTRFS_I(dir));
4341 	if (IS_ERR(trans)) {
4342 		ret = PTR_ERR(trans);
4343 		goto fscrypt_free;
4344 	}
4345 
4346 	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4347 				false);
4348 
4349 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4350 				 &fname.disk_name);
4351 	if (ret)
4352 		goto end_trans;
4353 
4354 	if (inode->i_nlink == 0) {
4355 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4356 		if (ret)
4357 			goto end_trans;
4358 	}
4359 
4360 end_trans:
4361 	btrfs_end_transaction(trans);
4362 	btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4363 fscrypt_free:
4364 	fscrypt_free_filename(&fname);
4365 	return ret;
4366 }
4367 
btrfs_unlink_subvol(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct dentry * dentry)4368 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4369 			       struct btrfs_inode *dir, struct dentry *dentry)
4370 {
4371 	struct btrfs_root *root = dir->root;
4372 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4373 	struct btrfs_path *path;
4374 	struct extent_buffer *leaf;
4375 	struct btrfs_dir_item *di;
4376 	struct btrfs_key key;
4377 	u64 index;
4378 	int ret;
4379 	u64 objectid;
4380 	u64 dir_ino = btrfs_ino(dir);
4381 	struct fscrypt_name fname;
4382 
4383 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4384 	if (ret)
4385 		return ret;
4386 
4387 	/* This needs to handle no-key deletions later on */
4388 
4389 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4390 		objectid = btrfs_root_id(inode->root);
4391 	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4392 		objectid = inode->ref_root_id;
4393 	} else {
4394 		WARN_ON(1);
4395 		fscrypt_free_filename(&fname);
4396 		return -EINVAL;
4397 	}
4398 
4399 	path = btrfs_alloc_path();
4400 	if (!path) {
4401 		ret = -ENOMEM;
4402 		goto out;
4403 	}
4404 
4405 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4406 				   &fname.disk_name, -1);
4407 	if (IS_ERR_OR_NULL(di)) {
4408 		ret = di ? PTR_ERR(di) : -ENOENT;
4409 		goto out;
4410 	}
4411 
4412 	leaf = path->nodes[0];
4413 	btrfs_dir_item_key_to_cpu(leaf, di, &key);
4414 	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4415 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4416 	if (ret) {
4417 		btrfs_abort_transaction(trans, ret);
4418 		goto out;
4419 	}
4420 	btrfs_release_path(path);
4421 
4422 	/*
4423 	 * This is a placeholder inode for a subvolume we didn't have a
4424 	 * reference to at the time of the snapshot creation.  In the meantime
4425 	 * we could have renamed the real subvol link into our snapshot, so
4426 	 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4427 	 * Instead simply lookup the dir_index_item for this entry so we can
4428 	 * remove it.  Otherwise we know we have a ref to the root and we can
4429 	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4430 	 */
4431 	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4432 		di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4433 		if (IS_ERR(di)) {
4434 			ret = PTR_ERR(di);
4435 			btrfs_abort_transaction(trans, ret);
4436 			goto out;
4437 		}
4438 
4439 		leaf = path->nodes[0];
4440 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4441 		index = key.offset;
4442 		btrfs_release_path(path);
4443 	} else {
4444 		ret = btrfs_del_root_ref(trans, objectid,
4445 					 btrfs_root_id(root), dir_ino,
4446 					 &index, &fname.disk_name);
4447 		if (ret) {
4448 			btrfs_abort_transaction(trans, ret);
4449 			goto out;
4450 		}
4451 	}
4452 
4453 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4454 	if (ret) {
4455 		btrfs_abort_transaction(trans, ret);
4456 		goto out;
4457 	}
4458 
4459 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4460 	inode_inc_iversion(&dir->vfs_inode);
4461 	inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4462 	ret = btrfs_update_inode_fallback(trans, dir);
4463 	if (ret)
4464 		btrfs_abort_transaction(trans, ret);
4465 out:
4466 	btrfs_free_path(path);
4467 	fscrypt_free_filename(&fname);
4468 	return ret;
4469 }
4470 
4471 /*
4472  * Helper to check if the subvolume references other subvolumes or if it's
4473  * default.
4474  */
may_destroy_subvol(struct btrfs_root * root)4475 static noinline int may_destroy_subvol(struct btrfs_root *root)
4476 {
4477 	struct btrfs_fs_info *fs_info = root->fs_info;
4478 	BTRFS_PATH_AUTO_FREE(path);
4479 	struct btrfs_dir_item *di;
4480 	struct btrfs_key key;
4481 	struct fscrypt_str name = FSTR_INIT("default", 7);
4482 	u64 dir_id;
4483 	int ret;
4484 
4485 	path = btrfs_alloc_path();
4486 	if (!path)
4487 		return -ENOMEM;
4488 
4489 	/* Make sure this root isn't set as the default subvol */
4490 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4491 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4492 				   dir_id, &name, 0);
4493 	if (di && !IS_ERR(di)) {
4494 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4495 		if (key.objectid == btrfs_root_id(root)) {
4496 			ret = -EPERM;
4497 			btrfs_err(fs_info,
4498 				  "deleting default subvolume %llu is not allowed",
4499 				  key.objectid);
4500 			return ret;
4501 		}
4502 		btrfs_release_path(path);
4503 	}
4504 
4505 	key.objectid = btrfs_root_id(root);
4506 	key.type = BTRFS_ROOT_REF_KEY;
4507 	key.offset = (u64)-1;
4508 
4509 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4510 	if (ret < 0)
4511 		return ret;
4512 	if (ret == 0) {
4513 		/*
4514 		 * Key with offset -1 found, there would have to exist a root
4515 		 * with such id, but this is out of valid range.
4516 		 */
4517 		return -EUCLEAN;
4518 	}
4519 
4520 	ret = 0;
4521 	if (path->slots[0] > 0) {
4522 		path->slots[0]--;
4523 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4524 		if (key.objectid == btrfs_root_id(root) && key.type == BTRFS_ROOT_REF_KEY)
4525 			ret = -ENOTEMPTY;
4526 	}
4527 
4528 	return ret;
4529 }
4530 
4531 /* Delete all dentries for inodes belonging to the root */
btrfs_prune_dentries(struct btrfs_root * root)4532 static void btrfs_prune_dentries(struct btrfs_root *root)
4533 {
4534 	struct btrfs_fs_info *fs_info = root->fs_info;
4535 	struct btrfs_inode *inode;
4536 	u64 min_ino = 0;
4537 
4538 	if (!BTRFS_FS_ERROR(fs_info))
4539 		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4540 
4541 	inode = btrfs_find_first_inode(root, min_ino);
4542 	while (inode) {
4543 		if (atomic_read(&inode->vfs_inode.i_count) > 1)
4544 			d_prune_aliases(&inode->vfs_inode);
4545 
4546 		min_ino = btrfs_ino(inode) + 1;
4547 		/*
4548 		 * btrfs_drop_inode() will have it removed from the inode
4549 		 * cache when its usage count hits zero.
4550 		 */
4551 		iput(&inode->vfs_inode);
4552 		cond_resched();
4553 		inode = btrfs_find_first_inode(root, min_ino);
4554 	}
4555 }
4556 
btrfs_delete_subvolume(struct btrfs_inode * dir,struct dentry * dentry)4557 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4558 {
4559 	struct btrfs_root *root = dir->root;
4560 	struct btrfs_fs_info *fs_info = root->fs_info;
4561 	struct inode *inode = d_inode(dentry);
4562 	struct btrfs_root *dest = BTRFS_I(inode)->root;
4563 	struct btrfs_trans_handle *trans;
4564 	struct btrfs_block_rsv block_rsv;
4565 	u64 root_flags;
4566 	u64 qgroup_reserved = 0;
4567 	int ret;
4568 
4569 	down_write(&fs_info->subvol_sem);
4570 
4571 	/*
4572 	 * Don't allow to delete a subvolume with send in progress. This is
4573 	 * inside the inode lock so the error handling that has to drop the bit
4574 	 * again is not run concurrently.
4575 	 */
4576 	spin_lock(&dest->root_item_lock);
4577 	if (dest->send_in_progress) {
4578 		spin_unlock(&dest->root_item_lock);
4579 		btrfs_warn(fs_info,
4580 			   "attempt to delete subvolume %llu during send",
4581 			   btrfs_root_id(dest));
4582 		ret = -EPERM;
4583 		goto out_up_write;
4584 	}
4585 	if (atomic_read(&dest->nr_swapfiles)) {
4586 		spin_unlock(&dest->root_item_lock);
4587 		btrfs_warn(fs_info,
4588 			   "attempt to delete subvolume %llu with active swapfile",
4589 			   btrfs_root_id(root));
4590 		ret = -EPERM;
4591 		goto out_up_write;
4592 	}
4593 	root_flags = btrfs_root_flags(&dest->root_item);
4594 	btrfs_set_root_flags(&dest->root_item,
4595 			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4596 	spin_unlock(&dest->root_item_lock);
4597 
4598 	ret = may_destroy_subvol(dest);
4599 	if (ret)
4600 		goto out_undead;
4601 
4602 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4603 	/*
4604 	 * One for dir inode,
4605 	 * two for dir entries,
4606 	 * two for root ref/backref.
4607 	 */
4608 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4609 	if (ret)
4610 		goto out_undead;
4611 	qgroup_reserved = block_rsv.qgroup_rsv_reserved;
4612 
4613 	trans = btrfs_start_transaction(root, 0);
4614 	if (IS_ERR(trans)) {
4615 		ret = PTR_ERR(trans);
4616 		goto out_release;
4617 	}
4618 	btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
4619 	qgroup_reserved = 0;
4620 	trans->block_rsv = &block_rsv;
4621 	trans->bytes_reserved = block_rsv.size;
4622 
4623 	btrfs_record_snapshot_destroy(trans, dir);
4624 
4625 	ret = btrfs_unlink_subvol(trans, dir, dentry);
4626 	if (ret) {
4627 		btrfs_abort_transaction(trans, ret);
4628 		goto out_end_trans;
4629 	}
4630 
4631 	ret = btrfs_record_root_in_trans(trans, dest);
4632 	if (ret) {
4633 		btrfs_abort_transaction(trans, ret);
4634 		goto out_end_trans;
4635 	}
4636 
4637 	memset(&dest->root_item.drop_progress, 0,
4638 		sizeof(dest->root_item.drop_progress));
4639 	btrfs_set_root_drop_level(&dest->root_item, 0);
4640 	btrfs_set_root_refs(&dest->root_item, 0);
4641 
4642 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4643 		ret = btrfs_insert_orphan_item(trans,
4644 					fs_info->tree_root,
4645 					btrfs_root_id(dest));
4646 		if (ret) {
4647 			btrfs_abort_transaction(trans, ret);
4648 			goto out_end_trans;
4649 		}
4650 	}
4651 
4652 	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4653 				     BTRFS_UUID_KEY_SUBVOL, btrfs_root_id(dest));
4654 	if (ret && ret != -ENOENT) {
4655 		btrfs_abort_transaction(trans, ret);
4656 		goto out_end_trans;
4657 	}
4658 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4659 		ret = btrfs_uuid_tree_remove(trans,
4660 					  dest->root_item.received_uuid,
4661 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4662 					  btrfs_root_id(dest));
4663 		if (ret && ret != -ENOENT) {
4664 			btrfs_abort_transaction(trans, ret);
4665 			goto out_end_trans;
4666 		}
4667 	}
4668 
4669 	free_anon_bdev(dest->anon_dev);
4670 	dest->anon_dev = 0;
4671 out_end_trans:
4672 	trans->block_rsv = NULL;
4673 	trans->bytes_reserved = 0;
4674 	ret = btrfs_end_transaction(trans);
4675 	inode->i_flags |= S_DEAD;
4676 out_release:
4677 	btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
4678 	if (qgroup_reserved)
4679 		btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
4680 out_undead:
4681 	if (ret) {
4682 		spin_lock(&dest->root_item_lock);
4683 		root_flags = btrfs_root_flags(&dest->root_item);
4684 		btrfs_set_root_flags(&dest->root_item,
4685 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4686 		spin_unlock(&dest->root_item_lock);
4687 	}
4688 out_up_write:
4689 	up_write(&fs_info->subvol_sem);
4690 	if (!ret) {
4691 		d_invalidate(dentry);
4692 		btrfs_prune_dentries(dest);
4693 		ASSERT(dest->send_in_progress == 0);
4694 	}
4695 
4696 	return ret;
4697 }
4698 
btrfs_rmdir(struct inode * vfs_dir,struct dentry * dentry)4699 static int btrfs_rmdir(struct inode *vfs_dir, struct dentry *dentry)
4700 {
4701 	struct btrfs_inode *dir = BTRFS_I(vfs_dir);
4702 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4703 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4704 	int ret = 0;
4705 	struct btrfs_trans_handle *trans;
4706 	struct fscrypt_name fname;
4707 
4708 	if (inode->vfs_inode.i_size > BTRFS_EMPTY_DIR_SIZE)
4709 		return -ENOTEMPTY;
4710 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4711 		if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4712 			btrfs_err(fs_info,
4713 			"extent tree v2 doesn't support snapshot deletion yet");
4714 			return -EOPNOTSUPP;
4715 		}
4716 		return btrfs_delete_subvolume(dir, dentry);
4717 	}
4718 
4719 	ret = fscrypt_setup_filename(vfs_dir, &dentry->d_name, 1, &fname);
4720 	if (ret)
4721 		return ret;
4722 
4723 	/* This needs to handle no-key deletions later on */
4724 
4725 	trans = __unlink_start_trans(dir);
4726 	if (IS_ERR(trans)) {
4727 		ret = PTR_ERR(trans);
4728 		goto out_notrans;
4729 	}
4730 
4731 	/*
4732 	 * Propagate the last_unlink_trans value of the deleted dir to its
4733 	 * parent directory. This is to prevent an unrecoverable log tree in the
4734 	 * case we do something like this:
4735 	 * 1) create dir foo
4736 	 * 2) create snapshot under dir foo
4737 	 * 3) delete the snapshot
4738 	 * 4) rmdir foo
4739 	 * 5) mkdir foo
4740 	 * 6) fsync foo or some file inside foo
4741 	 *
4742 	 * This is because we can't unlink other roots when replaying the dir
4743 	 * deletes for directory foo.
4744 	 */
4745 	if (inode->last_unlink_trans >= trans->transid)
4746 		btrfs_record_snapshot_destroy(trans, dir);
4747 
4748 	if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4749 		ret = btrfs_unlink_subvol(trans, dir, dentry);
4750 		goto out;
4751 	}
4752 
4753 	ret = btrfs_orphan_add(trans, inode);
4754 	if (ret)
4755 		goto out;
4756 
4757 	/* now the directory is empty */
4758 	ret = btrfs_unlink_inode(trans, dir, inode, &fname.disk_name);
4759 	if (!ret)
4760 		btrfs_i_size_write(inode, 0);
4761 out:
4762 	btrfs_end_transaction(trans);
4763 out_notrans:
4764 	btrfs_btree_balance_dirty(fs_info);
4765 	fscrypt_free_filename(&fname);
4766 
4767 	return ret;
4768 }
4769 
is_inside_block(u64 bytenr,u64 blockstart,u32 blocksize)4770 static bool is_inside_block(u64 bytenr, u64 blockstart, u32 blocksize)
4771 {
4772 	ASSERT(IS_ALIGNED(blockstart, blocksize), "blockstart=%llu blocksize=%u",
4773 		blockstart, blocksize);
4774 
4775 	if (blockstart <= bytenr && bytenr <= blockstart + blocksize - 1)
4776 		return true;
4777 	return false;
4778 }
4779 
truncate_block_zero_beyond_eof(struct btrfs_inode * inode,u64 start)4780 static int truncate_block_zero_beyond_eof(struct btrfs_inode *inode, u64 start)
4781 {
4782 	const pgoff_t index = (start >> PAGE_SHIFT);
4783 	struct address_space *mapping = inode->vfs_inode.i_mapping;
4784 	struct folio *folio;
4785 	u64 zero_start;
4786 	u64 zero_end;
4787 	int ret = 0;
4788 
4789 again:
4790 	folio = filemap_lock_folio(mapping, index);
4791 	/* No folio present. */
4792 	if (IS_ERR(folio))
4793 		return 0;
4794 
4795 	if (!folio_test_uptodate(folio)) {
4796 		ret = btrfs_read_folio(NULL, folio);
4797 		folio_lock(folio);
4798 		if (folio->mapping != mapping) {
4799 			folio_unlock(folio);
4800 			folio_put(folio);
4801 			goto again;
4802 		}
4803 		if (!folio_test_uptodate(folio)) {
4804 			ret = -EIO;
4805 			goto out_unlock;
4806 		}
4807 	}
4808 	folio_wait_writeback(folio);
4809 
4810 	/*
4811 	 * We do not need to lock extents nor wait for OE, as it's already
4812 	 * beyond EOF.
4813 	 */
4814 
4815 	zero_start = max_t(u64, folio_pos(folio), start);
4816 	zero_end = folio_end(folio);
4817 	folio_zero_range(folio, zero_start - folio_pos(folio),
4818 			 zero_end - zero_start);
4819 
4820 out_unlock:
4821 	folio_unlock(folio);
4822 	folio_put(folio);
4823 	return ret;
4824 }
4825 
4826 /*
4827  * Handle the truncation of a fs block.
4828  *
4829  * @inode  - inode that we're zeroing
4830  * @offset - the file offset of the block to truncate
4831  *           The value must be inside [@start, @end], and the function will do
4832  *           extra checks if the block that covers @offset needs to be zeroed.
4833  * @start  - the start file offset of the range we want to zero
4834  * @end    - the end (inclusive) file offset of the range we want to zero.
4835  *
4836  * If the range is not block aligned, read out the folio that covers @offset,
4837  * and if needed zero blocks that are inside the folio and covered by [@start, @end).
4838  * If @start or @end + 1 lands inside a block, that block will be marked dirty
4839  * for writeback.
4840  *
4841  * This is utilized by hole punch, zero range, file expansion.
4842  */
btrfs_truncate_block(struct btrfs_inode * inode,u64 offset,u64 start,u64 end)4843 int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 end)
4844 {
4845 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4846 	struct address_space *mapping = inode->vfs_inode.i_mapping;
4847 	struct extent_io_tree *io_tree = &inode->io_tree;
4848 	struct btrfs_ordered_extent *ordered;
4849 	struct extent_state *cached_state = NULL;
4850 	struct extent_changeset *data_reserved = NULL;
4851 	bool only_release_metadata = false;
4852 	u32 blocksize = fs_info->sectorsize;
4853 	pgoff_t index = (offset >> PAGE_SHIFT);
4854 	struct folio *folio;
4855 	gfp_t mask = btrfs_alloc_write_mask(mapping);
4856 	int ret = 0;
4857 	const bool in_head_block = is_inside_block(offset, round_down(start, blocksize),
4858 						   blocksize);
4859 	const bool in_tail_block = is_inside_block(offset, round_down(end, blocksize),
4860 						   blocksize);
4861 	bool need_truncate_head = false;
4862 	bool need_truncate_tail = false;
4863 	u64 zero_start;
4864 	u64 zero_end;
4865 	u64 block_start;
4866 	u64 block_end;
4867 
4868 	/* @offset should be inside the range. */
4869 	ASSERT(start <= offset && offset <= end, "offset=%llu start=%llu end=%llu",
4870 	       offset, start, end);
4871 
4872 	/* The range is aligned at both ends. */
4873 	if (IS_ALIGNED(start, blocksize) && IS_ALIGNED(end + 1, blocksize)) {
4874 		/*
4875 		 * For block size < page size case, we may have polluted blocks
4876 		 * beyond EOF. So we also need to zero them out.
4877 		 */
4878 		if (end == (u64)-1 && blocksize < PAGE_SIZE)
4879 			ret = truncate_block_zero_beyond_eof(inode, start);
4880 		goto out;
4881 	}
4882 
4883 	/*
4884 	 * @offset may not be inside the head nor tail block. In that case we
4885 	 * don't need to do anything.
4886 	 */
4887 	if (!in_head_block && !in_tail_block)
4888 		goto out;
4889 
4890 	/*
4891 	 * Skip the truncatioin if the range in the target block is already aligned.
4892 	 * The seemingly complex check will also handle the same block case.
4893 	 */
4894 	if (in_head_block && !IS_ALIGNED(start, blocksize))
4895 		need_truncate_head = true;
4896 	if (in_tail_block && !IS_ALIGNED(end + 1, blocksize))
4897 		need_truncate_tail = true;
4898 	if (!need_truncate_head && !need_truncate_tail)
4899 		goto out;
4900 
4901 	block_start = round_down(offset, blocksize);
4902 	block_end = block_start + blocksize - 1;
4903 
4904 	ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4905 					  blocksize, false);
4906 	if (ret < 0) {
4907 		size_t write_bytes = blocksize;
4908 
4909 		if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4910 			/* For nocow case, no need to reserve data space. */
4911 			ASSERT(write_bytes == blocksize, "write_bytes=%zu blocksize=%u",
4912 			       write_bytes, blocksize);
4913 			only_release_metadata = true;
4914 		} else {
4915 			goto out;
4916 		}
4917 	}
4918 	ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4919 	if (ret < 0) {
4920 		if (!only_release_metadata)
4921 			btrfs_free_reserved_data_space(inode, data_reserved,
4922 						       block_start, blocksize);
4923 		goto out;
4924 	}
4925 again:
4926 	folio = __filemap_get_folio(mapping, index,
4927 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
4928 	if (IS_ERR(folio)) {
4929 		if (only_release_metadata)
4930 			btrfs_delalloc_release_metadata(inode, blocksize, true);
4931 		else
4932 			btrfs_delalloc_release_space(inode, data_reserved,
4933 						     block_start, blocksize, true);
4934 		btrfs_delalloc_release_extents(inode, blocksize);
4935 		ret = PTR_ERR(folio);
4936 		goto out;
4937 	}
4938 
4939 	if (!folio_test_uptodate(folio)) {
4940 		ret = btrfs_read_folio(NULL, folio);
4941 		folio_lock(folio);
4942 		if (folio->mapping != mapping) {
4943 			folio_unlock(folio);
4944 			folio_put(folio);
4945 			goto again;
4946 		}
4947 		if (!folio_test_uptodate(folio)) {
4948 			ret = -EIO;
4949 			goto out_unlock;
4950 		}
4951 	}
4952 
4953 	/*
4954 	 * We unlock the page after the io is completed and then re-lock it
4955 	 * above.  release_folio() could have come in between that and cleared
4956 	 * folio private, but left the page in the mapping.  Set the page mapped
4957 	 * here to make sure it's properly set for the subpage stuff.
4958 	 */
4959 	ret = set_folio_extent_mapped(folio);
4960 	if (ret < 0)
4961 		goto out_unlock;
4962 
4963 	folio_wait_writeback(folio);
4964 
4965 	btrfs_lock_extent(io_tree, block_start, block_end, &cached_state);
4966 
4967 	ordered = btrfs_lookup_ordered_extent(inode, block_start);
4968 	if (ordered) {
4969 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
4970 		folio_unlock(folio);
4971 		folio_put(folio);
4972 		btrfs_start_ordered_extent(ordered);
4973 		btrfs_put_ordered_extent(ordered);
4974 		goto again;
4975 	}
4976 
4977 	btrfs_clear_extent_bit(&inode->io_tree, block_start, block_end,
4978 			       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4979 			       &cached_state);
4980 
4981 	ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4982 					&cached_state);
4983 	if (ret) {
4984 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
4985 		goto out_unlock;
4986 	}
4987 
4988 	if (end == (u64)-1) {
4989 		/*
4990 		 * We're truncating beyond EOF, the remaining blocks normally are
4991 		 * already holes thus no need to zero again, but it's possible for
4992 		 * fs block size < page size cases to have memory mapped writes
4993 		 * to pollute ranges beyond EOF.
4994 		 *
4995 		 * In that case although such polluted blocks beyond EOF will
4996 		 * not reach disk, it still affects our page caches.
4997 		 */
4998 		zero_start = max_t(u64, folio_pos(folio), start);
4999 		zero_end = min_t(u64, folio_end(folio) - 1, end);
5000 	} else {
5001 		zero_start = max_t(u64, block_start, start);
5002 		zero_end = min_t(u64, block_end, end);
5003 	}
5004 	folio_zero_range(folio, zero_start - folio_pos(folio),
5005 			 zero_end - zero_start + 1);
5006 
5007 	btrfs_folio_clear_checked(fs_info, folio, block_start,
5008 				  block_end + 1 - block_start);
5009 	btrfs_folio_set_dirty(fs_info, folio, block_start,
5010 			      block_end + 1 - block_start);
5011 
5012 	if (only_release_metadata)
5013 		btrfs_set_extent_bit(&inode->io_tree, block_start, block_end,
5014 				     EXTENT_NORESERVE, &cached_state);
5015 
5016 	btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5017 
5018 out_unlock:
5019 	if (ret) {
5020 		if (only_release_metadata)
5021 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5022 		else
5023 			btrfs_delalloc_release_space(inode, data_reserved,
5024 					block_start, blocksize, true);
5025 	}
5026 	btrfs_delalloc_release_extents(inode, blocksize);
5027 	folio_unlock(folio);
5028 	folio_put(folio);
5029 out:
5030 	if (only_release_metadata)
5031 		btrfs_check_nocow_unlock(inode);
5032 	extent_changeset_free(data_reserved);
5033 	return ret;
5034 }
5035 
maybe_insert_hole(struct btrfs_inode * inode,u64 offset,u64 len)5036 static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
5037 {
5038 	struct btrfs_root *root = inode->root;
5039 	struct btrfs_fs_info *fs_info = root->fs_info;
5040 	struct btrfs_trans_handle *trans;
5041 	struct btrfs_drop_extents_args drop_args = { 0 };
5042 	int ret;
5043 
5044 	/*
5045 	 * If NO_HOLES is enabled, we don't need to do anything.
5046 	 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5047 	 * or btrfs_update_inode() will be called, which guarantee that the next
5048 	 * fsync will know this inode was changed and needs to be logged.
5049 	 */
5050 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
5051 		return 0;
5052 
5053 	/*
5054 	 * 1 - for the one we're dropping
5055 	 * 1 - for the one we're adding
5056 	 * 1 - for updating the inode.
5057 	 */
5058 	trans = btrfs_start_transaction(root, 3);
5059 	if (IS_ERR(trans))
5060 		return PTR_ERR(trans);
5061 
5062 	drop_args.start = offset;
5063 	drop_args.end = offset + len;
5064 	drop_args.drop_cache = true;
5065 
5066 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5067 	if (ret) {
5068 		btrfs_abort_transaction(trans, ret);
5069 		btrfs_end_transaction(trans);
5070 		return ret;
5071 	}
5072 
5073 	ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5074 	if (ret) {
5075 		btrfs_abort_transaction(trans, ret);
5076 	} else {
5077 		btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5078 		btrfs_update_inode(trans, inode);
5079 	}
5080 	btrfs_end_transaction(trans);
5081 	return ret;
5082 }
5083 
5084 /*
5085  * This function puts in dummy file extents for the area we're creating a hole
5086  * for.  So if we are truncating this file to a larger size we need to insert
5087  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5088  * the range between oldsize and size
5089  */
btrfs_cont_expand(struct btrfs_inode * inode,loff_t oldsize,loff_t size)5090 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5091 {
5092 	struct btrfs_root *root = inode->root;
5093 	struct btrfs_fs_info *fs_info = root->fs_info;
5094 	struct extent_io_tree *io_tree = &inode->io_tree;
5095 	struct extent_map *em = NULL;
5096 	struct extent_state *cached_state = NULL;
5097 	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5098 	u64 block_end = ALIGN(size, fs_info->sectorsize);
5099 	u64 last_byte;
5100 	u64 cur_offset;
5101 	u64 hole_size;
5102 	int ret = 0;
5103 
5104 	/*
5105 	 * If our size started in the middle of a block we need to zero out the
5106 	 * rest of the block before we expand the i_size, otherwise we could
5107 	 * expose stale data.
5108 	 */
5109 	ret = btrfs_truncate_block(inode, oldsize, oldsize, -1);
5110 	if (ret)
5111 		return ret;
5112 
5113 	if (size <= hole_start)
5114 		return 0;
5115 
5116 	btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5117 					   &cached_state);
5118 	cur_offset = hole_start;
5119 	while (1) {
5120 		em = btrfs_get_extent(inode, NULL, cur_offset, block_end - cur_offset);
5121 		if (IS_ERR(em)) {
5122 			ret = PTR_ERR(em);
5123 			em = NULL;
5124 			break;
5125 		}
5126 		last_byte = min(btrfs_extent_map_end(em), block_end);
5127 		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5128 		hole_size = last_byte - cur_offset;
5129 
5130 		if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
5131 			struct extent_map *hole_em;
5132 
5133 			ret = maybe_insert_hole(inode, cur_offset, hole_size);
5134 			if (ret)
5135 				break;
5136 
5137 			ret = btrfs_inode_set_file_extent_range(inode,
5138 							cur_offset, hole_size);
5139 			if (ret)
5140 				break;
5141 
5142 			hole_em = btrfs_alloc_extent_map();
5143 			if (!hole_em) {
5144 				btrfs_drop_extent_map_range(inode, cur_offset,
5145 						    cur_offset + hole_size - 1,
5146 						    false);
5147 				btrfs_set_inode_full_sync(inode);
5148 				goto next;
5149 			}
5150 			hole_em->start = cur_offset;
5151 			hole_em->len = hole_size;
5152 
5153 			hole_em->disk_bytenr = EXTENT_MAP_HOLE;
5154 			hole_em->disk_num_bytes = 0;
5155 			hole_em->ram_bytes = hole_size;
5156 			hole_em->generation = btrfs_get_fs_generation(fs_info);
5157 
5158 			ret = btrfs_replace_extent_map_range(inode, hole_em, true);
5159 			btrfs_free_extent_map(hole_em);
5160 		} else {
5161 			ret = btrfs_inode_set_file_extent_range(inode,
5162 							cur_offset, hole_size);
5163 			if (ret)
5164 				break;
5165 		}
5166 next:
5167 		btrfs_free_extent_map(em);
5168 		em = NULL;
5169 		cur_offset = last_byte;
5170 		if (cur_offset >= block_end)
5171 			break;
5172 	}
5173 	btrfs_free_extent_map(em);
5174 	btrfs_unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5175 	return ret;
5176 }
5177 
btrfs_setsize(struct inode * inode,struct iattr * attr)5178 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5179 {
5180 	struct btrfs_root *root = BTRFS_I(inode)->root;
5181 	struct btrfs_trans_handle *trans;
5182 	loff_t oldsize = i_size_read(inode);
5183 	loff_t newsize = attr->ia_size;
5184 	int mask = attr->ia_valid;
5185 	int ret;
5186 
5187 	/*
5188 	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5189 	 * special case where we need to update the times despite not having
5190 	 * these flags set.  For all other operations the VFS set these flags
5191 	 * explicitly if it wants a timestamp update.
5192 	 */
5193 	if (newsize != oldsize) {
5194 		inode_inc_iversion(inode);
5195 		if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5196 			inode_set_mtime_to_ts(inode,
5197 					      inode_set_ctime_current(inode));
5198 		}
5199 	}
5200 
5201 	if (newsize > oldsize) {
5202 		/*
5203 		 * Don't do an expanding truncate while snapshotting is ongoing.
5204 		 * This is to ensure the snapshot captures a fully consistent
5205 		 * state of this file - if the snapshot captures this expanding
5206 		 * truncation, it must capture all writes that happened before
5207 		 * this truncation.
5208 		 */
5209 		btrfs_drew_write_lock(&root->snapshot_lock);
5210 		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5211 		if (ret) {
5212 			btrfs_drew_write_unlock(&root->snapshot_lock);
5213 			return ret;
5214 		}
5215 
5216 		trans = btrfs_start_transaction(root, 1);
5217 		if (IS_ERR(trans)) {
5218 			btrfs_drew_write_unlock(&root->snapshot_lock);
5219 			return PTR_ERR(trans);
5220 		}
5221 
5222 		i_size_write(inode, newsize);
5223 		btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5224 		pagecache_isize_extended(inode, oldsize, newsize);
5225 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
5226 		btrfs_drew_write_unlock(&root->snapshot_lock);
5227 		btrfs_end_transaction(trans);
5228 	} else {
5229 		struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
5230 
5231 		if (btrfs_is_zoned(fs_info)) {
5232 			ret = btrfs_wait_ordered_range(BTRFS_I(inode),
5233 					ALIGN(newsize, fs_info->sectorsize),
5234 					(u64)-1);
5235 			if (ret)
5236 				return ret;
5237 		}
5238 
5239 		/*
5240 		 * We're truncating a file that used to have good data down to
5241 		 * zero. Make sure any new writes to the file get on disk
5242 		 * on close.
5243 		 */
5244 		if (newsize == 0)
5245 			set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5246 				&BTRFS_I(inode)->runtime_flags);
5247 
5248 		truncate_setsize(inode, newsize);
5249 
5250 		inode_dio_wait(inode);
5251 
5252 		ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5253 		if (ret && inode->i_nlink) {
5254 			int ret2;
5255 
5256 			/*
5257 			 * Truncate failed, so fix up the in-memory size. We
5258 			 * adjusted disk_i_size down as we removed extents, so
5259 			 * wait for disk_i_size to be stable and then update the
5260 			 * in-memory size to match.
5261 			 */
5262 			ret2 = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
5263 			if (ret2)
5264 				return ret2;
5265 			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5266 		}
5267 	}
5268 
5269 	return ret;
5270 }
5271 
btrfs_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * attr)5272 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5273 			 struct iattr *attr)
5274 {
5275 	struct inode *inode = d_inode(dentry);
5276 	struct btrfs_root *root = BTRFS_I(inode)->root;
5277 	int ret;
5278 
5279 	if (btrfs_root_readonly(root))
5280 		return -EROFS;
5281 
5282 	ret = setattr_prepare(idmap, dentry, attr);
5283 	if (ret)
5284 		return ret;
5285 
5286 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5287 		ret = btrfs_setsize(inode, attr);
5288 		if (ret)
5289 			return ret;
5290 	}
5291 
5292 	if (attr->ia_valid) {
5293 		setattr_copy(idmap, inode, attr);
5294 		inode_inc_iversion(inode);
5295 		ret = btrfs_dirty_inode(BTRFS_I(inode));
5296 
5297 		if (!ret && attr->ia_valid & ATTR_MODE)
5298 			ret = posix_acl_chmod(idmap, dentry, inode->i_mode);
5299 	}
5300 
5301 	return ret;
5302 }
5303 
5304 /*
5305  * While truncating the inode pages during eviction, we get the VFS
5306  * calling btrfs_invalidate_folio() against each folio of the inode. This
5307  * is slow because the calls to btrfs_invalidate_folio() result in a
5308  * huge amount of calls to lock_extent() and clear_extent_bit(),
5309  * which keep merging and splitting extent_state structures over and over,
5310  * wasting lots of time.
5311  *
5312  * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5313  * skip all those expensive operations on a per folio basis and do only
5314  * the ordered io finishing, while we release here the extent_map and
5315  * extent_state structures, without the excessive merging and splitting.
5316  */
evict_inode_truncate_pages(struct inode * inode)5317 static void evict_inode_truncate_pages(struct inode *inode)
5318 {
5319 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5320 	struct rb_node *node;
5321 
5322 	ASSERT(inode->i_state & I_FREEING);
5323 	truncate_inode_pages_final(&inode->i_data);
5324 
5325 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5326 
5327 	/*
5328 	 * Keep looping until we have no more ranges in the io tree.
5329 	 * We can have ongoing bios started by readahead that have
5330 	 * their endio callback (extent_io.c:end_bio_extent_readpage)
5331 	 * still in progress (unlocked the pages in the bio but did not yet
5332 	 * unlocked the ranges in the io tree). Therefore this means some
5333 	 * ranges can still be locked and eviction started because before
5334 	 * submitting those bios, which are executed by a separate task (work
5335 	 * queue kthread), inode references (inode->i_count) were not taken
5336 	 * (which would be dropped in the end io callback of each bio).
5337 	 * Therefore here we effectively end up waiting for those bios and
5338 	 * anyone else holding locked ranges without having bumped the inode's
5339 	 * reference count - if we don't do it, when they access the inode's
5340 	 * io_tree to unlock a range it may be too late, leading to an
5341 	 * use-after-free issue.
5342 	 */
5343 	spin_lock(&io_tree->lock);
5344 	while (!RB_EMPTY_ROOT(&io_tree->state)) {
5345 		struct extent_state *state;
5346 		struct extent_state *cached_state = NULL;
5347 		u64 start;
5348 		u64 end;
5349 		unsigned state_flags;
5350 
5351 		node = rb_first(&io_tree->state);
5352 		state = rb_entry(node, struct extent_state, rb_node);
5353 		start = state->start;
5354 		end = state->end;
5355 		state_flags = state->state;
5356 		spin_unlock(&io_tree->lock);
5357 
5358 		btrfs_lock_extent(io_tree, start, end, &cached_state);
5359 
5360 		/*
5361 		 * If still has DELALLOC flag, the extent didn't reach disk,
5362 		 * and its reserved space won't be freed by delayed_ref.
5363 		 * So we need to free its reserved space here.
5364 		 * (Refer to comment in btrfs_invalidate_folio, case 2)
5365 		 *
5366 		 * Note, end is the bytenr of last byte, so we need + 1 here.
5367 		 */
5368 		if (state_flags & EXTENT_DELALLOC)
5369 			btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5370 					       end - start + 1, NULL);
5371 
5372 		btrfs_clear_extent_bit(io_tree, start, end,
5373 				       EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5374 				       &cached_state);
5375 
5376 		cond_resched();
5377 		spin_lock(&io_tree->lock);
5378 	}
5379 	spin_unlock(&io_tree->lock);
5380 }
5381 
evict_refill_and_join(struct btrfs_root * root,struct btrfs_block_rsv * rsv)5382 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5383 							struct btrfs_block_rsv *rsv)
5384 {
5385 	struct btrfs_fs_info *fs_info = root->fs_info;
5386 	struct btrfs_trans_handle *trans;
5387 	u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5388 	int ret;
5389 
5390 	/*
5391 	 * Eviction should be taking place at some place safe because of our
5392 	 * delayed iputs.  However the normal flushing code will run delayed
5393 	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5394 	 *
5395 	 * We reserve the delayed_refs_extra here again because we can't use
5396 	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5397 	 * above.  We reserve our extra bit here because we generate a ton of
5398 	 * delayed refs activity by truncating.
5399 	 *
5400 	 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5401 	 * if we fail to make this reservation we can re-try without the
5402 	 * delayed_refs_extra so we can make some forward progress.
5403 	 */
5404 	ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5405 				     BTRFS_RESERVE_FLUSH_EVICT);
5406 	if (ret) {
5407 		ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5408 					     BTRFS_RESERVE_FLUSH_EVICT);
5409 		if (ret) {
5410 			btrfs_warn(fs_info,
5411 				   "could not allocate space for delete; will truncate on mount");
5412 			return ERR_PTR(-ENOSPC);
5413 		}
5414 		delayed_refs_extra = 0;
5415 	}
5416 
5417 	trans = btrfs_join_transaction(root);
5418 	if (IS_ERR(trans))
5419 		return trans;
5420 
5421 	if (delayed_refs_extra) {
5422 		trans->block_rsv = &fs_info->trans_block_rsv;
5423 		trans->bytes_reserved = delayed_refs_extra;
5424 		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5425 					delayed_refs_extra, true);
5426 	}
5427 	return trans;
5428 }
5429 
btrfs_evict_inode(struct inode * inode)5430 void btrfs_evict_inode(struct inode *inode)
5431 {
5432 	struct btrfs_fs_info *fs_info;
5433 	struct btrfs_trans_handle *trans;
5434 	struct btrfs_root *root = BTRFS_I(inode)->root;
5435 	struct btrfs_block_rsv rsv;
5436 	int ret;
5437 
5438 	trace_btrfs_inode_evict(inode);
5439 
5440 	if (!root) {
5441 		fsverity_cleanup_inode(inode);
5442 		clear_inode(inode);
5443 		return;
5444 	}
5445 
5446 	fs_info = inode_to_fs_info(inode);
5447 	evict_inode_truncate_pages(inode);
5448 
5449 	if (inode->i_nlink &&
5450 	    ((btrfs_root_refs(&root->root_item) != 0 &&
5451 	      btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID) ||
5452 	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5453 		goto out;
5454 
5455 	if (is_bad_inode(inode))
5456 		goto out;
5457 
5458 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5459 		goto out;
5460 
5461 	if (inode->i_nlink > 0) {
5462 		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5463 		       btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID);
5464 		goto out;
5465 	}
5466 
5467 	/*
5468 	 * This makes sure the inode item in tree is uptodate and the space for
5469 	 * the inode update is released.
5470 	 */
5471 	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5472 	if (ret)
5473 		goto out;
5474 
5475 	/*
5476 	 * This drops any pending insert or delete operations we have for this
5477 	 * inode.  We could have a delayed dir index deletion queued up, but
5478 	 * we're removing the inode completely so that'll be taken care of in
5479 	 * the truncate.
5480 	 */
5481 	btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5482 
5483 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
5484 	rsv.size = btrfs_calc_metadata_size(fs_info, 1);
5485 	rsv.failfast = true;
5486 
5487 	btrfs_i_size_write(BTRFS_I(inode), 0);
5488 
5489 	while (1) {
5490 		struct btrfs_truncate_control control = {
5491 			.inode = BTRFS_I(inode),
5492 			.ino = btrfs_ino(BTRFS_I(inode)),
5493 			.new_size = 0,
5494 			.min_type = 0,
5495 		};
5496 
5497 		trans = evict_refill_and_join(root, &rsv);
5498 		if (IS_ERR(trans))
5499 			goto out_release;
5500 
5501 		trans->block_rsv = &rsv;
5502 
5503 		ret = btrfs_truncate_inode_items(trans, root, &control);
5504 		trans->block_rsv = &fs_info->trans_block_rsv;
5505 		btrfs_end_transaction(trans);
5506 		/*
5507 		 * We have not added new delayed items for our inode after we
5508 		 * have flushed its delayed items, so no need to throttle on
5509 		 * delayed items. However we have modified extent buffers.
5510 		 */
5511 		btrfs_btree_balance_dirty_nodelay(fs_info);
5512 		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5513 			goto out_release;
5514 		else if (!ret)
5515 			break;
5516 	}
5517 
5518 	/*
5519 	 * Errors here aren't a big deal, it just means we leave orphan items in
5520 	 * the tree. They will be cleaned up on the next mount. If the inode
5521 	 * number gets reused, cleanup deletes the orphan item without doing
5522 	 * anything, and unlink reuses the existing orphan item.
5523 	 *
5524 	 * If it turns out that we are dropping too many of these, we might want
5525 	 * to add a mechanism for retrying these after a commit.
5526 	 */
5527 	trans = evict_refill_and_join(root, &rsv);
5528 	if (!IS_ERR(trans)) {
5529 		trans->block_rsv = &rsv;
5530 		btrfs_orphan_del(trans, BTRFS_I(inode));
5531 		trans->block_rsv = &fs_info->trans_block_rsv;
5532 		btrfs_end_transaction(trans);
5533 	}
5534 
5535 out_release:
5536 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
5537 out:
5538 	/*
5539 	 * If we didn't successfully delete, the orphan item will still be in
5540 	 * the tree and we'll retry on the next mount. Again, we might also want
5541 	 * to retry these periodically in the future.
5542 	 */
5543 	btrfs_remove_delayed_node(BTRFS_I(inode));
5544 	fsverity_cleanup_inode(inode);
5545 	clear_inode(inode);
5546 }
5547 
5548 /*
5549  * Return the key found in the dir entry in the location pointer, fill @type
5550  * with BTRFS_FT_*, and return 0.
5551  *
5552  * If no dir entries were found, returns -ENOENT.
5553  * If found a corrupted location in dir entry, returns -EUCLEAN.
5554  */
btrfs_inode_by_name(struct btrfs_inode * dir,struct dentry * dentry,struct btrfs_key * location,u8 * type)5555 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5556 			       struct btrfs_key *location, u8 *type)
5557 {
5558 	struct btrfs_dir_item *di;
5559 	BTRFS_PATH_AUTO_FREE(path);
5560 	struct btrfs_root *root = dir->root;
5561 	int ret = 0;
5562 	struct fscrypt_name fname;
5563 
5564 	path = btrfs_alloc_path();
5565 	if (!path)
5566 		return -ENOMEM;
5567 
5568 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5569 	if (ret < 0)
5570 		return ret;
5571 	/*
5572 	 * fscrypt_setup_filename() should never return a positive value, but
5573 	 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5574 	 */
5575 	ASSERT(ret == 0);
5576 
5577 	/* This needs to handle no-key deletions later on */
5578 
5579 	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5580 				   &fname.disk_name, 0);
5581 	if (IS_ERR_OR_NULL(di)) {
5582 		ret = di ? PTR_ERR(di) : -ENOENT;
5583 		goto out;
5584 	}
5585 
5586 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5587 	if (location->type != BTRFS_INODE_ITEM_KEY &&
5588 	    location->type != BTRFS_ROOT_ITEM_KEY) {
5589 		ret = -EUCLEAN;
5590 		btrfs_warn(root->fs_info,
5591 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5592 			   __func__, fname.disk_name.name, btrfs_ino(dir),
5593 			   location->objectid, location->type, location->offset);
5594 	}
5595 	if (!ret)
5596 		*type = btrfs_dir_ftype(path->nodes[0], di);
5597 out:
5598 	fscrypt_free_filename(&fname);
5599 	return ret;
5600 }
5601 
5602 /*
5603  * when we hit a tree root in a directory, the btrfs part of the inode
5604  * needs to be changed to reflect the root directory of the tree root.  This
5605  * is kind of like crossing a mount point.
5606  */
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)5607 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5608 				    struct btrfs_inode *dir,
5609 				    struct dentry *dentry,
5610 				    struct btrfs_key *location,
5611 				    struct btrfs_root **sub_root)
5612 {
5613 	BTRFS_PATH_AUTO_FREE(path);
5614 	struct btrfs_root *new_root;
5615 	struct btrfs_root_ref *ref;
5616 	struct extent_buffer *leaf;
5617 	struct btrfs_key key;
5618 	int ret;
5619 	int err = 0;
5620 	struct fscrypt_name fname;
5621 
5622 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5623 	if (ret)
5624 		return ret;
5625 
5626 	path = btrfs_alloc_path();
5627 	if (!path) {
5628 		err = -ENOMEM;
5629 		goto out;
5630 	}
5631 
5632 	err = -ENOENT;
5633 	key.objectid = btrfs_root_id(dir->root);
5634 	key.type = BTRFS_ROOT_REF_KEY;
5635 	key.offset = location->objectid;
5636 
5637 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5638 	if (ret) {
5639 		if (ret < 0)
5640 			err = ret;
5641 		goto out;
5642 	}
5643 
5644 	leaf = path->nodes[0];
5645 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5646 	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5647 	    btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5648 		goto out;
5649 
5650 	ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5651 				   (unsigned long)(ref + 1), fname.disk_name.len);
5652 	if (ret)
5653 		goto out;
5654 
5655 	btrfs_release_path(path);
5656 
5657 	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5658 	if (IS_ERR(new_root)) {
5659 		err = PTR_ERR(new_root);
5660 		goto out;
5661 	}
5662 
5663 	*sub_root = new_root;
5664 	location->objectid = btrfs_root_dirid(&new_root->root_item);
5665 	location->type = BTRFS_INODE_ITEM_KEY;
5666 	location->offset = 0;
5667 	err = 0;
5668 out:
5669 	fscrypt_free_filename(&fname);
5670 	return err;
5671 }
5672 
5673 
5674 
btrfs_del_inode_from_root(struct btrfs_inode * inode)5675 static void btrfs_del_inode_from_root(struct btrfs_inode *inode)
5676 {
5677 	struct btrfs_root *root = inode->root;
5678 	struct btrfs_inode *entry;
5679 	bool empty = false;
5680 
5681 	xa_lock(&root->inodes);
5682 	entry = __xa_erase(&root->inodes, btrfs_ino(inode));
5683 	if (entry == inode)
5684 		empty = xa_empty(&root->inodes);
5685 	xa_unlock(&root->inodes);
5686 
5687 	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5688 		xa_lock(&root->inodes);
5689 		empty = xa_empty(&root->inodes);
5690 		xa_unlock(&root->inodes);
5691 		if (empty)
5692 			btrfs_add_dead_root(root);
5693 	}
5694 }
5695 
5696 
btrfs_init_locked_inode(struct inode * inode,void * p)5697 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5698 {
5699 	struct btrfs_iget_args *args = p;
5700 
5701 	btrfs_set_inode_number(BTRFS_I(inode), args->ino);
5702 	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5703 
5704 	if (args->root && args->root == args->root->fs_info->tree_root &&
5705 	    args->ino != BTRFS_BTREE_INODE_OBJECTID)
5706 		set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5707 			&BTRFS_I(inode)->runtime_flags);
5708 	return 0;
5709 }
5710 
btrfs_find_actor(struct inode * inode,void * opaque)5711 static int btrfs_find_actor(struct inode *inode, void *opaque)
5712 {
5713 	struct btrfs_iget_args *args = opaque;
5714 
5715 	return args->ino == btrfs_ino(BTRFS_I(inode)) &&
5716 		args->root == BTRFS_I(inode)->root;
5717 }
5718 
btrfs_iget_locked(u64 ino,struct btrfs_root * root)5719 static struct btrfs_inode *btrfs_iget_locked(u64 ino, struct btrfs_root *root)
5720 {
5721 	struct inode *inode;
5722 	struct btrfs_iget_args args;
5723 	unsigned long hashval = btrfs_inode_hash(ino, root);
5724 
5725 	args.ino = ino;
5726 	args.root = root;
5727 
5728 	inode = iget5_locked_rcu(root->fs_info->sb, hashval, btrfs_find_actor,
5729 			     btrfs_init_locked_inode,
5730 			     (void *)&args);
5731 	if (!inode)
5732 		return NULL;
5733 	return BTRFS_I(inode);
5734 }
5735 
5736 /*
5737  * Get an inode object given its inode number and corresponding root.  Path is
5738  * preallocated to prevent recursing back to iget through allocator.
5739  */
btrfs_iget_path(u64 ino,struct btrfs_root * root,struct btrfs_path * path)5740 struct btrfs_inode *btrfs_iget_path(u64 ino, struct btrfs_root *root,
5741 				    struct btrfs_path *path)
5742 {
5743 	struct btrfs_inode *inode;
5744 	int ret;
5745 
5746 	inode = btrfs_iget_locked(ino, root);
5747 	if (!inode)
5748 		return ERR_PTR(-ENOMEM);
5749 
5750 	if (!(inode->vfs_inode.i_state & I_NEW))
5751 		return inode;
5752 
5753 	ret = btrfs_read_locked_inode(inode, path);
5754 	if (ret)
5755 		return ERR_PTR(ret);
5756 
5757 	unlock_new_inode(&inode->vfs_inode);
5758 	return inode;
5759 }
5760 
5761 /*
5762  * Get an inode object given its inode number and corresponding root.
5763  */
btrfs_iget(u64 ino,struct btrfs_root * root)5764 struct btrfs_inode *btrfs_iget(u64 ino, struct btrfs_root *root)
5765 {
5766 	struct btrfs_inode *inode;
5767 	struct btrfs_path *path;
5768 	int ret;
5769 
5770 	inode = btrfs_iget_locked(ino, root);
5771 	if (!inode)
5772 		return ERR_PTR(-ENOMEM);
5773 
5774 	if (!(inode->vfs_inode.i_state & I_NEW))
5775 		return inode;
5776 
5777 	path = btrfs_alloc_path();
5778 	if (!path) {
5779 		iget_failed(&inode->vfs_inode);
5780 		return ERR_PTR(-ENOMEM);
5781 	}
5782 
5783 	ret = btrfs_read_locked_inode(inode, path);
5784 	btrfs_free_path(path);
5785 	if (ret)
5786 		return ERR_PTR(ret);
5787 
5788 	unlock_new_inode(&inode->vfs_inode);
5789 	return inode;
5790 }
5791 
new_simple_dir(struct inode * dir,struct btrfs_key * key,struct btrfs_root * root)5792 static struct btrfs_inode *new_simple_dir(struct inode *dir,
5793 					  struct btrfs_key *key,
5794 					  struct btrfs_root *root)
5795 {
5796 	struct timespec64 ts;
5797 	struct inode *vfs_inode;
5798 	struct btrfs_inode *inode;
5799 
5800 	vfs_inode = new_inode(dir->i_sb);
5801 	if (!vfs_inode)
5802 		return ERR_PTR(-ENOMEM);
5803 
5804 	inode = BTRFS_I(vfs_inode);
5805 	inode->root = btrfs_grab_root(root);
5806 	inode->ref_root_id = key->objectid;
5807 	set_bit(BTRFS_INODE_ROOT_STUB, &inode->runtime_flags);
5808 	set_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags);
5809 
5810 	btrfs_set_inode_number(inode, BTRFS_EMPTY_SUBVOL_DIR_OBJECTID);
5811 	/*
5812 	 * We only need lookup, the rest is read-only and there's no inode
5813 	 * associated with the dentry
5814 	 */
5815 	vfs_inode->i_op = &simple_dir_inode_operations;
5816 	vfs_inode->i_opflags &= ~IOP_XATTR;
5817 	vfs_inode->i_fop = &simple_dir_operations;
5818 	vfs_inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5819 
5820 	ts = inode_set_ctime_current(vfs_inode);
5821 	inode_set_mtime_to_ts(vfs_inode, ts);
5822 	inode_set_atime_to_ts(vfs_inode, inode_get_atime(dir));
5823 	inode->i_otime_sec = ts.tv_sec;
5824 	inode->i_otime_nsec = ts.tv_nsec;
5825 
5826 	vfs_inode->i_uid = dir->i_uid;
5827 	vfs_inode->i_gid = dir->i_gid;
5828 
5829 	return inode;
5830 }
5831 
5832 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5833 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5834 static_assert(BTRFS_FT_DIR == FT_DIR);
5835 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5836 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5837 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5838 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5839 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5840 
btrfs_inode_type(const struct btrfs_inode * inode)5841 static inline u8 btrfs_inode_type(const struct btrfs_inode *inode)
5842 {
5843 	return fs_umode_to_ftype(inode->vfs_inode.i_mode);
5844 }
5845 
btrfs_lookup_dentry(struct inode * dir,struct dentry * dentry)5846 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5847 {
5848 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
5849 	struct btrfs_inode *inode;
5850 	struct btrfs_root *root = BTRFS_I(dir)->root;
5851 	struct btrfs_root *sub_root = root;
5852 	struct btrfs_key location = { 0 };
5853 	u8 di_type = 0;
5854 	int ret = 0;
5855 
5856 	if (dentry->d_name.len > BTRFS_NAME_LEN)
5857 		return ERR_PTR(-ENAMETOOLONG);
5858 
5859 	ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5860 	if (ret < 0)
5861 		return ERR_PTR(ret);
5862 
5863 	if (location.type == BTRFS_INODE_ITEM_KEY) {
5864 		inode = btrfs_iget(location.objectid, root);
5865 		if (IS_ERR(inode))
5866 			return ERR_CAST(inode);
5867 
5868 		/* Do extra check against inode mode with di_type */
5869 		if (btrfs_inode_type(inode) != di_type) {
5870 			btrfs_crit(fs_info,
5871 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5872 				  inode->vfs_inode.i_mode, btrfs_inode_type(inode),
5873 				  di_type);
5874 			iput(&inode->vfs_inode);
5875 			return ERR_PTR(-EUCLEAN);
5876 		}
5877 		return &inode->vfs_inode;
5878 	}
5879 
5880 	ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5881 				       &location, &sub_root);
5882 	if (ret < 0) {
5883 		if (ret != -ENOENT)
5884 			inode = ERR_PTR(ret);
5885 		else
5886 			inode = new_simple_dir(dir, &location, root);
5887 	} else {
5888 		inode = btrfs_iget(location.objectid, sub_root);
5889 		btrfs_put_root(sub_root);
5890 
5891 		if (IS_ERR(inode))
5892 			return ERR_CAST(inode);
5893 
5894 		down_read(&fs_info->cleanup_work_sem);
5895 		if (!sb_rdonly(inode->vfs_inode.i_sb))
5896 			ret = btrfs_orphan_cleanup(sub_root);
5897 		up_read(&fs_info->cleanup_work_sem);
5898 		if (ret) {
5899 			iput(&inode->vfs_inode);
5900 			inode = ERR_PTR(ret);
5901 		}
5902 	}
5903 
5904 	if (IS_ERR(inode))
5905 		return ERR_CAST(inode);
5906 
5907 	return &inode->vfs_inode;
5908 }
5909 
btrfs_dentry_delete(const struct dentry * dentry)5910 static int btrfs_dentry_delete(const struct dentry *dentry)
5911 {
5912 	struct btrfs_root *root;
5913 	struct inode *inode = d_inode(dentry);
5914 
5915 	if (!inode && !IS_ROOT(dentry))
5916 		inode = d_inode(dentry->d_parent);
5917 
5918 	if (inode) {
5919 		root = BTRFS_I(inode)->root;
5920 		if (btrfs_root_refs(&root->root_item) == 0)
5921 			return 1;
5922 
5923 		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5924 			return 1;
5925 	}
5926 	return 0;
5927 }
5928 
btrfs_lookup(struct inode * dir,struct dentry * dentry,unsigned int flags)5929 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5930 				   unsigned int flags)
5931 {
5932 	struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5933 
5934 	if (inode == ERR_PTR(-ENOENT))
5935 		inode = NULL;
5936 	return d_splice_alias(inode, dentry);
5937 }
5938 
5939 /*
5940  * Find the highest existing sequence number in a directory and then set the
5941  * in-memory index_cnt variable to the first free sequence number.
5942  */
btrfs_set_inode_index_count(struct btrfs_inode * inode)5943 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5944 {
5945 	struct btrfs_root *root = inode->root;
5946 	struct btrfs_key key, found_key;
5947 	BTRFS_PATH_AUTO_FREE(path);
5948 	struct extent_buffer *leaf;
5949 	int ret;
5950 
5951 	key.objectid = btrfs_ino(inode);
5952 	key.type = BTRFS_DIR_INDEX_KEY;
5953 	key.offset = (u64)-1;
5954 
5955 	path = btrfs_alloc_path();
5956 	if (!path)
5957 		return -ENOMEM;
5958 
5959 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5960 	if (ret < 0)
5961 		return ret;
5962 	/* FIXME: we should be able to handle this */
5963 	if (ret == 0)
5964 		return ret;
5965 
5966 	if (path->slots[0] == 0) {
5967 		inode->index_cnt = BTRFS_DIR_START_INDEX;
5968 		return 0;
5969 	}
5970 
5971 	path->slots[0]--;
5972 
5973 	leaf = path->nodes[0];
5974 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5975 
5976 	if (found_key.objectid != btrfs_ino(inode) ||
5977 	    found_key.type != BTRFS_DIR_INDEX_KEY) {
5978 		inode->index_cnt = BTRFS_DIR_START_INDEX;
5979 		return 0;
5980 	}
5981 
5982 	inode->index_cnt = found_key.offset + 1;
5983 
5984 	return 0;
5985 }
5986 
btrfs_get_dir_last_index(struct btrfs_inode * dir,u64 * index)5987 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
5988 {
5989 	int ret = 0;
5990 
5991 	btrfs_inode_lock(dir, 0);
5992 	if (dir->index_cnt == (u64)-1) {
5993 		ret = btrfs_inode_delayed_dir_index_count(dir);
5994 		if (ret) {
5995 			ret = btrfs_set_inode_index_count(dir);
5996 			if (ret)
5997 				goto out;
5998 		}
5999 	}
6000 
6001 	/* index_cnt is the index number of next new entry, so decrement it. */
6002 	*index = dir->index_cnt - 1;
6003 out:
6004 	btrfs_inode_unlock(dir, 0);
6005 
6006 	return ret;
6007 }
6008 
6009 /*
6010  * All this infrastructure exists because dir_emit can fault, and we are holding
6011  * the tree lock when doing readdir.  For now just allocate a buffer and copy
6012  * our information into that, and then dir_emit from the buffer.  This is
6013  * similar to what NFS does, only we don't keep the buffer around in pagecache
6014  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
6015  * copy_to_user_inatomic so we don't have to worry about page faulting under the
6016  * tree lock.
6017  */
btrfs_opendir(struct inode * inode,struct file * file)6018 static int btrfs_opendir(struct inode *inode, struct file *file)
6019 {
6020 	struct btrfs_file_private *private;
6021 	u64 last_index;
6022 	int ret;
6023 
6024 	ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
6025 	if (ret)
6026 		return ret;
6027 
6028 	private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
6029 	if (!private)
6030 		return -ENOMEM;
6031 	private->last_index = last_index;
6032 	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6033 	if (!private->filldir_buf) {
6034 		kfree(private);
6035 		return -ENOMEM;
6036 	}
6037 	file->private_data = private;
6038 	return 0;
6039 }
6040 
btrfs_dir_llseek(struct file * file,loff_t offset,int whence)6041 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
6042 {
6043 	struct btrfs_file_private *private = file->private_data;
6044 	int ret;
6045 
6046 	ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
6047 				       &private->last_index);
6048 	if (ret)
6049 		return ret;
6050 
6051 	return generic_file_llseek(file, offset, whence);
6052 }
6053 
6054 struct dir_entry {
6055 	u64 ino;
6056 	u64 offset;
6057 	unsigned type;
6058 	int name_len;
6059 };
6060 
btrfs_filldir(void * addr,int entries,struct dir_context * ctx)6061 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6062 {
6063 	while (entries--) {
6064 		struct dir_entry *entry = addr;
6065 		char *name = (char *)(entry + 1);
6066 
6067 		ctx->pos = get_unaligned(&entry->offset);
6068 		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6069 					 get_unaligned(&entry->ino),
6070 					 get_unaligned(&entry->type)))
6071 			return 1;
6072 		addr += sizeof(struct dir_entry) +
6073 			get_unaligned(&entry->name_len);
6074 		ctx->pos++;
6075 	}
6076 	return 0;
6077 }
6078 
btrfs_real_readdir(struct file * file,struct dir_context * ctx)6079 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6080 {
6081 	struct inode *inode = file_inode(file);
6082 	struct btrfs_root *root = BTRFS_I(inode)->root;
6083 	struct btrfs_file_private *private = file->private_data;
6084 	struct btrfs_dir_item *di;
6085 	struct btrfs_key key;
6086 	struct btrfs_key found_key;
6087 	BTRFS_PATH_AUTO_FREE(path);
6088 	void *addr;
6089 	LIST_HEAD(ins_list);
6090 	LIST_HEAD(del_list);
6091 	int ret;
6092 	char *name_ptr;
6093 	int name_len;
6094 	int entries = 0;
6095 	int total_len = 0;
6096 	bool put = false;
6097 	struct btrfs_key location;
6098 
6099 	if (!dir_emit_dots(file, ctx))
6100 		return 0;
6101 
6102 	path = btrfs_alloc_path();
6103 	if (!path)
6104 		return -ENOMEM;
6105 
6106 	addr = private->filldir_buf;
6107 	path->reada = READA_FORWARD;
6108 
6109 	put = btrfs_readdir_get_delayed_items(BTRFS_I(inode), private->last_index,
6110 					      &ins_list, &del_list);
6111 
6112 again:
6113 	key.type = BTRFS_DIR_INDEX_KEY;
6114 	key.offset = ctx->pos;
6115 	key.objectid = btrfs_ino(BTRFS_I(inode));
6116 
6117 	btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6118 		struct dir_entry *entry;
6119 		struct extent_buffer *leaf = path->nodes[0];
6120 		u8 ftype;
6121 
6122 		if (found_key.objectid != key.objectid)
6123 			break;
6124 		if (found_key.type != BTRFS_DIR_INDEX_KEY)
6125 			break;
6126 		if (found_key.offset < ctx->pos)
6127 			continue;
6128 		if (found_key.offset > private->last_index)
6129 			break;
6130 		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6131 			continue;
6132 		di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6133 		name_len = btrfs_dir_name_len(leaf, di);
6134 		if ((total_len + sizeof(struct dir_entry) + name_len) >=
6135 		    PAGE_SIZE) {
6136 			btrfs_release_path(path);
6137 			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6138 			if (ret)
6139 				goto nopos;
6140 			addr = private->filldir_buf;
6141 			entries = 0;
6142 			total_len = 0;
6143 			goto again;
6144 		}
6145 
6146 		ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6147 		entry = addr;
6148 		name_ptr = (char *)(entry + 1);
6149 		read_extent_buffer(leaf, name_ptr,
6150 				   (unsigned long)(di + 1), name_len);
6151 		put_unaligned(name_len, &entry->name_len);
6152 		put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6153 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
6154 		put_unaligned(location.objectid, &entry->ino);
6155 		put_unaligned(found_key.offset, &entry->offset);
6156 		entries++;
6157 		addr += sizeof(struct dir_entry) + name_len;
6158 		total_len += sizeof(struct dir_entry) + name_len;
6159 	}
6160 	/* Catch error encountered during iteration */
6161 	if (ret < 0)
6162 		goto err;
6163 
6164 	btrfs_release_path(path);
6165 
6166 	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6167 	if (ret)
6168 		goto nopos;
6169 
6170 	if (btrfs_readdir_delayed_dir_index(ctx, &ins_list))
6171 		goto nopos;
6172 
6173 	/*
6174 	 * Stop new entries from being returned after we return the last
6175 	 * entry.
6176 	 *
6177 	 * New directory entries are assigned a strictly increasing
6178 	 * offset.  This means that new entries created during readdir
6179 	 * are *guaranteed* to be seen in the future by that readdir.
6180 	 * This has broken buggy programs which operate on names as
6181 	 * they're returned by readdir.  Until we reuse freed offsets
6182 	 * we have this hack to stop new entries from being returned
6183 	 * under the assumption that they'll never reach this huge
6184 	 * offset.
6185 	 *
6186 	 * This is being careful not to overflow 32bit loff_t unless the
6187 	 * last entry requires it because doing so has broken 32bit apps
6188 	 * in the past.
6189 	 */
6190 	if (ctx->pos >= INT_MAX)
6191 		ctx->pos = LLONG_MAX;
6192 	else
6193 		ctx->pos = INT_MAX;
6194 nopos:
6195 	ret = 0;
6196 err:
6197 	if (put)
6198 		btrfs_readdir_put_delayed_items(BTRFS_I(inode), &ins_list, &del_list);
6199 	return ret;
6200 }
6201 
6202 /*
6203  * This is somewhat expensive, updating the tree every time the
6204  * inode changes.  But, it is most likely to find the inode in cache.
6205  * FIXME, needs more benchmarking...there are no reasons other than performance
6206  * to keep or drop this code.
6207  */
btrfs_dirty_inode(struct btrfs_inode * inode)6208 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6209 {
6210 	struct btrfs_root *root = inode->root;
6211 	struct btrfs_fs_info *fs_info = root->fs_info;
6212 	struct btrfs_trans_handle *trans;
6213 	int ret;
6214 
6215 	if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6216 		return 0;
6217 
6218 	trans = btrfs_join_transaction(root);
6219 	if (IS_ERR(trans))
6220 		return PTR_ERR(trans);
6221 
6222 	ret = btrfs_update_inode(trans, inode);
6223 	if (ret == -ENOSPC || ret == -EDQUOT) {
6224 		/* whoops, lets try again with the full transaction */
6225 		btrfs_end_transaction(trans);
6226 		trans = btrfs_start_transaction(root, 1);
6227 		if (IS_ERR(trans))
6228 			return PTR_ERR(trans);
6229 
6230 		ret = btrfs_update_inode(trans, inode);
6231 	}
6232 	btrfs_end_transaction(trans);
6233 	if (inode->delayed_node)
6234 		btrfs_balance_delayed_items(fs_info);
6235 
6236 	return ret;
6237 }
6238 
6239 /*
6240  * This is a copy of file_update_time.  We need this so we can return error on
6241  * ENOSPC for updating the inode in the case of file write and mmap writes.
6242  */
btrfs_update_time(struct inode * inode,int flags)6243 static int btrfs_update_time(struct inode *inode, int flags)
6244 {
6245 	struct btrfs_root *root = BTRFS_I(inode)->root;
6246 	bool dirty;
6247 
6248 	if (btrfs_root_readonly(root))
6249 		return -EROFS;
6250 
6251 	dirty = inode_update_timestamps(inode, flags);
6252 	return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
6253 }
6254 
6255 /*
6256  * helper to find a free sequence number in a given directory.  This current
6257  * code is very simple, later versions will do smarter things in the btree
6258  */
btrfs_set_inode_index(struct btrfs_inode * dir,u64 * index)6259 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6260 {
6261 	int ret = 0;
6262 
6263 	if (dir->index_cnt == (u64)-1) {
6264 		ret = btrfs_inode_delayed_dir_index_count(dir);
6265 		if (ret) {
6266 			ret = btrfs_set_inode_index_count(dir);
6267 			if (ret)
6268 				return ret;
6269 		}
6270 	}
6271 
6272 	*index = dir->index_cnt;
6273 	dir->index_cnt++;
6274 
6275 	return ret;
6276 }
6277 
btrfs_insert_inode_locked(struct inode * inode)6278 static int btrfs_insert_inode_locked(struct inode *inode)
6279 {
6280 	struct btrfs_iget_args args;
6281 
6282 	args.ino = btrfs_ino(BTRFS_I(inode));
6283 	args.root = BTRFS_I(inode)->root;
6284 
6285 	return insert_inode_locked4(inode,
6286 		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6287 		   btrfs_find_actor, &args);
6288 }
6289 
btrfs_new_inode_prepare(struct btrfs_new_inode_args * args,unsigned int * trans_num_items)6290 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6291 			    unsigned int *trans_num_items)
6292 {
6293 	struct inode *dir = args->dir;
6294 	struct inode *inode = args->inode;
6295 	int ret;
6296 
6297 	if (!args->orphan) {
6298 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6299 					     &args->fname);
6300 		if (ret)
6301 			return ret;
6302 	}
6303 
6304 	ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6305 	if (ret) {
6306 		fscrypt_free_filename(&args->fname);
6307 		return ret;
6308 	}
6309 
6310 	/* 1 to add inode item */
6311 	*trans_num_items = 1;
6312 	/* 1 to add compression property */
6313 	if (BTRFS_I(dir)->prop_compress)
6314 		(*trans_num_items)++;
6315 	/* 1 to add default ACL xattr */
6316 	if (args->default_acl)
6317 		(*trans_num_items)++;
6318 	/* 1 to add access ACL xattr */
6319 	if (args->acl)
6320 		(*trans_num_items)++;
6321 #ifdef CONFIG_SECURITY
6322 	/* 1 to add LSM xattr */
6323 	if (dir->i_security)
6324 		(*trans_num_items)++;
6325 #endif
6326 	if (args->orphan) {
6327 		/* 1 to add orphan item */
6328 		(*trans_num_items)++;
6329 	} else {
6330 		/*
6331 		 * 1 to add dir item
6332 		 * 1 to add dir index
6333 		 * 1 to update parent inode item
6334 		 *
6335 		 * No need for 1 unit for the inode ref item because it is
6336 		 * inserted in a batch together with the inode item at
6337 		 * btrfs_create_new_inode().
6338 		 */
6339 		*trans_num_items += 3;
6340 	}
6341 	return 0;
6342 }
6343 
btrfs_new_inode_args_destroy(struct btrfs_new_inode_args * args)6344 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6345 {
6346 	posix_acl_release(args->acl);
6347 	posix_acl_release(args->default_acl);
6348 	fscrypt_free_filename(&args->fname);
6349 }
6350 
6351 /*
6352  * Inherit flags from the parent inode.
6353  *
6354  * Currently only the compression flags and the cow flags are inherited.
6355  */
btrfs_inherit_iflags(struct btrfs_inode * inode,struct btrfs_inode * dir)6356 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6357 {
6358 	unsigned int flags;
6359 
6360 	flags = dir->flags;
6361 
6362 	if (flags & BTRFS_INODE_NOCOMPRESS) {
6363 		inode->flags &= ~BTRFS_INODE_COMPRESS;
6364 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
6365 	} else if (flags & BTRFS_INODE_COMPRESS) {
6366 		inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6367 		inode->flags |= BTRFS_INODE_COMPRESS;
6368 	}
6369 
6370 	if (flags & BTRFS_INODE_NODATACOW) {
6371 		inode->flags |= BTRFS_INODE_NODATACOW;
6372 		if (S_ISREG(inode->vfs_inode.i_mode))
6373 			inode->flags |= BTRFS_INODE_NODATASUM;
6374 	}
6375 
6376 	btrfs_sync_inode_flags_to_i_flags(inode);
6377 }
6378 
btrfs_create_new_inode(struct btrfs_trans_handle * trans,struct btrfs_new_inode_args * args)6379 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6380 			   struct btrfs_new_inode_args *args)
6381 {
6382 	struct timespec64 ts;
6383 	struct inode *dir = args->dir;
6384 	struct inode *inode = args->inode;
6385 	const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6386 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6387 	struct btrfs_root *root;
6388 	struct btrfs_inode_item *inode_item;
6389 	struct btrfs_path *path;
6390 	u64 objectid;
6391 	struct btrfs_inode_ref *ref;
6392 	struct btrfs_key key[2];
6393 	u32 sizes[2];
6394 	struct btrfs_item_batch batch;
6395 	unsigned long ptr;
6396 	int ret;
6397 	bool xa_reserved = false;
6398 
6399 	path = btrfs_alloc_path();
6400 	if (!path)
6401 		return -ENOMEM;
6402 
6403 	if (!args->subvol)
6404 		BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6405 	root = BTRFS_I(inode)->root;
6406 
6407 	ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
6408 	if (ret)
6409 		goto out;
6410 
6411 	ret = btrfs_get_free_objectid(root, &objectid);
6412 	if (ret)
6413 		goto out;
6414 	btrfs_set_inode_number(BTRFS_I(inode), objectid);
6415 
6416 	ret = xa_reserve(&root->inodes, objectid, GFP_NOFS);
6417 	if (ret)
6418 		goto out;
6419 	xa_reserved = true;
6420 
6421 	if (args->orphan) {
6422 		/*
6423 		 * O_TMPFILE, set link count to 0, so that after this point, we
6424 		 * fill in an inode item with the correct link count.
6425 		 */
6426 		set_nlink(inode, 0);
6427 	} else {
6428 		trace_btrfs_inode_request(dir);
6429 
6430 		ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6431 		if (ret)
6432 			goto out;
6433 	}
6434 
6435 	if (S_ISDIR(inode->i_mode))
6436 		BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6437 
6438 	BTRFS_I(inode)->generation = trans->transid;
6439 	inode->i_generation = BTRFS_I(inode)->generation;
6440 
6441 	/*
6442 	 * We don't have any capability xattrs set here yet, shortcut any
6443 	 * queries for the xattrs here.  If we add them later via the inode
6444 	 * security init path or any other path this flag will be cleared.
6445 	 */
6446 	set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
6447 
6448 	/*
6449 	 * Subvolumes don't inherit flags from their parent directory.
6450 	 * Originally this was probably by accident, but we probably can't
6451 	 * change it now without compatibility issues.
6452 	 */
6453 	if (!args->subvol)
6454 		btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6455 
6456 	if (S_ISREG(inode->i_mode)) {
6457 		if (btrfs_test_opt(fs_info, NODATASUM))
6458 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6459 		if (btrfs_test_opt(fs_info, NODATACOW))
6460 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6461 				BTRFS_INODE_NODATASUM;
6462 		btrfs_update_inode_mapping_flags(BTRFS_I(inode));
6463 		btrfs_set_inode_mapping_order(BTRFS_I(inode));
6464 	}
6465 
6466 	ret = btrfs_insert_inode_locked(inode);
6467 	if (ret < 0) {
6468 		if (!args->orphan)
6469 			BTRFS_I(dir)->index_cnt--;
6470 		goto out;
6471 	}
6472 
6473 	/*
6474 	 * We could have gotten an inode number from somebody who was fsynced
6475 	 * and then removed in this same transaction, so let's just set full
6476 	 * sync since it will be a full sync anyway and this will blow away the
6477 	 * old info in the log.
6478 	 */
6479 	btrfs_set_inode_full_sync(BTRFS_I(inode));
6480 
6481 	key[0].objectid = objectid;
6482 	key[0].type = BTRFS_INODE_ITEM_KEY;
6483 	key[0].offset = 0;
6484 
6485 	sizes[0] = sizeof(struct btrfs_inode_item);
6486 
6487 	if (!args->orphan) {
6488 		/*
6489 		 * Start new inodes with an inode_ref. This is slightly more
6490 		 * efficient for small numbers of hard links since they will
6491 		 * be packed into one item. Extended refs will kick in if we
6492 		 * add more hard links than can fit in the ref item.
6493 		 */
6494 		key[1].objectid = objectid;
6495 		key[1].type = BTRFS_INODE_REF_KEY;
6496 		if (args->subvol) {
6497 			key[1].offset = objectid;
6498 			sizes[1] = 2 + sizeof(*ref);
6499 		} else {
6500 			key[1].offset = btrfs_ino(BTRFS_I(dir));
6501 			sizes[1] = name->len + sizeof(*ref);
6502 		}
6503 	}
6504 
6505 	batch.keys = &key[0];
6506 	batch.data_sizes = &sizes[0];
6507 	batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6508 	batch.nr = args->orphan ? 1 : 2;
6509 	ret = btrfs_insert_empty_items(trans, root, path, &batch);
6510 	if (ret != 0) {
6511 		btrfs_abort_transaction(trans, ret);
6512 		goto discard;
6513 	}
6514 
6515 	ts = simple_inode_init_ts(inode);
6516 	BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
6517 	BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
6518 
6519 	/*
6520 	 * We're going to fill the inode item now, so at this point the inode
6521 	 * must be fully initialized.
6522 	 */
6523 
6524 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6525 				  struct btrfs_inode_item);
6526 	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6527 			     sizeof(*inode_item));
6528 	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6529 
6530 	if (!args->orphan) {
6531 		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6532 				     struct btrfs_inode_ref);
6533 		ptr = (unsigned long)(ref + 1);
6534 		if (args->subvol) {
6535 			btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6536 			btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6537 			write_extent_buffer(path->nodes[0], "..", ptr, 2);
6538 		} else {
6539 			btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6540 						     name->len);
6541 			btrfs_set_inode_ref_index(path->nodes[0], ref,
6542 						  BTRFS_I(inode)->dir_index);
6543 			write_extent_buffer(path->nodes[0], name->name, ptr,
6544 					    name->len);
6545 		}
6546 	}
6547 
6548 	/*
6549 	 * We don't need the path anymore, plus inheriting properties, adding
6550 	 * ACLs, security xattrs, orphan item or adding the link, will result in
6551 	 * allocating yet another path. So just free our path.
6552 	 */
6553 	btrfs_free_path(path);
6554 	path = NULL;
6555 
6556 	if (args->subvol) {
6557 		struct btrfs_inode *parent;
6558 
6559 		/*
6560 		 * Subvolumes inherit properties from their parent subvolume,
6561 		 * not the directory they were created in.
6562 		 */
6563 		parent = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, BTRFS_I(dir)->root);
6564 		if (IS_ERR(parent)) {
6565 			ret = PTR_ERR(parent);
6566 		} else {
6567 			ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6568 							parent);
6569 			iput(&parent->vfs_inode);
6570 		}
6571 	} else {
6572 		ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6573 						BTRFS_I(dir));
6574 	}
6575 	if (ret) {
6576 		btrfs_err(fs_info,
6577 			  "error inheriting props for ino %llu (root %llu): %d",
6578 			  btrfs_ino(BTRFS_I(inode)), btrfs_root_id(root), ret);
6579 	}
6580 
6581 	/*
6582 	 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6583 	 * probably a bug.
6584 	 */
6585 	if (!args->subvol) {
6586 		ret = btrfs_init_inode_security(trans, args);
6587 		if (ret) {
6588 			btrfs_abort_transaction(trans, ret);
6589 			goto discard;
6590 		}
6591 	}
6592 
6593 	ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
6594 	if (WARN_ON(ret)) {
6595 		/* Shouldn't happen, we used xa_reserve() before. */
6596 		btrfs_abort_transaction(trans, ret);
6597 		goto discard;
6598 	}
6599 
6600 	trace_btrfs_inode_new(inode);
6601 	btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6602 
6603 	btrfs_update_root_times(trans, root);
6604 
6605 	if (args->orphan) {
6606 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6607 		if (ret) {
6608 			btrfs_abort_transaction(trans, ret);
6609 			goto discard;
6610 		}
6611 	} else {
6612 		ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6613 				     0, BTRFS_I(inode)->dir_index);
6614 		if (ret) {
6615 			btrfs_abort_transaction(trans, ret);
6616 			goto discard;
6617 		}
6618 	}
6619 
6620 	return 0;
6621 
6622 discard:
6623 	/*
6624 	 * discard_new_inode() calls iput(), but the caller owns the reference
6625 	 * to the inode.
6626 	 */
6627 	ihold(inode);
6628 	discard_new_inode(inode);
6629 out:
6630 	if (xa_reserved)
6631 		xa_release(&root->inodes, objectid);
6632 
6633 	btrfs_free_path(path);
6634 	return ret;
6635 }
6636 
6637 /*
6638  * utility function to add 'inode' into 'parent_inode' with
6639  * a give name and a given sequence number.
6640  * if 'add_backref' is true, also insert a backref from the
6641  * inode to the parent directory.
6642  */
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)6643 int btrfs_add_link(struct btrfs_trans_handle *trans,
6644 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6645 		   const struct fscrypt_str *name, int add_backref, u64 index)
6646 {
6647 	int ret = 0;
6648 	struct btrfs_key key;
6649 	struct btrfs_root *root = parent_inode->root;
6650 	u64 ino = btrfs_ino(inode);
6651 	u64 parent_ino = btrfs_ino(parent_inode);
6652 
6653 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6654 		memcpy(&key, &inode->root->root_key, sizeof(key));
6655 	} else {
6656 		key.objectid = ino;
6657 		key.type = BTRFS_INODE_ITEM_KEY;
6658 		key.offset = 0;
6659 	}
6660 
6661 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6662 		ret = btrfs_add_root_ref(trans, key.objectid,
6663 					 btrfs_root_id(root), parent_ino,
6664 					 index, name);
6665 	} else if (add_backref) {
6666 		ret = btrfs_insert_inode_ref(trans, root, name,
6667 					     ino, parent_ino, index);
6668 	}
6669 
6670 	/* Nothing to clean up yet */
6671 	if (ret)
6672 		return ret;
6673 
6674 	ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6675 				    btrfs_inode_type(inode), index);
6676 	if (ret == -EEXIST || ret == -EOVERFLOW)
6677 		goto fail_dir_item;
6678 	else if (ret) {
6679 		btrfs_abort_transaction(trans, ret);
6680 		return ret;
6681 	}
6682 
6683 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6684 			   name->len * 2);
6685 	inode_inc_iversion(&parent_inode->vfs_inode);
6686 	/*
6687 	 * If we are replaying a log tree, we do not want to update the mtime
6688 	 * and ctime of the parent directory with the current time, since the
6689 	 * log replay procedure is responsible for setting them to their correct
6690 	 * values (the ones it had when the fsync was done).
6691 	 */
6692 	if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags))
6693 		inode_set_mtime_to_ts(&parent_inode->vfs_inode,
6694 				      inode_set_ctime_current(&parent_inode->vfs_inode));
6695 
6696 	ret = btrfs_update_inode(trans, parent_inode);
6697 	if (ret)
6698 		btrfs_abort_transaction(trans, ret);
6699 	return ret;
6700 
6701 fail_dir_item:
6702 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6703 		u64 local_index;
6704 		int ret2;
6705 
6706 		ret2 = btrfs_del_root_ref(trans, key.objectid, btrfs_root_id(root),
6707 					  parent_ino, &local_index, name);
6708 		if (ret2)
6709 			btrfs_abort_transaction(trans, ret2);
6710 	} else if (add_backref) {
6711 		int ret2;
6712 
6713 		ret2 = btrfs_del_inode_ref(trans, root, name, ino, parent_ino, NULL);
6714 		if (ret2)
6715 			btrfs_abort_transaction(trans, ret2);
6716 	}
6717 
6718 	/* Return the original error code */
6719 	return ret;
6720 }
6721 
btrfs_create_common(struct inode * dir,struct dentry * dentry,struct inode * inode)6722 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6723 			       struct inode *inode)
6724 {
6725 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6726 	struct btrfs_root *root = BTRFS_I(dir)->root;
6727 	struct btrfs_new_inode_args new_inode_args = {
6728 		.dir = dir,
6729 		.dentry = dentry,
6730 		.inode = inode,
6731 	};
6732 	unsigned int trans_num_items;
6733 	struct btrfs_trans_handle *trans;
6734 	int ret;
6735 
6736 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6737 	if (ret)
6738 		goto out_inode;
6739 
6740 	trans = btrfs_start_transaction(root, trans_num_items);
6741 	if (IS_ERR(trans)) {
6742 		ret = PTR_ERR(trans);
6743 		goto out_new_inode_args;
6744 	}
6745 
6746 	ret = btrfs_create_new_inode(trans, &new_inode_args);
6747 	if (!ret)
6748 		d_instantiate_new(dentry, inode);
6749 
6750 	btrfs_end_transaction(trans);
6751 	btrfs_btree_balance_dirty(fs_info);
6752 out_new_inode_args:
6753 	btrfs_new_inode_args_destroy(&new_inode_args);
6754 out_inode:
6755 	if (ret)
6756 		iput(inode);
6757 	return ret;
6758 }
6759 
btrfs_mknod(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,dev_t rdev)6760 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6761 		       struct dentry *dentry, umode_t mode, dev_t rdev)
6762 {
6763 	struct inode *inode;
6764 
6765 	inode = new_inode(dir->i_sb);
6766 	if (!inode)
6767 		return -ENOMEM;
6768 	inode_init_owner(idmap, inode, dir, mode);
6769 	inode->i_op = &btrfs_special_inode_operations;
6770 	init_special_inode(inode, inode->i_mode, rdev);
6771 	return btrfs_create_common(dir, dentry, inode);
6772 }
6773 
btrfs_create(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode,bool excl)6774 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6775 			struct dentry *dentry, umode_t mode, bool excl)
6776 {
6777 	struct inode *inode;
6778 
6779 	inode = new_inode(dir->i_sb);
6780 	if (!inode)
6781 		return -ENOMEM;
6782 	inode_init_owner(idmap, inode, dir, mode);
6783 	inode->i_fop = &btrfs_file_operations;
6784 	inode->i_op = &btrfs_file_inode_operations;
6785 	inode->i_mapping->a_ops = &btrfs_aops;
6786 	return btrfs_create_common(dir, dentry, inode);
6787 }
6788 
btrfs_link(struct dentry * old_dentry,struct inode * dir,struct dentry * dentry)6789 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6790 		      struct dentry *dentry)
6791 {
6792 	struct btrfs_trans_handle *trans = NULL;
6793 	struct btrfs_root *root = BTRFS_I(dir)->root;
6794 	struct inode *inode = d_inode(old_dentry);
6795 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
6796 	struct fscrypt_name fname;
6797 	u64 index;
6798 	int ret;
6799 	int drop_inode = 0;
6800 
6801 	/* do not allow sys_link's with other subvols of the same device */
6802 	if (btrfs_root_id(root) != btrfs_root_id(BTRFS_I(inode)->root))
6803 		return -EXDEV;
6804 
6805 	if (inode->i_nlink >= BTRFS_LINK_MAX)
6806 		return -EMLINK;
6807 
6808 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6809 	if (ret)
6810 		goto fail;
6811 
6812 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
6813 	if (ret)
6814 		goto fail;
6815 
6816 	/*
6817 	 * 2 items for inode and inode ref
6818 	 * 2 items for dir items
6819 	 * 1 item for parent inode
6820 	 * 1 item for orphan item deletion if O_TMPFILE
6821 	 */
6822 	trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6823 	if (IS_ERR(trans)) {
6824 		ret = PTR_ERR(trans);
6825 		trans = NULL;
6826 		goto fail;
6827 	}
6828 
6829 	/* There are several dir indexes for this inode, clear the cache. */
6830 	BTRFS_I(inode)->dir_index = 0ULL;
6831 	inc_nlink(inode);
6832 	inode_inc_iversion(inode);
6833 	inode_set_ctime_current(inode);
6834 	ihold(inode);
6835 	set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6836 
6837 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6838 			     &fname.disk_name, 1, index);
6839 
6840 	if (ret) {
6841 		drop_inode = 1;
6842 	} else {
6843 		struct dentry *parent = dentry->d_parent;
6844 
6845 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
6846 		if (ret)
6847 			goto fail;
6848 		if (inode->i_nlink == 1) {
6849 			/*
6850 			 * If new hard link count is 1, it's a file created
6851 			 * with open(2) O_TMPFILE flag.
6852 			 */
6853 			ret = btrfs_orphan_del(trans, BTRFS_I(inode));
6854 			if (ret)
6855 				goto fail;
6856 		}
6857 		d_instantiate(dentry, inode);
6858 		btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6859 	}
6860 
6861 fail:
6862 	fscrypt_free_filename(&fname);
6863 	if (trans)
6864 		btrfs_end_transaction(trans);
6865 	if (drop_inode) {
6866 		inode_dec_link_count(inode);
6867 		iput(inode);
6868 	}
6869 	btrfs_btree_balance_dirty(fs_info);
6870 	return ret;
6871 }
6872 
btrfs_mkdir(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,umode_t mode)6873 static struct dentry *btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6874 				  struct dentry *dentry, umode_t mode)
6875 {
6876 	struct inode *inode;
6877 
6878 	inode = new_inode(dir->i_sb);
6879 	if (!inode)
6880 		return ERR_PTR(-ENOMEM);
6881 	inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6882 	inode->i_op = &btrfs_dir_inode_operations;
6883 	inode->i_fop = &btrfs_dir_file_operations;
6884 	return ERR_PTR(btrfs_create_common(dir, dentry, inode));
6885 }
6886 
uncompress_inline(struct btrfs_path * path,struct folio * folio,struct btrfs_file_extent_item * item)6887 static noinline int uncompress_inline(struct btrfs_path *path,
6888 				      struct folio *folio,
6889 				      struct btrfs_file_extent_item *item)
6890 {
6891 	int ret;
6892 	struct extent_buffer *leaf = path->nodes[0];
6893 	const u32 blocksize = leaf->fs_info->sectorsize;
6894 	char *tmp;
6895 	size_t max_size;
6896 	unsigned long inline_size;
6897 	unsigned long ptr;
6898 	int compress_type;
6899 
6900 	compress_type = btrfs_file_extent_compression(leaf, item);
6901 	max_size = btrfs_file_extent_ram_bytes(leaf, item);
6902 	inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6903 	tmp = kmalloc(inline_size, GFP_NOFS);
6904 	if (!tmp)
6905 		return -ENOMEM;
6906 	ptr = btrfs_file_extent_inline_start(item);
6907 
6908 	read_extent_buffer(leaf, tmp, ptr, inline_size);
6909 
6910 	max_size = min_t(unsigned long, blocksize, max_size);
6911 	ret = btrfs_decompress(compress_type, tmp, folio, 0, inline_size,
6912 			       max_size);
6913 
6914 	/*
6915 	 * decompression code contains a memset to fill in any space between the end
6916 	 * of the uncompressed data and the end of max_size in case the decompressed
6917 	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6918 	 * the end of an inline extent and the beginning of the next block, so we
6919 	 * cover that region here.
6920 	 */
6921 
6922 	if (max_size < blocksize)
6923 		folio_zero_range(folio, max_size, blocksize - max_size);
6924 	kfree(tmp);
6925 	return ret;
6926 }
6927 
read_inline_extent(struct btrfs_path * path,struct folio * folio)6928 static int read_inline_extent(struct btrfs_path *path, struct folio *folio)
6929 {
6930 	const u32 blocksize = path->nodes[0]->fs_info->sectorsize;
6931 	struct btrfs_file_extent_item *fi;
6932 	void *kaddr;
6933 	size_t copy_size;
6934 
6935 	if (!folio || folio_test_uptodate(folio))
6936 		return 0;
6937 
6938 	ASSERT(folio_pos(folio) == 0);
6939 
6940 	fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6941 			    struct btrfs_file_extent_item);
6942 	if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
6943 		return uncompress_inline(path, folio, fi);
6944 
6945 	copy_size = min_t(u64, blocksize,
6946 			  btrfs_file_extent_ram_bytes(path->nodes[0], fi));
6947 	kaddr = kmap_local_folio(folio, 0);
6948 	read_extent_buffer(path->nodes[0], kaddr,
6949 			   btrfs_file_extent_inline_start(fi), copy_size);
6950 	kunmap_local(kaddr);
6951 	if (copy_size < blocksize)
6952 		folio_zero_range(folio, copy_size, blocksize - copy_size);
6953 	return 0;
6954 }
6955 
6956 /*
6957  * Lookup the first extent overlapping a range in a file.
6958  *
6959  * @inode:	file to search in
6960  * @page:	page to read extent data into if the extent is inline
6961  * @start:	file offset
6962  * @len:	length of range starting at @start
6963  *
6964  * Return the first &struct extent_map which overlaps the given range, reading
6965  * it from the B-tree and caching it if necessary. Note that there may be more
6966  * extents which overlap the given range after the returned extent_map.
6967  *
6968  * If @page is not NULL and the extent is inline, this also reads the extent
6969  * data directly into the page and marks the extent up to date in the io_tree.
6970  *
6971  * Return: ERR_PTR on error, non-NULL extent_map on success.
6972  */
btrfs_get_extent(struct btrfs_inode * inode,struct folio * folio,u64 start,u64 len)6973 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6974 				    struct folio *folio, u64 start, u64 len)
6975 {
6976 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
6977 	int ret = 0;
6978 	u64 extent_start = 0;
6979 	u64 extent_end = 0;
6980 	u64 objectid = btrfs_ino(inode);
6981 	int extent_type = -1;
6982 	struct btrfs_path *path = NULL;
6983 	struct btrfs_root *root = inode->root;
6984 	struct btrfs_file_extent_item *item;
6985 	struct extent_buffer *leaf;
6986 	struct btrfs_key found_key;
6987 	struct extent_map *em = NULL;
6988 	struct extent_map_tree *em_tree = &inode->extent_tree;
6989 
6990 	read_lock(&em_tree->lock);
6991 	em = btrfs_lookup_extent_mapping(em_tree, start, len);
6992 	read_unlock(&em_tree->lock);
6993 
6994 	if (em) {
6995 		if (em->start > start || em->start + em->len <= start)
6996 			btrfs_free_extent_map(em);
6997 		else if (em->disk_bytenr == EXTENT_MAP_INLINE && folio)
6998 			btrfs_free_extent_map(em);
6999 		else
7000 			goto out;
7001 	}
7002 	em = btrfs_alloc_extent_map();
7003 	if (!em) {
7004 		ret = -ENOMEM;
7005 		goto out;
7006 	}
7007 	em->start = EXTENT_MAP_HOLE;
7008 	em->disk_bytenr = EXTENT_MAP_HOLE;
7009 	em->len = (u64)-1;
7010 
7011 	path = btrfs_alloc_path();
7012 	if (!path) {
7013 		ret = -ENOMEM;
7014 		goto out;
7015 	}
7016 
7017 	/* Chances are we'll be called again, so go ahead and do readahead */
7018 	path->reada = READA_FORWARD;
7019 
7020 	/*
7021 	 * The same explanation in load_free_space_cache applies here as well,
7022 	 * we only read when we're loading the free space cache, and at that
7023 	 * point the commit_root has everything we need.
7024 	 */
7025 	if (btrfs_is_free_space_inode(inode)) {
7026 		path->search_commit_root = 1;
7027 		path->skip_locking = 1;
7028 	}
7029 
7030 	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7031 	if (ret < 0) {
7032 		goto out;
7033 	} else if (ret > 0) {
7034 		if (path->slots[0] == 0)
7035 			goto not_found;
7036 		path->slots[0]--;
7037 		ret = 0;
7038 	}
7039 
7040 	leaf = path->nodes[0];
7041 	item = btrfs_item_ptr(leaf, path->slots[0],
7042 			      struct btrfs_file_extent_item);
7043 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7044 	if (found_key.objectid != objectid ||
7045 	    found_key.type != BTRFS_EXTENT_DATA_KEY) {
7046 		/*
7047 		 * If we backup past the first extent we want to move forward
7048 		 * and see if there is an extent in front of us, otherwise we'll
7049 		 * say there is a hole for our whole search range which can
7050 		 * cause problems.
7051 		 */
7052 		extent_end = start;
7053 		goto next;
7054 	}
7055 
7056 	extent_type = btrfs_file_extent_type(leaf, item);
7057 	extent_start = found_key.offset;
7058 	extent_end = btrfs_file_extent_end(path);
7059 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7060 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7061 		/* Only regular file could have regular/prealloc extent */
7062 		if (!S_ISREG(inode->vfs_inode.i_mode)) {
7063 			ret = -EUCLEAN;
7064 			btrfs_crit(fs_info,
7065 		"regular/prealloc extent found for non-regular inode %llu",
7066 				   btrfs_ino(inode));
7067 			goto out;
7068 		}
7069 		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7070 						       extent_start);
7071 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7072 		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7073 						      path->slots[0],
7074 						      extent_start);
7075 	}
7076 next:
7077 	if (start >= extent_end) {
7078 		path->slots[0]++;
7079 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7080 			ret = btrfs_next_leaf(root, path);
7081 			if (ret < 0)
7082 				goto out;
7083 			else if (ret > 0)
7084 				goto not_found;
7085 
7086 			leaf = path->nodes[0];
7087 		}
7088 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7089 		if (found_key.objectid != objectid ||
7090 		    found_key.type != BTRFS_EXTENT_DATA_KEY)
7091 			goto not_found;
7092 		if (start + len <= found_key.offset)
7093 			goto not_found;
7094 		if (start > found_key.offset)
7095 			goto next;
7096 
7097 		/* New extent overlaps with existing one */
7098 		em->start = start;
7099 		em->len = found_key.offset - start;
7100 		em->disk_bytenr = EXTENT_MAP_HOLE;
7101 		goto insert;
7102 	}
7103 
7104 	btrfs_extent_item_to_extent_map(inode, path, item, em);
7105 
7106 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7107 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7108 		goto insert;
7109 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7110 		/*
7111 		 * Inline extent can only exist at file offset 0. This is
7112 		 * ensured by tree-checker and inline extent creation path.
7113 		 * Thus all members representing file offsets should be zero.
7114 		 */
7115 		ASSERT(extent_start == 0);
7116 		ASSERT(em->start == 0);
7117 
7118 		/*
7119 		 * btrfs_extent_item_to_extent_map() should have properly
7120 		 * initialized em members already.
7121 		 *
7122 		 * Other members are not utilized for inline extents.
7123 		 */
7124 		ASSERT(em->disk_bytenr == EXTENT_MAP_INLINE);
7125 		ASSERT(em->len == fs_info->sectorsize);
7126 
7127 		ret = read_inline_extent(path, folio);
7128 		if (ret < 0)
7129 			goto out;
7130 		goto insert;
7131 	}
7132 not_found:
7133 	em->start = start;
7134 	em->len = len;
7135 	em->disk_bytenr = EXTENT_MAP_HOLE;
7136 insert:
7137 	ret = 0;
7138 	btrfs_release_path(path);
7139 	if (em->start > start || btrfs_extent_map_end(em) <= start) {
7140 		btrfs_err(fs_info,
7141 			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
7142 			  em->start, em->len, start, len);
7143 		ret = -EIO;
7144 		goto out;
7145 	}
7146 
7147 	write_lock(&em_tree->lock);
7148 	ret = btrfs_add_extent_mapping(inode, &em, start, len);
7149 	write_unlock(&em_tree->lock);
7150 out:
7151 	btrfs_free_path(path);
7152 
7153 	trace_btrfs_get_extent(root, inode, em);
7154 
7155 	if (ret) {
7156 		btrfs_free_extent_map(em);
7157 		return ERR_PTR(ret);
7158 	}
7159 	return em;
7160 }
7161 
btrfs_extent_readonly(struct btrfs_fs_info * fs_info,u64 bytenr)7162 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7163 {
7164 	struct btrfs_block_group *block_group;
7165 	bool readonly = false;
7166 
7167 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
7168 	if (!block_group || block_group->ro)
7169 		readonly = true;
7170 	if (block_group)
7171 		btrfs_put_block_group(block_group);
7172 	return readonly;
7173 }
7174 
7175 /*
7176  * Check if we can do nocow write into the range [@offset, @offset + @len)
7177  *
7178  * @offset:	File offset
7179  * @len:	The length to write, will be updated to the nocow writeable
7180  *		range
7181  * @orig_start:	(optional) Return the original file offset of the file extent
7182  * @orig_len:	(optional) Return the original on-disk length of the file extent
7183  * @ram_bytes:	(optional) Return the ram_bytes of the file extent
7184  *
7185  * Return:
7186  * >0	and update @len if we can do nocow write
7187  *  0	if we can't do nocow write
7188  * <0	if error happened
7189  *
7190  * NOTE: This only checks the file extents, caller is responsible to wait for
7191  *	 any ordered extents.
7192  */
can_nocow_extent(struct btrfs_inode * inode,u64 offset,u64 * len,struct btrfs_file_extent * file_extent,bool nowait)7193 noinline int can_nocow_extent(struct btrfs_inode *inode, u64 offset, u64 *len,
7194 			      struct btrfs_file_extent *file_extent,
7195 			      bool nowait)
7196 {
7197 	struct btrfs_root *root = inode->root;
7198 	struct btrfs_fs_info *fs_info = root->fs_info;
7199 	struct can_nocow_file_extent_args nocow_args = { 0 };
7200 	BTRFS_PATH_AUTO_FREE(path);
7201 	int ret;
7202 	struct extent_buffer *leaf;
7203 	struct extent_io_tree *io_tree = &inode->io_tree;
7204 	struct btrfs_file_extent_item *fi;
7205 	struct btrfs_key key;
7206 	int found_type;
7207 
7208 	path = btrfs_alloc_path();
7209 	if (!path)
7210 		return -ENOMEM;
7211 	path->nowait = nowait;
7212 
7213 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7214 				       offset, 0);
7215 	if (ret < 0)
7216 		return ret;
7217 
7218 	if (ret == 1) {
7219 		if (path->slots[0] == 0) {
7220 			/* Can't find the item, must COW. */
7221 			return 0;
7222 		}
7223 		path->slots[0]--;
7224 	}
7225 	ret = 0;
7226 	leaf = path->nodes[0];
7227 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7228 	if (key.objectid != btrfs_ino(inode) ||
7229 	    key.type != BTRFS_EXTENT_DATA_KEY) {
7230 		/* Not our file or wrong item type, must COW. */
7231 		return 0;
7232 	}
7233 
7234 	if (key.offset > offset) {
7235 		/* Wrong offset, must COW. */
7236 		return 0;
7237 	}
7238 
7239 	if (btrfs_file_extent_end(path) <= offset)
7240 		return 0;
7241 
7242 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7243 	found_type = btrfs_file_extent_type(leaf, fi);
7244 
7245 	nocow_args.start = offset;
7246 	nocow_args.end = offset + *len - 1;
7247 	nocow_args.free_path = true;
7248 
7249 	ret = can_nocow_file_extent(path, &key, inode, &nocow_args);
7250 	/* can_nocow_file_extent() has freed the path. */
7251 	path = NULL;
7252 
7253 	if (ret != 1) {
7254 		/* Treat errors as not being able to NOCOW. */
7255 		return 0;
7256 	}
7257 
7258 	if (btrfs_extent_readonly(fs_info,
7259 				  nocow_args.file_extent.disk_bytenr +
7260 				  nocow_args.file_extent.offset))
7261 		return 0;
7262 
7263 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
7264 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7265 		u64 range_end;
7266 
7267 		range_end = round_up(offset + nocow_args.file_extent.num_bytes,
7268 				     root->fs_info->sectorsize) - 1;
7269 		ret = btrfs_test_range_bit_exists(io_tree, offset, range_end,
7270 						  EXTENT_DELALLOC);
7271 		if (ret)
7272 			return -EAGAIN;
7273 	}
7274 
7275 	if (file_extent)
7276 		memcpy(file_extent, &nocow_args.file_extent, sizeof(*file_extent));
7277 
7278 	*len = nocow_args.file_extent.num_bytes;
7279 
7280 	return 1;
7281 }
7282 
7283 /* 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)7284 struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
7285 				      const struct btrfs_file_extent *file_extent,
7286 				      int type)
7287 {
7288 	struct extent_map *em;
7289 	int ret;
7290 
7291 	/*
7292 	 * Note the missing NOCOW type.
7293 	 *
7294 	 * For pure NOCOW writes, we should not create an io extent map, but
7295 	 * just reusing the existing one.
7296 	 * Only PREALLOC writes (NOCOW write into preallocated range) can
7297 	 * create an io extent map.
7298 	 */
7299 	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7300 	       type == BTRFS_ORDERED_COMPRESSED ||
7301 	       type == BTRFS_ORDERED_REGULAR);
7302 
7303 	switch (type) {
7304 	case BTRFS_ORDERED_PREALLOC:
7305 		/* We're only referring part of a larger preallocated extent. */
7306 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7307 		break;
7308 	case BTRFS_ORDERED_REGULAR:
7309 		/* COW results a new extent matching our file extent size. */
7310 		ASSERT(file_extent->disk_num_bytes == file_extent->num_bytes);
7311 		ASSERT(file_extent->ram_bytes == file_extent->num_bytes);
7312 
7313 		/* Since it's a new extent, we should not have any offset. */
7314 		ASSERT(file_extent->offset == 0);
7315 		break;
7316 	case BTRFS_ORDERED_COMPRESSED:
7317 		/* Must be compressed. */
7318 		ASSERT(file_extent->compression != BTRFS_COMPRESS_NONE);
7319 
7320 		/*
7321 		 * Encoded write can make us to refer to part of the
7322 		 * uncompressed extent.
7323 		 */
7324 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7325 		break;
7326 	}
7327 
7328 	em = btrfs_alloc_extent_map();
7329 	if (!em)
7330 		return ERR_PTR(-ENOMEM);
7331 
7332 	em->start = start;
7333 	em->len = file_extent->num_bytes;
7334 	em->disk_bytenr = file_extent->disk_bytenr;
7335 	em->disk_num_bytes = file_extent->disk_num_bytes;
7336 	em->ram_bytes = file_extent->ram_bytes;
7337 	em->generation = -1;
7338 	em->offset = file_extent->offset;
7339 	em->flags |= EXTENT_FLAG_PINNED;
7340 	if (type == BTRFS_ORDERED_COMPRESSED)
7341 		btrfs_extent_map_set_compression(em, file_extent->compression);
7342 
7343 	ret = btrfs_replace_extent_map_range(inode, em, true);
7344 	if (ret) {
7345 		btrfs_free_extent_map(em);
7346 		return ERR_PTR(ret);
7347 	}
7348 
7349 	/* em got 2 refs now, callers needs to do btrfs_free_extent_map once. */
7350 	return em;
7351 }
7352 
7353 /*
7354  * For release_folio() and invalidate_folio() we have a race window where
7355  * folio_end_writeback() is called but the subpage spinlock is not yet released.
7356  * If we continue to release/invalidate the page, we could cause use-after-free
7357  * for subpage spinlock.  So this function is to spin and wait for subpage
7358  * spinlock.
7359  */
wait_subpage_spinlock(struct folio * folio)7360 static void wait_subpage_spinlock(struct folio *folio)
7361 {
7362 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
7363 	struct btrfs_folio_state *bfs;
7364 
7365 	if (!btrfs_is_subpage(fs_info, folio))
7366 		return;
7367 
7368 	ASSERT(folio_test_private(folio) && folio_get_private(folio));
7369 	bfs = folio_get_private(folio);
7370 
7371 	/*
7372 	 * This may look insane as we just acquire the spinlock and release it,
7373 	 * without doing anything.  But we just want to make sure no one is
7374 	 * still holding the subpage spinlock.
7375 	 * And since the page is not dirty nor writeback, and we have page
7376 	 * locked, the only possible way to hold a spinlock is from the endio
7377 	 * function to clear page writeback.
7378 	 *
7379 	 * Here we just acquire the spinlock so that all existing callers
7380 	 * should exit and we're safe to release/invalidate the page.
7381 	 */
7382 	spin_lock_irq(&bfs->lock);
7383 	spin_unlock_irq(&bfs->lock);
7384 }
7385 
btrfs_launder_folio(struct folio * folio)7386 static int btrfs_launder_folio(struct folio *folio)
7387 {
7388 	return btrfs_qgroup_free_data(folio_to_inode(folio), NULL, folio_pos(folio),
7389 				      folio_size(folio), NULL);
7390 }
7391 
__btrfs_release_folio(struct folio * folio,gfp_t gfp_flags)7392 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7393 {
7394 	if (try_release_extent_mapping(folio, gfp_flags)) {
7395 		wait_subpage_spinlock(folio);
7396 		clear_folio_extent_mapped(folio);
7397 		return true;
7398 	}
7399 	return false;
7400 }
7401 
btrfs_release_folio(struct folio * folio,gfp_t gfp_flags)7402 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7403 {
7404 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
7405 		return false;
7406 	return __btrfs_release_folio(folio, gfp_flags);
7407 }
7408 
7409 #ifdef CONFIG_MIGRATION
btrfs_migrate_folio(struct address_space * mapping,struct folio * dst,struct folio * src,enum migrate_mode mode)7410 static int btrfs_migrate_folio(struct address_space *mapping,
7411 			     struct folio *dst, struct folio *src,
7412 			     enum migrate_mode mode)
7413 {
7414 	int ret = filemap_migrate_folio(mapping, dst, src, mode);
7415 
7416 	if (ret != MIGRATEPAGE_SUCCESS)
7417 		return ret;
7418 
7419 	if (folio_test_ordered(src)) {
7420 		folio_clear_ordered(src);
7421 		folio_set_ordered(dst);
7422 	}
7423 
7424 	return MIGRATEPAGE_SUCCESS;
7425 }
7426 #else
7427 #define btrfs_migrate_folio NULL
7428 #endif
7429 
btrfs_invalidate_folio(struct folio * folio,size_t offset,size_t length)7430 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7431 				 size_t length)
7432 {
7433 	struct btrfs_inode *inode = folio_to_inode(folio);
7434 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7435 	struct extent_io_tree *tree = &inode->io_tree;
7436 	struct extent_state *cached_state = NULL;
7437 	u64 page_start = folio_pos(folio);
7438 	u64 page_end = page_start + folio_size(folio) - 1;
7439 	u64 cur;
7440 	int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
7441 
7442 	/*
7443 	 * We have folio locked so no new ordered extent can be created on this
7444 	 * page, nor bio can be submitted for this folio.
7445 	 *
7446 	 * But already submitted bio can still be finished on this folio.
7447 	 * Furthermore, endio function won't skip folio which has Ordered
7448 	 * already cleared, so it's possible for endio and
7449 	 * invalidate_folio to do the same ordered extent accounting twice
7450 	 * on one folio.
7451 	 *
7452 	 * So here we wait for any submitted bios to finish, so that we won't
7453 	 * do double ordered extent accounting on the same folio.
7454 	 */
7455 	folio_wait_writeback(folio);
7456 	wait_subpage_spinlock(folio);
7457 
7458 	/*
7459 	 * For subpage case, we have call sites like
7460 	 * btrfs_punch_hole_lock_range() which passes range not aligned to
7461 	 * sectorsize.
7462 	 * If the range doesn't cover the full folio, we don't need to and
7463 	 * shouldn't clear page extent mapped, as folio->private can still
7464 	 * record subpage dirty bits for other part of the range.
7465 	 *
7466 	 * For cases that invalidate the full folio even the range doesn't
7467 	 * cover the full folio, like invalidating the last folio, we're
7468 	 * still safe to wait for ordered extent to finish.
7469 	 */
7470 	if (!(offset == 0 && length == folio_size(folio))) {
7471 		btrfs_release_folio(folio, GFP_NOFS);
7472 		return;
7473 	}
7474 
7475 	if (!inode_evicting)
7476 		btrfs_lock_extent(tree, page_start, page_end, &cached_state);
7477 
7478 	cur = page_start;
7479 	while (cur < page_end) {
7480 		struct btrfs_ordered_extent *ordered;
7481 		u64 range_end;
7482 		u32 range_len;
7483 		u32 extra_flags = 0;
7484 
7485 		ordered = btrfs_lookup_first_ordered_range(inode, cur,
7486 							   page_end + 1 - cur);
7487 		if (!ordered) {
7488 			range_end = page_end;
7489 			/*
7490 			 * No ordered extent covering this range, we are safe
7491 			 * to delete all extent states in the range.
7492 			 */
7493 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7494 			goto next;
7495 		}
7496 		if (ordered->file_offset > cur) {
7497 			/*
7498 			 * There is a range between [cur, oe->file_offset) not
7499 			 * covered by any ordered extent.
7500 			 * We are safe to delete all extent states, and handle
7501 			 * the ordered extent in the next iteration.
7502 			 */
7503 			range_end = ordered->file_offset - 1;
7504 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7505 			goto next;
7506 		}
7507 
7508 		range_end = min(ordered->file_offset + ordered->num_bytes - 1,
7509 				page_end);
7510 		ASSERT(range_end + 1 - cur < U32_MAX);
7511 		range_len = range_end + 1 - cur;
7512 		if (!btrfs_folio_test_ordered(fs_info, folio, cur, range_len)) {
7513 			/*
7514 			 * If Ordered is cleared, it means endio has
7515 			 * already been executed for the range.
7516 			 * We can't delete the extent states as
7517 			 * btrfs_finish_ordered_io() may still use some of them.
7518 			 */
7519 			goto next;
7520 		}
7521 		btrfs_folio_clear_ordered(fs_info, folio, cur, range_len);
7522 
7523 		/*
7524 		 * IO on this page will never be started, so we need to account
7525 		 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
7526 		 * here, must leave that up for the ordered extent completion.
7527 		 *
7528 		 * This will also unlock the range for incoming
7529 		 * btrfs_finish_ordered_io().
7530 		 */
7531 		if (!inode_evicting)
7532 			btrfs_clear_extent_bit(tree, cur, range_end,
7533 					       EXTENT_DELALLOC |
7534 					       EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7535 					       EXTENT_DEFRAG, &cached_state);
7536 
7537 		spin_lock_irq(&inode->ordered_tree_lock);
7538 		set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7539 		ordered->truncated_len = min(ordered->truncated_len,
7540 					     cur - ordered->file_offset);
7541 		spin_unlock_irq(&inode->ordered_tree_lock);
7542 
7543 		/*
7544 		 * If the ordered extent has finished, we're safe to delete all
7545 		 * the extent states of the range, otherwise
7546 		 * btrfs_finish_ordered_io() will get executed by endio for
7547 		 * other pages, so we can't delete extent states.
7548 		 */
7549 		if (btrfs_dec_test_ordered_pending(inode, &ordered,
7550 						   cur, range_end + 1 - cur)) {
7551 			btrfs_finish_ordered_io(ordered);
7552 			/*
7553 			 * The ordered extent has finished, now we're again
7554 			 * safe to delete all extent states of the range.
7555 			 */
7556 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7557 		}
7558 next:
7559 		if (ordered)
7560 			btrfs_put_ordered_extent(ordered);
7561 		/*
7562 		 * Qgroup reserved space handler
7563 		 * Sector(s) here will be either:
7564 		 *
7565 		 * 1) Already written to disk or bio already finished
7566 		 *    Then its QGROUP_RESERVED bit in io_tree is already cleared.
7567 		 *    Qgroup will be handled by its qgroup_record then.
7568 		 *    btrfs_qgroup_free_data() call will do nothing here.
7569 		 *
7570 		 * 2) Not written to disk yet
7571 		 *    Then btrfs_qgroup_free_data() call will clear the
7572 		 *    QGROUP_RESERVED bit of its io_tree, and free the qgroup
7573 		 *    reserved data space.
7574 		 *    Since the IO will never happen for this page.
7575 		 */
7576 		btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
7577 		if (!inode_evicting)
7578 			btrfs_clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
7579 					       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7580 					       EXTENT_DEFRAG | extra_flags,
7581 					       &cached_state);
7582 		cur = range_end + 1;
7583 	}
7584 	/*
7585 	 * We have iterated through all ordered extents of the page, the page
7586 	 * should not have Ordered anymore, or the above iteration
7587 	 * did something wrong.
7588 	 */
7589 	ASSERT(!folio_test_ordered(folio));
7590 	btrfs_folio_clear_checked(fs_info, folio, folio_pos(folio), folio_size(folio));
7591 	if (!inode_evicting)
7592 		__btrfs_release_folio(folio, GFP_NOFS);
7593 	clear_folio_extent_mapped(folio);
7594 }
7595 
btrfs_truncate(struct btrfs_inode * inode,bool skip_writeback)7596 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
7597 {
7598 	struct btrfs_truncate_control control = {
7599 		.inode = inode,
7600 		.ino = btrfs_ino(inode),
7601 		.min_type = BTRFS_EXTENT_DATA_KEY,
7602 		.clear_extent_range = true,
7603 	};
7604 	struct btrfs_root *root = inode->root;
7605 	struct btrfs_fs_info *fs_info = root->fs_info;
7606 	struct btrfs_block_rsv rsv;
7607 	int ret;
7608 	struct btrfs_trans_handle *trans;
7609 	u64 mask = fs_info->sectorsize - 1;
7610 	const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
7611 
7612 	if (!skip_writeback) {
7613 		ret = btrfs_wait_ordered_range(inode,
7614 					       inode->vfs_inode.i_size & (~mask),
7615 					       (u64)-1);
7616 		if (ret)
7617 			return ret;
7618 	}
7619 
7620 	/*
7621 	 * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
7622 	 * things going on here:
7623 	 *
7624 	 * 1) We need to reserve space to update our inode.
7625 	 *
7626 	 * 2) We need to have something to cache all the space that is going to
7627 	 * be free'd up by the truncate operation, but also have some slack
7628 	 * space reserved in case it uses space during the truncate (thank you
7629 	 * very much snapshotting).
7630 	 *
7631 	 * And we need these to be separate.  The fact is we can use a lot of
7632 	 * space doing the truncate, and we have no earthly idea how much space
7633 	 * we will use, so we need the truncate reservation to be separate so it
7634 	 * doesn't end up using space reserved for updating the inode.  We also
7635 	 * need to be able to stop the transaction and start a new one, which
7636 	 * means we need to be able to update the inode several times, and we
7637 	 * have no idea of knowing how many times that will be, so we can't just
7638 	 * reserve 1 item for the entirety of the operation, so that has to be
7639 	 * done separately as well.
7640 	 *
7641 	 * So that leaves us with
7642 	 *
7643 	 * 1) rsv - for the truncate reservation, which we will steal from the
7644 	 * transaction reservation.
7645 	 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
7646 	 * updating the inode.
7647 	 */
7648 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
7649 	rsv.size = min_size;
7650 	rsv.failfast = true;
7651 
7652 	/*
7653 	 * 1 for the truncate slack space
7654 	 * 1 for updating the inode.
7655 	 */
7656 	trans = btrfs_start_transaction(root, 2);
7657 	if (IS_ERR(trans)) {
7658 		ret = PTR_ERR(trans);
7659 		goto out;
7660 	}
7661 
7662 	/* Migrate the slack space for the truncate to our reserve */
7663 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, &rsv,
7664 				      min_size, false);
7665 	/*
7666 	 * We have reserved 2 metadata units when we started the transaction and
7667 	 * min_size matches 1 unit, so this should never fail, but if it does,
7668 	 * it's not critical we just fail truncation.
7669 	 */
7670 	if (WARN_ON(ret)) {
7671 		btrfs_end_transaction(trans);
7672 		goto out;
7673 	}
7674 
7675 	trans->block_rsv = &rsv;
7676 
7677 	while (1) {
7678 		struct extent_state *cached_state = NULL;
7679 		const u64 new_size = inode->vfs_inode.i_size;
7680 		const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
7681 
7682 		control.new_size = new_size;
7683 		btrfs_lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7684 		/*
7685 		 * We want to drop from the next block forward in case this new
7686 		 * size is not block aligned since we will be keeping the last
7687 		 * block of the extent just the way it is.
7688 		 */
7689 		btrfs_drop_extent_map_range(inode,
7690 					    ALIGN(new_size, fs_info->sectorsize),
7691 					    (u64)-1, false);
7692 
7693 		ret = btrfs_truncate_inode_items(trans, root, &control);
7694 
7695 		inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
7696 		btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
7697 
7698 		btrfs_unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7699 
7700 		trans->block_rsv = &fs_info->trans_block_rsv;
7701 		if (ret != -ENOSPC && ret != -EAGAIN)
7702 			break;
7703 
7704 		ret = btrfs_update_inode(trans, inode);
7705 		if (ret)
7706 			break;
7707 
7708 		btrfs_end_transaction(trans);
7709 		btrfs_btree_balance_dirty(fs_info);
7710 
7711 		trans = btrfs_start_transaction(root, 2);
7712 		if (IS_ERR(trans)) {
7713 			ret = PTR_ERR(trans);
7714 			trans = NULL;
7715 			break;
7716 		}
7717 
7718 		btrfs_block_rsv_release(fs_info, &rsv, -1, NULL);
7719 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
7720 					      &rsv, min_size, false);
7721 		/*
7722 		 * We have reserved 2 metadata units when we started the
7723 		 * transaction and min_size matches 1 unit, so this should never
7724 		 * fail, but if it does, it's not critical we just fail truncation.
7725 		 */
7726 		if (WARN_ON(ret))
7727 			break;
7728 
7729 		trans->block_rsv = &rsv;
7730 	}
7731 
7732 	/*
7733 	 * We can't call btrfs_truncate_block inside a trans handle as we could
7734 	 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
7735 	 * know we've truncated everything except the last little bit, and can
7736 	 * do btrfs_truncate_block and then update the disk_i_size.
7737 	 */
7738 	if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
7739 		btrfs_end_transaction(trans);
7740 		btrfs_btree_balance_dirty(fs_info);
7741 
7742 		ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size,
7743 					   inode->vfs_inode.i_size, (u64)-1);
7744 		if (ret)
7745 			goto out;
7746 		trans = btrfs_start_transaction(root, 1);
7747 		if (IS_ERR(trans)) {
7748 			ret = PTR_ERR(trans);
7749 			goto out;
7750 		}
7751 		btrfs_inode_safe_disk_i_size_write(inode, 0);
7752 	}
7753 
7754 	if (trans) {
7755 		int ret2;
7756 
7757 		trans->block_rsv = &fs_info->trans_block_rsv;
7758 		ret2 = btrfs_update_inode(trans, inode);
7759 		if (ret2 && !ret)
7760 			ret = ret2;
7761 
7762 		ret2 = btrfs_end_transaction(trans);
7763 		if (ret2 && !ret)
7764 			ret = ret2;
7765 		btrfs_btree_balance_dirty(fs_info);
7766 	}
7767 out:
7768 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
7769 	/*
7770 	 * So if we truncate and then write and fsync we normally would just
7771 	 * write the extents that changed, which is a problem if we need to
7772 	 * first truncate that entire inode.  So set this flag so we write out
7773 	 * all of the extents in the inode to the sync log so we're completely
7774 	 * safe.
7775 	 *
7776 	 * If no extents were dropped or trimmed we don't need to force the next
7777 	 * fsync to truncate all the inode's items from the log and re-log them
7778 	 * all. This means the truncate operation did not change the file size,
7779 	 * or changed it to a smaller size but there was only an implicit hole
7780 	 * between the old i_size and the new i_size, and there were no prealloc
7781 	 * extents beyond i_size to drop.
7782 	 */
7783 	if (control.extents_found > 0)
7784 		btrfs_set_inode_full_sync(inode);
7785 
7786 	return ret;
7787 }
7788 
btrfs_new_subvol_inode(struct mnt_idmap * idmap,struct inode * dir)7789 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
7790 				     struct inode *dir)
7791 {
7792 	struct inode *inode;
7793 
7794 	inode = new_inode(dir->i_sb);
7795 	if (inode) {
7796 		/*
7797 		 * Subvolumes don't inherit the sgid bit or the parent's gid if
7798 		 * the parent's sgid bit is set. This is probably a bug.
7799 		 */
7800 		inode_init_owner(idmap, inode, NULL,
7801 				 S_IFDIR | (~current_umask() & S_IRWXUGO));
7802 		inode->i_op = &btrfs_dir_inode_operations;
7803 		inode->i_fop = &btrfs_dir_file_operations;
7804 	}
7805 	return inode;
7806 }
7807 
btrfs_alloc_inode(struct super_block * sb)7808 struct inode *btrfs_alloc_inode(struct super_block *sb)
7809 {
7810 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
7811 	struct btrfs_inode *ei;
7812 	struct inode *inode;
7813 
7814 	ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
7815 	if (!ei)
7816 		return NULL;
7817 
7818 	ei->root = NULL;
7819 	ei->generation = 0;
7820 	ei->last_trans = 0;
7821 	ei->last_sub_trans = 0;
7822 	ei->logged_trans = 0;
7823 	ei->delalloc_bytes = 0;
7824 	ei->new_delalloc_bytes = 0;
7825 	ei->defrag_bytes = 0;
7826 	ei->disk_i_size = 0;
7827 	ei->flags = 0;
7828 	ei->ro_flags = 0;
7829 	/*
7830 	 * ->index_cnt will be properly initialized later when creating a new
7831 	 * inode (btrfs_create_new_inode()) or when reading an existing inode
7832 	 * from disk (btrfs_read_locked_inode()).
7833 	 */
7834 	ei->csum_bytes = 0;
7835 	ei->dir_index = 0;
7836 	ei->last_unlink_trans = 0;
7837 	ei->last_reflink_trans = 0;
7838 	ei->last_log_commit = 0;
7839 
7840 	spin_lock_init(&ei->lock);
7841 	ei->outstanding_extents = 0;
7842 	if (sb->s_magic != BTRFS_TEST_MAGIC)
7843 		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
7844 					      BTRFS_BLOCK_RSV_DELALLOC);
7845 	ei->runtime_flags = 0;
7846 	ei->prop_compress = BTRFS_COMPRESS_NONE;
7847 	ei->defrag_compress = BTRFS_COMPRESS_NONE;
7848 
7849 	ei->delayed_node = NULL;
7850 
7851 	ei->i_otime_sec = 0;
7852 	ei->i_otime_nsec = 0;
7853 
7854 	inode = &ei->vfs_inode;
7855 	btrfs_extent_map_tree_init(&ei->extent_tree);
7856 
7857 	/* This io tree sets the valid inode. */
7858 	btrfs_extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
7859 	ei->io_tree.inode = ei;
7860 
7861 	ei->file_extent_tree = NULL;
7862 
7863 	mutex_init(&ei->log_mutex);
7864 	spin_lock_init(&ei->ordered_tree_lock);
7865 	ei->ordered_tree = RB_ROOT;
7866 	ei->ordered_tree_last = NULL;
7867 	INIT_LIST_HEAD(&ei->delalloc_inodes);
7868 	INIT_LIST_HEAD(&ei->delayed_iput);
7869 	init_rwsem(&ei->i_mmap_lock);
7870 
7871 	return inode;
7872 }
7873 
7874 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
btrfs_test_destroy_inode(struct inode * inode)7875 void btrfs_test_destroy_inode(struct inode *inode)
7876 {
7877 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
7878 	kfree(BTRFS_I(inode)->file_extent_tree);
7879 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7880 }
7881 #endif
7882 
btrfs_free_inode(struct inode * inode)7883 void btrfs_free_inode(struct inode *inode)
7884 {
7885 	kfree(BTRFS_I(inode)->file_extent_tree);
7886 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7887 }
7888 
btrfs_destroy_inode(struct inode * vfs_inode)7889 void btrfs_destroy_inode(struct inode *vfs_inode)
7890 {
7891 	struct btrfs_ordered_extent *ordered;
7892 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
7893 	struct btrfs_root *root = inode->root;
7894 	bool freespace_inode;
7895 
7896 	WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
7897 	WARN_ON(vfs_inode->i_data.nrpages);
7898 	WARN_ON(inode->block_rsv.reserved);
7899 	WARN_ON(inode->block_rsv.size);
7900 	WARN_ON(inode->outstanding_extents);
7901 	if (!S_ISDIR(vfs_inode->i_mode)) {
7902 		WARN_ON(inode->delalloc_bytes);
7903 		WARN_ON(inode->new_delalloc_bytes);
7904 		WARN_ON(inode->csum_bytes);
7905 	}
7906 	if (!root || !btrfs_is_data_reloc_root(root))
7907 		WARN_ON(inode->defrag_bytes);
7908 
7909 	/*
7910 	 * This can happen where we create an inode, but somebody else also
7911 	 * created the same inode and we need to destroy the one we already
7912 	 * created.
7913 	 */
7914 	if (!root)
7915 		return;
7916 
7917 	/*
7918 	 * If this is a free space inode do not take the ordered extents lockdep
7919 	 * map.
7920 	 */
7921 	freespace_inode = btrfs_is_free_space_inode(inode);
7922 
7923 	while (1) {
7924 		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7925 		if (!ordered)
7926 			break;
7927 		else {
7928 			btrfs_err(root->fs_info,
7929 				  "found ordered extent %llu %llu on inode cleanup",
7930 				  ordered->file_offset, ordered->num_bytes);
7931 
7932 			if (!freespace_inode)
7933 				btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
7934 
7935 			btrfs_remove_ordered_extent(inode, ordered);
7936 			btrfs_put_ordered_extent(ordered);
7937 			btrfs_put_ordered_extent(ordered);
7938 		}
7939 	}
7940 	btrfs_qgroup_check_reserved_leak(inode);
7941 	btrfs_del_inode_from_root(inode);
7942 	btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
7943 	btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
7944 	btrfs_put_root(inode->root);
7945 }
7946 
btrfs_drop_inode(struct inode * inode)7947 int btrfs_drop_inode(struct inode *inode)
7948 {
7949 	struct btrfs_root *root = BTRFS_I(inode)->root;
7950 
7951 	if (root == NULL)
7952 		return 1;
7953 
7954 	/* the snap/subvol tree is on deleting */
7955 	if (btrfs_root_refs(&root->root_item) == 0)
7956 		return 1;
7957 	else
7958 		return generic_drop_inode(inode);
7959 }
7960 
init_once(void * foo)7961 static void init_once(void *foo)
7962 {
7963 	struct btrfs_inode *ei = foo;
7964 
7965 	inode_init_once(&ei->vfs_inode);
7966 }
7967 
btrfs_destroy_cachep(void)7968 void __cold btrfs_destroy_cachep(void)
7969 {
7970 	/*
7971 	 * Make sure all delayed rcu free inodes are flushed before we
7972 	 * destroy cache.
7973 	 */
7974 	rcu_barrier();
7975 	kmem_cache_destroy(btrfs_inode_cachep);
7976 }
7977 
btrfs_init_cachep(void)7978 int __init btrfs_init_cachep(void)
7979 {
7980 	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7981 			sizeof(struct btrfs_inode), 0,
7982 			SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
7983 			init_once);
7984 	if (!btrfs_inode_cachep)
7985 		return -ENOMEM;
7986 
7987 	return 0;
7988 }
7989 
btrfs_getattr(struct mnt_idmap * idmap,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int flags)7990 static int btrfs_getattr(struct mnt_idmap *idmap,
7991 			 const struct path *path, struct kstat *stat,
7992 			 u32 request_mask, unsigned int flags)
7993 {
7994 	u64 delalloc_bytes;
7995 	u64 inode_bytes;
7996 	struct inode *inode = d_inode(path->dentry);
7997 	u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
7998 	u32 bi_flags = BTRFS_I(inode)->flags;
7999 	u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8000 
8001 	stat->result_mask |= STATX_BTIME;
8002 	stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
8003 	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
8004 	if (bi_flags & BTRFS_INODE_APPEND)
8005 		stat->attributes |= STATX_ATTR_APPEND;
8006 	if (bi_flags & BTRFS_INODE_COMPRESS)
8007 		stat->attributes |= STATX_ATTR_COMPRESSED;
8008 	if (bi_flags & BTRFS_INODE_IMMUTABLE)
8009 		stat->attributes |= STATX_ATTR_IMMUTABLE;
8010 	if (bi_flags & BTRFS_INODE_NODUMP)
8011 		stat->attributes |= STATX_ATTR_NODUMP;
8012 	if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8013 		stat->attributes |= STATX_ATTR_VERITY;
8014 
8015 	stat->attributes_mask |= (STATX_ATTR_APPEND |
8016 				  STATX_ATTR_COMPRESSED |
8017 				  STATX_ATTR_IMMUTABLE |
8018 				  STATX_ATTR_NODUMP);
8019 
8020 	generic_fillattr(idmap, request_mask, inode, stat);
8021 	stat->dev = BTRFS_I(inode)->root->anon_dev;
8022 
8023 	stat->subvol = btrfs_root_id(BTRFS_I(inode)->root);
8024 	stat->result_mask |= STATX_SUBVOL;
8025 
8026 	spin_lock(&BTRFS_I(inode)->lock);
8027 	delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8028 	inode_bytes = inode_get_bytes(inode);
8029 	spin_unlock(&BTRFS_I(inode)->lock);
8030 	stat->blocks = (ALIGN(inode_bytes, blocksize) +
8031 			ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8032 	return 0;
8033 }
8034 
btrfs_rename_exchange(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)8035 static int btrfs_rename_exchange(struct inode *old_dir,
8036 			      struct dentry *old_dentry,
8037 			      struct inode *new_dir,
8038 			      struct dentry *new_dentry)
8039 {
8040 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8041 	struct btrfs_trans_handle *trans;
8042 	unsigned int trans_num_items;
8043 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8044 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8045 	struct inode *new_inode = new_dentry->d_inode;
8046 	struct inode *old_inode = old_dentry->d_inode;
8047 	struct btrfs_rename_ctx old_rename_ctx;
8048 	struct btrfs_rename_ctx new_rename_ctx;
8049 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8050 	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8051 	u64 old_idx = 0;
8052 	u64 new_idx = 0;
8053 	int ret;
8054 	int ret2;
8055 	bool need_abort = false;
8056 	bool logs_pinned = false;
8057 	struct fscrypt_name old_fname, new_fname;
8058 	struct fscrypt_str *old_name, *new_name;
8059 
8060 	/*
8061 	 * For non-subvolumes allow exchange only within one subvolume, in the
8062 	 * same inode namespace. Two subvolumes (represented as directory) can
8063 	 * be exchanged as they're a logical link and have a fixed inode number.
8064 	 */
8065 	if (root != dest &&
8066 	    (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8067 	     new_ino != BTRFS_FIRST_FREE_OBJECTID))
8068 		return -EXDEV;
8069 
8070 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8071 	if (ret)
8072 		return ret;
8073 
8074 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8075 	if (ret) {
8076 		fscrypt_free_filename(&old_fname);
8077 		return ret;
8078 	}
8079 
8080 	old_name = &old_fname.disk_name;
8081 	new_name = &new_fname.disk_name;
8082 
8083 	/* close the race window with snapshot create/destroy ioctl */
8084 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8085 	    new_ino == BTRFS_FIRST_FREE_OBJECTID)
8086 		down_read(&fs_info->subvol_sem);
8087 
8088 	/*
8089 	 * For each inode:
8090 	 * 1 to remove old dir item
8091 	 * 1 to remove old dir index
8092 	 * 1 to add new dir item
8093 	 * 1 to add new dir index
8094 	 * 1 to update parent inode
8095 	 *
8096 	 * If the parents are the same, we only need to account for one
8097 	 */
8098 	trans_num_items = (old_dir == new_dir ? 9 : 10);
8099 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8100 		/*
8101 		 * 1 to remove old root ref
8102 		 * 1 to remove old root backref
8103 		 * 1 to add new root ref
8104 		 * 1 to add new root backref
8105 		 */
8106 		trans_num_items += 4;
8107 	} else {
8108 		/*
8109 		 * 1 to update inode item
8110 		 * 1 to remove old inode ref
8111 		 * 1 to add new inode ref
8112 		 */
8113 		trans_num_items += 3;
8114 	}
8115 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8116 		trans_num_items += 4;
8117 	else
8118 		trans_num_items += 3;
8119 	trans = btrfs_start_transaction(root, trans_num_items);
8120 	if (IS_ERR(trans)) {
8121 		ret = PTR_ERR(trans);
8122 		goto out_notrans;
8123 	}
8124 
8125 	if (dest != root) {
8126 		ret = btrfs_record_root_in_trans(trans, dest);
8127 		if (ret)
8128 			goto out_fail;
8129 	}
8130 
8131 	/*
8132 	 * We need to find a free sequence number both in the source and
8133 	 * in the destination directory for the exchange.
8134 	 */
8135 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8136 	if (ret)
8137 		goto out_fail;
8138 	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8139 	if (ret)
8140 		goto out_fail;
8141 
8142 	BTRFS_I(old_inode)->dir_index = 0ULL;
8143 	BTRFS_I(new_inode)->dir_index = 0ULL;
8144 
8145 	/* Reference for the source. */
8146 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8147 		/* force full log commit if subvolume involved. */
8148 		btrfs_set_log_full_commit(trans);
8149 	} else {
8150 		ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8151 					     btrfs_ino(BTRFS_I(new_dir)),
8152 					     old_idx);
8153 		if (ret)
8154 			goto out_fail;
8155 		need_abort = true;
8156 	}
8157 
8158 	/* And now for the dest. */
8159 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8160 		/* force full log commit if subvolume involved. */
8161 		btrfs_set_log_full_commit(trans);
8162 	} else {
8163 		ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8164 					     btrfs_ino(BTRFS_I(old_dir)),
8165 					     new_idx);
8166 		if (ret) {
8167 			if (need_abort)
8168 				btrfs_abort_transaction(trans, ret);
8169 			goto out_fail;
8170 		}
8171 	}
8172 
8173 	/* Update inode version and ctime/mtime. */
8174 	inode_inc_iversion(old_dir);
8175 	inode_inc_iversion(new_dir);
8176 	inode_inc_iversion(old_inode);
8177 	inode_inc_iversion(new_inode);
8178 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8179 
8180 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID &&
8181 	    new_ino != BTRFS_FIRST_FREE_OBJECTID) {
8182 		/*
8183 		 * If we are renaming in the same directory (and it's not for
8184 		 * root entries) pin the log early to prevent any concurrent
8185 		 * task from logging the directory after we removed the old
8186 		 * entries and before we add the new entries, otherwise that
8187 		 * task can sync a log without any entry for the inodes we are
8188 		 * renaming and therefore replaying that log, if a power failure
8189 		 * happens after syncing the log, would result in deleting the
8190 		 * inodes.
8191 		 *
8192 		 * If the rename affects two different directories, we want to
8193 		 * make sure the that there's no log commit that contains
8194 		 * updates for only one of the directories but not for the
8195 		 * other.
8196 		 *
8197 		 * If we are renaming an entry for a root, we don't care about
8198 		 * log updates since we called btrfs_set_log_full_commit().
8199 		 */
8200 		btrfs_pin_log_trans(root);
8201 		btrfs_pin_log_trans(dest);
8202 		logs_pinned = true;
8203 	}
8204 
8205 	if (old_dentry->d_parent != new_dentry->d_parent) {
8206 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8207 					BTRFS_I(old_inode), true);
8208 		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8209 					BTRFS_I(new_inode), true);
8210 	}
8211 
8212 	/* src is a subvolume */
8213 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8214 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8215 		if (ret) {
8216 			btrfs_abort_transaction(trans, ret);
8217 			goto out_fail;
8218 		}
8219 	} else { /* src is an inode */
8220 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8221 					   BTRFS_I(old_dentry->d_inode),
8222 					   old_name, &old_rename_ctx);
8223 		if (ret) {
8224 			btrfs_abort_transaction(trans, ret);
8225 			goto out_fail;
8226 		}
8227 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8228 		if (ret) {
8229 			btrfs_abort_transaction(trans, ret);
8230 			goto out_fail;
8231 		}
8232 	}
8233 
8234 	/* dest is a subvolume */
8235 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8236 		ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8237 		if (ret) {
8238 			btrfs_abort_transaction(trans, ret);
8239 			goto out_fail;
8240 		}
8241 	} else { /* dest is an inode */
8242 		ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8243 					   BTRFS_I(new_dentry->d_inode),
8244 					   new_name, &new_rename_ctx);
8245 		if (ret) {
8246 			btrfs_abort_transaction(trans, ret);
8247 			goto out_fail;
8248 		}
8249 		ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
8250 		if (ret) {
8251 			btrfs_abort_transaction(trans, ret);
8252 			goto out_fail;
8253 		}
8254 	}
8255 
8256 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8257 			     new_name, 0, old_idx);
8258 	if (ret) {
8259 		btrfs_abort_transaction(trans, ret);
8260 		goto out_fail;
8261 	}
8262 
8263 	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8264 			     old_name, 0, new_idx);
8265 	if (ret) {
8266 		btrfs_abort_transaction(trans, ret);
8267 		goto out_fail;
8268 	}
8269 
8270 	if (old_inode->i_nlink == 1)
8271 		BTRFS_I(old_inode)->dir_index = old_idx;
8272 	if (new_inode->i_nlink == 1)
8273 		BTRFS_I(new_inode)->dir_index = new_idx;
8274 
8275 	/*
8276 	 * Do the log updates for all inodes.
8277 	 *
8278 	 * If either entry is for a root we don't need to update the logs since
8279 	 * we've called btrfs_set_log_full_commit() before.
8280 	 */
8281 	if (logs_pinned) {
8282 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8283 				   old_rename_ctx.index, new_dentry->d_parent);
8284 		btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8285 				   new_rename_ctx.index, old_dentry->d_parent);
8286 	}
8287 
8288 out_fail:
8289 	if (logs_pinned) {
8290 		btrfs_end_log_trans(root);
8291 		btrfs_end_log_trans(dest);
8292 	}
8293 	ret2 = btrfs_end_transaction(trans);
8294 	ret = ret ? ret : ret2;
8295 out_notrans:
8296 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8297 	    old_ino == BTRFS_FIRST_FREE_OBJECTID)
8298 		up_read(&fs_info->subvol_sem);
8299 
8300 	fscrypt_free_filename(&new_fname);
8301 	fscrypt_free_filename(&old_fname);
8302 	return ret;
8303 }
8304 
new_whiteout_inode(struct mnt_idmap * idmap,struct inode * dir)8305 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8306 					struct inode *dir)
8307 {
8308 	struct inode *inode;
8309 
8310 	inode = new_inode(dir->i_sb);
8311 	if (inode) {
8312 		inode_init_owner(idmap, inode, dir,
8313 				 S_IFCHR | WHITEOUT_MODE);
8314 		inode->i_op = &btrfs_special_inode_operations;
8315 		init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8316 	}
8317 	return inode;
8318 }
8319 
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)8320 static int btrfs_rename(struct mnt_idmap *idmap,
8321 			struct inode *old_dir, struct dentry *old_dentry,
8322 			struct inode *new_dir, struct dentry *new_dentry,
8323 			unsigned int flags)
8324 {
8325 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8326 	struct btrfs_new_inode_args whiteout_args = {
8327 		.dir = old_dir,
8328 		.dentry = old_dentry,
8329 	};
8330 	struct btrfs_trans_handle *trans;
8331 	unsigned int trans_num_items;
8332 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8333 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8334 	struct inode *new_inode = d_inode(new_dentry);
8335 	struct inode *old_inode = d_inode(old_dentry);
8336 	struct btrfs_rename_ctx rename_ctx;
8337 	u64 index = 0;
8338 	int ret;
8339 	int ret2;
8340 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8341 	struct fscrypt_name old_fname, new_fname;
8342 	bool logs_pinned = false;
8343 
8344 	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8345 		return -EPERM;
8346 
8347 	/* we only allow rename subvolume link between subvolumes */
8348 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8349 		return -EXDEV;
8350 
8351 	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8352 	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8353 		return -ENOTEMPTY;
8354 
8355 	if (S_ISDIR(old_inode->i_mode) && new_inode &&
8356 	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8357 		return -ENOTEMPTY;
8358 
8359 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8360 	if (ret)
8361 		return ret;
8362 
8363 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8364 	if (ret) {
8365 		fscrypt_free_filename(&old_fname);
8366 		return ret;
8367 	}
8368 
8369 	/* check for collisions, even if the  name isn't there */
8370 	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8371 	if (ret) {
8372 		if (ret == -EEXIST) {
8373 			/* we shouldn't get
8374 			 * eexist without a new_inode */
8375 			if (WARN_ON(!new_inode)) {
8376 				goto out_fscrypt_names;
8377 			}
8378 		} else {
8379 			/* maybe -EOVERFLOW */
8380 			goto out_fscrypt_names;
8381 		}
8382 	}
8383 	ret = 0;
8384 
8385 	/*
8386 	 * we're using rename to replace one file with another.  Start IO on it
8387 	 * now so  we don't add too much work to the end of the transaction
8388 	 */
8389 	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8390 		filemap_flush(old_inode->i_mapping);
8391 
8392 	if (flags & RENAME_WHITEOUT) {
8393 		whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
8394 		if (!whiteout_args.inode) {
8395 			ret = -ENOMEM;
8396 			goto out_fscrypt_names;
8397 		}
8398 		ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
8399 		if (ret)
8400 			goto out_whiteout_inode;
8401 	} else {
8402 		/* 1 to update the old parent inode. */
8403 		trans_num_items = 1;
8404 	}
8405 
8406 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8407 		/* Close the race window with snapshot create/destroy ioctl */
8408 		down_read(&fs_info->subvol_sem);
8409 		/*
8410 		 * 1 to remove old root ref
8411 		 * 1 to remove old root backref
8412 		 * 1 to add new root ref
8413 		 * 1 to add new root backref
8414 		 */
8415 		trans_num_items += 4;
8416 	} else {
8417 		/*
8418 		 * 1 to update inode
8419 		 * 1 to remove old inode ref
8420 		 * 1 to add new inode ref
8421 		 */
8422 		trans_num_items += 3;
8423 	}
8424 	/*
8425 	 * 1 to remove old dir item
8426 	 * 1 to remove old dir index
8427 	 * 1 to add new dir item
8428 	 * 1 to add new dir index
8429 	 */
8430 	trans_num_items += 4;
8431 	/* 1 to update new parent inode if it's not the same as the old parent */
8432 	if (new_dir != old_dir)
8433 		trans_num_items++;
8434 	if (new_inode) {
8435 		/*
8436 		 * 1 to update inode
8437 		 * 1 to remove inode ref
8438 		 * 1 to remove dir item
8439 		 * 1 to remove dir index
8440 		 * 1 to possibly add orphan item
8441 		 */
8442 		trans_num_items += 5;
8443 	}
8444 	trans = btrfs_start_transaction(root, trans_num_items);
8445 	if (IS_ERR(trans)) {
8446 		ret = PTR_ERR(trans);
8447 		goto out_notrans;
8448 	}
8449 
8450 	if (dest != root) {
8451 		ret = btrfs_record_root_in_trans(trans, dest);
8452 		if (ret)
8453 			goto out_fail;
8454 	}
8455 
8456 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
8457 	if (ret)
8458 		goto out_fail;
8459 
8460 	BTRFS_I(old_inode)->dir_index = 0ULL;
8461 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8462 		/* force full log commit if subvolume involved. */
8463 		btrfs_set_log_full_commit(trans);
8464 	} else {
8465 		ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
8466 					     old_ino, btrfs_ino(BTRFS_I(new_dir)),
8467 					     index);
8468 		if (ret)
8469 			goto out_fail;
8470 	}
8471 
8472 	inode_inc_iversion(old_dir);
8473 	inode_inc_iversion(new_dir);
8474 	inode_inc_iversion(old_inode);
8475 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8476 
8477 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8478 		/*
8479 		 * If we are renaming in the same directory (and it's not a
8480 		 * root entry) pin the log to prevent any concurrent task from
8481 		 * logging the directory after we removed the old entry and
8482 		 * before we add the new entry, otherwise that task can sync
8483 		 * a log without any entry for the inode we are renaming and
8484 		 * therefore replaying that log, if a power failure happens
8485 		 * after syncing the log, would result in deleting the inode.
8486 		 *
8487 		 * If the rename affects two different directories, we want to
8488 		 * make sure the that there's no log commit that contains
8489 		 * updates for only one of the directories but not for the
8490 		 * other.
8491 		 *
8492 		 * If we are renaming an entry for a root, we don't care about
8493 		 * log updates since we called btrfs_set_log_full_commit().
8494 		 */
8495 		btrfs_pin_log_trans(root);
8496 		btrfs_pin_log_trans(dest);
8497 		logs_pinned = true;
8498 	}
8499 
8500 	if (old_dentry->d_parent != new_dentry->d_parent)
8501 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8502 					BTRFS_I(old_inode), true);
8503 
8504 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8505 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8506 		if (ret) {
8507 			btrfs_abort_transaction(trans, ret);
8508 			goto out_fail;
8509 		}
8510 	} else {
8511 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8512 					   BTRFS_I(d_inode(old_dentry)),
8513 					   &old_fname.disk_name, &rename_ctx);
8514 		if (ret) {
8515 			btrfs_abort_transaction(trans, ret);
8516 			goto out_fail;
8517 		}
8518 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8519 		if (ret) {
8520 			btrfs_abort_transaction(trans, ret);
8521 			goto out_fail;
8522 		}
8523 	}
8524 
8525 	if (new_inode) {
8526 		inode_inc_iversion(new_inode);
8527 		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
8528 			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8529 			ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8530 			if (ret) {
8531 				btrfs_abort_transaction(trans, ret);
8532 				goto out_fail;
8533 			}
8534 			BUG_ON(new_inode->i_nlink == 0);
8535 		} else {
8536 			ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8537 						 BTRFS_I(d_inode(new_dentry)),
8538 						 &new_fname.disk_name);
8539 			if (ret) {
8540 				btrfs_abort_transaction(trans, ret);
8541 				goto out_fail;
8542 			}
8543 		}
8544 		if (new_inode->i_nlink == 0) {
8545 			ret = btrfs_orphan_add(trans,
8546 					BTRFS_I(d_inode(new_dentry)));
8547 			if (ret) {
8548 				btrfs_abort_transaction(trans, ret);
8549 				goto out_fail;
8550 			}
8551 		}
8552 	}
8553 
8554 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8555 			     &new_fname.disk_name, 0, index);
8556 	if (ret) {
8557 		btrfs_abort_transaction(trans, ret);
8558 		goto out_fail;
8559 	}
8560 
8561 	if (old_inode->i_nlink == 1)
8562 		BTRFS_I(old_inode)->dir_index = index;
8563 
8564 	if (logs_pinned)
8565 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8566 				   rename_ctx.index, new_dentry->d_parent);
8567 
8568 	if (flags & RENAME_WHITEOUT) {
8569 		ret = btrfs_create_new_inode(trans, &whiteout_args);
8570 		if (ret) {
8571 			btrfs_abort_transaction(trans, ret);
8572 			goto out_fail;
8573 		} else {
8574 			unlock_new_inode(whiteout_args.inode);
8575 			iput(whiteout_args.inode);
8576 			whiteout_args.inode = NULL;
8577 		}
8578 	}
8579 out_fail:
8580 	if (logs_pinned) {
8581 		btrfs_end_log_trans(root);
8582 		btrfs_end_log_trans(dest);
8583 	}
8584 	ret2 = btrfs_end_transaction(trans);
8585 	ret = ret ? ret : ret2;
8586 out_notrans:
8587 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8588 		up_read(&fs_info->subvol_sem);
8589 	if (flags & RENAME_WHITEOUT)
8590 		btrfs_new_inode_args_destroy(&whiteout_args);
8591 out_whiteout_inode:
8592 	if (flags & RENAME_WHITEOUT)
8593 		iput(whiteout_args.inode);
8594 out_fscrypt_names:
8595 	fscrypt_free_filename(&old_fname);
8596 	fscrypt_free_filename(&new_fname);
8597 	return ret;
8598 }
8599 
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)8600 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
8601 			 struct dentry *old_dentry, struct inode *new_dir,
8602 			 struct dentry *new_dentry, unsigned int flags)
8603 {
8604 	int ret;
8605 
8606 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
8607 		return -EINVAL;
8608 
8609 	if (flags & RENAME_EXCHANGE)
8610 		ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
8611 					    new_dentry);
8612 	else
8613 		ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
8614 				   new_dentry, flags);
8615 
8616 	btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
8617 
8618 	return ret;
8619 }
8620 
8621 struct btrfs_delalloc_work {
8622 	struct inode *inode;
8623 	struct completion completion;
8624 	struct list_head list;
8625 	struct btrfs_work work;
8626 };
8627 
btrfs_run_delalloc_work(struct btrfs_work * work)8628 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8629 {
8630 	struct btrfs_delalloc_work *delalloc_work;
8631 	struct inode *inode;
8632 
8633 	delalloc_work = container_of(work, struct btrfs_delalloc_work,
8634 				     work);
8635 	inode = delalloc_work->inode;
8636 	filemap_flush(inode->i_mapping);
8637 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8638 				&BTRFS_I(inode)->runtime_flags))
8639 		filemap_flush(inode->i_mapping);
8640 
8641 	iput(inode);
8642 	complete(&delalloc_work->completion);
8643 }
8644 
btrfs_alloc_delalloc_work(struct inode * inode)8645 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8646 {
8647 	struct btrfs_delalloc_work *work;
8648 
8649 	work = kmalloc(sizeof(*work), GFP_NOFS);
8650 	if (!work)
8651 		return NULL;
8652 
8653 	init_completion(&work->completion);
8654 	INIT_LIST_HEAD(&work->list);
8655 	work->inode = inode;
8656 	btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
8657 
8658 	return work;
8659 }
8660 
8661 /*
8662  * some fairly slow code that needs optimization. This walks the list
8663  * of all the inodes with pending delalloc and forces them to disk.
8664  */
start_delalloc_inodes(struct btrfs_root * root,struct writeback_control * wbc,bool snapshot,bool in_reclaim_context)8665 static int start_delalloc_inodes(struct btrfs_root *root,
8666 				 struct writeback_control *wbc, bool snapshot,
8667 				 bool in_reclaim_context)
8668 {
8669 	struct btrfs_delalloc_work *work, *next;
8670 	LIST_HEAD(works);
8671 	LIST_HEAD(splice);
8672 	int ret = 0;
8673 	bool full_flush = wbc->nr_to_write == LONG_MAX;
8674 
8675 	mutex_lock(&root->delalloc_mutex);
8676 	spin_lock(&root->delalloc_lock);
8677 	list_splice_init(&root->delalloc_inodes, &splice);
8678 	while (!list_empty(&splice)) {
8679 		struct btrfs_inode *inode;
8680 		struct inode *tmp_inode;
8681 
8682 		inode = list_first_entry(&splice, struct btrfs_inode, delalloc_inodes);
8683 
8684 		list_move_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
8685 
8686 		if (in_reclaim_context &&
8687 		    test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags))
8688 			continue;
8689 
8690 		tmp_inode = igrab(&inode->vfs_inode);
8691 		if (!tmp_inode) {
8692 			cond_resched_lock(&root->delalloc_lock);
8693 			continue;
8694 		}
8695 		spin_unlock(&root->delalloc_lock);
8696 
8697 		if (snapshot)
8698 			set_bit(BTRFS_INODE_SNAPSHOT_FLUSH, &inode->runtime_flags);
8699 		if (full_flush) {
8700 			work = btrfs_alloc_delalloc_work(&inode->vfs_inode);
8701 			if (!work) {
8702 				iput(&inode->vfs_inode);
8703 				ret = -ENOMEM;
8704 				goto out;
8705 			}
8706 			list_add_tail(&work->list, &works);
8707 			btrfs_queue_work(root->fs_info->flush_workers,
8708 					 &work->work);
8709 		} else {
8710 			ret = filemap_fdatawrite_wbc(inode->vfs_inode.i_mapping, wbc);
8711 			btrfs_add_delayed_iput(inode);
8712 			if (ret || wbc->nr_to_write <= 0)
8713 				goto out;
8714 		}
8715 		cond_resched();
8716 		spin_lock(&root->delalloc_lock);
8717 	}
8718 	spin_unlock(&root->delalloc_lock);
8719 
8720 out:
8721 	list_for_each_entry_safe(work, next, &works, list) {
8722 		list_del_init(&work->list);
8723 		wait_for_completion(&work->completion);
8724 		kfree(work);
8725 	}
8726 
8727 	if (!list_empty(&splice)) {
8728 		spin_lock(&root->delalloc_lock);
8729 		list_splice_tail(&splice, &root->delalloc_inodes);
8730 		spin_unlock(&root->delalloc_lock);
8731 	}
8732 	mutex_unlock(&root->delalloc_mutex);
8733 	return ret;
8734 }
8735 
btrfs_start_delalloc_snapshot(struct btrfs_root * root,bool in_reclaim_context)8736 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
8737 {
8738 	struct writeback_control wbc = {
8739 		.nr_to_write = LONG_MAX,
8740 		.sync_mode = WB_SYNC_NONE,
8741 		.range_start = 0,
8742 		.range_end = LLONG_MAX,
8743 	};
8744 	struct btrfs_fs_info *fs_info = root->fs_info;
8745 
8746 	if (BTRFS_FS_ERROR(fs_info))
8747 		return -EROFS;
8748 
8749 	return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
8750 }
8751 
btrfs_start_delalloc_roots(struct btrfs_fs_info * fs_info,long nr,bool in_reclaim_context)8752 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
8753 			       bool in_reclaim_context)
8754 {
8755 	struct writeback_control wbc = {
8756 		.nr_to_write = nr,
8757 		.sync_mode = WB_SYNC_NONE,
8758 		.range_start = 0,
8759 		.range_end = LLONG_MAX,
8760 	};
8761 	struct btrfs_root *root;
8762 	LIST_HEAD(splice);
8763 	int ret;
8764 
8765 	if (BTRFS_FS_ERROR(fs_info))
8766 		return -EROFS;
8767 
8768 	mutex_lock(&fs_info->delalloc_root_mutex);
8769 	spin_lock(&fs_info->delalloc_root_lock);
8770 	list_splice_init(&fs_info->delalloc_roots, &splice);
8771 	while (!list_empty(&splice)) {
8772 		/*
8773 		 * Reset nr_to_write here so we know that we're doing a full
8774 		 * flush.
8775 		 */
8776 		if (nr == LONG_MAX)
8777 			wbc.nr_to_write = LONG_MAX;
8778 
8779 		root = list_first_entry(&splice, struct btrfs_root,
8780 					delalloc_root);
8781 		root = btrfs_grab_root(root);
8782 		BUG_ON(!root);
8783 		list_move_tail(&root->delalloc_root,
8784 			       &fs_info->delalloc_roots);
8785 		spin_unlock(&fs_info->delalloc_root_lock);
8786 
8787 		ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
8788 		btrfs_put_root(root);
8789 		if (ret < 0 || wbc.nr_to_write <= 0)
8790 			goto out;
8791 		spin_lock(&fs_info->delalloc_root_lock);
8792 	}
8793 	spin_unlock(&fs_info->delalloc_root_lock);
8794 
8795 	ret = 0;
8796 out:
8797 	if (!list_empty(&splice)) {
8798 		spin_lock(&fs_info->delalloc_root_lock);
8799 		list_splice_tail(&splice, &fs_info->delalloc_roots);
8800 		spin_unlock(&fs_info->delalloc_root_lock);
8801 	}
8802 	mutex_unlock(&fs_info->delalloc_root_mutex);
8803 	return ret;
8804 }
8805 
btrfs_symlink(struct mnt_idmap * idmap,struct inode * dir,struct dentry * dentry,const char * symname)8806 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
8807 			 struct dentry *dentry, const char *symname)
8808 {
8809 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
8810 	struct btrfs_trans_handle *trans;
8811 	struct btrfs_root *root = BTRFS_I(dir)->root;
8812 	struct btrfs_path *path;
8813 	struct btrfs_key key;
8814 	struct inode *inode;
8815 	struct btrfs_new_inode_args new_inode_args = {
8816 		.dir = dir,
8817 		.dentry = dentry,
8818 	};
8819 	unsigned int trans_num_items;
8820 	int ret;
8821 	int name_len;
8822 	int datasize;
8823 	unsigned long ptr;
8824 	struct btrfs_file_extent_item *ei;
8825 	struct extent_buffer *leaf;
8826 
8827 	name_len = strlen(symname);
8828 	/*
8829 	 * Symlinks utilize uncompressed inline extent data, which should not
8830 	 * reach block size.
8831 	 */
8832 	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
8833 	    name_len >= fs_info->sectorsize)
8834 		return -ENAMETOOLONG;
8835 
8836 	inode = new_inode(dir->i_sb);
8837 	if (!inode)
8838 		return -ENOMEM;
8839 	inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
8840 	inode->i_op = &btrfs_symlink_inode_operations;
8841 	inode_nohighmem(inode);
8842 	inode->i_mapping->a_ops = &btrfs_aops;
8843 	btrfs_i_size_write(BTRFS_I(inode), name_len);
8844 	inode_set_bytes(inode, name_len);
8845 
8846 	new_inode_args.inode = inode;
8847 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
8848 	if (ret)
8849 		goto out_inode;
8850 	/* 1 additional item for the inline extent */
8851 	trans_num_items++;
8852 
8853 	trans = btrfs_start_transaction(root, trans_num_items);
8854 	if (IS_ERR(trans)) {
8855 		ret = PTR_ERR(trans);
8856 		goto out_new_inode_args;
8857 	}
8858 
8859 	ret = btrfs_create_new_inode(trans, &new_inode_args);
8860 	if (ret)
8861 		goto out;
8862 
8863 	path = btrfs_alloc_path();
8864 	if (!path) {
8865 		ret = -ENOMEM;
8866 		btrfs_abort_transaction(trans, ret);
8867 		discard_new_inode(inode);
8868 		inode = NULL;
8869 		goto out;
8870 	}
8871 	key.objectid = btrfs_ino(BTRFS_I(inode));
8872 	key.type = BTRFS_EXTENT_DATA_KEY;
8873 	key.offset = 0;
8874 	datasize = btrfs_file_extent_calc_inline_size(name_len);
8875 	ret = btrfs_insert_empty_item(trans, root, path, &key, datasize);
8876 	if (ret) {
8877 		btrfs_abort_transaction(trans, ret);
8878 		btrfs_free_path(path);
8879 		discard_new_inode(inode);
8880 		inode = NULL;
8881 		goto out;
8882 	}
8883 	leaf = path->nodes[0];
8884 	ei = btrfs_item_ptr(leaf, path->slots[0],
8885 			    struct btrfs_file_extent_item);
8886 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8887 	btrfs_set_file_extent_type(leaf, ei,
8888 				   BTRFS_FILE_EXTENT_INLINE);
8889 	btrfs_set_file_extent_encryption(leaf, ei, 0);
8890 	btrfs_set_file_extent_compression(leaf, ei, 0);
8891 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8892 	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8893 
8894 	ptr = btrfs_file_extent_inline_start(ei);
8895 	write_extent_buffer(leaf, symname, ptr, name_len);
8896 	btrfs_free_path(path);
8897 
8898 	d_instantiate_new(dentry, inode);
8899 	ret = 0;
8900 out:
8901 	btrfs_end_transaction(trans);
8902 	btrfs_btree_balance_dirty(fs_info);
8903 out_new_inode_args:
8904 	btrfs_new_inode_args_destroy(&new_inode_args);
8905 out_inode:
8906 	if (ret)
8907 		iput(inode);
8908 	return ret;
8909 }
8910 
insert_prealloc_file_extent(struct btrfs_trans_handle * trans_in,struct btrfs_inode * inode,struct btrfs_key * ins,u64 file_offset)8911 static struct btrfs_trans_handle *insert_prealloc_file_extent(
8912 				       struct btrfs_trans_handle *trans_in,
8913 				       struct btrfs_inode *inode,
8914 				       struct btrfs_key *ins,
8915 				       u64 file_offset)
8916 {
8917 	struct btrfs_file_extent_item stack_fi;
8918 	struct btrfs_replace_extent_info extent_info;
8919 	struct btrfs_trans_handle *trans = trans_in;
8920 	struct btrfs_path *path;
8921 	u64 start = ins->objectid;
8922 	u64 len = ins->offset;
8923 	u64 qgroup_released = 0;
8924 	int ret;
8925 
8926 	memset(&stack_fi, 0, sizeof(stack_fi));
8927 
8928 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
8929 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
8930 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
8931 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
8932 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
8933 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
8934 	/* Encryption and other encoding is reserved and all 0 */
8935 
8936 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
8937 	if (ret < 0)
8938 		return ERR_PTR(ret);
8939 
8940 	if (trans) {
8941 		ret = insert_reserved_file_extent(trans, inode,
8942 						  file_offset, &stack_fi,
8943 						  true, qgroup_released);
8944 		if (ret)
8945 			goto free_qgroup;
8946 		return trans;
8947 	}
8948 
8949 	extent_info.disk_offset = start;
8950 	extent_info.disk_len = len;
8951 	extent_info.data_offset = 0;
8952 	extent_info.data_len = len;
8953 	extent_info.file_offset = file_offset;
8954 	extent_info.extent_buf = (char *)&stack_fi;
8955 	extent_info.is_new_extent = true;
8956 	extent_info.update_times = true;
8957 	extent_info.qgroup_reserved = qgroup_released;
8958 	extent_info.insertions = 0;
8959 
8960 	path = btrfs_alloc_path();
8961 	if (!path) {
8962 		ret = -ENOMEM;
8963 		goto free_qgroup;
8964 	}
8965 
8966 	ret = btrfs_replace_file_extents(inode, path, file_offset,
8967 				     file_offset + len - 1, &extent_info,
8968 				     &trans);
8969 	btrfs_free_path(path);
8970 	if (ret)
8971 		goto free_qgroup;
8972 	return trans;
8973 
8974 free_qgroup:
8975 	/*
8976 	 * We have released qgroup data range at the beginning of the function,
8977 	 * and normally qgroup_released bytes will be freed when committing
8978 	 * transaction.
8979 	 * But if we error out early, we have to free what we have released
8980 	 * or we leak qgroup data reservation.
8981 	 */
8982 	btrfs_qgroup_free_refroot(inode->root->fs_info,
8983 			btrfs_root_id(inode->root), qgroup_released,
8984 			BTRFS_QGROUP_RSV_DATA);
8985 	return ERR_PTR(ret);
8986 }
8987 
__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)8988 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8989 				       u64 start, u64 num_bytes, u64 min_size,
8990 				       loff_t actual_len, u64 *alloc_hint,
8991 				       struct btrfs_trans_handle *trans)
8992 {
8993 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
8994 	struct extent_map *em;
8995 	struct btrfs_root *root = BTRFS_I(inode)->root;
8996 	struct btrfs_key ins;
8997 	u64 cur_offset = start;
8998 	u64 clear_offset = start;
8999 	u64 i_size;
9000 	u64 cur_bytes;
9001 	u64 last_alloc = (u64)-1;
9002 	int ret = 0;
9003 	bool own_trans = true;
9004 	u64 end = start + num_bytes - 1;
9005 
9006 	if (trans)
9007 		own_trans = false;
9008 	while (num_bytes > 0) {
9009 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
9010 		cur_bytes = max(cur_bytes, min_size);
9011 		/*
9012 		 * If we are severely fragmented we could end up with really
9013 		 * small allocations, so if the allocator is returning small
9014 		 * chunks lets make its job easier by only searching for those
9015 		 * sized chunks.
9016 		 */
9017 		cur_bytes = min(cur_bytes, last_alloc);
9018 		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9019 				min_size, 0, *alloc_hint, &ins, 1, 0);
9020 		if (ret)
9021 			break;
9022 
9023 		/*
9024 		 * We've reserved this space, and thus converted it from
9025 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9026 		 * from here on out we will only need to clear our reservation
9027 		 * for the remaining unreserved area, so advance our
9028 		 * clear_offset by our extent size.
9029 		 */
9030 		clear_offset += ins.offset;
9031 
9032 		last_alloc = ins.offset;
9033 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9034 						    &ins, cur_offset);
9035 		/*
9036 		 * Now that we inserted the prealloc extent we can finally
9037 		 * decrement the number of reservations in the block group.
9038 		 * If we did it before, we could race with relocation and have
9039 		 * relocation miss the reserved extent, making it fail later.
9040 		 */
9041 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9042 		if (IS_ERR(trans)) {
9043 			ret = PTR_ERR(trans);
9044 			btrfs_free_reserved_extent(fs_info, ins.objectid,
9045 						   ins.offset, false);
9046 			break;
9047 		}
9048 
9049 		em = btrfs_alloc_extent_map();
9050 		if (!em) {
9051 			btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9052 					    cur_offset + ins.offset - 1, false);
9053 			btrfs_set_inode_full_sync(BTRFS_I(inode));
9054 			goto next;
9055 		}
9056 
9057 		em->start = cur_offset;
9058 		em->len = ins.offset;
9059 		em->disk_bytenr = ins.objectid;
9060 		em->offset = 0;
9061 		em->disk_num_bytes = ins.offset;
9062 		em->ram_bytes = ins.offset;
9063 		em->flags |= EXTENT_FLAG_PREALLOC;
9064 		em->generation = trans->transid;
9065 
9066 		ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9067 		btrfs_free_extent_map(em);
9068 next:
9069 		num_bytes -= ins.offset;
9070 		cur_offset += ins.offset;
9071 		*alloc_hint = ins.objectid + ins.offset;
9072 
9073 		inode_inc_iversion(inode);
9074 		inode_set_ctime_current(inode);
9075 		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9076 		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9077 		    (actual_len > inode->i_size) &&
9078 		    (cur_offset > inode->i_size)) {
9079 			if (cur_offset > actual_len)
9080 				i_size = actual_len;
9081 			else
9082 				i_size = cur_offset;
9083 			i_size_write(inode, i_size);
9084 			btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9085 		}
9086 
9087 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
9088 
9089 		if (ret) {
9090 			btrfs_abort_transaction(trans, ret);
9091 			if (own_trans)
9092 				btrfs_end_transaction(trans);
9093 			break;
9094 		}
9095 
9096 		if (own_trans) {
9097 			btrfs_end_transaction(trans);
9098 			trans = NULL;
9099 		}
9100 	}
9101 	if (clear_offset < end)
9102 		btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9103 			end - clear_offset + 1);
9104 	return ret;
9105 }
9106 
btrfs_prealloc_file_range(struct inode * inode,int mode,u64 start,u64 num_bytes,u64 min_size,loff_t actual_len,u64 * alloc_hint)9107 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9108 			      u64 start, u64 num_bytes, u64 min_size,
9109 			      loff_t actual_len, u64 *alloc_hint)
9110 {
9111 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9112 					   min_size, actual_len, alloc_hint,
9113 					   NULL);
9114 }
9115 
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)9116 int btrfs_prealloc_file_range_trans(struct inode *inode,
9117 				    struct btrfs_trans_handle *trans, int mode,
9118 				    u64 start, u64 num_bytes, u64 min_size,
9119 				    loff_t actual_len, u64 *alloc_hint)
9120 {
9121 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9122 					   min_size, actual_len, alloc_hint, trans);
9123 }
9124 
btrfs_permission(struct mnt_idmap * idmap,struct inode * inode,int mask)9125 static int btrfs_permission(struct mnt_idmap *idmap,
9126 			    struct inode *inode, int mask)
9127 {
9128 	struct btrfs_root *root = BTRFS_I(inode)->root;
9129 	umode_t mode = inode->i_mode;
9130 
9131 	if (mask & MAY_WRITE &&
9132 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9133 		if (btrfs_root_readonly(root))
9134 			return -EROFS;
9135 		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9136 			return -EACCES;
9137 	}
9138 	return generic_permission(idmap, inode, mask);
9139 }
9140 
btrfs_tmpfile(struct mnt_idmap * idmap,struct inode * dir,struct file * file,umode_t mode)9141 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9142 			 struct file *file, umode_t mode)
9143 {
9144 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9145 	struct btrfs_trans_handle *trans;
9146 	struct btrfs_root *root = BTRFS_I(dir)->root;
9147 	struct inode *inode;
9148 	struct btrfs_new_inode_args new_inode_args = {
9149 		.dir = dir,
9150 		.dentry = file->f_path.dentry,
9151 		.orphan = true,
9152 	};
9153 	unsigned int trans_num_items;
9154 	int ret;
9155 
9156 	inode = new_inode(dir->i_sb);
9157 	if (!inode)
9158 		return -ENOMEM;
9159 	inode_init_owner(idmap, inode, dir, mode);
9160 	inode->i_fop = &btrfs_file_operations;
9161 	inode->i_op = &btrfs_file_inode_operations;
9162 	inode->i_mapping->a_ops = &btrfs_aops;
9163 
9164 	new_inode_args.inode = inode;
9165 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9166 	if (ret)
9167 		goto out_inode;
9168 
9169 	trans = btrfs_start_transaction(root, trans_num_items);
9170 	if (IS_ERR(trans)) {
9171 		ret = PTR_ERR(trans);
9172 		goto out_new_inode_args;
9173 	}
9174 
9175 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9176 
9177 	/*
9178 	 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9179 	 * set it to 1 because d_tmpfile() will issue a warning if the count is
9180 	 * 0, through:
9181 	 *
9182 	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9183 	 */
9184 	set_nlink(inode, 1);
9185 
9186 	if (!ret) {
9187 		d_tmpfile(file, inode);
9188 		unlock_new_inode(inode);
9189 		mark_inode_dirty(inode);
9190 	}
9191 
9192 	btrfs_end_transaction(trans);
9193 	btrfs_btree_balance_dirty(fs_info);
9194 out_new_inode_args:
9195 	btrfs_new_inode_args_destroy(&new_inode_args);
9196 out_inode:
9197 	if (ret)
9198 		iput(inode);
9199 	return finish_open_simple(file, ret);
9200 }
9201 
btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info * fs_info,int compress_type)9202 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9203 					     int compress_type)
9204 {
9205 	switch (compress_type) {
9206 	case BTRFS_COMPRESS_NONE:
9207 		return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9208 	case BTRFS_COMPRESS_ZLIB:
9209 		return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9210 	case BTRFS_COMPRESS_LZO:
9211 		/*
9212 		 * The LZO format depends on the sector size. 64K is the maximum
9213 		 * sector size that we support.
9214 		 */
9215 		if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9216 			return -EINVAL;
9217 		return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9218 		       (fs_info->sectorsize_bits - 12);
9219 	case BTRFS_COMPRESS_ZSTD:
9220 		return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9221 	default:
9222 		return -EUCLEAN;
9223 	}
9224 }
9225 
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)9226 static ssize_t btrfs_encoded_read_inline(
9227 				struct kiocb *iocb,
9228 				struct iov_iter *iter, u64 start,
9229 				u64 lockend,
9230 				struct extent_state **cached_state,
9231 				u64 extent_start, size_t count,
9232 				struct btrfs_ioctl_encoded_io_args *encoded,
9233 				bool *unlocked)
9234 {
9235 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9236 	struct btrfs_root *root = inode->root;
9237 	struct btrfs_fs_info *fs_info = root->fs_info;
9238 	struct extent_io_tree *io_tree = &inode->io_tree;
9239 	BTRFS_PATH_AUTO_FREE(path);
9240 	struct extent_buffer *leaf;
9241 	struct btrfs_file_extent_item *item;
9242 	u64 ram_bytes;
9243 	unsigned long ptr;
9244 	void *tmp;
9245 	ssize_t ret;
9246 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9247 
9248 	path = btrfs_alloc_path();
9249 	if (!path)
9250 		return -ENOMEM;
9251 
9252 	path->nowait = nowait;
9253 
9254 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9255 				       extent_start, 0);
9256 	if (ret) {
9257 		if (ret > 0) {
9258 			/* The extent item disappeared? */
9259 			return -EIO;
9260 		}
9261 		return ret;
9262 	}
9263 	leaf = path->nodes[0];
9264 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9265 
9266 	ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9267 	ptr = btrfs_file_extent_inline_start(item);
9268 
9269 	encoded->len = min_t(u64, extent_start + ram_bytes,
9270 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9271 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
9272 				 btrfs_file_extent_compression(leaf, item));
9273 	if (ret < 0)
9274 		return ret;
9275 	encoded->compression = ret;
9276 	if (encoded->compression) {
9277 		size_t inline_size;
9278 
9279 		inline_size = btrfs_file_extent_inline_item_len(leaf,
9280 								path->slots[0]);
9281 		if (inline_size > count)
9282 			return -ENOBUFS;
9283 
9284 		count = inline_size;
9285 		encoded->unencoded_len = ram_bytes;
9286 		encoded->unencoded_offset = iocb->ki_pos - extent_start;
9287 	} else {
9288 		count = min_t(u64, count, encoded->len);
9289 		encoded->len = count;
9290 		encoded->unencoded_len = count;
9291 		ptr += iocb->ki_pos - extent_start;
9292 	}
9293 
9294 	tmp = kmalloc(count, GFP_NOFS);
9295 	if (!tmp)
9296 		return -ENOMEM;
9297 
9298 	read_extent_buffer(leaf, tmp, ptr, count);
9299 	btrfs_release_path(path);
9300 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9301 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9302 	*unlocked = true;
9303 
9304 	ret = copy_to_iter(tmp, count, iter);
9305 	if (ret != count)
9306 		ret = -EFAULT;
9307 	kfree(tmp);
9308 
9309 	return ret;
9310 }
9311 
9312 struct btrfs_encoded_read_private {
9313 	struct completion *sync_reads;
9314 	void *uring_ctx;
9315 	refcount_t pending_refs;
9316 	blk_status_t status;
9317 };
9318 
btrfs_encoded_read_endio(struct btrfs_bio * bbio)9319 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9320 {
9321 	struct btrfs_encoded_read_private *priv = bbio->private;
9322 
9323 	if (bbio->bio.bi_status) {
9324 		/*
9325 		 * The memory barrier implied by the refcount_dec_and_test() here
9326 		 * pairs with the memory barrier implied by the refcount_dec_and_test()
9327 		 * in btrfs_encoded_read_regular_fill_pages() to ensure that
9328 		 * this write is observed before the load of status in
9329 		 * btrfs_encoded_read_regular_fill_pages().
9330 		 */
9331 		WRITE_ONCE(priv->status, bbio->bio.bi_status);
9332 	}
9333 	if (refcount_dec_and_test(&priv->pending_refs)) {
9334 		int err = blk_status_to_errno(READ_ONCE(priv->status));
9335 
9336 		if (priv->uring_ctx) {
9337 			btrfs_uring_read_extent_endio(priv->uring_ctx, err);
9338 			kfree(priv);
9339 		} else {
9340 			complete(priv->sync_reads);
9341 		}
9342 	}
9343 	bio_put(&bbio->bio);
9344 }
9345 
btrfs_encoded_read_regular_fill_pages(struct btrfs_inode * inode,u64 disk_bytenr,u64 disk_io_size,struct page ** pages,void * uring_ctx)9346 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9347 					  u64 disk_bytenr, u64 disk_io_size,
9348 					  struct page **pages, void *uring_ctx)
9349 {
9350 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
9351 	struct btrfs_encoded_read_private *priv, sync_priv;
9352 	struct completion sync_reads;
9353 	unsigned long i = 0;
9354 	struct btrfs_bio *bbio;
9355 	int ret;
9356 
9357 	/*
9358 	 * Fast path for synchronous reads which completes in this call, io_uring
9359 	 * needs longer time span.
9360 	 */
9361 	if (uring_ctx) {
9362 		priv = kmalloc(sizeof(struct btrfs_encoded_read_private), GFP_NOFS);
9363 		if (!priv)
9364 			return -ENOMEM;
9365 	} else {
9366 		priv = &sync_priv;
9367 		init_completion(&sync_reads);
9368 		priv->sync_reads = &sync_reads;
9369 	}
9370 
9371 	refcount_set(&priv->pending_refs, 1);
9372 	priv->status = 0;
9373 	priv->uring_ctx = uring_ctx;
9374 
9375 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
9376 			       btrfs_encoded_read_endio, priv);
9377 	bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9378 	bbio->inode = inode;
9379 
9380 	do {
9381 		size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
9382 
9383 		if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
9384 			refcount_inc(&priv->pending_refs);
9385 			btrfs_submit_bbio(bbio, 0);
9386 
9387 			bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
9388 					       btrfs_encoded_read_endio, priv);
9389 			bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9390 			bbio->inode = inode;
9391 			continue;
9392 		}
9393 
9394 		i++;
9395 		disk_bytenr += bytes;
9396 		disk_io_size -= bytes;
9397 	} while (disk_io_size);
9398 
9399 	refcount_inc(&priv->pending_refs);
9400 	btrfs_submit_bbio(bbio, 0);
9401 
9402 	if (uring_ctx) {
9403 		if (refcount_dec_and_test(&priv->pending_refs)) {
9404 			ret = blk_status_to_errno(READ_ONCE(priv->status));
9405 			btrfs_uring_read_extent_endio(uring_ctx, ret);
9406 			kfree(priv);
9407 			return ret;
9408 		}
9409 
9410 		return -EIOCBQUEUED;
9411 	} else {
9412 		if (!refcount_dec_and_test(&priv->pending_refs))
9413 			wait_for_completion_io(&sync_reads);
9414 		/* See btrfs_encoded_read_endio() for ordering. */
9415 		return blk_status_to_errno(READ_ONCE(priv->status));
9416 	}
9417 }
9418 
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)9419 ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter,
9420 				   u64 start, u64 lockend,
9421 				   struct extent_state **cached_state,
9422 				   u64 disk_bytenr, u64 disk_io_size,
9423 				   size_t count, bool compressed, bool *unlocked)
9424 {
9425 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9426 	struct extent_io_tree *io_tree = &inode->io_tree;
9427 	struct page **pages;
9428 	unsigned long nr_pages, i;
9429 	u64 cur;
9430 	size_t page_offset;
9431 	ssize_t ret;
9432 
9433 	nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
9434 	pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
9435 	if (!pages)
9436 		return -ENOMEM;
9437 	ret = btrfs_alloc_page_array(nr_pages, pages, false);
9438 	if (ret) {
9439 		ret = -ENOMEM;
9440 		goto out;
9441 		}
9442 
9443 	ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
9444 						    disk_io_size, pages, NULL);
9445 	if (ret)
9446 		goto out;
9447 
9448 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9449 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9450 	*unlocked = true;
9451 
9452 	if (compressed) {
9453 		i = 0;
9454 		page_offset = 0;
9455 	} else {
9456 		i = (iocb->ki_pos - start) >> PAGE_SHIFT;
9457 		page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
9458 	}
9459 	cur = 0;
9460 	while (cur < count) {
9461 		size_t bytes = min_t(size_t, count - cur,
9462 				     PAGE_SIZE - page_offset);
9463 
9464 		if (copy_page_to_iter(pages[i], page_offset, bytes,
9465 				      iter) != bytes) {
9466 			ret = -EFAULT;
9467 			goto out;
9468 		}
9469 		i++;
9470 		cur += bytes;
9471 		page_offset = 0;
9472 	}
9473 	ret = count;
9474 out:
9475 	for (i = 0; i < nr_pages; i++) {
9476 		if (pages[i])
9477 			__free_page(pages[i]);
9478 	}
9479 	kfree(pages);
9480 	return ret;
9481 }
9482 
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)9483 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
9484 			   struct btrfs_ioctl_encoded_io_args *encoded,
9485 			   struct extent_state **cached_state,
9486 			   u64 *disk_bytenr, u64 *disk_io_size)
9487 {
9488 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9489 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
9490 	struct extent_io_tree *io_tree = &inode->io_tree;
9491 	ssize_t ret;
9492 	size_t count = iov_iter_count(iter);
9493 	u64 start, lockend;
9494 	struct extent_map *em;
9495 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9496 	bool unlocked = false;
9497 
9498 	file_accessed(iocb->ki_filp);
9499 
9500 	ret = btrfs_inode_lock(inode,
9501 			       BTRFS_ILOCK_SHARED | (nowait ? BTRFS_ILOCK_TRY : 0));
9502 	if (ret)
9503 		return ret;
9504 
9505 	if (iocb->ki_pos >= inode->vfs_inode.i_size) {
9506 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9507 		return 0;
9508 	}
9509 	start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
9510 	/*
9511 	 * We don't know how long the extent containing iocb->ki_pos is, but if
9512 	 * it's compressed we know that it won't be longer than this.
9513 	 */
9514 	lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
9515 
9516 	if (nowait) {
9517 		struct btrfs_ordered_extent *ordered;
9518 
9519 		if (filemap_range_needs_writeback(inode->vfs_inode.i_mapping,
9520 						  start, lockend)) {
9521 			ret = -EAGAIN;
9522 			goto out_unlock_inode;
9523 		}
9524 
9525 		if (!btrfs_try_lock_extent(io_tree, start, lockend, cached_state)) {
9526 			ret = -EAGAIN;
9527 			goto out_unlock_inode;
9528 		}
9529 
9530 		ordered = btrfs_lookup_ordered_range(inode, start,
9531 						     lockend - start + 1);
9532 		if (ordered) {
9533 			btrfs_put_ordered_extent(ordered);
9534 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9535 			ret = -EAGAIN;
9536 			goto out_unlock_inode;
9537 		}
9538 	} else {
9539 		for (;;) {
9540 			struct btrfs_ordered_extent *ordered;
9541 
9542 			ret = btrfs_wait_ordered_range(inode, start,
9543 						       lockend - start + 1);
9544 			if (ret)
9545 				goto out_unlock_inode;
9546 
9547 			btrfs_lock_extent(io_tree, start, lockend, cached_state);
9548 			ordered = btrfs_lookup_ordered_range(inode, start,
9549 							     lockend - start + 1);
9550 			if (!ordered)
9551 				break;
9552 			btrfs_put_ordered_extent(ordered);
9553 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9554 			cond_resched();
9555 		}
9556 	}
9557 
9558 	em = btrfs_get_extent(inode, NULL, start, lockend - start + 1);
9559 	if (IS_ERR(em)) {
9560 		ret = PTR_ERR(em);
9561 		goto out_unlock_extent;
9562 	}
9563 
9564 	if (em->disk_bytenr == EXTENT_MAP_INLINE) {
9565 		u64 extent_start = em->start;
9566 
9567 		/*
9568 		 * For inline extents we get everything we need out of the
9569 		 * extent item.
9570 		 */
9571 		btrfs_free_extent_map(em);
9572 		em = NULL;
9573 		ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
9574 						cached_state, extent_start,
9575 						count, encoded, &unlocked);
9576 		goto out_unlock_extent;
9577 	}
9578 
9579 	/*
9580 	 * We only want to return up to EOF even if the extent extends beyond
9581 	 * that.
9582 	 */
9583 	encoded->len = min_t(u64, btrfs_extent_map_end(em),
9584 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9585 	if (em->disk_bytenr == EXTENT_MAP_HOLE ||
9586 	    (em->flags & EXTENT_FLAG_PREALLOC)) {
9587 		*disk_bytenr = EXTENT_MAP_HOLE;
9588 		count = min_t(u64, count, encoded->len);
9589 		encoded->len = count;
9590 		encoded->unencoded_len = count;
9591 	} else if (btrfs_extent_map_is_compressed(em)) {
9592 		*disk_bytenr = em->disk_bytenr;
9593 		/*
9594 		 * Bail if the buffer isn't large enough to return the whole
9595 		 * compressed extent.
9596 		 */
9597 		if (em->disk_num_bytes > count) {
9598 			ret = -ENOBUFS;
9599 			goto out_em;
9600 		}
9601 		*disk_io_size = em->disk_num_bytes;
9602 		count = em->disk_num_bytes;
9603 		encoded->unencoded_len = em->ram_bytes;
9604 		encoded->unencoded_offset = iocb->ki_pos - (em->start - em->offset);
9605 		ret = btrfs_encoded_io_compression_from_extent(fs_info,
9606 					       btrfs_extent_map_compression(em));
9607 		if (ret < 0)
9608 			goto out_em;
9609 		encoded->compression = ret;
9610 	} else {
9611 		*disk_bytenr = btrfs_extent_map_block_start(em) + (start - em->start);
9612 		if (encoded->len > count)
9613 			encoded->len = count;
9614 		/*
9615 		 * Don't read beyond what we locked. This also limits the page
9616 		 * allocations that we'll do.
9617 		 */
9618 		*disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
9619 		count = start + *disk_io_size - iocb->ki_pos;
9620 		encoded->len = count;
9621 		encoded->unencoded_len = count;
9622 		*disk_io_size = ALIGN(*disk_io_size, fs_info->sectorsize);
9623 	}
9624 	btrfs_free_extent_map(em);
9625 	em = NULL;
9626 
9627 	if (*disk_bytenr == EXTENT_MAP_HOLE) {
9628 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9629 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9630 		unlocked = true;
9631 		ret = iov_iter_zero(count, iter);
9632 		if (ret != count)
9633 			ret = -EFAULT;
9634 	} else {
9635 		ret = -EIOCBQUEUED;
9636 		goto out_unlock_extent;
9637 	}
9638 
9639 out_em:
9640 	btrfs_free_extent_map(em);
9641 out_unlock_extent:
9642 	/* Leave inode and extent locked if we need to do a read. */
9643 	if (!unlocked && ret != -EIOCBQUEUED)
9644 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9645 out_unlock_inode:
9646 	if (!unlocked && ret != -EIOCBQUEUED)
9647 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9648 	return ret;
9649 }
9650 
btrfs_do_encoded_write(struct kiocb * iocb,struct iov_iter * from,const struct btrfs_ioctl_encoded_io_args * encoded)9651 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
9652 			       const struct btrfs_ioctl_encoded_io_args *encoded)
9653 {
9654 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9655 	struct btrfs_root *root = inode->root;
9656 	struct btrfs_fs_info *fs_info = root->fs_info;
9657 	struct extent_io_tree *io_tree = &inode->io_tree;
9658 	struct extent_changeset *data_reserved = NULL;
9659 	struct extent_state *cached_state = NULL;
9660 	struct btrfs_ordered_extent *ordered;
9661 	struct btrfs_file_extent file_extent;
9662 	int compression;
9663 	size_t orig_count;
9664 	u64 start, end;
9665 	u64 num_bytes, ram_bytes, disk_num_bytes;
9666 	unsigned long nr_folios, i;
9667 	struct folio **folios;
9668 	struct btrfs_key ins;
9669 	bool extent_reserved = false;
9670 	struct extent_map *em;
9671 	ssize_t ret;
9672 
9673 	switch (encoded->compression) {
9674 	case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
9675 		compression = BTRFS_COMPRESS_ZLIB;
9676 		break;
9677 	case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
9678 		compression = BTRFS_COMPRESS_ZSTD;
9679 		break;
9680 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
9681 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
9682 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
9683 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
9684 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
9685 		/* The sector size must match for LZO. */
9686 		if (encoded->compression -
9687 		    BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
9688 		    fs_info->sectorsize_bits)
9689 			return -EINVAL;
9690 		compression = BTRFS_COMPRESS_LZO;
9691 		break;
9692 	default:
9693 		return -EINVAL;
9694 	}
9695 	if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
9696 		return -EINVAL;
9697 
9698 	/*
9699 	 * Compressed extents should always have checksums, so error out if we
9700 	 * have a NOCOW file or inode was created while mounted with NODATASUM.
9701 	 */
9702 	if (inode->flags & BTRFS_INODE_NODATASUM)
9703 		return -EINVAL;
9704 
9705 	orig_count = iov_iter_count(from);
9706 
9707 	/* The extent size must be sane. */
9708 	if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
9709 	    orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
9710 		return -EINVAL;
9711 
9712 	/*
9713 	 * The compressed data must be smaller than the decompressed data.
9714 	 *
9715 	 * It's of course possible for data to compress to larger or the same
9716 	 * size, but the buffered I/O path falls back to no compression for such
9717 	 * data, and we don't want to break any assumptions by creating these
9718 	 * extents.
9719 	 *
9720 	 * Note that this is less strict than the current check we have that the
9721 	 * compressed data must be at least one sector smaller than the
9722 	 * decompressed data. We only want to enforce the weaker requirement
9723 	 * from old kernels that it is at least one byte smaller.
9724 	 */
9725 	if (orig_count >= encoded->unencoded_len)
9726 		return -EINVAL;
9727 
9728 	/* The extent must start on a sector boundary. */
9729 	start = iocb->ki_pos;
9730 	if (!IS_ALIGNED(start, fs_info->sectorsize))
9731 		return -EINVAL;
9732 
9733 	/*
9734 	 * The extent must end on a sector boundary. However, we allow a write
9735 	 * which ends at or extends i_size to have an unaligned length; we round
9736 	 * up the extent size and set i_size to the unaligned end.
9737 	 */
9738 	if (start + encoded->len < inode->vfs_inode.i_size &&
9739 	    !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
9740 		return -EINVAL;
9741 
9742 	/* Finally, the offset in the unencoded data must be sector-aligned. */
9743 	if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
9744 		return -EINVAL;
9745 
9746 	num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
9747 	ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
9748 	end = start + num_bytes - 1;
9749 
9750 	/*
9751 	 * If the extent cannot be inline, the compressed data on disk must be
9752 	 * sector-aligned. For convenience, we extend it with zeroes if it
9753 	 * isn't.
9754 	 */
9755 	disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
9756 	nr_folios = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
9757 	folios = kvcalloc(nr_folios, sizeof(struct folio *), GFP_KERNEL_ACCOUNT);
9758 	if (!folios)
9759 		return -ENOMEM;
9760 	for (i = 0; i < nr_folios; i++) {
9761 		size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
9762 		char *kaddr;
9763 
9764 		folios[i] = folio_alloc(GFP_KERNEL_ACCOUNT, 0);
9765 		if (!folios[i]) {
9766 			ret = -ENOMEM;
9767 			goto out_folios;
9768 		}
9769 		kaddr = kmap_local_folio(folios[i], 0);
9770 		if (copy_from_iter(kaddr, bytes, from) != bytes) {
9771 			kunmap_local(kaddr);
9772 			ret = -EFAULT;
9773 			goto out_folios;
9774 		}
9775 		if (bytes < PAGE_SIZE)
9776 			memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
9777 		kunmap_local(kaddr);
9778 	}
9779 
9780 	for (;;) {
9781 		struct btrfs_ordered_extent *ordered;
9782 
9783 		ret = btrfs_wait_ordered_range(inode, start, num_bytes);
9784 		if (ret)
9785 			goto out_folios;
9786 		ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
9787 						    start >> PAGE_SHIFT,
9788 						    end >> PAGE_SHIFT);
9789 		if (ret)
9790 			goto out_folios;
9791 		btrfs_lock_extent(io_tree, start, end, &cached_state);
9792 		ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
9793 		if (!ordered &&
9794 		    !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
9795 			break;
9796 		if (ordered)
9797 			btrfs_put_ordered_extent(ordered);
9798 		btrfs_unlock_extent(io_tree, start, end, &cached_state);
9799 		cond_resched();
9800 	}
9801 
9802 	/*
9803 	 * We don't use the higher-level delalloc space functions because our
9804 	 * num_bytes and disk_num_bytes are different.
9805 	 */
9806 	ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
9807 	if (ret)
9808 		goto out_unlock;
9809 	ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
9810 	if (ret)
9811 		goto out_free_data_space;
9812 	ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
9813 					      false);
9814 	if (ret)
9815 		goto out_qgroup_free_data;
9816 
9817 	/* Try an inline extent first. */
9818 	if (encoded->unencoded_len == encoded->len &&
9819 	    encoded->unencoded_offset == 0 &&
9820 	    can_cow_file_range_inline(inode, start, encoded->len, orig_count)) {
9821 		ret = __cow_file_range_inline(inode, encoded->len,
9822 					      orig_count, compression, folios[0],
9823 					      true);
9824 		if (ret <= 0) {
9825 			if (ret == 0)
9826 				ret = orig_count;
9827 			goto out_delalloc_release;
9828 		}
9829 	}
9830 
9831 	ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
9832 				   disk_num_bytes, 0, 0, &ins, 1, 1);
9833 	if (ret)
9834 		goto out_delalloc_release;
9835 	extent_reserved = true;
9836 
9837 	file_extent.disk_bytenr = ins.objectid;
9838 	file_extent.disk_num_bytes = ins.offset;
9839 	file_extent.num_bytes = num_bytes;
9840 	file_extent.ram_bytes = ram_bytes;
9841 	file_extent.offset = encoded->unencoded_offset;
9842 	file_extent.compression = compression;
9843 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
9844 	if (IS_ERR(em)) {
9845 		ret = PTR_ERR(em);
9846 		goto out_free_reserved;
9847 	}
9848 	btrfs_free_extent_map(em);
9849 
9850 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
9851 				       (1U << BTRFS_ORDERED_ENCODED) |
9852 				       (1U << BTRFS_ORDERED_COMPRESSED));
9853 	if (IS_ERR(ordered)) {
9854 		btrfs_drop_extent_map_range(inode, start, end, false);
9855 		ret = PTR_ERR(ordered);
9856 		goto out_free_reserved;
9857 	}
9858 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9859 
9860 	if (start + encoded->len > inode->vfs_inode.i_size)
9861 		i_size_write(&inode->vfs_inode, start + encoded->len);
9862 
9863 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
9864 
9865 	btrfs_delalloc_release_extents(inode, num_bytes);
9866 
9867 	btrfs_submit_compressed_write(ordered, folios, nr_folios, 0, false);
9868 	ret = orig_count;
9869 	goto out;
9870 
9871 out_free_reserved:
9872 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9873 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
9874 out_delalloc_release:
9875 	btrfs_delalloc_release_extents(inode, num_bytes);
9876 	btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
9877 out_qgroup_free_data:
9878 	if (ret < 0)
9879 		btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
9880 out_free_data_space:
9881 	/*
9882 	 * If btrfs_reserve_extent() succeeded, then we already decremented
9883 	 * bytes_may_use.
9884 	 */
9885 	if (!extent_reserved)
9886 		btrfs_free_reserved_data_space_noquota(inode, disk_num_bytes);
9887 out_unlock:
9888 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
9889 out_folios:
9890 	for (i = 0; i < nr_folios; i++) {
9891 		if (folios[i])
9892 			folio_put(folios[i]);
9893 	}
9894 	kvfree(folios);
9895 out:
9896 	if (ret >= 0)
9897 		iocb->ki_pos += encoded->len;
9898 	return ret;
9899 }
9900 
9901 #ifdef CONFIG_SWAP
9902 /*
9903  * Add an entry indicating a block group or device which is pinned by a
9904  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9905  * negative errno on failure.
9906  */
btrfs_add_swapfile_pin(struct inode * inode,void * ptr,bool is_block_group)9907 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9908 				  bool is_block_group)
9909 {
9910 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9911 	struct btrfs_swapfile_pin *sp, *entry;
9912 	struct rb_node **p;
9913 	struct rb_node *parent = NULL;
9914 
9915 	sp = kmalloc(sizeof(*sp), GFP_NOFS);
9916 	if (!sp)
9917 		return -ENOMEM;
9918 	sp->ptr = ptr;
9919 	sp->inode = inode;
9920 	sp->is_block_group = is_block_group;
9921 	sp->bg_extent_count = 1;
9922 
9923 	spin_lock(&fs_info->swapfile_pins_lock);
9924 	p = &fs_info->swapfile_pins.rb_node;
9925 	while (*p) {
9926 		parent = *p;
9927 		entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9928 		if (sp->ptr < entry->ptr ||
9929 		    (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9930 			p = &(*p)->rb_left;
9931 		} else if (sp->ptr > entry->ptr ||
9932 			   (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9933 			p = &(*p)->rb_right;
9934 		} else {
9935 			if (is_block_group)
9936 				entry->bg_extent_count++;
9937 			spin_unlock(&fs_info->swapfile_pins_lock);
9938 			kfree(sp);
9939 			return 1;
9940 		}
9941 	}
9942 	rb_link_node(&sp->node, parent, p);
9943 	rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9944 	spin_unlock(&fs_info->swapfile_pins_lock);
9945 	return 0;
9946 }
9947 
9948 /* Free all of the entries pinned by this swapfile. */
btrfs_free_swapfile_pins(struct inode * inode)9949 static void btrfs_free_swapfile_pins(struct inode *inode)
9950 {
9951 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9952 	struct btrfs_swapfile_pin *sp;
9953 	struct rb_node *node, *next;
9954 
9955 	spin_lock(&fs_info->swapfile_pins_lock);
9956 	node = rb_first(&fs_info->swapfile_pins);
9957 	while (node) {
9958 		next = rb_next(node);
9959 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9960 		if (sp->inode == inode) {
9961 			rb_erase(&sp->node, &fs_info->swapfile_pins);
9962 			if (sp->is_block_group) {
9963 				btrfs_dec_block_group_swap_extents(sp->ptr,
9964 							   sp->bg_extent_count);
9965 				btrfs_put_block_group(sp->ptr);
9966 			}
9967 			kfree(sp);
9968 		}
9969 		node = next;
9970 	}
9971 	spin_unlock(&fs_info->swapfile_pins_lock);
9972 }
9973 
9974 struct btrfs_swap_info {
9975 	u64 start;
9976 	u64 block_start;
9977 	u64 block_len;
9978 	u64 lowest_ppage;
9979 	u64 highest_ppage;
9980 	unsigned long nr_pages;
9981 	int nr_extents;
9982 };
9983 
btrfs_add_swap_extent(struct swap_info_struct * sis,struct btrfs_swap_info * bsi)9984 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9985 				 struct btrfs_swap_info *bsi)
9986 {
9987 	unsigned long nr_pages;
9988 	unsigned long max_pages;
9989 	u64 first_ppage, first_ppage_reported, next_ppage;
9990 	int ret;
9991 
9992 	/*
9993 	 * Our swapfile may have had its size extended after the swap header was
9994 	 * written. In that case activating the swapfile should not go beyond
9995 	 * the max size set in the swap header.
9996 	 */
9997 	if (bsi->nr_pages >= sis->max)
9998 		return 0;
9999 
10000 	max_pages = sis->max - bsi->nr_pages;
10001 	first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10002 	next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10003 
10004 	if (first_ppage >= next_ppage)
10005 		return 0;
10006 	nr_pages = next_ppage - first_ppage;
10007 	nr_pages = min(nr_pages, max_pages);
10008 
10009 	first_ppage_reported = first_ppage;
10010 	if (bsi->start == 0)
10011 		first_ppage_reported++;
10012 	if (bsi->lowest_ppage > first_ppage_reported)
10013 		bsi->lowest_ppage = first_ppage_reported;
10014 	if (bsi->highest_ppage < (next_ppage - 1))
10015 		bsi->highest_ppage = next_ppage - 1;
10016 
10017 	ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10018 	if (ret < 0)
10019 		return ret;
10020 	bsi->nr_extents += ret;
10021 	bsi->nr_pages += nr_pages;
10022 	return 0;
10023 }
10024 
btrfs_swap_deactivate(struct file * file)10025 static void btrfs_swap_deactivate(struct file *file)
10026 {
10027 	struct inode *inode = file_inode(file);
10028 
10029 	btrfs_free_swapfile_pins(inode);
10030 	atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10031 }
10032 
btrfs_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)10033 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10034 			       sector_t *span)
10035 {
10036 	struct inode *inode = file_inode(file);
10037 	struct btrfs_root *root = BTRFS_I(inode)->root;
10038 	struct btrfs_fs_info *fs_info = root->fs_info;
10039 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10040 	struct extent_state *cached_state = NULL;
10041 	struct btrfs_chunk_map *map = NULL;
10042 	struct btrfs_device *device = NULL;
10043 	struct btrfs_swap_info bsi = {
10044 		.lowest_ppage = (sector_t)-1ULL,
10045 	};
10046 	struct btrfs_backref_share_check_ctx *backref_ctx = NULL;
10047 	struct btrfs_path *path = NULL;
10048 	int ret = 0;
10049 	u64 isize;
10050 	u64 prev_extent_end = 0;
10051 
10052 	/*
10053 	 * Acquire the inode's mmap lock to prevent races with memory mapped
10054 	 * writes, as they could happen after we flush delalloc below and before
10055 	 * we lock the extent range further below. The inode was already locked
10056 	 * up in the call chain.
10057 	 */
10058 	btrfs_assert_inode_locked(BTRFS_I(inode));
10059 	down_write(&BTRFS_I(inode)->i_mmap_lock);
10060 
10061 	/*
10062 	 * If the swap file was just created, make sure delalloc is done. If the
10063 	 * file changes again after this, the user is doing something stupid and
10064 	 * we don't really care.
10065 	 */
10066 	ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
10067 	if (ret)
10068 		goto out_unlock_mmap;
10069 
10070 	/*
10071 	 * The inode is locked, so these flags won't change after we check them.
10072 	 */
10073 	if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10074 		btrfs_warn(fs_info, "swapfile must not be compressed");
10075 		ret = -EINVAL;
10076 		goto out_unlock_mmap;
10077 	}
10078 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10079 		btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10080 		ret = -EINVAL;
10081 		goto out_unlock_mmap;
10082 	}
10083 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10084 		btrfs_warn(fs_info, "swapfile must not be checksummed");
10085 		ret = -EINVAL;
10086 		goto out_unlock_mmap;
10087 	}
10088 
10089 	path = btrfs_alloc_path();
10090 	backref_ctx = btrfs_alloc_backref_share_check_ctx();
10091 	if (!path || !backref_ctx) {
10092 		ret = -ENOMEM;
10093 		goto out_unlock_mmap;
10094 	}
10095 
10096 	/*
10097 	 * Balance or device remove/replace/resize can move stuff around from
10098 	 * under us. The exclop protection makes sure they aren't running/won't
10099 	 * run concurrently while we are mapping the swap extents, and
10100 	 * fs_info->swapfile_pins prevents them from running while the swap
10101 	 * file is active and moving the extents. Note that this also prevents
10102 	 * a concurrent device add which isn't actually necessary, but it's not
10103 	 * really worth the trouble to allow it.
10104 	 */
10105 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10106 		btrfs_warn(fs_info,
10107 	   "cannot activate swapfile while exclusive operation is running");
10108 		ret = -EBUSY;
10109 		goto out_unlock_mmap;
10110 	}
10111 
10112 	/*
10113 	 * Prevent snapshot creation while we are activating the swap file.
10114 	 * We do not want to race with snapshot creation. If snapshot creation
10115 	 * already started before we bumped nr_swapfiles from 0 to 1 and
10116 	 * completes before the first write into the swap file after it is
10117 	 * activated, than that write would fallback to COW.
10118 	 */
10119 	if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10120 		btrfs_exclop_finish(fs_info);
10121 		btrfs_warn(fs_info,
10122 	   "cannot activate swapfile because snapshot creation is in progress");
10123 		ret = -EINVAL;
10124 		goto out_unlock_mmap;
10125 	}
10126 	/*
10127 	 * Snapshots can create extents which require COW even if NODATACOW is
10128 	 * set. We use this counter to prevent snapshots. We must increment it
10129 	 * before walking the extents because we don't want a concurrent
10130 	 * snapshot to run after we've already checked the extents.
10131 	 *
10132 	 * It is possible that subvolume is marked for deletion but still not
10133 	 * removed yet. To prevent this race, we check the root status before
10134 	 * activating the swapfile.
10135 	 */
10136 	spin_lock(&root->root_item_lock);
10137 	if (btrfs_root_dead(root)) {
10138 		spin_unlock(&root->root_item_lock);
10139 
10140 		btrfs_drew_write_unlock(&root->snapshot_lock);
10141 		btrfs_exclop_finish(fs_info);
10142 		btrfs_warn(fs_info,
10143 		"cannot activate swapfile because subvolume %llu is being deleted",
10144 			btrfs_root_id(root));
10145 		ret = -EPERM;
10146 		goto out_unlock_mmap;
10147 	}
10148 	atomic_inc(&root->nr_swapfiles);
10149 	spin_unlock(&root->root_item_lock);
10150 
10151 	isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10152 
10153 	btrfs_lock_extent(io_tree, 0, isize - 1, &cached_state);
10154 	while (prev_extent_end < isize) {
10155 		struct btrfs_key key;
10156 		struct extent_buffer *leaf;
10157 		struct btrfs_file_extent_item *ei;
10158 		struct btrfs_block_group *bg;
10159 		u64 logical_block_start;
10160 		u64 physical_block_start;
10161 		u64 extent_gen;
10162 		u64 disk_bytenr;
10163 		u64 len;
10164 
10165 		key.objectid = btrfs_ino(BTRFS_I(inode));
10166 		key.type = BTRFS_EXTENT_DATA_KEY;
10167 		key.offset = prev_extent_end;
10168 
10169 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
10170 		if (ret < 0)
10171 			goto out;
10172 
10173 		/*
10174 		 * If key not found it means we have an implicit hole (NO_HOLES
10175 		 * is enabled).
10176 		 */
10177 		if (ret > 0) {
10178 			btrfs_warn(fs_info, "swapfile must not have holes");
10179 			ret = -EINVAL;
10180 			goto out;
10181 		}
10182 
10183 		leaf = path->nodes[0];
10184 		ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10185 
10186 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
10187 			/*
10188 			 * It's unlikely we'll ever actually find ourselves
10189 			 * here, as a file small enough to fit inline won't be
10190 			 * big enough to store more than the swap header, but in
10191 			 * case something changes in the future, let's catch it
10192 			 * here rather than later.
10193 			 */
10194 			btrfs_warn(fs_info, "swapfile must not be inline");
10195 			ret = -EINVAL;
10196 			goto out;
10197 		}
10198 
10199 		if (btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
10200 			btrfs_warn(fs_info, "swapfile must not be compressed");
10201 			ret = -EINVAL;
10202 			goto out;
10203 		}
10204 
10205 		disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
10206 		if (disk_bytenr == 0) {
10207 			btrfs_warn(fs_info, "swapfile must not have holes");
10208 			ret = -EINVAL;
10209 			goto out;
10210 		}
10211 
10212 		logical_block_start = disk_bytenr + btrfs_file_extent_offset(leaf, ei);
10213 		extent_gen = btrfs_file_extent_generation(leaf, ei);
10214 		prev_extent_end = btrfs_file_extent_end(path);
10215 
10216 		if (prev_extent_end > isize)
10217 			len = isize - key.offset;
10218 		else
10219 			len = btrfs_file_extent_num_bytes(leaf, ei);
10220 
10221 		backref_ctx->curr_leaf_bytenr = leaf->start;
10222 
10223 		/*
10224 		 * Don't need the path anymore, release to avoid deadlocks when
10225 		 * calling btrfs_is_data_extent_shared() because when joining a
10226 		 * transaction it can block waiting for the current one's commit
10227 		 * which in turn may be trying to lock the same leaf to flush
10228 		 * delayed items for example.
10229 		 */
10230 		btrfs_release_path(path);
10231 
10232 		ret = btrfs_is_data_extent_shared(BTRFS_I(inode), disk_bytenr,
10233 						  extent_gen, backref_ctx);
10234 		if (ret < 0) {
10235 			goto out;
10236 		} else if (ret > 0) {
10237 			btrfs_warn(fs_info,
10238 				   "swapfile must not be copy-on-write");
10239 			ret = -EINVAL;
10240 			goto out;
10241 		}
10242 
10243 		map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10244 		if (IS_ERR(map)) {
10245 			ret = PTR_ERR(map);
10246 			goto out;
10247 		}
10248 
10249 		if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10250 			btrfs_warn(fs_info,
10251 				   "swapfile must have single data profile");
10252 			ret = -EINVAL;
10253 			goto out;
10254 		}
10255 
10256 		if (device == NULL) {
10257 			device = map->stripes[0].dev;
10258 			ret = btrfs_add_swapfile_pin(inode, device, false);
10259 			if (ret == 1)
10260 				ret = 0;
10261 			else if (ret)
10262 				goto out;
10263 		} else if (device != map->stripes[0].dev) {
10264 			btrfs_warn(fs_info, "swapfile must be on one device");
10265 			ret = -EINVAL;
10266 			goto out;
10267 		}
10268 
10269 		physical_block_start = (map->stripes[0].physical +
10270 					(logical_block_start - map->start));
10271 		btrfs_free_chunk_map(map);
10272 		map = NULL;
10273 
10274 		bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10275 		if (!bg) {
10276 			btrfs_warn(fs_info,
10277 			   "could not find block group containing swapfile");
10278 			ret = -EINVAL;
10279 			goto out;
10280 		}
10281 
10282 		if (!btrfs_inc_block_group_swap_extents(bg)) {
10283 			btrfs_warn(fs_info,
10284 			   "block group for swapfile at %llu is read-only%s",
10285 			   bg->start,
10286 			   atomic_read(&fs_info->scrubs_running) ?
10287 				       " (scrub running)" : "");
10288 			btrfs_put_block_group(bg);
10289 			ret = -EINVAL;
10290 			goto out;
10291 		}
10292 
10293 		ret = btrfs_add_swapfile_pin(inode, bg, true);
10294 		if (ret) {
10295 			btrfs_put_block_group(bg);
10296 			if (ret == 1)
10297 				ret = 0;
10298 			else
10299 				goto out;
10300 		}
10301 
10302 		if (bsi.block_len &&
10303 		    bsi.block_start + bsi.block_len == physical_block_start) {
10304 			bsi.block_len += len;
10305 		} else {
10306 			if (bsi.block_len) {
10307 				ret = btrfs_add_swap_extent(sis, &bsi);
10308 				if (ret)
10309 					goto out;
10310 			}
10311 			bsi.start = key.offset;
10312 			bsi.block_start = physical_block_start;
10313 			bsi.block_len = len;
10314 		}
10315 
10316 		if (fatal_signal_pending(current)) {
10317 			ret = -EINTR;
10318 			goto out;
10319 		}
10320 
10321 		cond_resched();
10322 	}
10323 
10324 	if (bsi.block_len)
10325 		ret = btrfs_add_swap_extent(sis, &bsi);
10326 
10327 out:
10328 	if (!IS_ERR_OR_NULL(map))
10329 		btrfs_free_chunk_map(map);
10330 
10331 	btrfs_unlock_extent(io_tree, 0, isize - 1, &cached_state);
10332 
10333 	if (ret)
10334 		btrfs_swap_deactivate(file);
10335 
10336 	btrfs_drew_write_unlock(&root->snapshot_lock);
10337 
10338 	btrfs_exclop_finish(fs_info);
10339 
10340 out_unlock_mmap:
10341 	up_write(&BTRFS_I(inode)->i_mmap_lock);
10342 	btrfs_free_backref_share_ctx(backref_ctx);
10343 	btrfs_free_path(path);
10344 	if (ret)
10345 		return ret;
10346 
10347 	if (device)
10348 		sis->bdev = device->bdev;
10349 	*span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10350 	sis->max = bsi.nr_pages;
10351 	sis->pages = bsi.nr_pages - 1;
10352 	return bsi.nr_extents;
10353 }
10354 #else
btrfs_swap_deactivate(struct file * file)10355 static void btrfs_swap_deactivate(struct file *file)
10356 {
10357 }
10358 
btrfs_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)10359 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10360 			       sector_t *span)
10361 {
10362 	return -EOPNOTSUPP;
10363 }
10364 #endif
10365 
10366 /*
10367  * Update the number of bytes used in the VFS' inode. When we replace extents in
10368  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10369  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10370  * always get a correct value.
10371  */
btrfs_update_inode_bytes(struct btrfs_inode * inode,const u64 add_bytes,const u64 del_bytes)10372 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10373 			      const u64 add_bytes,
10374 			      const u64 del_bytes)
10375 {
10376 	if (add_bytes == del_bytes)
10377 		return;
10378 
10379 	spin_lock(&inode->lock);
10380 	if (del_bytes > 0)
10381 		inode_sub_bytes(&inode->vfs_inode, del_bytes);
10382 	if (add_bytes > 0)
10383 		inode_add_bytes(&inode->vfs_inode, add_bytes);
10384 	spin_unlock(&inode->lock);
10385 }
10386 
10387 /*
10388  * Verify that there are no ordered extents for a given file range.
10389  *
10390  * @inode:   The target inode.
10391  * @start:   Start offset of the file range, should be sector size aligned.
10392  * @end:     End offset (inclusive) of the file range, its value +1 should be
10393  *           sector size aligned.
10394  *
10395  * This should typically be used for cases where we locked an inode's VFS lock in
10396  * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10397  * we have flushed all delalloc in the range, we have waited for all ordered
10398  * extents in the range to complete and finally we have locked the file range in
10399  * the inode's io_tree.
10400  */
btrfs_assert_inode_range_clean(struct btrfs_inode * inode,u64 start,u64 end)10401 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10402 {
10403 	struct btrfs_root *root = inode->root;
10404 	struct btrfs_ordered_extent *ordered;
10405 
10406 	if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10407 		return;
10408 
10409 	ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10410 	if (ordered) {
10411 		btrfs_err(root->fs_info,
10412 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10413 			  start, end, btrfs_ino(inode), btrfs_root_id(root),
10414 			  ordered->file_offset,
10415 			  ordered->file_offset + ordered->num_bytes - 1);
10416 		btrfs_put_ordered_extent(ordered);
10417 	}
10418 
10419 	ASSERT(ordered == NULL);
10420 }
10421 
10422 /*
10423  * Find the first inode with a minimum number.
10424  *
10425  * @root:	The root to search for.
10426  * @min_ino:	The minimum inode number.
10427  *
10428  * Find the first inode in the @root with a number >= @min_ino and return it.
10429  * Returns NULL if no such inode found.
10430  */
btrfs_find_first_inode(struct btrfs_root * root,u64 min_ino)10431 struct btrfs_inode *btrfs_find_first_inode(struct btrfs_root *root, u64 min_ino)
10432 {
10433 	struct btrfs_inode *inode;
10434 	unsigned long from = min_ino;
10435 
10436 	xa_lock(&root->inodes);
10437 	while (true) {
10438 		inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
10439 		if (!inode)
10440 			break;
10441 		if (igrab(&inode->vfs_inode))
10442 			break;
10443 
10444 		from = btrfs_ino(inode) + 1;
10445 		cond_resched_lock(&root->inodes.xa_lock);
10446 	}
10447 	xa_unlock(&root->inodes);
10448 
10449 	return inode;
10450 }
10451 
10452 static const struct inode_operations btrfs_dir_inode_operations = {
10453 	.getattr	= btrfs_getattr,
10454 	.lookup		= btrfs_lookup,
10455 	.create		= btrfs_create,
10456 	.unlink		= btrfs_unlink,
10457 	.link		= btrfs_link,
10458 	.mkdir		= btrfs_mkdir,
10459 	.rmdir		= btrfs_rmdir,
10460 	.rename		= btrfs_rename2,
10461 	.symlink	= btrfs_symlink,
10462 	.setattr	= btrfs_setattr,
10463 	.mknod		= btrfs_mknod,
10464 	.listxattr	= btrfs_listxattr,
10465 	.permission	= btrfs_permission,
10466 	.get_inode_acl	= btrfs_get_acl,
10467 	.set_acl	= btrfs_set_acl,
10468 	.update_time	= btrfs_update_time,
10469 	.tmpfile        = btrfs_tmpfile,
10470 	.fileattr_get	= btrfs_fileattr_get,
10471 	.fileattr_set	= btrfs_fileattr_set,
10472 };
10473 
10474 static const struct file_operations btrfs_dir_file_operations = {
10475 	.llseek		= btrfs_dir_llseek,
10476 	.read		= generic_read_dir,
10477 	.iterate_shared	= btrfs_real_readdir,
10478 	.open		= btrfs_opendir,
10479 	.unlocked_ioctl	= btrfs_ioctl,
10480 #ifdef CONFIG_COMPAT
10481 	.compat_ioctl	= btrfs_compat_ioctl,
10482 #endif
10483 	.release        = btrfs_release_file,
10484 	.fsync		= btrfs_sync_file,
10485 };
10486 
10487 /*
10488  * btrfs doesn't support the bmap operation because swapfiles
10489  * use bmap to make a mapping of extents in the file.  They assume
10490  * these extents won't change over the life of the file and they
10491  * use the bmap result to do IO directly to the drive.
10492  *
10493  * the btrfs bmap call would return logical addresses that aren't
10494  * suitable for IO and they also will change frequently as COW
10495  * operations happen.  So, swapfile + btrfs == corruption.
10496  *
10497  * For now we're avoiding this by dropping bmap.
10498  */
10499 static const struct address_space_operations btrfs_aops = {
10500 	.read_folio	= btrfs_read_folio,
10501 	.writepages	= btrfs_writepages,
10502 	.readahead	= btrfs_readahead,
10503 	.invalidate_folio = btrfs_invalidate_folio,
10504 	.launder_folio	= btrfs_launder_folio,
10505 	.release_folio	= btrfs_release_folio,
10506 	.migrate_folio	= btrfs_migrate_folio,
10507 	.dirty_folio	= filemap_dirty_folio,
10508 	.error_remove_folio = generic_error_remove_folio,
10509 	.swap_activate	= btrfs_swap_activate,
10510 	.swap_deactivate = btrfs_swap_deactivate,
10511 };
10512 
10513 static const struct inode_operations btrfs_file_inode_operations = {
10514 	.getattr	= btrfs_getattr,
10515 	.setattr	= btrfs_setattr,
10516 	.listxattr      = btrfs_listxattr,
10517 	.permission	= btrfs_permission,
10518 	.fiemap		= btrfs_fiemap,
10519 	.get_inode_acl	= btrfs_get_acl,
10520 	.set_acl	= btrfs_set_acl,
10521 	.update_time	= btrfs_update_time,
10522 	.fileattr_get	= btrfs_fileattr_get,
10523 	.fileattr_set	= btrfs_fileattr_set,
10524 };
10525 static const struct inode_operations btrfs_special_inode_operations = {
10526 	.getattr	= btrfs_getattr,
10527 	.setattr	= btrfs_setattr,
10528 	.permission	= btrfs_permission,
10529 	.listxattr	= btrfs_listxattr,
10530 	.get_inode_acl	= btrfs_get_acl,
10531 	.set_acl	= btrfs_set_acl,
10532 	.update_time	= btrfs_update_time,
10533 };
10534 static const struct inode_operations btrfs_symlink_inode_operations = {
10535 	.get_link	= page_get_link,
10536 	.getattr	= btrfs_getattr,
10537 	.setattr	= btrfs_setattr,
10538 	.permission	= btrfs_permission,
10539 	.listxattr	= btrfs_listxattr,
10540 	.update_time	= btrfs_update_time,
10541 };
10542 
10543 const struct dentry_operations btrfs_dentry_operations = {
10544 	.d_delete	= btrfs_dentry_delete,
10545 };
10546