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