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