]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - fs/btrfs/inode.c
btrfs: drop useless goto in open_fs_devices
[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
47df7765
OS
2729static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
2730 int icsum, struct page *page, int pgoff, u64 start,
2731 size_t len)
dc380aea 2732{
d5178578
JT
2733 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2734 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
dc380aea 2735 char *kaddr;
d5178578
JT
2736 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2737 u8 *csum_expected;
2738 u8 csum[BTRFS_CSUM_SIZE];
dc380aea 2739
d5178578 2740 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
dc380aea
MX
2741
2742 kaddr = kmap_atomic(page);
d5178578
JT
2743 shash->tfm = fs_info->csum_shash;
2744
2745 crypto_shash_init(shash);
2746 crypto_shash_update(shash, kaddr + pgoff, len);
2747 crypto_shash_final(shash, csum);
2748
2749 if (memcmp(csum, csum_expected, csum_size))
dc380aea
MX
2750 goto zeroit;
2751
2752 kunmap_atomic(kaddr);
2753 return 0;
2754zeroit:
ea41d6b2
JT
2755 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2756 io_bio->mirror_num);
dc380aea
MX
2757 memset(kaddr + pgoff, 1, len);
2758 flush_dcache_page(page);
2759 kunmap_atomic(kaddr);
dc380aea
MX
2760 return -EIO;
2761}
2762
d352ac68
CM
2763/*
2764 * when reads are done, we need to check csums to verify the data is correct
4a54c8c1
JS
2765 * if there's a match, we allow the bio to finish. If not, the code in
2766 * extent_io.c will try to find good copies for us.
d352ac68 2767 */
facc8a22
MX
2768static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2769 u64 phy_offset, struct page *page,
2770 u64 start, u64 end, int mirror)
07157aac 2771{
4eee4fa4 2772 size_t offset = start - page_offset(page);
07157aac 2773 struct inode *inode = page->mapping->host;
d1310b2e 2774 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
ff79f819 2775 struct btrfs_root *root = BTRFS_I(inode)->root;
d1310b2e 2776
d20f7043
CM
2777 if (PageChecked(page)) {
2778 ClearPageChecked(page);
dc380aea 2779 return 0;
d20f7043 2780 }
6cbff00f
CH
2781
2782 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
dc380aea 2783 return 0;
17d217fe
YZ
2784
2785 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 2786 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
91166212 2787 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
b6cda9bc 2788 return 0;
17d217fe 2789 }
d20f7043 2790
facc8a22 2791 phy_offset >>= inode->i_sb->s_blocksize_bits;
47df7765
OS
2792 return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2793 (size_t)(end - start + 1));
07157aac 2794}
b888db2b 2795
c1c3fac2
NB
2796/*
2797 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2798 *
2799 * @inode: The inode we want to perform iput on
2800 *
2801 * This function uses the generic vfs_inode::i_count to track whether we should
2802 * just decrement it (in case it's > 1) or if this is the last iput then link
2803 * the inode to the delayed iput machinery. Delayed iputs are processed at
2804 * transaction commit time/superblock commit/cleaner kthread.
2805 */
24bbcf04
YZ
2806void btrfs_add_delayed_iput(struct inode *inode)
2807{
0b246afa 2808 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8089fe62 2809 struct btrfs_inode *binode = BTRFS_I(inode);
24bbcf04
YZ
2810
2811 if (atomic_add_unless(&inode->i_count, -1, 1))
2812 return;
2813
034f784d 2814 atomic_inc(&fs_info->nr_delayed_iputs);
24bbcf04 2815 spin_lock(&fs_info->delayed_iput_lock);
c1c3fac2
NB
2816 ASSERT(list_empty(&binode->delayed_iput));
2817 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
24bbcf04 2818 spin_unlock(&fs_info->delayed_iput_lock);
fd340d0f
JB
2819 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2820 wake_up_process(fs_info->cleaner_kthread);
24bbcf04
YZ
2821}
2822
63611e73
JB
2823static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2824 struct btrfs_inode *inode)
2825{
2826 list_del_init(&inode->delayed_iput);
2827 spin_unlock(&fs_info->delayed_iput_lock);
2828 iput(&inode->vfs_inode);
2829 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2830 wake_up(&fs_info->delayed_iputs_wait);
2831 spin_lock(&fs_info->delayed_iput_lock);
2832}
2833
2834static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2835 struct btrfs_inode *inode)
2836{
2837 if (!list_empty(&inode->delayed_iput)) {
2838 spin_lock(&fs_info->delayed_iput_lock);
2839 if (!list_empty(&inode->delayed_iput))
2840 run_delayed_iput_locked(fs_info, inode);
2841 spin_unlock(&fs_info->delayed_iput_lock);
2842 }
2843}
2844
2ff7e61e 2845void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
24bbcf04 2846{
24bbcf04 2847
24bbcf04 2848 spin_lock(&fs_info->delayed_iput_lock);
8089fe62
DS
2849 while (!list_empty(&fs_info->delayed_iputs)) {
2850 struct btrfs_inode *inode;
2851
2852 inode = list_first_entry(&fs_info->delayed_iputs,
2853 struct btrfs_inode, delayed_iput);
63611e73 2854 run_delayed_iput_locked(fs_info, inode);
24bbcf04 2855 }
8089fe62 2856 spin_unlock(&fs_info->delayed_iput_lock);
24bbcf04
YZ
2857}
2858
034f784d
JB
2859/**
2860 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2861 * @fs_info - the fs_info for this fs
2862 * @return - EINTR if we were killed, 0 if nothing's pending
2863 *
2864 * This will wait on any delayed iputs that are currently running with KILLABLE
2865 * set. Once they are all done running we will return, unless we are killed in
2866 * which case we return EINTR. This helps in user operations like fallocate etc
2867 * that might get blocked on the iputs.
2868 */
2869int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2870{
2871 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2872 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2873 if (ret)
2874 return -EINTR;
2875 return 0;
2876}
2877
7b128766 2878/*
f7e9e8fc
OS
2879 * This creates an orphan entry for the given inode in case something goes wrong
2880 * in the middle of an unlink.
7b128766 2881 */
73f2e545 2882int btrfs_orphan_add(struct btrfs_trans_handle *trans,
27919067 2883 struct btrfs_inode *inode)
7b128766 2884{
d68fc57b 2885 int ret;
7b128766 2886
27919067
OS
2887 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2888 if (ret && ret != -EEXIST) {
2889 btrfs_abort_transaction(trans, ret);
2890 return ret;
d68fc57b
YZ
2891 }
2892
d68fc57b 2893 return 0;
7b128766
JB
2894}
2895
2896/*
f7e9e8fc
OS
2897 * We have done the delete so we can go ahead and remove the orphan item for
2898 * this particular inode.
7b128766 2899 */
48a3b636 2900static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3d6ae7bb 2901 struct btrfs_inode *inode)
7b128766 2902{
27919067 2903 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
7b128766
JB
2904}
2905
2906/*
2907 * this cleans up any orphans that may be left on the list from the last use
2908 * of this root.
2909 */
66b4ffd1 2910int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766 2911{
0b246afa 2912 struct btrfs_fs_info *fs_info = root->fs_info;
7b128766
JB
2913 struct btrfs_path *path;
2914 struct extent_buffer *leaf;
7b128766
JB
2915 struct btrfs_key key, found_key;
2916 struct btrfs_trans_handle *trans;
2917 struct inode *inode;
8f6d7f4f 2918 u64 last_objectid = 0;
f7e9e8fc 2919 int ret = 0, nr_unlink = 0;
7b128766 2920
d68fc57b 2921 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 2922 return 0;
c71bf099
YZ
2923
2924 path = btrfs_alloc_path();
66b4ffd1
JB
2925 if (!path) {
2926 ret = -ENOMEM;
2927 goto out;
2928 }
e4058b54 2929 path->reada = READA_BACK;
7b128766
JB
2930
2931 key.objectid = BTRFS_ORPHAN_OBJECTID;
962a298f 2932 key.type = BTRFS_ORPHAN_ITEM_KEY;
7b128766
JB
2933 key.offset = (u64)-1;
2934
7b128766
JB
2935 while (1) {
2936 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
2937 if (ret < 0)
2938 goto out;
7b128766
JB
2939
2940 /*
2941 * if ret == 0 means we found what we were searching for, which
25985edc 2942 * is weird, but possible, so only screw with path if we didn't
7b128766
JB
2943 * find the key and see if we have stuff that matches
2944 */
2945 if (ret > 0) {
66b4ffd1 2946 ret = 0;
7b128766
JB
2947 if (path->slots[0] == 0)
2948 break;
2949 path->slots[0]--;
2950 }
2951
2952 /* pull out the item */
2953 leaf = path->nodes[0];
7b128766
JB
2954 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2955
2956 /* make sure the item matches what we want */
2957 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2958 break;
962a298f 2959 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
7b128766
JB
2960 break;
2961
2962 /* release the path since we're done with it */
b3b4aa74 2963 btrfs_release_path(path);
7b128766
JB
2964
2965 /*
2966 * this is where we are basically btrfs_lookup, without the
2967 * crossing root thing. we store the inode number in the
2968 * offset of the orphan item.
2969 */
8f6d7f4f
JB
2970
2971 if (found_key.offset == last_objectid) {
0b246afa
JM
2972 btrfs_err(fs_info,
2973 "Error removing orphan entry, stopping orphan cleanup");
8f6d7f4f
JB
2974 ret = -EINVAL;
2975 goto out;
2976 }
2977
2978 last_objectid = found_key.offset;
2979
5d4f98a2
YZ
2980 found_key.objectid = found_key.offset;
2981 found_key.type = BTRFS_INODE_ITEM_KEY;
2982 found_key.offset = 0;
4c66e0d4 2983 inode = btrfs_iget(fs_info->sb, &found_key, root);
8c6ffba0 2984 ret = PTR_ERR_OR_ZERO(inode);
67710892 2985 if (ret && ret != -ENOENT)
66b4ffd1 2986 goto out;
7b128766 2987
0b246afa 2988 if (ret == -ENOENT && root == fs_info->tree_root) {
f8e9e0b0
AJ
2989 struct btrfs_root *dead_root;
2990 struct btrfs_fs_info *fs_info = root->fs_info;
2991 int is_dead_root = 0;
2992
2993 /*
2994 * this is an orphan in the tree root. Currently these
2995 * could come from 2 sources:
2996 * a) a snapshot deletion in progress
2997 * b) a free space cache inode
2998 * We need to distinguish those two, as the snapshot
2999 * orphan must not get deleted.
3000 * find_dead_roots already ran before us, so if this
3001 * is a snapshot deletion, we should find the root
3002 * in the dead_roots list
3003 */
3004 spin_lock(&fs_info->trans_lock);
3005 list_for_each_entry(dead_root, &fs_info->dead_roots,
3006 root_list) {
3007 if (dead_root->root_key.objectid ==
3008 found_key.objectid) {
3009 is_dead_root = 1;
3010 break;
3011 }
3012 }
3013 spin_unlock(&fs_info->trans_lock);
3014 if (is_dead_root) {
3015 /* prevent this orphan from being found again */
3016 key.offset = found_key.objectid - 1;
3017 continue;
3018 }
f7e9e8fc 3019
f8e9e0b0 3020 }
f7e9e8fc 3021
7b128766 3022 /*
f7e9e8fc
OS
3023 * If we have an inode with links, there are a couple of
3024 * possibilities. Old kernels (before v3.12) used to create an
3025 * orphan item for truncate indicating that there were possibly
3026 * extent items past i_size that needed to be deleted. In v3.12,
3027 * truncate was changed to update i_size in sync with the extent
3028 * items, but the (useless) orphan item was still created. Since
3029 * v4.18, we don't create the orphan item for truncate at all.
3030 *
3031 * So, this item could mean that we need to do a truncate, but
3032 * only if this filesystem was last used on a pre-v3.12 kernel
3033 * and was not cleanly unmounted. The odds of that are quite
3034 * slim, and it's a pain to do the truncate now, so just delete
3035 * the orphan item.
3036 *
3037 * It's also possible that this orphan item was supposed to be
3038 * deleted but wasn't. The inode number may have been reused,
3039 * but either way, we can delete the orphan item.
7b128766 3040 */
f7e9e8fc
OS
3041 if (ret == -ENOENT || inode->i_nlink) {
3042 if (!ret)
3043 iput(inode);
a8c9e576 3044 trans = btrfs_start_transaction(root, 1);
66b4ffd1
JB
3045 if (IS_ERR(trans)) {
3046 ret = PTR_ERR(trans);
3047 goto out;
3048 }
0b246afa
JM
3049 btrfs_debug(fs_info, "auto deleting %Lu",
3050 found_key.objectid);
a8c9e576
JB
3051 ret = btrfs_del_orphan_item(trans, root,
3052 found_key.objectid);
3a45bb20 3053 btrfs_end_transaction(trans);
4ef31a45
JB
3054 if (ret)
3055 goto out;
7b128766
JB
3056 continue;
3057 }
3058
f7e9e8fc 3059 nr_unlink++;
7b128766
JB
3060
3061 /* this will do delete_inode and everything for us */
3062 iput(inode);
3063 }
3254c876
MX
3064 /* release the path since we're done with it */
3065 btrfs_release_path(path);
3066
d68fc57b
YZ
3067 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3068
a575ceeb 3069 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
7a7eaa40 3070 trans = btrfs_join_transaction(root);
66b4ffd1 3071 if (!IS_ERR(trans))
3a45bb20 3072 btrfs_end_transaction(trans);
d68fc57b 3073 }
7b128766
JB
3074
3075 if (nr_unlink)
0b246afa 3076 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
66b4ffd1
JB
3077
3078out:
3079 if (ret)
0b246afa 3080 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
66b4ffd1
JB
3081 btrfs_free_path(path);
3082 return ret;
7b128766
JB
3083}
3084
46a53cca
CM
3085/*
3086 * very simple check to peek ahead in the leaf looking for xattrs. If we
3087 * don't find any xattrs, we know there can't be any acls.
3088 *
3089 * slot is the slot the inode is in, objectid is the objectid of the inode
3090 */
3091static noinline int acls_after_inode_item(struct extent_buffer *leaf,
63541927
FDBM
3092 int slot, u64 objectid,
3093 int *first_xattr_slot)
46a53cca
CM
3094{
3095 u32 nritems = btrfs_header_nritems(leaf);
3096 struct btrfs_key found_key;
f23b5a59
JB
3097 static u64 xattr_access = 0;
3098 static u64 xattr_default = 0;
46a53cca
CM
3099 int scanned = 0;
3100
f23b5a59 3101 if (!xattr_access) {
97d79299
AG
3102 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3103 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3104 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3105 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
f23b5a59
JB
3106 }
3107
46a53cca 3108 slot++;
63541927 3109 *first_xattr_slot = -1;
46a53cca
CM
3110 while (slot < nritems) {
3111 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3112
3113 /* we found a different objectid, there must not be acls */
3114 if (found_key.objectid != objectid)
3115 return 0;
3116
3117 /* we found an xattr, assume we've got an acl */
f23b5a59 3118 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
63541927
FDBM
3119 if (*first_xattr_slot == -1)
3120 *first_xattr_slot = slot;
f23b5a59
JB
3121 if (found_key.offset == xattr_access ||
3122 found_key.offset == xattr_default)
3123 return 1;
3124 }
46a53cca
CM
3125
3126 /*
3127 * we found a key greater than an xattr key, there can't
3128 * be any acls later on
3129 */
3130 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3131 return 0;
3132
3133 slot++;
3134 scanned++;
3135
3136 /*
3137 * it goes inode, inode backrefs, xattrs, extents,
3138 * so if there are a ton of hard links to an inode there can
3139 * be a lot of backrefs. Don't waste time searching too hard,
3140 * this is just an optimization
3141 */
3142 if (scanned >= 8)
3143 break;
3144 }
3145 /* we hit the end of the leaf before we found an xattr or
3146 * something larger than an xattr. We have to assume the inode
3147 * has acls
3148 */
63541927
FDBM
3149 if (*first_xattr_slot == -1)
3150 *first_xattr_slot = slot;
46a53cca
CM
3151 return 1;
3152}
3153
d352ac68
CM
3154/*
3155 * read an inode from the btree into the in-memory inode
3156 */
4222ea71
FM
3157static int btrfs_read_locked_inode(struct inode *inode,
3158 struct btrfs_path *in_path)
39279cc3 3159{
0b246afa 3160 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4222ea71 3161 struct btrfs_path *path = in_path;
5f39d397 3162 struct extent_buffer *leaf;
39279cc3
CM
3163 struct btrfs_inode_item *inode_item;
3164 struct btrfs_root *root = BTRFS_I(inode)->root;
3165 struct btrfs_key location;
67de1176 3166 unsigned long ptr;
46a53cca 3167 int maybe_acls;
618e21d5 3168 u32 rdev;
39279cc3 3169 int ret;
2f7e33d4 3170 bool filled = false;
63541927 3171 int first_xattr_slot;
2f7e33d4
MX
3172
3173 ret = btrfs_fill_inode(inode, &rdev);
3174 if (!ret)
3175 filled = true;
39279cc3 3176
4222ea71
FM
3177 if (!path) {
3178 path = btrfs_alloc_path();
3179 if (!path)
3180 return -ENOMEM;
3181 }
1748f843 3182
39279cc3 3183 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 3184
39279cc3 3185 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
67710892 3186 if (ret) {
4222ea71
FM
3187 if (path != in_path)
3188 btrfs_free_path(path);
f5b3a417 3189 return ret;
67710892 3190 }
39279cc3 3191
5f39d397 3192 leaf = path->nodes[0];
2f7e33d4
MX
3193
3194 if (filled)
67de1176 3195 goto cache_index;
2f7e33d4 3196
5f39d397
CM
3197 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3198 struct btrfs_inode_item);
5f39d397 3199 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
bfe86848 3200 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2f2f43d3
EB
3201 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3202 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
6ef06d27 3203 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
41a2ee75
JB
3204 btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3205 round_up(i_size_read(inode), fs_info->sectorsize));
5f39d397 3206
a937b979
DS
3207 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3208 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
5f39d397 3209
a937b979
DS
3210 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3211 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
5f39d397 3212
a937b979
DS
3213 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3214 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
5f39d397 3215
9cc97d64 3216 BTRFS_I(inode)->i_otime.tv_sec =
3217 btrfs_timespec_sec(leaf, &inode_item->otime);
3218 BTRFS_I(inode)->i_otime.tv_nsec =
3219 btrfs_timespec_nsec(leaf, &inode_item->otime);
5f39d397 3220
a76a3cd4 3221 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 3222 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
5dc562c5
JB
3223 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3224
c7f88c4e
JL
3225 inode_set_iversion_queried(inode,
3226 btrfs_inode_sequence(leaf, inode_item));
6e17d30b
YD
3227 inode->i_generation = BTRFS_I(inode)->generation;
3228 inode->i_rdev = 0;
3229 rdev = btrfs_inode_rdev(leaf, inode_item);
3230
3231 BTRFS_I(inode)->index_cnt = (u64)-1;
3232 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3233
3234cache_index:
5dc562c5
JB
3235 /*
3236 * If we were modified in the current generation and evicted from memory
3237 * and then re-read we need to do a full sync since we don't have any
3238 * idea about which extents were modified before we were evicted from
3239 * cache.
6e17d30b
YD
3240 *
3241 * This is required for both inode re-read from disk and delayed inode
3242 * in delayed_nodes_tree.
5dc562c5 3243 */
0b246afa 3244 if (BTRFS_I(inode)->last_trans == fs_info->generation)
5dc562c5
JB
3245 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3246 &BTRFS_I(inode)->runtime_flags);
3247
bde6c242
FM
3248 /*
3249 * We don't persist the id of the transaction where an unlink operation
3250 * against the inode was last made. So here we assume the inode might
3251 * have been evicted, and therefore the exact value of last_unlink_trans
3252 * lost, and set it to last_trans to avoid metadata inconsistencies
3253 * between the inode and its parent if the inode is fsync'ed and the log
3254 * replayed. For example, in the scenario:
3255 *
3256 * touch mydir/foo
3257 * ln mydir/foo mydir/bar
3258 * sync
3259 * unlink mydir/bar
3260 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3261 * xfs_io -c fsync mydir/foo
3262 * <power failure>
3263 * mount fs, triggers fsync log replay
3264 *
3265 * We must make sure that when we fsync our inode foo we also log its
3266 * parent inode, otherwise after log replay the parent still has the
3267 * dentry with the "bar" name but our inode foo has a link count of 1
3268 * and doesn't have an inode ref with the name "bar" anymore.
3269 *
3270 * Setting last_unlink_trans to last_trans is a pessimistic approach,
01327610 3271 * but it guarantees correctness at the expense of occasional full
bde6c242
FM
3272 * transaction commits on fsync if our inode is a directory, or if our
3273 * inode is not a directory, logging its parent unnecessarily.
3274 */
3275 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3276
67de1176
MX
3277 path->slots[0]++;
3278 if (inode->i_nlink != 1 ||
3279 path->slots[0] >= btrfs_header_nritems(leaf))
3280 goto cache_acl;
3281
3282 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4a0cc7ca 3283 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
67de1176
MX
3284 goto cache_acl;
3285
3286 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3287 if (location.type == BTRFS_INODE_REF_KEY) {
3288 struct btrfs_inode_ref *ref;
3289
3290 ref = (struct btrfs_inode_ref *)ptr;
3291 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3292 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3293 struct btrfs_inode_extref *extref;
3294
3295 extref = (struct btrfs_inode_extref *)ptr;
3296 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3297 extref);
3298 }
2f7e33d4 3299cache_acl:
46a53cca
CM
3300 /*
3301 * try to precache a NULL acl entry for files that don't have
3302 * any xattrs or acls
3303 */
33345d01 3304 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
f85b7379 3305 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
63541927
FDBM
3306 if (first_xattr_slot != -1) {
3307 path->slots[0] = first_xattr_slot;
3308 ret = btrfs_load_inode_props(inode, path);
3309 if (ret)
0b246afa 3310 btrfs_err(fs_info,
351fd353 3311 "error loading props for ino %llu (root %llu): %d",
4a0cc7ca 3312 btrfs_ino(BTRFS_I(inode)),
63541927
FDBM
3313 root->root_key.objectid, ret);
3314 }
4222ea71
FM
3315 if (path != in_path)
3316 btrfs_free_path(path);
63541927 3317
72c04902
AV
3318 if (!maybe_acls)
3319 cache_no_acl(inode);
46a53cca 3320
39279cc3 3321 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
3322 case S_IFREG:
3323 inode->i_mapping->a_ops = &btrfs_aops;
d1310b2e 3324 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
3325 inode->i_fop = &btrfs_file_operations;
3326 inode->i_op = &btrfs_file_inode_operations;
3327 break;
3328 case S_IFDIR:
3329 inode->i_fop = &btrfs_dir_file_operations;
67ade058 3330 inode->i_op = &btrfs_dir_inode_operations;
39279cc3
CM
3331 break;
3332 case S_IFLNK:
3333 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 3334 inode_nohighmem(inode);
4779cc04 3335 inode->i_mapping->a_ops = &btrfs_aops;
39279cc3 3336 break;
618e21d5 3337 default:
0279b4cd 3338 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
3339 init_special_inode(inode, inode->i_mode, rdev);
3340 break;
39279cc3 3341 }
6cbff00f 3342
7b6a221e 3343 btrfs_sync_inode_flags_to_i_flags(inode);
67710892 3344 return 0;
39279cc3
CM
3345}
3346
d352ac68
CM
3347/*
3348 * given a leaf and an inode, copy the inode fields into the leaf
3349 */
e02119d5
CM
3350static void fill_inode_item(struct btrfs_trans_handle *trans,
3351 struct extent_buffer *leaf,
5f39d397 3352 struct btrfs_inode_item *item,
39279cc3
CM
3353 struct inode *inode)
3354{
51fab693
LB
3355 struct btrfs_map_token token;
3356
c82f823c 3357 btrfs_init_map_token(&token, leaf);
5f39d397 3358
51fab693
LB
3359 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3360 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3361 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3362 &token);
3363 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3364 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
5f39d397 3365
a937b979 3366 btrfs_set_token_timespec_sec(leaf, &item->atime,
51fab693 3367 inode->i_atime.tv_sec, &token);
a937b979 3368 btrfs_set_token_timespec_nsec(leaf, &item->atime,
51fab693 3369 inode->i_atime.tv_nsec, &token);
5f39d397 3370
a937b979 3371 btrfs_set_token_timespec_sec(leaf, &item->mtime,
51fab693 3372 inode->i_mtime.tv_sec, &token);
a937b979 3373 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
51fab693 3374 inode->i_mtime.tv_nsec, &token);
5f39d397 3375
a937b979 3376 btrfs_set_token_timespec_sec(leaf, &item->ctime,
51fab693 3377 inode->i_ctime.tv_sec, &token);
a937b979 3378 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
51fab693 3379 inode->i_ctime.tv_nsec, &token);
5f39d397 3380
9cc97d64 3381 btrfs_set_token_timespec_sec(leaf, &item->otime,
3382 BTRFS_I(inode)->i_otime.tv_sec, &token);
3383 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3384 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3385
51fab693
LB
3386 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3387 &token);
3388 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3389 &token);
c7f88c4e
JL
3390 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3391 &token);
51fab693
LB
3392 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3393 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3394 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3395 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
39279cc3
CM
3396}
3397
d352ac68
CM
3398/*
3399 * copy everything in the in-memory inode into the btree.
3400 */
2115133f 3401static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
d397712b 3402 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
3403{
3404 struct btrfs_inode_item *inode_item;
3405 struct btrfs_path *path;
5f39d397 3406 struct extent_buffer *leaf;
39279cc3
CM
3407 int ret;
3408
3409 path = btrfs_alloc_path();
16cdcec7
MX
3410 if (!path)
3411 return -ENOMEM;
3412
b9473439 3413 path->leave_spinning = 1;
16cdcec7
MX
3414 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3415 1);
39279cc3
CM
3416 if (ret) {
3417 if (ret > 0)
3418 ret = -ENOENT;
3419 goto failed;
3420 }
3421
5f39d397
CM
3422 leaf = path->nodes[0];
3423 inode_item = btrfs_item_ptr(leaf, path->slots[0],
16cdcec7 3424 struct btrfs_inode_item);
39279cc3 3425
e02119d5 3426 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 3427 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 3428 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
3429 ret = 0;
3430failed:
39279cc3
CM
3431 btrfs_free_path(path);
3432 return ret;
3433}
3434
2115133f
CM
3435/*
3436 * copy everything in the in-memory inode into the btree.
3437 */
3438noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3439 struct btrfs_root *root, struct inode *inode)
3440{
0b246afa 3441 struct btrfs_fs_info *fs_info = root->fs_info;
2115133f
CM
3442 int ret;
3443
3444 /*
3445 * If the inode is a free space inode, we can deadlock during commit
3446 * if we put it into the delayed code.
3447 *
3448 * The data relocation inode should also be directly updated
3449 * without delay
3450 */
70ddc553 3451 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
1d52c78a 3452 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
0b246afa 3453 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
8ea05e3a
AB
3454 btrfs_update_root_times(trans, root);
3455
2115133f
CM
3456 ret = btrfs_delayed_update_inode(trans, root, inode);
3457 if (!ret)
3458 btrfs_set_inode_last_trans(trans, inode);
3459 return ret;
3460 }
3461
3462 return btrfs_update_inode_item(trans, root, inode);
3463}
3464
be6aef60
JB
3465noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3466 struct btrfs_root *root,
3467 struct inode *inode)
2115133f
CM
3468{
3469 int ret;
3470
3471 ret = btrfs_update_inode(trans, root, inode);
3472 if (ret == -ENOSPC)
3473 return btrfs_update_inode_item(trans, root, inode);
3474 return ret;
3475}
3476
d352ac68
CM
3477/*
3478 * unlink helper that gets used here in inode.c and in the tree logging
3479 * recovery code. It remove a link in a directory with a given name, and
3480 * also drops the back refs in the inode to the directory
3481 */
92986796
AV
3482static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3483 struct btrfs_root *root,
4ec5934e
NB
3484 struct btrfs_inode *dir,
3485 struct btrfs_inode *inode,
92986796 3486 const char *name, int name_len)
39279cc3 3487{
0b246afa 3488 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 3489 struct btrfs_path *path;
39279cc3 3490 int ret = 0;
39279cc3 3491 struct btrfs_dir_item *di;
aec7477b 3492 u64 index;
33345d01
LZ
3493 u64 ino = btrfs_ino(inode);
3494 u64 dir_ino = btrfs_ino(dir);
39279cc3
CM
3495
3496 path = btrfs_alloc_path();
54aa1f4d
CM
3497 if (!path) {
3498 ret = -ENOMEM;
554233a6 3499 goto out;
54aa1f4d
CM
3500 }
3501
b9473439 3502 path->leave_spinning = 1;
33345d01 3503 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
39279cc3 3504 name, name_len, -1);
3cf5068f
LB
3505 if (IS_ERR_OR_NULL(di)) {
3506 ret = di ? PTR_ERR(di) : -ENOENT;
39279cc3
CM
3507 goto err;
3508 }
39279cc3 3509 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
3510 if (ret)
3511 goto err;
b3b4aa74 3512 btrfs_release_path(path);
39279cc3 3513
67de1176
MX
3514 /*
3515 * If we don't have dir index, we have to get it by looking up
3516 * the inode ref, since we get the inode ref, remove it directly,
3517 * it is unnecessary to do delayed deletion.
3518 *
3519 * But if we have dir index, needn't search inode ref to get it.
3520 * Since the inode ref is close to the inode item, it is better
3521 * that we delay to delete it, and just do this deletion when
3522 * we update the inode item.
3523 */
4ec5934e 3524 if (inode->dir_index) {
67de1176
MX
3525 ret = btrfs_delayed_delete_inode_ref(inode);
3526 if (!ret) {
4ec5934e 3527 index = inode->dir_index;
67de1176
MX
3528 goto skip_backref;
3529 }
3530 }
3531
33345d01
LZ
3532 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3533 dir_ino, &index);
aec7477b 3534 if (ret) {
0b246afa 3535 btrfs_info(fs_info,
c2cf52eb 3536 "failed to delete reference to %.*s, inode %llu parent %llu",
c1c9ff7c 3537 name_len, name, ino, dir_ino);
66642832 3538 btrfs_abort_transaction(trans, ret);
aec7477b
JB
3539 goto err;
3540 }
67de1176 3541skip_backref:
9add2945 3542 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
79787eaa 3543 if (ret) {
66642832 3544 btrfs_abort_transaction(trans, ret);
39279cc3 3545 goto err;
79787eaa 3546 }
39279cc3 3547
4ec5934e
NB
3548 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3549 dir_ino);
79787eaa 3550 if (ret != 0 && ret != -ENOENT) {
66642832 3551 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3552 goto err;
3553 }
e02119d5 3554
4ec5934e
NB
3555 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3556 index);
6418c961
CM
3557 if (ret == -ENOENT)
3558 ret = 0;
d4e3991b 3559 else if (ret)
66642832 3560 btrfs_abort_transaction(trans, ret);
63611e73
JB
3561
3562 /*
3563 * If we have a pending delayed iput we could end up with the final iput
3564 * being run in btrfs-cleaner context. If we have enough of these built
3565 * up we can end up burning a lot of time in btrfs-cleaner without any
3566 * way to throttle the unlinks. Since we're currently holding a ref on
3567 * the inode we can run the delayed iput here without any issues as the
3568 * final iput won't be done until after we drop the ref we're currently
3569 * holding.
3570 */
3571 btrfs_run_delayed_iput(fs_info, inode);
39279cc3
CM
3572err:
3573 btrfs_free_path(path);
e02119d5
CM
3574 if (ret)
3575 goto out;
3576
6ef06d27 3577 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4ec5934e
NB
3578 inode_inc_iversion(&inode->vfs_inode);
3579 inode_inc_iversion(&dir->vfs_inode);
3580 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3581 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3582 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
e02119d5 3583out:
39279cc3
CM
3584 return ret;
3585}
3586
92986796
AV
3587int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3588 struct btrfs_root *root,
4ec5934e 3589 struct btrfs_inode *dir, struct btrfs_inode *inode,
92986796
AV
3590 const char *name, int name_len)
3591{
3592 int ret;
3593 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3594 if (!ret) {
4ec5934e
NB
3595 drop_nlink(&inode->vfs_inode);
3596 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
92986796
AV
3597 }
3598 return ret;
3599}
39279cc3 3600
a22285a6
YZ
3601/*
3602 * helper to start transaction for unlink and rmdir.
3603 *
d52be818
JB
3604 * unlink and rmdir are special in btrfs, they do not always free space, so
3605 * if we cannot make our reservations the normal way try and see if there is
3606 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3607 * allow the unlink to occur.
a22285a6 3608 */
d52be818 3609static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4df27c4d 3610{
a22285a6 3611 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d 3612
e70bea5f
JB
3613 /*
3614 * 1 for the possible orphan item
3615 * 1 for the dir item
3616 * 1 for the dir index
3617 * 1 for the inode ref
e70bea5f
JB
3618 * 1 for the inode
3619 */
7f9fe614 3620 return btrfs_start_transaction_fallback_global_rsv(root, 5);
a22285a6
YZ
3621}
3622
3623static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3624{
3625 struct btrfs_root *root = BTRFS_I(dir)->root;
3626 struct btrfs_trans_handle *trans;
2b0143b5 3627 struct inode *inode = d_inode(dentry);
a22285a6 3628 int ret;
a22285a6 3629
d52be818 3630 trans = __unlink_start_trans(dir);
a22285a6
YZ
3631 if (IS_ERR(trans))
3632 return PTR_ERR(trans);
5f39d397 3633
4ec5934e
NB
3634 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3635 0);
12fcfd22 3636
4ec5934e
NB
3637 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3638 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3639 dentry->d_name.len);
b532402e
TI
3640 if (ret)
3641 goto out;
7b128766 3642
a22285a6 3643 if (inode->i_nlink == 0) {
73f2e545 3644 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
b532402e
TI
3645 if (ret)
3646 goto out;
a22285a6 3647 }
7b128766 3648
b532402e 3649out:
3a45bb20 3650 btrfs_end_transaction(trans);
2ff7e61e 3651 btrfs_btree_balance_dirty(root->fs_info);
39279cc3
CM
3652 return ret;
3653}
3654
f60a2364 3655static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
045d3967 3656 struct inode *dir, struct dentry *dentry)
4df27c4d 3657{
401b3b19 3658 struct btrfs_root *root = BTRFS_I(dir)->root;
045d3967 3659 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4df27c4d
YZ
3660 struct btrfs_path *path;
3661 struct extent_buffer *leaf;
3662 struct btrfs_dir_item *di;
3663 struct btrfs_key key;
045d3967
JB
3664 const char *name = dentry->d_name.name;
3665 int name_len = dentry->d_name.len;
4df27c4d
YZ
3666 u64 index;
3667 int ret;
045d3967 3668 u64 objectid;
4a0cc7ca 3669 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4df27c4d 3670
045d3967
JB
3671 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3672 objectid = inode->root->root_key.objectid;
3673 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3674 objectid = inode->location.objectid;
3675 } else {
3676 WARN_ON(1);
3677 return -EINVAL;
3678 }
3679
4df27c4d
YZ
3680 path = btrfs_alloc_path();
3681 if (!path)
3682 return -ENOMEM;
3683
33345d01 3684 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4df27c4d 3685 name, name_len, -1);
79787eaa 3686 if (IS_ERR_OR_NULL(di)) {
3cf5068f 3687 ret = di ? PTR_ERR(di) : -ENOENT;
79787eaa
JM
3688 goto out;
3689 }
4df27c4d
YZ
3690
3691 leaf = path->nodes[0];
3692 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3693 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3694 ret = btrfs_delete_one_dir_name(trans, root, path, di);
79787eaa 3695 if (ret) {
66642832 3696 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3697 goto out;
3698 }
b3b4aa74 3699 btrfs_release_path(path);
4df27c4d 3700
d49d3287
JB
3701 /*
3702 * This is a placeholder inode for a subvolume we didn't have a
3703 * reference to at the time of the snapshot creation. In the meantime
3704 * we could have renamed the real subvol link into our snapshot, so
3705 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3706 * Instead simply lookup the dir_index_item for this entry so we can
3707 * remove it. Otherwise we know we have a ref to the root and we can
3708 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3709 */
3710 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
33345d01 3711 di = btrfs_search_dir_index_item(root, path, dir_ino,
4df27c4d 3712 name, name_len);
79787eaa
JM
3713 if (IS_ERR_OR_NULL(di)) {
3714 if (!di)
3715 ret = -ENOENT;
3716 else
3717 ret = PTR_ERR(di);
66642832 3718 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3719 goto out;
3720 }
4df27c4d
YZ
3721
3722 leaf = path->nodes[0];
3723 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4df27c4d 3724 index = key.offset;
d49d3287
JB
3725 btrfs_release_path(path);
3726 } else {
3727 ret = btrfs_del_root_ref(trans, objectid,
3728 root->root_key.objectid, dir_ino,
3729 &index, name, name_len);
3730 if (ret) {
3731 btrfs_abort_transaction(trans, ret);
3732 goto out;
3733 }
4df27c4d
YZ
3734 }
3735
9add2945 3736 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
79787eaa 3737 if (ret) {
66642832 3738 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3739 goto out;
3740 }
4df27c4d 3741
6ef06d27 3742 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
0c4d2d95 3743 inode_inc_iversion(dir);
c2050a45 3744 dir->i_mtime = dir->i_ctime = current_time(dir);
5a24e84c 3745 ret = btrfs_update_inode_fallback(trans, root, dir);
79787eaa 3746 if (ret)
66642832 3747 btrfs_abort_transaction(trans, ret);
79787eaa 3748out:
71d7aed0 3749 btrfs_free_path(path);
79787eaa 3750 return ret;
4df27c4d
YZ
3751}
3752
ec42f167
MT
3753/*
3754 * Helper to check if the subvolume references other subvolumes or if it's
3755 * default.
3756 */
f60a2364 3757static noinline int may_destroy_subvol(struct btrfs_root *root)
ec42f167
MT
3758{
3759 struct btrfs_fs_info *fs_info = root->fs_info;
3760 struct btrfs_path *path;
3761 struct btrfs_dir_item *di;
3762 struct btrfs_key key;
3763 u64 dir_id;
3764 int ret;
3765
3766 path = btrfs_alloc_path();
3767 if (!path)
3768 return -ENOMEM;
3769
3770 /* Make sure this root isn't set as the default subvol */
3771 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3772 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3773 dir_id, "default", 7, 0);
3774 if (di && !IS_ERR(di)) {
3775 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3776 if (key.objectid == root->root_key.objectid) {
3777 ret = -EPERM;
3778 btrfs_err(fs_info,
3779 "deleting default subvolume %llu is not allowed",
3780 key.objectid);
3781 goto out;
3782 }
3783 btrfs_release_path(path);
3784 }
3785
3786 key.objectid = root->root_key.objectid;
3787 key.type = BTRFS_ROOT_REF_KEY;
3788 key.offset = (u64)-1;
3789
3790 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3791 if (ret < 0)
3792 goto out;
3793 BUG_ON(ret == 0);
3794
3795 ret = 0;
3796 if (path->slots[0] > 0) {
3797 path->slots[0]--;
3798 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3799 if (key.objectid == root->root_key.objectid &&
3800 key.type == BTRFS_ROOT_REF_KEY)
3801 ret = -ENOTEMPTY;
3802 }
3803out:
3804 btrfs_free_path(path);
3805 return ret;
3806}
3807
20a68004
NB
3808/* Delete all dentries for inodes belonging to the root */
3809static void btrfs_prune_dentries(struct btrfs_root *root)
3810{
3811 struct btrfs_fs_info *fs_info = root->fs_info;
3812 struct rb_node *node;
3813 struct rb_node *prev;
3814 struct btrfs_inode *entry;
3815 struct inode *inode;
3816 u64 objectid = 0;
3817
3818 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3819 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3820
3821 spin_lock(&root->inode_lock);
3822again:
3823 node = root->inode_tree.rb_node;
3824 prev = NULL;
3825 while (node) {
3826 prev = node;
3827 entry = rb_entry(node, struct btrfs_inode, rb_node);
3828
37508515 3829 if (objectid < btrfs_ino(entry))
20a68004 3830 node = node->rb_left;
37508515 3831 else if (objectid > btrfs_ino(entry))
20a68004
NB
3832 node = node->rb_right;
3833 else
3834 break;
3835 }
3836 if (!node) {
3837 while (prev) {
3838 entry = rb_entry(prev, struct btrfs_inode, rb_node);
37508515 3839 if (objectid <= btrfs_ino(entry)) {
20a68004
NB
3840 node = prev;
3841 break;
3842 }
3843 prev = rb_next(prev);
3844 }
3845 }
3846 while (node) {
3847 entry = rb_entry(node, struct btrfs_inode, rb_node);
37508515 3848 objectid = btrfs_ino(entry) + 1;
20a68004
NB
3849 inode = igrab(&entry->vfs_inode);
3850 if (inode) {
3851 spin_unlock(&root->inode_lock);
3852 if (atomic_read(&inode->i_count) > 1)
3853 d_prune_aliases(inode);
3854 /*
3855 * btrfs_drop_inode will have it removed from the inode
3856 * cache when its usage count hits zero.
3857 */
3858 iput(inode);
3859 cond_resched();
3860 spin_lock(&root->inode_lock);
3861 goto again;
3862 }
3863
3864 if (cond_resched_lock(&root->inode_lock))
3865 goto again;
3866
3867 node = rb_next(node);
3868 }
3869 spin_unlock(&root->inode_lock);
3870}
3871
f60a2364
MT
3872int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3873{
3874 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3875 struct btrfs_root *root = BTRFS_I(dir)->root;
3876 struct inode *inode = d_inode(dentry);
3877 struct btrfs_root *dest = BTRFS_I(inode)->root;
3878 struct btrfs_trans_handle *trans;
3879 struct btrfs_block_rsv block_rsv;
3880 u64 root_flags;
f60a2364
MT
3881 int ret;
3882 int err;
3883
3884 /*
3885 * Don't allow to delete a subvolume with send in progress. This is
3886 * inside the inode lock so the error handling that has to drop the bit
3887 * again is not run concurrently.
3888 */
3889 spin_lock(&dest->root_item_lock);
a7176f74 3890 if (dest->send_in_progress) {
f60a2364
MT
3891 spin_unlock(&dest->root_item_lock);
3892 btrfs_warn(fs_info,
3893 "attempt to delete subvolume %llu during send",
3894 dest->root_key.objectid);
3895 return -EPERM;
3896 }
a7176f74
LF
3897 root_flags = btrfs_root_flags(&dest->root_item);
3898 btrfs_set_root_flags(&dest->root_item,
3899 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3900 spin_unlock(&dest->root_item_lock);
f60a2364
MT
3901
3902 down_write(&fs_info->subvol_sem);
3903
3904 err = may_destroy_subvol(dest);
3905 if (err)
3906 goto out_up_write;
3907
3908 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3909 /*
3910 * One for dir inode,
3911 * two for dir entries,
3912 * two for root ref/backref.
3913 */
c4c129db 3914 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
f60a2364
MT
3915 if (err)
3916 goto out_up_write;
3917
3918 trans = btrfs_start_transaction(root, 0);
3919 if (IS_ERR(trans)) {
3920 err = PTR_ERR(trans);
3921 goto out_release;
3922 }
3923 trans->block_rsv = &block_rsv;
3924 trans->bytes_reserved = block_rsv.size;
3925
3926 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3927
045d3967 3928 ret = btrfs_unlink_subvol(trans, dir, dentry);
f60a2364
MT
3929 if (ret) {
3930 err = ret;
3931 btrfs_abort_transaction(trans, ret);
3932 goto out_end_trans;
3933 }
3934
3935 btrfs_record_root_in_trans(trans, dest);
3936
3937 memset(&dest->root_item.drop_progress, 0,
3938 sizeof(dest->root_item.drop_progress));
3939 dest->root_item.drop_level = 0;
3940 btrfs_set_root_refs(&dest->root_item, 0);
3941
3942 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3943 ret = btrfs_insert_orphan_item(trans,
3944 fs_info->tree_root,
3945 dest->root_key.objectid);
3946 if (ret) {
3947 btrfs_abort_transaction(trans, ret);
3948 err = ret;
3949 goto out_end_trans;
3950 }
3951 }
3952
d1957791 3953 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
f60a2364
MT
3954 BTRFS_UUID_KEY_SUBVOL,
3955 dest->root_key.objectid);
3956 if (ret && ret != -ENOENT) {
3957 btrfs_abort_transaction(trans, ret);
3958 err = ret;
3959 goto out_end_trans;
3960 }
3961 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
d1957791 3962 ret = btrfs_uuid_tree_remove(trans,
f60a2364
MT
3963 dest->root_item.received_uuid,
3964 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3965 dest->root_key.objectid);
3966 if (ret && ret != -ENOENT) {
3967 btrfs_abort_transaction(trans, ret);
3968 err = ret;
3969 goto out_end_trans;
3970 }
3971 }
3972
3973out_end_trans:
3974 trans->block_rsv = NULL;
3975 trans->bytes_reserved = 0;
3976 ret = btrfs_end_transaction(trans);
3977 if (ret && !err)
3978 err = ret;
3979 inode->i_flags |= S_DEAD;
3980out_release:
3981 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3982out_up_write:
3983 up_write(&fs_info->subvol_sem);
3984 if (err) {
3985 spin_lock(&dest->root_item_lock);
3986 root_flags = btrfs_root_flags(&dest->root_item);
3987 btrfs_set_root_flags(&dest->root_item,
3988 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3989 spin_unlock(&dest->root_item_lock);
3990 } else {
3991 d_invalidate(dentry);
20a68004 3992 btrfs_prune_dentries(dest);
f60a2364
MT
3993 ASSERT(dest->send_in_progress == 0);
3994
3995 /* the last ref */
3996 if (dest->ino_cache_inode) {
3997 iput(dest->ino_cache_inode);
3998 dest->ino_cache_inode = NULL;
3999 }
4000 }
4001
4002 return err;
4003}
4004
39279cc3
CM
4005static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4006{
2b0143b5 4007 struct inode *inode = d_inode(dentry);
1832a6d5 4008 int err = 0;
39279cc3 4009 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 4010 struct btrfs_trans_handle *trans;
44f714da 4011 u64 last_unlink_trans;
39279cc3 4012
b3ae244e 4013 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
134d4512 4014 return -ENOTEMPTY;
4a0cc7ca 4015 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
a79a464d 4016 return btrfs_delete_subvolume(dir, dentry);
134d4512 4017
d52be818 4018 trans = __unlink_start_trans(dir);
a22285a6 4019 if (IS_ERR(trans))
5df6a9f6 4020 return PTR_ERR(trans);
5df6a9f6 4021
4a0cc7ca 4022 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
045d3967 4023 err = btrfs_unlink_subvol(trans, dir, dentry);
4df27c4d
YZ
4024 goto out;
4025 }
4026
73f2e545 4027 err = btrfs_orphan_add(trans, BTRFS_I(inode));
7b128766 4028 if (err)
4df27c4d 4029 goto out;
7b128766 4030
44f714da
FM
4031 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4032
39279cc3 4033 /* now the directory is empty */
4ec5934e
NB
4034 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4035 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4036 dentry->d_name.len);
44f714da 4037 if (!err) {
6ef06d27 4038 btrfs_i_size_write(BTRFS_I(inode), 0);
44f714da
FM
4039 /*
4040 * Propagate the last_unlink_trans value of the deleted dir to
4041 * its parent directory. This is to prevent an unrecoverable
4042 * log tree in the case we do something like this:
4043 * 1) create dir foo
4044 * 2) create snapshot under dir foo
4045 * 3) delete the snapshot
4046 * 4) rmdir foo
4047 * 5) mkdir foo
4048 * 6) fsync foo or some file inside foo
4049 */
4050 if (last_unlink_trans >= trans->transid)
4051 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4052 }
4df27c4d 4053out:
3a45bb20 4054 btrfs_end_transaction(trans);
2ff7e61e 4055 btrfs_btree_balance_dirty(root->fs_info);
3954401f 4056
39279cc3
CM
4057 return err;
4058}
4059
ddfae63c
JB
4060/*
4061 * Return this if we need to call truncate_block for the last bit of the
4062 * truncate.
4063 */
4064#define NEED_TRUNCATE_BLOCK 1
0305cd5f 4065
39279cc3
CM
4066/*
4067 * this can truncate away extent items, csum items and directory items.
4068 * It starts at a high offset and removes keys until it can't find
d352ac68 4069 * any higher than new_size
39279cc3
CM
4070 *
4071 * csum items that cross the new i_size are truncated to the new size
4072 * as well.
7b128766
JB
4073 *
4074 * min_type is the minimum key type to truncate down to. If set to 0, this
4075 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 4076 */
8082510e
YZ
4077int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4078 struct btrfs_root *root,
4079 struct inode *inode,
4080 u64 new_size, u32 min_type)
39279cc3 4081{
0b246afa 4082 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 4083 struct btrfs_path *path;
5f39d397 4084 struct extent_buffer *leaf;
39279cc3 4085 struct btrfs_file_extent_item *fi;
8082510e
YZ
4086 struct btrfs_key key;
4087 struct btrfs_key found_key;
39279cc3 4088 u64 extent_start = 0;
db94535d 4089 u64 extent_num_bytes = 0;
5d4f98a2 4090 u64 extent_offset = 0;
39279cc3 4091 u64 item_end = 0;
c1aa4575 4092 u64 last_size = new_size;
8082510e 4093 u32 found_type = (u8)-1;
39279cc3
CM
4094 int found_extent;
4095 int del_item;
85e21bac
CM
4096 int pending_del_nr = 0;
4097 int pending_del_slot = 0;
179e29e4 4098 int extent_type = -1;
8082510e 4099 int ret;
4a0cc7ca 4100 u64 ino = btrfs_ino(BTRFS_I(inode));
28ed1345 4101 u64 bytes_deleted = 0;
897ca819
TM
4102 bool be_nice = false;
4103 bool should_throttle = false;
28553fa9
FM
4104 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4105 struct extent_state *cached_state = NULL;
8082510e
YZ
4106
4107 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 4108
28ed1345
CM
4109 /*
4110 * for non-free space inodes and ref cows, we want to back off from
4111 * time to time
4112 */
70ddc553 4113 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
28ed1345 4114 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
897ca819 4115 be_nice = true;
28ed1345 4116
0eb0e19c
MF
4117 path = btrfs_alloc_path();
4118 if (!path)
4119 return -ENOMEM;
e4058b54 4120 path->reada = READA_BACK;
0eb0e19c 4121
a5ae50de
FM
4122 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4123 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4124 &cached_state);
28553fa9 4125
5dc562c5
JB
4126 /*
4127 * We want to drop from the next block forward in case this new size is
4128 * not block aligned since we will be keeping the last block of the
4129 * extent just the way it is.
4130 */
27cdeb70 4131 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4132 root == fs_info->tree_root)
dcdbc059 4133 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
0b246afa 4134 fs_info->sectorsize),
da17066c 4135 (u64)-1, 0);
8082510e 4136
16cdcec7
MX
4137 /*
4138 * This function is also used to drop the items in the log tree before
4139 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
52042d8e 4140 * it is used to drop the logged items. So we shouldn't kill the delayed
16cdcec7
MX
4141 * items.
4142 */
4143 if (min_type == 0 && root == BTRFS_I(inode)->root)
4ccb5c72 4144 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
16cdcec7 4145
33345d01 4146 key.objectid = ino;
39279cc3 4147 key.offset = (u64)-1;
5f39d397
CM
4148 key.type = (u8)-1;
4149
85e21bac 4150search_again:
28ed1345
CM
4151 /*
4152 * with a 16K leaf size and 128MB extents, you can actually queue
4153 * up a huge file in a single leaf. Most of the time that
4154 * bytes_deleted is > 0, it will be huge by the time we get here
4155 */
fd86a3a3
OS
4156 if (be_nice && bytes_deleted > SZ_32M &&
4157 btrfs_should_end_transaction(trans)) {
4158 ret = -EAGAIN;
4159 goto out;
28ed1345
CM
4160 }
4161
85e21bac 4162 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
fd86a3a3 4163 if (ret < 0)
8082510e 4164 goto out;
d397712b 4165
85e21bac 4166 if (ret > 0) {
fd86a3a3 4167 ret = 0;
e02119d5
CM
4168 /* there are no items in the tree for us to truncate, we're
4169 * done
4170 */
8082510e
YZ
4171 if (path->slots[0] == 0)
4172 goto out;
85e21bac
CM
4173 path->slots[0]--;
4174 }
4175
d397712b 4176 while (1) {
9ddc959e
JB
4177 u64 clear_start = 0, clear_len = 0;
4178
39279cc3 4179 fi = NULL;
5f39d397
CM
4180 leaf = path->nodes[0];
4181 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 4182 found_type = found_key.type;
39279cc3 4183
33345d01 4184 if (found_key.objectid != ino)
39279cc3 4185 break;
5f39d397 4186
85e21bac 4187 if (found_type < min_type)
39279cc3
CM
4188 break;
4189
5f39d397 4190 item_end = found_key.offset;
39279cc3 4191 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 4192 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 4193 struct btrfs_file_extent_item);
179e29e4
CM
4194 extent_type = btrfs_file_extent_type(leaf, fi);
4195 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 4196 item_end +=
db94535d 4197 btrfs_file_extent_num_bytes(leaf, fi);
09ed2f16
LB
4198
4199 trace_btrfs_truncate_show_fi_regular(
4200 BTRFS_I(inode), leaf, fi,
4201 found_key.offset);
179e29e4 4202 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
e41ca589
QW
4203 item_end += btrfs_file_extent_ram_bytes(leaf,
4204 fi);
09ed2f16
LB
4205
4206 trace_btrfs_truncate_show_fi_inline(
4207 BTRFS_I(inode), leaf, fi, path->slots[0],
4208 found_key.offset);
39279cc3 4209 }
008630c1 4210 item_end--;
39279cc3 4211 }
8082510e
YZ
4212 if (found_type > min_type) {
4213 del_item = 1;
4214 } else {
76b42abb 4215 if (item_end < new_size)
b888db2b 4216 break;
8082510e
YZ
4217 if (found_key.offset >= new_size)
4218 del_item = 1;
4219 else
4220 del_item = 0;
39279cc3 4221 }
39279cc3 4222 found_extent = 0;
39279cc3 4223 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
4224 if (found_type != BTRFS_EXTENT_DATA_KEY)
4225 goto delete;
4226
4227 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 4228 u64 num_dec;
9ddc959e
JB
4229
4230 clear_start = found_key.offset;
db94535d 4231 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
f70a9a6b 4232 if (!del_item) {
db94535d
CM
4233 u64 orig_num_bytes =
4234 btrfs_file_extent_num_bytes(leaf, fi);
fda2832f
QW
4235 extent_num_bytes = ALIGN(new_size -
4236 found_key.offset,
0b246afa 4237 fs_info->sectorsize);
9ddc959e 4238 clear_start = ALIGN(new_size, fs_info->sectorsize);
db94535d
CM
4239 btrfs_set_file_extent_num_bytes(leaf, fi,
4240 extent_num_bytes);
4241 num_dec = (orig_num_bytes -
9069218d 4242 extent_num_bytes);
27cdeb70
MX
4243 if (test_bit(BTRFS_ROOT_REF_COWS,
4244 &root->state) &&
4245 extent_start != 0)
a76a3cd4 4246 inode_sub_bytes(inode, num_dec);
5f39d397 4247 btrfs_mark_buffer_dirty(leaf);
39279cc3 4248 } else {
db94535d
CM
4249 extent_num_bytes =
4250 btrfs_file_extent_disk_num_bytes(leaf,
4251 fi);
5d4f98a2
YZ
4252 extent_offset = found_key.offset -
4253 btrfs_file_extent_offset(leaf, fi);
4254
39279cc3 4255 /* FIXME blocksize != 4096 */
9069218d 4256 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
4257 if (extent_start != 0) {
4258 found_extent = 1;
27cdeb70
MX
4259 if (test_bit(BTRFS_ROOT_REF_COWS,
4260 &root->state))
a76a3cd4 4261 inode_sub_bytes(inode, num_dec);
e02119d5 4262 }
39279cc3 4263 }
9ddc959e 4264 clear_len = num_dec;
9069218d 4265 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
4266 /*
4267 * we can't truncate inline items that have had
4268 * special encodings
4269 */
4270 if (!del_item &&
c8b97818 4271 btrfs_file_extent_encryption(leaf, fi) == 0 &&
ddfae63c
JB
4272 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4273 btrfs_file_extent_compression(leaf, fi) == 0) {
4274 u32 size = (u32)(new_size - found_key.offset);
4275
4276 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4277 size = btrfs_file_extent_calc_inline_size(size);
78ac4f9e 4278 btrfs_truncate_item(path, size, 1);
ddfae63c 4279 } else if (!del_item) {
514ac8ad 4280 /*
ddfae63c
JB
4281 * We have to bail so the last_size is set to
4282 * just before this extent.
514ac8ad 4283 */
fd86a3a3 4284 ret = NEED_TRUNCATE_BLOCK;
ddfae63c 4285 break;
9ddc959e
JB
4286 } else {
4287 /*
4288 * Inline extents are special, we just treat
4289 * them as a full sector worth in the file
4290 * extent tree just for simplicity sake.
4291 */
4292 clear_len = fs_info->sectorsize;
ddfae63c 4293 }
0305cd5f 4294
ddfae63c 4295 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
0305cd5f 4296 inode_sub_bytes(inode, item_end + 1 - new_size);
39279cc3 4297 }
179e29e4 4298delete:
9ddc959e
JB
4299 /*
4300 * We use btrfs_truncate_inode_items() to clean up log trees for
4301 * multiple fsyncs, and in this case we don't want to clear the
4302 * file extent range because it's just the log.
4303 */
4304 if (root == BTRFS_I(inode)->root) {
4305 ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4306 clear_start, clear_len);
4307 if (ret) {
4308 btrfs_abort_transaction(trans, ret);
4309 break;
4310 }
4311 }
4312
ddfae63c
JB
4313 if (del_item)
4314 last_size = found_key.offset;
4315 else
4316 last_size = new_size;
39279cc3 4317 if (del_item) {
85e21bac
CM
4318 if (!pending_del_nr) {
4319 /* no pending yet, add ourselves */
4320 pending_del_slot = path->slots[0];
4321 pending_del_nr = 1;
4322 } else if (pending_del_nr &&
4323 path->slots[0] + 1 == pending_del_slot) {
4324 /* hop on the pending chunk */
4325 pending_del_nr++;
4326 pending_del_slot = path->slots[0];
4327 } else {
d397712b 4328 BUG();
85e21bac 4329 }
39279cc3
CM
4330 } else {
4331 break;
4332 }
897ca819 4333 should_throttle = false;
28f75a0e 4334
27cdeb70
MX
4335 if (found_extent &&
4336 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4337 root == fs_info->tree_root)) {
ffd4bb2a
QW
4338 struct btrfs_ref ref = { 0 };
4339
28ed1345 4340 bytes_deleted += extent_num_bytes;
ffd4bb2a
QW
4341
4342 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4343 extent_start, extent_num_bytes, 0);
4344 ref.real_root = root->root_key.objectid;
4345 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4346 ino, extent_offset);
4347 ret = btrfs_free_extent(trans, &ref);
05522109
OS
4348 if (ret) {
4349 btrfs_abort_transaction(trans, ret);
4350 break;
4351 }
28f75a0e 4352 if (be_nice) {
7c861627 4353 if (btrfs_should_throttle_delayed_refs(trans))
897ca819 4354 should_throttle = true;
28f75a0e 4355 }
39279cc3 4356 }
85e21bac 4357
8082510e
YZ
4358 if (found_type == BTRFS_INODE_ITEM_KEY)
4359 break;
4360
4361 if (path->slots[0] == 0 ||
1262133b 4362 path->slots[0] != pending_del_slot ||
28bad212 4363 should_throttle) {
8082510e
YZ
4364 if (pending_del_nr) {
4365 ret = btrfs_del_items(trans, root, path,
4366 pending_del_slot,
4367 pending_del_nr);
79787eaa 4368 if (ret) {
66642832 4369 btrfs_abort_transaction(trans, ret);
fd86a3a3 4370 break;
79787eaa 4371 }
8082510e
YZ
4372 pending_del_nr = 0;
4373 }
b3b4aa74 4374 btrfs_release_path(path);
28bad212 4375
28f75a0e 4376 /*
28bad212
JB
4377 * We can generate a lot of delayed refs, so we need to
4378 * throttle every once and a while and make sure we're
4379 * adding enough space to keep up with the work we are
4380 * generating. Since we hold a transaction here we
4381 * can't flush, and we don't want to FLUSH_LIMIT because
4382 * we could have generated too many delayed refs to
4383 * actually allocate, so just bail if we're short and
4384 * let the normal reservation dance happen higher up.
28f75a0e 4385 */
28bad212
JB
4386 if (should_throttle) {
4387 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4388 BTRFS_RESERVE_NO_FLUSH);
4389 if (ret) {
4390 ret = -EAGAIN;
4391 break;
4392 }
28f75a0e 4393 }
85e21bac 4394 goto search_again;
8082510e
YZ
4395 } else {
4396 path->slots[0]--;
85e21bac 4397 }
39279cc3 4398 }
8082510e 4399out:
fd86a3a3
OS
4400 if (ret >= 0 && pending_del_nr) {
4401 int err;
4402
4403 err = btrfs_del_items(trans, root, path, pending_del_slot,
85e21bac 4404 pending_del_nr);
fd86a3a3
OS
4405 if (err) {
4406 btrfs_abort_transaction(trans, err);
4407 ret = err;
4408 }
85e21bac 4409 }
76b42abb
FM
4410 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4411 ASSERT(last_size >= new_size);
fd86a3a3 4412 if (!ret && last_size > new_size)
76b42abb 4413 last_size = new_size;
d923afe9 4414 btrfs_inode_safe_disk_i_size_write(inode, last_size);
a5ae50de
FM
4415 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4416 (u64)-1, &cached_state);
76b42abb 4417 }
28ed1345 4418
39279cc3 4419 btrfs_free_path(path);
fd86a3a3 4420 return ret;
39279cc3
CM
4421}
4422
4423/*
9703fefe 4424 * btrfs_truncate_block - read, zero a chunk and write a block
2aaa6655
JB
4425 * @inode - inode that we're zeroing
4426 * @from - the offset to start zeroing
4427 * @len - the length to zero, 0 to zero the entire range respective to the
4428 * offset
4429 * @front - zero up to the offset instead of from the offset on
4430 *
9703fefe 4431 * This will find the block for the "from" offset and cow the block and zero the
2aaa6655 4432 * part we want to zero. This is used with truncate and hole punching.
39279cc3 4433 */
9703fefe 4434int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
2aaa6655 4435 int front)
39279cc3 4436{
0b246afa 4437 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2aaa6655 4438 struct address_space *mapping = inode->i_mapping;
e6dcd2dc
CM
4439 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4440 struct btrfs_ordered_extent *ordered;
2ac55d41 4441 struct extent_state *cached_state = NULL;
364ecf36 4442 struct extent_changeset *data_reserved = NULL;
e6dcd2dc 4443 char *kaddr;
0b246afa 4444 u32 blocksize = fs_info->sectorsize;
09cbfeaf 4445 pgoff_t index = from >> PAGE_SHIFT;
9703fefe 4446 unsigned offset = from & (blocksize - 1);
39279cc3 4447 struct page *page;
3b16a4e3 4448 gfp_t mask = btrfs_alloc_write_mask(mapping);
39279cc3 4449 int ret = 0;
9703fefe
CR
4450 u64 block_start;
4451 u64 block_end;
39279cc3 4452
b03ebd99
NB
4453 if (IS_ALIGNED(offset, blocksize) &&
4454 (!len || IS_ALIGNED(len, blocksize)))
39279cc3 4455 goto out;
9703fefe 4456
8b62f87b
JB
4457 block_start = round_down(from, blocksize);
4458 block_end = block_start + blocksize - 1;
4459
364ecf36 4460 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8b62f87b 4461 block_start, blocksize);
5d5e103a
JB
4462 if (ret)
4463 goto out;
39279cc3 4464
211c17f5 4465again:
3b16a4e3 4466 page = find_or_create_page(mapping, index, mask);
5d5e103a 4467 if (!page) {
bc42bda2 4468 btrfs_delalloc_release_space(inode, data_reserved,
43b18595 4469 block_start, blocksize, true);
8702ba93 4470 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
ac6a2b36 4471 ret = -ENOMEM;
39279cc3 4472 goto out;
5d5e103a 4473 }
e6dcd2dc 4474
39279cc3 4475 if (!PageUptodate(page)) {
9ebefb18 4476 ret = btrfs_readpage(NULL, page);
39279cc3 4477 lock_page(page);
211c17f5
CM
4478 if (page->mapping != mapping) {
4479 unlock_page(page);
09cbfeaf 4480 put_page(page);
211c17f5
CM
4481 goto again;
4482 }
39279cc3
CM
4483 if (!PageUptodate(page)) {
4484 ret = -EIO;
89642229 4485 goto out_unlock;
39279cc3
CM
4486 }
4487 }
211c17f5 4488 wait_on_page_writeback(page);
e6dcd2dc 4489
9703fefe 4490 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
e6dcd2dc
CM
4491 set_page_extent_mapped(page);
4492
9703fefe 4493 ordered = btrfs_lookup_ordered_extent(inode, block_start);
e6dcd2dc 4494 if (ordered) {
9703fefe 4495 unlock_extent_cached(io_tree, block_start, block_end,
e43bbe5e 4496 &cached_state);
e6dcd2dc 4497 unlock_page(page);
09cbfeaf 4498 put_page(page);
eb84ae03 4499 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
4500 btrfs_put_ordered_extent(ordered);
4501 goto again;
4502 }
4503
9703fefe 4504 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
e182163d
OS
4505 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4506 0, 0, &cached_state);
5d5e103a 4507
e3b8a485 4508 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
330a5827 4509 &cached_state);
9ed74f2d 4510 if (ret) {
9703fefe 4511 unlock_extent_cached(io_tree, block_start, block_end,
e43bbe5e 4512 &cached_state);
9ed74f2d
JB
4513 goto out_unlock;
4514 }
4515
9703fefe 4516 if (offset != blocksize) {
2aaa6655 4517 if (!len)
9703fefe 4518 len = blocksize - offset;
e6dcd2dc 4519 kaddr = kmap(page);
2aaa6655 4520 if (front)
9703fefe
CR
4521 memset(kaddr + (block_start - page_offset(page)),
4522 0, offset);
2aaa6655 4523 else
9703fefe
CR
4524 memset(kaddr + (block_start - page_offset(page)) + offset,
4525 0, len);
e6dcd2dc
CM
4526 flush_dcache_page(page);
4527 kunmap(page);
4528 }
247e743c 4529 ClearPageChecked(page);
e6dcd2dc 4530 set_page_dirty(page);
e43bbe5e 4531 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
39279cc3 4532
89642229 4533out_unlock:
5d5e103a 4534 if (ret)
bc42bda2 4535 btrfs_delalloc_release_space(inode, data_reserved, block_start,
43b18595 4536 blocksize, true);
8702ba93 4537 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
39279cc3 4538 unlock_page(page);
09cbfeaf 4539 put_page(page);
39279cc3 4540out:
364ecf36 4541 extent_changeset_free(data_reserved);
39279cc3
CM
4542 return ret;
4543}
4544
16e7549f
JB
4545static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4546 u64 offset, u64 len)
4547{
0b246afa 4548 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
16e7549f
JB
4549 struct btrfs_trans_handle *trans;
4550 int ret;
4551
4552 /*
4553 * Still need to make sure the inode looks like it's been updated so
4554 * that any holes get logged if we fsync.
4555 */
0b246afa
JM
4556 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4557 BTRFS_I(inode)->last_trans = fs_info->generation;
16e7549f
JB
4558 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4559 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4560 return 0;
4561 }
4562
4563 /*
4564 * 1 - for the one we're dropping
4565 * 1 - for the one we're adding
4566 * 1 - for updating the inode.
4567 */
4568 trans = btrfs_start_transaction(root, 3);
4569 if (IS_ERR(trans))
4570 return PTR_ERR(trans);
4571
4572 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4573 if (ret) {
66642832 4574 btrfs_abort_transaction(trans, ret);
3a45bb20 4575 btrfs_end_transaction(trans);
16e7549f
JB
4576 return ret;
4577 }
4578
f85b7379
DS
4579 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4580 offset, 0, 0, len, 0, len, 0, 0, 0);
16e7549f 4581 if (ret)
66642832 4582 btrfs_abort_transaction(trans, ret);
16e7549f
JB
4583 else
4584 btrfs_update_inode(trans, root, inode);
3a45bb20 4585 btrfs_end_transaction(trans);
16e7549f
JB
4586 return ret;
4587}
4588
695a0d0d
JB
4589/*
4590 * This function puts in dummy file extents for the area we're creating a hole
4591 * for. So if we are truncating this file to a larger size we need to insert
4592 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4593 * the range between oldsize and size
4594 */
a41ad394 4595int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 4596{
0b246afa 4597 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9036c102
YZ
4598 struct btrfs_root *root = BTRFS_I(inode)->root;
4599 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 4600 struct extent_map *em = NULL;
2ac55d41 4601 struct extent_state *cached_state = NULL;
5dc562c5 4602 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
0b246afa
JM
4603 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4604 u64 block_end = ALIGN(size, fs_info->sectorsize);
9036c102
YZ
4605 u64 last_byte;
4606 u64 cur_offset;
4607 u64 hole_size;
9ed74f2d 4608 int err = 0;
39279cc3 4609
a71754fc 4610 /*
9703fefe
CR
4611 * If our size started in the middle of a block we need to zero out the
4612 * rest of the block before we expand the i_size, otherwise we could
a71754fc
JB
4613 * expose stale data.
4614 */
9703fefe 4615 err = btrfs_truncate_block(inode, oldsize, 0, 0);
a71754fc
JB
4616 if (err)
4617 return err;
4618
9036c102
YZ
4619 if (size <= hole_start)
4620 return 0;
4621
b272ae22 4622 btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
23d31bd4 4623 block_end - 1, &cached_state);
9036c102
YZ
4624 cur_offset = hole_start;
4625 while (1) {
fc4f21b1 4626 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
39b07b5d 4627 block_end - cur_offset);
79787eaa
JM
4628 if (IS_ERR(em)) {
4629 err = PTR_ERR(em);
f2767956 4630 em = NULL;
79787eaa
JM
4631 break;
4632 }
9036c102 4633 last_byte = min(extent_map_end(em), block_end);
0b246afa 4634 last_byte = ALIGN(last_byte, fs_info->sectorsize);
9ddc959e
JB
4635 hole_size = last_byte - cur_offset;
4636
8082510e 4637 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5dc562c5 4638 struct extent_map *hole_em;
9ed74f2d 4639
16e7549f
JB
4640 err = maybe_insert_hole(root, inode, cur_offset,
4641 hole_size);
4642 if (err)
3893e33b 4643 break;
9ddc959e
JB
4644
4645 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4646 cur_offset, hole_size);
4647 if (err)
4648 break;
4649
dcdbc059 4650 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
4651 cur_offset + hole_size - 1, 0);
4652 hole_em = alloc_extent_map();
4653 if (!hole_em) {
4654 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4655 &BTRFS_I(inode)->runtime_flags);
4656 goto next;
4657 }
4658 hole_em->start = cur_offset;
4659 hole_em->len = hole_size;
4660 hole_em->orig_start = cur_offset;
8082510e 4661
5dc562c5
JB
4662 hole_em->block_start = EXTENT_MAP_HOLE;
4663 hole_em->block_len = 0;
b4939680 4664 hole_em->orig_block_len = 0;
cc95bef6 4665 hole_em->ram_bytes = hole_size;
5dc562c5 4666 hole_em->compress_type = BTRFS_COMPRESS_NONE;
0b246afa 4667 hole_em->generation = fs_info->generation;
8082510e 4668
5dc562c5
JB
4669 while (1) {
4670 write_lock(&em_tree->lock);
09a2a8f9 4671 err = add_extent_mapping(em_tree, hole_em, 1);
5dc562c5
JB
4672 write_unlock(&em_tree->lock);
4673 if (err != -EEXIST)
4674 break;
dcdbc059
NB
4675 btrfs_drop_extent_cache(BTRFS_I(inode),
4676 cur_offset,
5dc562c5
JB
4677 cur_offset +
4678 hole_size - 1, 0);
4679 }
4680 free_extent_map(hole_em);
9ddc959e
JB
4681 } else {
4682 err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4683 cur_offset, hole_size);
4684 if (err)
4685 break;
9036c102 4686 }
16e7549f 4687next:
9036c102 4688 free_extent_map(em);
a22285a6 4689 em = NULL;
9036c102 4690 cur_offset = last_byte;
8082510e 4691 if (cur_offset >= block_end)
9036c102
YZ
4692 break;
4693 }
a22285a6 4694 free_extent_map(em);
e43bbe5e 4695 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
9036c102
YZ
4696 return err;
4697}
39279cc3 4698
3972f260 4699static int btrfs_setsize(struct inode *inode, struct iattr *attr)
8082510e 4700{
f4a2f4c5
MX
4701 struct btrfs_root *root = BTRFS_I(inode)->root;
4702 struct btrfs_trans_handle *trans;
a41ad394 4703 loff_t oldsize = i_size_read(inode);
3972f260
ES
4704 loff_t newsize = attr->ia_size;
4705 int mask = attr->ia_valid;
8082510e
YZ
4706 int ret;
4707
3972f260
ES
4708 /*
4709 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4710 * special case where we need to update the times despite not having
4711 * these flags set. For all other operations the VFS set these flags
4712 * explicitly if it wants a timestamp update.
4713 */
dff6efc3
CH
4714 if (newsize != oldsize) {
4715 inode_inc_iversion(inode);
4716 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4717 inode->i_ctime = inode->i_mtime =
c2050a45 4718 current_time(inode);
dff6efc3 4719 }
3972f260 4720
a41ad394 4721 if (newsize > oldsize) {
9ea24bbe 4722 /*
ea14b57f 4723 * Don't do an expanding truncate while snapshotting is ongoing.
9ea24bbe
FM
4724 * This is to ensure the snapshot captures a fully consistent
4725 * state of this file - if the snapshot captures this expanding
4726 * truncation, it must capture all writes that happened before
4727 * this truncation.
4728 */
dcc3eb96 4729 btrfs_drew_write_lock(&root->snapshot_lock);
a41ad394 4730 ret = btrfs_cont_expand(inode, oldsize, newsize);
9ea24bbe 4731 if (ret) {
dcc3eb96 4732 btrfs_drew_write_unlock(&root->snapshot_lock);
8082510e 4733 return ret;
9ea24bbe 4734 }
8082510e 4735
f4a2f4c5 4736 trans = btrfs_start_transaction(root, 1);
9ea24bbe 4737 if (IS_ERR(trans)) {
dcc3eb96 4738 btrfs_drew_write_unlock(&root->snapshot_lock);
f4a2f4c5 4739 return PTR_ERR(trans);
9ea24bbe 4740 }
f4a2f4c5
MX
4741
4742 i_size_write(inode, newsize);
d923afe9 4743 btrfs_inode_safe_disk_i_size_write(inode, 0);
27772b68 4744 pagecache_isize_extended(inode, oldsize, newsize);
f4a2f4c5 4745 ret = btrfs_update_inode(trans, root, inode);
dcc3eb96 4746 btrfs_drew_write_unlock(&root->snapshot_lock);
3a45bb20 4747 btrfs_end_transaction(trans);
a41ad394 4748 } else {
8082510e 4749
a41ad394
JB
4750 /*
4751 * We're truncating a file that used to have good data down to
4752 * zero. Make sure it gets into the ordered flush list so that
4753 * any new writes get down to disk quickly.
4754 */
4755 if (newsize == 0)
72ac3c0d
JB
4756 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4757 &BTRFS_I(inode)->runtime_flags);
8082510e 4758
a41ad394 4759 truncate_setsize(inode, newsize);
2e60a51e 4760
52042d8e 4761 /* Disable nonlocked read DIO to avoid the endless truncate */
abcefb1e 4762 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
2e60a51e 4763 inode_dio_wait(inode);
0b581701 4764 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
2e60a51e 4765
213e8c55 4766 ret = btrfs_truncate(inode, newsize == oldsize);
7f4f6e0a
JB
4767 if (ret && inode->i_nlink) {
4768 int err;
4769
4770 /*
f7e9e8fc
OS
4771 * Truncate failed, so fix up the in-memory size. We
4772 * adjusted disk_i_size down as we removed extents, so
4773 * wait for disk_i_size to be stable and then update the
4774 * in-memory size to match.
7f4f6e0a 4775 */
f7e9e8fc 4776 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
7f4f6e0a 4777 if (err)
f7e9e8fc
OS
4778 return err;
4779 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
7f4f6e0a 4780 }
8082510e
YZ
4781 }
4782
a41ad394 4783 return ret;
8082510e
YZ
4784}
4785
9036c102
YZ
4786static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4787{
2b0143b5 4788 struct inode *inode = d_inode(dentry);
b83cc969 4789 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 4790 int err;
39279cc3 4791
b83cc969
LZ
4792 if (btrfs_root_readonly(root))
4793 return -EROFS;
4794
31051c85 4795 err = setattr_prepare(dentry, attr);
9036c102
YZ
4796 if (err)
4797 return err;
2bf5a725 4798
5a3f23d5 4799 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3972f260 4800 err = btrfs_setsize(inode, attr);
8082510e
YZ
4801 if (err)
4802 return err;
39279cc3 4803 }
9036c102 4804
1025774c
CH
4805 if (attr->ia_valid) {
4806 setattr_copy(inode, attr);
0c4d2d95 4807 inode_inc_iversion(inode);
22c44fe6 4808 err = btrfs_dirty_inode(inode);
1025774c 4809
22c44fe6 4810 if (!err && attr->ia_valid & ATTR_MODE)
996a710d 4811 err = posix_acl_chmod(inode, inode->i_mode);
1025774c 4812 }
33268eaf 4813
39279cc3
CM
4814 return err;
4815}
61295eb8 4816
131e404a
FDBM
4817/*
4818 * While truncating the inode pages during eviction, we get the VFS calling
4819 * btrfs_invalidatepage() against each page of the inode. This is slow because
4820 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4821 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4822 * extent_state structures over and over, wasting lots of time.
4823 *
4824 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4825 * those expensive operations on a per page basis and do only the ordered io
4826 * finishing, while we release here the extent_map and extent_state structures,
4827 * without the excessive merging and splitting.
4828 */
4829static void evict_inode_truncate_pages(struct inode *inode)
4830{
4831 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4832 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4833 struct rb_node *node;
4834
4835 ASSERT(inode->i_state & I_FREEING);
91b0abe3 4836 truncate_inode_pages_final(&inode->i_data);
131e404a
FDBM
4837
4838 write_lock(&map_tree->lock);
07e1ce09 4839 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
131e404a
FDBM
4840 struct extent_map *em;
4841
07e1ce09 4842 node = rb_first_cached(&map_tree->map);
131e404a 4843 em = rb_entry(node, struct extent_map, rb_node);
180589ef
WS
4844 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4845 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
131e404a
FDBM
4846 remove_extent_mapping(map_tree, em);
4847 free_extent_map(em);
7064dd5c
FM
4848 if (need_resched()) {
4849 write_unlock(&map_tree->lock);
4850 cond_resched();
4851 write_lock(&map_tree->lock);
4852 }
131e404a
FDBM
4853 }
4854 write_unlock(&map_tree->lock);
4855
6ca07097
FM
4856 /*
4857 * Keep looping until we have no more ranges in the io tree.
4858 * We can have ongoing bios started by readpages (called from readahead)
9c6429d9
FM
4859 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4860 * still in progress (unlocked the pages in the bio but did not yet
4861 * unlocked the ranges in the io tree). Therefore this means some
6ca07097
FM
4862 * ranges can still be locked and eviction started because before
4863 * submitting those bios, which are executed by a separate task (work
4864 * queue kthread), inode references (inode->i_count) were not taken
4865 * (which would be dropped in the end io callback of each bio).
4866 * Therefore here we effectively end up waiting for those bios and
4867 * anyone else holding locked ranges without having bumped the inode's
4868 * reference count - if we don't do it, when they access the inode's
4869 * io_tree to unlock a range it may be too late, leading to an
4870 * use-after-free issue.
4871 */
131e404a
FDBM
4872 spin_lock(&io_tree->lock);
4873 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4874 struct extent_state *state;
4875 struct extent_state *cached_state = NULL;
6ca07097
FM
4876 u64 start;
4877 u64 end;
421f0922 4878 unsigned state_flags;
131e404a
FDBM
4879
4880 node = rb_first(&io_tree->state);
4881 state = rb_entry(node, struct extent_state, rb_node);
6ca07097
FM
4882 start = state->start;
4883 end = state->end;
421f0922 4884 state_flags = state->state;
131e404a
FDBM
4885 spin_unlock(&io_tree->lock);
4886
ff13db41 4887 lock_extent_bits(io_tree, start, end, &cached_state);
b9d0b389
QW
4888
4889 /*
4890 * If still has DELALLOC flag, the extent didn't reach disk,
4891 * and its reserved space won't be freed by delayed_ref.
4892 * So we need to free its reserved space here.
4893 * (Refer to comment in btrfs_invalidatepage, case 2)
4894 *
4895 * Note, end is the bytenr of last byte, so we need + 1 here.
4896 */
421f0922 4897 if (state_flags & EXTENT_DELALLOC)
bc42bda2 4898 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
b9d0b389 4899
6ca07097 4900 clear_extent_bit(io_tree, start, end,
e182163d
OS
4901 EXTENT_LOCKED | EXTENT_DELALLOC |
4902 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4903 &cached_state);
131e404a 4904
7064dd5c 4905 cond_resched();
131e404a
FDBM
4906 spin_lock(&io_tree->lock);
4907 }
4908 spin_unlock(&io_tree->lock);
4909}
4910
4b9d7b59 4911static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
ad80cf50 4912 struct btrfs_block_rsv *rsv)
4b9d7b59
OS
4913{
4914 struct btrfs_fs_info *fs_info = root->fs_info;
4915 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
d3984c90 4916 struct btrfs_trans_handle *trans;
2bd36e7b 4917 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
d3984c90 4918 int ret;
4b9d7b59 4919
d3984c90
JB
4920 /*
4921 * Eviction should be taking place at some place safe because of our
4922 * delayed iputs. However the normal flushing code will run delayed
4923 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4924 *
4925 * We reserve the delayed_refs_extra here again because we can't use
4926 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4927 * above. We reserve our extra bit here because we generate a ton of
4928 * delayed refs activity by truncating.
4929 *
4930 * If we cannot make our reservation we'll attempt to steal from the
4931 * global reserve, because we really want to be able to free up space.
4932 */
4933 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4934 BTRFS_RESERVE_FLUSH_EVICT);
4935 if (ret) {
4b9d7b59
OS
4936 /*
4937 * Try to steal from the global reserve if there is space for
4938 * it.
4939 */
d3984c90
JB
4940 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4941 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4942 btrfs_warn(fs_info,
4943 "could not allocate space for delete; will truncate on mount");
4944 return ERR_PTR(-ENOSPC);
4945 }
4946 delayed_refs_extra = 0;
4947 }
4b9d7b59 4948
d3984c90
JB
4949 trans = btrfs_join_transaction(root);
4950 if (IS_ERR(trans))
4951 return trans;
4952
4953 if (delayed_refs_extra) {
4954 trans->block_rsv = &fs_info->trans_block_rsv;
4955 trans->bytes_reserved = delayed_refs_extra;
4956 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4957 delayed_refs_extra, 1);
4b9d7b59 4958 }
d3984c90 4959 return trans;
4b9d7b59
OS
4960}
4961
bd555975 4962void btrfs_evict_inode(struct inode *inode)
39279cc3 4963{
0b246afa 4964 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
4965 struct btrfs_trans_handle *trans;
4966 struct btrfs_root *root = BTRFS_I(inode)->root;
4b9d7b59 4967 struct btrfs_block_rsv *rsv;
39279cc3
CM
4968 int ret;
4969
1abe9b8a 4970 trace_btrfs_inode_evict(inode);
4971
3d48d981 4972 if (!root) {
e8f1bc14 4973 clear_inode(inode);
3d48d981
NB
4974 return;
4975 }
4976
131e404a
FDBM
4977 evict_inode_truncate_pages(inode);
4978
69e9c6c6
SB
4979 if (inode->i_nlink &&
4980 ((btrfs_root_refs(&root->root_item) != 0 &&
4981 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
70ddc553 4982 btrfs_is_free_space_inode(BTRFS_I(inode))))
bd555975
AV
4983 goto no_delete;
4984
27919067 4985 if (is_bad_inode(inode))
39279cc3 4986 goto no_delete;
5f39d397 4987
7ab7956e 4988 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
f612496b 4989
7b40b695 4990 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
c71bf099 4991 goto no_delete;
c71bf099 4992
76dda93c 4993 if (inode->i_nlink > 0) {
69e9c6c6
SB
4994 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4995 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
76dda93c
YZ
4996 goto no_delete;
4997 }
4998
aa79021f 4999 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
27919067 5000 if (ret)
0e8c36a9 5001 goto no_delete;
0e8c36a9 5002
2ff7e61e 5003 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
27919067 5004 if (!rsv)
4289a667 5005 goto no_delete;
2bd36e7b 5006 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
ca7e70f5 5007 rsv->failfast = 1;
4289a667 5008
6ef06d27 5009 btrfs_i_size_write(BTRFS_I(inode), 0);
5f39d397 5010
8082510e 5011 while (1) {
ad80cf50 5012 trans = evict_refill_and_join(root, rsv);
27919067
OS
5013 if (IS_ERR(trans))
5014 goto free_rsv;
7b128766 5015
4289a667
JB
5016 trans->block_rsv = rsv;
5017
d68fc57b 5018 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
27919067
OS
5019 trans->block_rsv = &fs_info->trans_block_rsv;
5020 btrfs_end_transaction(trans);
5021 btrfs_btree_balance_dirty(fs_info);
5022 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5023 goto free_rsv;
5024 else if (!ret)
8082510e 5025 break;
8082510e 5026 }
5f39d397 5027
4ef31a45 5028 /*
27919067
OS
5029 * Errors here aren't a big deal, it just means we leave orphan items in
5030 * the tree. They will be cleaned up on the next mount. If the inode
5031 * number gets reused, cleanup deletes the orphan item without doing
5032 * anything, and unlink reuses the existing orphan item.
5033 *
5034 * If it turns out that we are dropping too many of these, we might want
5035 * to add a mechanism for retrying these after a commit.
4ef31a45 5036 */
ad80cf50 5037 trans = evict_refill_and_join(root, rsv);
27919067
OS
5038 if (!IS_ERR(trans)) {
5039 trans->block_rsv = rsv;
5040 btrfs_orphan_del(trans, BTRFS_I(inode));
5041 trans->block_rsv = &fs_info->trans_block_rsv;
5042 btrfs_end_transaction(trans);
5043 }
54aa1f4d 5044
0b246afa 5045 if (!(root == fs_info->tree_root ||
581bb050 5046 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4a0cc7ca 5047 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
581bb050 5048
27919067
OS
5049free_rsv:
5050 btrfs_free_block_rsv(fs_info, rsv);
39279cc3 5051no_delete:
27919067
OS
5052 /*
5053 * If we didn't successfully delete, the orphan item will still be in
5054 * the tree and we'll retry on the next mount. Again, we might also want
5055 * to retry these periodically in the future.
5056 */
f48d1cf5 5057 btrfs_remove_delayed_node(BTRFS_I(inode));
dbd5768f 5058 clear_inode(inode);
39279cc3
CM
5059}
5060
5061/*
6bf9e4bd
QW
5062 * Return the key found in the dir entry in the location pointer, fill @type
5063 * with BTRFS_FT_*, and return 0.
5064 *
005d6712
SY
5065 * If no dir entries were found, returns -ENOENT.
5066 * If found a corrupted location in dir entry, returns -EUCLEAN.
39279cc3
CM
5067 */
5068static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
6bf9e4bd 5069 struct btrfs_key *location, u8 *type)
39279cc3
CM
5070{
5071 const char *name = dentry->d_name.name;
5072 int namelen = dentry->d_name.len;
5073 struct btrfs_dir_item *di;
5074 struct btrfs_path *path;
5075 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 5076 int ret = 0;
39279cc3
CM
5077
5078 path = btrfs_alloc_path();
d8926bb3
MF
5079 if (!path)
5080 return -ENOMEM;
3954401f 5081
f85b7379
DS
5082 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5083 name, namelen, 0);
3cf5068f
LB
5084 if (IS_ERR_OR_NULL(di)) {
5085 ret = di ? PTR_ERR(di) : -ENOENT;
005d6712
SY
5086 goto out;
5087 }
d397712b 5088
5f39d397 5089 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
56a0e706
LB
5090 if (location->type != BTRFS_INODE_ITEM_KEY &&
5091 location->type != BTRFS_ROOT_ITEM_KEY) {
005d6712 5092 ret = -EUCLEAN;
56a0e706
LB
5093 btrfs_warn(root->fs_info,
5094"%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5095 __func__, name, btrfs_ino(BTRFS_I(dir)),
5096 location->objectid, location->type, location->offset);
56a0e706 5097 }
6bf9e4bd
QW
5098 if (!ret)
5099 *type = btrfs_dir_type(path->nodes[0], di);
39279cc3 5100out:
39279cc3
CM
5101 btrfs_free_path(path);
5102 return ret;
5103}
5104
5105/*
5106 * when we hit a tree root in a directory, the btrfs part of the inode
5107 * needs to be changed to reflect the root directory of the tree root. This
5108 * is kind of like crossing a mount point.
5109 */
2ff7e61e 5110static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
4df27c4d
YZ
5111 struct inode *dir,
5112 struct dentry *dentry,
5113 struct btrfs_key *location,
5114 struct btrfs_root **sub_root)
39279cc3 5115{
4df27c4d
YZ
5116 struct btrfs_path *path;
5117 struct btrfs_root *new_root;
5118 struct btrfs_root_ref *ref;
5119 struct extent_buffer *leaf;
1d4c08e0 5120 struct btrfs_key key;
4df27c4d
YZ
5121 int ret;
5122 int err = 0;
39279cc3 5123
4df27c4d
YZ
5124 path = btrfs_alloc_path();
5125 if (!path) {
5126 err = -ENOMEM;
5127 goto out;
5128 }
39279cc3 5129
4df27c4d 5130 err = -ENOENT;
1d4c08e0
DS
5131 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5132 key.type = BTRFS_ROOT_REF_KEY;
5133 key.offset = location->objectid;
5134
0b246afa 5135 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4df27c4d
YZ
5136 if (ret) {
5137 if (ret < 0)
5138 err = ret;
5139 goto out;
5140 }
39279cc3 5141
4df27c4d
YZ
5142 leaf = path->nodes[0];
5143 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4a0cc7ca 5144 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
4df27c4d
YZ
5145 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5146 goto out;
39279cc3 5147
4df27c4d
YZ
5148 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5149 (unsigned long)(ref + 1),
5150 dentry->d_name.len);
5151 if (ret)
5152 goto out;
5153
b3b4aa74 5154 btrfs_release_path(path);
4df27c4d 5155
3619c94f 5156 new_root = btrfs_get_fs_root(fs_info, location, true);
4df27c4d
YZ
5157 if (IS_ERR(new_root)) {
5158 err = PTR_ERR(new_root);
5159 goto out;
5160 }
5161
4df27c4d
YZ
5162 *sub_root = new_root;
5163 location->objectid = btrfs_root_dirid(&new_root->root_item);
5164 location->type = BTRFS_INODE_ITEM_KEY;
5165 location->offset = 0;
5166 err = 0;
5167out:
5168 btrfs_free_path(path);
5169 return err;
39279cc3
CM
5170}
5171
5d4f98a2
YZ
5172static void inode_tree_add(struct inode *inode)
5173{
5174 struct btrfs_root *root = BTRFS_I(inode)->root;
5175 struct btrfs_inode *entry;
03e860bd
NP
5176 struct rb_node **p;
5177 struct rb_node *parent;
cef21937 5178 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4a0cc7ca 5179 u64 ino = btrfs_ino(BTRFS_I(inode));
5d4f98a2 5180
1d3382cb 5181 if (inode_unhashed(inode))
76dda93c 5182 return;
e1409cef 5183 parent = NULL;
5d4f98a2 5184 spin_lock(&root->inode_lock);
e1409cef 5185 p = &root->inode_tree.rb_node;
5d4f98a2
YZ
5186 while (*p) {
5187 parent = *p;
5188 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5189
37508515 5190 if (ino < btrfs_ino(entry))
03e860bd 5191 p = &parent->rb_left;
37508515 5192 else if (ino > btrfs_ino(entry))
03e860bd 5193 p = &parent->rb_right;
5d4f98a2
YZ
5194 else {
5195 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 5196 (I_WILL_FREE | I_FREEING)));
cef21937 5197 rb_replace_node(parent, new, &root->inode_tree);
03e860bd
NP
5198 RB_CLEAR_NODE(parent);
5199 spin_unlock(&root->inode_lock);
cef21937 5200 return;
5d4f98a2
YZ
5201 }
5202 }
cef21937
FDBM
5203 rb_link_node(new, parent, p);
5204 rb_insert_color(new, &root->inode_tree);
5d4f98a2
YZ
5205 spin_unlock(&root->inode_lock);
5206}
5207
5208static void inode_tree_del(struct inode *inode)
5209{
5210 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 5211 int empty = 0;
5d4f98a2 5212
03e860bd 5213 spin_lock(&root->inode_lock);
5d4f98a2 5214 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 5215 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 5216 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 5217 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 5218 }
03e860bd 5219 spin_unlock(&root->inode_lock);
76dda93c 5220
69e9c6c6 5221 if (empty && btrfs_root_refs(&root->root_item) == 0) {
76dda93c
YZ
5222 spin_lock(&root->inode_lock);
5223 empty = RB_EMPTY_ROOT(&root->inode_tree);
5224 spin_unlock(&root->inode_lock);
5225 if (empty)
5226 btrfs_add_dead_root(root);
5227 }
5228}
5229
5d4f98a2 5230
e02119d5
CM
5231static int btrfs_init_locked_inode(struct inode *inode, void *p)
5232{
5233 struct btrfs_iget_args *args = p;
90d3e592
CM
5234 inode->i_ino = args->location->objectid;
5235 memcpy(&BTRFS_I(inode)->location, args->location,
5236 sizeof(*args->location));
5c8fd99f
JB
5237 BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5238 BUG_ON(args->root && !BTRFS_I(inode)->root);
39279cc3
CM
5239 return 0;
5240}
5241
5242static int btrfs_find_actor(struct inode *inode, void *opaque)
5243{
5244 struct btrfs_iget_args *args = opaque;
90d3e592 5245 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
d397712b 5246 args->root == BTRFS_I(inode)->root;
39279cc3
CM
5247}
5248
5d4f98a2 5249static struct inode *btrfs_iget_locked(struct super_block *s,
90d3e592 5250 struct btrfs_key *location,
5d4f98a2 5251 struct btrfs_root *root)
39279cc3
CM
5252{
5253 struct inode *inode;
5254 struct btrfs_iget_args args;
90d3e592 5255 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
778ba82b 5256
90d3e592 5257 args.location = location;
39279cc3
CM
5258 args.root = root;
5259
778ba82b 5260 inode = iget5_locked(s, hashval, btrfs_find_actor,
39279cc3
CM
5261 btrfs_init_locked_inode,
5262 (void *)&args);
5263 return inode;
5264}
5265
4c66e0d4
DS
5266/*
5267 * Get an inode object given its location and corresponding root.
5268 * Path can be preallocated to prevent recursing back to iget through
5269 * allocator. NULL is also valid but may require an additional allocation
5270 * later.
1a54ef8c 5271 */
4222ea71 5272struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
4c66e0d4 5273 struct btrfs_root *root, struct btrfs_path *path)
1a54ef8c
BR
5274{
5275 struct inode *inode;
5276
90d3e592 5277 inode = btrfs_iget_locked(s, location, root);
1a54ef8c 5278 if (!inode)
5d4f98a2 5279 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
5280
5281 if (inode->i_state & I_NEW) {
67710892
FM
5282 int ret;
5283
4222ea71 5284 ret = btrfs_read_locked_inode(inode, path);
9bc2ceff 5285 if (!ret) {
1748f843
MF
5286 inode_tree_add(inode);
5287 unlock_new_inode(inode);
1748f843 5288 } else {
f5b3a417
AV
5289 iget_failed(inode);
5290 /*
5291 * ret > 0 can come from btrfs_search_slot called by
5292 * btrfs_read_locked_inode, this means the inode item
5293 * was not found.
5294 */
5295 if (ret > 0)
5296 ret = -ENOENT;
5297 inode = ERR_PTR(ret);
1748f843
MF
5298 }
5299 }
5300
1a54ef8c
BR
5301 return inode;
5302}
5303
4222ea71 5304struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4c66e0d4 5305 struct btrfs_root *root)
4222ea71 5306{
4c66e0d4 5307 return btrfs_iget_path(s, location, root, NULL);
4222ea71
FM
5308}
5309
4df27c4d
YZ
5310static struct inode *new_simple_dir(struct super_block *s,
5311 struct btrfs_key *key,
5312 struct btrfs_root *root)
5313{
5314 struct inode *inode = new_inode(s);
5315
5316 if (!inode)
5317 return ERR_PTR(-ENOMEM);
5318
5c8fd99f 5319 BTRFS_I(inode)->root = btrfs_grab_root(root);
4df27c4d 5320 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
72ac3c0d 5321 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4df27c4d
YZ
5322
5323 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
6bb6b514
OS
5324 /*
5325 * We only need lookup, the rest is read-only and there's no inode
5326 * associated with the dentry
5327 */
5328 inode->i_op = &simple_dir_inode_operations;
1fdf4194 5329 inode->i_opflags &= ~IOP_XATTR;
4df27c4d
YZ
5330 inode->i_fop = &simple_dir_operations;
5331 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
c2050a45 5332 inode->i_mtime = current_time(inode);
9cc97d64 5333 inode->i_atime = inode->i_mtime;
5334 inode->i_ctime = inode->i_mtime;
d3c6be6f 5335 BTRFS_I(inode)->i_otime = inode->i_mtime;
4df27c4d
YZ
5336
5337 return inode;
5338}
5339
6bf9e4bd
QW
5340static inline u8 btrfs_inode_type(struct inode *inode)
5341{
5342 /*
5343 * Compile-time asserts that generic FT_* types still match
5344 * BTRFS_FT_* types
5345 */
5346 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5347 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5348 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5349 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5350 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5351 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5352 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5353 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5354
5355 return fs_umode_to_ftype(inode->i_mode);
5356}
5357
3de4586c 5358struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 5359{
0b246afa 5360 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
d397712b 5361 struct inode *inode;
4df27c4d 5362 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
5363 struct btrfs_root *sub_root = root;
5364 struct btrfs_key location;
6bf9e4bd 5365 u8 di_type = 0;
b4aff1f8 5366 int ret = 0;
39279cc3
CM
5367
5368 if (dentry->d_name.len > BTRFS_NAME_LEN)
5369 return ERR_PTR(-ENAMETOOLONG);
5f39d397 5370
6bf9e4bd 5371 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
39279cc3
CM
5372 if (ret < 0)
5373 return ERR_PTR(ret);
5f39d397 5374
4df27c4d 5375 if (location.type == BTRFS_INODE_ITEM_KEY) {
4c66e0d4 5376 inode = btrfs_iget(dir->i_sb, &location, root);
6bf9e4bd
QW
5377 if (IS_ERR(inode))
5378 return inode;
5379
5380 /* Do extra check against inode mode with di_type */
5381 if (btrfs_inode_type(inode) != di_type) {
5382 btrfs_crit(fs_info,
5383"inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5384 inode->i_mode, btrfs_inode_type(inode),
5385 di_type);
5386 iput(inode);
5387 return ERR_PTR(-EUCLEAN);
5388 }
4df27c4d
YZ
5389 return inode;
5390 }
5391
2ff7e61e 5392 ret = fixup_tree_root_location(fs_info, dir, dentry,
4df27c4d
YZ
5393 &location, &sub_root);
5394 if (ret < 0) {
5395 if (ret != -ENOENT)
5396 inode = ERR_PTR(ret);
5397 else
5398 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5399 } else {
4c66e0d4 5400 inode = btrfs_iget(dir->i_sb, &location, sub_root);
39279cc3 5401 }
8727002f 5402 if (root != sub_root)
00246528 5403 btrfs_put_root(sub_root);
76dda93c 5404
34d19bad 5405 if (!IS_ERR(inode) && root != sub_root) {
0b246afa 5406 down_read(&fs_info->cleanup_work_sem);
bc98a42c 5407 if (!sb_rdonly(inode->i_sb))
66b4ffd1 5408 ret = btrfs_orphan_cleanup(sub_root);
0b246afa 5409 up_read(&fs_info->cleanup_work_sem);
01cd3367
JB
5410 if (ret) {
5411 iput(inode);
66b4ffd1 5412 inode = ERR_PTR(ret);
01cd3367 5413 }
c71bf099
YZ
5414 }
5415
3de4586c
CM
5416 return inode;
5417}
5418
fe15ce44 5419static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
5420{
5421 struct btrfs_root *root;
2b0143b5 5422 struct inode *inode = d_inode(dentry);
76dda93c 5423
848cce0d 5424 if (!inode && !IS_ROOT(dentry))
2b0143b5 5425 inode = d_inode(dentry->d_parent);
76dda93c 5426
848cce0d
LZ
5427 if (inode) {
5428 root = BTRFS_I(inode)->root;
efefb143
YZ
5429 if (btrfs_root_refs(&root->root_item) == 0)
5430 return 1;
848cce0d 5431
4a0cc7ca 5432 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
848cce0d 5433 return 1;
efefb143 5434 }
76dda93c
YZ
5435 return 0;
5436}
5437
3de4586c 5438static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
00cd8dd3 5439 unsigned int flags)
3de4586c 5440{
3837d208 5441 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5662344b 5442
3837d208
AV
5443 if (inode == ERR_PTR(-ENOENT))
5444 inode = NULL;
41d28bca 5445 return d_splice_alias(inode, dentry);
39279cc3
CM
5446}
5447
23b5ec74
JB
5448/*
5449 * All this infrastructure exists because dir_emit can fault, and we are holding
5450 * the tree lock when doing readdir. For now just allocate a buffer and copy
5451 * our information into that, and then dir_emit from the buffer. This is
5452 * similar to what NFS does, only we don't keep the buffer around in pagecache
5453 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5454 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5455 * tree lock.
5456 */
5457static int btrfs_opendir(struct inode *inode, struct file *file)
5458{
5459 struct btrfs_file_private *private;
5460
5461 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5462 if (!private)
5463 return -ENOMEM;
5464 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5465 if (!private->filldir_buf) {
5466 kfree(private);
5467 return -ENOMEM;
5468 }
5469 file->private_data = private;
5470 return 0;
5471}
5472
5473struct dir_entry {
5474 u64 ino;
5475 u64 offset;
5476 unsigned type;
5477 int name_len;
5478};
5479
5480static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5481{
5482 while (entries--) {
5483 struct dir_entry *entry = addr;
5484 char *name = (char *)(entry + 1);
5485
92d32170
DS
5486 ctx->pos = get_unaligned(&entry->offset);
5487 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5488 get_unaligned(&entry->ino),
5489 get_unaligned(&entry->type)))
23b5ec74 5490 return 1;
92d32170
DS
5491 addr += sizeof(struct dir_entry) +
5492 get_unaligned(&entry->name_len);
23b5ec74
JB
5493 ctx->pos++;
5494 }
5495 return 0;
5496}
5497
9cdda8d3 5498static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
39279cc3 5499{
9cdda8d3 5500 struct inode *inode = file_inode(file);
39279cc3 5501 struct btrfs_root *root = BTRFS_I(inode)->root;
23b5ec74 5502 struct btrfs_file_private *private = file->private_data;
39279cc3
CM
5503 struct btrfs_dir_item *di;
5504 struct btrfs_key key;
5f39d397 5505 struct btrfs_key found_key;
39279cc3 5506 struct btrfs_path *path;
23b5ec74 5507 void *addr;
16cdcec7
MX
5508 struct list_head ins_list;
5509 struct list_head del_list;
39279cc3 5510 int ret;
5f39d397 5511 struct extent_buffer *leaf;
39279cc3 5512 int slot;
5f39d397
CM
5513 char *name_ptr;
5514 int name_len;
23b5ec74
JB
5515 int entries = 0;
5516 int total_len = 0;
02dbfc99 5517 bool put = false;
c2951f32 5518 struct btrfs_key location;
5f39d397 5519
9cdda8d3
AV
5520 if (!dir_emit_dots(file, ctx))
5521 return 0;
5522
49593bfa 5523 path = btrfs_alloc_path();
16cdcec7
MX
5524 if (!path)
5525 return -ENOMEM;
ff5714cc 5526
23b5ec74 5527 addr = private->filldir_buf;
e4058b54 5528 path->reada = READA_FORWARD;
49593bfa 5529
c2951f32
JM
5530 INIT_LIST_HEAD(&ins_list);
5531 INIT_LIST_HEAD(&del_list);
5532 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
16cdcec7 5533
23b5ec74 5534again:
c2951f32 5535 key.type = BTRFS_DIR_INDEX_KEY;
9cdda8d3 5536 key.offset = ctx->pos;
4a0cc7ca 5537 key.objectid = btrfs_ino(BTRFS_I(inode));
5f39d397 5538
39279cc3
CM
5539 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5540 if (ret < 0)
5541 goto err;
49593bfa
DW
5542
5543 while (1) {
23b5ec74
JB
5544 struct dir_entry *entry;
5545
5f39d397 5546 leaf = path->nodes[0];
39279cc3 5547 slot = path->slots[0];
b9e03af0
LZ
5548 if (slot >= btrfs_header_nritems(leaf)) {
5549 ret = btrfs_next_leaf(root, path);
5550 if (ret < 0)
5551 goto err;
5552 else if (ret > 0)
5553 break;
5554 continue;
39279cc3 5555 }
3de4586c 5556
5f39d397
CM
5557 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5558
5559 if (found_key.objectid != key.objectid)
39279cc3 5560 break;
c2951f32 5561 if (found_key.type != BTRFS_DIR_INDEX_KEY)
39279cc3 5562 break;
9cdda8d3 5563 if (found_key.offset < ctx->pos)
b9e03af0 5564 goto next;
c2951f32 5565 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
16cdcec7 5566 goto next;
39279cc3 5567 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
c2951f32 5568 name_len = btrfs_dir_name_len(leaf, di);
23b5ec74
JB
5569 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5570 PAGE_SIZE) {
5571 btrfs_release_path(path);
5572 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5573 if (ret)
5574 goto nopos;
5575 addr = private->filldir_buf;
5576 entries = 0;
5577 total_len = 0;
5578 goto again;
c2951f32 5579 }
23b5ec74
JB
5580
5581 entry = addr;
92d32170 5582 put_unaligned(name_len, &entry->name_len);
23b5ec74 5583 name_ptr = (char *)(entry + 1);
c2951f32
JM
5584 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5585 name_len);
7d157c3d 5586 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
92d32170 5587 &entry->type);
c2951f32 5588 btrfs_dir_item_key_to_cpu(leaf, di, &location);
92d32170
DS
5589 put_unaligned(location.objectid, &entry->ino);
5590 put_unaligned(found_key.offset, &entry->offset);
23b5ec74
JB
5591 entries++;
5592 addr += sizeof(struct dir_entry) + name_len;
5593 total_len += sizeof(struct dir_entry) + name_len;
b9e03af0
LZ
5594next:
5595 path->slots[0]++;
39279cc3 5596 }
23b5ec74
JB
5597 btrfs_release_path(path);
5598
5599 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5600 if (ret)
5601 goto nopos;
49593bfa 5602
d2fbb2b5 5603 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
c2951f32 5604 if (ret)
bc4ef759
DS
5605 goto nopos;
5606
db62efbb
ZB
5607 /*
5608 * Stop new entries from being returned after we return the last
5609 * entry.
5610 *
5611 * New directory entries are assigned a strictly increasing
5612 * offset. This means that new entries created during readdir
5613 * are *guaranteed* to be seen in the future by that readdir.
5614 * This has broken buggy programs which operate on names as
5615 * they're returned by readdir. Until we re-use freed offsets
5616 * we have this hack to stop new entries from being returned
5617 * under the assumption that they'll never reach this huge
5618 * offset.
5619 *
5620 * This is being careful not to overflow 32bit loff_t unless the
5621 * last entry requires it because doing so has broken 32bit apps
5622 * in the past.
5623 */
c2951f32
JM
5624 if (ctx->pos >= INT_MAX)
5625 ctx->pos = LLONG_MAX;
5626 else
5627 ctx->pos = INT_MAX;
39279cc3
CM
5628nopos:
5629 ret = 0;
5630err:
02dbfc99
OS
5631 if (put)
5632 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
39279cc3 5633 btrfs_free_path(path);
39279cc3
CM
5634 return ret;
5635}
5636
39279cc3 5637/*
54aa1f4d 5638 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
5639 * inode changes. But, it is most likely to find the inode in cache.
5640 * FIXME, needs more benchmarking...there are no reasons other than performance
5641 * to keep or drop this code.
5642 */
48a3b636 5643static int btrfs_dirty_inode(struct inode *inode)
39279cc3 5644{
2ff7e61e 5645 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
5646 struct btrfs_root *root = BTRFS_I(inode)->root;
5647 struct btrfs_trans_handle *trans;
8929ecfa
YZ
5648 int ret;
5649
72ac3c0d 5650 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
22c44fe6 5651 return 0;
39279cc3 5652
7a7eaa40 5653 trans = btrfs_join_transaction(root);
22c44fe6
JB
5654 if (IS_ERR(trans))
5655 return PTR_ERR(trans);
8929ecfa
YZ
5656
5657 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
5658 if (ret && ret == -ENOSPC) {
5659 /* whoops, lets try again with the full transaction */
3a45bb20 5660 btrfs_end_transaction(trans);
94b60442 5661 trans = btrfs_start_transaction(root, 1);
22c44fe6
JB
5662 if (IS_ERR(trans))
5663 return PTR_ERR(trans);
8929ecfa 5664
94b60442 5665 ret = btrfs_update_inode(trans, root, inode);
94b60442 5666 }
3a45bb20 5667 btrfs_end_transaction(trans);
16cdcec7 5668 if (BTRFS_I(inode)->delayed_node)
2ff7e61e 5669 btrfs_balance_delayed_items(fs_info);
22c44fe6
JB
5670
5671 return ret;
5672}
5673
5674/*
5675 * This is a copy of file_update_time. We need this so we can return error on
5676 * ENOSPC for updating the inode in the case of file write and mmap writes.
5677 */
95582b00 5678static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
e41f941a 5679 int flags)
22c44fe6 5680{
2bc55652 5681 struct btrfs_root *root = BTRFS_I(inode)->root;
3a8c7231 5682 bool dirty = flags & ~S_VERSION;
2bc55652
AB
5683
5684 if (btrfs_root_readonly(root))
5685 return -EROFS;
5686
e41f941a 5687 if (flags & S_VERSION)
3a8c7231 5688 dirty |= inode_maybe_inc_iversion(inode, dirty);
e41f941a
JB
5689 if (flags & S_CTIME)
5690 inode->i_ctime = *now;
5691 if (flags & S_MTIME)
5692 inode->i_mtime = *now;
5693 if (flags & S_ATIME)
5694 inode->i_atime = *now;
3a8c7231 5695 return dirty ? btrfs_dirty_inode(inode) : 0;
39279cc3
CM
5696}
5697
d352ac68
CM
5698/*
5699 * find the highest existing sequence number in a directory
5700 * and then set the in-memory index_cnt variable to reflect
5701 * free sequence numbers
5702 */
4c570655 5703static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
aec7477b 5704{
4c570655 5705 struct btrfs_root *root = inode->root;
aec7477b
JB
5706 struct btrfs_key key, found_key;
5707 struct btrfs_path *path;
5708 struct extent_buffer *leaf;
5709 int ret;
5710
4c570655 5711 key.objectid = btrfs_ino(inode);
962a298f 5712 key.type = BTRFS_DIR_INDEX_KEY;
aec7477b
JB
5713 key.offset = (u64)-1;
5714
5715 path = btrfs_alloc_path();
5716 if (!path)
5717 return -ENOMEM;
5718
5719 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5720 if (ret < 0)
5721 goto out;
5722 /* FIXME: we should be able to handle this */
5723 if (ret == 0)
5724 goto out;
5725 ret = 0;
5726
5727 /*
5728 * MAGIC NUMBER EXPLANATION:
5729 * since we search a directory based on f_pos we have to start at 2
5730 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5731 * else has to start at 2
5732 */
5733 if (path->slots[0] == 0) {
4c570655 5734 inode->index_cnt = 2;
aec7477b
JB
5735 goto out;
5736 }
5737
5738 path->slots[0]--;
5739
5740 leaf = path->nodes[0];
5741 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5742
4c570655 5743 if (found_key.objectid != btrfs_ino(inode) ||
962a298f 5744 found_key.type != BTRFS_DIR_INDEX_KEY) {
4c570655 5745 inode->index_cnt = 2;
aec7477b
JB
5746 goto out;
5747 }
5748
4c570655 5749 inode->index_cnt = found_key.offset + 1;
aec7477b
JB
5750out:
5751 btrfs_free_path(path);
5752 return ret;
5753}
5754
d352ac68
CM
5755/*
5756 * helper to find a free sequence number in a given directory. This current
5757 * code is very simple, later versions will do smarter things in the btree
5758 */
877574e2 5759int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
aec7477b
JB
5760{
5761 int ret = 0;
5762
877574e2
NB
5763 if (dir->index_cnt == (u64)-1) {
5764 ret = btrfs_inode_delayed_dir_index_count(dir);
16cdcec7
MX
5765 if (ret) {
5766 ret = btrfs_set_inode_index_count(dir);
5767 if (ret)
5768 return ret;
5769 }
aec7477b
JB
5770 }
5771
877574e2
NB
5772 *index = dir->index_cnt;
5773 dir->index_cnt++;
aec7477b
JB
5774
5775 return ret;
5776}
5777
b0d5d10f
CM
5778static int btrfs_insert_inode_locked(struct inode *inode)
5779{
5780 struct btrfs_iget_args args;
5781 args.location = &BTRFS_I(inode)->location;
5782 args.root = BTRFS_I(inode)->root;
5783
5784 return insert_inode_locked4(inode,
5785 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5786 btrfs_find_actor, &args);
5787}
5788
19aee8de
AJ
5789/*
5790 * Inherit flags from the parent inode.
5791 *
5792 * Currently only the compression flags and the cow flags are inherited.
5793 */
5794static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5795{
5796 unsigned int flags;
5797
5798 if (!dir)
5799 return;
5800
5801 flags = BTRFS_I(dir)->flags;
5802
5803 if (flags & BTRFS_INODE_NOCOMPRESS) {
5804 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5805 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5806 } else if (flags & BTRFS_INODE_COMPRESS) {
5807 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5808 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5809 }
5810
5811 if (flags & BTRFS_INODE_NODATACOW) {
5812 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5813 if (S_ISREG(inode->i_mode))
5814 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5815 }
5816
7b6a221e 5817 btrfs_sync_inode_flags_to_i_flags(inode);
19aee8de
AJ
5818}
5819
39279cc3
CM
5820static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5821 struct btrfs_root *root,
aec7477b 5822 struct inode *dir,
9c58309d 5823 const char *name, int name_len,
175a4eb7
AV
5824 u64 ref_objectid, u64 objectid,
5825 umode_t mode, u64 *index)
39279cc3 5826{
0b246afa 5827 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 5828 struct inode *inode;
5f39d397 5829 struct btrfs_inode_item *inode_item;
39279cc3 5830 struct btrfs_key *location;
5f39d397 5831 struct btrfs_path *path;
9c58309d
CM
5832 struct btrfs_inode_ref *ref;
5833 struct btrfs_key key[2];
5834 u32 sizes[2];
ef3b9af5 5835 int nitems = name ? 2 : 1;
9c58309d 5836 unsigned long ptr;
11a19a90 5837 unsigned int nofs_flag;
39279cc3 5838 int ret;
39279cc3 5839
5f39d397 5840 path = btrfs_alloc_path();
d8926bb3
MF
5841 if (!path)
5842 return ERR_PTR(-ENOMEM);
5f39d397 5843
11a19a90 5844 nofs_flag = memalloc_nofs_save();
0b246afa 5845 inode = new_inode(fs_info->sb);
11a19a90 5846 memalloc_nofs_restore(nofs_flag);
8fb27640
YS
5847 if (!inode) {
5848 btrfs_free_path(path);
39279cc3 5849 return ERR_PTR(-ENOMEM);
8fb27640 5850 }
39279cc3 5851
5762b5c9
FM
5852 /*
5853 * O_TMPFILE, set link count to 0, so that after this point,
5854 * we fill in an inode item with the correct link count.
5855 */
5856 if (!name)
5857 set_nlink(inode, 0);
5858
581bb050
LZ
5859 /*
5860 * we have to initialize this early, so we can reclaim the inode
5861 * number if we fail afterwards in this function.
5862 */
5863 inode->i_ino = objectid;
5864
ef3b9af5 5865 if (dir && name) {
1abe9b8a 5866 trace_btrfs_inode_request(dir);
5867
877574e2 5868 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
09771430 5869 if (ret) {
8fb27640 5870 btrfs_free_path(path);
09771430 5871 iput(inode);
aec7477b 5872 return ERR_PTR(ret);
09771430 5873 }
ef3b9af5
FM
5874 } else if (dir) {
5875 *index = 0;
aec7477b
JB
5876 }
5877 /*
5878 * index_cnt is ignored for everything but a dir,
df6703e1 5879 * btrfs_set_inode_index_count has an explanation for the magic
aec7477b
JB
5880 * number
5881 */
5882 BTRFS_I(inode)->index_cnt = 2;
67de1176 5883 BTRFS_I(inode)->dir_index = *index;
5c8fd99f 5884 BTRFS_I(inode)->root = btrfs_grab_root(root);
e02119d5 5885 BTRFS_I(inode)->generation = trans->transid;
76195853 5886 inode->i_generation = BTRFS_I(inode)->generation;
b888db2b 5887
5dc562c5
JB
5888 /*
5889 * We could have gotten an inode number from somebody who was fsynced
5890 * and then removed in this same transaction, so let's just set full
5891 * sync since it will be a full sync anyway and this will blow away the
5892 * old info in the log.
5893 */
5894 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5895
9c58309d 5896 key[0].objectid = objectid;
962a298f 5897 key[0].type = BTRFS_INODE_ITEM_KEY;
9c58309d
CM
5898 key[0].offset = 0;
5899
9c58309d 5900 sizes[0] = sizeof(struct btrfs_inode_item);
ef3b9af5
FM
5901
5902 if (name) {
5903 /*
5904 * Start new inodes with an inode_ref. This is slightly more
5905 * efficient for small numbers of hard links since they will
5906 * be packed into one item. Extended refs will kick in if we
5907 * add more hard links than can fit in the ref item.
5908 */
5909 key[1].objectid = objectid;
962a298f 5910 key[1].type = BTRFS_INODE_REF_KEY;
ef3b9af5
FM
5911 key[1].offset = ref_objectid;
5912
5913 sizes[1] = name_len + sizeof(*ref);
5914 }
9c58309d 5915
b0d5d10f
CM
5916 location = &BTRFS_I(inode)->location;
5917 location->objectid = objectid;
5918 location->offset = 0;
962a298f 5919 location->type = BTRFS_INODE_ITEM_KEY;
b0d5d10f
CM
5920
5921 ret = btrfs_insert_inode_locked(inode);
32955c54
AV
5922 if (ret < 0) {
5923 iput(inode);
b0d5d10f 5924 goto fail;
32955c54 5925 }
b0d5d10f 5926
b9473439 5927 path->leave_spinning = 1;
ef3b9af5 5928 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
9c58309d 5929 if (ret != 0)
b0d5d10f 5930 goto fail_unlock;
5f39d397 5931
ecc11fab 5932 inode_init_owner(inode, dir, mode);
a76a3cd4 5933 inode_set_bytes(inode, 0);
9cc97d64 5934
c2050a45 5935 inode->i_mtime = current_time(inode);
9cc97d64 5936 inode->i_atime = inode->i_mtime;
5937 inode->i_ctime = inode->i_mtime;
d3c6be6f 5938 BTRFS_I(inode)->i_otime = inode->i_mtime;
9cc97d64 5939
5f39d397
CM
5940 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5941 struct btrfs_inode_item);
b159fa28 5942 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
293f7e07 5943 sizeof(*inode_item));
e02119d5 5944 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d 5945
ef3b9af5
FM
5946 if (name) {
5947 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5948 struct btrfs_inode_ref);
5949 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5950 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5951 ptr = (unsigned long)(ref + 1);
5952 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5953 }
9c58309d 5954
5f39d397
CM
5955 btrfs_mark_buffer_dirty(path->nodes[0]);
5956 btrfs_free_path(path);
5957
6cbff00f
CH
5958 btrfs_inherit_iflags(inode, dir);
5959
569254b0 5960 if (S_ISREG(mode)) {
0b246afa 5961 if (btrfs_test_opt(fs_info, NODATASUM))
94272164 5962 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
0b246afa 5963 if (btrfs_test_opt(fs_info, NODATACOW))
f2bdf9a8
JB
5964 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5965 BTRFS_INODE_NODATASUM;
94272164
CM
5966 }
5967
5d4f98a2 5968 inode_tree_add(inode);
1abe9b8a 5969
5970 trace_btrfs_inode_new(inode);
1973f0fa 5971 btrfs_set_inode_last_trans(trans, inode);
1abe9b8a 5972
8ea05e3a
AB
5973 btrfs_update_root_times(trans, root);
5974
63541927
FDBM
5975 ret = btrfs_inode_inherit_props(trans, inode, dir);
5976 if (ret)
0b246afa 5977 btrfs_err(fs_info,
63541927 5978 "error inheriting props for ino %llu (root %llu): %d",
f85b7379 5979 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
63541927 5980
39279cc3 5981 return inode;
b0d5d10f
CM
5982
5983fail_unlock:
32955c54 5984 discard_new_inode(inode);
5f39d397 5985fail:
ef3b9af5 5986 if (dir && name)
aec7477b 5987 BTRFS_I(dir)->index_cnt--;
5f39d397
CM
5988 btrfs_free_path(path);
5989 return ERR_PTR(ret);
39279cc3
CM
5990}
5991
d352ac68
CM
5992/*
5993 * utility function to add 'inode' into 'parent_inode' with
5994 * a give name and a given sequence number.
5995 * if 'add_backref' is true, also insert a backref from the
5996 * inode to the parent directory.
5997 */
e02119d5 5998int btrfs_add_link(struct btrfs_trans_handle *trans,
db0a669f 5999 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
e02119d5 6000 const char *name, int name_len, int add_backref, u64 index)
39279cc3 6001{
4df27c4d 6002 int ret = 0;
39279cc3 6003 struct btrfs_key key;
db0a669f
NB
6004 struct btrfs_root *root = parent_inode->root;
6005 u64 ino = btrfs_ino(inode);
6006 u64 parent_ino = btrfs_ino(parent_inode);
5f39d397 6007
33345d01 6008 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
db0a669f 6009 memcpy(&key, &inode->root->root_key, sizeof(key));
4df27c4d 6010 } else {
33345d01 6011 key.objectid = ino;
962a298f 6012 key.type = BTRFS_INODE_ITEM_KEY;
4df27c4d
YZ
6013 key.offset = 0;
6014 }
6015
33345d01 6016 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6025c19f 6017 ret = btrfs_add_root_ref(trans, key.objectid,
0b246afa
JM
6018 root->root_key.objectid, parent_ino,
6019 index, name, name_len);
4df27c4d 6020 } else if (add_backref) {
33345d01
LZ
6021 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6022 parent_ino, index);
4df27c4d 6023 }
39279cc3 6024
79787eaa
JM
6025 /* Nothing to clean up yet */
6026 if (ret)
6027 return ret;
4df27c4d 6028
684572df 6029 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
db0a669f 6030 btrfs_inode_type(&inode->vfs_inode), index);
9c52057c 6031 if (ret == -EEXIST || ret == -EOVERFLOW)
79787eaa
JM
6032 goto fail_dir_item;
6033 else if (ret) {
66642832 6034 btrfs_abort_transaction(trans, ret);
79787eaa 6035 return ret;
39279cc3 6036 }
79787eaa 6037
db0a669f 6038 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
79787eaa 6039 name_len * 2);
db0a669f 6040 inode_inc_iversion(&parent_inode->vfs_inode);
5338e43a
FM
6041 /*
6042 * If we are replaying a log tree, we do not want to update the mtime
6043 * and ctime of the parent directory with the current time, since the
6044 * log replay procedure is responsible for setting them to their correct
6045 * values (the ones it had when the fsync was done).
6046 */
6047 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6048 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6049
6050 parent_inode->vfs_inode.i_mtime = now;
6051 parent_inode->vfs_inode.i_ctime = now;
6052 }
db0a669f 6053 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
79787eaa 6054 if (ret)
66642832 6055 btrfs_abort_transaction(trans, ret);
39279cc3 6056 return ret;
fe66a05a
CM
6057
6058fail_dir_item:
6059 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6060 u64 local_index;
6061 int err;
3ee1c553 6062 err = btrfs_del_root_ref(trans, key.objectid,
0b246afa
JM
6063 root->root_key.objectid, parent_ino,
6064 &local_index, name, name_len);
1690dd41
JT
6065 if (err)
6066 btrfs_abort_transaction(trans, err);
fe66a05a
CM
6067 } else if (add_backref) {
6068 u64 local_index;
6069 int err;
6070
6071 err = btrfs_del_inode_ref(trans, root, name, name_len,
6072 ino, parent_ino, &local_index);
1690dd41
JT
6073 if (err)
6074 btrfs_abort_transaction(trans, err);
fe66a05a 6075 }
1690dd41
JT
6076
6077 /* Return the original error code */
fe66a05a 6078 return ret;
39279cc3
CM
6079}
6080
6081static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
cef415af
NB
6082 struct btrfs_inode *dir, struct dentry *dentry,
6083 struct btrfs_inode *inode, int backref, u64 index)
39279cc3 6084{
a1b075d2
JB
6085 int err = btrfs_add_link(trans, dir, inode,
6086 dentry->d_name.name, dentry->d_name.len,
6087 backref, index);
39279cc3
CM
6088 if (err > 0)
6089 err = -EEXIST;
6090 return err;
6091}
6092
618e21d5 6093static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1a67aafb 6094 umode_t mode, dev_t rdev)
618e21d5 6095{
2ff7e61e 6096 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
618e21d5
JB
6097 struct btrfs_trans_handle *trans;
6098 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6099 struct inode *inode = NULL;
618e21d5 6100 int err;
618e21d5 6101 u64 objectid;
00e4e6b3 6102 u64 index = 0;
618e21d5 6103
9ed74f2d
JB
6104 /*
6105 * 2 for inode item and ref
6106 * 2 for dir items
6107 * 1 for xattr if selinux is on
6108 */
a22285a6
YZ
6109 trans = btrfs_start_transaction(root, 5);
6110 if (IS_ERR(trans))
6111 return PTR_ERR(trans);
1832a6d5 6112
581bb050
LZ
6113 err = btrfs_find_free_ino(root, &objectid);
6114 if (err)
6115 goto out_unlock;
6116
aec7477b 6117 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6118 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6119 mode, &index);
7cf96da3
TI
6120 if (IS_ERR(inode)) {
6121 err = PTR_ERR(inode);
32955c54 6122 inode = NULL;
618e21d5 6123 goto out_unlock;
7cf96da3 6124 }
618e21d5 6125
ad19db71
CS
6126 /*
6127 * If the active LSM wants to access the inode during
6128 * d_instantiate it needs these. Smack checks to see
6129 * if the filesystem supports xattrs by looking at the
6130 * ops vector.
6131 */
ad19db71 6132 inode->i_op = &btrfs_special_inode_operations;
b0d5d10f
CM
6133 init_special_inode(inode, inode->i_mode, rdev);
6134
6135 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
618e21d5 6136 if (err)
32955c54 6137 goto out_unlock;
b0d5d10f 6138
cef415af
NB
6139 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6140 0, index);
32955c54
AV
6141 if (err)
6142 goto out_unlock;
6143
6144 btrfs_update_inode(trans, root, inode);
6145 d_instantiate_new(dentry, inode);
b0d5d10f 6146
618e21d5 6147out_unlock:
3a45bb20 6148 btrfs_end_transaction(trans);
2ff7e61e 6149 btrfs_btree_balance_dirty(fs_info);
32955c54 6150 if (err && inode) {
618e21d5 6151 inode_dec_link_count(inode);
32955c54 6152 discard_new_inode(inode);
618e21d5 6153 }
618e21d5
JB
6154 return err;
6155}
6156
39279cc3 6157static int btrfs_create(struct inode *dir, struct dentry *dentry,
ebfc3b49 6158 umode_t mode, bool excl)
39279cc3 6159{
2ff7e61e 6160 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
6161 struct btrfs_trans_handle *trans;
6162 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6163 struct inode *inode = NULL;
a22285a6 6164 int err;
39279cc3 6165 u64 objectid;
00e4e6b3 6166 u64 index = 0;
39279cc3 6167
9ed74f2d
JB
6168 /*
6169 * 2 for inode item and ref
6170 * 2 for dir items
6171 * 1 for xattr if selinux is on
6172 */
a22285a6
YZ
6173 trans = btrfs_start_transaction(root, 5);
6174 if (IS_ERR(trans))
6175 return PTR_ERR(trans);
9ed74f2d 6176
581bb050
LZ
6177 err = btrfs_find_free_ino(root, &objectid);
6178 if (err)
6179 goto out_unlock;
6180
aec7477b 6181 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6182 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6183 mode, &index);
7cf96da3
TI
6184 if (IS_ERR(inode)) {
6185 err = PTR_ERR(inode);
32955c54 6186 inode = NULL;
39279cc3 6187 goto out_unlock;
7cf96da3 6188 }
ad19db71
CS
6189 /*
6190 * If the active LSM wants to access the inode during
6191 * d_instantiate it needs these. Smack checks to see
6192 * if the filesystem supports xattrs by looking at the
6193 * ops vector.
6194 */
6195 inode->i_fop = &btrfs_file_operations;
6196 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 6197 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
6198
6199 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6200 if (err)
32955c54 6201 goto out_unlock;
b0d5d10f
CM
6202
6203 err = btrfs_update_inode(trans, root, inode);
6204 if (err)
32955c54 6205 goto out_unlock;
ad19db71 6206
cef415af
NB
6207 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6208 0, index);
39279cc3 6209 if (err)
32955c54 6210 goto out_unlock;
43baa579 6211
43baa579 6212 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
1e2e547a 6213 d_instantiate_new(dentry, inode);
43baa579 6214
39279cc3 6215out_unlock:
3a45bb20 6216 btrfs_end_transaction(trans);
32955c54 6217 if (err && inode) {
39279cc3 6218 inode_dec_link_count(inode);
32955c54 6219 discard_new_inode(inode);
39279cc3 6220 }
2ff7e61e 6221 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6222 return err;
6223}
6224
6225static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6226 struct dentry *dentry)
6227{
271dba45 6228 struct btrfs_trans_handle *trans = NULL;
39279cc3 6229 struct btrfs_root *root = BTRFS_I(dir)->root;
2b0143b5 6230 struct inode *inode = d_inode(old_dentry);
2ff7e61e 6231 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
00e4e6b3 6232 u64 index;
39279cc3
CM
6233 int err;
6234 int drop_inode = 0;
6235
4a8be425 6236 /* do not allow sys_link's with other subvols of the same device */
4fd786e6 6237 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
3ab3564f 6238 return -EXDEV;
4a8be425 6239
f186373f 6240 if (inode->i_nlink >= BTRFS_LINK_MAX)
c055e99e 6241 return -EMLINK;
4a8be425 6242
877574e2 6243 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
aec7477b
JB
6244 if (err)
6245 goto fail;
6246
a22285a6 6247 /*
7e6b6465 6248 * 2 items for inode and inode ref
a22285a6 6249 * 2 items for dir items
7e6b6465 6250 * 1 item for parent inode
399b0bbf 6251 * 1 item for orphan item deletion if O_TMPFILE
a22285a6 6252 */
399b0bbf 6253 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
a22285a6
YZ
6254 if (IS_ERR(trans)) {
6255 err = PTR_ERR(trans);
271dba45 6256 trans = NULL;
a22285a6
YZ
6257 goto fail;
6258 }
5f39d397 6259
67de1176
MX
6260 /* There are several dir indexes for this inode, clear the cache. */
6261 BTRFS_I(inode)->dir_index = 0ULL;
8b558c5f 6262 inc_nlink(inode);
0c4d2d95 6263 inode_inc_iversion(inode);
c2050a45 6264 inode->i_ctime = current_time(inode);
7de9c6ee 6265 ihold(inode);
e9976151 6266 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
aec7477b 6267
cef415af
NB
6268 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6269 1, index);
5f39d397 6270
a5719521 6271 if (err) {
54aa1f4d 6272 drop_inode = 1;
a5719521 6273 } else {
10d9f309 6274 struct dentry *parent = dentry->d_parent;
d4682ba0
FM
6275 int ret;
6276
a5719521 6277 err = btrfs_update_inode(trans, root, inode);
79787eaa
JM
6278 if (err)
6279 goto fail;
ef3b9af5
FM
6280 if (inode->i_nlink == 1) {
6281 /*
6282 * If new hard link count is 1, it's a file created
6283 * with open(2) O_TMPFILE flag.
6284 */
3d6ae7bb 6285 err = btrfs_orphan_del(trans, BTRFS_I(inode));
ef3b9af5
FM
6286 if (err)
6287 goto fail;
6288 }
08c422c2 6289 d_instantiate(dentry, inode);
d4682ba0
FM
6290 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6291 true, NULL);
6292 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6293 err = btrfs_commit_transaction(trans);
6294 trans = NULL;
6295 }
a5719521 6296 }
39279cc3 6297
1832a6d5 6298fail:
271dba45 6299 if (trans)
3a45bb20 6300 btrfs_end_transaction(trans);
39279cc3
CM
6301 if (drop_inode) {
6302 inode_dec_link_count(inode);
6303 iput(inode);
6304 }
2ff7e61e 6305 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6306 return err;
6307}
6308
18bb1db3 6309static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
39279cc3 6310{
2ff7e61e 6311 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
b9d86667 6312 struct inode *inode = NULL;
39279cc3
CM
6313 struct btrfs_trans_handle *trans;
6314 struct btrfs_root *root = BTRFS_I(dir)->root;
6315 int err = 0;
b9d86667 6316 u64 objectid = 0;
00e4e6b3 6317 u64 index = 0;
39279cc3 6318
9ed74f2d
JB
6319 /*
6320 * 2 items for inode and ref
6321 * 2 items for dir items
6322 * 1 for xattr if selinux is on
6323 */
a22285a6
YZ
6324 trans = btrfs_start_transaction(root, 5);
6325 if (IS_ERR(trans))
6326 return PTR_ERR(trans);
39279cc3 6327
581bb050
LZ
6328 err = btrfs_find_free_ino(root, &objectid);
6329 if (err)
6330 goto out_fail;
6331
aec7477b 6332 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6333 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6334 S_IFDIR | mode, &index);
39279cc3
CM
6335 if (IS_ERR(inode)) {
6336 err = PTR_ERR(inode);
32955c54 6337 inode = NULL;
39279cc3
CM
6338 goto out_fail;
6339 }
5f39d397 6340
b0d5d10f
CM
6341 /* these must be set before we unlock the inode */
6342 inode->i_op = &btrfs_dir_inode_operations;
6343 inode->i_fop = &btrfs_dir_file_operations;
33268eaf 6344
2a7dba39 6345 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf 6346 if (err)
32955c54 6347 goto out_fail;
39279cc3 6348
6ef06d27 6349 btrfs_i_size_write(BTRFS_I(inode), 0);
39279cc3
CM
6350 err = btrfs_update_inode(trans, root, inode);
6351 if (err)
32955c54 6352 goto out_fail;
5f39d397 6353
db0a669f
NB
6354 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6355 dentry->d_name.name,
6356 dentry->d_name.len, 0, index);
39279cc3 6357 if (err)
32955c54 6358 goto out_fail;
5f39d397 6359
1e2e547a 6360 d_instantiate_new(dentry, inode);
39279cc3
CM
6361
6362out_fail:
3a45bb20 6363 btrfs_end_transaction(trans);
32955c54 6364 if (err && inode) {
c7cfb8a5 6365 inode_dec_link_count(inode);
32955c54 6366 discard_new_inode(inode);
c7cfb8a5 6367 }
2ff7e61e 6368 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6369 return err;
6370}
6371
c8b97818 6372static noinline int uncompress_inline(struct btrfs_path *path,
e40da0e5 6373 struct page *page,
c8b97818
CM
6374 size_t pg_offset, u64 extent_offset,
6375 struct btrfs_file_extent_item *item)
6376{
6377 int ret;
6378 struct extent_buffer *leaf = path->nodes[0];
6379 char *tmp;
6380 size_t max_size;
6381 unsigned long inline_size;
6382 unsigned long ptr;
261507a0 6383 int compress_type;
c8b97818
CM
6384
6385 WARN_ON(pg_offset != 0);
261507a0 6386 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
6387 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6388 inline_size = btrfs_file_extent_inline_item_len(leaf,
dd3cc16b 6389 btrfs_item_nr(path->slots[0]));
c8b97818 6390 tmp = kmalloc(inline_size, GFP_NOFS);
8d413713
TI
6391 if (!tmp)
6392 return -ENOMEM;
c8b97818
CM
6393 ptr = btrfs_file_extent_inline_start(item);
6394
6395 read_extent_buffer(leaf, tmp, ptr, inline_size);
6396
09cbfeaf 6397 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
261507a0
LZ
6398 ret = btrfs_decompress(compress_type, tmp, page,
6399 extent_offset, inline_size, max_size);
e1699d2d
ZB
6400
6401 /*
6402 * decompression code contains a memset to fill in any space between the end
6403 * of the uncompressed data and the end of max_size in case the decompressed
6404 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6405 * the end of an inline extent and the beginning of the next block, so we
6406 * cover that region here.
6407 */
6408
6409 if (max_size + pg_offset < PAGE_SIZE) {
6410 char *map = kmap(page);
6411 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6412 kunmap(page);
6413 }
c8b97818 6414 kfree(tmp);
166ae5a4 6415 return ret;
c8b97818
CM
6416}
6417
39b07b5d
OS
6418/**
6419 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6420 * @inode: file to search in
6421 * @page: page to read extent data into if the extent is inline
6422 * @pg_offset: offset into @page to copy to
6423 * @start: file offset
6424 * @len: length of range starting at @start
6425 *
6426 * This returns the first &struct extent_map which overlaps with the given
6427 * range, reading it from the B-tree and caching it if necessary. Note that
6428 * there may be more extents which overlap the given range after the returned
6429 * extent_map.
d352ac68 6430 *
39b07b5d
OS
6431 * If @page is not NULL and the extent is inline, this also reads the extent
6432 * data directly into the page and marks the extent up to date in the io_tree.
6433 *
6434 * Return: ERR_PTR on error, non-NULL extent_map on success.
d352ac68 6435 */
fc4f21b1 6436struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
39b07b5d
OS
6437 struct page *page, size_t pg_offset,
6438 u64 start, u64 len)
a52d9a80 6439{
3ffbd68c 6440 struct btrfs_fs_info *fs_info = inode->root->fs_info;
a52d9a80
CM
6441 int ret;
6442 int err = 0;
a52d9a80
CM
6443 u64 extent_start = 0;
6444 u64 extent_end = 0;
fc4f21b1 6445 u64 objectid = btrfs_ino(inode);
7e74e235 6446 int extent_type = -1;
f421950f 6447 struct btrfs_path *path = NULL;
fc4f21b1 6448 struct btrfs_root *root = inode->root;
a52d9a80 6449 struct btrfs_file_extent_item *item;
5f39d397
CM
6450 struct extent_buffer *leaf;
6451 struct btrfs_key found_key;
a52d9a80 6452 struct extent_map *em = NULL;
fc4f21b1
NB
6453 struct extent_map_tree *em_tree = &inode->extent_tree;
6454 struct extent_io_tree *io_tree = &inode->io_tree;
a52d9a80 6455
890871be 6456 read_lock(&em_tree->lock);
d1310b2e 6457 em = lookup_extent_mapping(em_tree, start, len);
890871be 6458 read_unlock(&em_tree->lock);
d1310b2e 6459
a52d9a80 6460 if (em) {
e1c4b745
CM
6461 if (em->start > start || em->start + em->len <= start)
6462 free_extent_map(em);
6463 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
6464 free_extent_map(em);
6465 else
6466 goto out;
a52d9a80 6467 }
172ddd60 6468 em = alloc_extent_map();
a52d9a80 6469 if (!em) {
d1310b2e
CM
6470 err = -ENOMEM;
6471 goto out;
a52d9a80 6472 }
d1310b2e 6473 em->start = EXTENT_MAP_HOLE;
445a6944 6474 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 6475 em->len = (u64)-1;
c8b97818 6476 em->block_len = (u64)-1;
f421950f 6477
bee6ec82 6478 path = btrfs_alloc_path();
f421950f 6479 if (!path) {
bee6ec82
LB
6480 err = -ENOMEM;
6481 goto out;
f421950f
CM
6482 }
6483
bee6ec82
LB
6484 /* Chances are we'll be called again, so go ahead and do readahead */
6485 path->reada = READA_FORWARD;
6486
e49aabd9
LB
6487 /*
6488 * Unless we're going to uncompress the inline extent, no sleep would
6489 * happen.
6490 */
6491 path->leave_spinning = 1;
6492
5c9a702e 6493 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
a52d9a80
CM
6494 if (ret < 0) {
6495 err = ret;
6496 goto out;
b8eeab7f 6497 } else if (ret > 0) {
a52d9a80
CM
6498 if (path->slots[0] == 0)
6499 goto not_found;
6500 path->slots[0]--;
6501 }
6502
5f39d397
CM
6503 leaf = path->nodes[0];
6504 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 6505 struct btrfs_file_extent_item);
5f39d397 6506 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5f39d397 6507 if (found_key.objectid != objectid ||
694c12ed 6508 found_key.type != BTRFS_EXTENT_DATA_KEY) {
25a50341
JB
6509 /*
6510 * If we backup past the first extent we want to move forward
6511 * and see if there is an extent in front of us, otherwise we'll
6512 * say there is a hole for our whole search range which can
6513 * cause problems.
6514 */
6515 extent_end = start;
6516 goto next;
a52d9a80
CM
6517 }
6518
694c12ed 6519 extent_type = btrfs_file_extent_type(leaf, item);
5f39d397 6520 extent_start = found_key.offset;
a5eeb3d1 6521 extent_end = btrfs_file_extent_end(path);
694c12ed
NB
6522 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6523 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6bf9e4bd
QW
6524 /* Only regular file could have regular/prealloc extent */
6525 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6526 ret = -EUCLEAN;
6527 btrfs_crit(fs_info,
6528 "regular/prealloc extent found for non-regular inode %llu",
6529 btrfs_ino(inode));
6530 goto out;
6531 }
09ed2f16
LB
6532 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6533 extent_start);
694c12ed 6534 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
09ed2f16
LB
6535 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6536 path->slots[0],
6537 extent_start);
9036c102 6538 }
25a50341 6539next:
9036c102
YZ
6540 if (start >= extent_end) {
6541 path->slots[0]++;
6542 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6543 ret = btrfs_next_leaf(root, path);
6544 if (ret < 0) {
6545 err = ret;
6546 goto out;
b8eeab7f 6547 } else if (ret > 0) {
9036c102 6548 goto not_found;
b8eeab7f 6549 }
9036c102 6550 leaf = path->nodes[0];
a52d9a80 6551 }
9036c102
YZ
6552 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6553 if (found_key.objectid != objectid ||
6554 found_key.type != BTRFS_EXTENT_DATA_KEY)
6555 goto not_found;
6556 if (start + len <= found_key.offset)
6557 goto not_found;
e2eca69d
WS
6558 if (start > found_key.offset)
6559 goto next;
02a033df
NB
6560
6561 /* New extent overlaps with existing one */
9036c102 6562 em->start = start;
70c8a91c 6563 em->orig_start = start;
9036c102 6564 em->len = found_key.offset - start;
02a033df
NB
6565 em->block_start = EXTENT_MAP_HOLE;
6566 goto insert;
9036c102
YZ
6567 }
6568
39b07b5d 6569 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
7ffbb598 6570
694c12ed
NB
6571 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6572 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 6573 goto insert;
694c12ed 6574 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 6575 unsigned long ptr;
a52d9a80 6576 char *map;
3326d1b0
CM
6577 size_t size;
6578 size_t extent_offset;
6579 size_t copy_size;
a52d9a80 6580
39b07b5d 6581 if (!page)
689f9346 6582 goto out;
5f39d397 6583
e41ca589 6584 size = btrfs_file_extent_ram_bytes(leaf, item);
9036c102 6585 extent_offset = page_offset(page) + pg_offset - extent_start;
09cbfeaf
KS
6586 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6587 size - extent_offset);
3326d1b0 6588 em->start = extent_start + extent_offset;
0b246afa 6589 em->len = ALIGN(copy_size, fs_info->sectorsize);
b4939680 6590 em->orig_block_len = em->len;
70c8a91c 6591 em->orig_start = em->start;
689f9346 6592 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
e49aabd9
LB
6593
6594 btrfs_set_path_blocking(path);
bf46f52d 6595 if (!PageUptodate(page)) {
261507a0
LZ
6596 if (btrfs_file_extent_compression(leaf, item) !=
6597 BTRFS_COMPRESS_NONE) {
e40da0e5 6598 ret = uncompress_inline(path, page, pg_offset,
c8b97818 6599 extent_offset, item);
166ae5a4
ZB
6600 if (ret) {
6601 err = ret;
6602 goto out;
6603 }
c8b97818
CM
6604 } else {
6605 map = kmap(page);
6606 read_extent_buffer(leaf, map + pg_offset, ptr,
6607 copy_size);
09cbfeaf 6608 if (pg_offset + copy_size < PAGE_SIZE) {
93c82d57 6609 memset(map + pg_offset + copy_size, 0,
09cbfeaf 6610 PAGE_SIZE - pg_offset -
93c82d57
CM
6611 copy_size);
6612 }
c8b97818
CM
6613 kunmap(page);
6614 }
179e29e4 6615 flush_dcache_page(page);
a52d9a80 6616 }
d1310b2e 6617 set_extent_uptodate(io_tree, em->start,
507903b8 6618 extent_map_end(em) - 1, NULL, GFP_NOFS);
a52d9a80 6619 goto insert;
a52d9a80
CM
6620 }
6621not_found:
6622 em->start = start;
70c8a91c 6623 em->orig_start = start;
d1310b2e 6624 em->len = len;
5f39d397 6625 em->block_start = EXTENT_MAP_HOLE;
a52d9a80 6626insert:
b3b4aa74 6627 btrfs_release_path(path);
d1310b2e 6628 if (em->start > start || extent_map_end(em) <= start) {
0b246afa 6629 btrfs_err(fs_info,
5d163e0e
JM
6630 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6631 em->start, em->len, start, len);
a52d9a80
CM
6632 err = -EIO;
6633 goto out;
6634 }
d1310b2e
CM
6635
6636 err = 0;
890871be 6637 write_lock(&em_tree->lock);
f46b24c9 6638 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
890871be 6639 write_unlock(&em_tree->lock);
a52d9a80 6640out:
c6414280 6641 btrfs_free_path(path);
1abe9b8a 6642
fc4f21b1 6643 trace_btrfs_get_extent(root, inode, em);
1abe9b8a 6644
a52d9a80
CM
6645 if (err) {
6646 free_extent_map(em);
a52d9a80
CM
6647 return ERR_PTR(err);
6648 }
79787eaa 6649 BUG_ON(!em); /* Error is always set */
a52d9a80
CM
6650 return em;
6651}
6652
fc4f21b1 6653struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
4ab47a8d 6654 u64 start, u64 len)
ec29ed5b
CM
6655{
6656 struct extent_map *em;
6657 struct extent_map *hole_em = NULL;
f3714ef4 6658 u64 delalloc_start = start;
ec29ed5b 6659 u64 end;
f3714ef4
NB
6660 u64 delalloc_len;
6661 u64 delalloc_end;
ec29ed5b
CM
6662 int err = 0;
6663
39b07b5d 6664 em = btrfs_get_extent(inode, NULL, 0, start, len);
ec29ed5b
CM
6665 if (IS_ERR(em))
6666 return em;
9986277e
DC
6667 /*
6668 * If our em maps to:
6669 * - a hole or
6670 * - a pre-alloc extent,
6671 * there might actually be delalloc bytes behind it.
6672 */
6673 if (em->block_start != EXTENT_MAP_HOLE &&
6674 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6675 return em;
6676 else
6677 hole_em = em;
ec29ed5b
CM
6678
6679 /* check to see if we've wrapped (len == -1 or similar) */
6680 end = start + len;
6681 if (end < start)
6682 end = (u64)-1;
6683 else
6684 end -= 1;
6685
6686 em = NULL;
6687
6688 /* ok, we didn't find anything, lets look for delalloc */
f3714ef4 6689 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
ec29ed5b 6690 end, len, EXTENT_DELALLOC, 1);
f3714ef4
NB
6691 delalloc_end = delalloc_start + delalloc_len;
6692 if (delalloc_end < delalloc_start)
6693 delalloc_end = (u64)-1;
ec29ed5b
CM
6694
6695 /*
f3714ef4
NB
6696 * We didn't find anything useful, return the original results from
6697 * get_extent()
ec29ed5b 6698 */
f3714ef4 6699 if (delalloc_start > end || delalloc_end <= start) {
ec29ed5b
CM
6700 em = hole_em;
6701 hole_em = NULL;
6702 goto out;
6703 }
6704
f3714ef4
NB
6705 /*
6706 * Adjust the delalloc_start to make sure it doesn't go backwards from
6707 * the start they passed in
ec29ed5b 6708 */
f3714ef4
NB
6709 delalloc_start = max(start, delalloc_start);
6710 delalloc_len = delalloc_end - delalloc_start;
ec29ed5b 6711
f3714ef4
NB
6712 if (delalloc_len > 0) {
6713 u64 hole_start;
02950af4 6714 u64 hole_len;
f3714ef4 6715 const u64 hole_end = extent_map_end(hole_em);
ec29ed5b 6716
172ddd60 6717 em = alloc_extent_map();
ec29ed5b
CM
6718 if (!em) {
6719 err = -ENOMEM;
6720 goto out;
6721 }
f3714ef4
NB
6722
6723 ASSERT(hole_em);
ec29ed5b 6724 /*
f3714ef4
NB
6725 * When btrfs_get_extent can't find anything it returns one
6726 * huge hole
ec29ed5b 6727 *
f3714ef4
NB
6728 * Make sure what it found really fits our range, and adjust to
6729 * make sure it is based on the start from the caller
ec29ed5b 6730 */
f3714ef4
NB
6731 if (hole_end <= start || hole_em->start > end) {
6732 free_extent_map(hole_em);
6733 hole_em = NULL;
6734 } else {
6735 hole_start = max(hole_em->start, start);
6736 hole_len = hole_end - hole_start;
ec29ed5b 6737 }
f3714ef4
NB
6738
6739 if (hole_em && delalloc_start > hole_start) {
6740 /*
6741 * Our hole starts before our delalloc, so we have to
6742 * return just the parts of the hole that go until the
6743 * delalloc starts
ec29ed5b 6744 */
f3714ef4 6745 em->len = min(hole_len, delalloc_start - hole_start);
ec29ed5b
CM
6746 em->start = hole_start;
6747 em->orig_start = hole_start;
6748 /*
f3714ef4
NB
6749 * Don't adjust block start at all, it is fixed at
6750 * EXTENT_MAP_HOLE
ec29ed5b
CM
6751 */
6752 em->block_start = hole_em->block_start;
6753 em->block_len = hole_len;
f9e4fb53
LB
6754 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6755 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
ec29ed5b 6756 } else {
f3714ef4
NB
6757 /*
6758 * Hole is out of passed range or it starts after
6759 * delalloc range
6760 */
6761 em->start = delalloc_start;
6762 em->len = delalloc_len;
6763 em->orig_start = delalloc_start;
ec29ed5b 6764 em->block_start = EXTENT_MAP_DELALLOC;
f3714ef4 6765 em->block_len = delalloc_len;
ec29ed5b 6766 }
bf8d32b9 6767 } else {
ec29ed5b
CM
6768 return hole_em;
6769 }
6770out:
6771
6772 free_extent_map(hole_em);
6773 if (err) {
6774 free_extent_map(em);
6775 return ERR_PTR(err);
6776 }
6777 return em;
6778}
6779
5f9a8a51
FM
6780static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6781 const u64 start,
6782 const u64 len,
6783 const u64 orig_start,
6784 const u64 block_start,
6785 const u64 block_len,
6786 const u64 orig_block_len,
6787 const u64 ram_bytes,
6788 const int type)
6789{
6790 struct extent_map *em = NULL;
6791 int ret;
6792
5f9a8a51 6793 if (type != BTRFS_ORDERED_NOCOW) {
6f9994db
LB
6794 em = create_io_em(inode, start, len, orig_start,
6795 block_start, block_len, orig_block_len,
6796 ram_bytes,
6797 BTRFS_COMPRESS_NONE, /* compress_type */
6798 type);
5f9a8a51
FM
6799 if (IS_ERR(em))
6800 goto out;
6801 }
6802 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6803 len, block_len, type);
6804 if (ret) {
6805 if (em) {
6806 free_extent_map(em);
dcdbc059 6807 btrfs_drop_extent_cache(BTRFS_I(inode), start,
5f9a8a51
FM
6808 start + len - 1, 0);
6809 }
6810 em = ERR_PTR(ret);
6811 }
6812 out:
5f9a8a51
FM
6813
6814 return em;
6815}
6816
4b46fce2
JB
6817static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6818 u64 start, u64 len)
6819{
0b246afa 6820 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 6821 struct btrfs_root *root = BTRFS_I(inode)->root;
70c8a91c 6822 struct extent_map *em;
4b46fce2
JB
6823 struct btrfs_key ins;
6824 u64 alloc_hint;
6825 int ret;
4b46fce2 6826
4b46fce2 6827 alloc_hint = get_extent_allocation_hint(inode, start, len);
0b246afa 6828 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
da17066c 6829 0, alloc_hint, &ins, 1, 1);
00361589
JB
6830 if (ret)
6831 return ERR_PTR(ret);
4b46fce2 6832
5f9a8a51
FM
6833 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6834 ins.objectid, ins.offset, ins.offset,
6288d6ea 6835 ins.offset, BTRFS_ORDERED_REGULAR);
0b246afa 6836 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
5f9a8a51 6837 if (IS_ERR(em))
2ff7e61e
JM
6838 btrfs_free_reserved_extent(fs_info, ins.objectid,
6839 ins.offset, 1);
de0ee0ed 6840
4b46fce2
JB
6841 return em;
6842}
6843
46bfbb5c
CM
6844/*
6845 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6846 * block must be cow'd
6847 */
00361589 6848noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7ee9e440
JB
6849 u64 *orig_start, u64 *orig_block_len,
6850 u64 *ram_bytes)
46bfbb5c 6851{
2ff7e61e 6852 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
46bfbb5c
CM
6853 struct btrfs_path *path;
6854 int ret;
6855 struct extent_buffer *leaf;
6856 struct btrfs_root *root = BTRFS_I(inode)->root;
7b2b7085 6857 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
46bfbb5c
CM
6858 struct btrfs_file_extent_item *fi;
6859 struct btrfs_key key;
6860 u64 disk_bytenr;
6861 u64 backref_offset;
6862 u64 extent_end;
6863 u64 num_bytes;
6864 int slot;
6865 int found_type;
7ee9e440 6866 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
e77751aa 6867
46bfbb5c
CM
6868 path = btrfs_alloc_path();
6869 if (!path)
6870 return -ENOMEM;
6871
f85b7379
DS
6872 ret = btrfs_lookup_file_extent(NULL, root, path,
6873 btrfs_ino(BTRFS_I(inode)), offset, 0);
46bfbb5c
CM
6874 if (ret < 0)
6875 goto out;
6876
6877 slot = path->slots[0];
6878 if (ret == 1) {
6879 if (slot == 0) {
6880 /* can't find the item, must cow */
6881 ret = 0;
6882 goto out;
6883 }
6884 slot--;
6885 }
6886 ret = 0;
6887 leaf = path->nodes[0];
6888 btrfs_item_key_to_cpu(leaf, &key, slot);
4a0cc7ca 6889 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
46bfbb5c
CM
6890 key.type != BTRFS_EXTENT_DATA_KEY) {
6891 /* not our file or wrong item type, must cow */
6892 goto out;
6893 }
6894
6895 if (key.offset > offset) {
6896 /* Wrong offset, must cow */
6897 goto out;
6898 }
6899
6900 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6901 found_type = btrfs_file_extent_type(leaf, fi);
6902 if (found_type != BTRFS_FILE_EXTENT_REG &&
6903 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6904 /* not a regular extent, must cow */
6905 goto out;
6906 }
7ee9e440
JB
6907
6908 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6909 goto out;
6910
e77751aa
MX
6911 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6912 if (extent_end <= offset)
6913 goto out;
6914
46bfbb5c 6915 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7ee9e440
JB
6916 if (disk_bytenr == 0)
6917 goto out;
6918
6919 if (btrfs_file_extent_compression(leaf, fi) ||
6920 btrfs_file_extent_encryption(leaf, fi) ||
6921 btrfs_file_extent_other_encoding(leaf, fi))
6922 goto out;
6923
78d4295b
EL
6924 /*
6925 * Do the same check as in btrfs_cross_ref_exist but without the
6926 * unnecessary search.
6927 */
6928 if (btrfs_file_extent_generation(leaf, fi) <=
6929 btrfs_root_last_snapshot(&root->root_item))
6930 goto out;
6931
46bfbb5c
CM
6932 backref_offset = btrfs_file_extent_offset(leaf, fi);
6933
7ee9e440
JB
6934 if (orig_start) {
6935 *orig_start = key.offset - backref_offset;
6936 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6937 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6938 }
eb384b55 6939
2ff7e61e 6940 if (btrfs_extent_readonly(fs_info, disk_bytenr))
46bfbb5c 6941 goto out;
7b2b7085
MX
6942
6943 num_bytes = min(offset + *len, extent_end) - offset;
6944 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6945 u64 range_end;
6946
da17066c
JM
6947 range_end = round_up(offset + num_bytes,
6948 root->fs_info->sectorsize) - 1;
7b2b7085
MX
6949 ret = test_range_bit(io_tree, offset, range_end,
6950 EXTENT_DELALLOC, 0, NULL);
6951 if (ret) {
6952 ret = -EAGAIN;
6953 goto out;
6954 }
6955 }
6956
1bda19eb 6957 btrfs_release_path(path);
46bfbb5c
CM
6958
6959 /*
6960 * look for other files referencing this extent, if we
6961 * find any we must cow
6962 */
00361589 6963
e4c3b2dc 6964 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
00361589 6965 key.offset - backref_offset, disk_bytenr);
00361589
JB
6966 if (ret) {
6967 ret = 0;
6968 goto out;
6969 }
46bfbb5c
CM
6970
6971 /*
6972 * adjust disk_bytenr and num_bytes to cover just the bytes
6973 * in this extent we are about to write. If there
6974 * are any csums in that range we have to cow in order
6975 * to keep the csums correct
6976 */
6977 disk_bytenr += backref_offset;
6978 disk_bytenr += offset - key.offset;
2ff7e61e
JM
6979 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6980 goto out;
46bfbb5c
CM
6981 /*
6982 * all of the above have passed, it is safe to overwrite this extent
6983 * without cow
6984 */
eb384b55 6985 *len = num_bytes;
46bfbb5c
CM
6986 ret = 1;
6987out:
6988 btrfs_free_path(path);
6989 return ret;
6990}
6991
eb838e73
JB
6992static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6993 struct extent_state **cached_state, int writing)
6994{
6995 struct btrfs_ordered_extent *ordered;
6996 int ret = 0;
6997
6998 while (1) {
6999 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
ff13db41 7000 cached_state);
eb838e73
JB
7001 /*
7002 * We're concerned with the entire range that we're going to be
01327610 7003 * doing DIO to, so we need to make sure there's no ordered
eb838e73
JB
7004 * extents in this range.
7005 */
a776c6fa 7006 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
eb838e73
JB
7007 lockend - lockstart + 1);
7008
7009 /*
7010 * We need to make sure there are no buffered pages in this
7011 * range either, we could have raced between the invalidate in
7012 * generic_file_direct_write and locking the extent. The
7013 * invalidate needs to happen so that reads after a write do not
7014 * get stale data.
7015 */
fc4adbff 7016 if (!ordered &&
051c98eb
DS
7017 (!writing || !filemap_range_has_page(inode->i_mapping,
7018 lockstart, lockend)))
eb838e73
JB
7019 break;
7020
7021 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
e43bbe5e 7022 cached_state);
eb838e73
JB
7023
7024 if (ordered) {
ade77029
FM
7025 /*
7026 * If we are doing a DIO read and the ordered extent we
7027 * found is for a buffered write, we can not wait for it
7028 * to complete and retry, because if we do so we can
7029 * deadlock with concurrent buffered writes on page
7030 * locks. This happens only if our DIO read covers more
7031 * than one extent map, if at this point has already
7032 * created an ordered extent for a previous extent map
7033 * and locked its range in the inode's io tree, and a
7034 * concurrent write against that previous extent map's
7035 * range and this range started (we unlock the ranges
7036 * in the io tree only when the bios complete and
7037 * buffered writes always lock pages before attempting
7038 * to lock range in the io tree).
7039 */
7040 if (writing ||
7041 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7042 btrfs_start_ordered_extent(inode, ordered, 1);
7043 else
7044 ret = -ENOTBLK;
eb838e73
JB
7045 btrfs_put_ordered_extent(ordered);
7046 } else {
eb838e73 7047 /*
b850ae14
FM
7048 * We could trigger writeback for this range (and wait
7049 * for it to complete) and then invalidate the pages for
7050 * this range (through invalidate_inode_pages2_range()),
7051 * but that can lead us to a deadlock with a concurrent
7052 * call to readpages() (a buffered read or a defrag call
7053 * triggered a readahead) on a page lock due to an
7054 * ordered dio extent we created before but did not have
7055 * yet a corresponding bio submitted (whence it can not
7056 * complete), which makes readpages() wait for that
7057 * ordered extent to complete while holding a lock on
7058 * that page.
eb838e73 7059 */
b850ae14 7060 ret = -ENOTBLK;
eb838e73
JB
7061 }
7062
ade77029
FM
7063 if (ret)
7064 break;
7065
eb838e73
JB
7066 cond_resched();
7067 }
7068
7069 return ret;
7070}
7071
6f9994db
LB
7072/* The callers of this must take lock_extent() */
7073static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7074 u64 orig_start, u64 block_start,
7075 u64 block_len, u64 orig_block_len,
7076 u64 ram_bytes, int compress_type,
7077 int type)
69ffb543
JB
7078{
7079 struct extent_map_tree *em_tree;
7080 struct extent_map *em;
69ffb543
JB
7081 int ret;
7082
6f9994db
LB
7083 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7084 type == BTRFS_ORDERED_COMPRESSED ||
7085 type == BTRFS_ORDERED_NOCOW ||
1af4a0aa 7086 type == BTRFS_ORDERED_REGULAR);
6f9994db 7087
69ffb543
JB
7088 em_tree = &BTRFS_I(inode)->extent_tree;
7089 em = alloc_extent_map();
7090 if (!em)
7091 return ERR_PTR(-ENOMEM);
7092
7093 em->start = start;
7094 em->orig_start = orig_start;
7095 em->len = len;
7096 em->block_len = block_len;
7097 em->block_start = block_start;
b4939680 7098 em->orig_block_len = orig_block_len;
cc95bef6 7099 em->ram_bytes = ram_bytes;
70c8a91c 7100 em->generation = -1;
69ffb543 7101 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1af4a0aa 7102 if (type == BTRFS_ORDERED_PREALLOC) {
b11e234d 7103 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1af4a0aa 7104 } else if (type == BTRFS_ORDERED_COMPRESSED) {
6f9994db
LB
7105 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7106 em->compress_type = compress_type;
7107 }
69ffb543
JB
7108
7109 do {
dcdbc059 7110 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
69ffb543
JB
7111 em->start + em->len - 1, 0);
7112 write_lock(&em_tree->lock);
09a2a8f9 7113 ret = add_extent_mapping(em_tree, em, 1);
69ffb543 7114 write_unlock(&em_tree->lock);
6f9994db
LB
7115 /*
7116 * The caller has taken lock_extent(), who could race with us
7117 * to add em?
7118 */
69ffb543
JB
7119 } while (ret == -EEXIST);
7120
7121 if (ret) {
7122 free_extent_map(em);
7123 return ERR_PTR(ret);
7124 }
7125
6f9994db 7126 /* em got 2 refs now, callers needs to do free_extent_map once. */
69ffb543
JB
7127 return em;
7128}
7129
1c8d0175
NB
7130
7131static int btrfs_get_blocks_direct_read(struct extent_map *em,
7132 struct buffer_head *bh_result,
7133 struct inode *inode,
7134 u64 start, u64 len)
7135{
8530c37a
DS
7136 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7137
1c8d0175
NB
7138 if (em->block_start == EXTENT_MAP_HOLE ||
7139 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7140 return -ENOENT;
7141
7142 len = min(len, em->len - (start - em->start));
7143
7144 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7145 inode->i_blkbits;
7146 bh_result->b_size = len;
8530c37a 7147 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
1c8d0175
NB
7148 set_buffer_mapped(bh_result);
7149
7150 return 0;
7151}
7152
c5794e51
NB
7153static int btrfs_get_blocks_direct_write(struct extent_map **map,
7154 struct buffer_head *bh_result,
7155 struct inode *inode,
7156 struct btrfs_dio_data *dio_data,
7157 u64 start, u64 len)
7158{
7159 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7160 struct extent_map *em = *map;
7161 int ret = 0;
7162
7163 /*
7164 * We don't allocate a new extent in the following cases
7165 *
7166 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7167 * existing extent.
7168 * 2) The extent is marked as PREALLOC. We're good to go here and can
7169 * just use the extent.
7170 *
7171 */
7172 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7173 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7174 em->block_start != EXTENT_MAP_HOLE)) {
7175 int type;
7176 u64 block_start, orig_start, orig_block_len, ram_bytes;
7177
7178 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7179 type = BTRFS_ORDERED_PREALLOC;
7180 else
7181 type = BTRFS_ORDERED_NOCOW;
7182 len = min(len, em->len - (start - em->start));
7183 block_start = em->block_start + (start - em->start);
7184
7185 if (can_nocow_extent(inode, start, &len, &orig_start,
7186 &orig_block_len, &ram_bytes) == 1 &&
7187 btrfs_inc_nocow_writers(fs_info, block_start)) {
7188 struct extent_map *em2;
7189
7190 em2 = btrfs_create_dio_extent(inode, start, len,
7191 orig_start, block_start,
7192 len, orig_block_len,
7193 ram_bytes, type);
7194 btrfs_dec_nocow_writers(fs_info, block_start);
7195 if (type == BTRFS_ORDERED_PREALLOC) {
7196 free_extent_map(em);
7197 *map = em = em2;
7198 }
7199
7200 if (em2 && IS_ERR(em2)) {
7201 ret = PTR_ERR(em2);
7202 goto out;
7203 }
7204 /*
7205 * For inode marked NODATACOW or extent marked PREALLOC,
7206 * use the existing or preallocated extent, so does not
7207 * need to adjust btrfs_space_info's bytes_may_use.
7208 */
7209 btrfs_free_reserved_data_space_noquota(inode, start,
7210 len);
7211 goto skip_cow;
7212 }
7213 }
7214
7215 /* this will cow the extent */
7216 len = bh_result->b_size;
7217 free_extent_map(em);
7218 *map = em = btrfs_new_extent_direct(inode, start, len);
7219 if (IS_ERR(em)) {
7220 ret = PTR_ERR(em);
7221 goto out;
7222 }
7223
7224 len = min(len, em->len - (start - em->start));
7225
7226skip_cow:
7227 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7228 inode->i_blkbits;
7229 bh_result->b_size = len;
8530c37a 7230 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
c5794e51
NB
7231 set_buffer_mapped(bh_result);
7232
7233 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7234 set_buffer_new(bh_result);
7235
7236 /*
7237 * Need to update the i_size under the extent lock so buffered
7238 * readers will get the updated i_size when we unlock.
7239 */
7240 if (!dio_data->overwrite && start + len > i_size_read(inode))
7241 i_size_write(inode, start + len);
7242
7243 WARN_ON(dio_data->reserve < len);
7244 dio_data->reserve -= len;
7245 dio_data->unsubmitted_oe_range_end = start + len;
7246 current->journal_info = dio_data;
7247out:
7248 return ret;
7249}
7250
4b46fce2
JB
7251static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7252 struct buffer_head *bh_result, int create)
7253{
0b246afa 7254 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 7255 struct extent_map *em;
eb838e73 7256 struct extent_state *cached_state = NULL;
50745b0a 7257 struct btrfs_dio_data *dio_data = NULL;
4b46fce2 7258 u64 start = iblock << inode->i_blkbits;
eb838e73 7259 u64 lockstart, lockend;
4b46fce2 7260 u64 len = bh_result->b_size;
0934856d 7261 int ret = 0;
eb838e73 7262
e182163d 7263 if (!create)
0b246afa 7264 len = min_t(u64, len, fs_info->sectorsize);
eb838e73 7265
c329861d
JB
7266 lockstart = start;
7267 lockend = start + len - 1;
7268
e1cbbfa5
JB
7269 if (current->journal_info) {
7270 /*
7271 * Need to pull our outstanding extents and set journal_info to NULL so
01327610 7272 * that anything that needs to check if there's a transaction doesn't get
e1cbbfa5
JB
7273 * confused.
7274 */
50745b0a 7275 dio_data = current->journal_info;
e1cbbfa5
JB
7276 current->journal_info = NULL;
7277 }
7278
eb838e73
JB
7279 /*
7280 * If this errors out it's because we couldn't invalidate pagecache for
7281 * this range and we need to fallback to buffered.
7282 */
9c9464cc
FM
7283 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7284 create)) {
7285 ret = -ENOTBLK;
7286 goto err;
7287 }
eb838e73 7288
39b07b5d 7289 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
eb838e73
JB
7290 if (IS_ERR(em)) {
7291 ret = PTR_ERR(em);
7292 goto unlock_err;
7293 }
4b46fce2
JB
7294
7295 /*
7296 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7297 * io. INLINE is special, and we could probably kludge it in here, but
7298 * it's still buffered so for safety lets just fall back to the generic
7299 * buffered path.
7300 *
7301 * For COMPRESSED we _have_ to read the entire extent in so we can
7302 * decompress it, so there will be buffering required no matter what we
7303 * do, so go ahead and fallback to buffered.
7304 *
01327610 7305 * We return -ENOTBLK because that's what makes DIO go ahead and go back
4b46fce2
JB
7306 * to buffered IO. Don't blame me, this is the price we pay for using
7307 * the generic code.
7308 */
7309 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7310 em->block_start == EXTENT_MAP_INLINE) {
7311 free_extent_map(em);
eb838e73
JB
7312 ret = -ENOTBLK;
7313 goto unlock_err;
4b46fce2
JB
7314 }
7315
c5794e51
NB
7316 if (create) {
7317 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7318 dio_data, start, len);
7319 if (ret < 0)
7320 goto unlock_err;
7321
e182163d
OS
7322 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7323 lockend, &cached_state);
c5794e51 7324 } else {
1c8d0175
NB
7325 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7326 start, len);
7327 /* Can be negative only if we read from a hole */
7328 if (ret < 0) {
7329 ret = 0;
7330 free_extent_map(em);
7331 goto unlock_err;
7332 }
7333 /*
7334 * We need to unlock only the end area that we aren't using.
7335 * The rest is going to be unlocked by the endio routine.
7336 */
7337 lockstart = start + bh_result->b_size;
7338 if (lockstart < lockend) {
e182163d
OS
7339 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7340 lockstart, lockend, &cached_state);
1c8d0175
NB
7341 } else {
7342 free_extent_state(cached_state);
7343 }
4b46fce2
JB
7344 }
7345
4b46fce2
JB
7346 free_extent_map(em);
7347
7348 return 0;
eb838e73
JB
7349
7350unlock_err:
e182163d
OS
7351 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7352 &cached_state);
9c9464cc 7353err:
50745b0a 7354 if (dio_data)
7355 current->journal_info = dio_data;
eb838e73 7356 return ret;
4b46fce2
JB
7357}
7358
769b4f24
OS
7359static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7360{
7361 /*
7362 * This implies a barrier so that stores to dio_bio->bi_status before
7363 * this and loads of dio_bio->bi_status after this are fully ordered.
7364 */
7365 if (!refcount_dec_and_test(&dip->refs))
7366 return;
7367
7368 if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7369 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7370 dip->bytes,
7371 !dip->dio_bio->bi_status);
7372 } else {
7373 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7374 dip->logical_offset,
7375 dip->logical_offset + dip->bytes - 1);
7376 }
7377
7378 dio_end_io(dip->dio_bio);
7379 kfree(dip);
7380}
7381
77d5d689
OS
7382static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7383 int mirror_num,
7384 unsigned long bio_flags)
8b110e39 7385{
77d5d689 7386 struct btrfs_dio_private *dip = bio->bi_private;
2ff7e61e 7387 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
58efbc9f 7388 blk_status_t ret;
8b110e39 7389
37226b21 7390 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
8b110e39 7391
5c047a69 7392 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8b110e39 7393 if (ret)
ea057f6d 7394 return ret;
8b110e39 7395
77d5d689 7396 refcount_inc(&dip->refs);
08635bae 7397 ret = btrfs_map_bio(fs_info, bio, mirror_num);
8b110e39 7398 if (ret)
fd9d6670 7399 refcount_dec(&dip->refs);
77d5d689 7400 return ret;
8b110e39
MX
7401}
7402
fd9d6670
OS
7403static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7404 struct btrfs_io_bio *io_bio,
7405 const bool uptodate)
4b46fce2 7406{
fd9d6670
OS
7407 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7408 const u32 sectorsize = fs_info->sectorsize;
7409 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7410 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7411 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
17347cec
LB
7412 struct bio_vec bvec;
7413 struct bvec_iter iter;
fd9d6670
OS
7414 u64 start = io_bio->logical;
7415 int icsum = 0;
58efbc9f 7416 blk_status_t err = BLK_STS_OK;
4b46fce2 7417
fd9d6670
OS
7418 __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7419 unsigned int i, nr_sectors, pgoff;
8b110e39 7420
17347cec
LB
7421 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7422 pgoff = bvec.bv_offset;
fd9d6670 7423 for (i = 0; i < nr_sectors; i++) {
97bf5a55 7424 ASSERT(pgoff < PAGE_SIZE);
fd9d6670
OS
7425 if (uptodate &&
7426 (!csum || !check_data_csum(inode, io_bio, icsum,
7427 bvec.bv_page, pgoff,
7428 start, sectorsize))) {
7429 clean_io_failure(fs_info, failure_tree, io_tree,
7430 start, bvec.bv_page,
7431 btrfs_ino(BTRFS_I(inode)),
7432 pgoff);
7433 } else {
7434 blk_status_t status;
7435
77d5d689
OS
7436 status = btrfs_submit_read_repair(inode,
7437 &io_bio->bio,
7438 start - io_bio->logical,
fd9d6670
OS
7439 bvec.bv_page, pgoff,
7440 start,
7441 start + sectorsize - 1,
77d5d689
OS
7442 io_bio->mirror_num,
7443 submit_dio_repair_bio);
fd9d6670
OS
7444 if (status)
7445 err = status;
7446 }
7447 start += sectorsize;
7448 icsum++;
2dabb324 7449 pgoff += sectorsize;
2dabb324 7450 }
2c30c71b 7451 }
c1dc0896
MX
7452 return err;
7453}
7454
52427260
QW
7455static void __endio_write_update_ordered(struct inode *inode,
7456 const u64 offset, const u64 bytes,
7457 const bool uptodate)
4b46fce2 7458{
0b246afa 7459 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4b46fce2 7460 struct btrfs_ordered_extent *ordered = NULL;
52427260 7461 struct btrfs_workqueue *wq;
14543774
FM
7462 u64 ordered_offset = offset;
7463 u64 ordered_bytes = bytes;
67c003f9 7464 u64 last_offset;
4b46fce2 7465
a0cac0ec 7466 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
52427260 7467 wq = fs_info->endio_freespace_worker;
a0cac0ec 7468 else
52427260 7469 wq = fs_info->endio_write_workers;
52427260 7470
b25f0d00
NB
7471 while (ordered_offset < offset + bytes) {
7472 last_offset = ordered_offset;
7473 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7474 &ordered_offset,
7475 ordered_bytes,
7476 uptodate)) {
a0cac0ec
OS
7477 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7478 NULL);
b25f0d00
NB
7479 btrfs_queue_work(wq, &ordered->work);
7480 }
7481 /*
7482 * If btrfs_dec_test_ordered_pending does not find any ordered
7483 * extent in the range, we can exit.
7484 */
7485 if (ordered_offset == last_offset)
7486 return;
7487 /*
7488 * Our bio might span multiple ordered extents. In this case
52042d8e 7489 * we keep going until we have accounted the whole dio.
b25f0d00
NB
7490 */
7491 if (ordered_offset < offset + bytes) {
7492 ordered_bytes = offset + bytes - ordered_offset;
7493 ordered = NULL;
7494 }
163cf09c 7495 }
14543774
FM
7496}
7497
d0ee3934 7498static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
d0779291 7499 struct bio *bio, u64 offset)
eaf25d93 7500{
c6100a4b 7501 struct inode *inode = private_data;
4e4cbee9 7502 blk_status_t ret;
2ff7e61e 7503 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
79787eaa 7504 BUG_ON(ret); /* -ENOMEM */
eaf25d93
CM
7505 return 0;
7506}
7507
4246a0b6 7508static void btrfs_end_dio_bio(struct bio *bio)
e65e1535
MX
7509{
7510 struct btrfs_dio_private *dip = bio->bi_private;
4e4cbee9 7511 blk_status_t err = bio->bi_status;
e65e1535 7512
8b110e39
MX
7513 if (err)
7514 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
6296b960 7515 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
f85b7379
DS
7516 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7517 bio->bi_opf,
8b110e39
MX
7518 (unsigned long long)bio->bi_iter.bi_sector,
7519 bio->bi_iter.bi_size, err);
7520
769b4f24
OS
7521 if (bio_op(bio) == REQ_OP_READ) {
7522 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
fd9d6670 7523 !err);
e65e1535
MX
7524 }
7525
769b4f24
OS
7526 if (err)
7527 dip->dio_bio->bi_status = err;
e65e1535 7528
e65e1535 7529 bio_put(bio);
769b4f24 7530 btrfs_dio_private_put(dip);
e65e1535
MX
7531}
7532
d0ee3934
DS
7533static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7534 struct inode *inode, u64 file_offset, int async_submit)
e65e1535 7535{
0b246afa 7536 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
facc8a22 7537 struct btrfs_dio_private *dip = bio->bi_private;
37226b21 7538 bool write = bio_op(bio) == REQ_OP_WRITE;
4e4cbee9 7539 blk_status_t ret;
e65e1535 7540
4c274bc6 7541 /* Check btrfs_submit_bio_hook() for rules about async submit. */
b812ce28
JB
7542 if (async_submit)
7543 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7544
5fd02043 7545 if (!write) {
0b246afa 7546 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
5fd02043
JB
7547 if (ret)
7548 goto err;
7549 }
e65e1535 7550
e6961cac 7551 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1ae39938
JB
7552 goto map;
7553
7554 if (write && async_submit) {
c6100a4b
JB
7555 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7556 file_offset, inode,
e288c080 7557 btrfs_submit_bio_start_direct_io);
e65e1535 7558 goto err;
1ae39938
JB
7559 } else if (write) {
7560 /*
7561 * If we aren't doing async submit, calculate the csum of the
7562 * bio now.
7563 */
2ff7e61e 7564 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
1ae39938
JB
7565 if (ret)
7566 goto err;
23ea8e5a 7567 } else {
85879573
OS
7568 u64 csum_offset;
7569
7570 csum_offset = file_offset - dip->logical_offset;
7571 csum_offset >>= inode->i_sb->s_blocksize_bits;
7572 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7573 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
c2db1073 7574 }
1ae39938 7575map:
08635bae 7576 ret = btrfs_map_bio(fs_info, bio, 0);
e65e1535 7577err:
e65e1535
MX
7578 return ret;
7579}
7580
c36cac28
OS
7581/*
7582 * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7583 * or ordered extents whether or not we submit any bios.
7584 */
7585static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7586 struct inode *inode,
7587 loff_t file_offset)
e65e1535 7588{
c36cac28 7589 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
85879573
OS
7590 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7591 size_t dip_size;
c36cac28 7592 struct btrfs_dio_private *dip;
c36cac28 7593
85879573
OS
7594 dip_size = sizeof(*dip);
7595 if (!write && csum) {
7596 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7597 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7598 size_t nblocks;
7599
7600 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7601 dip_size += csum_size * nblocks;
7602 }
7603
7604 dip = kzalloc(dip_size, GFP_NOFS);
c36cac28
OS
7605 if (!dip)
7606 return NULL;
7607
c36cac28
OS
7608 dip->inode = inode;
7609 dip->logical_offset = file_offset;
7610 dip->bytes = dio_bio->bi_iter.bi_size;
7611 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
c36cac28 7612 dip->dio_bio = dio_bio;
e3b318d1 7613 refcount_set(&dip->refs, 1);
c36cac28
OS
7614
7615 if (write) {
7616 struct btrfs_dio_data *dio_data = current->journal_info;
7617
7618 /*
7619 * Setting range start and end to the same value means that
7620 * no cleanup will happen in btrfs_direct_IO
7621 */
7622 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
7623 dip->bytes;
7624 dio_data->unsubmitted_oe_range_start =
7625 dio_data->unsubmitted_oe_range_end;
c36cac28
OS
7626 }
7627 return dip;
7628}
7629
7630static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7631 loff_t file_offset)
7632{
7633 const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
85879573 7634 const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
0b246afa 7635 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
769b4f24
OS
7636 const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7637 BTRFS_BLOCK_GROUP_RAID56_MASK);
c36cac28 7638 struct btrfs_dio_private *dip;
e65e1535 7639 struct bio *bio;
c36cac28 7640 u64 start_sector;
1ae39938 7641 int async_submit = 0;
725130ba
LB
7642 u64 submit_len;
7643 int clone_offset = 0;
7644 int clone_len;
5f4dc8fc 7645 int ret;
58efbc9f 7646 blk_status_t status;
89b798ad 7647 struct btrfs_io_geometry geom;
e65e1535 7648
c36cac28
OS
7649 dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7650 if (!dip) {
7651 if (!write) {
7652 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7653 file_offset + dio_bio->bi_iter.bi_size - 1);
7654 }
7655 dio_bio->bi_status = BLK_STS_RESOURCE;
7656 dio_end_io(dio_bio);
7657 return;
7658 }
7659
85879573
OS
7660 if (!write && csum) {
7661 /*
7662 * Load the csums up front to reduce csum tree searches and
7663 * contention when submitting bios.
7664 */
7665 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7666 dip->csums);
7667 if (status != BLK_STS_OK)
7668 goto out_err;
7669 }
7670
769b4f24
OS
7671 start_sector = dio_bio->bi_iter.bi_sector;
7672 submit_len = dio_bio->bi_iter.bi_size;
facc8a22 7673
3c91ee69 7674 do {
769b4f24
OS
7675 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7676 start_sector << 9, submit_len,
7677 &geom);
7678 if (ret) {
7679 status = errno_to_blk_status(ret);
7680 goto out_err;
7681 }
7682 ASSERT(geom.len <= INT_MAX);
7683
89b798ad 7684 clone_len = min_t(int, submit_len, geom.len);
02f57c7a 7685
725130ba
LB
7686 /*
7687 * This will never fail as it's passing GPF_NOFS and
7688 * the allocation is backed by btrfs_bioset.
7689 */
769b4f24 7690 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
725130ba
LB
7691 bio->bi_private = dip;
7692 bio->bi_end_io = btrfs_end_dio_bio;
7693 btrfs_io_bio(bio)->logical = file_offset;
7694
7695 ASSERT(submit_len >= clone_len);
7696 submit_len -= clone_len;
e65e1535 7697
725130ba
LB
7698 /*
7699 * Increase the count before we submit the bio so we know
7700 * the end IO handler won't happen before we increase the
7701 * count. Otherwise, the dip might get freed before we're
7702 * done setting it up.
769b4f24
OS
7703 *
7704 * We transfer the initial reference to the last bio, so we
7705 * don't need to increment the reference count for the last one.
725130ba 7706 */
769b4f24
OS
7707 if (submit_len > 0) {
7708 refcount_inc(&dip->refs);
7709 /*
7710 * If we are submitting more than one bio, submit them
7711 * all asynchronously. The exception is RAID 5 or 6, as
7712 * asynchronous checksums make it difficult to collect
7713 * full stripe writes.
7714 */
7715 if (!raid56)
7716 async_submit = 1;
7717 }
e65e1535 7718
d0ee3934 7719 status = btrfs_submit_dio_bio(bio, inode, file_offset,
58efbc9f
OS
7720 async_submit);
7721 if (status) {
725130ba 7722 bio_put(bio);
769b4f24
OS
7723 if (submit_len > 0)
7724 refcount_dec(&dip->refs);
725130ba
LB
7725 goto out_err;
7726 }
e65e1535 7727
725130ba
LB
7728 clone_offset += clone_len;
7729 start_sector += clone_len >> 9;
7730 file_offset += clone_len;
3c91ee69 7731 } while (submit_len > 0);
769b4f24 7732 return;
e65e1535 7733
e65e1535 7734out_err:
769b4f24
OS
7735 dip->dio_bio->bi_status = status;
7736 btrfs_dio_private_put(dip);
4b46fce2
JB
7737}
7738
2ff7e61e 7739static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
2ff7e61e 7740 const struct iov_iter *iter, loff_t offset)
5a5f79b5
CM
7741{
7742 int seg;
a1b75f7d 7743 int i;
0b246afa 7744 unsigned int blocksize_mask = fs_info->sectorsize - 1;
5a5f79b5 7745 ssize_t retval = -EINVAL;
5a5f79b5
CM
7746
7747 if (offset & blocksize_mask)
7748 goto out;
7749
28060d5d
AV
7750 if (iov_iter_alignment(iter) & blocksize_mask)
7751 goto out;
a1b75f7d 7752
28060d5d 7753 /* If this is a write we don't need to check anymore */
cd27e455 7754 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
28060d5d
AV
7755 return 0;
7756 /*
7757 * Check to make sure we don't have duplicate iov_base's in this
7758 * iovec, if so return EINVAL, otherwise we'll get csum errors
7759 * when reading back.
7760 */
7761 for (seg = 0; seg < iter->nr_segs; seg++) {
7762 for (i = seg + 1; i < iter->nr_segs; i++) {
7763 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
a1b75f7d
JB
7764 goto out;
7765 }
5a5f79b5
CM
7766 }
7767 retval = 0;
7768out:
7769 return retval;
7770}
eb838e73 7771
c8b8e32d 7772static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
16432985 7773{
4b46fce2
JB
7774 struct file *file = iocb->ki_filp;
7775 struct inode *inode = file->f_mapping->host;
0b246afa 7776 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
50745b0a 7777 struct btrfs_dio_data dio_data = { 0 };
364ecf36 7778 struct extent_changeset *data_reserved = NULL;
c8b8e32d 7779 loff_t offset = iocb->ki_pos;
0934856d 7780 size_t count = 0;
2e60a51e 7781 int flags = 0;
38851cc1
MX
7782 bool wakeup = true;
7783 bool relock = false;
0934856d 7784 ssize_t ret;
4b46fce2 7785
8c70c9f8 7786 if (check_direct_IO(fs_info, iter, offset))
5a5f79b5 7787 return 0;
3f7c579c 7788
fe0f07d0 7789 inode_dio_begin(inode);
38851cc1 7790
0e267c44 7791 /*
41bd9ca4
MX
7792 * The generic stuff only does filemap_write_and_wait_range, which
7793 * isn't enough if we've written compressed pages to this area, so
7794 * we need to flush the dirty pages again to make absolutely sure
7795 * that any outstanding dirty pages are on disk.
0e267c44 7796 */
a6cbcd4a 7797 count = iov_iter_count(iter);
41bd9ca4
MX
7798 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7799 &BTRFS_I(inode)->runtime_flags))
9a025a08
WS
7800 filemap_fdatawrite_range(inode->i_mapping, offset,
7801 offset + count - 1);
0e267c44 7802
6f673763 7803 if (iov_iter_rw(iter) == WRITE) {
38851cc1
MX
7804 /*
7805 * If the write DIO is beyond the EOF, we need update
7806 * the isize, but it is protected by i_mutex. So we can
7807 * not unlock the i_mutex at this case.
7808 */
7809 if (offset + count <= inode->i_size) {
4aaedfb0 7810 dio_data.overwrite = 1;
5955102c 7811 inode_unlock(inode);
38851cc1 7812 relock = true;
edf064e7
GR
7813 } else if (iocb->ki_flags & IOCB_NOWAIT) {
7814 ret = -EAGAIN;
7815 goto out;
38851cc1 7816 }
364ecf36
QW
7817 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
7818 offset, count);
0934856d 7819 if (ret)
38851cc1 7820 goto out;
e1cbbfa5
JB
7821
7822 /*
7823 * We need to know how many extents we reserved so that we can
7824 * do the accounting properly if we go over the number we
7825 * originally calculated. Abuse current->journal_info for this.
7826 */
da17066c 7827 dio_data.reserve = round_up(count,
0b246afa 7828 fs_info->sectorsize);
f28a4928
FM
7829 dio_data.unsubmitted_oe_range_start = (u64)offset;
7830 dio_data.unsubmitted_oe_range_end = (u64)offset;
50745b0a 7831 current->journal_info = &dio_data;
97dcdea0 7832 down_read(&BTRFS_I(inode)->dio_sem);
ee39b432
DS
7833 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7834 &BTRFS_I(inode)->runtime_flags)) {
fe0f07d0 7835 inode_dio_end(inode);
38851cc1
MX
7836 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7837 wakeup = false;
0934856d
MX
7838 }
7839
17f8c842 7840 ret = __blockdev_direct_IO(iocb, inode,
0b246afa 7841 fs_info->fs_devices->latest_bdev,
c8b8e32d 7842 iter, btrfs_get_blocks_direct, NULL,
17f8c842 7843 btrfs_submit_direct, flags);
6f673763 7844 if (iov_iter_rw(iter) == WRITE) {
97dcdea0 7845 up_read(&BTRFS_I(inode)->dio_sem);
e1cbbfa5 7846 current->journal_info = NULL;
ddba1bfc 7847 if (ret < 0 && ret != -EIOCBQUEUED) {
50745b0a 7848 if (dio_data.reserve)
bc42bda2 7849 btrfs_delalloc_release_space(inode, data_reserved,
43b18595 7850 offset, dio_data.reserve, true);
f28a4928
FM
7851 /*
7852 * On error we might have left some ordered extents
7853 * without submitting corresponding bios for them, so
7854 * cleanup them up to avoid other tasks getting them
7855 * and waiting for them to complete forever.
7856 */
7857 if (dio_data.unsubmitted_oe_range_start <
7858 dio_data.unsubmitted_oe_range_end)
52427260 7859 __endio_write_update_ordered(inode,
f28a4928
FM
7860 dio_data.unsubmitted_oe_range_start,
7861 dio_data.unsubmitted_oe_range_end -
7862 dio_data.unsubmitted_oe_range_start,
52427260 7863 false);
ddba1bfc 7864 } else if (ret >= 0 && (size_t)ret < count)
bc42bda2 7865 btrfs_delalloc_release_space(inode, data_reserved,
43b18595 7866 offset, count - (size_t)ret, true);
8702ba93 7867 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
0934856d 7868 }
38851cc1 7869out:
2e60a51e 7870 if (wakeup)
fe0f07d0 7871 inode_dio_end(inode);
38851cc1 7872 if (relock)
5955102c 7873 inode_lock(inode);
0934856d 7874
364ecf36 7875 extent_changeset_free(data_reserved);
0934856d 7876 return ret;
16432985
CM
7877}
7878
05dadc09
TI
7879#define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7880
1506fcc8
YS
7881static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7882 __u64 start, __u64 len)
7883{
05dadc09
TI
7884 int ret;
7885
7886 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7887 if (ret)
7888 return ret;
7889
2135fb9b 7890 return extent_fiemap(inode, fieinfo, start, len);
1506fcc8
YS
7891}
7892
a52d9a80 7893int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 7894{
71ad38b4 7895 return extent_read_full_page(page, btrfs_get_extent, 0);
9ebefb18 7896}
1832a6d5 7897
a52d9a80 7898static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 7899{
be7bd730
JB
7900 struct inode *inode = page->mapping->host;
7901 int ret;
b888db2b
CM
7902
7903 if (current->flags & PF_MEMALLOC) {
7904 redirty_page_for_writepage(wbc, page);
7905 unlock_page(page);
7906 return 0;
7907 }
be7bd730
JB
7908
7909 /*
7910 * If we are under memory pressure we will call this directly from the
7911 * VM, we need to make sure we have the inode referenced for the ordered
7912 * extent. If not just return like we didn't do anything.
7913 */
7914 if (!igrab(inode)) {
7915 redirty_page_for_writepage(wbc, page);
7916 return AOP_WRITEPAGE_ACTIVATE;
7917 }
0a9b0e53 7918 ret = extent_write_full_page(page, wbc);
be7bd730
JB
7919 btrfs_add_delayed_iput(inode);
7920 return ret;
9ebefb18
CM
7921}
7922
48a3b636
ES
7923static int btrfs_writepages(struct address_space *mapping,
7924 struct writeback_control *wbc)
b293f02e 7925{
8ae225a8 7926 return extent_writepages(mapping, wbc);
b293f02e
CM
7927}
7928
3ab2fb5a
CM
7929static int
7930btrfs_readpages(struct file *file, struct address_space *mapping,
7931 struct list_head *pages, unsigned nr_pages)
7932{
2a3ff0ad 7933 return extent_readpages(mapping, pages, nr_pages);
3ab2fb5a 7934}
2a3ff0ad 7935
e6dcd2dc 7936static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 7937{
477a30ba 7938 int ret = try_release_extent_mapping(page, gfp_flags);
a52d9a80
CM
7939 if (ret == 1) {
7940 ClearPagePrivate(page);
7941 set_page_private(page, 0);
09cbfeaf 7942 put_page(page);
39279cc3 7943 }
a52d9a80 7944 return ret;
39279cc3
CM
7945}
7946
e6dcd2dc
CM
7947static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7948{
98509cfc
CM
7949 if (PageWriteback(page) || PageDirty(page))
7950 return 0;
3ba7ab22 7951 return __btrfs_releasepage(page, gfp_flags);
e6dcd2dc
CM
7952}
7953
f8e66081
RG
7954#ifdef CONFIG_MIGRATION
7955static int btrfs_migratepage(struct address_space *mapping,
7956 struct page *newpage, struct page *page,
7957 enum migrate_mode mode)
7958{
7959 int ret;
7960
7961 ret = migrate_page_move_mapping(mapping, newpage, page, 0);
7962 if (ret != MIGRATEPAGE_SUCCESS)
7963 return ret;
7964
7965 if (page_has_private(page)) {
7966 ClearPagePrivate(page);
7967 get_page(newpage);
7968 set_page_private(newpage, page_private(page));
7969 set_page_private(page, 0);
7970 put_page(page);
7971 SetPagePrivate(newpage);
7972 }
7973
7974 if (PagePrivate2(page)) {
7975 ClearPagePrivate2(page);
7976 SetPagePrivate2(newpage);
7977 }
7978
7979 if (mode != MIGRATE_SYNC_NO_COPY)
7980 migrate_page_copy(newpage, page);
7981 else
7982 migrate_page_states(newpage, page);
7983 return MIGRATEPAGE_SUCCESS;
7984}
7985#endif
7986
d47992f8
LC
7987static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7988 unsigned int length)
39279cc3 7989{
5fd02043 7990 struct inode *inode = page->mapping->host;
d1310b2e 7991 struct extent_io_tree *tree;
e6dcd2dc 7992 struct btrfs_ordered_extent *ordered;
2ac55d41 7993 struct extent_state *cached_state = NULL;
e6dcd2dc 7994 u64 page_start = page_offset(page);
09cbfeaf 7995 u64 page_end = page_start + PAGE_SIZE - 1;
dbfdb6d1
CR
7996 u64 start;
7997 u64 end;
131e404a 7998 int inode_evicting = inode->i_state & I_FREEING;
39279cc3 7999
8b62b72b
CM
8000 /*
8001 * we have the page locked, so new writeback can't start,
8002 * and the dirty bit won't be cleared while we are here.
8003 *
8004 * Wait for IO on this page so that we can safely clear
8005 * the PagePrivate2 bit and do ordered accounting
8006 */
e6dcd2dc 8007 wait_on_page_writeback(page);
8b62b72b 8008
5fd02043 8009 tree = &BTRFS_I(inode)->io_tree;
e6dcd2dc
CM
8010 if (offset) {
8011 btrfs_releasepage(page, GFP_NOFS);
8012 return;
8013 }
131e404a
FDBM
8014
8015 if (!inode_evicting)
ff13db41 8016 lock_extent_bits(tree, page_start, page_end, &cached_state);
dbfdb6d1
CR
8017again:
8018 start = page_start;
a776c6fa 8019 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
dbfdb6d1 8020 page_end - start + 1);
e6dcd2dc 8021 if (ordered) {
bffe633e
OS
8022 end = min(page_end,
8023 ordered->file_offset + ordered->num_bytes - 1);
eb84ae03
CM
8024 /*
8025 * IO on this page will never be started, so we need
8026 * to account for any ordered extents now
8027 */
131e404a 8028 if (!inode_evicting)
dbfdb6d1 8029 clear_extent_bit(tree, start, end,
e182163d 8030 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
131e404a 8031 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
ae0f1625 8032 EXTENT_DEFRAG, 1, 0, &cached_state);
8b62b72b
CM
8033 /*
8034 * whoever cleared the private bit is responsible
8035 * for the finish_ordered_io
8036 */
77cef2ec
JB
8037 if (TestClearPagePrivate2(page)) {
8038 struct btrfs_ordered_inode_tree *tree;
8039 u64 new_len;
8040
8041 tree = &BTRFS_I(inode)->ordered_tree;
8042
8043 spin_lock_irq(&tree->lock);
8044 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
dbfdb6d1 8045 new_len = start - ordered->file_offset;
77cef2ec
JB
8046 if (new_len < ordered->truncated_len)
8047 ordered->truncated_len = new_len;
8048 spin_unlock_irq(&tree->lock);
8049
8050 if (btrfs_dec_test_ordered_pending(inode, &ordered,
dbfdb6d1
CR
8051 start,
8052 end - start + 1, 1))
77cef2ec 8053 btrfs_finish_ordered_io(ordered);
8b62b72b 8054 }
e6dcd2dc 8055 btrfs_put_ordered_extent(ordered);
131e404a
FDBM
8056 if (!inode_evicting) {
8057 cached_state = NULL;
dbfdb6d1 8058 lock_extent_bits(tree, start, end,
131e404a
FDBM
8059 &cached_state);
8060 }
dbfdb6d1
CR
8061
8062 start = end + 1;
8063 if (start < page_end)
8064 goto again;
131e404a
FDBM
8065 }
8066
b9d0b389
QW
8067 /*
8068 * Qgroup reserved space handler
8069 * Page here will be either
8070 * 1) Already written to disk
8071 * In this case, its reserved space is released from data rsv map
8072 * and will be freed by delayed_ref handler finally.
8073 * So even we call qgroup_free_data(), it won't decrease reserved
8074 * space.
8075 * 2) Not written to disk
0b34c261
GR
8076 * This means the reserved space should be freed here. However,
8077 * if a truncate invalidates the page (by clearing PageDirty)
8078 * and the page is accounted for while allocating extent
8079 * in btrfs_check_data_free_space() we let delayed_ref to
8080 * free the entire extent.
b9d0b389 8081 */
0b34c261 8082 if (PageDirty(page))
bc42bda2 8083 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
131e404a 8084 if (!inode_evicting) {
e182163d 8085 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
a7e3b975
FM
8086 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8087 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
ae0f1625 8088 &cached_state);
131e404a
FDBM
8089
8090 __btrfs_releasepage(page, GFP_NOFS);
e6dcd2dc 8091 }
e6dcd2dc 8092
4a096752 8093 ClearPageChecked(page);
9ad6b7bc 8094 if (PagePrivate(page)) {
9ad6b7bc
CM
8095 ClearPagePrivate(page);
8096 set_page_private(page, 0);
09cbfeaf 8097 put_page(page);
9ad6b7bc 8098 }
39279cc3
CM
8099}
8100
9ebefb18
CM
8101/*
8102 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8103 * called from a page fault handler when a page is first dirtied. Hence we must
8104 * be careful to check for EOF conditions here. We set the page up correctly
8105 * for a written page which means we get ENOSPC checking when writing into
8106 * holes and correct delalloc and unwritten extent mapping on filesystems that
8107 * support these features.
8108 *
8109 * We are not allowed to take the i_mutex here so we have to play games to
8110 * protect against truncate races as the page could now be beyond EOF. Because
d1342aad
OS
8111 * truncate_setsize() writes the inode size before removing pages, once we have
8112 * the page lock we can determine safely if the page is beyond EOF. If it is not
9ebefb18
CM
8113 * beyond EOF, then the page is guaranteed safe against truncation until we
8114 * unlock the page.
8115 */
a528a241 8116vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
9ebefb18 8117{
c2ec175c 8118 struct page *page = vmf->page;
11bac800 8119 struct inode *inode = file_inode(vmf->vma->vm_file);
0b246afa 8120 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc
CM
8121 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8122 struct btrfs_ordered_extent *ordered;
2ac55d41 8123 struct extent_state *cached_state = NULL;
364ecf36 8124 struct extent_changeset *data_reserved = NULL;
e6dcd2dc
CM
8125 char *kaddr;
8126 unsigned long zero_start;
9ebefb18 8127 loff_t size;
a528a241
SJ
8128 vm_fault_t ret;
8129 int ret2;
9998eb70 8130 int reserved = 0;
d0b7da88 8131 u64 reserved_space;
a52d9a80 8132 u64 page_start;
e6dcd2dc 8133 u64 page_end;
d0b7da88
CR
8134 u64 end;
8135
09cbfeaf 8136 reserved_space = PAGE_SIZE;
9ebefb18 8137
b2b5ef5c 8138 sb_start_pagefault(inode->i_sb);
df480633 8139 page_start = page_offset(page);
09cbfeaf 8140 page_end = page_start + PAGE_SIZE - 1;
d0b7da88 8141 end = page_end;
df480633 8142
d0b7da88
CR
8143 /*
8144 * Reserving delalloc space after obtaining the page lock can lead to
8145 * deadlock. For example, if a dirty page is locked by this function
8146 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8147 * dirty page write out, then the btrfs_writepage() function could
8148 * end up waiting indefinitely to get a lock on the page currently
8149 * being processed by btrfs_page_mkwrite() function.
8150 */
a528a241 8151 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
d0b7da88 8152 reserved_space);
a528a241
SJ
8153 if (!ret2) {
8154 ret2 = file_update_time(vmf->vma->vm_file);
9998eb70
CM
8155 reserved = 1;
8156 }
a528a241
SJ
8157 if (ret2) {
8158 ret = vmf_error(ret2);
9998eb70
CM
8159 if (reserved)
8160 goto out;
8161 goto out_noreserve;
56a76f82 8162 }
1832a6d5 8163
56a76f82 8164 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 8165again:
9ebefb18 8166 lock_page(page);
9ebefb18 8167 size = i_size_read(inode);
a52d9a80 8168
9ebefb18 8169 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 8170 (page_start >= size)) {
9ebefb18
CM
8171 /* page got truncated out from underneath us */
8172 goto out_unlock;
8173 }
e6dcd2dc
CM
8174 wait_on_page_writeback(page);
8175
ff13db41 8176 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
e6dcd2dc
CM
8177 set_page_extent_mapped(page);
8178
eb84ae03
CM
8179 /*
8180 * we can't set the delalloc bits if there are pending ordered
8181 * extents. Drop our locks and wait for them to finish
8182 */
a776c6fa
NB
8183 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8184 PAGE_SIZE);
e6dcd2dc 8185 if (ordered) {
2ac55d41 8186 unlock_extent_cached(io_tree, page_start, page_end,
e43bbe5e 8187 &cached_state);
e6dcd2dc 8188 unlock_page(page);
eb84ae03 8189 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
8190 btrfs_put_ordered_extent(ordered);
8191 goto again;
8192 }
8193
09cbfeaf 8194 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
da17066c 8195 reserved_space = round_up(size - page_start,
0b246afa 8196 fs_info->sectorsize);
09cbfeaf 8197 if (reserved_space < PAGE_SIZE) {
d0b7da88 8198 end = page_start + reserved_space - 1;
bc42bda2 8199 btrfs_delalloc_release_space(inode, data_reserved,
43b18595
QW
8200 page_start, PAGE_SIZE - reserved_space,
8201 true);
d0b7da88
CR
8202 }
8203 }
8204
fbf19087 8205 /*
5416034f
LB
8206 * page_mkwrite gets called when the page is firstly dirtied after it's
8207 * faulted in, but write(2) could also dirty a page and set delalloc
8208 * bits, thus in this case for space account reason, we still need to
8209 * clear any delalloc bits within this page range since we have to
8210 * reserve data&meta space before lock_page() (see above comments).
fbf19087 8211 */
d0b7da88 8212 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
e182163d
OS
8213 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8214 EXTENT_DEFRAG, 0, 0, &cached_state);
fbf19087 8215
a528a241 8216 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
330a5827 8217 &cached_state);
a528a241 8218 if (ret2) {
2ac55d41 8219 unlock_extent_cached(io_tree, page_start, page_end,
e43bbe5e 8220 &cached_state);
9ed74f2d
JB
8221 ret = VM_FAULT_SIGBUS;
8222 goto out_unlock;
8223 }
9ebefb18
CM
8224
8225 /* page is wholly or partially inside EOF */
09cbfeaf 8226 if (page_start + PAGE_SIZE > size)
7073017a 8227 zero_start = offset_in_page(size);
9ebefb18 8228 else
09cbfeaf 8229 zero_start = PAGE_SIZE;
9ebefb18 8230
09cbfeaf 8231 if (zero_start != PAGE_SIZE) {
e6dcd2dc 8232 kaddr = kmap(page);
09cbfeaf 8233 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
e6dcd2dc
CM
8234 flush_dcache_page(page);
8235 kunmap(page);
8236 }
247e743c 8237 ClearPageChecked(page);
e6dcd2dc 8238 set_page_dirty(page);
50a9b214 8239 SetPageUptodate(page);
5a3f23d5 8240
0b246afa 8241 BTRFS_I(inode)->last_trans = fs_info->generation;
257c62e1 8242 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
46d8bc34 8243 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
257c62e1 8244
e43bbe5e 8245 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9ebefb18 8246
76de60ed
YY
8247 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8248 sb_end_pagefault(inode->i_sb);
8249 extent_changeset_free(data_reserved);
8250 return VM_FAULT_LOCKED;
717beb96
CM
8251
8252out_unlock:
9ebefb18 8253 unlock_page(page);
1832a6d5 8254out:
8702ba93 8255 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
bc42bda2 8256 btrfs_delalloc_release_space(inode, data_reserved, page_start,
43b18595 8257 reserved_space, (ret != 0));
9998eb70 8258out_noreserve:
b2b5ef5c 8259 sb_end_pagefault(inode->i_sb);
364ecf36 8260 extent_changeset_free(data_reserved);
9ebefb18
CM
8261 return ret;
8262}
8263
213e8c55 8264static int btrfs_truncate(struct inode *inode, bool skip_writeback)
39279cc3 8265{
0b246afa 8266 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 8267 struct btrfs_root *root = BTRFS_I(inode)->root;
fcb80c2a 8268 struct btrfs_block_rsv *rsv;
ad7e1a74 8269 int ret;
39279cc3 8270 struct btrfs_trans_handle *trans;
0b246afa 8271 u64 mask = fs_info->sectorsize - 1;
2bd36e7b 8272 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
39279cc3 8273
213e8c55
FM
8274 if (!skip_writeback) {
8275 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8276 (u64)-1);
8277 if (ret)
8278 return ret;
8279 }
39279cc3 8280
fcb80c2a 8281 /*
f7e9e8fc
OS
8282 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8283 * things going on here:
fcb80c2a 8284 *
f7e9e8fc 8285 * 1) We need to reserve space to update our inode.
fcb80c2a 8286 *
f7e9e8fc 8287 * 2) We need to have something to cache all the space that is going to
fcb80c2a
JB
8288 * be free'd up by the truncate operation, but also have some slack
8289 * space reserved in case it uses space during the truncate (thank you
8290 * very much snapshotting).
8291 *
f7e9e8fc 8292 * And we need these to be separate. The fact is we can use a lot of
fcb80c2a 8293 * space doing the truncate, and we have no earthly idea how much space
01327610 8294 * we will use, so we need the truncate reservation to be separate so it
f7e9e8fc
OS
8295 * doesn't end up using space reserved for updating the inode. We also
8296 * need to be able to stop the transaction and start a new one, which
8297 * means we need to be able to update the inode several times, and we
8298 * have no idea of knowing how many times that will be, so we can't just
8299 * reserve 1 item for the entirety of the operation, so that has to be
8300 * done separately as well.
fcb80c2a
JB
8301 *
8302 * So that leaves us with
8303 *
f7e9e8fc 8304 * 1) rsv - for the truncate reservation, which we will steal from the
fcb80c2a 8305 * transaction reservation.
f7e9e8fc 8306 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
fcb80c2a
JB
8307 * updating the inode.
8308 */
2ff7e61e 8309 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
fcb80c2a
JB
8310 if (!rsv)
8311 return -ENOMEM;
4a338542 8312 rsv->size = min_size;
ca7e70f5 8313 rsv->failfast = 1;
f0cd846e 8314
907cbceb 8315 /*
07127184 8316 * 1 for the truncate slack space
907cbceb
JB
8317 * 1 for updating the inode.
8318 */
f3fe820c 8319 trans = btrfs_start_transaction(root, 2);
fcb80c2a 8320 if (IS_ERR(trans)) {
ad7e1a74 8321 ret = PTR_ERR(trans);
fcb80c2a
JB
8322 goto out;
8323 }
f0cd846e 8324
907cbceb 8325 /* Migrate the slack space for the truncate to our reserve */
0b246afa 8326 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
3a584174 8327 min_size, false);
fcb80c2a 8328 BUG_ON(ret);
f0cd846e 8329
5dc562c5
JB
8330 /*
8331 * So if we truncate and then write and fsync we normally would just
8332 * write the extents that changed, which is a problem if we need to
8333 * first truncate that entire inode. So set this flag so we write out
8334 * all of the extents in the inode to the sync log so we're completely
8335 * safe.
8336 */
8337 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
ca7e70f5 8338 trans->block_rsv = rsv;
907cbceb 8339
8082510e
YZ
8340 while (1) {
8341 ret = btrfs_truncate_inode_items(trans, root, inode,
8342 inode->i_size,
8343 BTRFS_EXTENT_DATA_KEY);
ddfae63c 8344 trans->block_rsv = &fs_info->trans_block_rsv;
ad7e1a74 8345 if (ret != -ENOSPC && ret != -EAGAIN)
8082510e 8346 break;
39279cc3 8347
8082510e 8348 ret = btrfs_update_inode(trans, root, inode);
ad7e1a74 8349 if (ret)
3893e33b 8350 break;
ca7e70f5 8351
3a45bb20 8352 btrfs_end_transaction(trans);
2ff7e61e 8353 btrfs_btree_balance_dirty(fs_info);
ca7e70f5
JB
8354
8355 trans = btrfs_start_transaction(root, 2);
8356 if (IS_ERR(trans)) {
ad7e1a74 8357 ret = PTR_ERR(trans);
ca7e70f5
JB
8358 trans = NULL;
8359 break;
8360 }
8361
63f018be 8362 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
0b246afa 8363 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
3a584174 8364 rsv, min_size, false);
ca7e70f5
JB
8365 BUG_ON(ret); /* shouldn't happen */
8366 trans->block_rsv = rsv;
8082510e
YZ
8367 }
8368
ddfae63c
JB
8369 /*
8370 * We can't call btrfs_truncate_block inside a trans handle as we could
8371 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8372 * we've truncated everything except the last little bit, and can do
8373 * btrfs_truncate_block and then update the disk_i_size.
8374 */
8375 if (ret == NEED_TRUNCATE_BLOCK) {
8376 btrfs_end_transaction(trans);
8377 btrfs_btree_balance_dirty(fs_info);
8378
8379 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8380 if (ret)
8381 goto out;
8382 trans = btrfs_start_transaction(root, 1);
8383 if (IS_ERR(trans)) {
8384 ret = PTR_ERR(trans);
8385 goto out;
8386 }
d923afe9 8387 btrfs_inode_safe_disk_i_size_write(inode, 0);
ddfae63c
JB
8388 }
8389
917c16b2 8390 if (trans) {
ad7e1a74
OS
8391 int ret2;
8392
0b246afa 8393 trans->block_rsv = &fs_info->trans_block_rsv;
ad7e1a74
OS
8394 ret2 = btrfs_update_inode(trans, root, inode);
8395 if (ret2 && !ret)
8396 ret = ret2;
7b128766 8397
ad7e1a74
OS
8398 ret2 = btrfs_end_transaction(trans);
8399 if (ret2 && !ret)
8400 ret = ret2;
2ff7e61e 8401 btrfs_btree_balance_dirty(fs_info);
917c16b2 8402 }
fcb80c2a 8403out:
2ff7e61e 8404 btrfs_free_block_rsv(fs_info, rsv);
fcb80c2a 8405
ad7e1a74 8406 return ret;
39279cc3
CM
8407}
8408
d352ac68
CM
8409/*
8410 * create a new subvolume directory/inode (helper for the ioctl).
8411 */
d2fb3437 8412int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
63541927
FDBM
8413 struct btrfs_root *new_root,
8414 struct btrfs_root *parent_root,
8415 u64 new_dirid)
39279cc3 8416{
39279cc3 8417 struct inode *inode;
76dda93c 8418 int err;
00e4e6b3 8419 u64 index = 0;
39279cc3 8420
12fc9d09
FA
8421 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8422 new_dirid, new_dirid,
8423 S_IFDIR | (~current_umask() & S_IRWXUGO),
8424 &index);
54aa1f4d 8425 if (IS_ERR(inode))
f46b5a66 8426 return PTR_ERR(inode);
39279cc3
CM
8427 inode->i_op = &btrfs_dir_inode_operations;
8428 inode->i_fop = &btrfs_dir_file_operations;
8429
bfe86848 8430 set_nlink(inode, 1);
6ef06d27 8431 btrfs_i_size_write(BTRFS_I(inode), 0);
b0d5d10f 8432 unlock_new_inode(inode);
3b96362c 8433
63541927
FDBM
8434 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8435 if (err)
8436 btrfs_err(new_root->fs_info,
351fd353 8437 "error inheriting subvolume %llu properties: %d",
63541927
FDBM
8438 new_root->root_key.objectid, err);
8439
76dda93c 8440 err = btrfs_update_inode(trans, new_root, inode);
cb8e7090 8441
76dda93c 8442 iput(inode);
ce598979 8443 return err;
39279cc3
CM
8444}
8445
39279cc3
CM
8446struct inode *btrfs_alloc_inode(struct super_block *sb)
8447{
69fe2d75 8448 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
39279cc3 8449 struct btrfs_inode *ei;
2ead6ae7 8450 struct inode *inode;
39279cc3 8451
712e36c5 8452 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
39279cc3
CM
8453 if (!ei)
8454 return NULL;
2ead6ae7
YZ
8455
8456 ei->root = NULL;
2ead6ae7 8457 ei->generation = 0;
15ee9bc7 8458 ei->last_trans = 0;
257c62e1 8459 ei->last_sub_trans = 0;
e02119d5 8460 ei->logged_trans = 0;
2ead6ae7 8461 ei->delalloc_bytes = 0;
a7e3b975 8462 ei->new_delalloc_bytes = 0;
47059d93 8463 ei->defrag_bytes = 0;
2ead6ae7
YZ
8464 ei->disk_i_size = 0;
8465 ei->flags = 0;
7709cde3 8466 ei->csum_bytes = 0;
2ead6ae7 8467 ei->index_cnt = (u64)-1;
67de1176 8468 ei->dir_index = 0;
2ead6ae7 8469 ei->last_unlink_trans = 0;
46d8bc34 8470 ei->last_log_commit = 0;
2ead6ae7 8471
9e0baf60
JB
8472 spin_lock_init(&ei->lock);
8473 ei->outstanding_extents = 0;
69fe2d75
JB
8474 if (sb->s_magic != BTRFS_TEST_MAGIC)
8475 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8476 BTRFS_BLOCK_RSV_DELALLOC);
72ac3c0d 8477 ei->runtime_flags = 0;
b52aa8c9 8478 ei->prop_compress = BTRFS_COMPRESS_NONE;
eec63c65 8479 ei->defrag_compress = BTRFS_COMPRESS_NONE;
2ead6ae7 8480
16cdcec7
MX
8481 ei->delayed_node = NULL;
8482
9cc97d64 8483 ei->i_otime.tv_sec = 0;
8484 ei->i_otime.tv_nsec = 0;
8485
2ead6ae7 8486 inode = &ei->vfs_inode;
a8067e02 8487 extent_map_tree_init(&ei->extent_tree);
43eb5f29
QW
8488 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8489 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8490 IO_TREE_INODE_IO_FAILURE, inode);
41a2ee75
JB
8491 extent_io_tree_init(fs_info, &ei->file_extent_tree,
8492 IO_TREE_INODE_FILE_EXTENT, inode);
7b439738
DS
8493 ei->io_tree.track_uptodate = true;
8494 ei->io_failure_tree.track_uptodate = true;
b812ce28 8495 atomic_set(&ei->sync_writers, 0);
2ead6ae7 8496 mutex_init(&ei->log_mutex);
e6dcd2dc 8497 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
2ead6ae7 8498 INIT_LIST_HEAD(&ei->delalloc_inodes);
8089fe62 8499 INIT_LIST_HEAD(&ei->delayed_iput);
2ead6ae7 8500 RB_CLEAR_NODE(&ei->rb_node);
5f9a8a51 8501 init_rwsem(&ei->dio_sem);
2ead6ae7
YZ
8502
8503 return inode;
39279cc3
CM
8504}
8505
aaedb55b
JB
8506#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8507void btrfs_test_destroy_inode(struct inode *inode)
8508{
dcdbc059 8509 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
aaedb55b
JB
8510 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8511}
8512#endif
8513
26602cab 8514void btrfs_free_inode(struct inode *inode)
fa0d7e3d 8515{
fa0d7e3d
NP
8516 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8517}
8518
39279cc3
CM
8519void btrfs_destroy_inode(struct inode *inode)
8520{
0b246afa 8521 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc 8522 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
8523 struct btrfs_root *root = BTRFS_I(inode)->root;
8524
b3d9b7a3 8525 WARN_ON(!hlist_empty(&inode->i_dentry));
39279cc3 8526 WARN_ON(inode->i_data.nrpages);
69fe2d75
JB
8527 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8528 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9e0baf60 8529 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7709cde3 8530 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
a7e3b975 8531 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
7709cde3 8532 WARN_ON(BTRFS_I(inode)->csum_bytes);
47059d93 8533 WARN_ON(BTRFS_I(inode)->defrag_bytes);
39279cc3 8534
a6dbd429
JB
8535 /*
8536 * This can happen where we create an inode, but somebody else also
8537 * created the same inode and we need to destroy the one we already
8538 * created.
8539 */
8540 if (!root)
26602cab 8541 return;
a6dbd429 8542
d397712b 8543 while (1) {
e6dcd2dc
CM
8544 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8545 if (!ordered)
8546 break;
8547 else {
0b246afa 8548 btrfs_err(fs_info,
5d163e0e 8549 "found ordered extent %llu %llu on inode cleanup",
bffe633e 8550 ordered->file_offset, ordered->num_bytes);
e6dcd2dc
CM
8551 btrfs_remove_ordered_extent(inode, ordered);
8552 btrfs_put_ordered_extent(ordered);
8553 btrfs_put_ordered_extent(ordered);
8554 }
8555 }
56fa9d07 8556 btrfs_qgroup_check_reserved_leak(inode);
5d4f98a2 8557 inode_tree_del(inode);
dcdbc059 8558 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
41a2ee75 8559 btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
5c8fd99f 8560 btrfs_put_root(BTRFS_I(inode)->root);
39279cc3
CM
8561}
8562
45321ac5 8563int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
8564{
8565 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 8566
6379ef9f
NA
8567 if (root == NULL)
8568 return 1;
8569
fa6ac876 8570 /* the snap/subvol tree is on deleting */
69e9c6c6 8571 if (btrfs_root_refs(&root->root_item) == 0)
45321ac5 8572 return 1;
76dda93c 8573 else
45321ac5 8574 return generic_drop_inode(inode);
76dda93c
YZ
8575}
8576
0ee0fda0 8577static void init_once(void *foo)
39279cc3
CM
8578{
8579 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8580
8581 inode_init_once(&ei->vfs_inode);
8582}
8583
e67c718b 8584void __cold btrfs_destroy_cachep(void)
39279cc3 8585{
8c0a8537
KS
8586 /*
8587 * Make sure all delayed rcu free inodes are flushed before we
8588 * destroy cache.
8589 */
8590 rcu_barrier();
5598e900
KM
8591 kmem_cache_destroy(btrfs_inode_cachep);
8592 kmem_cache_destroy(btrfs_trans_handle_cachep);
5598e900
KM
8593 kmem_cache_destroy(btrfs_path_cachep);
8594 kmem_cache_destroy(btrfs_free_space_cachep);
3acd4850 8595 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
39279cc3
CM
8596}
8597
f5c29bd9 8598int __init btrfs_init_cachep(void)
39279cc3 8599{
837e1972 8600 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9601e3f6 8601 sizeof(struct btrfs_inode), 0,
5d097056
VD
8602 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8603 init_once);
39279cc3
CM
8604 if (!btrfs_inode_cachep)
8605 goto fail;
9601e3f6 8606
837e1972 8607 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9601e3f6 8608 sizeof(struct btrfs_trans_handle), 0,
fba4b697 8609 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
8610 if (!btrfs_trans_handle_cachep)
8611 goto fail;
9601e3f6 8612
837e1972 8613 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9601e3f6 8614 sizeof(struct btrfs_path), 0,
fba4b697 8615 SLAB_MEM_SPREAD, NULL);
39279cc3
CM
8616 if (!btrfs_path_cachep)
8617 goto fail;
9601e3f6 8618
837e1972 8619 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
dc89e982 8620 sizeof(struct btrfs_free_space), 0,
fba4b697 8621 SLAB_MEM_SPREAD, NULL);
dc89e982
JB
8622 if (!btrfs_free_space_cachep)
8623 goto fail;
8624
3acd4850
CL
8625 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8626 PAGE_SIZE, PAGE_SIZE,
8627 SLAB_RED_ZONE, NULL);
8628 if (!btrfs_free_space_bitmap_cachep)
8629 goto fail;
8630
39279cc3
CM
8631 return 0;
8632fail:
8633 btrfs_destroy_cachep();
8634 return -ENOMEM;
8635}
8636
a528d35e
DH
8637static int btrfs_getattr(const struct path *path, struct kstat *stat,
8638 u32 request_mask, unsigned int flags)
39279cc3 8639{
df0af1a5 8640 u64 delalloc_bytes;
a528d35e 8641 struct inode *inode = d_inode(path->dentry);
fadc0d8b 8642 u32 blocksize = inode->i_sb->s_blocksize;
04a87e34
YS
8643 u32 bi_flags = BTRFS_I(inode)->flags;
8644
8645 stat->result_mask |= STATX_BTIME;
8646 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8647 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8648 if (bi_flags & BTRFS_INODE_APPEND)
8649 stat->attributes |= STATX_ATTR_APPEND;
8650 if (bi_flags & BTRFS_INODE_COMPRESS)
8651 stat->attributes |= STATX_ATTR_COMPRESSED;
8652 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8653 stat->attributes |= STATX_ATTR_IMMUTABLE;
8654 if (bi_flags & BTRFS_INODE_NODUMP)
8655 stat->attributes |= STATX_ATTR_NODUMP;
8656
8657 stat->attributes_mask |= (STATX_ATTR_APPEND |
8658 STATX_ATTR_COMPRESSED |
8659 STATX_ATTR_IMMUTABLE |
8660 STATX_ATTR_NODUMP);
fadc0d8b 8661
39279cc3 8662 generic_fillattr(inode, stat);
0ee5dc67 8663 stat->dev = BTRFS_I(inode)->root->anon_dev;
df0af1a5
MX
8664
8665 spin_lock(&BTRFS_I(inode)->lock);
a7e3b975 8666 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
df0af1a5 8667 spin_unlock(&BTRFS_I(inode)->lock);
fadc0d8b 8668 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
df0af1a5 8669 ALIGN(delalloc_bytes, blocksize)) >> 9;
39279cc3
CM
8670 return 0;
8671}
8672
cdd1fedf
DF
8673static int btrfs_rename_exchange(struct inode *old_dir,
8674 struct dentry *old_dentry,
8675 struct inode *new_dir,
8676 struct dentry *new_dentry)
8677{
0b246afa 8678 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
cdd1fedf
DF
8679 struct btrfs_trans_handle *trans;
8680 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8681 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8682 struct inode *new_inode = new_dentry->d_inode;
8683 struct inode *old_inode = old_dentry->d_inode;
95582b00 8684 struct timespec64 ctime = current_time(old_inode);
cdd1fedf 8685 struct dentry *parent;
4a0cc7ca
NB
8686 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8687 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
cdd1fedf
DF
8688 u64 old_idx = 0;
8689 u64 new_idx = 0;
cdd1fedf 8690 int ret;
86e8aa0e
FM
8691 bool root_log_pinned = false;
8692 bool dest_log_pinned = false;
d4682ba0
FM
8693 struct btrfs_log_ctx ctx_root;
8694 struct btrfs_log_ctx ctx_dest;
8695 bool sync_log_root = false;
8696 bool sync_log_dest = false;
8697 bool commit_transaction = false;
cdd1fedf
DF
8698
8699 /* we only allow rename subvolume link between subvolumes */
8700 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8701 return -EXDEV;
8702
d4682ba0
FM
8703 btrfs_init_log_ctx(&ctx_root, old_inode);
8704 btrfs_init_log_ctx(&ctx_dest, new_inode);
8705
cdd1fedf 8706 /* close the race window with snapshot create/destroy ioctl */
943eb3bf
JB
8707 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8708 new_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 8709 down_read(&fs_info->subvol_sem);
cdd1fedf
DF
8710
8711 /*
8712 * We want to reserve the absolute worst case amount of items. So if
8713 * both inodes are subvols and we need to unlink them then that would
8714 * require 4 item modifications, but if they are both normal inodes it
8715 * would require 5 item modifications, so we'll assume their normal
8716 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8717 * should cover the worst case number of items we'll modify.
8718 */
8719 trans = btrfs_start_transaction(root, 12);
8720 if (IS_ERR(trans)) {
8721 ret = PTR_ERR(trans);
8722 goto out_notrans;
8723 }
8724
3e174099
JB
8725 if (dest != root)
8726 btrfs_record_root_in_trans(trans, dest);
8727
cdd1fedf
DF
8728 /*
8729 * We need to find a free sequence number both in the source and
8730 * in the destination directory for the exchange.
8731 */
877574e2 8732 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
cdd1fedf
DF
8733 if (ret)
8734 goto out_fail;
877574e2 8735 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
cdd1fedf
DF
8736 if (ret)
8737 goto out_fail;
8738
8739 BTRFS_I(old_inode)->dir_index = 0ULL;
8740 BTRFS_I(new_inode)->dir_index = 0ULL;
8741
8742 /* Reference for the source. */
8743 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8744 /* force full log commit if subvolume involved. */
90787766 8745 btrfs_set_log_full_commit(trans);
cdd1fedf 8746 } else {
376e5a57
FM
8747 btrfs_pin_log_trans(root);
8748 root_log_pinned = true;
cdd1fedf
DF
8749 ret = btrfs_insert_inode_ref(trans, dest,
8750 new_dentry->d_name.name,
8751 new_dentry->d_name.len,
8752 old_ino,
f85b7379
DS
8753 btrfs_ino(BTRFS_I(new_dir)),
8754 old_idx);
cdd1fedf
DF
8755 if (ret)
8756 goto out_fail;
cdd1fedf
DF
8757 }
8758
8759 /* And now for the dest. */
8760 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8761 /* force full log commit if subvolume involved. */
90787766 8762 btrfs_set_log_full_commit(trans);
cdd1fedf 8763 } else {
376e5a57
FM
8764 btrfs_pin_log_trans(dest);
8765 dest_log_pinned = true;
cdd1fedf
DF
8766 ret = btrfs_insert_inode_ref(trans, root,
8767 old_dentry->d_name.name,
8768 old_dentry->d_name.len,
8769 new_ino,
f85b7379
DS
8770 btrfs_ino(BTRFS_I(old_dir)),
8771 new_idx);
cdd1fedf
DF
8772 if (ret)
8773 goto out_fail;
cdd1fedf
DF
8774 }
8775
8776 /* Update inode version and ctime/mtime. */
8777 inode_inc_iversion(old_dir);
8778 inode_inc_iversion(new_dir);
8779 inode_inc_iversion(old_inode);
8780 inode_inc_iversion(new_inode);
8781 old_dir->i_ctime = old_dir->i_mtime = ctime;
8782 new_dir->i_ctime = new_dir->i_mtime = ctime;
8783 old_inode->i_ctime = ctime;
8784 new_inode->i_ctime = ctime;
8785
8786 if (old_dentry->d_parent != new_dentry->d_parent) {
f85b7379
DS
8787 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8788 BTRFS_I(old_inode), 1);
8789 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8790 BTRFS_I(new_inode), 1);
cdd1fedf
DF
8791 }
8792
8793 /* src is a subvolume */
8794 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
045d3967 8795 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
cdd1fedf 8796 } else { /* src is an inode */
4ec5934e
NB
8797 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8798 BTRFS_I(old_dentry->d_inode),
cdd1fedf
DF
8799 old_dentry->d_name.name,
8800 old_dentry->d_name.len);
8801 if (!ret)
8802 ret = btrfs_update_inode(trans, root, old_inode);
8803 }
8804 if (ret) {
66642832 8805 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
8806 goto out_fail;
8807 }
8808
8809 /* dest is a subvolume */
8810 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
045d3967 8811 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
cdd1fedf 8812 } else { /* dest is an inode */
4ec5934e
NB
8813 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8814 BTRFS_I(new_dentry->d_inode),
cdd1fedf
DF
8815 new_dentry->d_name.name,
8816 new_dentry->d_name.len);
8817 if (!ret)
8818 ret = btrfs_update_inode(trans, dest, new_inode);
8819 }
8820 if (ret) {
66642832 8821 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
8822 goto out_fail;
8823 }
8824
db0a669f 8825 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
cdd1fedf
DF
8826 new_dentry->d_name.name,
8827 new_dentry->d_name.len, 0, old_idx);
8828 if (ret) {
66642832 8829 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
8830 goto out_fail;
8831 }
8832
db0a669f 8833 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
cdd1fedf
DF
8834 old_dentry->d_name.name,
8835 old_dentry->d_name.len, 0, new_idx);
8836 if (ret) {
66642832 8837 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
8838 goto out_fail;
8839 }
8840
8841 if (old_inode->i_nlink == 1)
8842 BTRFS_I(old_inode)->dir_index = old_idx;
8843 if (new_inode->i_nlink == 1)
8844 BTRFS_I(new_inode)->dir_index = new_idx;
8845
86e8aa0e 8846 if (root_log_pinned) {
cdd1fedf 8847 parent = new_dentry->d_parent;
d4682ba0
FM
8848 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8849 BTRFS_I(old_dir), parent,
8850 false, &ctx_root);
8851 if (ret == BTRFS_NEED_LOG_SYNC)
8852 sync_log_root = true;
8853 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8854 commit_transaction = true;
8855 ret = 0;
cdd1fedf 8856 btrfs_end_log_trans(root);
86e8aa0e 8857 root_log_pinned = false;
cdd1fedf 8858 }
86e8aa0e 8859 if (dest_log_pinned) {
d4682ba0
FM
8860 if (!commit_transaction) {
8861 parent = old_dentry->d_parent;
8862 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8863 BTRFS_I(new_dir), parent,
8864 false, &ctx_dest);
8865 if (ret == BTRFS_NEED_LOG_SYNC)
8866 sync_log_dest = true;
8867 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8868 commit_transaction = true;
8869 ret = 0;
8870 }
cdd1fedf 8871 btrfs_end_log_trans(dest);
86e8aa0e 8872 dest_log_pinned = false;
cdd1fedf
DF
8873 }
8874out_fail:
86e8aa0e
FM
8875 /*
8876 * If we have pinned a log and an error happened, we unpin tasks
8877 * trying to sync the log and force them to fallback to a transaction
8878 * commit if the log currently contains any of the inodes involved in
8879 * this rename operation (to ensure we do not persist a log with an
8880 * inconsistent state for any of these inodes or leading to any
8881 * inconsistencies when replayed). If the transaction was aborted, the
8882 * abortion reason is propagated to userspace when attempting to commit
8883 * the transaction. If the log does not contain any of these inodes, we
8884 * allow the tasks to sync it.
8885 */
8886 if (ret && (root_log_pinned || dest_log_pinned)) {
0f8939b8
NB
8887 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8888 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8889 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
86e8aa0e 8890 (new_inode &&
0f8939b8 8891 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
90787766 8892 btrfs_set_log_full_commit(trans);
86e8aa0e
FM
8893
8894 if (root_log_pinned) {
8895 btrfs_end_log_trans(root);
8896 root_log_pinned = false;
8897 }
8898 if (dest_log_pinned) {
8899 btrfs_end_log_trans(dest);
8900 dest_log_pinned = false;
8901 }
8902 }
d4682ba0
FM
8903 if (!ret && sync_log_root && !commit_transaction) {
8904 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8905 &ctx_root);
8906 if (ret)
8907 commit_transaction = true;
8908 }
8909 if (!ret && sync_log_dest && !commit_transaction) {
8910 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8911 &ctx_dest);
8912 if (ret)
8913 commit_transaction = true;
8914 }
8915 if (commit_transaction) {
e6c61710
FM
8916 /*
8917 * We may have set commit_transaction when logging the new name
8918 * in the destination root, in which case we left the source
8919 * root context in the list of log contextes. So make sure we
8920 * remove it to avoid invalid memory accesses, since the context
8921 * was allocated in our stack frame.
8922 */
8923 if (sync_log_root) {
8924 mutex_lock(&root->log_mutex);
8925 list_del_init(&ctx_root.list);
8926 mutex_unlock(&root->log_mutex);
8927 }
d4682ba0
FM
8928 ret = btrfs_commit_transaction(trans);
8929 } else {
8930 int ret2;
8931
8932 ret2 = btrfs_end_transaction(trans);
8933 ret = ret ? ret : ret2;
8934 }
cdd1fedf 8935out_notrans:
943eb3bf
JB
8936 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8937 old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 8938 up_read(&fs_info->subvol_sem);
cdd1fedf 8939
e6c61710
FM
8940 ASSERT(list_empty(&ctx_root.list));
8941 ASSERT(list_empty(&ctx_dest.list));
8942
cdd1fedf
DF
8943 return ret;
8944}
8945
8946static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8947 struct btrfs_root *root,
8948 struct inode *dir,
8949 struct dentry *dentry)
8950{
8951 int ret;
8952 struct inode *inode;
8953 u64 objectid;
8954 u64 index;
8955
8956 ret = btrfs_find_free_ino(root, &objectid);
8957 if (ret)
8958 return ret;
8959
8960 inode = btrfs_new_inode(trans, root, dir,
8961 dentry->d_name.name,
8962 dentry->d_name.len,
4a0cc7ca 8963 btrfs_ino(BTRFS_I(dir)),
cdd1fedf
DF
8964 objectid,
8965 S_IFCHR | WHITEOUT_MODE,
8966 &index);
8967
8968 if (IS_ERR(inode)) {
8969 ret = PTR_ERR(inode);
8970 return ret;
8971 }
8972
8973 inode->i_op = &btrfs_special_inode_operations;
8974 init_special_inode(inode, inode->i_mode,
8975 WHITEOUT_DEV);
8976
8977 ret = btrfs_init_inode_security(trans, inode, dir,
8978 &dentry->d_name);
8979 if (ret)
c9901618 8980 goto out;
cdd1fedf 8981
cef415af
NB
8982 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
8983 BTRFS_I(inode), 0, index);
cdd1fedf 8984 if (ret)
c9901618 8985 goto out;
cdd1fedf
DF
8986
8987 ret = btrfs_update_inode(trans, root, inode);
c9901618 8988out:
cdd1fedf 8989 unlock_new_inode(inode);
c9901618
FM
8990 if (ret)
8991 inode_dec_link_count(inode);
cdd1fedf
DF
8992 iput(inode);
8993
c9901618 8994 return ret;
cdd1fedf
DF
8995}
8996
d397712b 8997static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
cdd1fedf
DF
8998 struct inode *new_dir, struct dentry *new_dentry,
8999 unsigned int flags)
39279cc3 9000{
0b246afa 9001 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
39279cc3 9002 struct btrfs_trans_handle *trans;
5062af35 9003 unsigned int trans_num_items;
39279cc3 9004 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 9005 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
2b0143b5
DH
9006 struct inode *new_inode = d_inode(new_dentry);
9007 struct inode *old_inode = d_inode(old_dentry);
00e4e6b3 9008 u64 index = 0;
39279cc3 9009 int ret;
4a0cc7ca 9010 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
3dc9e8f7 9011 bool log_pinned = false;
d4682ba0
FM
9012 struct btrfs_log_ctx ctx;
9013 bool sync_log = false;
9014 bool commit_transaction = false;
39279cc3 9015
4a0cc7ca 9016 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
f679a840
YZ
9017 return -EPERM;
9018
4df27c4d 9019 /* we only allow rename subvolume link between subvolumes */
33345d01 9020 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
9021 return -EXDEV;
9022
33345d01 9023 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
4a0cc7ca 9024 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 9025 return -ENOTEMPTY;
5f39d397 9026
4df27c4d
YZ
9027 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9028 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9029 return -ENOTEMPTY;
9c52057c
CM
9030
9031
9032 /* check for collisions, even if the name isn't there */
4871c158 9033 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9c52057c
CM
9034 new_dentry->d_name.name,
9035 new_dentry->d_name.len);
9036
9037 if (ret) {
9038 if (ret == -EEXIST) {
9039 /* we shouldn't get
9040 * eexist without a new_inode */
fae7f21c 9041 if (WARN_ON(!new_inode)) {
9c52057c
CM
9042 return ret;
9043 }
9044 } else {
9045 /* maybe -EOVERFLOW */
9046 return ret;
9047 }
9048 }
9049 ret = 0;
9050
5a3f23d5 9051 /*
8d875f95
CM
9052 * we're using rename to replace one file with another. Start IO on it
9053 * now so we don't add too much work to the end of the transaction
5a3f23d5 9054 */
8d875f95 9055 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
5a3f23d5
CM
9056 filemap_flush(old_inode->i_mapping);
9057
76dda93c 9058 /* close the racy window with snapshot create/destroy ioctl */
33345d01 9059 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9060 down_read(&fs_info->subvol_sem);
a22285a6
YZ
9061 /*
9062 * We want to reserve the absolute worst case amount of items. So if
9063 * both inodes are subvols and we need to unlink them then that would
9064 * require 4 item modifications, but if they are both normal inodes it
cdd1fedf 9065 * would require 5 item modifications, so we'll assume they are normal
a22285a6
YZ
9066 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9067 * should cover the worst case number of items we'll modify.
5062af35
FM
9068 * If our rename has the whiteout flag, we need more 5 units for the
9069 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9070 * when selinux is enabled).
a22285a6 9071 */
5062af35
FM
9072 trans_num_items = 11;
9073 if (flags & RENAME_WHITEOUT)
9074 trans_num_items += 5;
9075 trans = btrfs_start_transaction(root, trans_num_items);
b44c59a8 9076 if (IS_ERR(trans)) {
cdd1fedf
DF
9077 ret = PTR_ERR(trans);
9078 goto out_notrans;
9079 }
76dda93c 9080
4df27c4d
YZ
9081 if (dest != root)
9082 btrfs_record_root_in_trans(trans, dest);
5f39d397 9083
877574e2 9084 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
a5719521
YZ
9085 if (ret)
9086 goto out_fail;
5a3f23d5 9087
67de1176 9088 BTRFS_I(old_inode)->dir_index = 0ULL;
33345d01 9089 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d 9090 /* force full log commit if subvolume involved. */
90787766 9091 btrfs_set_log_full_commit(trans);
4df27c4d 9092 } else {
c4aba954
FM
9093 btrfs_pin_log_trans(root);
9094 log_pinned = true;
a5719521
YZ
9095 ret = btrfs_insert_inode_ref(trans, dest,
9096 new_dentry->d_name.name,
9097 new_dentry->d_name.len,
33345d01 9098 old_ino,
4a0cc7ca 9099 btrfs_ino(BTRFS_I(new_dir)), index);
a5719521
YZ
9100 if (ret)
9101 goto out_fail;
4df27c4d 9102 }
5a3f23d5 9103
0c4d2d95
JB
9104 inode_inc_iversion(old_dir);
9105 inode_inc_iversion(new_dir);
9106 inode_inc_iversion(old_inode);
04b285f3
DD
9107 old_dir->i_ctime = old_dir->i_mtime =
9108 new_dir->i_ctime = new_dir->i_mtime =
c2050a45 9109 old_inode->i_ctime = current_time(old_dir);
5f39d397 9110
12fcfd22 9111 if (old_dentry->d_parent != new_dentry->d_parent)
f85b7379
DS
9112 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9113 BTRFS_I(old_inode), 1);
12fcfd22 9114
33345d01 9115 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
045d3967 9116 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
4df27c4d 9117 } else {
4ec5934e
NB
9118 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9119 BTRFS_I(d_inode(old_dentry)),
92986796
AV
9120 old_dentry->d_name.name,
9121 old_dentry->d_name.len);
9122 if (!ret)
9123 ret = btrfs_update_inode(trans, root, old_inode);
4df27c4d 9124 }
79787eaa 9125 if (ret) {
66642832 9126 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9127 goto out_fail;
9128 }
39279cc3
CM
9129
9130 if (new_inode) {
0c4d2d95 9131 inode_inc_iversion(new_inode);
c2050a45 9132 new_inode->i_ctime = current_time(new_inode);
4a0cc7ca 9133 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
4df27c4d 9134 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
045d3967 9135 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
4df27c4d
YZ
9136 BUG_ON(new_inode->i_nlink == 0);
9137 } else {
4ec5934e
NB
9138 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9139 BTRFS_I(d_inode(new_dentry)),
4df27c4d
YZ
9140 new_dentry->d_name.name,
9141 new_dentry->d_name.len);
9142 }
4ef31a45 9143 if (!ret && new_inode->i_nlink == 0)
73f2e545
NB
9144 ret = btrfs_orphan_add(trans,
9145 BTRFS_I(d_inode(new_dentry)));
79787eaa 9146 if (ret) {
66642832 9147 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9148 goto out_fail;
9149 }
39279cc3 9150 }
aec7477b 9151
db0a669f 9152 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
4df27c4d 9153 new_dentry->d_name.name,
a5719521 9154 new_dentry->d_name.len, 0, index);
79787eaa 9155 if (ret) {
66642832 9156 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9157 goto out_fail;
9158 }
39279cc3 9159
67de1176
MX
9160 if (old_inode->i_nlink == 1)
9161 BTRFS_I(old_inode)->dir_index = index;
9162
3dc9e8f7 9163 if (log_pinned) {
10d9f309 9164 struct dentry *parent = new_dentry->d_parent;
3dc9e8f7 9165
d4682ba0
FM
9166 btrfs_init_log_ctx(&ctx, old_inode);
9167 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9168 BTRFS_I(old_dir), parent,
9169 false, &ctx);
9170 if (ret == BTRFS_NEED_LOG_SYNC)
9171 sync_log = true;
9172 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9173 commit_transaction = true;
9174 ret = 0;
4df27c4d 9175 btrfs_end_log_trans(root);
3dc9e8f7 9176 log_pinned = false;
4df27c4d 9177 }
cdd1fedf
DF
9178
9179 if (flags & RENAME_WHITEOUT) {
9180 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9181 old_dentry);
9182
9183 if (ret) {
66642832 9184 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9185 goto out_fail;
9186 }
4df27c4d 9187 }
39279cc3 9188out_fail:
3dc9e8f7
FM
9189 /*
9190 * If we have pinned the log and an error happened, we unpin tasks
9191 * trying to sync the log and force them to fallback to a transaction
9192 * commit if the log currently contains any of the inodes involved in
9193 * this rename operation (to ensure we do not persist a log with an
9194 * inconsistent state for any of these inodes or leading to any
9195 * inconsistencies when replayed). If the transaction was aborted, the
9196 * abortion reason is propagated to userspace when attempting to commit
9197 * the transaction. If the log does not contain any of these inodes, we
9198 * allow the tasks to sync it.
9199 */
9200 if (ret && log_pinned) {
0f8939b8
NB
9201 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9202 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9203 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
3dc9e8f7 9204 (new_inode &&
0f8939b8 9205 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
90787766 9206 btrfs_set_log_full_commit(trans);
3dc9e8f7
FM
9207
9208 btrfs_end_log_trans(root);
9209 log_pinned = false;
9210 }
d4682ba0
FM
9211 if (!ret && sync_log) {
9212 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9213 if (ret)
9214 commit_transaction = true;
236ebc20
FM
9215 } else if (sync_log) {
9216 mutex_lock(&root->log_mutex);
9217 list_del(&ctx.list);
9218 mutex_unlock(&root->log_mutex);
d4682ba0
FM
9219 }
9220 if (commit_transaction) {
9221 ret = btrfs_commit_transaction(trans);
9222 } else {
9223 int ret2;
9224
9225 ret2 = btrfs_end_transaction(trans);
9226 ret = ret ? ret : ret2;
9227 }
b44c59a8 9228out_notrans:
33345d01 9229 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9230 up_read(&fs_info->subvol_sem);
9ed74f2d 9231
39279cc3
CM
9232 return ret;
9233}
9234
80ace85c
MS
9235static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9236 struct inode *new_dir, struct dentry *new_dentry,
9237 unsigned int flags)
9238{
cdd1fedf 9239 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
80ace85c
MS
9240 return -EINVAL;
9241
cdd1fedf
DF
9242 if (flags & RENAME_EXCHANGE)
9243 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9244 new_dentry);
9245
9246 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
80ace85c
MS
9247}
9248
3a2f8c07
NB
9249struct btrfs_delalloc_work {
9250 struct inode *inode;
9251 struct completion completion;
9252 struct list_head list;
9253 struct btrfs_work work;
9254};
9255
8ccf6f19
MX
9256static void btrfs_run_delalloc_work(struct btrfs_work *work)
9257{
9258 struct btrfs_delalloc_work *delalloc_work;
9f23e289 9259 struct inode *inode;
8ccf6f19
MX
9260
9261 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9262 work);
9f23e289 9263 inode = delalloc_work->inode;
30424601
DS
9264 filemap_flush(inode->i_mapping);
9265 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9266 &BTRFS_I(inode)->runtime_flags))
9f23e289 9267 filemap_flush(inode->i_mapping);
8ccf6f19 9268
076da91c 9269 iput(inode);
8ccf6f19
MX
9270 complete(&delalloc_work->completion);
9271}
9272
3a2f8c07 9273static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8ccf6f19
MX
9274{
9275 struct btrfs_delalloc_work *work;
9276
100d5702 9277 work = kmalloc(sizeof(*work), GFP_NOFS);
8ccf6f19
MX
9278 if (!work)
9279 return NULL;
9280
9281 init_completion(&work->completion);
9282 INIT_LIST_HEAD(&work->list);
9283 work->inode = inode;
a0cac0ec 9284 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
8ccf6f19
MX
9285
9286 return work;
9287}
9288
d352ac68
CM
9289/*
9290 * some fairly slow code that needs optimization. This walks the list
9291 * of all the inodes with pending delalloc and forces them to disk.
9292 */
3cd24c69 9293static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
ea8c2819 9294{
ea8c2819 9295 struct btrfs_inode *binode;
5b21f2ed 9296 struct inode *inode;
8ccf6f19
MX
9297 struct btrfs_delalloc_work *work, *next;
9298 struct list_head works;
1eafa6c7 9299 struct list_head splice;
8ccf6f19 9300 int ret = 0;
ea8c2819 9301
8ccf6f19 9302 INIT_LIST_HEAD(&works);
1eafa6c7 9303 INIT_LIST_HEAD(&splice);
63607cc8 9304
573bfb72 9305 mutex_lock(&root->delalloc_mutex);
eb73c1b7
MX
9306 spin_lock(&root->delalloc_lock);
9307 list_splice_init(&root->delalloc_inodes, &splice);
1eafa6c7
MX
9308 while (!list_empty(&splice)) {
9309 binode = list_entry(splice.next, struct btrfs_inode,
ea8c2819 9310 delalloc_inodes);
1eafa6c7 9311
eb73c1b7
MX
9312 list_move_tail(&binode->delalloc_inodes,
9313 &root->delalloc_inodes);
5b21f2ed 9314 inode = igrab(&binode->vfs_inode);
df0af1a5 9315 if (!inode) {
eb73c1b7 9316 cond_resched_lock(&root->delalloc_lock);
1eafa6c7 9317 continue;
df0af1a5 9318 }
eb73c1b7 9319 spin_unlock(&root->delalloc_lock);
1eafa6c7 9320
3cd24c69
EL
9321 if (snapshot)
9322 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9323 &binode->runtime_flags);
076da91c 9324 work = btrfs_alloc_delalloc_work(inode);
5d99a998 9325 if (!work) {
4fbb5147 9326 iput(inode);
1eafa6c7 9327 ret = -ENOMEM;
a1ecaabb 9328 goto out;
5b21f2ed 9329 }
1eafa6c7 9330 list_add_tail(&work->list, &works);
a44903ab
QW
9331 btrfs_queue_work(root->fs_info->flush_workers,
9332 &work->work);
6c255e67
MX
9333 ret++;
9334 if (nr != -1 && ret >= nr)
a1ecaabb 9335 goto out;
5b21f2ed 9336 cond_resched();
eb73c1b7 9337 spin_lock(&root->delalloc_lock);
ea8c2819 9338 }
eb73c1b7 9339 spin_unlock(&root->delalloc_lock);
8c8bee1d 9340
a1ecaabb 9341out:
eb73c1b7
MX
9342 list_for_each_entry_safe(work, next, &works, list) {
9343 list_del_init(&work->list);
40012f96
NB
9344 wait_for_completion(&work->completion);
9345 kfree(work);
eb73c1b7
MX
9346 }
9347
81f1d390 9348 if (!list_empty(&splice)) {
eb73c1b7
MX
9349 spin_lock(&root->delalloc_lock);
9350 list_splice_tail(&splice, &root->delalloc_inodes);
9351 spin_unlock(&root->delalloc_lock);
9352 }
573bfb72 9353 mutex_unlock(&root->delalloc_mutex);
eb73c1b7
MX
9354 return ret;
9355}
1eafa6c7 9356
3cd24c69 9357int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
eb73c1b7 9358{
0b246afa 9359 struct btrfs_fs_info *fs_info = root->fs_info;
eb73c1b7 9360 int ret;
1eafa6c7 9361
0b246afa 9362 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
9363 return -EROFS;
9364
3cd24c69 9365 ret = start_delalloc_inodes(root, -1, true);
6c255e67
MX
9366 if (ret > 0)
9367 ret = 0;
eb73c1b7
MX
9368 return ret;
9369}
9370
82b3e53b 9371int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
eb73c1b7
MX
9372{
9373 struct btrfs_root *root;
9374 struct list_head splice;
9375 int ret;
9376
2c21b4d7 9377 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
9378 return -EROFS;
9379
9380 INIT_LIST_HEAD(&splice);
9381
573bfb72 9382 mutex_lock(&fs_info->delalloc_root_mutex);
eb73c1b7
MX
9383 spin_lock(&fs_info->delalloc_root_lock);
9384 list_splice_init(&fs_info->delalloc_roots, &splice);
6c255e67 9385 while (!list_empty(&splice) && nr) {
eb73c1b7
MX
9386 root = list_first_entry(&splice, struct btrfs_root,
9387 delalloc_root);
00246528 9388 root = btrfs_grab_root(root);
eb73c1b7
MX
9389 BUG_ON(!root);
9390 list_move_tail(&root->delalloc_root,
9391 &fs_info->delalloc_roots);
9392 spin_unlock(&fs_info->delalloc_root_lock);
9393
3cd24c69 9394 ret = start_delalloc_inodes(root, nr, false);
00246528 9395 btrfs_put_root(root);
6c255e67 9396 if (ret < 0)
eb73c1b7
MX
9397 goto out;
9398
6c255e67
MX
9399 if (nr != -1) {
9400 nr -= ret;
9401 WARN_ON(nr < 0);
9402 }
eb73c1b7 9403 spin_lock(&fs_info->delalloc_root_lock);
8ccf6f19 9404 }
eb73c1b7 9405 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 9406
6c255e67 9407 ret = 0;
eb73c1b7 9408out:
81f1d390 9409 if (!list_empty(&splice)) {
eb73c1b7
MX
9410 spin_lock(&fs_info->delalloc_root_lock);
9411 list_splice_tail(&splice, &fs_info->delalloc_roots);
9412 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 9413 }
573bfb72 9414 mutex_unlock(&fs_info->delalloc_root_mutex);
8ccf6f19 9415 return ret;
ea8c2819
CM
9416}
9417
39279cc3
CM
9418static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9419 const char *symname)
9420{
0b246afa 9421 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
9422 struct btrfs_trans_handle *trans;
9423 struct btrfs_root *root = BTRFS_I(dir)->root;
9424 struct btrfs_path *path;
9425 struct btrfs_key key;
1832a6d5 9426 struct inode *inode = NULL;
39279cc3 9427 int err;
39279cc3 9428 u64 objectid;
67871254 9429 u64 index = 0;
39279cc3
CM
9430 int name_len;
9431 int datasize;
5f39d397 9432 unsigned long ptr;
39279cc3 9433 struct btrfs_file_extent_item *ei;
5f39d397 9434 struct extent_buffer *leaf;
39279cc3 9435
f06becc4 9436 name_len = strlen(symname);
0b246afa 9437 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
39279cc3 9438 return -ENAMETOOLONG;
1832a6d5 9439
9ed74f2d
JB
9440 /*
9441 * 2 items for inode item and ref
9442 * 2 items for dir items
9269d12b
FM
9443 * 1 item for updating parent inode item
9444 * 1 item for the inline extent item
9ed74f2d
JB
9445 * 1 item for xattr if selinux is on
9446 */
9269d12b 9447 trans = btrfs_start_transaction(root, 7);
a22285a6
YZ
9448 if (IS_ERR(trans))
9449 return PTR_ERR(trans);
1832a6d5 9450
581bb050
LZ
9451 err = btrfs_find_free_ino(root, &objectid);
9452 if (err)
9453 goto out_unlock;
9454
aec7477b 9455 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
9456 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9457 objectid, S_IFLNK|S_IRWXUGO, &index);
7cf96da3
TI
9458 if (IS_ERR(inode)) {
9459 err = PTR_ERR(inode);
32955c54 9460 inode = NULL;
39279cc3 9461 goto out_unlock;
7cf96da3 9462 }
39279cc3 9463
ad19db71
CS
9464 /*
9465 * If the active LSM wants to access the inode during
9466 * d_instantiate it needs these. Smack checks to see
9467 * if the filesystem supports xattrs by looking at the
9468 * ops vector.
9469 */
9470 inode->i_fop = &btrfs_file_operations;
9471 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 9472 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
9473 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9474
9475 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9476 if (err)
32955c54 9477 goto out_unlock;
ad19db71 9478
39279cc3 9479 path = btrfs_alloc_path();
d8926bb3
MF
9480 if (!path) {
9481 err = -ENOMEM;
32955c54 9482 goto out_unlock;
d8926bb3 9483 }
4a0cc7ca 9484 key.objectid = btrfs_ino(BTRFS_I(inode));
39279cc3 9485 key.offset = 0;
962a298f 9486 key.type = BTRFS_EXTENT_DATA_KEY;
39279cc3
CM
9487 datasize = btrfs_file_extent_calc_inline_size(name_len);
9488 err = btrfs_insert_empty_item(trans, root, path, &key,
9489 datasize);
54aa1f4d 9490 if (err) {
b0839166 9491 btrfs_free_path(path);
32955c54 9492 goto out_unlock;
54aa1f4d 9493 }
5f39d397
CM
9494 leaf = path->nodes[0];
9495 ei = btrfs_item_ptr(leaf, path->slots[0],
9496 struct btrfs_file_extent_item);
9497 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9498 btrfs_set_file_extent_type(leaf, ei,
39279cc3 9499 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
9500 btrfs_set_file_extent_encryption(leaf, ei, 0);
9501 btrfs_set_file_extent_compression(leaf, ei, 0);
9502 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9503 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9504
39279cc3 9505 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
9506 write_extent_buffer(leaf, symname, ptr, name_len);
9507 btrfs_mark_buffer_dirty(leaf);
39279cc3 9508 btrfs_free_path(path);
5f39d397 9509
39279cc3 9510 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 9511 inode_nohighmem(inode);
d899e052 9512 inode_set_bytes(inode, name_len);
6ef06d27 9513 btrfs_i_size_write(BTRFS_I(inode), name_len);
54aa1f4d 9514 err = btrfs_update_inode(trans, root, inode);
d50866d0
FM
9515 /*
9516 * Last step, add directory indexes for our symlink inode. This is the
9517 * last step to avoid extra cleanup of these indexes if an error happens
9518 * elsewhere above.
9519 */
9520 if (!err)
cef415af
NB
9521 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9522 BTRFS_I(inode), 0, index);
32955c54
AV
9523 if (err)
9524 goto out_unlock;
b0d5d10f 9525
1e2e547a 9526 d_instantiate_new(dentry, inode);
39279cc3
CM
9527
9528out_unlock:
3a45bb20 9529 btrfs_end_transaction(trans);
32955c54 9530 if (err && inode) {
39279cc3 9531 inode_dec_link_count(inode);
32955c54 9532 discard_new_inode(inode);
39279cc3 9533 }
2ff7e61e 9534 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
9535 return err;
9536}
16432985 9537
0af3d00b
JB
9538static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9539 u64 start, u64 num_bytes, u64 min_size,
9540 loff_t actual_len, u64 *alloc_hint,
9541 struct btrfs_trans_handle *trans)
d899e052 9542{
0b246afa 9543 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5dc562c5
JB
9544 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9545 struct extent_map *em;
d899e052
YZ
9546 struct btrfs_root *root = BTRFS_I(inode)->root;
9547 struct btrfs_key ins;
d899e052 9548 u64 cur_offset = start;
b778cf96 9549 u64 clear_offset = start;
55a61d1d 9550 u64 i_size;
154ea289 9551 u64 cur_bytes;
0b670dc4 9552 u64 last_alloc = (u64)-1;
d899e052 9553 int ret = 0;
0af3d00b 9554 bool own_trans = true;
18513091 9555 u64 end = start + num_bytes - 1;
d899e052 9556
0af3d00b
JB
9557 if (trans)
9558 own_trans = false;
d899e052 9559 while (num_bytes > 0) {
0af3d00b
JB
9560 if (own_trans) {
9561 trans = btrfs_start_transaction(root, 3);
9562 if (IS_ERR(trans)) {
9563 ret = PTR_ERR(trans);
9564 break;
9565 }
5a303d5d
YZ
9566 }
9567
ee22184b 9568 cur_bytes = min_t(u64, num_bytes, SZ_256M);
154ea289 9569 cur_bytes = max(cur_bytes, min_size);
0b670dc4
JB
9570 /*
9571 * If we are severely fragmented we could end up with really
9572 * small allocations, so if the allocator is returning small
9573 * chunks lets make its job easier by only searching for those
9574 * sized chunks.
9575 */
9576 cur_bytes = min(cur_bytes, last_alloc);
18513091
WX
9577 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9578 min_size, 0, *alloc_hint, &ins, 1, 0);
5a303d5d 9579 if (ret) {
0af3d00b 9580 if (own_trans)
3a45bb20 9581 btrfs_end_transaction(trans);
a22285a6 9582 break;
d899e052 9583 }
b778cf96
JB
9584
9585 /*
9586 * We've reserved this space, and thus converted it from
9587 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9588 * from here on out we will only need to clear our reservation
9589 * for the remaining unreserved area, so advance our
9590 * clear_offset by our extent size.
9591 */
9592 clear_offset += ins.offset;
0b246afa 9593 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
5a303d5d 9594
0b670dc4 9595 last_alloc = ins.offset;
d899e052
YZ
9596 ret = insert_reserved_file_extent(trans, inode,
9597 cur_offset, ins.objectid,
9598 ins.offset, ins.offset,
920bbbfb 9599 ins.offset, 0, 0, 0,
d899e052 9600 BTRFS_FILE_EXTENT_PREALLOC);
79787eaa 9601 if (ret) {
2ff7e61e 9602 btrfs_free_reserved_extent(fs_info, ins.objectid,
e570fd27 9603 ins.offset, 0);
66642832 9604 btrfs_abort_transaction(trans, ret);
79787eaa 9605 if (own_trans)
3a45bb20 9606 btrfs_end_transaction(trans);
79787eaa
JM
9607 break;
9608 }
31193213 9609
dcdbc059 9610 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
a1ed835e 9611 cur_offset + ins.offset -1, 0);
5a303d5d 9612
5dc562c5
JB
9613 em = alloc_extent_map();
9614 if (!em) {
9615 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9616 &BTRFS_I(inode)->runtime_flags);
9617 goto next;
9618 }
9619
9620 em->start = cur_offset;
9621 em->orig_start = cur_offset;
9622 em->len = ins.offset;
9623 em->block_start = ins.objectid;
9624 em->block_len = ins.offset;
b4939680 9625 em->orig_block_len = ins.offset;
cc95bef6 9626 em->ram_bytes = ins.offset;
5dc562c5
JB
9627 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9628 em->generation = trans->transid;
9629
9630 while (1) {
9631 write_lock(&em_tree->lock);
09a2a8f9 9632 ret = add_extent_mapping(em_tree, em, 1);
5dc562c5
JB
9633 write_unlock(&em_tree->lock);
9634 if (ret != -EEXIST)
9635 break;
dcdbc059 9636 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
9637 cur_offset + ins.offset - 1,
9638 0);
9639 }
9640 free_extent_map(em);
9641next:
d899e052
YZ
9642 num_bytes -= ins.offset;
9643 cur_offset += ins.offset;
efa56464 9644 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 9645
0c4d2d95 9646 inode_inc_iversion(inode);
c2050a45 9647 inode->i_ctime = current_time(inode);
6cbff00f 9648 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 9649 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
9650 (actual_len > inode->i_size) &&
9651 (cur_offset > inode->i_size)) {
d1ea6a61 9652 if (cur_offset > actual_len)
55a61d1d 9653 i_size = actual_len;
d1ea6a61 9654 else
55a61d1d
JB
9655 i_size = cur_offset;
9656 i_size_write(inode, i_size);
d923afe9 9657 btrfs_inode_safe_disk_i_size_write(inode, 0);
5a303d5d
YZ
9658 }
9659
d899e052 9660 ret = btrfs_update_inode(trans, root, inode);
79787eaa
JM
9661
9662 if (ret) {
66642832 9663 btrfs_abort_transaction(trans, ret);
79787eaa 9664 if (own_trans)
3a45bb20 9665 btrfs_end_transaction(trans);
79787eaa
JM
9666 break;
9667 }
d899e052 9668
0af3d00b 9669 if (own_trans)
3a45bb20 9670 btrfs_end_transaction(trans);
5a303d5d 9671 }
b778cf96
JB
9672 if (clear_offset < end)
9673 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9674 end - clear_offset + 1);
d899e052
YZ
9675 return ret;
9676}
9677
0af3d00b
JB
9678int btrfs_prealloc_file_range(struct inode *inode, int mode,
9679 u64 start, u64 num_bytes, u64 min_size,
9680 loff_t actual_len, u64 *alloc_hint)
9681{
9682 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9683 min_size, actual_len, alloc_hint,
9684 NULL);
9685}
9686
9687int btrfs_prealloc_file_range_trans(struct inode *inode,
9688 struct btrfs_trans_handle *trans, int mode,
9689 u64 start, u64 num_bytes, u64 min_size,
9690 loff_t actual_len, u64 *alloc_hint)
9691{
9692 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9693 min_size, actual_len, alloc_hint, trans);
9694}
9695
e6dcd2dc
CM
9696static int btrfs_set_page_dirty(struct page *page)
9697{
e6dcd2dc
CM
9698 return __set_page_dirty_nobuffers(page);
9699}
9700
10556cb2 9701static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 9702{
b83cc969 9703 struct btrfs_root *root = BTRFS_I(inode)->root;
cb6db4e5 9704 umode_t mode = inode->i_mode;
b83cc969 9705
cb6db4e5
JM
9706 if (mask & MAY_WRITE &&
9707 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9708 if (btrfs_root_readonly(root))
9709 return -EROFS;
9710 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9711 return -EACCES;
9712 }
2830ba7f 9713 return generic_permission(inode, mask);
fdebe2bd 9714}
39279cc3 9715
ef3b9af5
FM
9716static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9717{
2ff7e61e 9718 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
ef3b9af5
FM
9719 struct btrfs_trans_handle *trans;
9720 struct btrfs_root *root = BTRFS_I(dir)->root;
9721 struct inode *inode = NULL;
9722 u64 objectid;
9723 u64 index;
9724 int ret = 0;
9725
9726 /*
9727 * 5 units required for adding orphan entry
9728 */
9729 trans = btrfs_start_transaction(root, 5);
9730 if (IS_ERR(trans))
9731 return PTR_ERR(trans);
9732
9733 ret = btrfs_find_free_ino(root, &objectid);
9734 if (ret)
9735 goto out;
9736
9737 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
f85b7379 9738 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
ef3b9af5
FM
9739 if (IS_ERR(inode)) {
9740 ret = PTR_ERR(inode);
9741 inode = NULL;
9742 goto out;
9743 }
9744
ef3b9af5
FM
9745 inode->i_fop = &btrfs_file_operations;
9746 inode->i_op = &btrfs_file_inode_operations;
9747
9748 inode->i_mapping->a_ops = &btrfs_aops;
ef3b9af5
FM
9749 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9750
b0d5d10f
CM
9751 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9752 if (ret)
32955c54 9753 goto out;
b0d5d10f
CM
9754
9755 ret = btrfs_update_inode(trans, root, inode);
9756 if (ret)
32955c54 9757 goto out;
73f2e545 9758 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
ef3b9af5 9759 if (ret)
32955c54 9760 goto out;
ef3b9af5 9761
5762b5c9
FM
9762 /*
9763 * We set number of links to 0 in btrfs_new_inode(), and here we set
9764 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9765 * through:
9766 *
9767 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9768 */
9769 set_nlink(inode, 1);
ef3b9af5 9770 d_tmpfile(dentry, inode);
32955c54 9771 unlock_new_inode(inode);
ef3b9af5 9772 mark_inode_dirty(inode);
ef3b9af5 9773out:
3a45bb20 9774 btrfs_end_transaction(trans);
32955c54
AV
9775 if (ret && inode)
9776 discard_new_inode(inode);
2ff7e61e 9777 btrfs_btree_balance_dirty(fs_info);
ef3b9af5
FM
9778 return ret;
9779}
9780
5cdc84bf 9781void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
c6100a4b 9782{
5cdc84bf 9783 struct inode *inode = tree->private_data;
c6100a4b
JB
9784 unsigned long index = start >> PAGE_SHIFT;
9785 unsigned long end_index = end >> PAGE_SHIFT;
9786 struct page *page;
9787
9788 while (index <= end_index) {
9789 page = find_get_page(inode->i_mapping, index);
9790 ASSERT(page); /* Pages should be in the extent_io_tree */
9791 set_page_writeback(page);
9792 put_page(page);
9793 index++;
9794 }
9795}
9796
ed46ff3d
OS
9797#ifdef CONFIG_SWAP
9798/*
9799 * Add an entry indicating a block group or device which is pinned by a
9800 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9801 * negative errno on failure.
9802 */
9803static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9804 bool is_block_group)
9805{
9806 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9807 struct btrfs_swapfile_pin *sp, *entry;
9808 struct rb_node **p;
9809 struct rb_node *parent = NULL;
9810
9811 sp = kmalloc(sizeof(*sp), GFP_NOFS);
9812 if (!sp)
9813 return -ENOMEM;
9814 sp->ptr = ptr;
9815 sp->inode = inode;
9816 sp->is_block_group = is_block_group;
9817
9818 spin_lock(&fs_info->swapfile_pins_lock);
9819 p = &fs_info->swapfile_pins.rb_node;
9820 while (*p) {
9821 parent = *p;
9822 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9823 if (sp->ptr < entry->ptr ||
9824 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9825 p = &(*p)->rb_left;
9826 } else if (sp->ptr > entry->ptr ||
9827 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9828 p = &(*p)->rb_right;
9829 } else {
9830 spin_unlock(&fs_info->swapfile_pins_lock);
9831 kfree(sp);
9832 return 1;
9833 }
9834 }
9835 rb_link_node(&sp->node, parent, p);
9836 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9837 spin_unlock(&fs_info->swapfile_pins_lock);
9838 return 0;
9839}
9840
9841/* Free all of the entries pinned by this swapfile. */
9842static void btrfs_free_swapfile_pins(struct inode *inode)
9843{
9844 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9845 struct btrfs_swapfile_pin *sp;
9846 struct rb_node *node, *next;
9847
9848 spin_lock(&fs_info->swapfile_pins_lock);
9849 node = rb_first(&fs_info->swapfile_pins);
9850 while (node) {
9851 next = rb_next(node);
9852 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9853 if (sp->inode == inode) {
9854 rb_erase(&sp->node, &fs_info->swapfile_pins);
9855 if (sp->is_block_group)
9856 btrfs_put_block_group(sp->ptr);
9857 kfree(sp);
9858 }
9859 node = next;
9860 }
9861 spin_unlock(&fs_info->swapfile_pins_lock);
9862}
9863
9864struct btrfs_swap_info {
9865 u64 start;
9866 u64 block_start;
9867 u64 block_len;
9868 u64 lowest_ppage;
9869 u64 highest_ppage;
9870 unsigned long nr_pages;
9871 int nr_extents;
9872};
9873
9874static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9875 struct btrfs_swap_info *bsi)
9876{
9877 unsigned long nr_pages;
9878 u64 first_ppage, first_ppage_reported, next_ppage;
9879 int ret;
9880
9881 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9882 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9883 PAGE_SIZE) >> PAGE_SHIFT;
9884
9885 if (first_ppage >= next_ppage)
9886 return 0;
9887 nr_pages = next_ppage - first_ppage;
9888
9889 first_ppage_reported = first_ppage;
9890 if (bsi->start == 0)
9891 first_ppage_reported++;
9892 if (bsi->lowest_ppage > first_ppage_reported)
9893 bsi->lowest_ppage = first_ppage_reported;
9894 if (bsi->highest_ppage < (next_ppage - 1))
9895 bsi->highest_ppage = next_ppage - 1;
9896
9897 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9898 if (ret < 0)
9899 return ret;
9900 bsi->nr_extents += ret;
9901 bsi->nr_pages += nr_pages;
9902 return 0;
9903}
9904
9905static void btrfs_swap_deactivate(struct file *file)
9906{
9907 struct inode *inode = file_inode(file);
9908
9909 btrfs_free_swapfile_pins(inode);
9910 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9911}
9912
9913static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9914 sector_t *span)
9915{
9916 struct inode *inode = file_inode(file);
9917 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9918 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9919 struct extent_state *cached_state = NULL;
9920 struct extent_map *em = NULL;
9921 struct btrfs_device *device = NULL;
9922 struct btrfs_swap_info bsi = {
9923 .lowest_ppage = (sector_t)-1ULL,
9924 };
9925 int ret = 0;
9926 u64 isize;
9927 u64 start;
9928
9929 /*
9930 * If the swap file was just created, make sure delalloc is done. If the
9931 * file changes again after this, the user is doing something stupid and
9932 * we don't really care.
9933 */
9934 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9935 if (ret)
9936 return ret;
9937
9938 /*
9939 * The inode is locked, so these flags won't change after we check them.
9940 */
9941 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9942 btrfs_warn(fs_info, "swapfile must not be compressed");
9943 return -EINVAL;
9944 }
9945 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9946 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9947 return -EINVAL;
9948 }
9949 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9950 btrfs_warn(fs_info, "swapfile must not be checksummed");
9951 return -EINVAL;
9952 }
9953
9954 /*
9955 * Balance or device remove/replace/resize can move stuff around from
9956 * under us. The EXCL_OP flag makes sure they aren't running/won't run
9957 * concurrently while we are mapping the swap extents, and
9958 * fs_info->swapfile_pins prevents them from running while the swap file
9959 * is active and moving the extents. Note that this also prevents a
9960 * concurrent device add which isn't actually necessary, but it's not
9961 * really worth the trouble to allow it.
9962 */
9963 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
9964 btrfs_warn(fs_info,
9965 "cannot activate swapfile while exclusive operation is running");
9966 return -EBUSY;
9967 }
9968 /*
9969 * Snapshots can create extents which require COW even if NODATACOW is
9970 * set. We use this counter to prevent snapshots. We must increment it
9971 * before walking the extents because we don't want a concurrent
9972 * snapshot to run after we've already checked the extents.
9973 */
9974 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
9975
9976 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
9977
9978 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
9979 start = 0;
9980 while (start < isize) {
9981 u64 logical_block_start, physical_block_start;
32da5386 9982 struct btrfs_block_group *bg;
ed46ff3d
OS
9983 u64 len = isize - start;
9984
39b07b5d 9985 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
ed46ff3d
OS
9986 if (IS_ERR(em)) {
9987 ret = PTR_ERR(em);
9988 goto out;
9989 }
9990
9991 if (em->block_start == EXTENT_MAP_HOLE) {
9992 btrfs_warn(fs_info, "swapfile must not have holes");
9993 ret = -EINVAL;
9994 goto out;
9995 }
9996 if (em->block_start == EXTENT_MAP_INLINE) {
9997 /*
9998 * It's unlikely we'll ever actually find ourselves
9999 * here, as a file small enough to fit inline won't be
10000 * big enough to store more than the swap header, but in
10001 * case something changes in the future, let's catch it
10002 * here rather than later.
10003 */
10004 btrfs_warn(fs_info, "swapfile must not be inline");
10005 ret = -EINVAL;
10006 goto out;
10007 }
10008 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10009 btrfs_warn(fs_info, "swapfile must not be compressed");
10010 ret = -EINVAL;
10011 goto out;
10012 }
10013
10014 logical_block_start = em->block_start + (start - em->start);
10015 len = min(len, em->len - (start - em->start));
10016 free_extent_map(em);
10017 em = NULL;
10018
10019 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10020 if (ret < 0) {
10021 goto out;
10022 } else if (ret) {
10023 ret = 0;
10024 } else {
10025 btrfs_warn(fs_info,
10026 "swapfile must not be copy-on-write");
10027 ret = -EINVAL;
10028 goto out;
10029 }
10030
10031 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10032 if (IS_ERR(em)) {
10033 ret = PTR_ERR(em);
10034 goto out;
10035 }
10036
10037 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10038 btrfs_warn(fs_info,
10039 "swapfile must have single data profile");
10040 ret = -EINVAL;
10041 goto out;
10042 }
10043
10044 if (device == NULL) {
10045 device = em->map_lookup->stripes[0].dev;
10046 ret = btrfs_add_swapfile_pin(inode, device, false);
10047 if (ret == 1)
10048 ret = 0;
10049 else if (ret)
10050 goto out;
10051 } else if (device != em->map_lookup->stripes[0].dev) {
10052 btrfs_warn(fs_info, "swapfile must be on one device");
10053 ret = -EINVAL;
10054 goto out;
10055 }
10056
10057 physical_block_start = (em->map_lookup->stripes[0].physical +
10058 (logical_block_start - em->start));
10059 len = min(len, em->len - (logical_block_start - em->start));
10060 free_extent_map(em);
10061 em = NULL;
10062
10063 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10064 if (!bg) {
10065 btrfs_warn(fs_info,
10066 "could not find block group containing swapfile");
10067 ret = -EINVAL;
10068 goto out;
10069 }
10070
10071 ret = btrfs_add_swapfile_pin(inode, bg, true);
10072 if (ret) {
10073 btrfs_put_block_group(bg);
10074 if (ret == 1)
10075 ret = 0;
10076 else
10077 goto out;
10078 }
10079
10080 if (bsi.block_len &&
10081 bsi.block_start + bsi.block_len == physical_block_start) {
10082 bsi.block_len += len;
10083 } else {
10084 if (bsi.block_len) {
10085 ret = btrfs_add_swap_extent(sis, &bsi);
10086 if (ret)
10087 goto out;
10088 }
10089 bsi.start = start;
10090 bsi.block_start = physical_block_start;
10091 bsi.block_len = len;
10092 }
10093
10094 start += len;
10095 }
10096
10097 if (bsi.block_len)
10098 ret = btrfs_add_swap_extent(sis, &bsi);
10099
10100out:
10101 if (!IS_ERR_OR_NULL(em))
10102 free_extent_map(em);
10103
10104 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10105
10106 if (ret)
10107 btrfs_swap_deactivate(file);
10108
10109 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10110
10111 if (ret)
10112 return ret;
10113
10114 if (device)
10115 sis->bdev = device->bdev;
10116 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10117 sis->max = bsi.nr_pages;
10118 sis->pages = bsi.nr_pages - 1;
10119 sis->highest_bit = bsi.nr_pages - 1;
10120 return bsi.nr_extents;
10121}
10122#else
10123static void btrfs_swap_deactivate(struct file *file)
10124{
10125}
10126
10127static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10128 sector_t *span)
10129{
10130 return -EOPNOTSUPP;
10131}
10132#endif
10133
6e1d5dcc 10134static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 10135 .getattr = btrfs_getattr,
39279cc3
CM
10136 .lookup = btrfs_lookup,
10137 .create = btrfs_create,
10138 .unlink = btrfs_unlink,
10139 .link = btrfs_link,
10140 .mkdir = btrfs_mkdir,
10141 .rmdir = btrfs_rmdir,
2773bf00 10142 .rename = btrfs_rename2,
39279cc3
CM
10143 .symlink = btrfs_symlink,
10144 .setattr = btrfs_setattr,
618e21d5 10145 .mknod = btrfs_mknod,
5103e947 10146 .listxattr = btrfs_listxattr,
fdebe2bd 10147 .permission = btrfs_permission,
4e34e719 10148 .get_acl = btrfs_get_acl,
996a710d 10149 .set_acl = btrfs_set_acl,
93fd63c2 10150 .update_time = btrfs_update_time,
ef3b9af5 10151 .tmpfile = btrfs_tmpfile,
39279cc3 10152};
76dda93c 10153
828c0950 10154static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
10155 .llseek = generic_file_llseek,
10156 .read = generic_read_dir,
02dbfc99 10157 .iterate_shared = btrfs_real_readdir,
23b5ec74 10158 .open = btrfs_opendir,
34287aa3 10159 .unlocked_ioctl = btrfs_ioctl,
39279cc3 10160#ifdef CONFIG_COMPAT
4c63c245 10161 .compat_ioctl = btrfs_compat_ioctl,
39279cc3 10162#endif
6bf13c0c 10163 .release = btrfs_release_file,
e02119d5 10164 .fsync = btrfs_sync_file,
39279cc3
CM
10165};
10166
20e5506b 10167static const struct extent_io_ops btrfs_extent_io_ops = {
4d53dddb 10168 /* mandatory callbacks */
065631f6 10169 .submit_bio_hook = btrfs_submit_bio_hook,
07157aac
CM
10170 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10171};
10172
35054394
CM
10173/*
10174 * btrfs doesn't support the bmap operation because swapfiles
10175 * use bmap to make a mapping of extents in the file. They assume
10176 * these extents won't change over the life of the file and they
10177 * use the bmap result to do IO directly to the drive.
10178 *
10179 * the btrfs bmap call would return logical addresses that aren't
10180 * suitable for IO and they also will change frequently as COW
10181 * operations happen. So, swapfile + btrfs == corruption.
10182 *
10183 * For now we're avoiding this by dropping bmap.
10184 */
7f09410b 10185static const struct address_space_operations btrfs_aops = {
39279cc3
CM
10186 .readpage = btrfs_readpage,
10187 .writepage = btrfs_writepage,
b293f02e 10188 .writepages = btrfs_writepages,
3ab2fb5a 10189 .readpages = btrfs_readpages,
16432985 10190 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
10191 .invalidatepage = btrfs_invalidatepage,
10192 .releasepage = btrfs_releasepage,
f8e66081
RG
10193#ifdef CONFIG_MIGRATION
10194 .migratepage = btrfs_migratepage,
10195#endif
e6dcd2dc 10196 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 10197 .error_remove_page = generic_error_remove_page,
ed46ff3d
OS
10198 .swap_activate = btrfs_swap_activate,
10199 .swap_deactivate = btrfs_swap_deactivate,
39279cc3
CM
10200};
10201
6e1d5dcc 10202static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
10203 .getattr = btrfs_getattr,
10204 .setattr = btrfs_setattr,
5103e947 10205 .listxattr = btrfs_listxattr,
fdebe2bd 10206 .permission = btrfs_permission,
1506fcc8 10207 .fiemap = btrfs_fiemap,
4e34e719 10208 .get_acl = btrfs_get_acl,
996a710d 10209 .set_acl = btrfs_set_acl,
e41f941a 10210 .update_time = btrfs_update_time,
39279cc3 10211};
6e1d5dcc 10212static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
10213 .getattr = btrfs_getattr,
10214 .setattr = btrfs_setattr,
fdebe2bd 10215 .permission = btrfs_permission,
33268eaf 10216 .listxattr = btrfs_listxattr,
4e34e719 10217 .get_acl = btrfs_get_acl,
996a710d 10218 .set_acl = btrfs_set_acl,
e41f941a 10219 .update_time = btrfs_update_time,
618e21d5 10220};
6e1d5dcc 10221static const struct inode_operations btrfs_symlink_inode_operations = {
6b255391 10222 .get_link = page_get_link,
f209561a 10223 .getattr = btrfs_getattr,
22c44fe6 10224 .setattr = btrfs_setattr,
fdebe2bd 10225 .permission = btrfs_permission,
0279b4cd 10226 .listxattr = btrfs_listxattr,
e41f941a 10227 .update_time = btrfs_update_time,
39279cc3 10228};
76dda93c 10229
82d339d9 10230const struct dentry_operations btrfs_dentry_operations = {
76dda93c
YZ
10231 .d_delete = btrfs_dentry_delete,
10232};