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