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