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