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