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