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