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