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