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