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