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