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