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