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