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