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