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