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