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