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