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