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