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