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