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