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