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