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