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