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