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