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