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