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