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