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