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