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