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