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