Debian Codegraph @

fs/btrfs/inode.c

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