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