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