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