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