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