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