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