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