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