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