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