]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - fs/btrfs/inode.c
Merge branch 'for-chris-4.11-part2' of git://git.kernel.org/pub/scm/linux/kernel...
[mirror_ubuntu-artful-kernel.git] / fs / btrfs / inode.c
CommitLineData
6cbd5570
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
18
8f18cf13 19#include <linux/kernel.h>
065631f6 20#include <linux/bio.h>
39279cc3 21#include <linux/buffer_head.h>
f2eb0a24 22#include <linux/file.h>
39279cc3
CM
23#include <linux/fs.h>
24#include <linux/pagemap.h>
25#include <linux/highmem.h>
26#include <linux/time.h>
27#include <linux/init.h>
28#include <linux/string.h>
39279cc3
CM
29#include <linux/backing-dev.h>
30#include <linux/mpage.h>
31#include <linux/swap.h>
32#include <linux/writeback.h>
39279cc3 33#include <linux/compat.h>
9ebefb18 34#include <linux/bit_spinlock.h>
5103e947 35#include <linux/xattr.h>
33268eaf 36#include <linux/posix_acl.h>
d899e052 37#include <linux/falloc.h>
5a0e3ad6 38#include <linux/slab.h>
7a36ddec 39#include <linux/ratelimit.h>
22c44fe6 40#include <linux/mount.h>
55e301fd 41#include <linux/btrfs.h>
53b381b3 42#include <linux/blkdev.h>
f23b5a59 43#include <linux/posix_acl_xattr.h>
e2e40f2c 44#include <linux/uio.h>
39279cc3
CM
45#include "ctree.h"
46#include "disk-io.h"
47#include "transaction.h"
48#include "btrfs_inode.h"
39279cc3 49#include "print-tree.h"
e6dcd2dc 50#include "ordered-data.h"
95819c05 51#include "xattr.h"
e02119d5 52#include "tree-log.h"
4a54c8c1 53#include "volumes.h"
c8b97818 54#include "compression.h"
b4ce94de 55#include "locking.h"
dc89e982 56#include "free-space-cache.h"
581bb050 57#include "inode-map.h"
38c227d8 58#include "backref.h"
f23b5a59 59#include "hash.h"
63541927 60#include "props.h"
31193213 61#include "qgroup.h"
dda3245e 62#include "dedupe.h"
39279cc3
CM
63
64struct btrfs_iget_args {
90d3e592 65 struct btrfs_key *location;
39279cc3
CM
66 struct btrfs_root *root;
67};
68
f28a4928
FM
69struct btrfs_dio_data {
70 u64 outstanding_extents;
71 u64 reserve;
72 u64 unsubmitted_oe_range_start;
73 u64 unsubmitted_oe_range_end;
4aaedfb0 74 int overwrite;
f28a4928
FM
75};
76
6e1d5dcc
AD
77static const struct inode_operations btrfs_dir_inode_operations;
78static const struct inode_operations btrfs_symlink_inode_operations;
79static const struct inode_operations btrfs_dir_ro_inode_operations;
80static const struct inode_operations btrfs_special_inode_operations;
81static const struct inode_operations btrfs_file_inode_operations;
7f09410b
AD
82static const struct address_space_operations btrfs_aops;
83static const struct address_space_operations btrfs_symlink_aops;
828c0950 84static const struct file_operations btrfs_dir_file_operations;
20e5506b 85static const struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
86
87static struct kmem_cache *btrfs_inode_cachep;
88struct kmem_cache *btrfs_trans_handle_cachep;
89struct kmem_cache *btrfs_transaction_cachep;
39279cc3 90struct kmem_cache *btrfs_path_cachep;
dc89e982 91struct kmem_cache *btrfs_free_space_cachep;
39279cc3
CM
92
93#define S_SHIFT 12
4d4ab6d6 94static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
39279cc3
CM
95 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
96 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
97 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
98 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
99 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
100 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
101 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
102};
103
3972f260 104static int btrfs_setsize(struct inode *inode, struct iattr *attr);
a41ad394 105static int btrfs_truncate(struct inode *inode);
5fd02043 106static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
771ed689
CM
107static noinline int cow_file_range(struct inode *inode,
108 struct page *locked_page,
dda3245e
WX
109 u64 start, u64 end, u64 delalloc_end,
110 int *page_started, unsigned long *nr_written,
111 int unlock, struct btrfs_dedupe_hash *hash);
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);
691fa059 319 btrfs_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
dcdbc059 320 btrfs_drop_extent_cache(BTRFS_I(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
6158e1ce 392static inline void inode_should_defrag(struct btrfs_inode *inode,
26d30f85
AJ
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 &&
6158e1ce 397 (start > 0 || end + 1 < inode->disk_i_size))
26d30f85
AJ
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;
c8b97818
CM
433 unsigned long total_compressed = 0;
434 unsigned long total_in = 0;
c8b97818
CM
435 int i;
436 int will_compress;
0b246afa 437 int compress_type = fs_info->compress_type;
4adaa611 438 int redirty = 0;
b888db2b 439
6158e1ce
NB
440 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
441 SZ_16K);
4cb5300b 442
42dc7bab 443 actual_end = min_t(u64, isize, end + 1);
c8b97818
CM
444again:
445 will_compress = 0;
09cbfeaf 446 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
069eac78
DS
447 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
448 nr_pages = min_t(unsigned long, nr_pages,
449 BTRFS_MAX_COMPRESSED / 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
069eac78
DS
474 total_compressed = min_t(unsigned long, total_compressed,
475 BTRFS_MAX_UNCOMPRESSED);
fda2832f 476 num_bytes = ALIGN(end - start + 1, blocksize);
be20aa9d 477 num_bytes = max(blocksize, num_bytes);
c8b97818
CM
478 total_in = 0;
479 ret = 0;
db94535d 480
771ed689
CM
481 /*
482 * we do compression for mount -o compress and when the
483 * inode has not been flagged as nocompress. This flag can
484 * change at any time if we discover bad compression ratios.
c8b97818 485 */
f79707b0 486 if (inode_need_compress(inode)) {
c8b97818 487 WARN_ON(pages);
31e818fe 488 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
560f7d75
LZ
489 if (!pages) {
490 /* just bail out to the uncompressed code */
491 goto cont;
492 }
c8b97818 493
261507a0
LZ
494 if (BTRFS_I(inode)->force_compress)
495 compress_type = BTRFS_I(inode)->force_compress;
496
4adaa611
CM
497 /*
498 * we need to call clear_page_dirty_for_io on each
499 * page in the range. Otherwise applications with the file
500 * mmap'd can wander in and change the page contents while
501 * we are compressing them.
502 *
503 * If the compression fails for any reason, we set the pages
504 * dirty again later on.
505 */
506 extent_range_clear_dirty_for_io(inode, start, end);
507 redirty = 1;
261507a0
LZ
508 ret = btrfs_compress_pages(compress_type,
509 inode->i_mapping, start,
38c31464 510 pages,
4d3a800e 511 &nr_pages,
261507a0 512 &total_in,
e5d74902 513 &total_compressed);
c8b97818
CM
514
515 if (!ret) {
516 unsigned long offset = total_compressed &
09cbfeaf 517 (PAGE_SIZE - 1);
4d3a800e 518 struct page *page = pages[nr_pages - 1];
c8b97818
CM
519 char *kaddr;
520
521 /* zero the tail end of the last page, we might be
522 * sending it down to disk
523 */
524 if (offset) {
7ac687d9 525 kaddr = kmap_atomic(page);
c8b97818 526 memset(kaddr + offset, 0,
09cbfeaf 527 PAGE_SIZE - offset);
7ac687d9 528 kunmap_atomic(kaddr);
c8b97818
CM
529 }
530 will_compress = 1;
531 }
532 }
560f7d75 533cont:
c8b97818
CM
534 if (start == 0) {
535 /* lets try to make an inline extent */
771ed689 536 if (ret || total_in < (actual_end - start)) {
c8b97818 537 /* we didn't compress the entire range, try
771ed689 538 * to make an uncompressed inline extent.
c8b97818 539 */
00361589 540 ret = cow_file_range_inline(root, inode, start, end,
f74670f7 541 0, BTRFS_COMPRESS_NONE, NULL);
c8b97818 542 } else {
771ed689 543 /* try making a compressed inline extent */
00361589 544 ret = cow_file_range_inline(root, inode, start, end,
fe3f566c
LZ
545 total_compressed,
546 compress_type, pages);
c8b97818 547 }
79787eaa 548 if (ret <= 0) {
151a41bc
JB
549 unsigned long clear_flags = EXTENT_DELALLOC |
550 EXTENT_DEFRAG;
e6eb4314
FM
551 unsigned long page_error_op;
552
151a41bc 553 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
e6eb4314 554 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
151a41bc 555
771ed689 556 /*
79787eaa
JM
557 * inline extent creation worked or returned error,
558 * we don't need to create any more async work items.
559 * Unlock and free up our temp pages.
771ed689 560 */
ba8b04c1
QW
561 extent_clear_unlock_delalloc(inode, start, end, end,
562 NULL, clear_flags,
563 PAGE_UNLOCK |
c2790a2e
JB
564 PAGE_CLEAR_DIRTY |
565 PAGE_SET_WRITEBACK |
e6eb4314 566 page_error_op |
c2790a2e 567 PAGE_END_WRITEBACK);
18513091
WX
568 btrfs_free_reserved_data_space_noquota(inode, start,
569 end - start + 1);
c8b97818
CM
570 goto free_pages_out;
571 }
572 }
573
574 if (will_compress) {
575 /*
576 * we aren't doing an inline extent round the compressed size
577 * up to a block size boundary so the allocator does sane
578 * things
579 */
fda2832f 580 total_compressed = ALIGN(total_compressed, blocksize);
c8b97818
CM
581
582 /*
583 * one last check to make sure the compression is really a
584 * win, compare the page count read with the blocks on disk
585 */
09cbfeaf 586 total_in = ALIGN(total_in, PAGE_SIZE);
c8b97818
CM
587 if (total_compressed >= total_in) {
588 will_compress = 0;
589 } else {
c8b97818 590 num_bytes = total_in;
c8bb0c8b
AS
591 *num_added += 1;
592
593 /*
594 * The async work queues will take care of doing actual
595 * allocation on disk for these compressed pages, and
596 * will submit them to the elevator.
597 */
598 add_async_extent(async_cow, start, num_bytes,
4d3a800e 599 total_compressed, pages, nr_pages,
c8bb0c8b
AS
600 compress_type);
601
602 if (start + num_bytes < end) {
603 start += num_bytes;
604 pages = NULL;
605 cond_resched();
606 goto again;
607 }
608 return;
c8b97818
CM
609 }
610 }
c8bb0c8b 611 if (pages) {
c8b97818
CM
612 /*
613 * the compression code ran but failed to make things smaller,
614 * free any pages it allocated and our page pointer array
615 */
4d3a800e 616 for (i = 0; i < nr_pages; i++) {
70b99e69 617 WARN_ON(pages[i]->mapping);
09cbfeaf 618 put_page(pages[i]);
c8b97818
CM
619 }
620 kfree(pages);
621 pages = NULL;
622 total_compressed = 0;
4d3a800e 623 nr_pages = 0;
c8b97818
CM
624
625 /* flag the file so we don't compress in the future */
0b246afa 626 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
1e701a32 627 !(BTRFS_I(inode)->force_compress)) {
a555f810 628 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
1e701a32 629 }
c8b97818 630 }
f03d9301 631cleanup_and_bail_uncompressed:
c8bb0c8b
AS
632 /*
633 * No compression, but we still need to write the pages in the file
634 * we've been given so far. redirty the locked page if it corresponds
635 * to our extent and set things up for the async work queue to run
636 * cow_file_range to do the normal delalloc dance.
637 */
638 if (page_offset(locked_page) >= start &&
639 page_offset(locked_page) <= end)
640 __set_page_dirty_nobuffers(locked_page);
641 /* unlocked later on in the async handlers */
642
643 if (redirty)
644 extent_range_redirty_for_io(inode, start, end);
645 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
646 BTRFS_COMPRESS_NONE);
647 *num_added += 1;
3b951516 648
c44f649e 649 return;
771ed689
CM
650
651free_pages_out:
4d3a800e 652 for (i = 0; i < nr_pages; i++) {
771ed689 653 WARN_ON(pages[i]->mapping);
09cbfeaf 654 put_page(pages[i]);
771ed689 655 }
d397712b 656 kfree(pages);
771ed689 657}
771ed689 658
40ae837b
FM
659static void free_async_extent_pages(struct async_extent *async_extent)
660{
661 int i;
662
663 if (!async_extent->pages)
664 return;
665
666 for (i = 0; i < async_extent->nr_pages; i++) {
667 WARN_ON(async_extent->pages[i]->mapping);
09cbfeaf 668 put_page(async_extent->pages[i]);
40ae837b
FM
669 }
670 kfree(async_extent->pages);
671 async_extent->nr_pages = 0;
672 async_extent->pages = NULL;
771ed689
CM
673}
674
675/*
676 * phase two of compressed writeback. This is the ordered portion
677 * of the code, which only gets called in the order the work was
678 * queued. We walk all the async extents created by compress_file_range
679 * and send them down to the disk.
680 */
dec8f175 681static noinline void submit_compressed_extents(struct inode *inode,
771ed689
CM
682 struct async_cow *async_cow)
683{
0b246afa 684 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
771ed689
CM
685 struct async_extent *async_extent;
686 u64 alloc_hint = 0;
771ed689
CM
687 struct btrfs_key ins;
688 struct extent_map *em;
689 struct btrfs_root *root = BTRFS_I(inode)->root;
771ed689 690 struct extent_io_tree *io_tree;
f5a84ee3 691 int ret = 0;
771ed689 692
3e04e7f1 693again:
d397712b 694 while (!list_empty(&async_cow->extents)) {
771ed689
CM
695 async_extent = list_entry(async_cow->extents.next,
696 struct async_extent, list);
697 list_del(&async_extent->list);
c8b97818 698
771ed689
CM
699 io_tree = &BTRFS_I(inode)->io_tree;
700
f5a84ee3 701retry:
771ed689
CM
702 /* did the compression code fall back to uncompressed IO? */
703 if (!async_extent->pages) {
704 int page_started = 0;
705 unsigned long nr_written = 0;
706
707 lock_extent(io_tree, async_extent->start,
2ac55d41 708 async_extent->start +
d0082371 709 async_extent->ram_size - 1);
771ed689
CM
710
711 /* allocate blocks */
f5a84ee3
JB
712 ret = cow_file_range(inode, async_cow->locked_page,
713 async_extent->start,
714 async_extent->start +
715 async_extent->ram_size - 1,
dda3245e
WX
716 async_extent->start +
717 async_extent->ram_size - 1,
718 &page_started, &nr_written, 0,
719 NULL);
771ed689 720
79787eaa
JM
721 /* JDM XXX */
722
771ed689
CM
723 /*
724 * if page_started, cow_file_range inserted an
725 * inline extent and took care of all the unlocking
726 * and IO for us. Otherwise, we need to submit
727 * all those pages down to the drive.
728 */
f5a84ee3 729 if (!page_started && !ret)
771ed689
CM
730 extent_write_locked_range(io_tree,
731 inode, async_extent->start,
d397712b 732 async_extent->start +
771ed689
CM
733 async_extent->ram_size - 1,
734 btrfs_get_extent,
735 WB_SYNC_ALL);
3e04e7f1
JB
736 else if (ret)
737 unlock_page(async_cow->locked_page);
771ed689
CM
738 kfree(async_extent);
739 cond_resched();
740 continue;
741 }
742
743 lock_extent(io_tree, async_extent->start,
d0082371 744 async_extent->start + async_extent->ram_size - 1);
771ed689 745
18513091 746 ret = btrfs_reserve_extent(root, async_extent->ram_size,
771ed689
CM
747 async_extent->compressed_size,
748 async_extent->compressed_size,
e570fd27 749 0, alloc_hint, &ins, 1, 1);
f5a84ee3 750 if (ret) {
40ae837b 751 free_async_extent_pages(async_extent);
3e04e7f1 752
fdf8e2ea
JB
753 if (ret == -ENOSPC) {
754 unlock_extent(io_tree, async_extent->start,
755 async_extent->start +
756 async_extent->ram_size - 1);
ce62003f
LB
757
758 /*
759 * we need to redirty the pages if we decide to
760 * fallback to uncompressed IO, otherwise we
761 * will not submit these pages down to lower
762 * layers.
763 */
764 extent_range_redirty_for_io(inode,
765 async_extent->start,
766 async_extent->start +
767 async_extent->ram_size - 1);
768
79787eaa 769 goto retry;
fdf8e2ea 770 }
3e04e7f1 771 goto out_free;
f5a84ee3 772 }
c2167754
YZ
773 /*
774 * here we're doing allocation and writeback of the
775 * compressed pages
776 */
6f9994db
LB
777 em = create_io_em(inode, async_extent->start,
778 async_extent->ram_size, /* len */
779 async_extent->start, /* orig_start */
780 ins.objectid, /* block_start */
781 ins.offset, /* block_len */
782 ins.offset, /* orig_block_len */
783 async_extent->ram_size, /* ram_bytes */
784 async_extent->compress_type,
785 BTRFS_ORDERED_COMPRESSED);
786 if (IS_ERR(em))
787 /* ret value is not necessary due to void function */
3e04e7f1 788 goto out_free_reserve;
6f9994db 789 free_extent_map(em);
3e04e7f1 790
261507a0
LZ
791 ret = btrfs_add_ordered_extent_compress(inode,
792 async_extent->start,
793 ins.objectid,
794 async_extent->ram_size,
795 ins.offset,
796 BTRFS_ORDERED_COMPRESSED,
797 async_extent->compress_type);
d9f85963 798 if (ret) {
dcdbc059
NB
799 btrfs_drop_extent_cache(BTRFS_I(inode),
800 async_extent->start,
d9f85963
FM
801 async_extent->start +
802 async_extent->ram_size - 1, 0);
3e04e7f1 803 goto out_free_reserve;
d9f85963 804 }
0b246afa 805 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
771ed689 806
771ed689
CM
807 /*
808 * clear dirty, set writeback and unlock the pages.
809 */
c2790a2e 810 extent_clear_unlock_delalloc(inode, async_extent->start,
ba8b04c1
QW
811 async_extent->start +
812 async_extent->ram_size - 1,
a791e35e
CM
813 async_extent->start +
814 async_extent->ram_size - 1,
151a41bc
JB
815 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
816 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
c2790a2e 817 PAGE_SET_WRITEBACK);
771ed689 818 ret = btrfs_submit_compressed_write(inode,
d397712b
CM
819 async_extent->start,
820 async_extent->ram_size,
821 ins.objectid,
822 ins.offset, async_extent->pages,
823 async_extent->nr_pages);
fce2a4e6
FM
824 if (ret) {
825 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
826 struct page *p = async_extent->pages[0];
827 const u64 start = async_extent->start;
828 const u64 end = start + async_extent->ram_size - 1;
829
830 p->mapping = inode->i_mapping;
831 tree->ops->writepage_end_io_hook(p, start, end,
832 NULL, 0);
833 p->mapping = NULL;
ba8b04c1
QW
834 extent_clear_unlock_delalloc(inode, start, end, end,
835 NULL, 0,
fce2a4e6
FM
836 PAGE_END_WRITEBACK |
837 PAGE_SET_ERROR);
40ae837b 838 free_async_extent_pages(async_extent);
fce2a4e6 839 }
771ed689
CM
840 alloc_hint = ins.objectid + ins.offset;
841 kfree(async_extent);
842 cond_resched();
843 }
dec8f175 844 return;
3e04e7f1 845out_free_reserve:
0b246afa 846 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
2ff7e61e 847 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
79787eaa 848out_free:
c2790a2e 849 extent_clear_unlock_delalloc(inode, async_extent->start,
ba8b04c1
QW
850 async_extent->start +
851 async_extent->ram_size - 1,
3e04e7f1
JB
852 async_extent->start +
853 async_extent->ram_size - 1,
c2790a2e 854 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
855 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
856 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
704de49d
FM
857 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
858 PAGE_SET_ERROR);
40ae837b 859 free_async_extent_pages(async_extent);
79787eaa 860 kfree(async_extent);
3e04e7f1 861 goto again;
771ed689
CM
862}
863
4b46fce2
JB
864static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
865 u64 num_bytes)
866{
867 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
868 struct extent_map *em;
869 u64 alloc_hint = 0;
870
871 read_lock(&em_tree->lock);
872 em = search_extent_mapping(em_tree, start, num_bytes);
873 if (em) {
874 /*
875 * if block start isn't an actual block number then find the
876 * first block in this inode and use that as a hint. If that
877 * block is also bogus then just don't worry about it.
878 */
879 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
880 free_extent_map(em);
881 em = search_extent_mapping(em_tree, 0, 0);
882 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
883 alloc_hint = em->block_start;
884 if (em)
885 free_extent_map(em);
886 } else {
887 alloc_hint = em->block_start;
888 free_extent_map(em);
889 }
890 }
891 read_unlock(&em_tree->lock);
892
893 return alloc_hint;
894}
895
771ed689
CM
896/*
897 * when extent_io.c finds a delayed allocation range in the file,
898 * the call backs end up in this code. The basic idea is to
899 * allocate extents on disk for the range, and create ordered data structs
900 * in ram to track those extents.
901 *
902 * locked_page is the page that writepage had locked already. We use
903 * it to make sure we don't do extra locks or unlocks.
904 *
905 * *page_started is set to one if we unlock locked_page and do everything
906 * required to start IO on it. It may be clean and already done with
907 * IO when we return.
908 */
00361589
JB
909static noinline int cow_file_range(struct inode *inode,
910 struct page *locked_page,
dda3245e
WX
911 u64 start, u64 end, u64 delalloc_end,
912 int *page_started, unsigned long *nr_written,
913 int unlock, struct btrfs_dedupe_hash *hash)
771ed689 914{
0b246afa 915 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
00361589 916 struct btrfs_root *root = BTRFS_I(inode)->root;
771ed689
CM
917 u64 alloc_hint = 0;
918 u64 num_bytes;
919 unsigned long ram_size;
920 u64 disk_num_bytes;
921 u64 cur_alloc_size;
0b246afa 922 u64 blocksize = fs_info->sectorsize;
771ed689
CM
923 struct btrfs_key ins;
924 struct extent_map *em;
771ed689
CM
925 int ret = 0;
926
70ddc553 927 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
02ecd2c2 928 WARN_ON_ONCE(1);
29bce2f3
JB
929 ret = -EINVAL;
930 goto out_unlock;
02ecd2c2 931 }
771ed689 932
fda2832f 933 num_bytes = ALIGN(end - start + 1, blocksize);
771ed689
CM
934 num_bytes = max(blocksize, num_bytes);
935 disk_num_bytes = num_bytes;
771ed689 936
6158e1ce 937 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
4cb5300b 938
771ed689
CM
939 if (start == 0) {
940 /* lets try to make an inline extent */
f74670f7
AJ
941 ret = cow_file_range_inline(root, inode, start, end, 0,
942 BTRFS_COMPRESS_NONE, NULL);
771ed689 943 if (ret == 0) {
ba8b04c1
QW
944 extent_clear_unlock_delalloc(inode, start, end,
945 delalloc_end, NULL,
c2790a2e 946 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc 947 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
948 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
949 PAGE_END_WRITEBACK);
18513091
WX
950 btrfs_free_reserved_data_space_noquota(inode, start,
951 end - start + 1);
771ed689 952 *nr_written = *nr_written +
09cbfeaf 953 (end - start + PAGE_SIZE) / PAGE_SIZE;
771ed689 954 *page_started = 1;
771ed689 955 goto out;
79787eaa 956 } else if (ret < 0) {
79787eaa 957 goto out_unlock;
771ed689
CM
958 }
959 }
960
961 BUG_ON(disk_num_bytes >
0b246afa 962 btrfs_super_total_bytes(fs_info->super_copy));
771ed689 963
4b46fce2 964 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
dcdbc059
NB
965 btrfs_drop_extent_cache(BTRFS_I(inode), start,
966 start + num_bytes - 1, 0);
771ed689 967
d397712b 968 while (disk_num_bytes > 0) {
a791e35e
CM
969 unsigned long op;
970
287a0ab9 971 cur_alloc_size = disk_num_bytes;
18513091 972 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
0b246afa 973 fs_info->sectorsize, 0, alloc_hint,
e570fd27 974 &ins, 1, 1);
00361589 975 if (ret < 0)
79787eaa 976 goto out_unlock;
d397712b 977
771ed689 978 ram_size = ins.offset;
6f9994db
LB
979 em = create_io_em(inode, start, ins.offset, /* len */
980 start, /* orig_start */
981 ins.objectid, /* block_start */
982 ins.offset, /* block_len */
983 ins.offset, /* orig_block_len */
984 ram_size, /* ram_bytes */
985 BTRFS_COMPRESS_NONE, /* compress_type */
1af4a0aa 986 BTRFS_ORDERED_REGULAR /* type */);
6f9994db 987 if (IS_ERR(em))
ace68bac 988 goto out_reserve;
6f9994db 989 free_extent_map(em);
e6dcd2dc 990
98d20f67 991 cur_alloc_size = ins.offset;
e6dcd2dc 992 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 993 ram_size, cur_alloc_size, 0);
ace68bac 994 if (ret)
d9f85963 995 goto out_drop_extent_cache;
c8b97818 996
17d217fe
YZ
997 if (root->root_key.objectid ==
998 BTRFS_DATA_RELOC_TREE_OBJECTID) {
999 ret = btrfs_reloc_clone_csums(inode, start,
1000 cur_alloc_size);
00361589 1001 if (ret)
d9f85963 1002 goto out_drop_extent_cache;
17d217fe
YZ
1003 }
1004
0b246afa 1005 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9cfa3e34 1006
d397712b 1007 if (disk_num_bytes < cur_alloc_size)
3b951516 1008 break;
d397712b 1009
c8b97818
CM
1010 /* we're not doing compressed IO, don't unlock the first
1011 * page (which the caller expects to stay locked), don't
1012 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
1013 *
1014 * Do set the Private2 bit so we know this page was properly
1015 * setup for writepage
c8b97818 1016 */
c2790a2e
JB
1017 op = unlock ? PAGE_UNLOCK : 0;
1018 op |= PAGE_SET_PRIVATE2;
a791e35e 1019
c2790a2e 1020 extent_clear_unlock_delalloc(inode, start,
ba8b04c1
QW
1021 start + ram_size - 1,
1022 delalloc_end, locked_page,
c2790a2e
JB
1023 EXTENT_LOCKED | EXTENT_DELALLOC,
1024 op);
c8b97818 1025 disk_num_bytes -= cur_alloc_size;
c59f8951
CM
1026 num_bytes -= cur_alloc_size;
1027 alloc_hint = ins.objectid + ins.offset;
1028 start += cur_alloc_size;
b888db2b 1029 }
79787eaa 1030out:
be20aa9d 1031 return ret;
b7d5b0a8 1032
d9f85963 1033out_drop_extent_cache:
dcdbc059 1034 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
ace68bac 1035out_reserve:
0b246afa 1036 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
2ff7e61e 1037 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
79787eaa 1038out_unlock:
ba8b04c1
QW
1039 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1040 locked_page,
151a41bc
JB
1041 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1042 EXTENT_DELALLOC | EXTENT_DEFRAG,
1043 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1044 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
79787eaa 1045 goto out;
771ed689 1046}
c8b97818 1047
771ed689
CM
1048/*
1049 * work queue call back to started compression on a file and pages
1050 */
1051static noinline void async_cow_start(struct btrfs_work *work)
1052{
1053 struct async_cow *async_cow;
1054 int num_added = 0;
1055 async_cow = container_of(work, struct async_cow, work);
1056
1057 compress_file_range(async_cow->inode, async_cow->locked_page,
1058 async_cow->start, async_cow->end, async_cow,
1059 &num_added);
8180ef88 1060 if (num_added == 0) {
cb77fcd8 1061 btrfs_add_delayed_iput(async_cow->inode);
771ed689 1062 async_cow->inode = NULL;
8180ef88 1063 }
771ed689
CM
1064}
1065
1066/*
1067 * work queue call back to submit previously compressed pages
1068 */
1069static noinline void async_cow_submit(struct btrfs_work *work)
1070{
0b246afa 1071 struct btrfs_fs_info *fs_info;
771ed689
CM
1072 struct async_cow *async_cow;
1073 struct btrfs_root *root;
1074 unsigned long nr_pages;
1075
1076 async_cow = container_of(work, struct async_cow, work);
1077
1078 root = async_cow->root;
0b246afa 1079 fs_info = root->fs_info;
09cbfeaf
KS
1080 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1081 PAGE_SHIFT;
771ed689 1082
ee863954
DS
1083 /*
1084 * atomic_sub_return implies a barrier for waitqueue_active
1085 */
0b246afa 1086 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
ee22184b 1087 5 * SZ_1M &&
0b246afa
JM
1088 waitqueue_active(&fs_info->async_submit_wait))
1089 wake_up(&fs_info->async_submit_wait);
771ed689 1090
d397712b 1091 if (async_cow->inode)
771ed689 1092 submit_compressed_extents(async_cow->inode, async_cow);
771ed689 1093}
c8b97818 1094
771ed689
CM
1095static noinline void async_cow_free(struct btrfs_work *work)
1096{
1097 struct async_cow *async_cow;
1098 async_cow = container_of(work, struct async_cow, work);
8180ef88 1099 if (async_cow->inode)
cb77fcd8 1100 btrfs_add_delayed_iput(async_cow->inode);
771ed689
CM
1101 kfree(async_cow);
1102}
1103
1104static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1105 u64 start, u64 end, int *page_started,
1106 unsigned long *nr_written)
1107{
0b246afa 1108 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
771ed689
CM
1109 struct async_cow *async_cow;
1110 struct btrfs_root *root = BTRFS_I(inode)->root;
1111 unsigned long nr_pages;
1112 u64 cur_end;
771ed689 1113
a3429ab7
CM
1114 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1115 1, 0, NULL, GFP_NOFS);
d397712b 1116 while (start < end) {
771ed689 1117 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
79787eaa 1118 BUG_ON(!async_cow); /* -ENOMEM */
8180ef88 1119 async_cow->inode = igrab(inode);
771ed689
CM
1120 async_cow->root = root;
1121 async_cow->locked_page = locked_page;
1122 async_cow->start = start;
1123
f79707b0 1124 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
0b246afa 1125 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
771ed689
CM
1126 cur_end = end;
1127 else
ee22184b 1128 cur_end = min(end, start + SZ_512K - 1);
771ed689
CM
1129
1130 async_cow->end = cur_end;
1131 INIT_LIST_HEAD(&async_cow->extents);
1132
9e0af237
LB
1133 btrfs_init_work(&async_cow->work,
1134 btrfs_delalloc_helper,
1135 async_cow_start, async_cow_submit,
1136 async_cow_free);
771ed689 1137
09cbfeaf
KS
1138 nr_pages = (cur_end - start + PAGE_SIZE) >>
1139 PAGE_SHIFT;
0b246afa 1140 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
771ed689 1141
0b246afa 1142 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
771ed689 1143
0b246afa
JM
1144 while (atomic_read(&fs_info->async_submit_draining) &&
1145 atomic_read(&fs_info->async_delalloc_pages)) {
1146 wait_event(fs_info->async_submit_wait,
1147 (atomic_read(&fs_info->async_delalloc_pages) ==
1148 0));
771ed689
CM
1149 }
1150
1151 *nr_written += nr_pages;
1152 start = cur_end + 1;
1153 }
1154 *page_started = 1;
1155 return 0;
be20aa9d
CM
1156}
1157
2ff7e61e 1158static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
17d217fe
YZ
1159 u64 bytenr, u64 num_bytes)
1160{
1161 int ret;
1162 struct btrfs_ordered_sum *sums;
1163 LIST_HEAD(list);
1164
0b246afa 1165 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
a2de733c 1166 bytenr + num_bytes - 1, &list, 0);
17d217fe
YZ
1167 if (ret == 0 && list_empty(&list))
1168 return 0;
1169
1170 while (!list_empty(&list)) {
1171 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1172 list_del(&sums->list);
1173 kfree(sums);
1174 }
1175 return 1;
1176}
1177
d352ac68
CM
1178/*
1179 * when nowcow writeback call back. This checks for snapshots or COW copies
1180 * of the extents that exist in the file, and COWs the file as required.
1181 *
1182 * If no cow copies or snapshots exist, we write directly to the existing
1183 * blocks on disk
1184 */
7f366cfe
CM
1185static noinline int run_delalloc_nocow(struct inode *inode,
1186 struct page *locked_page,
771ed689
CM
1187 u64 start, u64 end, int *page_started, int force,
1188 unsigned long *nr_written)
be20aa9d 1189{
0b246afa 1190 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
be20aa9d
CM
1191 struct btrfs_root *root = BTRFS_I(inode)->root;
1192 struct extent_buffer *leaf;
be20aa9d 1193 struct btrfs_path *path;
80ff3856 1194 struct btrfs_file_extent_item *fi;
be20aa9d 1195 struct btrfs_key found_key;
6f9994db 1196 struct extent_map *em;
80ff3856
YZ
1197 u64 cow_start;
1198 u64 cur_offset;
1199 u64 extent_end;
5d4f98a2 1200 u64 extent_offset;
80ff3856
YZ
1201 u64 disk_bytenr;
1202 u64 num_bytes;
b4939680 1203 u64 disk_num_bytes;
cc95bef6 1204 u64 ram_bytes;
80ff3856 1205 int extent_type;
79787eaa 1206 int ret, err;
d899e052 1207 int type;
80ff3856
YZ
1208 int nocow;
1209 int check_prev = 1;
82d5902d 1210 bool nolock;
4a0cc7ca 1211 u64 ino = btrfs_ino(BTRFS_I(inode));
be20aa9d
CM
1212
1213 path = btrfs_alloc_path();
17ca04af 1214 if (!path) {
ba8b04c1
QW
1215 extent_clear_unlock_delalloc(inode, start, end, end,
1216 locked_page,
c2790a2e 1217 EXTENT_LOCKED | EXTENT_DELALLOC |
151a41bc
JB
1218 EXTENT_DO_ACCOUNTING |
1219 EXTENT_DEFRAG, PAGE_UNLOCK |
c2790a2e
JB
1220 PAGE_CLEAR_DIRTY |
1221 PAGE_SET_WRITEBACK |
1222 PAGE_END_WRITEBACK);
d8926bb3 1223 return -ENOMEM;
17ca04af 1224 }
82d5902d 1225
70ddc553 1226 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
82d5902d 1227
80ff3856
YZ
1228 cow_start = (u64)-1;
1229 cur_offset = start;
1230 while (1) {
e4c3b2dc 1231 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
80ff3856 1232 cur_offset, 0);
d788a349 1233 if (ret < 0)
79787eaa 1234 goto error;
80ff3856
YZ
1235 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1236 leaf = path->nodes[0];
1237 btrfs_item_key_to_cpu(leaf, &found_key,
1238 path->slots[0] - 1);
33345d01 1239 if (found_key.objectid == ino &&
80ff3856
YZ
1240 found_key.type == BTRFS_EXTENT_DATA_KEY)
1241 path->slots[0]--;
1242 }
1243 check_prev = 0;
1244next_slot:
1245 leaf = path->nodes[0];
1246 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1247 ret = btrfs_next_leaf(root, path);
d788a349 1248 if (ret < 0)
79787eaa 1249 goto error;
80ff3856
YZ
1250 if (ret > 0)
1251 break;
1252 leaf = path->nodes[0];
1253 }
be20aa9d 1254
80ff3856
YZ
1255 nocow = 0;
1256 disk_bytenr = 0;
17d217fe 1257 num_bytes = 0;
80ff3856
YZ
1258 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1259
1d512cb7
FM
1260 if (found_key.objectid > ino)
1261 break;
1262 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1263 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1264 path->slots[0]++;
1265 goto next_slot;
1266 }
1267 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
80ff3856
YZ
1268 found_key.offset > end)
1269 break;
1270
1271 if (found_key.offset > cur_offset) {
1272 extent_end = found_key.offset;
e9061e21 1273 extent_type = 0;
80ff3856
YZ
1274 goto out_check;
1275 }
1276
1277 fi = btrfs_item_ptr(leaf, path->slots[0],
1278 struct btrfs_file_extent_item);
1279 extent_type = btrfs_file_extent_type(leaf, fi);
1280
cc95bef6 1281 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
d899e052
YZ
1282 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1283 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1284 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1285 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1286 extent_end = found_key.offset +
1287 btrfs_file_extent_num_bytes(leaf, fi);
b4939680
JB
1288 disk_num_bytes =
1289 btrfs_file_extent_disk_num_bytes(leaf, fi);
80ff3856
YZ
1290 if (extent_end <= start) {
1291 path->slots[0]++;
1292 goto next_slot;
1293 }
17d217fe
YZ
1294 if (disk_bytenr == 0)
1295 goto out_check;
80ff3856
YZ
1296 if (btrfs_file_extent_compression(leaf, fi) ||
1297 btrfs_file_extent_encryption(leaf, fi) ||
1298 btrfs_file_extent_other_encoding(leaf, fi))
1299 goto out_check;
d899e052
YZ
1300 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1301 goto out_check;
2ff7e61e 1302 if (btrfs_extent_readonly(fs_info, disk_bytenr))
80ff3856 1303 goto out_check;
e4c3b2dc 1304 if (btrfs_cross_ref_exist(root, ino,
5d4f98a2
YZ
1305 found_key.offset -
1306 extent_offset, disk_bytenr))
17d217fe 1307 goto out_check;
5d4f98a2 1308 disk_bytenr += extent_offset;
17d217fe
YZ
1309 disk_bytenr += cur_offset - found_key.offset;
1310 num_bytes = min(end + 1, extent_end) - cur_offset;
e9894fd3
WS
1311 /*
1312 * if there are pending snapshots for this root,
1313 * we fall into common COW way.
1314 */
1315 if (!nolock) {
9ea24bbe 1316 err = btrfs_start_write_no_snapshoting(root);
e9894fd3
WS
1317 if (!err)
1318 goto out_check;
1319 }
17d217fe
YZ
1320 /*
1321 * force cow if csum exists in the range.
1322 * this ensure that csum for a given extent are
1323 * either valid or do not exist.
1324 */
2ff7e61e 1325 if (csum_exist_in_range(fs_info, disk_bytenr,
91e1f56a
RK
1326 num_bytes)) {
1327 if (!nolock)
1328 btrfs_end_write_no_snapshoting(root);
17d217fe 1329 goto out_check;
91e1f56a
RK
1330 }
1331 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1332 if (!nolock)
1333 btrfs_end_write_no_snapshoting(root);
f78c436c 1334 goto out_check;
91e1f56a 1335 }
80ff3856
YZ
1336 nocow = 1;
1337 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1338 extent_end = found_key.offset +
514ac8ad
CM
1339 btrfs_file_extent_inline_len(leaf,
1340 path->slots[0], fi);
da17066c 1341 extent_end = ALIGN(extent_end,
0b246afa 1342 fs_info->sectorsize);
80ff3856
YZ
1343 } else {
1344 BUG_ON(1);
1345 }
1346out_check:
1347 if (extent_end <= start) {
1348 path->slots[0]++;
e9894fd3 1349 if (!nolock && nocow)
9ea24bbe 1350 btrfs_end_write_no_snapshoting(root);
f78c436c 1351 if (nocow)
0b246afa 1352 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
80ff3856
YZ
1353 goto next_slot;
1354 }
1355 if (!nocow) {
1356 if (cow_start == (u64)-1)
1357 cow_start = cur_offset;
1358 cur_offset = extent_end;
1359 if (cur_offset > end)
1360 break;
1361 path->slots[0]++;
1362 goto next_slot;
7ea394f1
YZ
1363 }
1364
b3b4aa74 1365 btrfs_release_path(path);
80ff3856 1366 if (cow_start != (u64)-1) {
00361589
JB
1367 ret = cow_file_range(inode, locked_page,
1368 cow_start, found_key.offset - 1,
dda3245e
WX
1369 end, page_started, nr_written, 1,
1370 NULL);
e9894fd3
WS
1371 if (ret) {
1372 if (!nolock && nocow)
9ea24bbe 1373 btrfs_end_write_no_snapshoting(root);
f78c436c 1374 if (nocow)
0b246afa 1375 btrfs_dec_nocow_writers(fs_info,
f78c436c 1376 disk_bytenr);
79787eaa 1377 goto error;
e9894fd3 1378 }
80ff3856 1379 cow_start = (u64)-1;
7ea394f1 1380 }
80ff3856 1381
d899e052 1382 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6f9994db
LB
1383 u64 orig_start = found_key.offset - extent_offset;
1384
1385 em = create_io_em(inode, cur_offset, num_bytes,
1386 orig_start,
1387 disk_bytenr, /* block_start */
1388 num_bytes, /* block_len */
1389 disk_num_bytes, /* orig_block_len */
1390 ram_bytes, BTRFS_COMPRESS_NONE,
1391 BTRFS_ORDERED_PREALLOC);
1392 if (IS_ERR(em)) {
1393 if (!nolock && nocow)
1394 btrfs_end_write_no_snapshoting(root);
1395 if (nocow)
1396 btrfs_dec_nocow_writers(fs_info,
1397 disk_bytenr);
1398 ret = PTR_ERR(em);
1399 goto error;
d899e052 1400 }
6f9994db
LB
1401 free_extent_map(em);
1402 }
1403
1404 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
d899e052
YZ
1405 type = BTRFS_ORDERED_PREALLOC;
1406 } else {
1407 type = BTRFS_ORDERED_NOCOW;
1408 }
80ff3856
YZ
1409
1410 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052 1411 num_bytes, num_bytes, type);
f78c436c 1412 if (nocow)
0b246afa 1413 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
79787eaa 1414 BUG_ON(ret); /* -ENOMEM */
771ed689 1415
efa56464
YZ
1416 if (root->root_key.objectid ==
1417 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1418 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1419 num_bytes);
e9894fd3
WS
1420 if (ret) {
1421 if (!nolock && nocow)
9ea24bbe 1422 btrfs_end_write_no_snapshoting(root);
79787eaa 1423 goto error;
e9894fd3 1424 }
efa56464
YZ
1425 }
1426
c2790a2e 1427 extent_clear_unlock_delalloc(inode, cur_offset,
ba8b04c1 1428 cur_offset + num_bytes - 1, end,
c2790a2e 1429 locked_page, EXTENT_LOCKED |
18513091
WX
1430 EXTENT_DELALLOC |
1431 EXTENT_CLEAR_DATA_RESV,
1432 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1433
e9894fd3 1434 if (!nolock && nocow)
9ea24bbe 1435 btrfs_end_write_no_snapshoting(root);
80ff3856
YZ
1436 cur_offset = extent_end;
1437 if (cur_offset > end)
1438 break;
be20aa9d 1439 }
b3b4aa74 1440 btrfs_release_path(path);
80ff3856 1441
17ca04af 1442 if (cur_offset <= end && cow_start == (u64)-1) {
80ff3856 1443 cow_start = cur_offset;
17ca04af
JB
1444 cur_offset = end;
1445 }
1446
80ff3856 1447 if (cow_start != (u64)-1) {
dda3245e
WX
1448 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1449 page_started, nr_written, 1, NULL);
d788a349 1450 if (ret)
79787eaa 1451 goto error;
80ff3856
YZ
1452 }
1453
79787eaa 1454error:
17ca04af 1455 if (ret && cur_offset < end)
ba8b04c1 1456 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
c2790a2e 1457 locked_page, EXTENT_LOCKED |
151a41bc
JB
1458 EXTENT_DELALLOC | EXTENT_DEFRAG |
1459 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1460 PAGE_CLEAR_DIRTY |
c2790a2e
JB
1461 PAGE_SET_WRITEBACK |
1462 PAGE_END_WRITEBACK);
7ea394f1 1463 btrfs_free_path(path);
79787eaa 1464 return ret;
be20aa9d
CM
1465}
1466
47059d93
WS
1467static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1468{
1469
1470 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1471 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1472 return 0;
1473
1474 /*
1475 * @defrag_bytes is a hint value, no spinlock held here,
1476 * if is not zero, it means the file is defragging.
1477 * Force cow if given extent needs to be defragged.
1478 */
1479 if (BTRFS_I(inode)->defrag_bytes &&
1480 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1481 EXTENT_DEFRAG, 0, NULL))
1482 return 1;
1483
1484 return 0;
1485}
1486
d352ac68
CM
1487/*
1488 * extent_io.c call back to do delayed allocation processing
1489 */
c8b97818 1490static int run_delalloc_range(struct inode *inode, struct page *locked_page,
771ed689
CM
1491 u64 start, u64 end, int *page_started,
1492 unsigned long *nr_written)
be20aa9d 1493{
be20aa9d 1494 int ret;
47059d93 1495 int force_cow = need_force_cow(inode, start, end);
a2135011 1496
47059d93 1497 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
c8b97818 1498 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1499 page_started, 1, nr_written);
47059d93 1500 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
d899e052 1501 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1502 page_started, 0, nr_written);
7816030e 1503 } else if (!inode_need_compress(inode)) {
dda3245e
WX
1504 ret = cow_file_range(inode, locked_page, start, end, end,
1505 page_started, nr_written, 1, NULL);
7ddf5a42
JB
1506 } else {
1507 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1508 &BTRFS_I(inode)->runtime_flags);
771ed689 1509 ret = cow_file_range_async(inode, locked_page, start, end,
d397712b 1510 page_started, nr_written);
7ddf5a42 1511 }
b888db2b
CM
1512 return ret;
1513}
1514
1bf85046
JM
1515static void btrfs_split_extent_hook(struct inode *inode,
1516 struct extent_state *orig, u64 split)
9ed74f2d 1517{
dcab6a3b
JB
1518 u64 size;
1519
0ca1f7ce 1520 /* not delalloc, ignore it */
9ed74f2d 1521 if (!(orig->state & EXTENT_DELALLOC))
1bf85046 1522 return;
9ed74f2d 1523
dcab6a3b
JB
1524 size = orig->end - orig->start + 1;
1525 if (size > BTRFS_MAX_EXTENT_SIZE) {
823bb20a 1526 u32 num_extents;
dcab6a3b
JB
1527 u64 new_size;
1528
1529 /*
ba117213
JB
1530 * See the explanation in btrfs_merge_extent_hook, the same
1531 * applies here, just in reverse.
dcab6a3b
JB
1532 */
1533 new_size = orig->end - split + 1;
823bb20a 1534 num_extents = count_max_extents(new_size);
ba117213 1535 new_size = split - orig->start;
823bb20a
DS
1536 num_extents += count_max_extents(new_size);
1537 if (count_max_extents(size) >= num_extents)
dcab6a3b
JB
1538 return;
1539 }
1540
9e0baf60
JB
1541 spin_lock(&BTRFS_I(inode)->lock);
1542 BTRFS_I(inode)->outstanding_extents++;
1543 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1544}
1545
1546/*
1547 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1548 * extents so we can keep track of new extents that are just merged onto old
1549 * extents, such as when we are doing sequential writes, so we can properly
1550 * account for the metadata space we'll need.
1551 */
1bf85046
JM
1552static void btrfs_merge_extent_hook(struct inode *inode,
1553 struct extent_state *new,
1554 struct extent_state *other)
9ed74f2d 1555{
dcab6a3b 1556 u64 new_size, old_size;
823bb20a 1557 u32 num_extents;
dcab6a3b 1558
9ed74f2d
JB
1559 /* not delalloc, ignore it */
1560 if (!(other->state & EXTENT_DELALLOC))
1bf85046 1561 return;
9ed74f2d 1562
8461a3de
JB
1563 if (new->start > other->start)
1564 new_size = new->end - other->start + 1;
1565 else
1566 new_size = other->end - new->start + 1;
dcab6a3b
JB
1567
1568 /* we're not bigger than the max, unreserve the space and go */
1569 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1570 spin_lock(&BTRFS_I(inode)->lock);
1571 BTRFS_I(inode)->outstanding_extents--;
1572 spin_unlock(&BTRFS_I(inode)->lock);
1573 return;
1574 }
1575
1576 /*
ba117213
JB
1577 * We have to add up either side to figure out how many extents were
1578 * accounted for before we merged into one big extent. If the number of
1579 * extents we accounted for is <= the amount we need for the new range
1580 * then we can return, otherwise drop. Think of it like this
1581 *
1582 * [ 4k][MAX_SIZE]
1583 *
1584 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1585 * need 2 outstanding extents, on one side we have 1 and the other side
1586 * we have 1 so they are == and we can return. But in this case
1587 *
1588 * [MAX_SIZE+4k][MAX_SIZE+4k]
1589 *
1590 * Each range on their own accounts for 2 extents, but merged together
1591 * they are only 3 extents worth of accounting, so we need to drop in
1592 * this case.
dcab6a3b 1593 */
ba117213 1594 old_size = other->end - other->start + 1;
823bb20a 1595 num_extents = count_max_extents(old_size);
ba117213 1596 old_size = new->end - new->start + 1;
823bb20a
DS
1597 num_extents += count_max_extents(old_size);
1598 if (count_max_extents(new_size) >= num_extents)
dcab6a3b
JB
1599 return;
1600
9e0baf60
JB
1601 spin_lock(&BTRFS_I(inode)->lock);
1602 BTRFS_I(inode)->outstanding_extents--;
1603 spin_unlock(&BTRFS_I(inode)->lock);
9ed74f2d
JB
1604}
1605
eb73c1b7
MX
1606static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1607 struct inode *inode)
1608{
0b246afa
JM
1609 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1610
eb73c1b7
MX
1611 spin_lock(&root->delalloc_lock);
1612 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1613 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1614 &root->delalloc_inodes);
1615 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1616 &BTRFS_I(inode)->runtime_flags);
1617 root->nr_delalloc_inodes++;
1618 if (root->nr_delalloc_inodes == 1) {
0b246afa 1619 spin_lock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1620 BUG_ON(!list_empty(&root->delalloc_root));
1621 list_add_tail(&root->delalloc_root,
0b246afa
JM
1622 &fs_info->delalloc_roots);
1623 spin_unlock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1624 }
1625 }
1626 spin_unlock(&root->delalloc_lock);
1627}
1628
1629static void btrfs_del_delalloc_inode(struct btrfs_root *root,
9e3e97f4 1630 struct btrfs_inode *inode)
eb73c1b7 1631{
9e3e97f4 1632 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
0b246afa 1633
eb73c1b7 1634 spin_lock(&root->delalloc_lock);
9e3e97f4
NB
1635 if (!list_empty(&inode->delalloc_inodes)) {
1636 list_del_init(&inode->delalloc_inodes);
eb73c1b7 1637 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
9e3e97f4 1638 &inode->runtime_flags);
eb73c1b7
MX
1639 root->nr_delalloc_inodes--;
1640 if (!root->nr_delalloc_inodes) {
0b246afa 1641 spin_lock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1642 BUG_ON(list_empty(&root->delalloc_root));
1643 list_del_init(&root->delalloc_root);
0b246afa 1644 spin_unlock(&fs_info->delalloc_root_lock);
eb73c1b7
MX
1645 }
1646 }
1647 spin_unlock(&root->delalloc_lock);
1648}
1649
d352ac68
CM
1650/*
1651 * extent_io.c set_bit_hook, used to track delayed allocation
1652 * bytes in this file, and to maintain the list of inodes that
1653 * have pending delalloc work to be done.
1654 */
1bf85046 1655static void btrfs_set_bit_hook(struct inode *inode,
9ee49a04 1656 struct extent_state *state, unsigned *bits)
291d673e 1657{
9ed74f2d 1658
0b246afa
JM
1659 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1660
47059d93
WS
1661 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1662 WARN_ON(1);
75eff68e
CM
1663 /*
1664 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1665 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1666 * bit, which is only set or cleared with irqs on
1667 */
0ca1f7ce 1668 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
291d673e 1669 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 1670 u64 len = state->end + 1 - state->start;
70ddc553 1671 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
9ed74f2d 1672
9e0baf60 1673 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1674 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60
JB
1675 } else {
1676 spin_lock(&BTRFS_I(inode)->lock);
1677 BTRFS_I(inode)->outstanding_extents++;
1678 spin_unlock(&BTRFS_I(inode)->lock);
1679 }
287a0ab9 1680
6a3891c5 1681 /* For sanity tests */
0b246afa 1682 if (btrfs_is_testing(fs_info))
6a3891c5
JB
1683 return;
1684
0b246afa
JM
1685 __percpu_counter_add(&fs_info->delalloc_bytes, len,
1686 fs_info->delalloc_batch);
df0af1a5 1687 spin_lock(&BTRFS_I(inode)->lock);
0ca1f7ce 1688 BTRFS_I(inode)->delalloc_bytes += len;
47059d93
WS
1689 if (*bits & EXTENT_DEFRAG)
1690 BTRFS_I(inode)->defrag_bytes += len;
df0af1a5 1691 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
eb73c1b7
MX
1692 &BTRFS_I(inode)->runtime_flags))
1693 btrfs_add_delalloc_inodes(root, inode);
df0af1a5 1694 spin_unlock(&BTRFS_I(inode)->lock);
291d673e 1695 }
291d673e
CM
1696}
1697
d352ac68
CM
1698/*
1699 * extent_io.c clear_bit_hook, see set_bit_hook for why
1700 */
6fc0ef68 1701static void btrfs_clear_bit_hook(struct btrfs_inode *inode,
41074888 1702 struct extent_state *state,
9ee49a04 1703 unsigned *bits)
291d673e 1704{
6fc0ef68 1705 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
47059d93 1706 u64 len = state->end + 1 - state->start;
823bb20a 1707 u32 num_extents = count_max_extents(len);
47059d93 1708
6fc0ef68 1709 spin_lock(&inode->lock);
47059d93 1710 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
6fc0ef68
NB
1711 inode->defrag_bytes -= len;
1712 spin_unlock(&inode->lock);
47059d93 1713
75eff68e
CM
1714 /*
1715 * set_bit and clear bit hooks normally require _irqsave/restore
27160b6b 1716 * but in this case, we are only testing for the DELALLOC
75eff68e
CM
1717 * bit, which is only set or cleared with irqs on
1718 */
0ca1f7ce 1719 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
6fc0ef68 1720 struct btrfs_root *root = inode->root;
83eea1f1 1721 bool do_list = !btrfs_is_free_space_inode(inode);
bcbfce8a 1722
9e0baf60 1723 if (*bits & EXTENT_FIRST_DELALLOC) {
0ca1f7ce 1724 *bits &= ~EXTENT_FIRST_DELALLOC;
9e0baf60 1725 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
6fc0ef68
NB
1726 spin_lock(&inode->lock);
1727 inode->outstanding_extents -= num_extents;
1728 spin_unlock(&inode->lock);
9e0baf60 1729 }
0ca1f7ce 1730
b6d08f06
JB
1731 /*
1732 * We don't reserve metadata space for space cache inodes so we
1733 * don't need to call dellalloc_release_metadata if there is an
1734 * error.
1735 */
1736 if (*bits & EXTENT_DO_ACCOUNTING &&
0b246afa 1737 root != fs_info->tree_root)
0ca1f7ce
YZ
1738 btrfs_delalloc_release_metadata(inode, len);
1739
6a3891c5 1740 /* For sanity tests. */
0b246afa 1741 if (btrfs_is_testing(fs_info))
6a3891c5
JB
1742 return;
1743
0cb59c99 1744 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
18513091
WX
1745 && do_list && !(state->state & EXTENT_NORESERVE)
1746 && (*bits & (EXTENT_DO_ACCOUNTING |
1747 EXTENT_CLEAR_DATA_RESV)))
6fc0ef68
NB
1748 btrfs_free_reserved_data_space_noquota(
1749 &inode->vfs_inode,
51773bec 1750 state->start, len);
9ed74f2d 1751
0b246afa
JM
1752 __percpu_counter_add(&fs_info->delalloc_bytes, -len,
1753 fs_info->delalloc_batch);
6fc0ef68
NB
1754 spin_lock(&inode->lock);
1755 inode->delalloc_bytes -= len;
1756 if (do_list && inode->delalloc_bytes == 0 &&
df0af1a5 1757 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
9e3e97f4 1758 &inode->runtime_flags))
eb73c1b7 1759 btrfs_del_delalloc_inode(root, inode);
6fc0ef68 1760 spin_unlock(&inode->lock);
291d673e 1761 }
291d673e
CM
1762}
1763
d352ac68
CM
1764/*
1765 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1766 * we don't create bios that span stripes or chunks
6f034ece
LB
1767 *
1768 * return 1 if page cannot be merged to bio
1769 * return 0 if page can be merged to bio
1770 * return error otherwise
d352ac68 1771 */
81a75f67 1772int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
c8b97818
CM
1773 size_t size, struct bio *bio,
1774 unsigned long bio_flags)
239b14b3 1775{
0b246afa
JM
1776 struct inode *inode = page->mapping->host;
1777 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4f024f37 1778 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
239b14b3
CM
1779 u64 length = 0;
1780 u64 map_length;
239b14b3
CM
1781 int ret;
1782
771ed689
CM
1783 if (bio_flags & EXTENT_BIO_COMPRESSED)
1784 return 0;
1785
4f024f37 1786 length = bio->bi_iter.bi_size;
239b14b3 1787 map_length = length;
0b246afa
JM
1788 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1789 NULL, 0);
6f034ece
LB
1790 if (ret < 0)
1791 return ret;
d397712b 1792 if (map_length < length + size)
239b14b3 1793 return 1;
3444a972 1794 return 0;
239b14b3
CM
1795}
1796
d352ac68
CM
1797/*
1798 * in order to insert checksums into the metadata in large chunks,
1799 * we wait until bio submission time. All the pages in the bio are
1800 * checksummed and sums are attached onto the ordered extent record.
1801 *
1802 * At IO completion time the cums attached on the ordered extent record
1803 * are inserted into the btree
1804 */
81a75f67
MC
1805static int __btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
1806 int mirror_num, unsigned long bio_flags,
eaf25d93 1807 u64 bio_offset)
065631f6 1808{
065631f6 1809 int ret = 0;
e015640f 1810
2ff7e61e 1811 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
79787eaa 1812 BUG_ON(ret); /* -ENOMEM */
4a69a410
CM
1813 return 0;
1814}
e015640f 1815
4a69a410
CM
1816/*
1817 * in order to insert checksums into the metadata in large chunks,
1818 * we wait until bio submission time. All the pages in the bio are
1819 * checksummed and sums are attached onto the ordered extent record.
1820 *
1821 * At IO completion time the cums attached on the ordered extent record
1822 * are inserted into the btree
1823 */
81a75f67 1824static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
eaf25d93
CM
1825 int mirror_num, unsigned long bio_flags,
1826 u64 bio_offset)
4a69a410 1827{
2ff7e61e 1828 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
61891923
SB
1829 int ret;
1830
2ff7e61e 1831 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
4246a0b6
CH
1832 if (ret) {
1833 bio->bi_error = ret;
1834 bio_endio(bio);
1835 }
61891923 1836 return ret;
44b8bd7e
CM
1837}
1838
d352ac68 1839/*
cad321ad
CM
1840 * extent_io.c submission hook. This does the right thing for csum calculation
1841 * on write, or reading the csums from the tree before a read
d352ac68 1842 */
81a75f67 1843static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
eaf25d93
CM
1844 int mirror_num, unsigned long bio_flags,
1845 u64 bio_offset)
44b8bd7e 1846{
0b246afa 1847 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
44b8bd7e 1848 struct btrfs_root *root = BTRFS_I(inode)->root;
0d51e28a 1849 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
44b8bd7e 1850 int ret = 0;
19b9bdb0 1851 int skip_sum;
b812ce28 1852 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
44b8bd7e 1853
6cbff00f 1854 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 1855
70ddc553 1856 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
0d51e28a 1857 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
0417341e 1858
37226b21 1859 if (bio_op(bio) != REQ_OP_WRITE) {
0b246afa 1860 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
5fd02043 1861 if (ret)
61891923 1862 goto out;
5fd02043 1863
d20f7043 1864 if (bio_flags & EXTENT_BIO_COMPRESSED) {
61891923
SB
1865 ret = btrfs_submit_compressed_read(inode, bio,
1866 mirror_num,
1867 bio_flags);
1868 goto out;
c2db1073 1869 } else if (!skip_sum) {
2ff7e61e 1870 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
c2db1073 1871 if (ret)
61891923 1872 goto out;
c2db1073 1873 }
4d1b5fb4 1874 goto mapit;
b812ce28 1875 } else if (async && !skip_sum) {
17d217fe
YZ
1876 /* csum items have already been cloned */
1877 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1878 goto mapit;
19b9bdb0 1879 /* we're doing a write, do the async checksumming */
0b246afa
JM
1880 ret = btrfs_wq_submit_bio(fs_info, inode, bio, mirror_num,
1881 bio_flags, bio_offset,
1882 __btrfs_submit_bio_start,
1883 __btrfs_submit_bio_done);
61891923 1884 goto out;
b812ce28 1885 } else if (!skip_sum) {
2ff7e61e 1886 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
b812ce28
JB
1887 if (ret)
1888 goto out;
19b9bdb0
CM
1889 }
1890
0b86a832 1891mapit:
2ff7e61e 1892 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
61891923
SB
1893
1894out:
4246a0b6
CH
1895 if (ret < 0) {
1896 bio->bi_error = ret;
1897 bio_endio(bio);
1898 }
61891923 1899 return ret;
065631f6 1900}
6885f308 1901
d352ac68
CM
1902/*
1903 * given a list of ordered sums record them in the inode. This happens
1904 * at IO completion time based on sums calculated at bio submission time.
1905 */
ba1da2f4 1906static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
df9f628e 1907 struct inode *inode, struct list_head *list)
e6dcd2dc 1908{
e6dcd2dc
CM
1909 struct btrfs_ordered_sum *sum;
1910
c6e30871 1911 list_for_each_entry(sum, list, list) {
39847c4d 1912 trans->adding_csums = 1;
d20f7043
CM
1913 btrfs_csum_file_blocks(trans,
1914 BTRFS_I(inode)->root->fs_info->csum_root, sum);
39847c4d 1915 trans->adding_csums = 0;
e6dcd2dc
CM
1916 }
1917 return 0;
1918}
1919
2ac55d41 1920int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
ba8b04c1 1921 struct extent_state **cached_state, int dedupe)
ea8c2819 1922{
09cbfeaf 1923 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
ea8c2819 1924 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
7cd8c752 1925 cached_state);
ea8c2819
CM
1926}
1927
d352ac68 1928/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
1929struct btrfs_writepage_fixup {
1930 struct page *page;
1931 struct btrfs_work work;
1932};
1933
b2950863 1934static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
1935{
1936 struct btrfs_writepage_fixup *fixup;
1937 struct btrfs_ordered_extent *ordered;
2ac55d41 1938 struct extent_state *cached_state = NULL;
247e743c
CM
1939 struct page *page;
1940 struct inode *inode;
1941 u64 page_start;
1942 u64 page_end;
87826df0 1943 int ret;
247e743c
CM
1944
1945 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1946 page = fixup->page;
4a096752 1947again:
247e743c
CM
1948 lock_page(page);
1949 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1950 ClearPageChecked(page);
1951 goto out_page;
1952 }
1953
1954 inode = page->mapping->host;
1955 page_start = page_offset(page);
09cbfeaf 1956 page_end = page_offset(page) + PAGE_SIZE - 1;
247e743c 1957
ff13db41 1958 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
d0082371 1959 &cached_state);
4a096752
CM
1960
1961 /* already ordered? We're done */
8b62b72b 1962 if (PagePrivate2(page))
247e743c 1963 goto out;
4a096752 1964
a776c6fa 1965 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
09cbfeaf 1966 PAGE_SIZE);
4a096752 1967 if (ordered) {
2ac55d41
JB
1968 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1969 page_end, &cached_state, GFP_NOFS);
4a096752
CM
1970 unlock_page(page);
1971 btrfs_start_ordered_extent(inode, ordered, 1);
87826df0 1972 btrfs_put_ordered_extent(ordered);
4a096752
CM
1973 goto again;
1974 }
247e743c 1975
7cf5b976 1976 ret = btrfs_delalloc_reserve_space(inode, page_start,
09cbfeaf 1977 PAGE_SIZE);
87826df0
JM
1978 if (ret) {
1979 mapping_set_error(page->mapping, ret);
1980 end_extent_writepage(page, ret, page_start, page_end);
1981 ClearPageChecked(page);
1982 goto out;
1983 }
1984
ba8b04c1
QW
1985 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
1986 0);
247e743c 1987 ClearPageChecked(page);
87826df0 1988 set_page_dirty(page);
247e743c 1989out:
2ac55d41
JB
1990 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1991 &cached_state, GFP_NOFS);
247e743c
CM
1992out_page:
1993 unlock_page(page);
09cbfeaf 1994 put_page(page);
b897abec 1995 kfree(fixup);
247e743c
CM
1996}
1997
1998/*
1999 * There are a few paths in the higher layers of the kernel that directly
2000 * set the page dirty bit without asking the filesystem if it is a
2001 * good idea. This causes problems because we want to make sure COW
2002 * properly happens and the data=ordered rules are followed.
2003 *
c8b97818 2004 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
2005 * hasn't been properly setup for IO. We kick off an async process
2006 * to fix it up. The async helper will wait for ordered extents, set
2007 * the delalloc bit and make it safe to write the page.
2008 */
b2950863 2009static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
247e743c
CM
2010{
2011 struct inode *inode = page->mapping->host;
0b246afa 2012 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
247e743c 2013 struct btrfs_writepage_fixup *fixup;
247e743c 2014
8b62b72b
CM
2015 /* this page is properly in the ordered list */
2016 if (TestClearPagePrivate2(page))
247e743c
CM
2017 return 0;
2018
2019 if (PageChecked(page))
2020 return -EAGAIN;
2021
2022 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2023 if (!fixup)
2024 return -EAGAIN;
f421950f 2025
247e743c 2026 SetPageChecked(page);
09cbfeaf 2027 get_page(page);
9e0af237
LB
2028 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2029 btrfs_writepage_fixup_worker, NULL, NULL);
247e743c 2030 fixup->page = page;
0b246afa 2031 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
87826df0 2032 return -EBUSY;
247e743c
CM
2033}
2034
d899e052
YZ
2035static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2036 struct inode *inode, u64 file_pos,
2037 u64 disk_bytenr, u64 disk_num_bytes,
2038 u64 num_bytes, u64 ram_bytes,
2039 u8 compression, u8 encryption,
2040 u16 other_encoding, int extent_type)
2041{
2042 struct btrfs_root *root = BTRFS_I(inode)->root;
2043 struct btrfs_file_extent_item *fi;
2044 struct btrfs_path *path;
2045 struct extent_buffer *leaf;
2046 struct btrfs_key ins;
1acae57b 2047 int extent_inserted = 0;
d899e052
YZ
2048 int ret;
2049
2050 path = btrfs_alloc_path();
d8926bb3
MF
2051 if (!path)
2052 return -ENOMEM;
d899e052 2053
a1ed835e
CM
2054 /*
2055 * we may be replacing one extent in the tree with another.
2056 * The new extent is pinned in the extent map, and we don't want
2057 * to drop it from the cache until it is completely in the btree.
2058 *
2059 * So, tell btrfs_drop_extents to leave this extent in the cache.
2060 * the caller is expected to unpin it and allow it to be merged
2061 * with the others.
2062 */
1acae57b
FDBM
2063 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2064 file_pos + num_bytes, NULL, 0,
2065 1, sizeof(*fi), &extent_inserted);
79787eaa
JM
2066 if (ret)
2067 goto out;
d899e052 2068
1acae57b 2069 if (!extent_inserted) {
4a0cc7ca 2070 ins.objectid = btrfs_ino(BTRFS_I(inode));
1acae57b
FDBM
2071 ins.offset = file_pos;
2072 ins.type = BTRFS_EXTENT_DATA_KEY;
2073
2074 path->leave_spinning = 1;
2075 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2076 sizeof(*fi));
2077 if (ret)
2078 goto out;
2079 }
d899e052
YZ
2080 leaf = path->nodes[0];
2081 fi = btrfs_item_ptr(leaf, path->slots[0],
2082 struct btrfs_file_extent_item);
2083 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2084 btrfs_set_file_extent_type(leaf, fi, extent_type);
2085 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2086 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2087 btrfs_set_file_extent_offset(leaf, fi, 0);
2088 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2089 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2090 btrfs_set_file_extent_compression(leaf, fi, compression);
2091 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2092 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439 2093
d899e052 2094 btrfs_mark_buffer_dirty(leaf);
ce195332 2095 btrfs_release_path(path);
d899e052
YZ
2096
2097 inode_add_bytes(inode, num_bytes);
d899e052
YZ
2098
2099 ins.objectid = disk_bytenr;
2100 ins.offset = disk_num_bytes;
2101 ins.type = BTRFS_EXTENT_ITEM_KEY;
2ff7e61e 2102 ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
f85b7379 2103 btrfs_ino(BTRFS_I(inode)), file_pos, ram_bytes, &ins);
297d750b 2104 /*
5846a3c2
QW
2105 * Release the reserved range from inode dirty range map, as it is
2106 * already moved into delayed_ref_head
297d750b
QW
2107 */
2108 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
79787eaa 2109out:
d899e052 2110 btrfs_free_path(path);
b9473439 2111
79787eaa 2112 return ret;
d899e052
YZ
2113}
2114
38c227d8
LB
2115/* snapshot-aware defrag */
2116struct sa_defrag_extent_backref {
2117 struct rb_node node;
2118 struct old_sa_defrag_extent *old;
2119 u64 root_id;
2120 u64 inum;
2121 u64 file_pos;
2122 u64 extent_offset;
2123 u64 num_bytes;
2124 u64 generation;
2125};
2126
2127struct old_sa_defrag_extent {
2128 struct list_head list;
2129 struct new_sa_defrag_extent *new;
2130
2131 u64 extent_offset;
2132 u64 bytenr;
2133 u64 offset;
2134 u64 len;
2135 int count;
2136};
2137
2138struct new_sa_defrag_extent {
2139 struct rb_root root;
2140 struct list_head head;
2141 struct btrfs_path *path;
2142 struct inode *inode;
2143 u64 file_pos;
2144 u64 len;
2145 u64 bytenr;
2146 u64 disk_len;
2147 u8 compress_type;
2148};
2149
2150static int backref_comp(struct sa_defrag_extent_backref *b1,
2151 struct sa_defrag_extent_backref *b2)
2152{
2153 if (b1->root_id < b2->root_id)
2154 return -1;
2155 else if (b1->root_id > b2->root_id)
2156 return 1;
2157
2158 if (b1->inum < b2->inum)
2159 return -1;
2160 else if (b1->inum > b2->inum)
2161 return 1;
2162
2163 if (b1->file_pos < b2->file_pos)
2164 return -1;
2165 else if (b1->file_pos > b2->file_pos)
2166 return 1;
2167
2168 /*
2169 * [------------------------------] ===> (a range of space)
2170 * |<--->| |<---->| =============> (fs/file tree A)
2171 * |<---------------------------->| ===> (fs/file tree B)
2172 *
2173 * A range of space can refer to two file extents in one tree while
2174 * refer to only one file extent in another tree.
2175 *
2176 * So we may process a disk offset more than one time(two extents in A)
2177 * and locate at the same extent(one extent in B), then insert two same
2178 * backrefs(both refer to the extent in B).
2179 */
2180 return 0;
2181}
2182
2183static void backref_insert(struct rb_root *root,
2184 struct sa_defrag_extent_backref *backref)
2185{
2186 struct rb_node **p = &root->rb_node;
2187 struct rb_node *parent = NULL;
2188 struct sa_defrag_extent_backref *entry;
2189 int ret;
2190
2191 while (*p) {
2192 parent = *p;
2193 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2194
2195 ret = backref_comp(backref, entry);
2196 if (ret < 0)
2197 p = &(*p)->rb_left;
2198 else
2199 p = &(*p)->rb_right;
2200 }
2201
2202 rb_link_node(&backref->node, parent, p);
2203 rb_insert_color(&backref->node, root);
2204}
2205
2206/*
2207 * Note the backref might has changed, and in this case we just return 0.
2208 */
2209static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2210 void *ctx)
2211{
2212 struct btrfs_file_extent_item *extent;
38c227d8
LB
2213 struct old_sa_defrag_extent *old = ctx;
2214 struct new_sa_defrag_extent *new = old->new;
2215 struct btrfs_path *path = new->path;
2216 struct btrfs_key key;
2217 struct btrfs_root *root;
2218 struct sa_defrag_extent_backref *backref;
2219 struct extent_buffer *leaf;
2220 struct inode *inode = new->inode;
0b246afa 2221 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
38c227d8
LB
2222 int slot;
2223 int ret;
2224 u64 extent_offset;
2225 u64 num_bytes;
2226
2227 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
4a0cc7ca 2228 inum == btrfs_ino(BTRFS_I(inode)))
38c227d8
LB
2229 return 0;
2230
2231 key.objectid = root_id;
2232 key.type = BTRFS_ROOT_ITEM_KEY;
2233 key.offset = (u64)-1;
2234
38c227d8
LB
2235 root = btrfs_read_fs_root_no_name(fs_info, &key);
2236 if (IS_ERR(root)) {
2237 if (PTR_ERR(root) == -ENOENT)
2238 return 0;
2239 WARN_ON(1);
ab8d0fc4 2240 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
38c227d8
LB
2241 inum, offset, root_id);
2242 return PTR_ERR(root);
2243 }
2244
2245 key.objectid = inum;
2246 key.type = BTRFS_EXTENT_DATA_KEY;
2247 if (offset > (u64)-1 << 32)
2248 key.offset = 0;
2249 else
2250 key.offset = offset;
2251
2252 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
fae7f21c 2253 if (WARN_ON(ret < 0))
38c227d8 2254 return ret;
50f1319c 2255 ret = 0;
38c227d8
LB
2256
2257 while (1) {
2258 cond_resched();
2259
2260 leaf = path->nodes[0];
2261 slot = path->slots[0];
2262
2263 if (slot >= btrfs_header_nritems(leaf)) {
2264 ret = btrfs_next_leaf(root, path);
2265 if (ret < 0) {
2266 goto out;
2267 } else if (ret > 0) {
2268 ret = 0;
2269 goto out;
2270 }
2271 continue;
2272 }
2273
2274 path->slots[0]++;
2275
2276 btrfs_item_key_to_cpu(leaf, &key, slot);
2277
2278 if (key.objectid > inum)
2279 goto out;
2280
2281 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2282 continue;
2283
2284 extent = btrfs_item_ptr(leaf, slot,
2285 struct btrfs_file_extent_item);
2286
2287 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2288 continue;
2289
e68afa49
LB
2290 /*
2291 * 'offset' refers to the exact key.offset,
2292 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2293 * (key.offset - extent_offset).
2294 */
2295 if (key.offset != offset)
38c227d8
LB
2296 continue;
2297
e68afa49 2298 extent_offset = btrfs_file_extent_offset(leaf, extent);
38c227d8 2299 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
e68afa49 2300
38c227d8
LB
2301 if (extent_offset >= old->extent_offset + old->offset +
2302 old->len || extent_offset + num_bytes <=
2303 old->extent_offset + old->offset)
2304 continue;
38c227d8
LB
2305 break;
2306 }
2307
2308 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2309 if (!backref) {
2310 ret = -ENOENT;
2311 goto out;
2312 }
2313
2314 backref->root_id = root_id;
2315 backref->inum = inum;
e68afa49 2316 backref->file_pos = offset;
38c227d8
LB
2317 backref->num_bytes = num_bytes;
2318 backref->extent_offset = extent_offset;
2319 backref->generation = btrfs_file_extent_generation(leaf, extent);
2320 backref->old = old;
2321 backref_insert(&new->root, backref);
2322 old->count++;
2323out:
2324 btrfs_release_path(path);
2325 WARN_ON(ret);
2326 return ret;
2327}
2328
2329static noinline bool record_extent_backrefs(struct btrfs_path *path,
2330 struct new_sa_defrag_extent *new)
2331{
0b246afa 2332 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8
LB
2333 struct old_sa_defrag_extent *old, *tmp;
2334 int ret;
2335
2336 new->path = path;
2337
2338 list_for_each_entry_safe(old, tmp, &new->head, list) {
e68afa49
LB
2339 ret = iterate_inodes_from_logical(old->bytenr +
2340 old->extent_offset, fs_info,
38c227d8
LB
2341 path, record_one_backref,
2342 old);
4724b106
JB
2343 if (ret < 0 && ret != -ENOENT)
2344 return false;
38c227d8
LB
2345
2346 /* no backref to be processed for this extent */
2347 if (!old->count) {
2348 list_del(&old->list);
2349 kfree(old);
2350 }
2351 }
2352
2353 if (list_empty(&new->head))
2354 return false;
2355
2356 return true;
2357}
2358
2359static int relink_is_mergable(struct extent_buffer *leaf,
2360 struct btrfs_file_extent_item *fi,
116e0024 2361 struct new_sa_defrag_extent *new)
38c227d8 2362{
116e0024 2363 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
38c227d8
LB
2364 return 0;
2365
2366 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2367 return 0;
2368
116e0024
LB
2369 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2370 return 0;
2371
2372 if (btrfs_file_extent_encryption(leaf, fi) ||
38c227d8
LB
2373 btrfs_file_extent_other_encoding(leaf, fi))
2374 return 0;
2375
2376 return 1;
2377}
2378
2379/*
2380 * Note the backref might has changed, and in this case we just return 0.
2381 */
2382static noinline int relink_extent_backref(struct btrfs_path *path,
2383 struct sa_defrag_extent_backref *prev,
2384 struct sa_defrag_extent_backref *backref)
2385{
2386 struct btrfs_file_extent_item *extent;
2387 struct btrfs_file_extent_item *item;
2388 struct btrfs_ordered_extent *ordered;
2389 struct btrfs_trans_handle *trans;
38c227d8
LB
2390 struct btrfs_root *root;
2391 struct btrfs_key key;
2392 struct extent_buffer *leaf;
2393 struct old_sa_defrag_extent *old = backref->old;
2394 struct new_sa_defrag_extent *new = old->new;
0b246afa 2395 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8
LB
2396 struct inode *inode;
2397 struct extent_state *cached = NULL;
2398 int ret = 0;
2399 u64 start;
2400 u64 len;
2401 u64 lock_start;
2402 u64 lock_end;
2403 bool merge = false;
2404 int index;
2405
2406 if (prev && prev->root_id == backref->root_id &&
2407 prev->inum == backref->inum &&
2408 prev->file_pos + prev->num_bytes == backref->file_pos)
2409 merge = true;
2410
2411 /* step 1: get root */
2412 key.objectid = backref->root_id;
2413 key.type = BTRFS_ROOT_ITEM_KEY;
2414 key.offset = (u64)-1;
2415
38c227d8
LB
2416 index = srcu_read_lock(&fs_info->subvol_srcu);
2417
2418 root = btrfs_read_fs_root_no_name(fs_info, &key);
2419 if (IS_ERR(root)) {
2420 srcu_read_unlock(&fs_info->subvol_srcu, index);
2421 if (PTR_ERR(root) == -ENOENT)
2422 return 0;
2423 return PTR_ERR(root);
2424 }
38c227d8 2425
bcbba5e6
WS
2426 if (btrfs_root_readonly(root)) {
2427 srcu_read_unlock(&fs_info->subvol_srcu, index);
2428 return 0;
2429 }
2430
38c227d8
LB
2431 /* step 2: get inode */
2432 key.objectid = backref->inum;
2433 key.type = BTRFS_INODE_ITEM_KEY;
2434 key.offset = 0;
2435
2436 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2437 if (IS_ERR(inode)) {
2438 srcu_read_unlock(&fs_info->subvol_srcu, index);
2439 return 0;
2440 }
2441
2442 srcu_read_unlock(&fs_info->subvol_srcu, index);
2443
2444 /* step 3: relink backref */
2445 lock_start = backref->file_pos;
2446 lock_end = backref->file_pos + backref->num_bytes - 1;
2447 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
ff13db41 2448 &cached);
38c227d8
LB
2449
2450 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2451 if (ordered) {
2452 btrfs_put_ordered_extent(ordered);
2453 goto out_unlock;
2454 }
2455
2456 trans = btrfs_join_transaction(root);
2457 if (IS_ERR(trans)) {
2458 ret = PTR_ERR(trans);
2459 goto out_unlock;
2460 }
2461
2462 key.objectid = backref->inum;
2463 key.type = BTRFS_EXTENT_DATA_KEY;
2464 key.offset = backref->file_pos;
2465
2466 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2467 if (ret < 0) {
2468 goto out_free_path;
2469 } else if (ret > 0) {
2470 ret = 0;
2471 goto out_free_path;
2472 }
2473
2474 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2475 struct btrfs_file_extent_item);
2476
2477 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2478 backref->generation)
2479 goto out_free_path;
2480
2481 btrfs_release_path(path);
2482
2483 start = backref->file_pos;
2484 if (backref->extent_offset < old->extent_offset + old->offset)
2485 start += old->extent_offset + old->offset -
2486 backref->extent_offset;
2487
2488 len = min(backref->extent_offset + backref->num_bytes,
2489 old->extent_offset + old->offset + old->len);
2490 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2491
2492 ret = btrfs_drop_extents(trans, root, inode, start,
2493 start + len, 1);
2494 if (ret)
2495 goto out_free_path;
2496again:
4a0cc7ca 2497 key.objectid = btrfs_ino(BTRFS_I(inode));
38c227d8
LB
2498 key.type = BTRFS_EXTENT_DATA_KEY;
2499 key.offset = start;
2500
a09a0a70 2501 path->leave_spinning = 1;
38c227d8
LB
2502 if (merge) {
2503 struct btrfs_file_extent_item *fi;
2504 u64 extent_len;
2505 struct btrfs_key found_key;
2506
3c9665df 2507 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
38c227d8
LB
2508 if (ret < 0)
2509 goto out_free_path;
2510
2511 path->slots[0]--;
2512 leaf = path->nodes[0];
2513 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2514
2515 fi = btrfs_item_ptr(leaf, path->slots[0],
2516 struct btrfs_file_extent_item);
2517 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2518
116e0024
LB
2519 if (extent_len + found_key.offset == start &&
2520 relink_is_mergable(leaf, fi, new)) {
38c227d8
LB
2521 btrfs_set_file_extent_num_bytes(leaf, fi,
2522 extent_len + len);
2523 btrfs_mark_buffer_dirty(leaf);
2524 inode_add_bytes(inode, len);
2525
2526 ret = 1;
2527 goto out_free_path;
2528 } else {
2529 merge = false;
2530 btrfs_release_path(path);
2531 goto again;
2532 }
2533 }
2534
2535 ret = btrfs_insert_empty_item(trans, root, path, &key,
2536 sizeof(*extent));
2537 if (ret) {
66642832 2538 btrfs_abort_transaction(trans, ret);
38c227d8
LB
2539 goto out_free_path;
2540 }
2541
2542 leaf = path->nodes[0];
2543 item = btrfs_item_ptr(leaf, path->slots[0],
2544 struct btrfs_file_extent_item);
2545 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2546 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2547 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2548 btrfs_set_file_extent_num_bytes(leaf, item, len);
2549 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2550 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2551 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2552 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2553 btrfs_set_file_extent_encryption(leaf, item, 0);
2554 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2555
2556 btrfs_mark_buffer_dirty(leaf);
2557 inode_add_bytes(inode, len);
a09a0a70 2558 btrfs_release_path(path);
38c227d8 2559
2ff7e61e 2560 ret = btrfs_inc_extent_ref(trans, fs_info, new->bytenr,
38c227d8
LB
2561 new->disk_len, 0,
2562 backref->root_id, backref->inum,
b06c4bf5 2563 new->file_pos); /* start - extent_offset */
38c227d8 2564 if (ret) {
66642832 2565 btrfs_abort_transaction(trans, ret);
38c227d8
LB
2566 goto out_free_path;
2567 }
2568
2569 ret = 1;
2570out_free_path:
2571 btrfs_release_path(path);
a09a0a70 2572 path->leave_spinning = 0;
3a45bb20 2573 btrfs_end_transaction(trans);
38c227d8
LB
2574out_unlock:
2575 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2576 &cached, GFP_NOFS);
2577 iput(inode);
2578 return ret;
2579}
2580
6f519564
LB
2581static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2582{
2583 struct old_sa_defrag_extent *old, *tmp;
2584
2585 if (!new)
2586 return;
2587
2588 list_for_each_entry_safe(old, tmp, &new->head, list) {
6f519564
LB
2589 kfree(old);
2590 }
2591 kfree(new);
2592}
2593
38c227d8
LB
2594static void relink_file_extents(struct new_sa_defrag_extent *new)
2595{
0b246afa 2596 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
38c227d8 2597 struct btrfs_path *path;
38c227d8
LB
2598 struct sa_defrag_extent_backref *backref;
2599 struct sa_defrag_extent_backref *prev = NULL;
2600 struct inode *inode;
2601 struct btrfs_root *root;
2602 struct rb_node *node;
2603 int ret;
2604
2605 inode = new->inode;
2606 root = BTRFS_I(inode)->root;
2607
2608 path = btrfs_alloc_path();
2609 if (!path)
2610 return;
2611
2612 if (!record_extent_backrefs(path, new)) {
2613 btrfs_free_path(path);
2614 goto out;
2615 }
2616 btrfs_release_path(path);
2617
2618 while (1) {
2619 node = rb_first(&new->root);
2620 if (!node)
2621 break;
2622 rb_erase(node, &new->root);
2623
2624 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2625
2626 ret = relink_extent_backref(path, prev, backref);
2627 WARN_ON(ret < 0);
2628
2629 kfree(prev);
2630
2631 if (ret == 1)
2632 prev = backref;
2633 else
2634 prev = NULL;
2635 cond_resched();
2636 }
2637 kfree(prev);
2638
2639 btrfs_free_path(path);
38c227d8 2640out:
6f519564
LB
2641 free_sa_defrag_extent(new);
2642
0b246afa
JM
2643 atomic_dec(&fs_info->defrag_running);
2644 wake_up(&fs_info->transaction_wait);
38c227d8
LB
2645}
2646
2647static struct new_sa_defrag_extent *
2648record_old_file_extents(struct inode *inode,
2649 struct btrfs_ordered_extent *ordered)
2650{
0b246afa 2651 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
38c227d8
LB
2652 struct btrfs_root *root = BTRFS_I(inode)->root;
2653 struct btrfs_path *path;
2654 struct btrfs_key key;
6f519564 2655 struct old_sa_defrag_extent *old;
38c227d8
LB
2656 struct new_sa_defrag_extent *new;
2657 int ret;
2658
2659 new = kmalloc(sizeof(*new), GFP_NOFS);
2660 if (!new)
2661 return NULL;
2662
2663 new->inode = inode;
2664 new->file_pos = ordered->file_offset;
2665 new->len = ordered->len;
2666 new->bytenr = ordered->start;
2667 new->disk_len = ordered->disk_len;
2668 new->compress_type = ordered->compress_type;
2669 new->root = RB_ROOT;
2670 INIT_LIST_HEAD(&new->head);
2671
2672 path = btrfs_alloc_path();
2673 if (!path)
2674 goto out_kfree;
2675
4a0cc7ca 2676 key.objectid = btrfs_ino(BTRFS_I(inode));
38c227d8
LB
2677 key.type = BTRFS_EXTENT_DATA_KEY;
2678 key.offset = new->file_pos;
2679
2680 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2681 if (ret < 0)
2682 goto out_free_path;
2683 if (ret > 0 && path->slots[0] > 0)
2684 path->slots[0]--;
2685
2686 /* find out all the old extents for the file range */
2687 while (1) {
2688 struct btrfs_file_extent_item *extent;
2689 struct extent_buffer *l;
2690 int slot;
2691 u64 num_bytes;
2692 u64 offset;
2693 u64 end;
2694 u64 disk_bytenr;
2695 u64 extent_offset;
2696
2697 l = path->nodes[0];
2698 slot = path->slots[0];
2699
2700 if (slot >= btrfs_header_nritems(l)) {
2701 ret = btrfs_next_leaf(root, path);
2702 if (ret < 0)
6f519564 2703 goto out_free_path;
38c227d8
LB
2704 else if (ret > 0)
2705 break;
2706 continue;
2707 }
2708
2709 btrfs_item_key_to_cpu(l, &key, slot);
2710
4a0cc7ca 2711 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
38c227d8
LB
2712 break;
2713 if (key.type != BTRFS_EXTENT_DATA_KEY)
2714 break;
2715 if (key.offset >= new->file_pos + new->len)
2716 break;
2717
2718 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2719
2720 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2721 if (key.offset + num_bytes < new->file_pos)
2722 goto next;
2723
2724 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2725 if (!disk_bytenr)
2726 goto next;
2727
2728 extent_offset = btrfs_file_extent_offset(l, extent);
2729
2730 old = kmalloc(sizeof(*old), GFP_NOFS);
2731 if (!old)
6f519564 2732 goto out_free_path;
38c227d8
LB
2733
2734 offset = max(new->file_pos, key.offset);
2735 end = min(new->file_pos + new->len, key.offset + num_bytes);
2736
2737 old->bytenr = disk_bytenr;
2738 old->extent_offset = extent_offset;
2739 old->offset = offset - key.offset;
2740 old->len = end - offset;
2741 old->new = new;
2742 old->count = 0;
2743 list_add_tail(&old->list, &new->head);
2744next:
2745 path->slots[0]++;
2746 cond_resched();
2747 }
2748
2749 btrfs_free_path(path);
0b246afa 2750 atomic_inc(&fs_info->defrag_running);
38c227d8
LB
2751
2752 return new;
2753
38c227d8
LB
2754out_free_path:
2755 btrfs_free_path(path);
2756out_kfree:
6f519564 2757 free_sa_defrag_extent(new);
38c227d8
LB
2758 return NULL;
2759}
2760
2ff7e61e 2761static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
e570fd27
MX
2762 u64 start, u64 len)
2763{
2764 struct btrfs_block_group_cache *cache;
2765
0b246afa 2766 cache = btrfs_lookup_block_group(fs_info, start);
e570fd27
MX
2767 ASSERT(cache);
2768
2769 spin_lock(&cache->lock);
2770 cache->delalloc_bytes -= len;
2771 spin_unlock(&cache->lock);
2772
2773 btrfs_put_block_group(cache);
2774}
2775
d352ac68
CM
2776/* as ordered data IO finishes, this gets called so we can finish
2777 * an ordered extent if the range of bytes in the file it covers are
2778 * fully written.
2779 */
5fd02043 2780static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
e6dcd2dc 2781{
5fd02043 2782 struct inode *inode = ordered_extent->inode;
0b246afa 2783 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc 2784 struct btrfs_root *root = BTRFS_I(inode)->root;
0ca1f7ce 2785 struct btrfs_trans_handle *trans = NULL;
e6dcd2dc 2786 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2ac55d41 2787 struct extent_state *cached_state = NULL;
38c227d8 2788 struct new_sa_defrag_extent *new = NULL;
261507a0 2789 int compress_type = 0;
77cef2ec
JB
2790 int ret = 0;
2791 u64 logical_len = ordered_extent->len;
82d5902d 2792 bool nolock;
77cef2ec 2793 bool truncated = false;
e6dcd2dc 2794
70ddc553 2795 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
0cb59c99 2796
5fd02043
JB
2797 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2798 ret = -EIO;
2799 goto out;
2800 }
2801
7ab7956e
NB
2802 btrfs_free_io_failure_record(BTRFS_I(inode),
2803 ordered_extent->file_offset,
2804 ordered_extent->file_offset +
2805 ordered_extent->len - 1);
f612496b 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);
7a6d7067 2876 ret = btrfs_mark_extent_written(trans, BTRFS_I(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)
691fa059
NB
2917 btrfs_delalloc_release_metadata(BTRFS_I(inode),
2918 ordered_extent->len);
a698d075 2919 if (trans)
3a45bb20 2920 btrfs_end_transaction(trans);
0cb59c99 2921
77cef2ec
JB
2922 if (ret || truncated) {
2923 u64 start, end;
2924
2925 if (truncated)
2926 start = ordered_extent->file_offset + logical_len;
2927 else
2928 start = ordered_extent->file_offset;
2929 end = ordered_extent->file_offset + ordered_extent->len - 1;
2930 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2931
2932 /* Drop the cache for the part of the extent we didn't write. */
dcdbc059 2933 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
5fd02043 2934
0bec9ef5
JB
2935 /*
2936 * If the ordered extent had an IOERR or something else went
2937 * wrong we need to return the space for this ordered extent
77cef2ec
JB
2938 * back to the allocator. We only free the extent in the
2939 * truncated case if we didn't write out the extent at all.
0bec9ef5 2940 */
77cef2ec
JB
2941 if ((ret || !logical_len) &&
2942 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
0bec9ef5 2943 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2ff7e61e
JM
2944 btrfs_free_reserved_extent(fs_info,
2945 ordered_extent->start,
e570fd27 2946 ordered_extent->disk_len, 1);
0bec9ef5
JB
2947 }
2948
2949
5fd02043 2950 /*
8bad3c02
LB
2951 * This needs to be done to make sure anybody waiting knows we are done
2952 * updating everything for this ordered extent.
5fd02043
JB
2953 */
2954 btrfs_remove_ordered_extent(inode, ordered_extent);
2955
38c227d8 2956 /* for snapshot-aware defrag */
6f519564
LB
2957 if (new) {
2958 if (ret) {
2959 free_sa_defrag_extent(new);
0b246afa 2960 atomic_dec(&fs_info->defrag_running);
6f519564
LB
2961 } else {
2962 relink_file_extents(new);
2963 }
2964 }
38c227d8 2965
e6dcd2dc
CM
2966 /* once for us */
2967 btrfs_put_ordered_extent(ordered_extent);
2968 /* once for the tree */
2969 btrfs_put_ordered_extent(ordered_extent);
2970
5fd02043
JB
2971 return ret;
2972}
2973
2974static void finish_ordered_fn(struct btrfs_work *work)
2975{
2976 struct btrfs_ordered_extent *ordered_extent;
2977 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2978 btrfs_finish_ordered_io(ordered_extent);
e6dcd2dc
CM
2979}
2980
c3988d63 2981static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
211f90e6
CM
2982 struct extent_state *state, int uptodate)
2983{
5fd02043 2984 struct inode *inode = page->mapping->host;
0b246afa 2985 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5fd02043 2986 struct btrfs_ordered_extent *ordered_extent = NULL;
9e0af237
LB
2987 struct btrfs_workqueue *wq;
2988 btrfs_work_func_t func;
5fd02043 2989
1abe9b8a 2990 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2991
8b62b72b 2992 ClearPagePrivate2(page);
5fd02043
JB
2993 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2994 end - start + 1, uptodate))
c3988d63 2995 return;
5fd02043 2996
70ddc553 2997 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
0b246afa 2998 wq = fs_info->endio_freespace_worker;
9e0af237
LB
2999 func = btrfs_freespace_write_helper;
3000 } else {
0b246afa 3001 wq = fs_info->endio_write_workers;
9e0af237
LB
3002 func = btrfs_endio_write_helper;
3003 }
5fd02043 3004
9e0af237
LB
3005 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3006 NULL);
3007 btrfs_queue_work(wq, &ordered_extent->work);
211f90e6
CM
3008}
3009
dc380aea
MX
3010static int __readpage_endio_check(struct inode *inode,
3011 struct btrfs_io_bio *io_bio,
3012 int icsum, struct page *page,
3013 int pgoff, u64 start, size_t len)
3014{
3015 char *kaddr;
3016 u32 csum_expected;
3017 u32 csum = ~(u32)0;
dc380aea
MX
3018
3019 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3020
3021 kaddr = kmap_atomic(page);
3022 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
0b5e3daf 3023 btrfs_csum_final(csum, (u8 *)&csum);
dc380aea
MX
3024 if (csum != csum_expected)
3025 goto zeroit;
3026
3027 kunmap_atomic(kaddr);
3028 return 0;
3029zeroit:
0970a22e 3030 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
6f6b643e 3031 io_bio->mirror_num);
dc380aea
MX
3032 memset(kaddr + pgoff, 1, len);
3033 flush_dcache_page(page);
3034 kunmap_atomic(kaddr);
3035 if (csum_expected == 0)
3036 return 0;
3037 return -EIO;
3038}
3039
d352ac68
CM
3040/*
3041 * when reads are done, we need to check csums to verify the data is correct
4a54c8c1
JS
3042 * if there's a match, we allow the bio to finish. If not, the code in
3043 * extent_io.c will try to find good copies for us.
d352ac68 3044 */
facc8a22
MX
3045static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3046 u64 phy_offset, struct page *page,
3047 u64 start, u64 end, int mirror)
07157aac 3048{
4eee4fa4 3049 size_t offset = start - page_offset(page);
07157aac 3050 struct inode *inode = page->mapping->host;
d1310b2e 3051 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
ff79f819 3052 struct btrfs_root *root = BTRFS_I(inode)->root;
d1310b2e 3053
d20f7043
CM
3054 if (PageChecked(page)) {
3055 ClearPageChecked(page);
dc380aea 3056 return 0;
d20f7043 3057 }
6cbff00f
CH
3058
3059 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
dc380aea 3060 return 0;
17d217fe
YZ
3061
3062 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 3063 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
91166212 3064 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
b6cda9bc 3065 return 0;
17d217fe 3066 }
d20f7043 3067
facc8a22 3068 phy_offset >>= inode->i_sb->s_blocksize_bits;
dc380aea
MX
3069 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3070 start, (size_t)(end - start + 1));
07157aac 3071}
b888db2b 3072
24bbcf04
YZ
3073void btrfs_add_delayed_iput(struct inode *inode)
3074{
0b246afa 3075 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8089fe62 3076 struct btrfs_inode *binode = BTRFS_I(inode);
24bbcf04
YZ
3077
3078 if (atomic_add_unless(&inode->i_count, -1, 1))
3079 return;
3080
24bbcf04 3081 spin_lock(&fs_info->delayed_iput_lock);
8089fe62
DS
3082 if (binode->delayed_iput_count == 0) {
3083 ASSERT(list_empty(&binode->delayed_iput));
3084 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3085 } else {
3086 binode->delayed_iput_count++;
3087 }
24bbcf04
YZ
3088 spin_unlock(&fs_info->delayed_iput_lock);
3089}
3090
2ff7e61e 3091void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
24bbcf04 3092{
24bbcf04 3093
24bbcf04 3094 spin_lock(&fs_info->delayed_iput_lock);
8089fe62
DS
3095 while (!list_empty(&fs_info->delayed_iputs)) {
3096 struct btrfs_inode *inode;
3097
3098 inode = list_first_entry(&fs_info->delayed_iputs,
3099 struct btrfs_inode, delayed_iput);
3100 if (inode->delayed_iput_count) {
3101 inode->delayed_iput_count--;
3102 list_move_tail(&inode->delayed_iput,
3103 &fs_info->delayed_iputs);
3104 } else {
3105 list_del_init(&inode->delayed_iput);
3106 }
3107 spin_unlock(&fs_info->delayed_iput_lock);
3108 iput(&inode->vfs_inode);
3109 spin_lock(&fs_info->delayed_iput_lock);
24bbcf04 3110 }
8089fe62 3111 spin_unlock(&fs_info->delayed_iput_lock);
24bbcf04
YZ
3112}
3113
d68fc57b 3114/*
42b2aa86 3115 * This is called in transaction commit time. If there are no orphan
d68fc57b
YZ
3116 * files in the subvolume, it removes orphan item and frees block_rsv
3117 * structure.
3118 */
3119void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3120 struct btrfs_root *root)
3121{
0b246afa 3122 struct btrfs_fs_info *fs_info = root->fs_info;
90290e19 3123 struct btrfs_block_rsv *block_rsv;
d68fc57b
YZ
3124 int ret;
3125
8a35d95f 3126 if (atomic_read(&root->orphan_inodes) ||
d68fc57b
YZ
3127 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3128 return;
3129
90290e19 3130 spin_lock(&root->orphan_lock);
8a35d95f 3131 if (atomic_read(&root->orphan_inodes)) {
90290e19
JB
3132 spin_unlock(&root->orphan_lock);
3133 return;
3134 }
3135
3136 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3137 spin_unlock(&root->orphan_lock);
3138 return;
3139 }
3140
3141 block_rsv = root->orphan_block_rsv;
3142 root->orphan_block_rsv = NULL;
3143 spin_unlock(&root->orphan_lock);
3144
27cdeb70 3145 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
d68fc57b 3146 btrfs_root_refs(&root->root_item) > 0) {
0b246afa 3147 ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
d68fc57b 3148 root->root_key.objectid);
4ef31a45 3149 if (ret)
66642832 3150 btrfs_abort_transaction(trans, ret);
4ef31a45 3151 else
27cdeb70
MX
3152 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3153 &root->state);
d68fc57b
YZ
3154 }
3155
90290e19
JB
3156 if (block_rsv) {
3157 WARN_ON(block_rsv->size > 0);
2ff7e61e 3158 btrfs_free_block_rsv(fs_info, block_rsv);
d68fc57b
YZ
3159 }
3160}
3161
7b128766
JB
3162/*
3163 * This creates an orphan entry for the given inode in case something goes
3164 * wrong in the middle of an unlink/truncate.
d68fc57b
YZ
3165 *
3166 * NOTE: caller of this function should reserve 5 units of metadata for
3167 * this function.
7b128766 3168 */
73f2e545
NB
3169int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3170 struct btrfs_inode *inode)
7b128766 3171{
73f2e545
NB
3172 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3173 struct btrfs_root *root = 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 3194 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
73f2e545 3195 &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 3211 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
73f2e545 3212 &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) {
3218 ret = btrfs_orphan_reserve_metadata(trans, inode);
3b6571c1
JB
3219 ASSERT(!ret);
3220 if (ret) {
3221 atomic_dec(&root->orphan_inodes);
3222 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
73f2e545 3223 &inode->runtime_flags);
3b6571c1
JB
3224 if (insert)
3225 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
73f2e545 3226 &inode->runtime_flags);
3b6571c1
JB
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) {
73f2e545 3233 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
4ef31a45 3234 if (ret) {
703c88e0 3235 atomic_dec(&root->orphan_inodes);
4ef31a45
JB
3236 if (reserve) {
3237 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
73f2e545 3238 &inode->runtime_flags);
4ef31a45
JB
3239 btrfs_orphan_release_metadata(inode);
3240 }
3241 if (ret != -EEXIST) {
e8e7cff6 3242 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
73f2e545 3243 &inode->runtime_flags);
66642832 3244 btrfs_abort_transaction(trans, ret);
4ef31a45
JB
3245 return ret;
3246 }
79787eaa
JM
3247 }
3248 ret = 0;
d68fc57b
YZ
3249 }
3250
3251 /* insert an orphan item to track subvolume contains orphan files */
3252 if (insert >= 2) {
0b246afa 3253 ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
d68fc57b 3254 root->root_key.objectid);
79787eaa 3255 if (ret && ret != -EEXIST) {
66642832 3256 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3257 return ret;
3258 }
d68fc57b
YZ
3259 }
3260 return 0;
7b128766
JB
3261}
3262
3263/*
3264 * We have done the truncate/delete so we can go ahead and remove the orphan
3265 * item for this particular inode.
3266 */
48a3b636 3267static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3d6ae7bb 3268 struct btrfs_inode *inode)
7b128766 3269{
3d6ae7bb 3270 struct btrfs_root *root = inode->root;
d68fc57b
YZ
3271 int delete_item = 0;
3272 int release_rsv = 0;
7b128766
JB
3273 int ret = 0;
3274
d68fc57b 3275 spin_lock(&root->orphan_lock);
8a35d95f 3276 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3d6ae7bb 3277 &inode->runtime_flags))
d68fc57b 3278 delete_item = 1;
7b128766 3279
72ac3c0d 3280 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3d6ae7bb 3281 &inode->runtime_flags))
d68fc57b 3282 release_rsv = 1;
d68fc57b 3283 spin_unlock(&root->orphan_lock);
7b128766 3284
703c88e0 3285 if (delete_item) {
8a35d95f 3286 atomic_dec(&root->orphan_inodes);
703c88e0
FDBM
3287 if (trans)
3288 ret = btrfs_del_orphan_item(trans, root,
3d6ae7bb 3289 btrfs_ino(inode));
8a35d95f 3290 }
7b128766 3291
703c88e0
FDBM
3292 if (release_rsv)
3293 btrfs_orphan_release_metadata(inode);
3294
4ef31a45 3295 return ret;
7b128766
JB
3296}
3297
3298/*
3299 * this cleans up any orphans that may be left on the list from the last use
3300 * of this root.
3301 */
66b4ffd1 3302int btrfs_orphan_cleanup(struct btrfs_root *root)
7b128766 3303{
0b246afa 3304 struct btrfs_fs_info *fs_info = root->fs_info;
7b128766
JB
3305 struct btrfs_path *path;
3306 struct extent_buffer *leaf;
7b128766
JB
3307 struct btrfs_key key, found_key;
3308 struct btrfs_trans_handle *trans;
3309 struct inode *inode;
8f6d7f4f 3310 u64 last_objectid = 0;
7b128766
JB
3311 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3312
d68fc57b 3313 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
66b4ffd1 3314 return 0;
c71bf099
YZ
3315
3316 path = btrfs_alloc_path();
66b4ffd1
JB
3317 if (!path) {
3318 ret = -ENOMEM;
3319 goto out;
3320 }
e4058b54 3321 path->reada = READA_BACK;
7b128766
JB
3322
3323 key.objectid = BTRFS_ORPHAN_OBJECTID;
962a298f 3324 key.type = BTRFS_ORPHAN_ITEM_KEY;
7b128766
JB
3325 key.offset = (u64)-1;
3326
7b128766
JB
3327 while (1) {
3328 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
66b4ffd1
JB
3329 if (ret < 0)
3330 goto out;
7b128766
JB
3331
3332 /*
3333 * if ret == 0 means we found what we were searching for, which
25985edc 3334 * is weird, but possible, so only screw with path if we didn't
7b128766
JB
3335 * find the key and see if we have stuff that matches
3336 */
3337 if (ret > 0) {
66b4ffd1 3338 ret = 0;
7b128766
JB
3339 if (path->slots[0] == 0)
3340 break;
3341 path->slots[0]--;
3342 }
3343
3344 /* pull out the item */
3345 leaf = path->nodes[0];
7b128766
JB
3346 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3347
3348 /* make sure the item matches what we want */
3349 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3350 break;
962a298f 3351 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
7b128766
JB
3352 break;
3353
3354 /* release the path since we're done with it */
b3b4aa74 3355 btrfs_release_path(path);
7b128766
JB
3356
3357 /*
3358 * this is where we are basically btrfs_lookup, without the
3359 * crossing root thing. we store the inode number in the
3360 * offset of the orphan item.
3361 */
8f6d7f4f
JB
3362
3363 if (found_key.offset == last_objectid) {
0b246afa
JM
3364 btrfs_err(fs_info,
3365 "Error removing orphan entry, stopping orphan cleanup");
8f6d7f4f
JB
3366 ret = -EINVAL;
3367 goto out;
3368 }
3369
3370 last_objectid = found_key.offset;
3371
5d4f98a2
YZ
3372 found_key.objectid = found_key.offset;
3373 found_key.type = BTRFS_INODE_ITEM_KEY;
3374 found_key.offset = 0;
0b246afa 3375 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
8c6ffba0 3376 ret = PTR_ERR_OR_ZERO(inode);
67710892 3377 if (ret && ret != -ENOENT)
66b4ffd1 3378 goto out;
7b128766 3379
0b246afa 3380 if (ret == -ENOENT && root == fs_info->tree_root) {
f8e9e0b0
AJ
3381 struct btrfs_root *dead_root;
3382 struct btrfs_fs_info *fs_info = root->fs_info;
3383 int is_dead_root = 0;
3384
3385 /*
3386 * this is an orphan in the tree root. Currently these
3387 * could come from 2 sources:
3388 * a) a snapshot deletion in progress
3389 * b) a free space cache inode
3390 * We need to distinguish those two, as the snapshot
3391 * orphan must not get deleted.
3392 * find_dead_roots already ran before us, so if this
3393 * is a snapshot deletion, we should find the root
3394 * in the dead_roots list
3395 */
3396 spin_lock(&fs_info->trans_lock);
3397 list_for_each_entry(dead_root, &fs_info->dead_roots,
3398 root_list) {
3399 if (dead_root->root_key.objectid ==
3400 found_key.objectid) {
3401 is_dead_root = 1;
3402 break;
3403 }
3404 }
3405 spin_unlock(&fs_info->trans_lock);
3406 if (is_dead_root) {
3407 /* prevent this orphan from being found again */
3408 key.offset = found_key.objectid - 1;
3409 continue;
3410 }
3411 }
7b128766 3412 /*
a8c9e576
JB
3413 * Inode is already gone but the orphan item is still there,
3414 * kill the orphan item.
7b128766 3415 */
67710892 3416 if (ret == -ENOENT) {
a8c9e576 3417 trans = btrfs_start_transaction(root, 1);
66b4ffd1
JB
3418 if (IS_ERR(trans)) {
3419 ret = PTR_ERR(trans);
3420 goto out;
3421 }
0b246afa
JM
3422 btrfs_debug(fs_info, "auto deleting %Lu",
3423 found_key.objectid);
a8c9e576
JB
3424 ret = btrfs_del_orphan_item(trans, root,
3425 found_key.objectid);
3a45bb20 3426 btrfs_end_transaction(trans);
4ef31a45
JB
3427 if (ret)
3428 goto out;
7b128766
JB
3429 continue;
3430 }
3431
a8c9e576
JB
3432 /*
3433 * add this inode to the orphan list so btrfs_orphan_del does
3434 * the proper thing when we hit it
3435 */
8a35d95f
JB
3436 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3437 &BTRFS_I(inode)->runtime_flags);
925396ec 3438 atomic_inc(&root->orphan_inodes);
a8c9e576 3439
7b128766
JB
3440 /* if we have links, this was a truncate, lets do that */
3441 if (inode->i_nlink) {
fae7f21c 3442 if (WARN_ON(!S_ISREG(inode->i_mode))) {
a41ad394
JB
3443 iput(inode);
3444 continue;
3445 }
7b128766 3446 nr_truncate++;
f3fe820c
JB
3447
3448 /* 1 for the orphan item deletion. */
3449 trans = btrfs_start_transaction(root, 1);
3450 if (IS_ERR(trans)) {
c69b26b0 3451 iput(inode);
f3fe820c
JB
3452 ret = PTR_ERR(trans);
3453 goto out;
3454 }
73f2e545 3455 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3a45bb20 3456 btrfs_end_transaction(trans);
c69b26b0
JB
3457 if (ret) {
3458 iput(inode);
f3fe820c 3459 goto out;
c69b26b0 3460 }
f3fe820c 3461
66b4ffd1 3462 ret = btrfs_truncate(inode);
4a7d0f68 3463 if (ret)
3d6ae7bb 3464 btrfs_orphan_del(NULL, BTRFS_I(inode));
7b128766
JB
3465 } else {
3466 nr_unlink++;
3467 }
3468
3469 /* this will do delete_inode and everything for us */
3470 iput(inode);
66b4ffd1
JB
3471 if (ret)
3472 goto out;
7b128766 3473 }
3254c876
MX
3474 /* release the path since we're done with it */
3475 btrfs_release_path(path);
3476
d68fc57b
YZ
3477 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3478
3479 if (root->orphan_block_rsv)
2ff7e61e 3480 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
d68fc57b
YZ
3481 (u64)-1);
3482
27cdeb70
MX
3483 if (root->orphan_block_rsv ||
3484 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
7a7eaa40 3485 trans = btrfs_join_transaction(root);
66b4ffd1 3486 if (!IS_ERR(trans))
3a45bb20 3487 btrfs_end_transaction(trans);
d68fc57b 3488 }
7b128766
JB
3489
3490 if (nr_unlink)
0b246afa 3491 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
7b128766 3492 if (nr_truncate)
0b246afa 3493 btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
66b4ffd1
JB
3494
3495out:
3496 if (ret)
0b246afa 3497 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
66b4ffd1
JB
3498 btrfs_free_path(path);
3499 return ret;
7b128766
JB
3500}
3501
46a53cca
CM
3502/*
3503 * very simple check to peek ahead in the leaf looking for xattrs. If we
3504 * don't find any xattrs, we know there can't be any acls.
3505 *
3506 * slot is the slot the inode is in, objectid is the objectid of the inode
3507 */
3508static noinline int acls_after_inode_item(struct extent_buffer *leaf,
63541927
FDBM
3509 int slot, u64 objectid,
3510 int *first_xattr_slot)
46a53cca
CM
3511{
3512 u32 nritems = btrfs_header_nritems(leaf);
3513 struct btrfs_key found_key;
f23b5a59
JB
3514 static u64 xattr_access = 0;
3515 static u64 xattr_default = 0;
46a53cca
CM
3516 int scanned = 0;
3517
f23b5a59 3518 if (!xattr_access) {
97d79299
AG
3519 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3520 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3521 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3522 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
f23b5a59
JB
3523 }
3524
46a53cca 3525 slot++;
63541927 3526 *first_xattr_slot = -1;
46a53cca
CM
3527 while (slot < nritems) {
3528 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3529
3530 /* we found a different objectid, there must not be acls */
3531 if (found_key.objectid != objectid)
3532 return 0;
3533
3534 /* we found an xattr, assume we've got an acl */
f23b5a59 3535 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
63541927
FDBM
3536 if (*first_xattr_slot == -1)
3537 *first_xattr_slot = slot;
f23b5a59
JB
3538 if (found_key.offset == xattr_access ||
3539 found_key.offset == xattr_default)
3540 return 1;
3541 }
46a53cca
CM
3542
3543 /*
3544 * we found a key greater than an xattr key, there can't
3545 * be any acls later on
3546 */
3547 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3548 return 0;
3549
3550 slot++;
3551 scanned++;
3552
3553 /*
3554 * it goes inode, inode backrefs, xattrs, extents,
3555 * so if there are a ton of hard links to an inode there can
3556 * be a lot of backrefs. Don't waste time searching too hard,
3557 * this is just an optimization
3558 */
3559 if (scanned >= 8)
3560 break;
3561 }
3562 /* we hit the end of the leaf before we found an xattr or
3563 * something larger than an xattr. We have to assume the inode
3564 * has acls
3565 */
63541927
FDBM
3566 if (*first_xattr_slot == -1)
3567 *first_xattr_slot = slot;
46a53cca
CM
3568 return 1;
3569}
3570
d352ac68
CM
3571/*
3572 * read an inode from the btree into the in-memory inode
3573 */
67710892 3574static int btrfs_read_locked_inode(struct inode *inode)
39279cc3 3575{
0b246afa 3576 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 3577 struct btrfs_path *path;
5f39d397 3578 struct extent_buffer *leaf;
39279cc3
CM
3579 struct btrfs_inode_item *inode_item;
3580 struct btrfs_root *root = BTRFS_I(inode)->root;
3581 struct btrfs_key location;
67de1176 3582 unsigned long ptr;
46a53cca 3583 int maybe_acls;
618e21d5 3584 u32 rdev;
39279cc3 3585 int ret;
2f7e33d4 3586 bool filled = false;
63541927 3587 int first_xattr_slot;
2f7e33d4
MX
3588
3589 ret = btrfs_fill_inode(inode, &rdev);
3590 if (!ret)
3591 filled = true;
39279cc3
CM
3592
3593 path = btrfs_alloc_path();
67710892
FM
3594 if (!path) {
3595 ret = -ENOMEM;
1748f843 3596 goto make_bad;
67710892 3597 }
1748f843 3598
39279cc3 3599 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 3600
39279cc3 3601 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
67710892
FM
3602 if (ret) {
3603 if (ret > 0)
3604 ret = -ENOENT;
39279cc3 3605 goto make_bad;
67710892 3606 }
39279cc3 3607
5f39d397 3608 leaf = path->nodes[0];
2f7e33d4
MX
3609
3610 if (filled)
67de1176 3611 goto cache_index;
2f7e33d4 3612
5f39d397
CM
3613 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3614 struct btrfs_inode_item);
5f39d397 3615 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
bfe86848 3616 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2f2f43d3
EB
3617 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3618 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
6ef06d27 3619 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
5f39d397 3620
a937b979
DS
3621 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3622 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
5f39d397 3623
a937b979
DS
3624 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3625 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
5f39d397 3626
a937b979
DS
3627 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3628 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
5f39d397 3629
9cc97d64 3630 BTRFS_I(inode)->i_otime.tv_sec =
3631 btrfs_timespec_sec(leaf, &inode_item->otime);
3632 BTRFS_I(inode)->i_otime.tv_nsec =
3633 btrfs_timespec_nsec(leaf, &inode_item->otime);
5f39d397 3634
a76a3cd4 3635 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 3636 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
5dc562c5
JB
3637 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3638
6e17d30b
YD
3639 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3640 inode->i_generation = BTRFS_I(inode)->generation;
3641 inode->i_rdev = 0;
3642 rdev = btrfs_inode_rdev(leaf, inode_item);
3643
3644 BTRFS_I(inode)->index_cnt = (u64)-1;
3645 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3646
3647cache_index:
5dc562c5
JB
3648 /*
3649 * If we were modified in the current generation and evicted from memory
3650 * and then re-read we need to do a full sync since we don't have any
3651 * idea about which extents were modified before we were evicted from
3652 * cache.
6e17d30b
YD
3653 *
3654 * This is required for both inode re-read from disk and delayed inode
3655 * in delayed_nodes_tree.
5dc562c5 3656 */
0b246afa 3657 if (BTRFS_I(inode)->last_trans == fs_info->generation)
5dc562c5
JB
3658 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3659 &BTRFS_I(inode)->runtime_flags);
3660
bde6c242
FM
3661 /*
3662 * We don't persist the id of the transaction where an unlink operation
3663 * against the inode was last made. So here we assume the inode might
3664 * have been evicted, and therefore the exact value of last_unlink_trans
3665 * lost, and set it to last_trans to avoid metadata inconsistencies
3666 * between the inode and its parent if the inode is fsync'ed and the log
3667 * replayed. For example, in the scenario:
3668 *
3669 * touch mydir/foo
3670 * ln mydir/foo mydir/bar
3671 * sync
3672 * unlink mydir/bar
3673 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3674 * xfs_io -c fsync mydir/foo
3675 * <power failure>
3676 * mount fs, triggers fsync log replay
3677 *
3678 * We must make sure that when we fsync our inode foo we also log its
3679 * parent inode, otherwise after log replay the parent still has the
3680 * dentry with the "bar" name but our inode foo has a link count of 1
3681 * and doesn't have an inode ref with the name "bar" anymore.
3682 *
3683 * Setting last_unlink_trans to last_trans is a pessimistic approach,
01327610 3684 * but it guarantees correctness at the expense of occasional full
bde6c242
FM
3685 * transaction commits on fsync if our inode is a directory, or if our
3686 * inode is not a directory, logging its parent unnecessarily.
3687 */
3688 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3689
67de1176
MX
3690 path->slots[0]++;
3691 if (inode->i_nlink != 1 ||
3692 path->slots[0] >= btrfs_header_nritems(leaf))
3693 goto cache_acl;
3694
3695 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4a0cc7ca 3696 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
67de1176
MX
3697 goto cache_acl;
3698
3699 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3700 if (location.type == BTRFS_INODE_REF_KEY) {
3701 struct btrfs_inode_ref *ref;
3702
3703 ref = (struct btrfs_inode_ref *)ptr;
3704 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3705 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3706 struct btrfs_inode_extref *extref;
3707
3708 extref = (struct btrfs_inode_extref *)ptr;
3709 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3710 extref);
3711 }
2f7e33d4 3712cache_acl:
46a53cca
CM
3713 /*
3714 * try to precache a NULL acl entry for files that don't have
3715 * any xattrs or acls
3716 */
33345d01 3717 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
f85b7379 3718 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
63541927
FDBM
3719 if (first_xattr_slot != -1) {
3720 path->slots[0] = first_xattr_slot;
3721 ret = btrfs_load_inode_props(inode, path);
3722 if (ret)
0b246afa 3723 btrfs_err(fs_info,
351fd353 3724 "error loading props for ino %llu (root %llu): %d",
4a0cc7ca 3725 btrfs_ino(BTRFS_I(inode)),
63541927
FDBM
3726 root->root_key.objectid, ret);
3727 }
3728 btrfs_free_path(path);
3729
72c04902
AV
3730 if (!maybe_acls)
3731 cache_no_acl(inode);
46a53cca 3732
39279cc3 3733 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
3734 case S_IFREG:
3735 inode->i_mapping->a_ops = &btrfs_aops;
d1310b2e 3736 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
3737 inode->i_fop = &btrfs_file_operations;
3738 inode->i_op = &btrfs_file_inode_operations;
3739 break;
3740 case S_IFDIR:
3741 inode->i_fop = &btrfs_dir_file_operations;
67ade058 3742 inode->i_op = &btrfs_dir_inode_operations;
39279cc3
CM
3743 break;
3744 case S_IFLNK:
3745 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 3746 inode_nohighmem(inode);
39279cc3
CM
3747 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3748 break;
618e21d5 3749 default:
0279b4cd 3750 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
3751 init_special_inode(inode, inode->i_mode, rdev);
3752 break;
39279cc3 3753 }
6cbff00f
CH
3754
3755 btrfs_update_iflags(inode);
67710892 3756 return 0;
39279cc3
CM
3757
3758make_bad:
39279cc3 3759 btrfs_free_path(path);
39279cc3 3760 make_bad_inode(inode);
67710892 3761 return ret;
39279cc3
CM
3762}
3763
d352ac68
CM
3764/*
3765 * given a leaf and an inode, copy the inode fields into the leaf
3766 */
e02119d5
CM
3767static void fill_inode_item(struct btrfs_trans_handle *trans,
3768 struct extent_buffer *leaf,
5f39d397 3769 struct btrfs_inode_item *item,
39279cc3
CM
3770 struct inode *inode)
3771{
51fab693
LB
3772 struct btrfs_map_token token;
3773
3774 btrfs_init_map_token(&token);
5f39d397 3775
51fab693
LB
3776 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3777 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3778 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3779 &token);
3780 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3781 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
5f39d397 3782
a937b979 3783 btrfs_set_token_timespec_sec(leaf, &item->atime,
51fab693 3784 inode->i_atime.tv_sec, &token);
a937b979 3785 btrfs_set_token_timespec_nsec(leaf, &item->atime,
51fab693 3786 inode->i_atime.tv_nsec, &token);
5f39d397 3787
a937b979 3788 btrfs_set_token_timespec_sec(leaf, &item->mtime,
51fab693 3789 inode->i_mtime.tv_sec, &token);
a937b979 3790 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
51fab693 3791 inode->i_mtime.tv_nsec, &token);
5f39d397 3792
a937b979 3793 btrfs_set_token_timespec_sec(leaf, &item->ctime,
51fab693 3794 inode->i_ctime.tv_sec, &token);
a937b979 3795 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
51fab693 3796 inode->i_ctime.tv_nsec, &token);
5f39d397 3797
9cc97d64 3798 btrfs_set_token_timespec_sec(leaf, &item->otime,
3799 BTRFS_I(inode)->i_otime.tv_sec, &token);
3800 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3801 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3802
51fab693
LB
3803 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3804 &token);
3805 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3806 &token);
3807 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3808 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3809 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3810 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3811 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
39279cc3
CM
3812}
3813
d352ac68
CM
3814/*
3815 * copy everything in the in-memory inode into the btree.
3816 */
2115133f 3817static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
d397712b 3818 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
3819{
3820 struct btrfs_inode_item *inode_item;
3821 struct btrfs_path *path;
5f39d397 3822 struct extent_buffer *leaf;
39279cc3
CM
3823 int ret;
3824
3825 path = btrfs_alloc_path();
16cdcec7
MX
3826 if (!path)
3827 return -ENOMEM;
3828
b9473439 3829 path->leave_spinning = 1;
16cdcec7
MX
3830 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3831 1);
39279cc3
CM
3832 if (ret) {
3833 if (ret > 0)
3834 ret = -ENOENT;
3835 goto failed;
3836 }
3837
5f39d397
CM
3838 leaf = path->nodes[0];
3839 inode_item = btrfs_item_ptr(leaf, path->slots[0],
16cdcec7 3840 struct btrfs_inode_item);
39279cc3 3841
e02119d5 3842 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 3843 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 3844 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
3845 ret = 0;
3846failed:
39279cc3
CM
3847 btrfs_free_path(path);
3848 return ret;
3849}
3850
2115133f
CM
3851/*
3852 * copy everything in the in-memory inode into the btree.
3853 */
3854noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3855 struct btrfs_root *root, struct inode *inode)
3856{
0b246afa 3857 struct btrfs_fs_info *fs_info = root->fs_info;
2115133f
CM
3858 int ret;
3859
3860 /*
3861 * If the inode is a free space inode, we can deadlock during commit
3862 * if we put it into the delayed code.
3863 *
3864 * The data relocation inode should also be directly updated
3865 * without delay
3866 */
70ddc553 3867 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
1d52c78a 3868 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
0b246afa 3869 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
8ea05e3a
AB
3870 btrfs_update_root_times(trans, root);
3871
2115133f
CM
3872 ret = btrfs_delayed_update_inode(trans, root, inode);
3873 if (!ret)
3874 btrfs_set_inode_last_trans(trans, inode);
3875 return ret;
3876 }
3877
3878 return btrfs_update_inode_item(trans, root, inode);
3879}
3880
be6aef60
JB
3881noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3882 struct btrfs_root *root,
3883 struct inode *inode)
2115133f
CM
3884{
3885 int ret;
3886
3887 ret = btrfs_update_inode(trans, root, inode);
3888 if (ret == -ENOSPC)
3889 return btrfs_update_inode_item(trans, root, inode);
3890 return ret;
3891}
3892
d352ac68
CM
3893/*
3894 * unlink helper that gets used here in inode.c and in the tree logging
3895 * recovery code. It remove a link in a directory with a given name, and
3896 * also drops the back refs in the inode to the directory
3897 */
92986796
AV
3898static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3899 struct btrfs_root *root,
4ec5934e
NB
3900 struct btrfs_inode *dir,
3901 struct btrfs_inode *inode,
92986796 3902 const char *name, int name_len)
39279cc3 3903{
0b246afa 3904 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 3905 struct btrfs_path *path;
39279cc3 3906 int ret = 0;
5f39d397 3907 struct extent_buffer *leaf;
39279cc3 3908 struct btrfs_dir_item *di;
5f39d397 3909 struct btrfs_key key;
aec7477b 3910 u64 index;
4ec5934e
NB
3911 u64 ino = btrfs_ino(inode);
3912 u64 dir_ino = btrfs_ino(dir);
39279cc3
CM
3913
3914 path = btrfs_alloc_path();
54aa1f4d
CM
3915 if (!path) {
3916 ret = -ENOMEM;
554233a6 3917 goto out;
54aa1f4d
CM
3918 }
3919
b9473439 3920 path->leave_spinning = 1;
33345d01 3921 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
39279cc3
CM
3922 name, name_len, -1);
3923 if (IS_ERR(di)) {
3924 ret = PTR_ERR(di);
3925 goto err;
3926 }
3927 if (!di) {
3928 ret = -ENOENT;
3929 goto err;
3930 }
5f39d397
CM
3931 leaf = path->nodes[0];
3932 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 3933 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
3934 if (ret)
3935 goto err;
b3b4aa74 3936 btrfs_release_path(path);
39279cc3 3937
67de1176
MX
3938 /*
3939 * If we don't have dir index, we have to get it by looking up
3940 * the inode ref, since we get the inode ref, remove it directly,
3941 * it is unnecessary to do delayed deletion.
3942 *
3943 * But if we have dir index, needn't search inode ref to get it.
3944 * Since the inode ref is close to the inode item, it is better
3945 * that we delay to delete it, and just do this deletion when
3946 * we update the inode item.
3947 */
4ec5934e
NB
3948 if (inode->dir_index) {
3949 ret = btrfs_delayed_delete_inode_ref(inode);
67de1176 3950 if (!ret) {
4ec5934e 3951 index = inode->dir_index;
67de1176
MX
3952 goto skip_backref;
3953 }
3954 }
3955
33345d01
LZ
3956 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3957 dir_ino, &index);
aec7477b 3958 if (ret) {
0b246afa 3959 btrfs_info(fs_info,
c2cf52eb 3960 "failed to delete reference to %.*s, inode %llu parent %llu",
c1c9ff7c 3961 name_len, name, ino, dir_ino);
66642832 3962 btrfs_abort_transaction(trans, ret);
aec7477b
JB
3963 goto err;
3964 }
67de1176 3965skip_backref:
4ec5934e 3966 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
79787eaa 3967 if (ret) {
66642832 3968 btrfs_abort_transaction(trans, ret);
39279cc3 3969 goto err;
79787eaa 3970 }
39279cc3 3971
4ec5934e
NB
3972 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3973 dir_ino);
79787eaa 3974 if (ret != 0 && ret != -ENOENT) {
66642832 3975 btrfs_abort_transaction(trans, ret);
79787eaa
JM
3976 goto err;
3977 }
e02119d5 3978
4ec5934e
NB
3979 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3980 index);
6418c961
CM
3981 if (ret == -ENOENT)
3982 ret = 0;
d4e3991b 3983 else if (ret)
66642832 3984 btrfs_abort_transaction(trans, ret);
39279cc3
CM
3985err:
3986 btrfs_free_path(path);
e02119d5
CM
3987 if (ret)
3988 goto out;
3989
6ef06d27 3990 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4ec5934e
NB
3991 inode_inc_iversion(&inode->vfs_inode);
3992 inode_inc_iversion(&dir->vfs_inode);
3993 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3994 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3995 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
e02119d5 3996out:
39279cc3
CM
3997 return ret;
3998}
3999
92986796
AV
4000int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4001 struct btrfs_root *root,
4ec5934e 4002 struct btrfs_inode *dir, struct btrfs_inode *inode,
92986796
AV
4003 const char *name, int name_len)
4004{
4005 int ret;
4006 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4007 if (!ret) {
4ec5934e
NB
4008 drop_nlink(&inode->vfs_inode);
4009 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
92986796
AV
4010 }
4011 return ret;
4012}
39279cc3 4013
a22285a6
YZ
4014/*
4015 * helper to start transaction for unlink and rmdir.
4016 *
d52be818
JB
4017 * unlink and rmdir are special in btrfs, they do not always free space, so
4018 * if we cannot make our reservations the normal way try and see if there is
4019 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4020 * allow the unlink to occur.
a22285a6 4021 */
d52be818 4022static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4df27c4d 4023{
a22285a6 4024 struct btrfs_root *root = BTRFS_I(dir)->root;
4df27c4d 4025
e70bea5f
JB
4026 /*
4027 * 1 for the possible orphan item
4028 * 1 for the dir item
4029 * 1 for the dir index
4030 * 1 for the inode ref
e70bea5f
JB
4031 * 1 for the inode
4032 */
8eab77ff 4033 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
a22285a6
YZ
4034}
4035
4036static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4037{
4038 struct btrfs_root *root = BTRFS_I(dir)->root;
4039 struct btrfs_trans_handle *trans;
2b0143b5 4040 struct inode *inode = d_inode(dentry);
a22285a6 4041 int ret;
a22285a6 4042
d52be818 4043 trans = __unlink_start_trans(dir);
a22285a6
YZ
4044 if (IS_ERR(trans))
4045 return PTR_ERR(trans);
5f39d397 4046
4ec5934e
NB
4047 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4048 0);
12fcfd22 4049
4ec5934e
NB
4050 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4051 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4052 dentry->d_name.len);
b532402e
TI
4053 if (ret)
4054 goto out;
7b128766 4055
a22285a6 4056 if (inode->i_nlink == 0) {
73f2e545 4057 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
b532402e
TI
4058 if (ret)
4059 goto out;
a22285a6 4060 }
7b128766 4061
b532402e 4062out:
3a45bb20 4063 btrfs_end_transaction(trans);
2ff7e61e 4064 btrfs_btree_balance_dirty(root->fs_info);
39279cc3
CM
4065 return ret;
4066}
4067
4df27c4d
YZ
4068int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4069 struct btrfs_root *root,
4070 struct inode *dir, u64 objectid,
4071 const char *name, int name_len)
4072{
0b246afa 4073 struct btrfs_fs_info *fs_info = root->fs_info;
4df27c4d
YZ
4074 struct btrfs_path *path;
4075 struct extent_buffer *leaf;
4076 struct btrfs_dir_item *di;
4077 struct btrfs_key key;
4078 u64 index;
4079 int ret;
4a0cc7ca 4080 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4df27c4d
YZ
4081
4082 path = btrfs_alloc_path();
4083 if (!path)
4084 return -ENOMEM;
4085
33345d01 4086 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4df27c4d 4087 name, name_len, -1);
79787eaa
JM
4088 if (IS_ERR_OR_NULL(di)) {
4089 if (!di)
4090 ret = -ENOENT;
4091 else
4092 ret = PTR_ERR(di);
4093 goto out;
4094 }
4df27c4d
YZ
4095
4096 leaf = path->nodes[0];
4097 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4098 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4099 ret = btrfs_delete_one_dir_name(trans, root, path, di);
79787eaa 4100 if (ret) {
66642832 4101 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4102 goto out;
4103 }
b3b4aa74 4104 btrfs_release_path(path);
4df27c4d 4105
0b246afa
JM
4106 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4107 root->root_key.objectid, dir_ino,
4108 &index, name, name_len);
4df27c4d 4109 if (ret < 0) {
79787eaa 4110 if (ret != -ENOENT) {
66642832 4111 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4112 goto out;
4113 }
33345d01 4114 di = btrfs_search_dir_index_item(root, path, dir_ino,
4df27c4d 4115 name, name_len);
79787eaa
JM
4116 if (IS_ERR_OR_NULL(di)) {
4117 if (!di)
4118 ret = -ENOENT;
4119 else
4120 ret = PTR_ERR(di);
66642832 4121 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4122 goto out;
4123 }
4df27c4d
YZ
4124
4125 leaf = path->nodes[0];
4126 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
b3b4aa74 4127 btrfs_release_path(path);
4df27c4d
YZ
4128 index = key.offset;
4129 }
945d8962 4130 btrfs_release_path(path);
4df27c4d 4131
e67bbbb9 4132 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
79787eaa 4133 if (ret) {
66642832 4134 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4135 goto out;
4136 }
4df27c4d 4137
6ef06d27 4138 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
0c4d2d95 4139 inode_inc_iversion(dir);
c2050a45 4140 dir->i_mtime = dir->i_ctime = current_time(dir);
5a24e84c 4141 ret = btrfs_update_inode_fallback(trans, root, dir);
79787eaa 4142 if (ret)
66642832 4143 btrfs_abort_transaction(trans, ret);
79787eaa 4144out:
71d7aed0 4145 btrfs_free_path(path);
79787eaa 4146 return ret;
4df27c4d
YZ
4147}
4148
39279cc3
CM
4149static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4150{
2b0143b5 4151 struct inode *inode = d_inode(dentry);
1832a6d5 4152 int err = 0;
39279cc3 4153 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 4154 struct btrfs_trans_handle *trans;
44f714da 4155 u64 last_unlink_trans;
39279cc3 4156
b3ae244e 4157 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
134d4512 4158 return -ENOTEMPTY;
4a0cc7ca 4159 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
b3ae244e 4160 return -EPERM;
134d4512 4161
d52be818 4162 trans = __unlink_start_trans(dir);
a22285a6 4163 if (IS_ERR(trans))
5df6a9f6 4164 return PTR_ERR(trans);
5df6a9f6 4165
4a0cc7ca 4166 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4df27c4d
YZ
4167 err = btrfs_unlink_subvol(trans, root, dir,
4168 BTRFS_I(inode)->location.objectid,
4169 dentry->d_name.name,
4170 dentry->d_name.len);
4171 goto out;
4172 }
4173
73f2e545 4174 err = btrfs_orphan_add(trans, BTRFS_I(inode));
7b128766 4175 if (err)
4df27c4d 4176 goto out;
7b128766 4177
44f714da
FM
4178 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4179
39279cc3 4180 /* now the directory is empty */
4ec5934e
NB
4181 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4182 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4183 dentry->d_name.len);
44f714da 4184 if (!err) {
6ef06d27 4185 btrfs_i_size_write(BTRFS_I(inode), 0);
44f714da
FM
4186 /*
4187 * Propagate the last_unlink_trans value of the deleted dir to
4188 * its parent directory. This is to prevent an unrecoverable
4189 * log tree in the case we do something like this:
4190 * 1) create dir foo
4191 * 2) create snapshot under dir foo
4192 * 3) delete the snapshot
4193 * 4) rmdir foo
4194 * 5) mkdir foo
4195 * 6) fsync foo or some file inside foo
4196 */
4197 if (last_unlink_trans >= trans->transid)
4198 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4199 }
4df27c4d 4200out:
3a45bb20 4201 btrfs_end_transaction(trans);
2ff7e61e 4202 btrfs_btree_balance_dirty(root->fs_info);
3954401f 4203
39279cc3
CM
4204 return err;
4205}
4206
28f75a0e
CM
4207static int truncate_space_check(struct btrfs_trans_handle *trans,
4208 struct btrfs_root *root,
4209 u64 bytes_deleted)
4210{
0b246afa 4211 struct btrfs_fs_info *fs_info = root->fs_info;
28f75a0e
CM
4212 int ret;
4213
dc95f7bf
JB
4214 /*
4215 * This is only used to apply pressure to the enospc system, we don't
4216 * intend to use this reservation at all.
4217 */
2ff7e61e 4218 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
0b246afa
JM
4219 bytes_deleted *= fs_info->nodesize;
4220 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
28f75a0e 4221 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
dc95f7bf 4222 if (!ret) {
0b246afa 4223 trace_btrfs_space_reservation(fs_info, "transaction",
dc95f7bf
JB
4224 trans->transid,
4225 bytes_deleted, 1);
28f75a0e 4226 trans->bytes_reserved += bytes_deleted;
dc95f7bf 4227 }
28f75a0e
CM
4228 return ret;
4229
4230}
4231
0305cd5f
FM
4232static int truncate_inline_extent(struct inode *inode,
4233 struct btrfs_path *path,
4234 struct btrfs_key *found_key,
4235 const u64 item_end,
4236 const u64 new_size)
4237{
4238 struct extent_buffer *leaf = path->nodes[0];
4239 int slot = path->slots[0];
4240 struct btrfs_file_extent_item *fi;
4241 u32 size = (u32)(new_size - found_key->offset);
4242 struct btrfs_root *root = BTRFS_I(inode)->root;
4243
4244 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4245
4246 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4247 loff_t offset = new_size;
09cbfeaf 4248 loff_t page_end = ALIGN(offset, PAGE_SIZE);
0305cd5f
FM
4249
4250 /*
4251 * Zero out the remaining of the last page of our inline extent,
4252 * instead of directly truncating our inline extent here - that
4253 * would be much more complex (decompressing all the data, then
4254 * compressing the truncated data, which might be bigger than
4255 * the size of the inline extent, resize the extent, etc).
4256 * We release the path because to get the page we might need to
4257 * read the extent item from disk (data not in the page cache).
4258 */
4259 btrfs_release_path(path);
9703fefe
CR
4260 return btrfs_truncate_block(inode, offset, page_end - offset,
4261 0);
0305cd5f
FM
4262 }
4263
4264 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4265 size = btrfs_file_extent_calc_inline_size(size);
2ff7e61e 4266 btrfs_truncate_item(root->fs_info, path, size, 1);
0305cd5f
FM
4267
4268 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4269 inode_sub_bytes(inode, item_end + 1 - new_size);
4270
4271 return 0;
4272}
4273
39279cc3
CM
4274/*
4275 * this can truncate away extent items, csum items and directory items.
4276 * It starts at a high offset and removes keys until it can't find
d352ac68 4277 * any higher than new_size
39279cc3
CM
4278 *
4279 * csum items that cross the new i_size are truncated to the new size
4280 * as well.
7b128766
JB
4281 *
4282 * min_type is the minimum key type to truncate down to. If set to 0, this
4283 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 4284 */
8082510e
YZ
4285int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4286 struct btrfs_root *root,
4287 struct inode *inode,
4288 u64 new_size, u32 min_type)
39279cc3 4289{
0b246afa 4290 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 4291 struct btrfs_path *path;
5f39d397 4292 struct extent_buffer *leaf;
39279cc3 4293 struct btrfs_file_extent_item *fi;
8082510e
YZ
4294 struct btrfs_key key;
4295 struct btrfs_key found_key;
39279cc3 4296 u64 extent_start = 0;
db94535d 4297 u64 extent_num_bytes = 0;
5d4f98a2 4298 u64 extent_offset = 0;
39279cc3 4299 u64 item_end = 0;
c1aa4575 4300 u64 last_size = new_size;
8082510e 4301 u32 found_type = (u8)-1;
39279cc3
CM
4302 int found_extent;
4303 int del_item;
85e21bac
CM
4304 int pending_del_nr = 0;
4305 int pending_del_slot = 0;
179e29e4 4306 int extent_type = -1;
8082510e
YZ
4307 int ret;
4308 int err = 0;
4a0cc7ca 4309 u64 ino = btrfs_ino(BTRFS_I(inode));
28ed1345 4310 u64 bytes_deleted = 0;
1262133b
JB
4311 bool be_nice = 0;
4312 bool should_throttle = 0;
28f75a0e 4313 bool should_end = 0;
8082510e
YZ
4314
4315 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 4316
28ed1345
CM
4317 /*
4318 * for non-free space inodes and ref cows, we want to back off from
4319 * time to time
4320 */
70ddc553 4321 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
28ed1345
CM
4322 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4323 be_nice = 1;
4324
0eb0e19c
MF
4325 path = btrfs_alloc_path();
4326 if (!path)
4327 return -ENOMEM;
e4058b54 4328 path->reada = READA_BACK;
0eb0e19c 4329
5dc562c5
JB
4330 /*
4331 * We want to drop from the next block forward in case this new size is
4332 * not block aligned since we will be keeping the last block of the
4333 * extent just the way it is.
4334 */
27cdeb70 4335 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4336 root == fs_info->tree_root)
dcdbc059 4337 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
0b246afa 4338 fs_info->sectorsize),
da17066c 4339 (u64)-1, 0);
8082510e 4340
16cdcec7
MX
4341 /*
4342 * This function is also used to drop the items in the log tree before
4343 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4344 * it is used to drop the loged items. So we shouldn't kill the delayed
4345 * items.
4346 */
4347 if (min_type == 0 && root == BTRFS_I(inode)->root)
4ccb5c72 4348 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
16cdcec7 4349
33345d01 4350 key.objectid = ino;
39279cc3 4351 key.offset = (u64)-1;
5f39d397
CM
4352 key.type = (u8)-1;
4353
85e21bac 4354search_again:
28ed1345
CM
4355 /*
4356 * with a 16K leaf size and 128MB extents, you can actually queue
4357 * up a huge file in a single leaf. Most of the time that
4358 * bytes_deleted is > 0, it will be huge by the time we get here
4359 */
ee22184b 4360 if (be_nice && bytes_deleted > SZ_32M) {
3a45bb20 4361 if (btrfs_should_end_transaction(trans)) {
28ed1345
CM
4362 err = -EAGAIN;
4363 goto error;
4364 }
4365 }
4366
4367
b9473439 4368 path->leave_spinning = 1;
85e21bac 4369 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8082510e
YZ
4370 if (ret < 0) {
4371 err = ret;
4372 goto out;
4373 }
d397712b 4374
85e21bac 4375 if (ret > 0) {
e02119d5
CM
4376 /* there are no items in the tree for us to truncate, we're
4377 * done
4378 */
8082510e
YZ
4379 if (path->slots[0] == 0)
4380 goto out;
85e21bac
CM
4381 path->slots[0]--;
4382 }
4383
d397712b 4384 while (1) {
39279cc3 4385 fi = NULL;
5f39d397
CM
4386 leaf = path->nodes[0];
4387 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 4388 found_type = found_key.type;
39279cc3 4389
33345d01 4390 if (found_key.objectid != ino)
39279cc3 4391 break;
5f39d397 4392
85e21bac 4393 if (found_type < min_type)
39279cc3
CM
4394 break;
4395
5f39d397 4396 item_end = found_key.offset;
39279cc3 4397 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 4398 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 4399 struct btrfs_file_extent_item);
179e29e4
CM
4400 extent_type = btrfs_file_extent_type(leaf, fi);
4401 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 4402 item_end +=
db94535d 4403 btrfs_file_extent_num_bytes(leaf, fi);
179e29e4 4404 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
179e29e4 4405 item_end += btrfs_file_extent_inline_len(leaf,
514ac8ad 4406 path->slots[0], fi);
39279cc3 4407 }
008630c1 4408 item_end--;
39279cc3 4409 }
8082510e
YZ
4410 if (found_type > min_type) {
4411 del_item = 1;
4412 } else {
76b42abb 4413 if (item_end < new_size)
b888db2b 4414 break;
8082510e
YZ
4415 if (found_key.offset >= new_size)
4416 del_item = 1;
4417 else
4418 del_item = 0;
39279cc3 4419 }
39279cc3 4420 found_extent = 0;
39279cc3 4421 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
4422 if (found_type != BTRFS_EXTENT_DATA_KEY)
4423 goto delete;
4424
7f4f6e0a
JB
4425 if (del_item)
4426 last_size = found_key.offset;
4427 else
4428 last_size = new_size;
4429
179e29e4 4430 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 4431 u64 num_dec;
db94535d 4432 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
f70a9a6b 4433 if (!del_item) {
db94535d
CM
4434 u64 orig_num_bytes =
4435 btrfs_file_extent_num_bytes(leaf, fi);
fda2832f
QW
4436 extent_num_bytes = ALIGN(new_size -
4437 found_key.offset,
0b246afa 4438 fs_info->sectorsize);
db94535d
CM
4439 btrfs_set_file_extent_num_bytes(leaf, fi,
4440 extent_num_bytes);
4441 num_dec = (orig_num_bytes -
9069218d 4442 extent_num_bytes);
27cdeb70
MX
4443 if (test_bit(BTRFS_ROOT_REF_COWS,
4444 &root->state) &&
4445 extent_start != 0)
a76a3cd4 4446 inode_sub_bytes(inode, num_dec);
5f39d397 4447 btrfs_mark_buffer_dirty(leaf);
39279cc3 4448 } else {
db94535d
CM
4449 extent_num_bytes =
4450 btrfs_file_extent_disk_num_bytes(leaf,
4451 fi);
5d4f98a2
YZ
4452 extent_offset = found_key.offset -
4453 btrfs_file_extent_offset(leaf, fi);
4454
39279cc3 4455 /* FIXME blocksize != 4096 */
9069218d 4456 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
4457 if (extent_start != 0) {
4458 found_extent = 1;
27cdeb70
MX
4459 if (test_bit(BTRFS_ROOT_REF_COWS,
4460 &root->state))
a76a3cd4 4461 inode_sub_bytes(inode, num_dec);
e02119d5 4462 }
39279cc3 4463 }
9069218d 4464 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
4465 /*
4466 * we can't truncate inline items that have had
4467 * special encodings
4468 */
4469 if (!del_item &&
c8b97818
CM
4470 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4471 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
514ac8ad
CM
4472
4473 /*
0305cd5f
FM
4474 * Need to release path in order to truncate a
4475 * compressed extent. So delete any accumulated
4476 * extent items so far.
514ac8ad 4477 */
0305cd5f
FM
4478 if (btrfs_file_extent_compression(leaf, fi) !=
4479 BTRFS_COMPRESS_NONE && pending_del_nr) {
4480 err = btrfs_del_items(trans, root, path,
4481 pending_del_slot,
4482 pending_del_nr);
4483 if (err) {
4484 btrfs_abort_transaction(trans,
0305cd5f
FM
4485 err);
4486 goto error;
4487 }
4488 pending_del_nr = 0;
4489 }
4490
4491 err = truncate_inline_extent(inode, path,
4492 &found_key,
4493 item_end,
4494 new_size);
4495 if (err) {
66642832 4496 btrfs_abort_transaction(trans, err);
0305cd5f
FM
4497 goto error;
4498 }
27cdeb70
MX
4499 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4500 &root->state)) {
0305cd5f 4501 inode_sub_bytes(inode, item_end + 1 - new_size);
9069218d 4502 }
39279cc3 4503 }
179e29e4 4504delete:
39279cc3 4505 if (del_item) {
85e21bac
CM
4506 if (!pending_del_nr) {
4507 /* no pending yet, add ourselves */
4508 pending_del_slot = path->slots[0];
4509 pending_del_nr = 1;
4510 } else if (pending_del_nr &&
4511 path->slots[0] + 1 == pending_del_slot) {
4512 /* hop on the pending chunk */
4513 pending_del_nr++;
4514 pending_del_slot = path->slots[0];
4515 } else {
d397712b 4516 BUG();
85e21bac 4517 }
39279cc3
CM
4518 } else {
4519 break;
4520 }
28f75a0e
CM
4521 should_throttle = 0;
4522
27cdeb70
MX
4523 if (found_extent &&
4524 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
0b246afa 4525 root == fs_info->tree_root)) {
b9473439 4526 btrfs_set_path_blocking(path);
28ed1345 4527 bytes_deleted += extent_num_bytes;
2ff7e61e 4528 ret = btrfs_free_extent(trans, fs_info, extent_start,
5d4f98a2
YZ
4529 extent_num_bytes, 0,
4530 btrfs_header_owner(leaf),
b06c4bf5 4531 ino, extent_offset);
39279cc3 4532 BUG_ON(ret);
2ff7e61e
JM
4533 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4534 btrfs_async_run_delayed_refs(fs_info,
dd4b857a
WX
4535 trans->delayed_ref_updates * 2,
4536 trans->transid, 0);
28f75a0e
CM
4537 if (be_nice) {
4538 if (truncate_space_check(trans, root,
4539 extent_num_bytes)) {
4540 should_end = 1;
4541 }
4542 if (btrfs_should_throttle_delayed_refs(trans,
2ff7e61e 4543 fs_info))
28f75a0e 4544 should_throttle = 1;
28f75a0e 4545 }
39279cc3 4546 }
85e21bac 4547
8082510e
YZ
4548 if (found_type == BTRFS_INODE_ITEM_KEY)
4549 break;
4550
4551 if (path->slots[0] == 0 ||
1262133b 4552 path->slots[0] != pending_del_slot ||
28f75a0e 4553 should_throttle || should_end) {
8082510e
YZ
4554 if (pending_del_nr) {
4555 ret = btrfs_del_items(trans, root, path,
4556 pending_del_slot,
4557 pending_del_nr);
79787eaa 4558 if (ret) {
66642832 4559 btrfs_abort_transaction(trans, ret);
79787eaa
JM
4560 goto error;
4561 }
8082510e
YZ
4562 pending_del_nr = 0;
4563 }
b3b4aa74 4564 btrfs_release_path(path);
28f75a0e 4565 if (should_throttle) {
1262133b
JB
4566 unsigned long updates = trans->delayed_ref_updates;
4567 if (updates) {
4568 trans->delayed_ref_updates = 0;
2ff7e61e
JM
4569 ret = btrfs_run_delayed_refs(trans,
4570 fs_info,
4571 updates * 2);
1262133b
JB
4572 if (ret && !err)
4573 err = ret;
4574 }
4575 }
28f75a0e
CM
4576 /*
4577 * if we failed to refill our space rsv, bail out
4578 * and let the transaction restart
4579 */
4580 if (should_end) {
4581 err = -EAGAIN;
4582 goto error;
4583 }
85e21bac 4584 goto search_again;
8082510e
YZ
4585 } else {
4586 path->slots[0]--;
85e21bac 4587 }
39279cc3 4588 }
8082510e 4589out:
85e21bac
CM
4590 if (pending_del_nr) {
4591 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4592 pending_del_nr);
79787eaa 4593 if (ret)
66642832 4594 btrfs_abort_transaction(trans, ret);
85e21bac 4595 }
79787eaa 4596error:
76b42abb
FM
4597 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4598 ASSERT(last_size >= new_size);
4599 if (!err && last_size > new_size)
4600 last_size = new_size;
7f4f6e0a 4601 btrfs_ordered_update_i_size(inode, last_size, NULL);
76b42abb 4602 }
28ed1345 4603
39279cc3 4604 btrfs_free_path(path);
28ed1345 4605
19fd2df5
LB
4606 if (err == 0) {
4607 /* only inline file may have last_size != new_size */
4608 if (new_size >= fs_info->sectorsize ||
4609 new_size > fs_info->max_inline)
4610 ASSERT(last_size == new_size);
4611 }
4612
ee22184b 4613 if (be_nice && bytes_deleted > SZ_32M) {
28ed1345
CM
4614 unsigned long updates = trans->delayed_ref_updates;
4615 if (updates) {
4616 trans->delayed_ref_updates = 0;
2ff7e61e
JM
4617 ret = btrfs_run_delayed_refs(trans, fs_info,
4618 updates * 2);
28ed1345
CM
4619 if (ret && !err)
4620 err = ret;
4621 }
4622 }
8082510e 4623 return err;
39279cc3
CM
4624}
4625
4626/*
9703fefe 4627 * btrfs_truncate_block - read, zero a chunk and write a block
2aaa6655
JB
4628 * @inode - inode that we're zeroing
4629 * @from - the offset to start zeroing
4630 * @len - the length to zero, 0 to zero the entire range respective to the
4631 * offset
4632 * @front - zero up to the offset instead of from the offset on
4633 *
9703fefe 4634 * This will find the block for the "from" offset and cow the block and zero the
2aaa6655 4635 * part we want to zero. This is used with truncate and hole punching.
39279cc3 4636 */
9703fefe 4637int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
2aaa6655 4638 int front)
39279cc3 4639{
0b246afa 4640 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2aaa6655 4641 struct address_space *mapping = inode->i_mapping;
e6dcd2dc
CM
4642 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4643 struct btrfs_ordered_extent *ordered;
2ac55d41 4644 struct extent_state *cached_state = NULL;
e6dcd2dc 4645 char *kaddr;
0b246afa 4646 u32 blocksize = fs_info->sectorsize;
09cbfeaf 4647 pgoff_t index = from >> PAGE_SHIFT;
9703fefe 4648 unsigned offset = from & (blocksize - 1);
39279cc3 4649 struct page *page;
3b16a4e3 4650 gfp_t mask = btrfs_alloc_write_mask(mapping);
39279cc3 4651 int ret = 0;
9703fefe
CR
4652 u64 block_start;
4653 u64 block_end;
39279cc3 4654
2aaa6655
JB
4655 if ((offset & (blocksize - 1)) == 0 &&
4656 (!len || ((len & (blocksize - 1)) == 0)))
39279cc3 4657 goto out;
9703fefe 4658
7cf5b976 4659 ret = btrfs_delalloc_reserve_space(inode,
9703fefe 4660 round_down(from, blocksize), blocksize);
5d5e103a
JB
4661 if (ret)
4662 goto out;
39279cc3 4663
211c17f5 4664again:
3b16a4e3 4665 page = find_or_create_page(mapping, index, mask);
5d5e103a 4666 if (!page) {
7cf5b976 4667 btrfs_delalloc_release_space(inode,
9703fefe
CR
4668 round_down(from, blocksize),
4669 blocksize);
ac6a2b36 4670 ret = -ENOMEM;
39279cc3 4671 goto out;
5d5e103a 4672 }
e6dcd2dc 4673
9703fefe
CR
4674 block_start = round_down(from, blocksize);
4675 block_end = block_start + blocksize - 1;
e6dcd2dc 4676
39279cc3 4677 if (!PageUptodate(page)) {
9ebefb18 4678 ret = btrfs_readpage(NULL, page);
39279cc3 4679 lock_page(page);
211c17f5
CM
4680 if (page->mapping != mapping) {
4681 unlock_page(page);
09cbfeaf 4682 put_page(page);
211c17f5
CM
4683 goto again;
4684 }
39279cc3
CM
4685 if (!PageUptodate(page)) {
4686 ret = -EIO;
89642229 4687 goto out_unlock;
39279cc3
CM
4688 }
4689 }
211c17f5 4690 wait_on_page_writeback(page);
e6dcd2dc 4691
9703fefe 4692 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
e6dcd2dc
CM
4693 set_page_extent_mapped(page);
4694
9703fefe 4695 ordered = btrfs_lookup_ordered_extent(inode, block_start);
e6dcd2dc 4696 if (ordered) {
9703fefe 4697 unlock_extent_cached(io_tree, block_start, block_end,
2ac55d41 4698 &cached_state, GFP_NOFS);
e6dcd2dc 4699 unlock_page(page);
09cbfeaf 4700 put_page(page);
eb84ae03 4701 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
4702 btrfs_put_ordered_extent(ordered);
4703 goto again;
4704 }
4705
9703fefe 4706 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
9e8a4a8b
LB
4707 EXTENT_DIRTY | EXTENT_DELALLOC |
4708 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
2ac55d41 4709 0, 0, &cached_state, GFP_NOFS);
5d5e103a 4710
9703fefe 4711 ret = btrfs_set_extent_delalloc(inode, block_start, block_end,
ba8b04c1 4712 &cached_state, 0);
9ed74f2d 4713 if (ret) {
9703fefe 4714 unlock_extent_cached(io_tree, block_start, block_end,
2ac55d41 4715 &cached_state, GFP_NOFS);
9ed74f2d
JB
4716 goto out_unlock;
4717 }
4718
9703fefe 4719 if (offset != blocksize) {
2aaa6655 4720 if (!len)
9703fefe 4721 len = blocksize - offset;
e6dcd2dc 4722 kaddr = kmap(page);
2aaa6655 4723 if (front)
9703fefe
CR
4724 memset(kaddr + (block_start - page_offset(page)),
4725 0, offset);
2aaa6655 4726 else
9703fefe
CR
4727 memset(kaddr + (block_start - page_offset(page)) + offset,
4728 0, len);
e6dcd2dc
CM
4729 flush_dcache_page(page);
4730 kunmap(page);
4731 }
247e743c 4732 ClearPageChecked(page);
e6dcd2dc 4733 set_page_dirty(page);
9703fefe 4734 unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
2ac55d41 4735 GFP_NOFS);
39279cc3 4736
89642229 4737out_unlock:
5d5e103a 4738 if (ret)
9703fefe
CR
4739 btrfs_delalloc_release_space(inode, block_start,
4740 blocksize);
39279cc3 4741 unlock_page(page);
09cbfeaf 4742 put_page(page);
39279cc3
CM
4743out:
4744 return ret;
4745}
4746
16e7549f
JB
4747static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4748 u64 offset, u64 len)
4749{
0b246afa 4750 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
16e7549f
JB
4751 struct btrfs_trans_handle *trans;
4752 int ret;
4753
4754 /*
4755 * Still need to make sure the inode looks like it's been updated so
4756 * that any holes get logged if we fsync.
4757 */
0b246afa
JM
4758 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4759 BTRFS_I(inode)->last_trans = fs_info->generation;
16e7549f
JB
4760 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4761 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4762 return 0;
4763 }
4764
4765 /*
4766 * 1 - for the one we're dropping
4767 * 1 - for the one we're adding
4768 * 1 - for updating the inode.
4769 */
4770 trans = btrfs_start_transaction(root, 3);
4771 if (IS_ERR(trans))
4772 return PTR_ERR(trans);
4773
4774 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4775 if (ret) {
66642832 4776 btrfs_abort_transaction(trans, ret);
3a45bb20 4777 btrfs_end_transaction(trans);
16e7549f
JB
4778 return ret;
4779 }
4780
f85b7379
DS
4781 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4782 offset, 0, 0, len, 0, len, 0, 0, 0);
16e7549f 4783 if (ret)
66642832 4784 btrfs_abort_transaction(trans, ret);
16e7549f
JB
4785 else
4786 btrfs_update_inode(trans, root, inode);
3a45bb20 4787 btrfs_end_transaction(trans);
16e7549f
JB
4788 return ret;
4789}
4790
695a0d0d
JB
4791/*
4792 * This function puts in dummy file extents for the area we're creating a hole
4793 * for. So if we are truncating this file to a larger size we need to insert
4794 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4795 * the range between oldsize and size
4796 */
a41ad394 4797int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
39279cc3 4798{
0b246afa 4799 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9036c102
YZ
4800 struct btrfs_root *root = BTRFS_I(inode)->root;
4801 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a22285a6 4802 struct extent_map *em = NULL;
2ac55d41 4803 struct extent_state *cached_state = NULL;
5dc562c5 4804 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
0b246afa
JM
4805 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4806 u64 block_end = ALIGN(size, fs_info->sectorsize);
9036c102
YZ
4807 u64 last_byte;
4808 u64 cur_offset;
4809 u64 hole_size;
9ed74f2d 4810 int err = 0;
39279cc3 4811
a71754fc 4812 /*
9703fefe
CR
4813 * If our size started in the middle of a block we need to zero out the
4814 * rest of the block before we expand the i_size, otherwise we could
a71754fc
JB
4815 * expose stale data.
4816 */
9703fefe 4817 err = btrfs_truncate_block(inode, oldsize, 0, 0);
a71754fc
JB
4818 if (err)
4819 return err;
4820
9036c102
YZ
4821 if (size <= hole_start)
4822 return 0;
4823
9036c102
YZ
4824 while (1) {
4825 struct btrfs_ordered_extent *ordered;
fa7c1494 4826
ff13db41 4827 lock_extent_bits(io_tree, hole_start, block_end - 1,
d0082371 4828 &cached_state);
a776c6fa 4829 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
fa7c1494 4830 block_end - hole_start);
9036c102
YZ
4831 if (!ordered)
4832 break;
2ac55d41
JB
4833 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4834 &cached_state, GFP_NOFS);
fa7c1494 4835 btrfs_start_ordered_extent(inode, ordered, 1);
9036c102
YZ
4836 btrfs_put_ordered_extent(ordered);
4837 }
39279cc3 4838
9036c102
YZ
4839 cur_offset = hole_start;
4840 while (1) {
fc4f21b1 4841 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
9036c102 4842 block_end - cur_offset, 0);
79787eaa
JM
4843 if (IS_ERR(em)) {
4844 err = PTR_ERR(em);
f2767956 4845 em = NULL;
79787eaa
JM
4846 break;
4847 }
9036c102 4848 last_byte = min(extent_map_end(em), block_end);
0b246afa 4849 last_byte = ALIGN(last_byte, fs_info->sectorsize);
8082510e 4850 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5dc562c5 4851 struct extent_map *hole_em;
9036c102 4852 hole_size = last_byte - cur_offset;
9ed74f2d 4853
16e7549f
JB
4854 err = maybe_insert_hole(root, inode, cur_offset,
4855 hole_size);
4856 if (err)
3893e33b 4857 break;
dcdbc059 4858 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
4859 cur_offset + hole_size - 1, 0);
4860 hole_em = alloc_extent_map();
4861 if (!hole_em) {
4862 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4863 &BTRFS_I(inode)->runtime_flags);
4864 goto next;
4865 }
4866 hole_em->start = cur_offset;
4867 hole_em->len = hole_size;
4868 hole_em->orig_start = cur_offset;
8082510e 4869
5dc562c5
JB
4870 hole_em->block_start = EXTENT_MAP_HOLE;
4871 hole_em->block_len = 0;
b4939680 4872 hole_em->orig_block_len = 0;
cc95bef6 4873 hole_em->ram_bytes = hole_size;
0b246afa 4874 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5dc562c5 4875 hole_em->compress_type = BTRFS_COMPRESS_NONE;
0b246afa 4876 hole_em->generation = fs_info->generation;
8082510e 4877
5dc562c5
JB
4878 while (1) {
4879 write_lock(&em_tree->lock);
09a2a8f9 4880 err = add_extent_mapping(em_tree, hole_em, 1);
5dc562c5
JB
4881 write_unlock(&em_tree->lock);
4882 if (err != -EEXIST)
4883 break;
dcdbc059
NB
4884 btrfs_drop_extent_cache(BTRFS_I(inode),
4885 cur_offset,
5dc562c5
JB
4886 cur_offset +
4887 hole_size - 1, 0);
4888 }
4889 free_extent_map(hole_em);
9036c102 4890 }
16e7549f 4891next:
9036c102 4892 free_extent_map(em);
a22285a6 4893 em = NULL;
9036c102 4894 cur_offset = last_byte;
8082510e 4895 if (cur_offset >= block_end)
9036c102
YZ
4896 break;
4897 }
a22285a6 4898 free_extent_map(em);
2ac55d41
JB
4899 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4900 GFP_NOFS);
9036c102
YZ
4901 return err;
4902}
39279cc3 4903
3972f260 4904static int btrfs_setsize(struct inode *inode, struct iattr *attr)
8082510e 4905{
f4a2f4c5
MX
4906 struct btrfs_root *root = BTRFS_I(inode)->root;
4907 struct btrfs_trans_handle *trans;
a41ad394 4908 loff_t oldsize = i_size_read(inode);
3972f260
ES
4909 loff_t newsize = attr->ia_size;
4910 int mask = attr->ia_valid;
8082510e
YZ
4911 int ret;
4912
3972f260
ES
4913 /*
4914 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4915 * special case where we need to update the times despite not having
4916 * these flags set. For all other operations the VFS set these flags
4917 * explicitly if it wants a timestamp update.
4918 */
dff6efc3
CH
4919 if (newsize != oldsize) {
4920 inode_inc_iversion(inode);
4921 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4922 inode->i_ctime = inode->i_mtime =
c2050a45 4923 current_time(inode);
dff6efc3 4924 }
3972f260 4925
a41ad394 4926 if (newsize > oldsize) {
9ea24bbe
FM
4927 /*
4928 * Don't do an expanding truncate while snapshoting is ongoing.
4929 * This is to ensure the snapshot captures a fully consistent
4930 * state of this file - if the snapshot captures this expanding
4931 * truncation, it must capture all writes that happened before
4932 * this truncation.
4933 */
0bc19f90 4934 btrfs_wait_for_snapshot_creation(root);
a41ad394 4935 ret = btrfs_cont_expand(inode, oldsize, newsize);
9ea24bbe
FM
4936 if (ret) {
4937 btrfs_end_write_no_snapshoting(root);
8082510e 4938 return ret;
9ea24bbe 4939 }
8082510e 4940
f4a2f4c5 4941 trans = btrfs_start_transaction(root, 1);
9ea24bbe
FM
4942 if (IS_ERR(trans)) {
4943 btrfs_end_write_no_snapshoting(root);
f4a2f4c5 4944 return PTR_ERR(trans);
9ea24bbe 4945 }
f4a2f4c5
MX
4946
4947 i_size_write(inode, newsize);
4948 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
27772b68 4949 pagecache_isize_extended(inode, oldsize, newsize);
f4a2f4c5 4950 ret = btrfs_update_inode(trans, root, inode);
9ea24bbe 4951 btrfs_end_write_no_snapshoting(root);
3a45bb20 4952 btrfs_end_transaction(trans);
a41ad394 4953 } else {
8082510e 4954
a41ad394
JB
4955 /*
4956 * We're truncating a file that used to have good data down to
4957 * zero. Make sure it gets into the ordered flush list so that
4958 * any new writes get down to disk quickly.
4959 */
4960 if (newsize == 0)
72ac3c0d
JB
4961 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4962 &BTRFS_I(inode)->runtime_flags);
8082510e 4963
f3fe820c
JB
4964 /*
4965 * 1 for the orphan item we're going to add
4966 * 1 for the orphan item deletion.
4967 */
4968 trans = btrfs_start_transaction(root, 2);
4969 if (IS_ERR(trans))
4970 return PTR_ERR(trans);
4971
4972 /*
4973 * We need to do this in case we fail at _any_ point during the
4974 * actual truncate. Once we do the truncate_setsize we could
4975 * invalidate pages which forces any outstanding ordered io to
4976 * be instantly completed which will give us extents that need
4977 * to be truncated. If we fail to get an orphan inode down we
4978 * could have left over extents that were never meant to live,
01327610 4979 * so we need to guarantee from this point on that everything
f3fe820c
JB
4980 * will be consistent.
4981 */
73f2e545 4982 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3a45bb20 4983 btrfs_end_transaction(trans);
f3fe820c
JB
4984 if (ret)
4985 return ret;
4986
a41ad394
JB
4987 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4988 truncate_setsize(inode, newsize);
2e60a51e
MX
4989
4990 /* Disable nonlocked read DIO to avoid the end less truncate */
abcefb1e 4991 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
2e60a51e 4992 inode_dio_wait(inode);
0b581701 4993 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
2e60a51e 4994
a41ad394 4995 ret = btrfs_truncate(inode);
7f4f6e0a
JB
4996 if (ret && inode->i_nlink) {
4997 int err;
4998
19fd2df5
LB
4999 /* To get a stable disk_i_size */
5000 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5001 if (err) {
3d6ae7bb 5002 btrfs_orphan_del(NULL, BTRFS_I(inode));
19fd2df5
LB
5003 return err;
5004 }
5005
7f4f6e0a
JB
5006 /*
5007 * failed to truncate, disk_i_size is only adjusted down
5008 * as we remove extents, so it should represent the true
5009 * size of the inode, so reset the in memory size and
5010 * delete our orphan entry.
5011 */
5012 trans = btrfs_join_transaction(root);
5013 if (IS_ERR(trans)) {
3d6ae7bb 5014 btrfs_orphan_del(NULL, BTRFS_I(inode));
7f4f6e0a
JB
5015 return ret;
5016 }
5017 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
3d6ae7bb 5018 err = btrfs_orphan_del(trans, BTRFS_I(inode));
7f4f6e0a 5019 if (err)
66642832 5020 btrfs_abort_transaction(trans, err);
3a45bb20 5021 btrfs_end_transaction(trans);
7f4f6e0a 5022 }
8082510e
YZ
5023 }
5024
a41ad394 5025 return ret;
8082510e
YZ
5026}
5027
9036c102
YZ
5028static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5029{
2b0143b5 5030 struct inode *inode = d_inode(dentry);
b83cc969 5031 struct btrfs_root *root = BTRFS_I(inode)->root;
9036c102 5032 int err;
39279cc3 5033
b83cc969
LZ
5034 if (btrfs_root_readonly(root))
5035 return -EROFS;
5036
31051c85 5037 err = setattr_prepare(dentry, attr);
9036c102
YZ
5038 if (err)
5039 return err;
2bf5a725 5040
5a3f23d5 5041 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3972f260 5042 err = btrfs_setsize(inode, attr);
8082510e
YZ
5043 if (err)
5044 return err;
39279cc3 5045 }
9036c102 5046
1025774c
CH
5047 if (attr->ia_valid) {
5048 setattr_copy(inode, attr);
0c4d2d95 5049 inode_inc_iversion(inode);
22c44fe6 5050 err = btrfs_dirty_inode(inode);
1025774c 5051
22c44fe6 5052 if (!err && attr->ia_valid & ATTR_MODE)
996a710d 5053 err = posix_acl_chmod(inode, inode->i_mode);
1025774c 5054 }
33268eaf 5055
39279cc3
CM
5056 return err;
5057}
61295eb8 5058
131e404a
FDBM
5059/*
5060 * While truncating the inode pages during eviction, we get the VFS calling
5061 * btrfs_invalidatepage() against each page of the inode. This is slow because
5062 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5063 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5064 * extent_state structures over and over, wasting lots of time.
5065 *
5066 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5067 * those expensive operations on a per page basis and do only the ordered io
5068 * finishing, while we release here the extent_map and extent_state structures,
5069 * without the excessive merging and splitting.
5070 */
5071static void evict_inode_truncate_pages(struct inode *inode)
5072{
5073 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5074 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5075 struct rb_node *node;
5076
5077 ASSERT(inode->i_state & I_FREEING);
91b0abe3 5078 truncate_inode_pages_final(&inode->i_data);
131e404a
FDBM
5079
5080 write_lock(&map_tree->lock);
5081 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5082 struct extent_map *em;
5083
5084 node = rb_first(&map_tree->map);
5085 em = rb_entry(node, struct extent_map, rb_node);
180589ef
WS
5086 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5087 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
131e404a
FDBM
5088 remove_extent_mapping(map_tree, em);
5089 free_extent_map(em);
7064dd5c
FM
5090 if (need_resched()) {
5091 write_unlock(&map_tree->lock);
5092 cond_resched();
5093 write_lock(&map_tree->lock);
5094 }
131e404a
FDBM
5095 }
5096 write_unlock(&map_tree->lock);
5097
6ca07097
FM
5098 /*
5099 * Keep looping until we have no more ranges in the io tree.
5100 * We can have ongoing bios started by readpages (called from readahead)
9c6429d9
FM
5101 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5102 * still in progress (unlocked the pages in the bio but did not yet
5103 * unlocked the ranges in the io tree). Therefore this means some
6ca07097
FM
5104 * ranges can still be locked and eviction started because before
5105 * submitting those bios, which are executed by a separate task (work
5106 * queue kthread), inode references (inode->i_count) were not taken
5107 * (which would be dropped in the end io callback of each bio).
5108 * Therefore here we effectively end up waiting for those bios and
5109 * anyone else holding locked ranges without having bumped the inode's
5110 * reference count - if we don't do it, when they access the inode's
5111 * io_tree to unlock a range it may be too late, leading to an
5112 * use-after-free issue.
5113 */
131e404a
FDBM
5114 spin_lock(&io_tree->lock);
5115 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5116 struct extent_state *state;
5117 struct extent_state *cached_state = NULL;
6ca07097
FM
5118 u64 start;
5119 u64 end;
131e404a
FDBM
5120
5121 node = rb_first(&io_tree->state);
5122 state = rb_entry(node, struct extent_state, rb_node);
6ca07097
FM
5123 start = state->start;
5124 end = state->end;
131e404a
FDBM
5125 spin_unlock(&io_tree->lock);
5126
ff13db41 5127 lock_extent_bits(io_tree, start, end, &cached_state);
b9d0b389
QW
5128
5129 /*
5130 * If still has DELALLOC flag, the extent didn't reach disk,
5131 * and its reserved space won't be freed by delayed_ref.
5132 * So we need to free its reserved space here.
5133 * (Refer to comment in btrfs_invalidatepage, case 2)
5134 *
5135 * Note, end is the bytenr of last byte, so we need + 1 here.
5136 */
5137 if (state->state & EXTENT_DELALLOC)
5138 btrfs_qgroup_free_data(inode, start, end - start + 1);
5139
6ca07097 5140 clear_extent_bit(io_tree, start, end,
131e404a
FDBM
5141 EXTENT_LOCKED | EXTENT_DIRTY |
5142 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5143 EXTENT_DEFRAG, 1, 1,
5144 &cached_state, GFP_NOFS);
131e404a 5145
7064dd5c 5146 cond_resched();
131e404a
FDBM
5147 spin_lock(&io_tree->lock);
5148 }
5149 spin_unlock(&io_tree->lock);
5150}
5151
bd555975 5152void btrfs_evict_inode(struct inode *inode)
39279cc3 5153{
0b246afa 5154 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
5155 struct btrfs_trans_handle *trans;
5156 struct btrfs_root *root = BTRFS_I(inode)->root;
726c35fa 5157 struct btrfs_block_rsv *rsv, *global_rsv;
3bce876f 5158 int steal_from_global = 0;
3d48d981 5159 u64 min_size;
39279cc3
CM
5160 int ret;
5161
1abe9b8a 5162 trace_btrfs_inode_evict(inode);
5163
3d48d981
NB
5164 if (!root) {
5165 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5166 return;
5167 }
5168
0b246afa 5169 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
3d48d981 5170
131e404a
FDBM
5171 evict_inode_truncate_pages(inode);
5172
69e9c6c6
SB
5173 if (inode->i_nlink &&
5174 ((btrfs_root_refs(&root->root_item) != 0 &&
5175 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
70ddc553 5176 btrfs_is_free_space_inode(BTRFS_I(inode))))
bd555975
AV
5177 goto no_delete;
5178
39279cc3 5179 if (is_bad_inode(inode)) {
3d6ae7bb 5180 btrfs_orphan_del(NULL, BTRFS_I(inode));
39279cc3
CM
5181 goto no_delete;
5182 }
bd555975 5183 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
a30e577c
JM
5184 if (!special_file(inode->i_mode))
5185 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5f39d397 5186
7ab7956e 5187 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
f612496b 5188
0b246afa 5189 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
6bf02314 5190 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8a35d95f 5191 &BTRFS_I(inode)->runtime_flags));
c71bf099
YZ
5192 goto no_delete;
5193 }
5194
76dda93c 5195 if (inode->i_nlink > 0) {
69e9c6c6
SB
5196 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5197 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
76dda93c
YZ
5198 goto no_delete;
5199 }
5200
aa79021f 5201 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
0e8c36a9 5202 if (ret) {
3d6ae7bb 5203 btrfs_orphan_del(NULL, BTRFS_I(inode));
0e8c36a9
MX
5204 goto no_delete;
5205 }
5206
2ff7e61e 5207 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
4289a667 5208 if (!rsv) {
3d6ae7bb 5209 btrfs_orphan_del(NULL, BTRFS_I(inode));
4289a667
JB
5210 goto no_delete;
5211 }
4a338542 5212 rsv->size = min_size;
ca7e70f5 5213 rsv->failfast = 1;
0b246afa 5214 global_rsv = &fs_info->global_block_rsv;
4289a667 5215
6ef06d27 5216 btrfs_i_size_write(BTRFS_I(inode), 0);
5f39d397 5217
4289a667 5218 /*
8407aa46
MX
5219 * This is a bit simpler than btrfs_truncate since we've already
5220 * reserved our space for our orphan item in the unlink, so we just
5221 * need to reserve some slack space in case we add bytes and update
5222 * inode item when doing the truncate.
4289a667 5223 */
8082510e 5224 while (1) {
08e007d2
MX
5225 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5226 BTRFS_RESERVE_FLUSH_LIMIT);
726c35fa
JB
5227
5228 /*
5229 * Try and steal from the global reserve since we will
5230 * likely not use this space anyway, we want to try as
5231 * hard as possible to get this to work.
5232 */
5233 if (ret)
3bce876f
JB
5234 steal_from_global++;
5235 else
5236 steal_from_global = 0;
5237 ret = 0;
d68fc57b 5238
3bce876f
JB
5239 /*
5240 * steal_from_global == 0: we reserved stuff, hooray!
5241 * steal_from_global == 1: we didn't reserve stuff, boo!
5242 * steal_from_global == 2: we've committed, still not a lot of
5243 * room but maybe we'll have room in the global reserve this
5244 * time.
5245 * steal_from_global == 3: abandon all hope!
5246 */
5247 if (steal_from_global > 2) {
0b246afa
JM
5248 btrfs_warn(fs_info,
5249 "Could not get space for a delete, will truncate on mount %d",
5250 ret);
3d6ae7bb 5251 btrfs_orphan_del(NULL, BTRFS_I(inode));
2ff7e61e 5252 btrfs_free_block_rsv(fs_info, rsv);
4289a667 5253 goto no_delete;
d68fc57b 5254 }
7b128766 5255
0e8c36a9 5256 trans = btrfs_join_transaction(root);
4289a667 5257 if (IS_ERR(trans)) {
3d6ae7bb 5258 btrfs_orphan_del(NULL, BTRFS_I(inode));
2ff7e61e 5259 btrfs_free_block_rsv(fs_info, rsv);
4289a667 5260 goto no_delete;
d68fc57b 5261 }
7b128766 5262
3bce876f 5263 /*
01327610 5264 * We can't just steal from the global reserve, we need to make
3bce876f
JB
5265 * sure there is room to do it, if not we need to commit and try
5266 * again.
5267 */
5268 if (steal_from_global) {
2ff7e61e 5269 if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
3bce876f 5270 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
25d609f8 5271 min_size, 0);
3bce876f
JB
5272 else
5273 ret = -ENOSPC;
5274 }
5275
5276 /*
5277 * Couldn't steal from the global reserve, we have too much
5278 * pending stuff built up, commit the transaction and try it
5279 * again.
5280 */
5281 if (ret) {
3a45bb20 5282 ret = btrfs_commit_transaction(trans);
3bce876f 5283 if (ret) {
3d6ae7bb 5284 btrfs_orphan_del(NULL, BTRFS_I(inode));
2ff7e61e 5285 btrfs_free_block_rsv(fs_info, rsv);
3bce876f
JB
5286 goto no_delete;
5287 }
5288 continue;
5289 } else {
5290 steal_from_global = 0;
5291 }
5292
4289a667
JB
5293 trans->block_rsv = rsv;
5294
d68fc57b 5295 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
28ed1345 5296 if (ret != -ENOSPC && ret != -EAGAIN)
8082510e 5297 break;
85e21bac 5298
0b246afa 5299 trans->block_rsv = &fs_info->trans_block_rsv;
3a45bb20 5300 btrfs_end_transaction(trans);
8082510e 5301 trans = NULL;
2ff7e61e 5302 btrfs_btree_balance_dirty(fs_info);
8082510e 5303 }
5f39d397 5304
2ff7e61e 5305 btrfs_free_block_rsv(fs_info, rsv);
4289a667 5306
4ef31a45
JB
5307 /*
5308 * Errors here aren't a big deal, it just means we leave orphan items
5309 * in the tree. They will be cleaned up on the next mount.
5310 */
8082510e 5311 if (ret == 0) {
4289a667 5312 trans->block_rsv = root->orphan_block_rsv;
3d6ae7bb 5313 btrfs_orphan_del(trans, BTRFS_I(inode));
4ef31a45 5314 } else {
3d6ae7bb 5315 btrfs_orphan_del(NULL, BTRFS_I(inode));
8082510e 5316 }
54aa1f4d 5317
0b246afa
JM
5318 trans->block_rsv = &fs_info->trans_block_rsv;
5319 if (!(root == fs_info->tree_root ||
581bb050 5320 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4a0cc7ca 5321 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
581bb050 5322
3a45bb20 5323 btrfs_end_transaction(trans);
2ff7e61e 5324 btrfs_btree_balance_dirty(fs_info);
39279cc3 5325no_delete:
f48d1cf5 5326 btrfs_remove_delayed_node(BTRFS_I(inode));
dbd5768f 5327 clear_inode(inode);
39279cc3
CM
5328}
5329
5330/*
5331 * this returns the key found in the dir entry in the location pointer.
5332 * If no dir entries were found, location->objectid is 0.
5333 */
5334static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5335 struct btrfs_key *location)
5336{
5337 const char *name = dentry->d_name.name;
5338 int namelen = dentry->d_name.len;
5339 struct btrfs_dir_item *di;
5340 struct btrfs_path *path;
5341 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 5342 int ret = 0;
39279cc3
CM
5343
5344 path = btrfs_alloc_path();
d8926bb3
MF
5345 if (!path)
5346 return -ENOMEM;
3954401f 5347
f85b7379
DS
5348 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5349 name, namelen, 0);
0d9f7f3e
Y
5350 if (IS_ERR(di))
5351 ret = PTR_ERR(di);
d397712b 5352
c704005d 5353 if (IS_ERR_OR_NULL(di))
3954401f 5354 goto out_err;
d397712b 5355
5f39d397 5356 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
39279cc3 5357out:
39279cc3
CM
5358 btrfs_free_path(path);
5359 return ret;
3954401f
CM
5360out_err:
5361 location->objectid = 0;
5362 goto out;
39279cc3
CM
5363}
5364
5365/*
5366 * when we hit a tree root in a directory, the btrfs part of the inode
5367 * needs to be changed to reflect the root directory of the tree root. This
5368 * is kind of like crossing a mount point.
5369 */
2ff7e61e 5370static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
4df27c4d
YZ
5371 struct inode *dir,
5372 struct dentry *dentry,
5373 struct btrfs_key *location,
5374 struct btrfs_root **sub_root)
39279cc3 5375{
4df27c4d
YZ
5376 struct btrfs_path *path;
5377 struct btrfs_root *new_root;
5378 struct btrfs_root_ref *ref;
5379 struct extent_buffer *leaf;
1d4c08e0 5380 struct btrfs_key key;
4df27c4d
YZ
5381 int ret;
5382 int err = 0;
39279cc3 5383
4df27c4d
YZ
5384 path = btrfs_alloc_path();
5385 if (!path) {
5386 err = -ENOMEM;
5387 goto out;
5388 }
39279cc3 5389
4df27c4d 5390 err = -ENOENT;
1d4c08e0
DS
5391 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5392 key.type = BTRFS_ROOT_REF_KEY;
5393 key.offset = location->objectid;
5394
0b246afa 5395 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4df27c4d
YZ
5396 if (ret) {
5397 if (ret < 0)
5398 err = ret;
5399 goto out;
5400 }
39279cc3 5401
4df27c4d
YZ
5402 leaf = path->nodes[0];
5403 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4a0cc7ca 5404 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
4df27c4d
YZ
5405 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5406 goto out;
39279cc3 5407
4df27c4d
YZ
5408 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5409 (unsigned long)(ref + 1),
5410 dentry->d_name.len);
5411 if (ret)
5412 goto out;
5413
b3b4aa74 5414 btrfs_release_path(path);
4df27c4d 5415
0b246afa 5416 new_root = btrfs_read_fs_root_no_name(fs_info, location);
4df27c4d
YZ
5417 if (IS_ERR(new_root)) {
5418 err = PTR_ERR(new_root);
5419 goto out;
5420 }
5421
4df27c4d
YZ
5422 *sub_root = new_root;
5423 location->objectid = btrfs_root_dirid(&new_root->root_item);
5424 location->type = BTRFS_INODE_ITEM_KEY;
5425 location->offset = 0;
5426 err = 0;
5427out:
5428 btrfs_free_path(path);
5429 return err;
39279cc3
CM
5430}
5431
5d4f98a2
YZ
5432static void inode_tree_add(struct inode *inode)
5433{
5434 struct btrfs_root *root = BTRFS_I(inode)->root;
5435 struct btrfs_inode *entry;
03e860bd
FNP
5436 struct rb_node **p;
5437 struct rb_node *parent;
cef21937 5438 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4a0cc7ca 5439 u64 ino = btrfs_ino(BTRFS_I(inode));
5d4f98a2 5440
1d3382cb 5441 if (inode_unhashed(inode))
76dda93c 5442 return;
e1409cef 5443 parent = NULL;
5d4f98a2 5444 spin_lock(&root->inode_lock);
e1409cef 5445 p = &root->inode_tree.rb_node;
5d4f98a2
YZ
5446 while (*p) {
5447 parent = *p;
5448 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5449
4a0cc7ca 5450 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
03e860bd 5451 p = &parent->rb_left;
4a0cc7ca 5452 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
03e860bd 5453 p = &parent->rb_right;
5d4f98a2
YZ
5454 else {
5455 WARN_ON(!(entry->vfs_inode.i_state &
a4ffdde6 5456 (I_WILL_FREE | I_FREEING)));
cef21937 5457 rb_replace_node(parent, new, &root->inode_tree);
03e860bd
FNP
5458 RB_CLEAR_NODE(parent);
5459 spin_unlock(&root->inode_lock);
cef21937 5460 return;
5d4f98a2
YZ
5461 }
5462 }
cef21937
FDBM
5463 rb_link_node(new, parent, p);
5464 rb_insert_color(new, &root->inode_tree);
5d4f98a2
YZ
5465 spin_unlock(&root->inode_lock);
5466}
5467
5468static void inode_tree_del(struct inode *inode)
5469{
0b246afa 5470 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5d4f98a2 5471 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 5472 int empty = 0;
5d4f98a2 5473
03e860bd 5474 spin_lock(&root->inode_lock);
5d4f98a2 5475 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 5476 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 5477 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 5478 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 5479 }
03e860bd 5480 spin_unlock(&root->inode_lock);
76dda93c 5481
69e9c6c6 5482 if (empty && btrfs_root_refs(&root->root_item) == 0) {
0b246afa 5483 synchronize_srcu(&fs_info->subvol_srcu);
76dda93c
YZ
5484 spin_lock(&root->inode_lock);
5485 empty = RB_EMPTY_ROOT(&root->inode_tree);
5486 spin_unlock(&root->inode_lock);
5487 if (empty)
5488 btrfs_add_dead_root(root);
5489 }
5490}
5491
143bede5 5492void btrfs_invalidate_inodes(struct btrfs_root *root)
76dda93c 5493{
0b246afa 5494 struct btrfs_fs_info *fs_info = root->fs_info;
76dda93c
YZ
5495 struct rb_node *node;
5496 struct rb_node *prev;
5497 struct btrfs_inode *entry;
5498 struct inode *inode;
5499 u64 objectid = 0;
5500
0b246afa 5501 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
7813b3db 5502 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
76dda93c
YZ
5503
5504 spin_lock(&root->inode_lock);
5505again:
5506 node = root->inode_tree.rb_node;
5507 prev = NULL;
5508 while (node) {
5509 prev = node;
5510 entry = rb_entry(node, struct btrfs_inode, rb_node);
5511
4a0cc7ca 5512 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
76dda93c 5513 node = node->rb_left;
4a0cc7ca 5514 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
76dda93c
YZ
5515 node = node->rb_right;
5516 else
5517 break;
5518 }
5519 if (!node) {
5520 while (prev) {
5521 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4a0cc7ca 5522 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
76dda93c
YZ
5523 node = prev;
5524 break;
5525 }
5526 prev = rb_next(prev);
5527 }
5528 }
5529 while (node) {
5530 entry = rb_entry(node, struct btrfs_inode, rb_node);
4a0cc7ca 5531 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
76dda93c
YZ
5532 inode = igrab(&entry->vfs_inode);
5533 if (inode) {
5534 spin_unlock(&root->inode_lock);
5535 if (atomic_read(&inode->i_count) > 1)
5536 d_prune_aliases(inode);
5537 /*
45321ac5 5538 * btrfs_drop_inode will have it removed from
76dda93c
YZ
5539 * the inode cache when its usage count
5540 * hits zero.
5541 */
5542 iput(inode);
5543 cond_resched();
5544 spin_lock(&root->inode_lock);
5545 goto again;
5546 }
5547
5548 if (cond_resched_lock(&root->inode_lock))
5549 goto again;
5550
5551 node = rb_next(node);
5552 }
5553 spin_unlock(&root->inode_lock);
5d4f98a2
YZ
5554}
5555
e02119d5
CM
5556static int btrfs_init_locked_inode(struct inode *inode, void *p)
5557{
5558 struct btrfs_iget_args *args = p;
90d3e592
CM
5559 inode->i_ino = args->location->objectid;
5560 memcpy(&BTRFS_I(inode)->location, args->location,
5561 sizeof(*args->location));
e02119d5 5562 BTRFS_I(inode)->root = args->root;
39279cc3
CM
5563 return 0;
5564}
5565
5566static int btrfs_find_actor(struct inode *inode, void *opaque)
5567{
5568 struct btrfs_iget_args *args = opaque;
90d3e592 5569 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
d397712b 5570 args->root == BTRFS_I(inode)->root;
39279cc3
CM
5571}
5572
5d4f98a2 5573static struct inode *btrfs_iget_locked(struct super_block *s,
90d3e592 5574 struct btrfs_key *location,
5d4f98a2 5575 struct btrfs_root *root)
39279cc3
CM
5576{
5577 struct inode *inode;
5578 struct btrfs_iget_args args;
90d3e592 5579 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
778ba82b 5580
90d3e592 5581 args.location = location;
39279cc3
CM
5582 args.root = root;
5583
778ba82b 5584 inode = iget5_locked(s, hashval, btrfs_find_actor,
39279cc3
CM
5585 btrfs_init_locked_inode,
5586 (void *)&args);
5587 return inode;
5588}
5589
1a54ef8c
BR
5590/* Get an inode object given its location and corresponding root.
5591 * Returns in *is_new if the inode was read from disk
5592 */
5593struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
73f73415 5594 struct btrfs_root *root, int *new)
1a54ef8c
BR
5595{
5596 struct inode *inode;
5597
90d3e592 5598 inode = btrfs_iget_locked(s, location, root);
1a54ef8c 5599 if (!inode)
5d4f98a2 5600 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
5601
5602 if (inode->i_state & I_NEW) {
67710892
FM
5603 int ret;
5604
5605 ret = btrfs_read_locked_inode(inode);
1748f843
MF
5606 if (!is_bad_inode(inode)) {
5607 inode_tree_add(inode);
5608 unlock_new_inode(inode);
5609 if (new)
5610 *new = 1;
5611 } else {
e0b6d65b
ST
5612 unlock_new_inode(inode);
5613 iput(inode);
67710892
FM
5614 ASSERT(ret < 0);
5615 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
1748f843
MF
5616 }
5617 }
5618
1a54ef8c
BR
5619 return inode;
5620}
5621
4df27c4d
YZ
5622static struct inode *new_simple_dir(struct super_block *s,
5623 struct btrfs_key *key,
5624 struct btrfs_root *root)
5625{
5626 struct inode *inode = new_inode(s);
5627
5628 if (!inode)
5629 return ERR_PTR(-ENOMEM);
5630
4df27c4d
YZ
5631 BTRFS_I(inode)->root = root;
5632 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
72ac3c0d 5633 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4df27c4d
YZ
5634
5635 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
848cce0d 5636 inode->i_op = &btrfs_dir_ro_inode_operations;
1fdf4194 5637 inode->i_opflags &= ~IOP_XATTR;
4df27c4d
YZ
5638 inode->i_fop = &simple_dir_operations;
5639 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
c2050a45 5640 inode->i_mtime = current_time(inode);
9cc97d64 5641 inode->i_atime = inode->i_mtime;
5642 inode->i_ctime = inode->i_mtime;
5643 BTRFS_I(inode)->i_otime = inode->i_mtime;
4df27c4d
YZ
5644
5645 return inode;
5646}
5647
3de4586c 5648struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 5649{
0b246afa 5650 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
d397712b 5651 struct inode *inode;
4df27c4d 5652 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
5653 struct btrfs_root *sub_root = root;
5654 struct btrfs_key location;
76dda93c 5655 int index;
b4aff1f8 5656 int ret = 0;
39279cc3
CM
5657
5658 if (dentry->d_name.len > BTRFS_NAME_LEN)
5659 return ERR_PTR(-ENAMETOOLONG);
5f39d397 5660
39e3c955 5661 ret = btrfs_inode_by_name(dir, dentry, &location);
39279cc3
CM
5662 if (ret < 0)
5663 return ERR_PTR(ret);
5f39d397 5664
4df27c4d 5665 if (location.objectid == 0)
5662344b 5666 return ERR_PTR(-ENOENT);
4df27c4d
YZ
5667
5668 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 5669 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4df27c4d
YZ
5670 return inode;
5671 }
5672
5673 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5674
0b246afa 5675 index = srcu_read_lock(&fs_info->subvol_srcu);
2ff7e61e 5676 ret = fixup_tree_root_location(fs_info, dir, dentry,
4df27c4d
YZ
5677 &location, &sub_root);
5678 if (ret < 0) {
5679 if (ret != -ENOENT)
5680 inode = ERR_PTR(ret);
5681 else
5682 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5683 } else {
73f73415 5684 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 5685 }
0b246afa 5686 srcu_read_unlock(&fs_info->subvol_srcu, index);
76dda93c 5687
34d19bad 5688 if (!IS_ERR(inode) && root != sub_root) {
0b246afa 5689 down_read(&fs_info->cleanup_work_sem);
c71bf099 5690 if (!(inode->i_sb->s_flags & MS_RDONLY))
66b4ffd1 5691 ret = btrfs_orphan_cleanup(sub_root);
0b246afa 5692 up_read(&fs_info->cleanup_work_sem);
01cd3367
JB
5693 if (ret) {
5694 iput(inode);
66b4ffd1 5695 inode = ERR_PTR(ret);
01cd3367 5696 }
c71bf099
YZ
5697 }
5698
3de4586c
CM
5699 return inode;
5700}
5701
fe15ce44 5702static int btrfs_dentry_delete(const struct dentry *dentry)
76dda93c
YZ
5703{
5704 struct btrfs_root *root;
2b0143b5 5705 struct inode *inode = d_inode(dentry);
76dda93c 5706
848cce0d 5707 if (!inode && !IS_ROOT(dentry))
2b0143b5 5708 inode = d_inode(dentry->d_parent);
76dda93c 5709
848cce0d
LZ
5710 if (inode) {
5711 root = BTRFS_I(inode)->root;
efefb143
YZ
5712 if (btrfs_root_refs(&root->root_item) == 0)
5713 return 1;
848cce0d 5714
4a0cc7ca 5715 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
848cce0d 5716 return 1;
efefb143 5717 }
76dda93c
YZ
5718 return 0;
5719}
5720
b4aff1f8
JB
5721static void btrfs_dentry_release(struct dentry *dentry)
5722{
944a4515 5723 kfree(dentry->d_fsdata);
b4aff1f8
JB
5724}
5725
3de4586c 5726static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
00cd8dd3 5727 unsigned int flags)
3de4586c 5728{
5662344b 5729 struct inode *inode;
a66e7cc6 5730
5662344b
TI
5731 inode = btrfs_lookup_dentry(dir, dentry);
5732 if (IS_ERR(inode)) {
5733 if (PTR_ERR(inode) == -ENOENT)
5734 inode = NULL;
5735 else
5736 return ERR_CAST(inode);
5737 }
5738
41d28bca 5739 return d_splice_alias(inode, dentry);
39279cc3
CM
5740}
5741
16cdcec7 5742unsigned char btrfs_filetype_table[] = {
39279cc3
CM
5743 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5744};
5745
9cdda8d3 5746static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
39279cc3 5747{
9cdda8d3 5748 struct inode *inode = file_inode(file);
2ff7e61e 5749 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
5750 struct btrfs_root *root = BTRFS_I(inode)->root;
5751 struct btrfs_item *item;
5752 struct btrfs_dir_item *di;
5753 struct btrfs_key key;
5f39d397 5754 struct btrfs_key found_key;
39279cc3 5755 struct btrfs_path *path;
16cdcec7
MX
5756 struct list_head ins_list;
5757 struct list_head del_list;
39279cc3 5758 int ret;
5f39d397 5759 struct extent_buffer *leaf;
39279cc3 5760 int slot;
39279cc3
CM
5761 unsigned char d_type;
5762 int over = 0;
5f39d397
CM
5763 char tmp_name[32];
5764 char *name_ptr;
5765 int name_len;
02dbfc99 5766 bool put = false;
c2951f32 5767 struct btrfs_key location;
5f39d397 5768
9cdda8d3
AV
5769 if (!dir_emit_dots(file, ctx))
5770 return 0;
5771
49593bfa 5772 path = btrfs_alloc_path();
16cdcec7
MX
5773 if (!path)
5774 return -ENOMEM;
ff5714cc 5775
e4058b54 5776 path->reada = READA_FORWARD;
49593bfa 5777
c2951f32
JM
5778 INIT_LIST_HEAD(&ins_list);
5779 INIT_LIST_HEAD(&del_list);
5780 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
16cdcec7 5781
c2951f32 5782 key.type = BTRFS_DIR_INDEX_KEY;
9cdda8d3 5783 key.offset = ctx->pos;
4a0cc7ca 5784 key.objectid = btrfs_ino(BTRFS_I(inode));
5f39d397 5785
39279cc3
CM
5786 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5787 if (ret < 0)
5788 goto err;
49593bfa
DW
5789
5790 while (1) {
5f39d397 5791 leaf = path->nodes[0];
39279cc3 5792 slot = path->slots[0];
b9e03af0
LZ
5793 if (slot >= btrfs_header_nritems(leaf)) {
5794 ret = btrfs_next_leaf(root, path);
5795 if (ret < 0)
5796 goto err;
5797 else if (ret > 0)
5798 break;
5799 continue;
39279cc3 5800 }
3de4586c 5801
dd3cc16b 5802 item = btrfs_item_nr(slot);
5f39d397
CM
5803 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5804
5805 if (found_key.objectid != key.objectid)
39279cc3 5806 break;
c2951f32 5807 if (found_key.type != BTRFS_DIR_INDEX_KEY)
39279cc3 5808 break;
9cdda8d3 5809 if (found_key.offset < ctx->pos)
b9e03af0 5810 goto next;
c2951f32 5811 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
16cdcec7 5812 goto next;
5f39d397 5813
9cdda8d3 5814 ctx->pos = found_key.offset;
49593bfa 5815
39279cc3 5816 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
2ff7e61e 5817 if (verify_dir_item(fs_info, leaf, di))
c2951f32 5818 goto next;
22a94d44 5819
c2951f32
JM
5820 name_len = btrfs_dir_name_len(leaf, di);
5821 if (name_len <= sizeof(tmp_name)) {
5822 name_ptr = tmp_name;
5823 } else {
5824 name_ptr = kmalloc(name_len, GFP_KERNEL);
5825 if (!name_ptr) {
5826 ret = -ENOMEM;
5827 goto err;
5f39d397 5828 }
c2951f32
JM
5829 }
5830 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5831 name_len);
3de4586c 5832
c2951f32
JM
5833 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5834 btrfs_dir_item_key_to_cpu(leaf, di, &location);
fede766f 5835
c2951f32
JM
5836 over = !dir_emit(ctx, name_ptr, name_len, location.objectid,
5837 d_type);
5f39d397 5838
c2951f32
JM
5839 if (name_ptr != tmp_name)
5840 kfree(name_ptr);
5f39d397 5841
c2951f32
JM
5842 if (over)
5843 goto nopos;
d2fbb2b5 5844 ctx->pos++;
b9e03af0
LZ
5845next:
5846 path->slots[0]++;
39279cc3 5847 }
49593bfa 5848
d2fbb2b5 5849 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
c2951f32 5850 if (ret)
bc4ef759
DS
5851 goto nopos;
5852
db62efbb
ZB
5853 /*
5854 * Stop new entries from being returned after we return the last
5855 * entry.
5856 *
5857 * New directory entries are assigned a strictly increasing
5858 * offset. This means that new entries created during readdir
5859 * are *guaranteed* to be seen in the future by that readdir.
5860 * This has broken buggy programs which operate on names as
5861 * they're returned by readdir. Until we re-use freed offsets
5862 * we have this hack to stop new entries from being returned
5863 * under the assumption that they'll never reach this huge
5864 * offset.
5865 *
5866 * This is being careful not to overflow 32bit loff_t unless the
5867 * last entry requires it because doing so has broken 32bit apps
5868 * in the past.
5869 */
c2951f32
JM
5870 if (ctx->pos >= INT_MAX)
5871 ctx->pos = LLONG_MAX;
5872 else
5873 ctx->pos = INT_MAX;
39279cc3
CM
5874nopos:
5875 ret = 0;
5876err:
02dbfc99
OS
5877 if (put)
5878 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
39279cc3 5879 btrfs_free_path(path);
39279cc3
CM
5880 return ret;
5881}
5882
a9185b41 5883int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
39279cc3
CM
5884{
5885 struct btrfs_root *root = BTRFS_I(inode)->root;
5886 struct btrfs_trans_handle *trans;
5887 int ret = 0;
0af3d00b 5888 bool nolock = false;
39279cc3 5889
72ac3c0d 5890 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4ca8b41e
CM
5891 return 0;
5892
70ddc553
NB
5893 if (btrfs_fs_closing(root->fs_info) &&
5894 btrfs_is_free_space_inode(BTRFS_I(inode)))
82d5902d 5895 nolock = true;
0af3d00b 5896
a9185b41 5897 if (wbc->sync_mode == WB_SYNC_ALL) {
0af3d00b 5898 if (nolock)
7a7eaa40 5899 trans = btrfs_join_transaction_nolock(root);
0af3d00b 5900 else
7a7eaa40 5901 trans = btrfs_join_transaction(root);
3612b495
TI
5902 if (IS_ERR(trans))
5903 return PTR_ERR(trans);
3a45bb20 5904 ret = btrfs_commit_transaction(trans);
39279cc3
CM
5905 }
5906 return ret;
5907}
5908
5909/*
54aa1f4d 5910 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
5911 * inode changes. But, it is most likely to find the inode in cache.
5912 * FIXME, needs more benchmarking...there are no reasons other than performance
5913 * to keep or drop this code.
5914 */
48a3b636 5915static int btrfs_dirty_inode(struct inode *inode)
39279cc3 5916{
2ff7e61e 5917 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3
CM
5918 struct btrfs_root *root = BTRFS_I(inode)->root;
5919 struct btrfs_trans_handle *trans;
8929ecfa
YZ
5920 int ret;
5921
72ac3c0d 5922 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
22c44fe6 5923 return 0;
39279cc3 5924
7a7eaa40 5925 trans = btrfs_join_transaction(root);
22c44fe6
JB
5926 if (IS_ERR(trans))
5927 return PTR_ERR(trans);
8929ecfa
YZ
5928
5929 ret = btrfs_update_inode(trans, root, inode);
94b60442
CM
5930 if (ret && ret == -ENOSPC) {
5931 /* whoops, lets try again with the full transaction */
3a45bb20 5932 btrfs_end_transaction(trans);
94b60442 5933 trans = btrfs_start_transaction(root, 1);
22c44fe6
JB
5934 if (IS_ERR(trans))
5935 return PTR_ERR(trans);
8929ecfa 5936
94b60442 5937 ret = btrfs_update_inode(trans, root, inode);
94b60442 5938 }
3a45bb20 5939 btrfs_end_transaction(trans);
16cdcec7 5940 if (BTRFS_I(inode)->delayed_node)
2ff7e61e 5941 btrfs_balance_delayed_items(fs_info);
22c44fe6
JB
5942
5943 return ret;
5944}
5945
5946/*
5947 * This is a copy of file_update_time. We need this so we can return error on
5948 * ENOSPC for updating the inode in the case of file write and mmap writes.
5949 */
e41f941a
JB
5950static int btrfs_update_time(struct inode *inode, struct timespec *now,
5951 int flags)
22c44fe6 5952{
2bc55652
AB
5953 struct btrfs_root *root = BTRFS_I(inode)->root;
5954
5955 if (btrfs_root_readonly(root))
5956 return -EROFS;
5957
e41f941a 5958 if (flags & S_VERSION)
22c44fe6 5959 inode_inc_iversion(inode);
e41f941a
JB
5960 if (flags & S_CTIME)
5961 inode->i_ctime = *now;
5962 if (flags & S_MTIME)
5963 inode->i_mtime = *now;
5964 if (flags & S_ATIME)
5965 inode->i_atime = *now;
5966 return btrfs_dirty_inode(inode);
39279cc3
CM
5967}
5968
d352ac68
CM
5969/*
5970 * find the highest existing sequence number in a directory
5971 * and then set the in-memory index_cnt variable to reflect
5972 * free sequence numbers
5973 */
4c570655 5974static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
aec7477b 5975{
4c570655 5976 struct btrfs_root *root = inode->root;
aec7477b
JB
5977 struct btrfs_key key, found_key;
5978 struct btrfs_path *path;
5979 struct extent_buffer *leaf;
5980 int ret;
5981
4c570655 5982 key.objectid = btrfs_ino(inode);
962a298f 5983 key.type = BTRFS_DIR_INDEX_KEY;
aec7477b
JB
5984 key.offset = (u64)-1;
5985
5986 path = btrfs_alloc_path();
5987 if (!path)
5988 return -ENOMEM;
5989
5990 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5991 if (ret < 0)
5992 goto out;
5993 /* FIXME: we should be able to handle this */
5994 if (ret == 0)
5995 goto out;
5996 ret = 0;
5997
5998 /*
5999 * MAGIC NUMBER EXPLANATION:
6000 * since we search a directory based on f_pos we have to start at 2
6001 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6002 * else has to start at 2
6003 */
6004 if (path->slots[0] == 0) {
4c570655 6005 inode->index_cnt = 2;
aec7477b
JB
6006 goto out;
6007 }
6008
6009 path->slots[0]--;
6010
6011 leaf = path->nodes[0];
6012 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6013
4c570655 6014 if (found_key.objectid != btrfs_ino(inode) ||
962a298f 6015 found_key.type != BTRFS_DIR_INDEX_KEY) {
4c570655 6016 inode->index_cnt = 2;
aec7477b
JB
6017 goto out;
6018 }
6019
4c570655 6020 inode->index_cnt = found_key.offset + 1;
aec7477b
JB
6021out:
6022 btrfs_free_path(path);
6023 return ret;
6024}
6025
d352ac68
CM
6026/*
6027 * helper to find a free sequence number in a given directory. This current
6028 * code is very simple, later versions will do smarter things in the btree
6029 */
877574e2 6030int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
aec7477b
JB
6031{
6032 int ret = 0;
6033
877574e2
NB
6034 if (dir->index_cnt == (u64)-1) {
6035 ret = btrfs_inode_delayed_dir_index_count(dir);
16cdcec7
MX
6036 if (ret) {
6037 ret = btrfs_set_inode_index_count(dir);
6038 if (ret)
6039 return ret;
6040 }
aec7477b
JB
6041 }
6042
877574e2
NB
6043 *index = dir->index_cnt;
6044 dir->index_cnt++;
aec7477b
JB
6045
6046 return ret;
6047}
6048
b0d5d10f
CM
6049static int btrfs_insert_inode_locked(struct inode *inode)
6050{
6051 struct btrfs_iget_args args;
6052 args.location = &BTRFS_I(inode)->location;
6053 args.root = BTRFS_I(inode)->root;
6054
6055 return insert_inode_locked4(inode,
6056 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6057 btrfs_find_actor, &args);
6058}
6059
39279cc3
CM
6060static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6061 struct btrfs_root *root,
aec7477b 6062 struct inode *dir,
9c58309d 6063 const char *name, int name_len,
175a4eb7
AV
6064 u64 ref_objectid, u64 objectid,
6065 umode_t mode, u64 *index)
39279cc3 6066{
0b246afa 6067 struct btrfs_fs_info *fs_info = root->fs_info;
39279cc3 6068 struct inode *inode;
5f39d397 6069 struct btrfs_inode_item *inode_item;
39279cc3 6070 struct btrfs_key *location;
5f39d397 6071 struct btrfs_path *path;
9c58309d
CM
6072 struct btrfs_inode_ref *ref;
6073 struct btrfs_key key[2];
6074 u32 sizes[2];
ef3b9af5 6075 int nitems = name ? 2 : 1;
9c58309d 6076 unsigned long ptr;
39279cc3 6077 int ret;
39279cc3 6078
5f39d397 6079 path = btrfs_alloc_path();
d8926bb3
MF
6080 if (!path)
6081 return ERR_PTR(-ENOMEM);
5f39d397 6082
0b246afa 6083 inode = new_inode(fs_info->sb);
8fb27640
YS
6084 if (!inode) {
6085 btrfs_free_path(path);
39279cc3 6086 return ERR_PTR(-ENOMEM);
8fb27640 6087 }
39279cc3 6088
5762b5c9
FM
6089 /*
6090 * O_TMPFILE, set link count to 0, so that after this point,
6091 * we fill in an inode item with the correct link count.
6092 */
6093 if (!name)
6094 set_nlink(inode, 0);
6095
581bb050
LZ
6096 /*
6097 * we have to initialize this early, so we can reclaim the inode
6098 * number if we fail afterwards in this function.
6099 */
6100 inode->i_ino = objectid;
6101
ef3b9af5 6102 if (dir && name) {
1abe9b8a 6103 trace_btrfs_inode_request(dir);
6104
877574e2 6105 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
09771430 6106 if (ret) {
8fb27640 6107 btrfs_free_path(path);
09771430 6108 iput(inode);
aec7477b 6109 return ERR_PTR(ret);
09771430 6110 }
ef3b9af5
FM
6111 } else if (dir) {
6112 *index = 0;
aec7477b
JB
6113 }
6114 /*
6115 * index_cnt is ignored for everything but a dir,
6116 * btrfs_get_inode_index_count has an explanation for the magic
6117 * number
6118 */
6119 BTRFS_I(inode)->index_cnt = 2;
67de1176 6120 BTRFS_I(inode)->dir_index = *index;
39279cc3 6121 BTRFS_I(inode)->root = root;
e02119d5 6122 BTRFS_I(inode)->generation = trans->transid;
76195853 6123 inode->i_generation = BTRFS_I(inode)->generation;
b888db2b 6124
5dc562c5
JB
6125 /*
6126 * We could have gotten an inode number from somebody who was fsynced
6127 * and then removed in this same transaction, so let's just set full
6128 * sync since it will be a full sync anyway and this will blow away the
6129 * old info in the log.
6130 */
6131 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6132
9c58309d 6133 key[0].objectid = objectid;
962a298f 6134 key[0].type = BTRFS_INODE_ITEM_KEY;
9c58309d
CM
6135 key[0].offset = 0;
6136
9c58309d 6137 sizes[0] = sizeof(struct btrfs_inode_item);
ef3b9af5
FM
6138
6139 if (name) {
6140 /*
6141 * Start new inodes with an inode_ref. This is slightly more
6142 * efficient for small numbers of hard links since they will
6143 * be packed into one item. Extended refs will kick in if we
6144 * add more hard links than can fit in the ref item.
6145 */
6146 key[1].objectid = objectid;
962a298f 6147 key[1].type = BTRFS_INODE_REF_KEY;
ef3b9af5
FM
6148 key[1].offset = ref_objectid;
6149
6150 sizes[1] = name_len + sizeof(*ref);
6151 }
9c58309d 6152
b0d5d10f
CM
6153 location = &BTRFS_I(inode)->location;
6154 location->objectid = objectid;
6155 location->offset = 0;
962a298f 6156 location->type = BTRFS_INODE_ITEM_KEY;
b0d5d10f
CM
6157
6158 ret = btrfs_insert_inode_locked(inode);
6159 if (ret < 0)
6160 goto fail;
6161
b9473439 6162 path->leave_spinning = 1;
ef3b9af5 6163 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
9c58309d 6164 if (ret != 0)
b0d5d10f 6165 goto fail_unlock;
5f39d397 6166
ecc11fab 6167 inode_init_owner(inode, dir, mode);
a76a3cd4 6168 inode_set_bytes(inode, 0);
9cc97d64 6169
c2050a45 6170 inode->i_mtime = current_time(inode);
9cc97d64 6171 inode->i_atime = inode->i_mtime;
6172 inode->i_ctime = inode->i_mtime;
6173 BTRFS_I(inode)->i_otime = inode->i_mtime;
6174
5f39d397
CM
6175 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6176 struct btrfs_inode_item);
b159fa28 6177 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
293f7e07 6178 sizeof(*inode_item));
e02119d5 6179 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d 6180
ef3b9af5
FM
6181 if (name) {
6182 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6183 struct btrfs_inode_ref);
6184 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6185 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6186 ptr = (unsigned long)(ref + 1);
6187 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6188 }
9c58309d 6189
5f39d397
CM
6190 btrfs_mark_buffer_dirty(path->nodes[0]);
6191 btrfs_free_path(path);
6192
6cbff00f
CH
6193 btrfs_inherit_iflags(inode, dir);
6194
569254b0 6195 if (S_ISREG(mode)) {
0b246afa 6196 if (btrfs_test_opt(fs_info, NODATASUM))
94272164 6197 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
0b246afa 6198 if (btrfs_test_opt(fs_info, NODATACOW))
f2bdf9a8
JB
6199 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6200 BTRFS_INODE_NODATASUM;
94272164
CM
6201 }
6202
5d4f98a2 6203 inode_tree_add(inode);
1abe9b8a 6204
6205 trace_btrfs_inode_new(inode);
1973f0fa 6206 btrfs_set_inode_last_trans(trans, inode);
1abe9b8a 6207
8ea05e3a
AB
6208 btrfs_update_root_times(trans, root);
6209
63541927
FDBM
6210 ret = btrfs_inode_inherit_props(trans, inode, dir);
6211 if (ret)
0b246afa 6212 btrfs_err(fs_info,
63541927 6213 "error inheriting props for ino %llu (root %llu): %d",
f85b7379 6214 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
63541927 6215
39279cc3 6216 return inode;
b0d5d10f
CM
6217
6218fail_unlock:
6219 unlock_new_inode(inode);
5f39d397 6220fail:
ef3b9af5 6221 if (dir && name)
aec7477b 6222 BTRFS_I(dir)->index_cnt--;
5f39d397 6223 btrfs_free_path(path);
09771430 6224 iput(inode);
5f39d397 6225 return ERR_PTR(ret);
39279cc3
CM
6226}
6227
6228static inline u8 btrfs_inode_type(struct inode *inode)
6229{
6230 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6231}
6232
d352ac68
CM
6233/*
6234 * utility function to add 'inode' into 'parent_inode' with
6235 * a give name and a given sequence number.
6236 * if 'add_backref' is true, also insert a backref from the
6237 * inode to the parent directory.
6238 */
e02119d5 6239int btrfs_add_link(struct btrfs_trans_handle *trans,
db0a669f 6240 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
e02119d5 6241 const char *name, int name_len, int add_backref, u64 index)
39279cc3 6242{
db0a669f 6243 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
4df27c4d 6244 int ret = 0;
39279cc3 6245 struct btrfs_key key;
db0a669f
NB
6246 struct btrfs_root *root = parent_inode->root;
6247 u64 ino = btrfs_ino(inode);
6248 u64 parent_ino = btrfs_ino(parent_inode);
5f39d397 6249
33345d01 6250 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
db0a669f 6251 memcpy(&key, &inode->root->root_key, sizeof(key));
4df27c4d 6252 } else {
33345d01 6253 key.objectid = ino;
962a298f 6254 key.type = BTRFS_INODE_ITEM_KEY;
4df27c4d
YZ
6255 key.offset = 0;
6256 }
6257
33345d01 6258 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
0b246afa
JM
6259 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6260 root->root_key.objectid, parent_ino,
6261 index, name, name_len);
4df27c4d 6262 } else if (add_backref) {
33345d01
LZ
6263 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6264 parent_ino, index);
4df27c4d 6265 }
39279cc3 6266
79787eaa
JM
6267 /* Nothing to clean up yet */
6268 if (ret)
6269 return ret;
4df27c4d 6270
79787eaa
JM
6271 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6272 parent_inode, &key,
db0a669f 6273 btrfs_inode_type(&inode->vfs_inode), index);
9c52057c 6274 if (ret == -EEXIST || ret == -EOVERFLOW)
79787eaa
JM
6275 goto fail_dir_item;
6276 else if (ret) {
66642832 6277 btrfs_abort_transaction(trans, ret);
79787eaa 6278 return ret;
39279cc3 6279 }
79787eaa 6280
db0a669f 6281 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
79787eaa 6282 name_len * 2);
db0a669f
NB
6283 inode_inc_iversion(&parent_inode->vfs_inode);
6284 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6285 current_time(&parent_inode->vfs_inode);
6286 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
79787eaa 6287 if (ret)
66642832 6288 btrfs_abort_transaction(trans, ret);
39279cc3 6289 return ret;
fe66a05a
CM
6290
6291fail_dir_item:
6292 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6293 u64 local_index;
6294 int err;
0b246afa
JM
6295 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6296 root->root_key.objectid, parent_ino,
6297 &local_index, name, name_len);
fe66a05a
CM
6298
6299 } else if (add_backref) {
6300 u64 local_index;
6301 int err;
6302
6303 err = btrfs_del_inode_ref(trans, root, name, name_len,
6304 ino, parent_ino, &local_index);
6305 }
6306 return ret;
39279cc3
CM
6307}
6308
6309static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
cef415af
NB
6310 struct btrfs_inode *dir, struct dentry *dentry,
6311 struct btrfs_inode *inode, int backref, u64 index)
39279cc3 6312{
a1b075d2
JB
6313 int err = btrfs_add_link(trans, dir, inode,
6314 dentry->d_name.name, dentry->d_name.len,
6315 backref, index);
39279cc3
CM
6316 if (err > 0)
6317 err = -EEXIST;
6318 return err;
6319}
6320
618e21d5 6321static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
1a67aafb 6322 umode_t mode, dev_t rdev)
618e21d5 6323{
2ff7e61e 6324 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
618e21d5
JB
6325 struct btrfs_trans_handle *trans;
6326 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6327 struct inode *inode = NULL;
618e21d5
JB
6328 int err;
6329 int drop_inode = 0;
6330 u64 objectid;
00e4e6b3 6331 u64 index = 0;
618e21d5 6332
9ed74f2d
JB
6333 /*
6334 * 2 for inode item and ref
6335 * 2 for dir items
6336 * 1 for xattr if selinux is on
6337 */
a22285a6
YZ
6338 trans = btrfs_start_transaction(root, 5);
6339 if (IS_ERR(trans))
6340 return PTR_ERR(trans);
1832a6d5 6341
581bb050
LZ
6342 err = btrfs_find_free_ino(root, &objectid);
6343 if (err)
6344 goto out_unlock;
6345
aec7477b 6346 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6347 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6348 mode, &index);
7cf96da3
TI
6349 if (IS_ERR(inode)) {
6350 err = PTR_ERR(inode);
618e21d5 6351 goto out_unlock;
7cf96da3 6352 }
618e21d5 6353
ad19db71
CS
6354 /*
6355 * If the active LSM wants to access the inode during
6356 * d_instantiate it needs these. Smack checks to see
6357 * if the filesystem supports xattrs by looking at the
6358 * ops vector.
6359 */
ad19db71 6360 inode->i_op = &btrfs_special_inode_operations;
b0d5d10f
CM
6361 init_special_inode(inode, inode->i_mode, rdev);
6362
6363 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
618e21d5 6364 if (err)
b0d5d10f
CM
6365 goto out_unlock_inode;
6366
cef415af
NB
6367 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6368 0, index);
b0d5d10f
CM
6369 if (err) {
6370 goto out_unlock_inode;
6371 } else {
1b4ab1bb 6372 btrfs_update_inode(trans, root, inode);
b0d5d10f 6373 unlock_new_inode(inode);
08c422c2 6374 d_instantiate(dentry, inode);
618e21d5 6375 }
b0d5d10f 6376
618e21d5 6377out_unlock:
3a45bb20 6378 btrfs_end_transaction(trans);
2ff7e61e
JM
6379 btrfs_balance_delayed_items(fs_info);
6380 btrfs_btree_balance_dirty(fs_info);
618e21d5
JB
6381 if (drop_inode) {
6382 inode_dec_link_count(inode);
6383 iput(inode);
6384 }
618e21d5 6385 return err;
b0d5d10f
CM
6386
6387out_unlock_inode:
6388 drop_inode = 1;
6389 unlock_new_inode(inode);
6390 goto out_unlock;
6391
618e21d5
JB
6392}
6393
39279cc3 6394static int btrfs_create(struct inode *dir, struct dentry *dentry,
ebfc3b49 6395 umode_t mode, bool excl)
39279cc3 6396{
2ff7e61e 6397 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
6398 struct btrfs_trans_handle *trans;
6399 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 6400 struct inode *inode = NULL;
43baa579 6401 int drop_inode_on_err = 0;
a22285a6 6402 int err;
39279cc3 6403 u64 objectid;
00e4e6b3 6404 u64 index = 0;
39279cc3 6405
9ed74f2d
JB
6406 /*
6407 * 2 for inode item and ref
6408 * 2 for dir items
6409 * 1 for xattr if selinux is on
6410 */
a22285a6
YZ
6411 trans = btrfs_start_transaction(root, 5);
6412 if (IS_ERR(trans))
6413 return PTR_ERR(trans);
9ed74f2d 6414
581bb050
LZ
6415 err = btrfs_find_free_ino(root, &objectid);
6416 if (err)
6417 goto out_unlock;
6418
aec7477b 6419 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6420 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6421 mode, &index);
7cf96da3
TI
6422 if (IS_ERR(inode)) {
6423 err = PTR_ERR(inode);
39279cc3 6424 goto out_unlock;
7cf96da3 6425 }
43baa579 6426 drop_inode_on_err = 1;
ad19db71
CS
6427 /*
6428 * If the active LSM wants to access the inode during
6429 * d_instantiate it needs these. Smack checks to see
6430 * if the filesystem supports xattrs by looking at the
6431 * ops vector.
6432 */
6433 inode->i_fop = &btrfs_file_operations;
6434 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 6435 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
6436
6437 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6438 if (err)
6439 goto out_unlock_inode;
6440
6441 err = btrfs_update_inode(trans, root, inode);
6442 if (err)
6443 goto out_unlock_inode;
ad19db71 6444
cef415af
NB
6445 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6446 0, index);
39279cc3 6447 if (err)
b0d5d10f 6448 goto out_unlock_inode;
43baa579 6449
43baa579 6450 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
b0d5d10f 6451 unlock_new_inode(inode);
43baa579
FB
6452 d_instantiate(dentry, inode);
6453
39279cc3 6454out_unlock:
3a45bb20 6455 btrfs_end_transaction(trans);
43baa579 6456 if (err && drop_inode_on_err) {
39279cc3
CM
6457 inode_dec_link_count(inode);
6458 iput(inode);
6459 }
2ff7e61e
JM
6460 btrfs_balance_delayed_items(fs_info);
6461 btrfs_btree_balance_dirty(fs_info);
39279cc3 6462 return err;
b0d5d10f
CM
6463
6464out_unlock_inode:
6465 unlock_new_inode(inode);
6466 goto out_unlock;
6467
39279cc3
CM
6468}
6469
6470static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6471 struct dentry *dentry)
6472{
271dba45 6473 struct btrfs_trans_handle *trans = NULL;
39279cc3 6474 struct btrfs_root *root = BTRFS_I(dir)->root;
2b0143b5 6475 struct inode *inode = d_inode(old_dentry);
2ff7e61e 6476 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
00e4e6b3 6477 u64 index;
39279cc3
CM
6478 int err;
6479 int drop_inode = 0;
6480
4a8be425
TH
6481 /* do not allow sys_link's with other subvols of the same device */
6482 if (root->objectid != BTRFS_I(inode)->root->objectid)
3ab3564f 6483 return -EXDEV;
4a8be425 6484
f186373f 6485 if (inode->i_nlink >= BTRFS_LINK_MAX)
c055e99e 6486 return -EMLINK;
4a8be425 6487
877574e2 6488 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
aec7477b
JB
6489 if (err)
6490 goto fail;
6491
a22285a6 6492 /*
7e6b6465 6493 * 2 items for inode and inode ref
a22285a6 6494 * 2 items for dir items
7e6b6465 6495 * 1 item for parent inode
a22285a6 6496 */
7e6b6465 6497 trans = btrfs_start_transaction(root, 5);
a22285a6
YZ
6498 if (IS_ERR(trans)) {
6499 err = PTR_ERR(trans);
271dba45 6500 trans = NULL;
a22285a6
YZ
6501 goto fail;
6502 }
5f39d397 6503
67de1176
MX
6504 /* There are several dir indexes for this inode, clear the cache. */
6505 BTRFS_I(inode)->dir_index = 0ULL;
8b558c5f 6506 inc_nlink(inode);
0c4d2d95 6507 inode_inc_iversion(inode);
c2050a45 6508 inode->i_ctime = current_time(inode);
7de9c6ee 6509 ihold(inode);
e9976151 6510 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
aec7477b 6511
cef415af
NB
6512 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6513 1, index);
5f39d397 6514
a5719521 6515 if (err) {
54aa1f4d 6516 drop_inode = 1;
a5719521 6517 } else {
10d9f309 6518 struct dentry *parent = dentry->d_parent;
a5719521 6519 err = btrfs_update_inode(trans, root, inode);
79787eaa
JM
6520 if (err)
6521 goto fail;
ef3b9af5
FM
6522 if (inode->i_nlink == 1) {
6523 /*
6524 * If new hard link count is 1, it's a file created
6525 * with open(2) O_TMPFILE flag.
6526 */
3d6ae7bb 6527 err = btrfs_orphan_del(trans, BTRFS_I(inode));
ef3b9af5
FM
6528 if (err)
6529 goto fail;
6530 }
08c422c2 6531 d_instantiate(dentry, inode);
9ca5fbfb 6532 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
a5719521 6533 }
39279cc3 6534
2ff7e61e 6535 btrfs_balance_delayed_items(fs_info);
1832a6d5 6536fail:
271dba45 6537 if (trans)
3a45bb20 6538 btrfs_end_transaction(trans);
39279cc3
CM
6539 if (drop_inode) {
6540 inode_dec_link_count(inode);
6541 iput(inode);
6542 }
2ff7e61e 6543 btrfs_btree_balance_dirty(fs_info);
39279cc3
CM
6544 return err;
6545}
6546
18bb1db3 6547static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
39279cc3 6548{
2ff7e61e 6549 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
b9d86667 6550 struct inode *inode = NULL;
39279cc3
CM
6551 struct btrfs_trans_handle *trans;
6552 struct btrfs_root *root = BTRFS_I(dir)->root;
6553 int err = 0;
6554 int drop_on_err = 0;
b9d86667 6555 u64 objectid = 0;
00e4e6b3 6556 u64 index = 0;
39279cc3 6557
9ed74f2d
JB
6558 /*
6559 * 2 items for inode and ref
6560 * 2 items for dir items
6561 * 1 for xattr if selinux is on
6562 */
a22285a6
YZ
6563 trans = btrfs_start_transaction(root, 5);
6564 if (IS_ERR(trans))
6565 return PTR_ERR(trans);
39279cc3 6566
581bb050
LZ
6567 err = btrfs_find_free_ino(root, &objectid);
6568 if (err)
6569 goto out_fail;
6570
aec7477b 6571 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
6572 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6573 S_IFDIR | mode, &index);
39279cc3
CM
6574 if (IS_ERR(inode)) {
6575 err = PTR_ERR(inode);
6576 goto out_fail;
6577 }
5f39d397 6578
39279cc3 6579 drop_on_err = 1;
b0d5d10f
CM
6580 /* these must be set before we unlock the inode */
6581 inode->i_op = &btrfs_dir_inode_operations;
6582 inode->i_fop = &btrfs_dir_file_operations;
33268eaf 6583
2a7dba39 6584 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
33268eaf 6585 if (err)
b0d5d10f 6586 goto out_fail_inode;
39279cc3 6587
6ef06d27 6588 btrfs_i_size_write(BTRFS_I(inode), 0);
39279cc3
CM
6589 err = btrfs_update_inode(trans, root, inode);
6590 if (err)
b0d5d10f 6591 goto out_fail_inode;
5f39d397 6592
db0a669f
NB
6593 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6594 dentry->d_name.name,
6595 dentry->d_name.len, 0, index);
39279cc3 6596 if (err)
b0d5d10f 6597 goto out_fail_inode;
5f39d397 6598
39279cc3 6599 d_instantiate(dentry, inode);
b0d5d10f
CM
6600 /*
6601 * mkdir is special. We're unlocking after we call d_instantiate
6602 * to avoid a race with nfsd calling d_instantiate.
6603 */
6604 unlock_new_inode(inode);
39279cc3 6605 drop_on_err = 0;
39279cc3
CM
6606
6607out_fail:
3a45bb20 6608 btrfs_end_transaction(trans);
c7cfb8a5
WS
6609 if (drop_on_err) {
6610 inode_dec_link_count(inode);
39279cc3 6611 iput(inode);
c7cfb8a5 6612 }
2ff7e61e
JM
6613 btrfs_balance_delayed_items(fs_info);
6614 btrfs_btree_balance_dirty(fs_info);
39279cc3 6615 return err;
b0d5d10f
CM
6616
6617out_fail_inode:
6618 unlock_new_inode(inode);
6619 goto out_fail;
39279cc3
CM
6620}
6621
e6c4efd8
QW
6622/* Find next extent map of a given extent map, caller needs to ensure locks */
6623static struct extent_map *next_extent_map(struct extent_map *em)
6624{
6625 struct rb_node *next;
6626
6627 next = rb_next(&em->rb_node);
6628 if (!next)
6629 return NULL;
6630 return container_of(next, struct extent_map, rb_node);
6631}
6632
6633static struct extent_map *prev_extent_map(struct extent_map *em)
6634{
6635 struct rb_node *prev;
6636
6637 prev = rb_prev(&em->rb_node);
6638 if (!prev)
6639 return NULL;
6640 return container_of(prev, struct extent_map, rb_node);
6641}
6642
d352ac68 6643/* helper for btfs_get_extent. Given an existing extent in the tree,
e6c4efd8 6644 * the existing extent is the nearest extent to map_start,
d352ac68 6645 * and an extent that you want to insert, deal with overlap and insert
e6c4efd8 6646 * the best fitted new extent into the tree.
d352ac68 6647 */
3b951516
CM
6648static int merge_extent_mapping(struct extent_map_tree *em_tree,
6649 struct extent_map *existing,
e6dcd2dc 6650 struct extent_map *em,
51f395ad 6651 u64 map_start)
3b951516 6652{
e6c4efd8
QW
6653 struct extent_map *prev;
6654 struct extent_map *next;
6655 u64 start;
6656 u64 end;
3b951516 6657 u64 start_diff;
3b951516 6658
e6dcd2dc 6659 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
e6c4efd8
QW
6660
6661 if (existing->start > map_start) {
6662 next = existing;
6663 prev = prev_extent_map(next);
6664 } else {
6665 prev = existing;
6666 next = next_extent_map(prev);
6667 }
6668
6669 start = prev ? extent_map_end(prev) : em->start;
6670 start = max_t(u64, start, em->start);
6671 end = next ? next->start : extent_map_end(em);
6672 end = min_t(u64, end, extent_map_end(em));
6673 start_diff = start - em->start;
6674 em->start = start;
6675 em->len = end - start;
c8b97818
CM
6676 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6677 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
e6dcd2dc 6678 em->block_start += start_diff;
c8b97818
CM
6679 em->block_len -= start_diff;
6680 }
09a2a8f9 6681 return add_extent_mapping(em_tree, em, 0);
3b951516
CM
6682}
6683
c8b97818 6684static noinline int uncompress_inline(struct btrfs_path *path,
e40da0e5 6685 struct page *page,
c8b97818
CM
6686 size_t pg_offset, u64 extent_offset,
6687 struct btrfs_file_extent_item *item)
6688{
6689 int ret;
6690 struct extent_buffer *leaf = path->nodes[0];
6691 char *tmp;
6692 size_t max_size;
6693 unsigned long inline_size;
6694 unsigned long ptr;
261507a0 6695 int compress_type;
c8b97818
CM
6696
6697 WARN_ON(pg_offset != 0);
261507a0 6698 compress_type = btrfs_file_extent_compression(leaf, item);
c8b97818
CM
6699 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6700 inline_size = btrfs_file_extent_inline_item_len(leaf,
dd3cc16b 6701 btrfs_item_nr(path->slots[0]));
c8b97818 6702 tmp = kmalloc(inline_size, GFP_NOFS);
8d413713
TI
6703 if (!tmp)
6704 return -ENOMEM;
c8b97818
CM
6705 ptr = btrfs_file_extent_inline_start(item);
6706
6707 read_extent_buffer(leaf, tmp, ptr, inline_size);
6708
09cbfeaf 6709 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
261507a0
LZ
6710 ret = btrfs_decompress(compress_type, tmp, page,
6711 extent_offset, inline_size, max_size);
c8b97818 6712 kfree(tmp);
166ae5a4 6713 return ret;
c8b97818
CM
6714}
6715
d352ac68
CM
6716/*
6717 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
6718 * the ugly parts come from merging extents from the disk with the in-ram
6719 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
6720 * where the in-ram extents might be locked pending data=ordered completion.
6721 *
6722 * This also copies inline extents directly into the page.
6723 */
d397712b 6724
fc4f21b1
NB
6725struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6726 struct page *page,
6727 size_t pg_offset, u64 start, u64 len,
6728 int create)
a52d9a80 6729{
fc4f21b1 6730 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
a52d9a80
CM
6731 int ret;
6732 int err = 0;
a52d9a80
CM
6733 u64 extent_start = 0;
6734 u64 extent_end = 0;
fc4f21b1 6735 u64 objectid = btrfs_ino(inode);
a52d9a80 6736 u32 found_type;
f421950f 6737 struct btrfs_path *path = NULL;
fc4f21b1 6738 struct btrfs_root *root = inode->root;
a52d9a80 6739 struct btrfs_file_extent_item *item;
5f39d397
CM
6740 struct extent_buffer *leaf;
6741 struct btrfs_key found_key;
a52d9a80 6742 struct extent_map *em = NULL;
fc4f21b1
NB
6743 struct extent_map_tree *em_tree = &inode->extent_tree;
6744 struct extent_io_tree *io_tree = &inode->io_tree;
a52d9a80 6745 struct btrfs_trans_handle *trans = NULL;
7ffbb598 6746 const bool new_inline = !page || create;
a52d9a80 6747
a52d9a80 6748again:
890871be 6749 read_lock(&em_tree->lock);
d1310b2e 6750 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d 6751 if (em)
0b246afa 6752 em->bdev = fs_info->fs_devices->latest_bdev;
890871be 6753 read_unlock(&em_tree->lock);
d1310b2e 6754
a52d9a80 6755 if (em) {
e1c4b745
CM
6756 if (em->start > start || em->start + em->len <= start)
6757 free_extent_map(em);
6758 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
6759 free_extent_map(em);
6760 else
6761 goto out;
a52d9a80 6762 }
172ddd60 6763 em = alloc_extent_map();
a52d9a80 6764 if (!em) {
d1310b2e
CM
6765 err = -ENOMEM;
6766 goto out;
a52d9a80 6767 }
0b246afa 6768 em->bdev = fs_info->fs_devices->latest_bdev;
d1310b2e 6769 em->start = EXTENT_MAP_HOLE;
445a6944 6770 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 6771 em->len = (u64)-1;
c8b97818 6772 em->block_len = (u64)-1;
f421950f
CM
6773
6774 if (!path) {
6775 path = btrfs_alloc_path();
026fd317
JB
6776 if (!path) {
6777 err = -ENOMEM;
6778 goto out;
6779 }
6780 /*
6781 * Chances are we'll be called again, so go ahead and do
6782 * readahead
6783 */
e4058b54 6784 path->reada = READA_FORWARD;
f421950f
CM
6785 }
6786
179e29e4
CM
6787 ret = btrfs_lookup_file_extent(trans, root, path,
6788 objectid, start, trans != NULL);
a52d9a80
CM
6789 if (ret < 0) {
6790 err = ret;
6791 goto out;
6792 }
6793
6794 if (ret != 0) {
6795 if (path->slots[0] == 0)
6796 goto not_found;
6797 path->slots[0]--;
6798 }
6799
5f39d397
CM
6800 leaf = path->nodes[0];
6801 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 6802 struct btrfs_file_extent_item);
a52d9a80 6803 /* are we inside the extent that was found? */
5f39d397 6804 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
962a298f 6805 found_type = found_key.type;
5f39d397 6806 if (found_key.objectid != objectid ||
a52d9a80 6807 found_type != BTRFS_EXTENT_DATA_KEY) {
25a50341
JB
6808 /*
6809 * If we backup past the first extent we want to move forward
6810 * and see if there is an extent in front of us, otherwise we'll
6811 * say there is a hole for our whole search range which can
6812 * cause problems.
6813 */
6814 extent_end = start;
6815 goto next;
a52d9a80
CM
6816 }
6817
5f39d397
CM
6818 found_type = btrfs_file_extent_type(leaf, item);
6819 extent_start = found_key.offset;
d899e052
YZ
6820 if (found_type == BTRFS_FILE_EXTENT_REG ||
6821 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 6822 extent_end = extent_start +
db94535d 6823 btrfs_file_extent_num_bytes(leaf, item);
9036c102
YZ
6824 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6825 size_t size;
514ac8ad 6826 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
da17066c 6827 extent_end = ALIGN(extent_start + size,
0b246afa 6828 fs_info->sectorsize);
9036c102 6829 }
25a50341 6830next:
9036c102
YZ
6831 if (start >= extent_end) {
6832 path->slots[0]++;
6833 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6834 ret = btrfs_next_leaf(root, path);
6835 if (ret < 0) {
6836 err = ret;
6837 goto out;
a52d9a80 6838 }
9036c102
YZ
6839 if (ret > 0)
6840 goto not_found;
6841 leaf = path->nodes[0];
a52d9a80 6842 }
9036c102
YZ
6843 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6844 if (found_key.objectid != objectid ||
6845 found_key.type != BTRFS_EXTENT_DATA_KEY)
6846 goto not_found;
6847 if (start + len <= found_key.offset)
6848 goto not_found;
e2eca69d
WS
6849 if (start > found_key.offset)
6850 goto next;
9036c102 6851 em->start = start;
70c8a91c 6852 em->orig_start = start;
9036c102
YZ
6853 em->len = found_key.offset - start;
6854 goto not_found_em;
6855 }
6856
fc4f21b1 6857 btrfs_extent_item_to_extent_map(inode, path, item,
9cdc5124 6858 new_inline, em);
7ffbb598 6859
d899e052
YZ
6860 if (found_type == BTRFS_FILE_EXTENT_REG ||
6861 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80
CM
6862 goto insert;
6863 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 6864 unsigned long ptr;
a52d9a80 6865 char *map;
3326d1b0
CM
6866 size_t size;
6867 size_t extent_offset;
6868 size_t copy_size;
a52d9a80 6869
7ffbb598 6870 if (new_inline)
689f9346 6871 goto out;
5f39d397 6872
514ac8ad 6873 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
9036c102 6874 extent_offset = page_offset(page) + pg_offset - extent_start;
09cbfeaf
KS
6875 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6876 size - extent_offset);
3326d1b0 6877 em->start = extent_start + extent_offset;
0b246afa 6878 em->len = ALIGN(copy_size, fs_info->sectorsize);
b4939680 6879 em->orig_block_len = em->len;
70c8a91c 6880 em->orig_start = em->start;
689f9346 6881 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
179e29e4 6882 if (create == 0 && !PageUptodate(page)) {
261507a0
LZ
6883 if (btrfs_file_extent_compression(leaf, item) !=
6884 BTRFS_COMPRESS_NONE) {
e40da0e5 6885 ret = uncompress_inline(path, page, pg_offset,
c8b97818 6886 extent_offset, item);
166ae5a4
ZB
6887 if (ret) {
6888 err = ret;
6889 goto out;
6890 }
c8b97818
CM
6891 } else {
6892 map = kmap(page);
6893 read_extent_buffer(leaf, map + pg_offset, ptr,
6894 copy_size);
09cbfeaf 6895 if (pg_offset + copy_size < PAGE_SIZE) {
93c82d57 6896 memset(map + pg_offset + copy_size, 0,
09cbfeaf 6897 PAGE_SIZE - pg_offset -
93c82d57
CM
6898 copy_size);
6899 }
c8b97818
CM
6900 kunmap(page);
6901 }
179e29e4
CM
6902 flush_dcache_page(page);
6903 } else if (create && PageUptodate(page)) {
6bf7e080 6904 BUG();
179e29e4
CM
6905 if (!trans) {
6906 kunmap(page);
6907 free_extent_map(em);
6908 em = NULL;
ff5714cc 6909
b3b4aa74 6910 btrfs_release_path(path);
7a7eaa40 6911 trans = btrfs_join_transaction(root);
ff5714cc 6912
3612b495
TI
6913 if (IS_ERR(trans))
6914 return ERR_CAST(trans);
179e29e4
CM
6915 goto again;
6916 }
c8b97818 6917 map = kmap(page);
70dec807 6918 write_extent_buffer(leaf, map + pg_offset, ptr,
179e29e4 6919 copy_size);
c8b97818 6920 kunmap(page);
179e29e4 6921 btrfs_mark_buffer_dirty(leaf);
a52d9a80 6922 }
d1310b2e 6923 set_extent_uptodate(io_tree, em->start,
507903b8 6924 extent_map_end(em) - 1, NULL, GFP_NOFS);
a52d9a80 6925 goto insert;
a52d9a80
CM
6926 }
6927not_found:
6928 em->start = start;
70c8a91c 6929 em->orig_start = start;
d1310b2e 6930 em->len = len;
a52d9a80 6931not_found_em:
5f39d397 6932 em->block_start = EXTENT_MAP_HOLE;
9036c102 6933 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
a52d9a80 6934insert:
b3b4aa74 6935 btrfs_release_path(path);
d1310b2e 6936 if (em->start > start || extent_map_end(em) <= start) {
0b246afa 6937 btrfs_err(fs_info,
5d163e0e
JM
6938 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6939 em->start, em->len, start, len);
a52d9a80
CM
6940 err = -EIO;
6941 goto out;
6942 }
d1310b2e
CM
6943
6944 err = 0;
890871be 6945 write_lock(&em_tree->lock);
09a2a8f9 6946 ret = add_extent_mapping(em_tree, em, 0);
3b951516
CM
6947 /* it is possible that someone inserted the extent into the tree
6948 * while we had the lock dropped. It is also possible that
6949 * an overlapping map exists in the tree
6950 */
a52d9a80 6951 if (ret == -EEXIST) {
3b951516 6952 struct extent_map *existing;
e6dcd2dc
CM
6953
6954 ret = 0;
6955
e6c4efd8
QW
6956 existing = search_extent_mapping(em_tree, start, len);
6957 /*
6958 * existing will always be non-NULL, since there must be
6959 * extent causing the -EEXIST.
6960 */
8dff9c85 6961 if (existing->start == em->start &&
8e2bd3b7 6962 extent_map_end(existing) >= extent_map_end(em) &&
8dff9c85
CM
6963 em->block_start == existing->block_start) {
6964 /*
8e2bd3b7
OS
6965 * The existing extent map already encompasses the
6966 * entire extent map we tried to add.
8dff9c85
CM
6967 */
6968 free_extent_map(em);
6969 em = existing;
6970 err = 0;
6971
6972 } else if (start >= extent_map_end(existing) ||
32be3a1a 6973 start <= existing->start) {
e6c4efd8
QW
6974 /*
6975 * The existing extent map is the one nearest to
6976 * the [start, start + len) range which overlaps
6977 */
6978 err = merge_extent_mapping(em_tree, existing,
6979 em, start);
e1c4b745 6980 free_extent_map(existing);
e6c4efd8 6981 if (err) {
3b951516
CM
6982 free_extent_map(em);
6983 em = NULL;
6984 }
6985 } else {
6986 free_extent_map(em);
6987 em = existing;
e6dcd2dc 6988 err = 0;
a52d9a80 6989 }
a52d9a80 6990 }
890871be 6991 write_unlock(&em_tree->lock);
a52d9a80 6992out:
1abe9b8a 6993
fc4f21b1 6994 trace_btrfs_get_extent(root, inode, em);
1abe9b8a 6995
527afb44 6996 btrfs_free_path(path);
a52d9a80 6997 if (trans) {
3a45bb20 6998 ret = btrfs_end_transaction(trans);
d397712b 6999 if (!err)
a52d9a80
CM
7000 err = ret;
7001 }
a52d9a80
CM
7002 if (err) {
7003 free_extent_map(em);
a52d9a80
CM
7004 return ERR_PTR(err);
7005 }
79787eaa 7006 BUG_ON(!em); /* Error is always set */
a52d9a80
CM
7007 return em;
7008}
7009
fc4f21b1
NB
7010struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7011 struct page *page,
7012 size_t pg_offset, u64 start, u64 len,
7013 int create)
ec29ed5b
CM
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 */
fc4f21b1 7050 found = count_range_bits(&inode->io_tree, &range_start,
ec29ed5b
CM
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);
dcdbc059 7165 btrfs_drop_extent_cache(BTRFS_I(inode), start,
5f9a8a51
FM
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 */
a776c6fa 7426 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
eb838e73
JB
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 {
dcdbc059 7532 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
69ffb543
JB
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
fc4f21b1 7620 em = btrfs_get_extent(BTRFS_I(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) {
4ac1f4ac 7857 free_io_failure(BTRFS_I(inode), failrec);
8b110e39
MX
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 7870 if (!bio) {
4ac1f4ac 7871 free_io_failure(BTRFS_I(inode), failrec);
8b110e39
MX
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 7881 if (ret) {
4ac1f4ac 7882 free_io_failure(BTRFS_I(inode), failrec);
8b110e39
MX
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)
b30cb441 7912 clean_io_failure(BTRFS_I(done->inode), done->start, bvec->bv_page, 0);
8b110e39
MX
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 7997 if (!ret)
b30cb441 7998 clean_io_failure(BTRFS_I(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;
a776c6fa 8799 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
dbfdb6d1 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 */
a776c6fa
NB
8965 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8966 PAGE_SIZE);
e6dcd2dc 8967 if (ordered) {
2ac55d41
JB
8968 unlock_extent_cached(io_tree, page_start, page_end,
8969 &cached_state, GFP_NOFS);
e6dcd2dc 8970 unlock_page(page);
eb84ae03 8971 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
8972 btrfs_put_ordered_extent(ordered);
8973 goto again;
8974 }
8975
09cbfeaf 8976 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
da17066c 8977 reserved_space = round_up(size - page_start,
0b246afa 8978 fs_info->sectorsize);
09cbfeaf 8979 if (reserved_space < PAGE_SIZE) {
d0b7da88
CR
8980 end = page_start + reserved_space - 1;
8981 spin_lock(&BTRFS_I(inode)->lock);
8982 BTRFS_I(inode)->outstanding_extents++;
8983 spin_unlock(&BTRFS_I(inode)->lock);
8984 btrfs_delalloc_release_space(inode, page_start,
09cbfeaf 8985 PAGE_SIZE - reserved_space);
d0b7da88
CR
8986 }
8987 }
8988
fbf19087 8989 /*
5416034f
LB
8990 * page_mkwrite gets called when the page is firstly dirtied after it's
8991 * faulted in, but write(2) could also dirty a page and set delalloc
8992 * bits, thus in this case for space account reason, we still need to
8993 * clear any delalloc bits within this page range since we have to
8994 * reserve data&meta space before lock_page() (see above comments).
fbf19087 8995 */
d0b7da88 8996 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9e8a4a8b
LB
8997 EXTENT_DIRTY | EXTENT_DELALLOC |
8998 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
2ac55d41 8999 0, 0, &cached_state, GFP_NOFS);
fbf19087 9000
d0b7da88 9001 ret = btrfs_set_extent_delalloc(inode, page_start, end,
ba8b04c1 9002 &cached_state, 0);
9ed74f2d 9003 if (ret) {
2ac55d41
JB
9004 unlock_extent_cached(io_tree, page_start, page_end,
9005 &cached_state, GFP_NOFS);
9ed74f2d
JB
9006 ret = VM_FAULT_SIGBUS;
9007 goto out_unlock;
9008 }
e6dcd2dc 9009 ret = 0;
9ebefb18
CM
9010
9011 /* page is wholly or partially inside EOF */
09cbfeaf
KS
9012 if (page_start + PAGE_SIZE > size)
9013 zero_start = size & ~PAGE_MASK;
9ebefb18 9014 else
09cbfeaf 9015 zero_start = PAGE_SIZE;
9ebefb18 9016
09cbfeaf 9017 if (zero_start != PAGE_SIZE) {
e6dcd2dc 9018 kaddr = kmap(page);
09cbfeaf 9019 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
e6dcd2dc
CM
9020 flush_dcache_page(page);
9021 kunmap(page);
9022 }
247e743c 9023 ClearPageChecked(page);
e6dcd2dc 9024 set_page_dirty(page);
50a9b214 9025 SetPageUptodate(page);
5a3f23d5 9026
0b246afa 9027 BTRFS_I(inode)->last_trans = fs_info->generation;
257c62e1 9028 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
46d8bc34 9029 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
257c62e1 9030
2ac55d41 9031 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
9ebefb18
CM
9032
9033out_unlock:
b2b5ef5c
JK
9034 if (!ret) {
9035 sb_end_pagefault(inode->i_sb);
50a9b214 9036 return VM_FAULT_LOCKED;
b2b5ef5c 9037 }
9ebefb18 9038 unlock_page(page);
1832a6d5 9039out:
d0b7da88 9040 btrfs_delalloc_release_space(inode, page_start, reserved_space);
9998eb70 9041out_noreserve:
b2b5ef5c 9042 sb_end_pagefault(inode->i_sb);
9ebefb18
CM
9043 return ret;
9044}
9045
a41ad394 9046static int btrfs_truncate(struct inode *inode)
39279cc3 9047{
0b246afa 9048 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
39279cc3 9049 struct btrfs_root *root = BTRFS_I(inode)->root;
fcb80c2a 9050 struct btrfs_block_rsv *rsv;
a71754fc 9051 int ret = 0;
3893e33b 9052 int err = 0;
39279cc3 9053 struct btrfs_trans_handle *trans;
0b246afa
JM
9054 u64 mask = fs_info->sectorsize - 1;
9055 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
39279cc3 9056
0ef8b726
JB
9057 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9058 (u64)-1);
9059 if (ret)
9060 return ret;
39279cc3 9061
fcb80c2a 9062 /*
01327610 9063 * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
fcb80c2a
JB
9064 * 3 things going on here
9065 *
9066 * 1) We need to reserve space for our orphan item and the space to
9067 * delete our orphan item. Lord knows we don't want to have a dangling
9068 * orphan item because we didn't reserve space to remove it.
9069 *
9070 * 2) We need to reserve space to update our inode.
9071 *
9072 * 3) We need to have something to cache all the space that is going to
9073 * be free'd up by the truncate operation, but also have some slack
9074 * space reserved in case it uses space during the truncate (thank you
9075 * very much snapshotting).
9076 *
01327610 9077 * And we need these to all be separate. The fact is we can use a lot of
fcb80c2a 9078 * space doing the truncate, and we have no earthly idea how much space
01327610 9079 * we will use, so we need the truncate reservation to be separate so it
fcb80c2a
JB
9080 * doesn't end up using space reserved for updating the inode or
9081 * removing the orphan item. We also need to be able to stop the
9082 * transaction and start a new one, which means we need to be able to
9083 * update the inode several times, and we have no idea of knowing how
9084 * many times that will be, so we can't just reserve 1 item for the
01327610 9085 * entirety of the operation, so that has to be done separately as well.
fcb80c2a
JB
9086 * Then there is the orphan item, which does indeed need to be held on
9087 * to for the whole operation, and we need nobody to touch this reserved
9088 * space except the orphan code.
9089 *
9090 * So that leaves us with
9091 *
9092 * 1) root->orphan_block_rsv - for the orphan deletion.
9093 * 2) rsv - for the truncate reservation, which we will steal from the
9094 * transaction reservation.
9095 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
9096 * updating the inode.
9097 */
2ff7e61e 9098 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
fcb80c2a
JB
9099 if (!rsv)
9100 return -ENOMEM;
4a338542 9101 rsv->size = min_size;
ca7e70f5 9102 rsv->failfast = 1;
f0cd846e 9103
907cbceb 9104 /*
07127184 9105 * 1 for the truncate slack space
907cbceb
JB
9106 * 1 for updating the inode.
9107 */
f3fe820c 9108 trans = btrfs_start_transaction(root, 2);
fcb80c2a
JB
9109 if (IS_ERR(trans)) {
9110 err = PTR_ERR(trans);
9111 goto out;
9112 }
f0cd846e 9113
907cbceb 9114 /* Migrate the slack space for the truncate to our reserve */
0b246afa 9115 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
25d609f8 9116 min_size, 0);
fcb80c2a 9117 BUG_ON(ret);
f0cd846e 9118
5dc562c5
JB
9119 /*
9120 * So if we truncate and then write and fsync we normally would just
9121 * write the extents that changed, which is a problem if we need to
9122 * first truncate that entire inode. So set this flag so we write out
9123 * all of the extents in the inode to the sync log so we're completely
9124 * safe.
9125 */
9126 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
ca7e70f5 9127 trans->block_rsv = rsv;
907cbceb 9128
8082510e
YZ
9129 while (1) {
9130 ret = btrfs_truncate_inode_items(trans, root, inode,
9131 inode->i_size,
9132 BTRFS_EXTENT_DATA_KEY);
28ed1345 9133 if (ret != -ENOSPC && ret != -EAGAIN) {
3893e33b 9134 err = ret;
8082510e 9135 break;
3893e33b 9136 }
39279cc3 9137
0b246afa 9138 trans->block_rsv = &fs_info->trans_block_rsv;
8082510e 9139 ret = btrfs_update_inode(trans, root, inode);
3893e33b
JB
9140 if (ret) {
9141 err = ret;
9142 break;
9143 }
ca7e70f5 9144
3a45bb20 9145 btrfs_end_transaction(trans);
2ff7e61e 9146 btrfs_btree_balance_dirty(fs_info);
ca7e70f5
JB
9147
9148 trans = btrfs_start_transaction(root, 2);
9149 if (IS_ERR(trans)) {
9150 ret = err = PTR_ERR(trans);
9151 trans = NULL;
9152 break;
9153 }
9154
47b5d646 9155 btrfs_block_rsv_release(fs_info, rsv, -1);
0b246afa 9156 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
25d609f8 9157 rsv, min_size, 0);
ca7e70f5
JB
9158 BUG_ON(ret); /* shouldn't happen */
9159 trans->block_rsv = rsv;
8082510e
YZ
9160 }
9161
9162 if (ret == 0 && inode->i_nlink > 0) {
fcb80c2a 9163 trans->block_rsv = root->orphan_block_rsv;
3d6ae7bb 9164 ret = btrfs_orphan_del(trans, BTRFS_I(inode));
3893e33b
JB
9165 if (ret)
9166 err = ret;
8082510e
YZ
9167 }
9168
917c16b2 9169 if (trans) {
0b246afa 9170 trans->block_rsv = &fs_info->trans_block_rsv;
917c16b2
CM
9171 ret = btrfs_update_inode(trans, root, inode);
9172 if (ret && !err)
9173 err = ret;
7b128766 9174
3a45bb20 9175 ret = btrfs_end_transaction(trans);
2ff7e61e 9176 btrfs_btree_balance_dirty(fs_info);
917c16b2 9177 }
fcb80c2a 9178out:
2ff7e61e 9179 btrfs_free_block_rsv(fs_info, rsv);
fcb80c2a 9180
3893e33b
JB
9181 if (ret && !err)
9182 err = ret;
a41ad394 9183
3893e33b 9184 return err;
39279cc3
CM
9185}
9186
d352ac68
CM
9187/*
9188 * create a new subvolume directory/inode (helper for the ioctl).
9189 */
d2fb3437 9190int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
63541927
FDBM
9191 struct btrfs_root *new_root,
9192 struct btrfs_root *parent_root,
9193 u64 new_dirid)
39279cc3 9194{
39279cc3 9195 struct inode *inode;
76dda93c 9196 int err;
00e4e6b3 9197 u64 index = 0;
39279cc3 9198
12fc9d09
FA
9199 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9200 new_dirid, new_dirid,
9201 S_IFDIR | (~current_umask() & S_IRWXUGO),
9202 &index);
54aa1f4d 9203 if (IS_ERR(inode))
f46b5a66 9204 return PTR_ERR(inode);
39279cc3
CM
9205 inode->i_op = &btrfs_dir_inode_operations;
9206 inode->i_fop = &btrfs_dir_file_operations;
9207
bfe86848 9208 set_nlink(inode, 1);
6ef06d27 9209 btrfs_i_size_write(BTRFS_I(inode), 0);
b0d5d10f 9210 unlock_new_inode(inode);
3b96362c 9211
63541927
FDBM
9212 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9213 if (err)
9214 btrfs_err(new_root->fs_info,
351fd353 9215 "error inheriting subvolume %llu properties: %d",
63541927
FDBM
9216 new_root->root_key.objectid, err);
9217
76dda93c 9218 err = btrfs_update_inode(trans, new_root, inode);
cb8e7090 9219
76dda93c 9220 iput(inode);
ce598979 9221 return err;
39279cc3
CM
9222}
9223
39279cc3
CM
9224struct inode *btrfs_alloc_inode(struct super_block *sb)
9225{
9226 struct btrfs_inode *ei;
2ead6ae7 9227 struct inode *inode;
39279cc3
CM
9228
9229 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9230 if (!ei)
9231 return NULL;
2ead6ae7
YZ
9232
9233 ei->root = NULL;
2ead6ae7 9234 ei->generation = 0;
15ee9bc7 9235 ei->last_trans = 0;
257c62e1 9236 ei->last_sub_trans = 0;
e02119d5 9237 ei->logged_trans = 0;
2ead6ae7 9238 ei->delalloc_bytes = 0;
47059d93 9239 ei->defrag_bytes = 0;
2ead6ae7
YZ
9240 ei->disk_i_size = 0;
9241 ei->flags = 0;
7709cde3 9242 ei->csum_bytes = 0;
2ead6ae7 9243 ei->index_cnt = (u64)-1;
67de1176 9244 ei->dir_index = 0;
2ead6ae7 9245 ei->last_unlink_trans = 0;
46d8bc34 9246 ei->last_log_commit = 0;
8089fe62 9247 ei->delayed_iput_count = 0;
2ead6ae7 9248
9e0baf60
JB
9249 spin_lock_init(&ei->lock);
9250 ei->outstanding_extents = 0;
9251 ei->reserved_extents = 0;
2ead6ae7 9252
72ac3c0d 9253 ei->runtime_flags = 0;
261507a0 9254 ei->force_compress = BTRFS_COMPRESS_NONE;
2ead6ae7 9255
16cdcec7
MX
9256 ei->delayed_node = NULL;
9257
9cc97d64 9258 ei->i_otime.tv_sec = 0;
9259 ei->i_otime.tv_nsec = 0;
9260
2ead6ae7 9261 inode = &ei->vfs_inode;
a8067e02 9262 extent_map_tree_init(&ei->extent_tree);
f993c883
DS
9263 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9264 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
0b32f4bb
JB
9265 ei->io_tree.track_uptodate = 1;
9266 ei->io_failure_tree.track_uptodate = 1;
b812ce28 9267 atomic_set(&ei->sync_writers, 0);
2ead6ae7 9268 mutex_init(&ei->log_mutex);
f248679e 9269 mutex_init(&ei->delalloc_mutex);
e6dcd2dc 9270 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
2ead6ae7 9271 INIT_LIST_HEAD(&ei->delalloc_inodes);
8089fe62 9272 INIT_LIST_HEAD(&ei->delayed_iput);
2ead6ae7 9273 RB_CLEAR_NODE(&ei->rb_node);
5f9a8a51 9274 init_rwsem(&ei->dio_sem);
2ead6ae7
YZ
9275
9276 return inode;
39279cc3
CM
9277}
9278
aaedb55b
JB
9279#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9280void btrfs_test_destroy_inode(struct inode *inode)
9281{
dcdbc059 9282 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
aaedb55b
JB
9283 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9284}
9285#endif
9286
fa0d7e3d
NP
9287static void btrfs_i_callback(struct rcu_head *head)
9288{
9289 struct inode *inode = container_of(head, struct inode, i_rcu);
fa0d7e3d
NP
9290 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9291}
9292
39279cc3
CM
9293void btrfs_destroy_inode(struct inode *inode)
9294{
0b246afa 9295 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
e6dcd2dc 9296 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
9297 struct btrfs_root *root = BTRFS_I(inode)->root;
9298
b3d9b7a3 9299 WARN_ON(!hlist_empty(&inode->i_dentry));
39279cc3 9300 WARN_ON(inode->i_data.nrpages);
9e0baf60
JB
9301 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9302 WARN_ON(BTRFS_I(inode)->reserved_extents);
7709cde3
JB
9303 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9304 WARN_ON(BTRFS_I(inode)->csum_bytes);
47059d93 9305 WARN_ON(BTRFS_I(inode)->defrag_bytes);
39279cc3 9306
a6dbd429
JB
9307 /*
9308 * This can happen where we create an inode, but somebody else also
9309 * created the same inode and we need to destroy the one we already
9310 * created.
9311 */
9312 if (!root)
9313 goto free;
9314
8a35d95f
JB
9315 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9316 &BTRFS_I(inode)->runtime_flags)) {
0b246afa 9317 btrfs_info(fs_info, "inode %llu still on the orphan list",
4a0cc7ca 9318 btrfs_ino(BTRFS_I(inode)));
8a35d95f 9319 atomic_dec(&root->orphan_inodes);
7b128766 9320 }
7b128766 9321
d397712b 9322 while (1) {
e6dcd2dc
CM
9323 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9324 if (!ordered)
9325 break;
9326 else {
0b246afa 9327 btrfs_err(fs_info,
5d163e0e
JM
9328 "found ordered extent %llu %llu on inode cleanup",
9329 ordered->file_offset, ordered->len);
e6dcd2dc
CM
9330 btrfs_remove_ordered_extent(inode, ordered);
9331 btrfs_put_ordered_extent(ordered);
9332 btrfs_put_ordered_extent(ordered);
9333 }
9334 }
56fa9d07 9335 btrfs_qgroup_check_reserved_leak(inode);
5d4f98a2 9336 inode_tree_del(inode);
dcdbc059 9337 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
a6dbd429 9338free:
fa0d7e3d 9339 call_rcu(&inode->i_rcu, btrfs_i_callback);
39279cc3
CM
9340}
9341
45321ac5 9342int btrfs_drop_inode(struct inode *inode)
76dda93c
YZ
9343{
9344 struct btrfs_root *root = BTRFS_I(inode)->root;
45321ac5 9345
6379ef9f
NA
9346 if (root == NULL)
9347 return 1;
9348
fa6ac876 9349 /* the snap/subvol tree is on deleting */
69e9c6c6 9350 if (btrfs_root_refs(&root->root_item) == 0)
45321ac5 9351 return 1;
76dda93c 9352 else
45321ac5 9353 return generic_drop_inode(inode);
76dda93c
YZ
9354}
9355
0ee0fda0 9356static void init_once(void *foo)
39279cc3
CM
9357{
9358 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9359
9360 inode_init_once(&ei->vfs_inode);
9361}
9362
9363void btrfs_destroy_cachep(void)
9364{
8c0a8537
KS
9365 /*
9366 * Make sure all delayed rcu free inodes are flushed before we
9367 * destroy cache.
9368 */
9369 rcu_barrier();
5598e900
KM
9370 kmem_cache_destroy(btrfs_inode_cachep);
9371 kmem_cache_destroy(btrfs_trans_handle_cachep);
9372 kmem_cache_destroy(btrfs_transaction_cachep);
9373 kmem_cache_destroy(btrfs_path_cachep);
9374 kmem_cache_destroy(btrfs_free_space_cachep);
39279cc3
CM
9375}
9376
9377int btrfs_init_cachep(void)
9378{
837e1972 9379 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9601e3f6 9380 sizeof(struct btrfs_inode), 0,
5d097056
VD
9381 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9382 init_once);
39279cc3
CM
9383 if (!btrfs_inode_cachep)
9384 goto fail;
9601e3f6 9385
837e1972 9386 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9601e3f6 9387 sizeof(struct btrfs_trans_handle), 0,
fba4b697 9388 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
9389 if (!btrfs_trans_handle_cachep)
9390 goto fail;
9601e3f6 9391
837e1972 9392 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9601e3f6 9393 sizeof(struct btrfs_transaction), 0,
fba4b697 9394 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
9395 if (!btrfs_transaction_cachep)
9396 goto fail;
9601e3f6 9397
837e1972 9398 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9601e3f6 9399 sizeof(struct btrfs_path), 0,
fba4b697 9400 SLAB_MEM_SPREAD, NULL);
39279cc3
CM
9401 if (!btrfs_path_cachep)
9402 goto fail;
9601e3f6 9403
837e1972 9404 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
dc89e982 9405 sizeof(struct btrfs_free_space), 0,
fba4b697 9406 SLAB_MEM_SPREAD, NULL);
dc89e982
JB
9407 if (!btrfs_free_space_cachep)
9408 goto fail;
9409
39279cc3
CM
9410 return 0;
9411fail:
9412 btrfs_destroy_cachep();
9413 return -ENOMEM;
9414}
9415
9416static int btrfs_getattr(struct vfsmount *mnt,
9417 struct dentry *dentry, struct kstat *stat)
9418{
df0af1a5 9419 u64 delalloc_bytes;
2b0143b5 9420 struct inode *inode = d_inode(dentry);
fadc0d8b
DS
9421 u32 blocksize = inode->i_sb->s_blocksize;
9422
39279cc3 9423 generic_fillattr(inode, stat);
0ee5dc67 9424 stat->dev = BTRFS_I(inode)->root->anon_dev;
df0af1a5
MX
9425
9426 spin_lock(&BTRFS_I(inode)->lock);
9427 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9428 spin_unlock(&BTRFS_I(inode)->lock);
fadc0d8b 9429 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
df0af1a5 9430 ALIGN(delalloc_bytes, blocksize)) >> 9;
39279cc3
CM
9431 return 0;
9432}
9433
cdd1fedf
DF
9434static int btrfs_rename_exchange(struct inode *old_dir,
9435 struct dentry *old_dentry,
9436 struct inode *new_dir,
9437 struct dentry *new_dentry)
9438{
0b246afa 9439 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
cdd1fedf
DF
9440 struct btrfs_trans_handle *trans;
9441 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9442 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9443 struct inode *new_inode = new_dentry->d_inode;
9444 struct inode *old_inode = old_dentry->d_inode;
c2050a45 9445 struct timespec ctime = current_time(old_inode);
cdd1fedf 9446 struct dentry *parent;
4a0cc7ca
NB
9447 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9448 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
cdd1fedf
DF
9449 u64 old_idx = 0;
9450 u64 new_idx = 0;
9451 u64 root_objectid;
9452 int ret;
86e8aa0e
FM
9453 bool root_log_pinned = false;
9454 bool dest_log_pinned = false;
cdd1fedf
DF
9455
9456 /* we only allow rename subvolume link between subvolumes */
9457 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9458 return -EXDEV;
9459
9460 /* close the race window with snapshot create/destroy ioctl */
9461 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9462 down_read(&fs_info->subvol_sem);
cdd1fedf 9463 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9464 down_read(&fs_info->subvol_sem);
cdd1fedf
DF
9465
9466 /*
9467 * We want to reserve the absolute worst case amount of items. So if
9468 * both inodes are subvols and we need to unlink them then that would
9469 * require 4 item modifications, but if they are both normal inodes it
9470 * would require 5 item modifications, so we'll assume their normal
9471 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9472 * should cover the worst case number of items we'll modify.
9473 */
9474 trans = btrfs_start_transaction(root, 12);
9475 if (IS_ERR(trans)) {
9476 ret = PTR_ERR(trans);
9477 goto out_notrans;
9478 }
9479
9480 /*
9481 * We need to find a free sequence number both in the source and
9482 * in the destination directory for the exchange.
9483 */
877574e2 9484 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
cdd1fedf
DF
9485 if (ret)
9486 goto out_fail;
877574e2 9487 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
cdd1fedf
DF
9488 if (ret)
9489 goto out_fail;
9490
9491 BTRFS_I(old_inode)->dir_index = 0ULL;
9492 BTRFS_I(new_inode)->dir_index = 0ULL;
9493
9494 /* Reference for the source. */
9495 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9496 /* force full log commit if subvolume involved. */
0b246afa 9497 btrfs_set_log_full_commit(fs_info, trans);
cdd1fedf 9498 } else {
376e5a57
FM
9499 btrfs_pin_log_trans(root);
9500 root_log_pinned = true;
cdd1fedf
DF
9501 ret = btrfs_insert_inode_ref(trans, dest,
9502 new_dentry->d_name.name,
9503 new_dentry->d_name.len,
9504 old_ino,
f85b7379
DS
9505 btrfs_ino(BTRFS_I(new_dir)),
9506 old_idx);
cdd1fedf
DF
9507 if (ret)
9508 goto out_fail;
cdd1fedf
DF
9509 }
9510
9511 /* And now for the dest. */
9512 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9513 /* force full log commit if subvolume involved. */
0b246afa 9514 btrfs_set_log_full_commit(fs_info, trans);
cdd1fedf 9515 } else {
376e5a57
FM
9516 btrfs_pin_log_trans(dest);
9517 dest_log_pinned = true;
cdd1fedf
DF
9518 ret = btrfs_insert_inode_ref(trans, root,
9519 old_dentry->d_name.name,
9520 old_dentry->d_name.len,
9521 new_ino,
f85b7379
DS
9522 btrfs_ino(BTRFS_I(old_dir)),
9523 new_idx);
cdd1fedf
DF
9524 if (ret)
9525 goto out_fail;
cdd1fedf
DF
9526 }
9527
9528 /* Update inode version and ctime/mtime. */
9529 inode_inc_iversion(old_dir);
9530 inode_inc_iversion(new_dir);
9531 inode_inc_iversion(old_inode);
9532 inode_inc_iversion(new_inode);
9533 old_dir->i_ctime = old_dir->i_mtime = ctime;
9534 new_dir->i_ctime = new_dir->i_mtime = ctime;
9535 old_inode->i_ctime = ctime;
9536 new_inode->i_ctime = ctime;
9537
9538 if (old_dentry->d_parent != new_dentry->d_parent) {
f85b7379
DS
9539 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9540 BTRFS_I(old_inode), 1);
9541 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9542 BTRFS_I(new_inode), 1);
cdd1fedf
DF
9543 }
9544
9545 /* src is a subvolume */
9546 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9547 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9548 ret = btrfs_unlink_subvol(trans, root, old_dir,
9549 root_objectid,
9550 old_dentry->d_name.name,
9551 old_dentry->d_name.len);
9552 } else { /* src is an inode */
4ec5934e
NB
9553 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9554 BTRFS_I(old_dentry->d_inode),
cdd1fedf
DF
9555 old_dentry->d_name.name,
9556 old_dentry->d_name.len);
9557 if (!ret)
9558 ret = btrfs_update_inode(trans, root, old_inode);
9559 }
9560 if (ret) {
66642832 9561 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9562 goto out_fail;
9563 }
9564
9565 /* dest is a subvolume */
9566 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9567 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9568 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9569 root_objectid,
9570 new_dentry->d_name.name,
9571 new_dentry->d_name.len);
9572 } else { /* dest is an inode */
4ec5934e
NB
9573 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9574 BTRFS_I(new_dentry->d_inode),
cdd1fedf
DF
9575 new_dentry->d_name.name,
9576 new_dentry->d_name.len);
9577 if (!ret)
9578 ret = btrfs_update_inode(trans, dest, new_inode);
9579 }
9580 if (ret) {
66642832 9581 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9582 goto out_fail;
9583 }
9584
db0a669f 9585 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
cdd1fedf
DF
9586 new_dentry->d_name.name,
9587 new_dentry->d_name.len, 0, old_idx);
9588 if (ret) {
66642832 9589 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9590 goto out_fail;
9591 }
9592
db0a669f 9593 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
cdd1fedf
DF
9594 old_dentry->d_name.name,
9595 old_dentry->d_name.len, 0, new_idx);
9596 if (ret) {
66642832 9597 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9598 goto out_fail;
9599 }
9600
9601 if (old_inode->i_nlink == 1)
9602 BTRFS_I(old_inode)->dir_index = old_idx;
9603 if (new_inode->i_nlink == 1)
9604 BTRFS_I(new_inode)->dir_index = new_idx;
9605
86e8aa0e 9606 if (root_log_pinned) {
cdd1fedf 9607 parent = new_dentry->d_parent;
f85b7379
DS
9608 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9609 parent);
cdd1fedf 9610 btrfs_end_log_trans(root);
86e8aa0e 9611 root_log_pinned = false;
cdd1fedf 9612 }
86e8aa0e 9613 if (dest_log_pinned) {
cdd1fedf 9614 parent = old_dentry->d_parent;
f85b7379
DS
9615 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9616 parent);
cdd1fedf 9617 btrfs_end_log_trans(dest);
86e8aa0e 9618 dest_log_pinned = false;
cdd1fedf
DF
9619 }
9620out_fail:
86e8aa0e
FM
9621 /*
9622 * If we have pinned a log and an error happened, we unpin tasks
9623 * trying to sync the log and force them to fallback to a transaction
9624 * commit if the log currently contains any of the inodes involved in
9625 * this rename operation (to ensure we do not persist a log with an
9626 * inconsistent state for any of these inodes or leading to any
9627 * inconsistencies when replayed). If the transaction was aborted, the
9628 * abortion reason is propagated to userspace when attempting to commit
9629 * the transaction. If the log does not contain any of these inodes, we
9630 * allow the tasks to sync it.
9631 */
9632 if (ret && (root_log_pinned || dest_log_pinned)) {
0f8939b8
NB
9633 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9634 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9635 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
86e8aa0e 9636 (new_inode &&
0f8939b8 9637 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
0b246afa 9638 btrfs_set_log_full_commit(fs_info, trans);
86e8aa0e
FM
9639
9640 if (root_log_pinned) {
9641 btrfs_end_log_trans(root);
9642 root_log_pinned = false;
9643 }
9644 if (dest_log_pinned) {
9645 btrfs_end_log_trans(dest);
9646 dest_log_pinned = false;
9647 }
9648 }
3a45bb20 9649 ret = btrfs_end_transaction(trans);
cdd1fedf
DF
9650out_notrans:
9651 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9652 up_read(&fs_info->subvol_sem);
cdd1fedf 9653 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9654 up_read(&fs_info->subvol_sem);
cdd1fedf
DF
9655
9656 return ret;
9657}
9658
9659static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9660 struct btrfs_root *root,
9661 struct inode *dir,
9662 struct dentry *dentry)
9663{
9664 int ret;
9665 struct inode *inode;
9666 u64 objectid;
9667 u64 index;
9668
9669 ret = btrfs_find_free_ino(root, &objectid);
9670 if (ret)
9671 return ret;
9672
9673 inode = btrfs_new_inode(trans, root, dir,
9674 dentry->d_name.name,
9675 dentry->d_name.len,
4a0cc7ca 9676 btrfs_ino(BTRFS_I(dir)),
cdd1fedf
DF
9677 objectid,
9678 S_IFCHR | WHITEOUT_MODE,
9679 &index);
9680
9681 if (IS_ERR(inode)) {
9682 ret = PTR_ERR(inode);
9683 return ret;
9684 }
9685
9686 inode->i_op = &btrfs_special_inode_operations;
9687 init_special_inode(inode, inode->i_mode,
9688 WHITEOUT_DEV);
9689
9690 ret = btrfs_init_inode_security(trans, inode, dir,
9691 &dentry->d_name);
9692 if (ret)
c9901618 9693 goto out;
cdd1fedf 9694
cef415af
NB
9695 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9696 BTRFS_I(inode), 0, index);
cdd1fedf 9697 if (ret)
c9901618 9698 goto out;
cdd1fedf
DF
9699
9700 ret = btrfs_update_inode(trans, root, inode);
c9901618 9701out:
cdd1fedf 9702 unlock_new_inode(inode);
c9901618
FM
9703 if (ret)
9704 inode_dec_link_count(inode);
cdd1fedf
DF
9705 iput(inode);
9706
c9901618 9707 return ret;
cdd1fedf
DF
9708}
9709
d397712b 9710static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
cdd1fedf
DF
9711 struct inode *new_dir, struct dentry *new_dentry,
9712 unsigned int flags)
39279cc3 9713{
0b246afa 9714 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
39279cc3 9715 struct btrfs_trans_handle *trans;
5062af35 9716 unsigned int trans_num_items;
39279cc3 9717 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 9718 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
2b0143b5
DH
9719 struct inode *new_inode = d_inode(new_dentry);
9720 struct inode *old_inode = d_inode(old_dentry);
00e4e6b3 9721 u64 index = 0;
4df27c4d 9722 u64 root_objectid;
39279cc3 9723 int ret;
4a0cc7ca 9724 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
3dc9e8f7 9725 bool log_pinned = false;
39279cc3 9726
4a0cc7ca 9727 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
f679a840
YZ
9728 return -EPERM;
9729
4df27c4d 9730 /* we only allow rename subvolume link between subvolumes */
33345d01 9731 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
9732 return -EXDEV;
9733
33345d01 9734 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
4a0cc7ca 9735 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 9736 return -ENOTEMPTY;
5f39d397 9737
4df27c4d
YZ
9738 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9739 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9740 return -ENOTEMPTY;
9c52057c
CM
9741
9742
9743 /* check for collisions, even if the name isn't there */
4871c158 9744 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9c52057c
CM
9745 new_dentry->d_name.name,
9746 new_dentry->d_name.len);
9747
9748 if (ret) {
9749 if (ret == -EEXIST) {
9750 /* we shouldn't get
9751 * eexist without a new_inode */
fae7f21c 9752 if (WARN_ON(!new_inode)) {
9c52057c
CM
9753 return ret;
9754 }
9755 } else {
9756 /* maybe -EOVERFLOW */
9757 return ret;
9758 }
9759 }
9760 ret = 0;
9761
5a3f23d5 9762 /*
8d875f95
CM
9763 * we're using rename to replace one file with another. Start IO on it
9764 * now so we don't add too much work to the end of the transaction
5a3f23d5 9765 */
8d875f95 9766 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
5a3f23d5
CM
9767 filemap_flush(old_inode->i_mapping);
9768
76dda93c 9769 /* close the racy window with snapshot create/destroy ioctl */
33345d01 9770 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9771 down_read(&fs_info->subvol_sem);
a22285a6
YZ
9772 /*
9773 * We want to reserve the absolute worst case amount of items. So if
9774 * both inodes are subvols and we need to unlink them then that would
9775 * require 4 item modifications, but if they are both normal inodes it
cdd1fedf 9776 * would require 5 item modifications, so we'll assume they are normal
a22285a6
YZ
9777 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9778 * should cover the worst case number of items we'll modify.
5062af35
FM
9779 * If our rename has the whiteout flag, we need more 5 units for the
9780 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9781 * when selinux is enabled).
a22285a6 9782 */
5062af35
FM
9783 trans_num_items = 11;
9784 if (flags & RENAME_WHITEOUT)
9785 trans_num_items += 5;
9786 trans = btrfs_start_transaction(root, trans_num_items);
b44c59a8 9787 if (IS_ERR(trans)) {
cdd1fedf
DF
9788 ret = PTR_ERR(trans);
9789 goto out_notrans;
9790 }
76dda93c 9791
4df27c4d
YZ
9792 if (dest != root)
9793 btrfs_record_root_in_trans(trans, dest);
5f39d397 9794
877574e2 9795 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
a5719521
YZ
9796 if (ret)
9797 goto out_fail;
5a3f23d5 9798
67de1176 9799 BTRFS_I(old_inode)->dir_index = 0ULL;
33345d01 9800 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d 9801 /* force full log commit if subvolume involved. */
0b246afa 9802 btrfs_set_log_full_commit(fs_info, trans);
4df27c4d 9803 } else {
c4aba954
FM
9804 btrfs_pin_log_trans(root);
9805 log_pinned = true;
a5719521
YZ
9806 ret = btrfs_insert_inode_ref(trans, dest,
9807 new_dentry->d_name.name,
9808 new_dentry->d_name.len,
33345d01 9809 old_ino,
4a0cc7ca 9810 btrfs_ino(BTRFS_I(new_dir)), index);
a5719521
YZ
9811 if (ret)
9812 goto out_fail;
4df27c4d 9813 }
5a3f23d5 9814
0c4d2d95
JB
9815 inode_inc_iversion(old_dir);
9816 inode_inc_iversion(new_dir);
9817 inode_inc_iversion(old_inode);
04b285f3
DD
9818 old_dir->i_ctime = old_dir->i_mtime =
9819 new_dir->i_ctime = new_dir->i_mtime =
c2050a45 9820 old_inode->i_ctime = current_time(old_dir);
5f39d397 9821
12fcfd22 9822 if (old_dentry->d_parent != new_dentry->d_parent)
f85b7379
DS
9823 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9824 BTRFS_I(old_inode), 1);
12fcfd22 9825
33345d01 9826 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
9827 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9828 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9829 old_dentry->d_name.name,
9830 old_dentry->d_name.len);
9831 } else {
4ec5934e
NB
9832 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9833 BTRFS_I(d_inode(old_dentry)),
92986796
AV
9834 old_dentry->d_name.name,
9835 old_dentry->d_name.len);
9836 if (!ret)
9837 ret = btrfs_update_inode(trans, root, old_inode);
4df27c4d 9838 }
79787eaa 9839 if (ret) {
66642832 9840 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9841 goto out_fail;
9842 }
39279cc3
CM
9843
9844 if (new_inode) {
0c4d2d95 9845 inode_inc_iversion(new_inode);
c2050a45 9846 new_inode->i_ctime = current_time(new_inode);
4a0cc7ca 9847 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
4df27c4d
YZ
9848 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9849 root_objectid = BTRFS_I(new_inode)->location.objectid;
9850 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9851 root_objectid,
9852 new_dentry->d_name.name,
9853 new_dentry->d_name.len);
9854 BUG_ON(new_inode->i_nlink == 0);
9855 } else {
4ec5934e
NB
9856 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9857 BTRFS_I(d_inode(new_dentry)),
4df27c4d
YZ
9858 new_dentry->d_name.name,
9859 new_dentry->d_name.len);
9860 }
4ef31a45 9861 if (!ret && new_inode->i_nlink == 0)
73f2e545
NB
9862 ret = btrfs_orphan_add(trans,
9863 BTRFS_I(d_inode(new_dentry)));
79787eaa 9864 if (ret) {
66642832 9865 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9866 goto out_fail;
9867 }
39279cc3 9868 }
aec7477b 9869
db0a669f 9870 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
4df27c4d 9871 new_dentry->d_name.name,
a5719521 9872 new_dentry->d_name.len, 0, index);
79787eaa 9873 if (ret) {
66642832 9874 btrfs_abort_transaction(trans, ret);
79787eaa
JM
9875 goto out_fail;
9876 }
39279cc3 9877
67de1176
MX
9878 if (old_inode->i_nlink == 1)
9879 BTRFS_I(old_inode)->dir_index = index;
9880
3dc9e8f7 9881 if (log_pinned) {
10d9f309 9882 struct dentry *parent = new_dentry->d_parent;
3dc9e8f7 9883
f85b7379
DS
9884 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9885 parent);
4df27c4d 9886 btrfs_end_log_trans(root);
3dc9e8f7 9887 log_pinned = false;
4df27c4d 9888 }
cdd1fedf
DF
9889
9890 if (flags & RENAME_WHITEOUT) {
9891 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9892 old_dentry);
9893
9894 if (ret) {
66642832 9895 btrfs_abort_transaction(trans, ret);
cdd1fedf
DF
9896 goto out_fail;
9897 }
4df27c4d 9898 }
39279cc3 9899out_fail:
3dc9e8f7
FM
9900 /*
9901 * If we have pinned the log and an error happened, we unpin tasks
9902 * trying to sync the log and force them to fallback to a transaction
9903 * commit if the log currently contains any of the inodes involved in
9904 * this rename operation (to ensure we do not persist a log with an
9905 * inconsistent state for any of these inodes or leading to any
9906 * inconsistencies when replayed). If the transaction was aborted, the
9907 * abortion reason is propagated to userspace when attempting to commit
9908 * the transaction. If the log does not contain any of these inodes, we
9909 * allow the tasks to sync it.
9910 */
9911 if (ret && log_pinned) {
0f8939b8
NB
9912 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9913 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9914 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
3dc9e8f7 9915 (new_inode &&
0f8939b8 9916 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
0b246afa 9917 btrfs_set_log_full_commit(fs_info, trans);
3dc9e8f7
FM
9918
9919 btrfs_end_log_trans(root);
9920 log_pinned = false;
9921 }
3a45bb20 9922 btrfs_end_transaction(trans);
b44c59a8 9923out_notrans:
33345d01 9924 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
0b246afa 9925 up_read(&fs_info->subvol_sem);
9ed74f2d 9926
39279cc3
CM
9927 return ret;
9928}
9929
80ace85c
MS
9930static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9931 struct inode *new_dir, struct dentry *new_dentry,
9932 unsigned int flags)
9933{
cdd1fedf 9934 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
80ace85c
MS
9935 return -EINVAL;
9936
cdd1fedf
DF
9937 if (flags & RENAME_EXCHANGE)
9938 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9939 new_dentry);
9940
9941 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
80ace85c
MS
9942}
9943
8ccf6f19
MX
9944static void btrfs_run_delalloc_work(struct btrfs_work *work)
9945{
9946 struct btrfs_delalloc_work *delalloc_work;
9f23e289 9947 struct inode *inode;
8ccf6f19
MX
9948
9949 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9950 work);
9f23e289 9951 inode = delalloc_work->inode;
30424601
DS
9952 filemap_flush(inode->i_mapping);
9953 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9954 &BTRFS_I(inode)->runtime_flags))
9f23e289 9955 filemap_flush(inode->i_mapping);
8ccf6f19
MX
9956
9957 if (delalloc_work->delay_iput)
9f23e289 9958 btrfs_add_delayed_iput(inode);
8ccf6f19 9959 else
9f23e289 9960 iput(inode);
8ccf6f19
MX
9961 complete(&delalloc_work->completion);
9962}
9963
9964struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
651d494a 9965 int delay_iput)
8ccf6f19
MX
9966{
9967 struct btrfs_delalloc_work *work;
9968
100d5702 9969 work = kmalloc(sizeof(*work), GFP_NOFS);
8ccf6f19
MX
9970 if (!work)
9971 return NULL;
9972
9973 init_completion(&work->completion);
9974 INIT_LIST_HEAD(&work->list);
9975 work->inode = inode;
8ccf6f19 9976 work->delay_iput = delay_iput;
9e0af237
LB
9977 WARN_ON_ONCE(!inode);
9978 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9979 btrfs_run_delalloc_work, NULL, NULL);
8ccf6f19
MX
9980
9981 return work;
9982}
9983
9984void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9985{
9986 wait_for_completion(&work->completion);
100d5702 9987 kfree(work);
8ccf6f19
MX
9988}
9989
d352ac68
CM
9990/*
9991 * some fairly slow code that needs optimization. This walks the list
9992 * of all the inodes with pending delalloc and forces them to disk.
9993 */
6c255e67
MX
9994static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9995 int nr)
ea8c2819 9996{
ea8c2819 9997 struct btrfs_inode *binode;
5b21f2ed 9998 struct inode *inode;
8ccf6f19
MX
9999 struct btrfs_delalloc_work *work, *next;
10000 struct list_head works;
1eafa6c7 10001 struct list_head splice;
8ccf6f19 10002 int ret = 0;
ea8c2819 10003
8ccf6f19 10004 INIT_LIST_HEAD(&works);
1eafa6c7 10005 INIT_LIST_HEAD(&splice);
63607cc8 10006
573bfb72 10007 mutex_lock(&root->delalloc_mutex);
eb73c1b7
MX
10008 spin_lock(&root->delalloc_lock);
10009 list_splice_init(&root->delalloc_inodes, &splice);
1eafa6c7
MX
10010 while (!list_empty(&splice)) {
10011 binode = list_entry(splice.next, struct btrfs_inode,
ea8c2819 10012 delalloc_inodes);
1eafa6c7 10013
eb73c1b7
MX
10014 list_move_tail(&binode->delalloc_inodes,
10015 &root->delalloc_inodes);
5b21f2ed 10016 inode = igrab(&binode->vfs_inode);
df0af1a5 10017 if (!inode) {
eb73c1b7 10018 cond_resched_lock(&root->delalloc_lock);
1eafa6c7 10019 continue;
df0af1a5 10020 }
eb73c1b7 10021 spin_unlock(&root->delalloc_lock);
1eafa6c7 10022
651d494a 10023 work = btrfs_alloc_delalloc_work(inode, delay_iput);
5d99a998 10024 if (!work) {
f4ab9ea7
JB
10025 if (delay_iput)
10026 btrfs_add_delayed_iput(inode);
10027 else
10028 iput(inode);
1eafa6c7 10029 ret = -ENOMEM;
a1ecaabb 10030 goto out;
5b21f2ed 10031 }
1eafa6c7 10032 list_add_tail(&work->list, &works);
a44903ab
QW
10033 btrfs_queue_work(root->fs_info->flush_workers,
10034 &work->work);
6c255e67
MX
10035 ret++;
10036 if (nr != -1 && ret >= nr)
a1ecaabb 10037 goto out;
5b21f2ed 10038 cond_resched();
eb73c1b7 10039 spin_lock(&root->delalloc_lock);
ea8c2819 10040 }
eb73c1b7 10041 spin_unlock(&root->delalloc_lock);
8c8bee1d 10042
a1ecaabb 10043out:
eb73c1b7
MX
10044 list_for_each_entry_safe(work, next, &works, list) {
10045 list_del_init(&work->list);
10046 btrfs_wait_and_free_delalloc_work(work);
10047 }
10048
10049 if (!list_empty_careful(&splice)) {
10050 spin_lock(&root->delalloc_lock);
10051 list_splice_tail(&splice, &root->delalloc_inodes);
10052 spin_unlock(&root->delalloc_lock);
10053 }
573bfb72 10054 mutex_unlock(&root->delalloc_mutex);
eb73c1b7
MX
10055 return ret;
10056}
1eafa6c7 10057
eb73c1b7
MX
10058int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
10059{
0b246afa 10060 struct btrfs_fs_info *fs_info = root->fs_info;
eb73c1b7 10061 int ret;
1eafa6c7 10062
0b246afa 10063 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
10064 return -EROFS;
10065
6c255e67
MX
10066 ret = __start_delalloc_inodes(root, delay_iput, -1);
10067 if (ret > 0)
10068 ret = 0;
eb73c1b7
MX
10069 /*
10070 * the filemap_flush will queue IO into the worker threads, but
8c8bee1d
CM
10071 * we have to make sure the IO is actually started and that
10072 * ordered extents get created before we return
10073 */
0b246afa
JM
10074 atomic_inc(&fs_info->async_submit_draining);
10075 while (atomic_read(&fs_info->nr_async_submits) ||
10076 atomic_read(&fs_info->async_delalloc_pages)) {
10077 wait_event(fs_info->async_submit_wait,
10078 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10079 atomic_read(&fs_info->async_delalloc_pages) == 0));
10080 }
10081 atomic_dec(&fs_info->async_submit_draining);
eb73c1b7
MX
10082 return ret;
10083}
10084
6c255e67
MX
10085int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
10086 int nr)
eb73c1b7
MX
10087{
10088 struct btrfs_root *root;
10089 struct list_head splice;
10090 int ret;
10091
2c21b4d7 10092 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
eb73c1b7
MX
10093 return -EROFS;
10094
10095 INIT_LIST_HEAD(&splice);
10096
573bfb72 10097 mutex_lock(&fs_info->delalloc_root_mutex);
eb73c1b7
MX
10098 spin_lock(&fs_info->delalloc_root_lock);
10099 list_splice_init(&fs_info->delalloc_roots, &splice);
6c255e67 10100 while (!list_empty(&splice) && nr) {
eb73c1b7
MX
10101 root = list_first_entry(&splice, struct btrfs_root,
10102 delalloc_root);
10103 root = btrfs_grab_fs_root(root);
10104 BUG_ON(!root);
10105 list_move_tail(&root->delalloc_root,
10106 &fs_info->delalloc_roots);
10107 spin_unlock(&fs_info->delalloc_root_lock);
10108
6c255e67 10109 ret = __start_delalloc_inodes(root, delay_iput, nr);
eb73c1b7 10110 btrfs_put_fs_root(root);
6c255e67 10111 if (ret < 0)
eb73c1b7
MX
10112 goto out;
10113
6c255e67
MX
10114 if (nr != -1) {
10115 nr -= ret;
10116 WARN_ON(nr < 0);
10117 }
eb73c1b7 10118 spin_lock(&fs_info->delalloc_root_lock);
8ccf6f19 10119 }
eb73c1b7 10120 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 10121
6c255e67 10122 ret = 0;
eb73c1b7
MX
10123 atomic_inc(&fs_info->async_submit_draining);
10124 while (atomic_read(&fs_info->nr_async_submits) ||
10125 atomic_read(&fs_info->async_delalloc_pages)) {
10126 wait_event(fs_info->async_submit_wait,
10127 (atomic_read(&fs_info->nr_async_submits) == 0 &&
10128 atomic_read(&fs_info->async_delalloc_pages) == 0));
10129 }
10130 atomic_dec(&fs_info->async_submit_draining);
eb73c1b7 10131out:
1eafa6c7 10132 if (!list_empty_careful(&splice)) {
eb73c1b7
MX
10133 spin_lock(&fs_info->delalloc_root_lock);
10134 list_splice_tail(&splice, &fs_info->delalloc_roots);
10135 spin_unlock(&fs_info->delalloc_root_lock);
1eafa6c7 10136 }
573bfb72 10137 mutex_unlock(&fs_info->delalloc_root_mutex);
8ccf6f19 10138 return ret;
ea8c2819
CM
10139}
10140
39279cc3
CM
10141static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10142 const char *symname)
10143{
0b246afa 10144 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
39279cc3
CM
10145 struct btrfs_trans_handle *trans;
10146 struct btrfs_root *root = BTRFS_I(dir)->root;
10147 struct btrfs_path *path;
10148 struct btrfs_key key;
1832a6d5 10149 struct inode *inode = NULL;
39279cc3
CM
10150 int err;
10151 int drop_inode = 0;
10152 u64 objectid;
67871254 10153 u64 index = 0;
39279cc3
CM
10154 int name_len;
10155 int datasize;
5f39d397 10156 unsigned long ptr;
39279cc3 10157 struct btrfs_file_extent_item *ei;
5f39d397 10158 struct extent_buffer *leaf;
39279cc3 10159
f06becc4 10160 name_len = strlen(symname);
0b246afa 10161 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
39279cc3 10162 return -ENAMETOOLONG;
1832a6d5 10163
9ed74f2d
JB
10164 /*
10165 * 2 items for inode item and ref
10166 * 2 items for dir items
9269d12b
FM
10167 * 1 item for updating parent inode item
10168 * 1 item for the inline extent item
9ed74f2d
JB
10169 * 1 item for xattr if selinux is on
10170 */
9269d12b 10171 trans = btrfs_start_transaction(root, 7);
a22285a6
YZ
10172 if (IS_ERR(trans))
10173 return PTR_ERR(trans);
1832a6d5 10174
581bb050
LZ
10175 err = btrfs_find_free_ino(root, &objectid);
10176 if (err)
10177 goto out_unlock;
10178
aec7477b 10179 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
f85b7379
DS
10180 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10181 objectid, S_IFLNK|S_IRWXUGO, &index);
7cf96da3
TI
10182 if (IS_ERR(inode)) {
10183 err = PTR_ERR(inode);
39279cc3 10184 goto out_unlock;
7cf96da3 10185 }
39279cc3 10186
ad19db71
CS
10187 /*
10188 * If the active LSM wants to access the inode during
10189 * d_instantiate it needs these. Smack checks to see
10190 * if the filesystem supports xattrs by looking at the
10191 * ops vector.
10192 */
10193 inode->i_fop = &btrfs_file_operations;
10194 inode->i_op = &btrfs_file_inode_operations;
b0d5d10f 10195 inode->i_mapping->a_ops = &btrfs_aops;
b0d5d10f
CM
10196 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10197
10198 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10199 if (err)
10200 goto out_unlock_inode;
ad19db71 10201
39279cc3 10202 path = btrfs_alloc_path();
d8926bb3
MF
10203 if (!path) {
10204 err = -ENOMEM;
b0d5d10f 10205 goto out_unlock_inode;
d8926bb3 10206 }
4a0cc7ca 10207 key.objectid = btrfs_ino(BTRFS_I(inode));
39279cc3 10208 key.offset = 0;
962a298f 10209 key.type = BTRFS_EXTENT_DATA_KEY;
39279cc3
CM
10210 datasize = btrfs_file_extent_calc_inline_size(name_len);
10211 err = btrfs_insert_empty_item(trans, root, path, &key,
10212 datasize);
54aa1f4d 10213 if (err) {
b0839166 10214 btrfs_free_path(path);
b0d5d10f 10215 goto out_unlock_inode;
54aa1f4d 10216 }
5f39d397
CM
10217 leaf = path->nodes[0];
10218 ei = btrfs_item_ptr(leaf, path->slots[0],
10219 struct btrfs_file_extent_item);
10220 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10221 btrfs_set_file_extent_type(leaf, ei,
39279cc3 10222 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
10223 btrfs_set_file_extent_encryption(leaf, ei, 0);
10224 btrfs_set_file_extent_compression(leaf, ei, 0);
10225 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10226 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10227
39279cc3 10228 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
10229 write_extent_buffer(leaf, symname, ptr, name_len);
10230 btrfs_mark_buffer_dirty(leaf);
39279cc3 10231 btrfs_free_path(path);
5f39d397 10232
39279cc3 10233 inode->i_op = &btrfs_symlink_inode_operations;
21fc61c7 10234 inode_nohighmem(inode);
39279cc3 10235 inode->i_mapping->a_ops = &btrfs_symlink_aops;
d899e052 10236 inode_set_bytes(inode, name_len);
6ef06d27 10237 btrfs_i_size_write(BTRFS_I(inode), name_len);
54aa1f4d 10238 err = btrfs_update_inode(trans, root, inode);
d50866d0
FM
10239 /*
10240 * Last step, add directory indexes for our symlink inode. This is the
10241 * last step to avoid extra cleanup of these indexes if an error happens
10242 * elsewhere above.
10243 */
10244 if (!err)
cef415af
NB
10245 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10246 BTRFS_I(inode), 0, index);
b0d5d10f 10247 if (err) {
54aa1f4d 10248 drop_inode = 1;
b0d5d10f
CM
10249 goto out_unlock_inode;
10250 }
10251
10252 unlock_new_inode(inode);
10253 d_instantiate(dentry, inode);
39279cc3
CM
10254
10255out_unlock:
3a45bb20 10256 btrfs_end_transaction(trans);
39279cc3
CM
10257 if (drop_inode) {
10258 inode_dec_link_count(inode);
10259 iput(inode);
10260 }
2ff7e61e 10261 btrfs_btree_balance_dirty(fs_info);
39279cc3 10262 return err;
b0d5d10f
CM
10263
10264out_unlock_inode:
10265 drop_inode = 1;
10266 unlock_new_inode(inode);
10267 goto out_unlock;
39279cc3 10268}
16432985 10269
0af3d00b
JB
10270static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10271 u64 start, u64 num_bytes, u64 min_size,
10272 loff_t actual_len, u64 *alloc_hint,
10273 struct btrfs_trans_handle *trans)
d899e052 10274{
0b246afa 10275 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5dc562c5
JB
10276 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10277 struct extent_map *em;
d899e052
YZ
10278 struct btrfs_root *root = BTRFS_I(inode)->root;
10279 struct btrfs_key ins;
d899e052 10280 u64 cur_offset = start;
55a61d1d 10281 u64 i_size;
154ea289 10282 u64 cur_bytes;
0b670dc4 10283 u64 last_alloc = (u64)-1;
d899e052 10284 int ret = 0;
0af3d00b 10285 bool own_trans = true;
18513091 10286 u64 end = start + num_bytes - 1;
d899e052 10287
0af3d00b
JB
10288 if (trans)
10289 own_trans = false;
d899e052 10290 while (num_bytes > 0) {
0af3d00b
JB
10291 if (own_trans) {
10292 trans = btrfs_start_transaction(root, 3);
10293 if (IS_ERR(trans)) {
10294 ret = PTR_ERR(trans);
10295 break;
10296 }
5a303d5d
YZ
10297 }
10298
ee22184b 10299 cur_bytes = min_t(u64, num_bytes, SZ_256M);
154ea289 10300 cur_bytes = max(cur_bytes, min_size);
0b670dc4
JB
10301 /*
10302 * If we are severely fragmented we could end up with really
10303 * small allocations, so if the allocator is returning small
10304 * chunks lets make its job easier by only searching for those
10305 * sized chunks.
10306 */
10307 cur_bytes = min(cur_bytes, last_alloc);
18513091
WX
10308 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10309 min_size, 0, *alloc_hint, &ins, 1, 0);
5a303d5d 10310 if (ret) {
0af3d00b 10311 if (own_trans)
3a45bb20 10312 btrfs_end_transaction(trans);
a22285a6 10313 break;
d899e052 10314 }
0b246afa 10315 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
5a303d5d 10316
0b670dc4 10317 last_alloc = ins.offset;
d899e052
YZ
10318 ret = insert_reserved_file_extent(trans, inode,
10319 cur_offset, ins.objectid,
10320 ins.offset, ins.offset,
920bbbfb 10321 ins.offset, 0, 0, 0,
d899e052 10322 BTRFS_FILE_EXTENT_PREALLOC);
79787eaa 10323 if (ret) {
2ff7e61e 10324 btrfs_free_reserved_extent(fs_info, ins.objectid,
e570fd27 10325 ins.offset, 0);
66642832 10326 btrfs_abort_transaction(trans, ret);
79787eaa 10327 if (own_trans)
3a45bb20 10328 btrfs_end_transaction(trans);
79787eaa
JM
10329 break;
10330 }
31193213 10331
dcdbc059 10332 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
a1ed835e 10333 cur_offset + ins.offset -1, 0);
5a303d5d 10334
5dc562c5
JB
10335 em = alloc_extent_map();
10336 if (!em) {
10337 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10338 &BTRFS_I(inode)->runtime_flags);
10339 goto next;
10340 }
10341
10342 em->start = cur_offset;
10343 em->orig_start = cur_offset;
10344 em->len = ins.offset;
10345 em->block_start = ins.objectid;
10346 em->block_len = ins.offset;
b4939680 10347 em->orig_block_len = ins.offset;
cc95bef6 10348 em->ram_bytes = ins.offset;
0b246afa 10349 em->bdev = fs_info->fs_devices->latest_bdev;
5dc562c5
JB
10350 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10351 em->generation = trans->transid;
10352
10353 while (1) {
10354 write_lock(&em_tree->lock);
09a2a8f9 10355 ret = add_extent_mapping(em_tree, em, 1);
5dc562c5
JB
10356 write_unlock(&em_tree->lock);
10357 if (ret != -EEXIST)
10358 break;
dcdbc059 10359 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5dc562c5
JB
10360 cur_offset + ins.offset - 1,
10361 0);
10362 }
10363 free_extent_map(em);
10364next:
d899e052
YZ
10365 num_bytes -= ins.offset;
10366 cur_offset += ins.offset;
efa56464 10367 *alloc_hint = ins.objectid + ins.offset;
5a303d5d 10368
0c4d2d95 10369 inode_inc_iversion(inode);
c2050a45 10370 inode->i_ctime = current_time(inode);
6cbff00f 10371 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 10372 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
efa56464
YZ
10373 (actual_len > inode->i_size) &&
10374 (cur_offset > inode->i_size)) {
d1ea6a61 10375 if (cur_offset > actual_len)
55a61d1d 10376 i_size = actual_len;
d1ea6a61 10377 else
55a61d1d
JB
10378 i_size = cur_offset;
10379 i_size_write(inode, i_size);
10380 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
10381 }
10382
d899e052 10383 ret = btrfs_update_inode(trans, root, inode);
79787eaa
JM
10384
10385 if (ret) {
66642832 10386 btrfs_abort_transaction(trans, ret);
79787eaa 10387 if (own_trans)
3a45bb20 10388 btrfs_end_transaction(trans);
79787eaa
JM
10389 break;
10390 }
d899e052 10391
0af3d00b 10392 if (own_trans)
3a45bb20 10393 btrfs_end_transaction(trans);
5a303d5d 10394 }
18513091
WX
10395 if (cur_offset < end)
10396 btrfs_free_reserved_data_space(inode, cur_offset,
10397 end - cur_offset + 1);
d899e052
YZ
10398 return ret;
10399}
10400
0af3d00b
JB
10401int btrfs_prealloc_file_range(struct inode *inode, int mode,
10402 u64 start, u64 num_bytes, u64 min_size,
10403 loff_t actual_len, u64 *alloc_hint)
10404{
10405 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10406 min_size, actual_len, alloc_hint,
10407 NULL);
10408}
10409
10410int btrfs_prealloc_file_range_trans(struct inode *inode,
10411 struct btrfs_trans_handle *trans, int mode,
10412 u64 start, u64 num_bytes, u64 min_size,
10413 loff_t actual_len, u64 *alloc_hint)
10414{
10415 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10416 min_size, actual_len, alloc_hint, trans);
10417}
10418
e6dcd2dc
CM
10419static int btrfs_set_page_dirty(struct page *page)
10420{
e6dcd2dc
CM
10421 return __set_page_dirty_nobuffers(page);
10422}
10423
10556cb2 10424static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 10425{
b83cc969 10426 struct btrfs_root *root = BTRFS_I(inode)->root;
cb6db4e5 10427 umode_t mode = inode->i_mode;
b83cc969 10428
cb6db4e5
JM
10429 if (mask & MAY_WRITE &&
10430 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10431 if (btrfs_root_readonly(root))
10432 return -EROFS;
10433 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10434 return -EACCES;
10435 }
2830ba7f 10436 return generic_permission(inode, mask);
fdebe2bd 10437}
39279cc3 10438
ef3b9af5
FM
10439static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10440{
2ff7e61e 10441 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
ef3b9af5
FM
10442 struct btrfs_trans_handle *trans;
10443 struct btrfs_root *root = BTRFS_I(dir)->root;
10444 struct inode *inode = NULL;
10445 u64 objectid;
10446 u64 index;
10447 int ret = 0;
10448
10449 /*
10450 * 5 units required for adding orphan entry
10451 */
10452 trans = btrfs_start_transaction(root, 5);
10453 if (IS_ERR(trans))
10454 return PTR_ERR(trans);
10455
10456 ret = btrfs_find_free_ino(root, &objectid);
10457 if (ret)
10458 goto out;
10459
10460 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
f85b7379 10461 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
ef3b9af5
FM
10462 if (IS_ERR(inode)) {
10463 ret = PTR_ERR(inode);
10464 inode = NULL;
10465 goto out;
10466 }
10467
ef3b9af5
FM
10468 inode->i_fop = &btrfs_file_operations;
10469 inode->i_op = &btrfs_file_inode_operations;
10470
10471 inode->i_mapping->a_ops = &btrfs_aops;
ef3b9af5
FM
10472 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10473
b0d5d10f
CM
10474 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10475 if (ret)
10476 goto out_inode;
10477
10478 ret = btrfs_update_inode(trans, root, inode);
10479 if (ret)
10480 goto out_inode;
73f2e545 10481 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
ef3b9af5 10482 if (ret)
b0d5d10f 10483 goto out_inode;
ef3b9af5 10484
5762b5c9
FM
10485 /*
10486 * We set number of links to 0 in btrfs_new_inode(), and here we set
10487 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10488 * through:
10489 *
10490 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10491 */
10492 set_nlink(inode, 1);
b0d5d10f 10493 unlock_new_inode(inode);
ef3b9af5
FM
10494 d_tmpfile(dentry, inode);
10495 mark_inode_dirty(inode);
10496
10497out:
3a45bb20 10498 btrfs_end_transaction(trans);
ef3b9af5
FM
10499 if (ret)
10500 iput(inode);
2ff7e61e
JM
10501 btrfs_balance_delayed_items(fs_info);
10502 btrfs_btree_balance_dirty(fs_info);
ef3b9af5 10503 return ret;
b0d5d10f
CM
10504
10505out_inode:
10506 unlock_new_inode(inode);
10507 goto out;
10508
ef3b9af5
FM
10509}
10510
20a7db8a
DS
10511__attribute__((const))
10512static int dummy_readpage_io_failed_hook(struct page *page, int failed_mirror)
10513{
10514 return 0;
10515}
10516
6e1d5dcc 10517static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 10518 .getattr = btrfs_getattr,
39279cc3
CM
10519 .lookup = btrfs_lookup,
10520 .create = btrfs_create,
10521 .unlink = btrfs_unlink,
10522 .link = btrfs_link,
10523 .mkdir = btrfs_mkdir,
10524 .rmdir = btrfs_rmdir,
2773bf00 10525 .rename = btrfs_rename2,
39279cc3
CM
10526 .symlink = btrfs_symlink,
10527 .setattr = btrfs_setattr,
618e21d5 10528 .mknod = btrfs_mknod,
5103e947 10529 .listxattr = btrfs_listxattr,
fdebe2bd 10530 .permission = btrfs_permission,
4e34e719 10531 .get_acl = btrfs_get_acl,
996a710d 10532 .set_acl = btrfs_set_acl,
93fd63c2 10533 .update_time = btrfs_update_time,
ef3b9af5 10534 .tmpfile = btrfs_tmpfile,
39279cc3 10535};
6e1d5dcc 10536static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 10537 .lookup = btrfs_lookup,
fdebe2bd 10538 .permission = btrfs_permission,
93fd63c2 10539 .update_time = btrfs_update_time,
39279cc3 10540};
76dda93c 10541
828c0950 10542static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
10543 .llseek = generic_file_llseek,
10544 .read = generic_read_dir,
02dbfc99 10545 .iterate_shared = btrfs_real_readdir,
34287aa3 10546 .unlocked_ioctl = btrfs_ioctl,
39279cc3 10547#ifdef CONFIG_COMPAT
4c63c245 10548 .compat_ioctl = btrfs_compat_ioctl,
39279cc3 10549#endif
6bf13c0c 10550 .release = btrfs_release_file,
e02119d5 10551 .fsync = btrfs_sync_file,
39279cc3
CM
10552};
10553
20e5506b 10554static const struct extent_io_ops btrfs_extent_io_ops = {
4d53dddb 10555 /* mandatory callbacks */
065631f6 10556 .submit_bio_hook = btrfs_submit_bio_hook,
07157aac 10557 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
4d53dddb 10558 .merge_bio_hook = btrfs_merge_bio_hook,
20a7db8a 10559 .readpage_io_failed_hook = dummy_readpage_io_failed_hook,
4d53dddb
DS
10560
10561 /* optional callbacks */
10562 .fill_delalloc = run_delalloc_range,
e6dcd2dc 10563 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
247e743c 10564 .writepage_start_hook = btrfs_writepage_start_hook,
b0c68f8b
CM
10565 .set_bit_hook = btrfs_set_bit_hook,
10566 .clear_bit_hook = btrfs_clear_bit_hook,
9ed74f2d
JB
10567 .merge_extent_hook = btrfs_merge_extent_hook,
10568 .split_extent_hook = btrfs_split_extent_hook,
07157aac
CM
10569};
10570
35054394
CM
10571/*
10572 * btrfs doesn't support the bmap operation because swapfiles
10573 * use bmap to make a mapping of extents in the file. They assume
10574 * these extents won't change over the life of the file and they
10575 * use the bmap result to do IO directly to the drive.
10576 *
10577 * the btrfs bmap call would return logical addresses that aren't
10578 * suitable for IO and they also will change frequently as COW
10579 * operations happen. So, swapfile + btrfs == corruption.
10580 *
10581 * For now we're avoiding this by dropping bmap.
10582 */
7f09410b 10583static const struct address_space_operations btrfs_aops = {
39279cc3
CM
10584 .readpage = btrfs_readpage,
10585 .writepage = btrfs_writepage,
b293f02e 10586 .writepages = btrfs_writepages,
3ab2fb5a 10587 .readpages = btrfs_readpages,
16432985 10588 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
10589 .invalidatepage = btrfs_invalidatepage,
10590 .releasepage = btrfs_releasepage,
e6dcd2dc 10591 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 10592 .error_remove_page = generic_error_remove_page,
39279cc3
CM
10593};
10594
7f09410b 10595static const struct address_space_operations btrfs_symlink_aops = {
39279cc3
CM
10596 .readpage = btrfs_readpage,
10597 .writepage = btrfs_writepage,
2bf5a725
CM
10598 .invalidatepage = btrfs_invalidatepage,
10599 .releasepage = btrfs_releasepage,
39279cc3
CM
10600};
10601
6e1d5dcc 10602static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
10603 .getattr = btrfs_getattr,
10604 .setattr = btrfs_setattr,
5103e947 10605 .listxattr = btrfs_listxattr,
fdebe2bd 10606 .permission = btrfs_permission,
1506fcc8 10607 .fiemap = btrfs_fiemap,
4e34e719 10608 .get_acl = btrfs_get_acl,
996a710d 10609 .set_acl = btrfs_set_acl,
e41f941a 10610 .update_time = btrfs_update_time,
39279cc3 10611};
6e1d5dcc 10612static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
10613 .getattr = btrfs_getattr,
10614 .setattr = btrfs_setattr,
fdebe2bd 10615 .permission = btrfs_permission,
33268eaf 10616 .listxattr = btrfs_listxattr,
4e34e719 10617 .get_acl = btrfs_get_acl,
996a710d 10618 .set_acl = btrfs_set_acl,
e41f941a 10619 .update_time = btrfs_update_time,
618e21d5 10620};
6e1d5dcc 10621static const struct inode_operations btrfs_symlink_inode_operations = {
6b255391 10622 .get_link = page_get_link,
f209561a 10623 .getattr = btrfs_getattr,
22c44fe6 10624 .setattr = btrfs_setattr,
fdebe2bd 10625 .permission = btrfs_permission,
0279b4cd 10626 .listxattr = btrfs_listxattr,
e41f941a 10627 .update_time = btrfs_update_time,
39279cc3 10628};
76dda93c 10629
82d339d9 10630const struct dentry_operations btrfs_dentry_operations = {
76dda93c 10631 .d_delete = btrfs_dentry_delete,
b4aff1f8 10632 .d_release = btrfs_dentry_release,
76dda93c 10633};