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