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