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