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