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