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