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