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