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