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