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