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