Btrfs: be more selective in the defrag ioctl
[linux-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>
4b4e25f2 39#include "compat.h"
39279cc3
CM
40#include "ctree.h"
41#include "disk-io.h"
42#include "transaction.h"
43#include "btrfs_inode.h"
44#include "ioctl.h"
45#include "print-tree.h"
0b86a832 46#include "volumes.h"
e6dcd2dc 47#include "ordered-data.h"
95819c05 48#include "xattr.h"
e02119d5 49#include "tree-log.h"
c8b97818 50#include "compression.h"
b4ce94de 51#include "locking.h"
39279cc3
CM
52
53struct btrfs_iget_args {
54 u64 ino;
55 struct btrfs_root *root;
56};
57
6e1d5dcc
AD
58static const struct inode_operations btrfs_dir_inode_operations;
59static const struct inode_operations btrfs_symlink_inode_operations;
60static const struct inode_operations btrfs_dir_ro_inode_operations;
61static const struct inode_operations btrfs_special_inode_operations;
62static const struct inode_operations btrfs_file_inode_operations;
7f09410b
AD
63static const struct address_space_operations btrfs_aops;
64static const struct address_space_operations btrfs_symlink_aops;
828c0950 65static const struct file_operations btrfs_dir_file_operations;
d1310b2e 66static struct extent_io_ops btrfs_extent_io_ops;
39279cc3
CM
67
68static struct kmem_cache *btrfs_inode_cachep;
69struct kmem_cache *btrfs_trans_handle_cachep;
70struct kmem_cache *btrfs_transaction_cachep;
39279cc3
CM
71struct kmem_cache *btrfs_path_cachep;
72
73#define S_SHIFT 12
74static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
75 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
76 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
77 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
78 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
79 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
80 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
81 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
82};
83
7b128766 84static void btrfs_truncate(struct inode *inode);
c8b97818 85static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
771ed689
CM
86static noinline int cow_file_range(struct inode *inode,
87 struct page *locked_page,
88 u64 start, u64 end, int *page_started,
89 unsigned long *nr_written, int unlock);
7b128766 90
f34f57a3
YZ
91static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
92 struct inode *inode, struct inode *dir)
0279b4cd
JO
93{
94 int err;
95
f34f57a3 96 err = btrfs_init_acl(trans, inode, dir);
0279b4cd 97 if (!err)
f34f57a3 98 err = btrfs_xattr_security_init(trans, inode, dir);
0279b4cd
JO
99 return err;
100}
101
c8b97818
CM
102/*
103 * this does all the hard work for inserting an inline extent into
104 * the btree. The caller should have done a btrfs_drop_extents so that
105 * no overlapping inline items exist in the btree
106 */
d397712b 107static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
c8b97818
CM
108 struct btrfs_root *root, struct inode *inode,
109 u64 start, size_t size, size_t compressed_size,
110 struct page **compressed_pages)
111{
112 struct btrfs_key key;
113 struct btrfs_path *path;
114 struct extent_buffer *leaf;
115 struct page *page = NULL;
116 char *kaddr;
117 unsigned long ptr;
118 struct btrfs_file_extent_item *ei;
119 int err = 0;
120 int ret;
121 size_t cur_size = size;
122 size_t datasize;
123 unsigned long offset;
124 int use_compress = 0;
125
126 if (compressed_size && compressed_pages) {
127 use_compress = 1;
128 cur_size = compressed_size;
129 }
130
d397712b
CM
131 path = btrfs_alloc_path();
132 if (!path)
c8b97818
CM
133 return -ENOMEM;
134
b9473439 135 path->leave_spinning = 1;
c8b97818
CM
136 btrfs_set_trans_block_group(trans, inode);
137
138 key.objectid = inode->i_ino;
139 key.offset = start;
140 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
c8b97818
CM
141 datasize = btrfs_file_extent_calc_inline_size(cur_size);
142
143 inode_add_bytes(inode, size);
144 ret = btrfs_insert_empty_item(trans, root, path, &key,
145 datasize);
146 BUG_ON(ret);
147 if (ret) {
148 err = ret;
c8b97818
CM
149 goto fail;
150 }
151 leaf = path->nodes[0];
152 ei = btrfs_item_ptr(leaf, path->slots[0],
153 struct btrfs_file_extent_item);
154 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
155 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
156 btrfs_set_file_extent_encryption(leaf, ei, 0);
157 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
158 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
159 ptr = btrfs_file_extent_inline_start(ei);
160
161 if (use_compress) {
162 struct page *cpage;
163 int i = 0;
d397712b 164 while (compressed_size > 0) {
c8b97818 165 cpage = compressed_pages[i];
5b050f04 166 cur_size = min_t(unsigned long, compressed_size,
c8b97818
CM
167 PAGE_CACHE_SIZE);
168
b9473439 169 kaddr = kmap_atomic(cpage, KM_USER0);
c8b97818 170 write_extent_buffer(leaf, kaddr, ptr, cur_size);
b9473439 171 kunmap_atomic(kaddr, KM_USER0);
c8b97818
CM
172
173 i++;
174 ptr += cur_size;
175 compressed_size -= cur_size;
176 }
177 btrfs_set_file_extent_compression(leaf, ei,
178 BTRFS_COMPRESS_ZLIB);
179 } else {
180 page = find_get_page(inode->i_mapping,
181 start >> PAGE_CACHE_SHIFT);
182 btrfs_set_file_extent_compression(leaf, ei, 0);
183 kaddr = kmap_atomic(page, KM_USER0);
184 offset = start & (PAGE_CACHE_SIZE - 1);
185 write_extent_buffer(leaf, kaddr + offset, ptr, size);
186 kunmap_atomic(kaddr, KM_USER0);
187 page_cache_release(page);
188 }
189 btrfs_mark_buffer_dirty(leaf);
190 btrfs_free_path(path);
191
c2167754
YZ
192 /*
193 * we're an inline extent, so nobody can
194 * extend the file past i_size without locking
195 * a page we already have locked.
196 *
197 * We must do any isize and inode updates
198 * before we unlock the pages. Otherwise we
199 * could end up racing with unlink.
200 */
c8b97818
CM
201 BTRFS_I(inode)->disk_i_size = inode->i_size;
202 btrfs_update_inode(trans, root, inode);
c2167754 203
c8b97818
CM
204 return 0;
205fail:
206 btrfs_free_path(path);
207 return err;
208}
209
210
211/*
212 * conditionally insert an inline extent into the file. This
213 * does the checks required to make sure the data is small enough
214 * to fit as an inline extent.
215 */
7f366cfe 216static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
c8b97818
CM
217 struct btrfs_root *root,
218 struct inode *inode, u64 start, u64 end,
219 size_t compressed_size,
220 struct page **compressed_pages)
221{
222 u64 isize = i_size_read(inode);
223 u64 actual_end = min(end + 1, isize);
224 u64 inline_len = actual_end - start;
225 u64 aligned_end = (end + root->sectorsize - 1) &
226 ~((u64)root->sectorsize - 1);
227 u64 hint_byte;
228 u64 data_len = inline_len;
229 int ret;
230
231 if (compressed_size)
232 data_len = compressed_size;
233
234 if (start > 0 ||
70b99e69 235 actual_end >= PAGE_CACHE_SIZE ||
c8b97818
CM
236 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
237 (!compressed_size &&
238 (actual_end & (root->sectorsize - 1)) == 0) ||
239 end + 1 < isize ||
240 data_len > root->fs_info->max_inline) {
241 return 1;
242 }
243
920bbbfb 244 ret = btrfs_drop_extents(trans, inode, start, aligned_end,
a1ed835e 245 &hint_byte, 1);
c8b97818
CM
246 BUG_ON(ret);
247
248 if (isize > actual_end)
249 inline_len = min_t(u64, isize, actual_end);
250 ret = insert_inline_extent(trans, root, inode, start,
251 inline_len, compressed_size,
252 compressed_pages);
253 BUG_ON(ret);
a1ed835e 254 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
c8b97818
CM
255 return 0;
256}
257
771ed689
CM
258struct async_extent {
259 u64 start;
260 u64 ram_size;
261 u64 compressed_size;
262 struct page **pages;
263 unsigned long nr_pages;
264 struct list_head list;
265};
266
267struct async_cow {
268 struct inode *inode;
269 struct btrfs_root *root;
270 struct page *locked_page;
271 u64 start;
272 u64 end;
273 struct list_head extents;
274 struct btrfs_work work;
275};
276
277static noinline int add_async_extent(struct async_cow *cow,
278 u64 start, u64 ram_size,
279 u64 compressed_size,
280 struct page **pages,
281 unsigned long nr_pages)
282{
283 struct async_extent *async_extent;
284
285 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
286 async_extent->start = start;
287 async_extent->ram_size = ram_size;
288 async_extent->compressed_size = compressed_size;
289 async_extent->pages = pages;
290 async_extent->nr_pages = nr_pages;
291 list_add_tail(&async_extent->list, &cow->extents);
292 return 0;
293}
294
d352ac68 295/*
771ed689
CM
296 * we create compressed extents in two phases. The first
297 * phase compresses a range of pages that have already been
298 * locked (both pages and state bits are locked).
c8b97818 299 *
771ed689
CM
300 * This is done inside an ordered work queue, and the compression
301 * is spread across many cpus. The actual IO submission is step
302 * two, and the ordered work queue takes care of making sure that
303 * happens in the same order things were put onto the queue by
304 * writepages and friends.
c8b97818 305 *
771ed689
CM
306 * If this code finds it can't get good compression, it puts an
307 * entry onto the work queue to write the uncompressed bytes. This
308 * makes sure that both compressed inodes and uncompressed inodes
309 * are written in the same order that pdflush sent them down.
d352ac68 310 */
771ed689
CM
311static noinline int compress_file_range(struct inode *inode,
312 struct page *locked_page,
313 u64 start, u64 end,
314 struct async_cow *async_cow,
315 int *num_added)
b888db2b
CM
316{
317 struct btrfs_root *root = BTRFS_I(inode)->root;
318 struct btrfs_trans_handle *trans;
db94535d 319 u64 num_bytes;
c8b97818
CM
320 u64 orig_start;
321 u64 disk_num_bytes;
db94535d 322 u64 blocksize = root->sectorsize;
c8b97818 323 u64 actual_end;
42dc7bab 324 u64 isize = i_size_read(inode);
e6dcd2dc 325 int ret = 0;
c8b97818
CM
326 struct page **pages = NULL;
327 unsigned long nr_pages;
328 unsigned long nr_pages_ret = 0;
329 unsigned long total_compressed = 0;
330 unsigned long total_in = 0;
331 unsigned long max_compressed = 128 * 1024;
771ed689 332 unsigned long max_uncompressed = 128 * 1024;
c8b97818
CM
333 int i;
334 int will_compress;
b888db2b 335
c8b97818
CM
336 orig_start = start;
337
42dc7bab 338 actual_end = min_t(u64, isize, end + 1);
c8b97818
CM
339again:
340 will_compress = 0;
341 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
342 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
be20aa9d 343
f03d9301
CM
344 /*
345 * we don't want to send crud past the end of i_size through
346 * compression, that's just a waste of CPU time. So, if the
347 * end of the file is before the start of our current
348 * requested range of bytes, we bail out to the uncompressed
349 * cleanup code that can deal with all of this.
350 *
351 * It isn't really the fastest way to fix things, but this is a
352 * very uncommon corner.
353 */
354 if (actual_end <= start)
355 goto cleanup_and_bail_uncompressed;
356
c8b97818
CM
357 total_compressed = actual_end - start;
358
359 /* we want to make sure that amount of ram required to uncompress
360 * an extent is reasonable, so we limit the total size in ram
771ed689
CM
361 * of a compressed extent to 128k. This is a crucial number
362 * because it also controls how easily we can spread reads across
363 * cpus for decompression.
364 *
365 * We also want to make sure the amount of IO required to do
366 * a random read is reasonably small, so we limit the size of
367 * a compressed extent to 128k.
c8b97818
CM
368 */
369 total_compressed = min(total_compressed, max_uncompressed);
db94535d 370 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
be20aa9d 371 num_bytes = max(blocksize, num_bytes);
c8b97818
CM
372 disk_num_bytes = num_bytes;
373 total_in = 0;
374 ret = 0;
db94535d 375
771ed689
CM
376 /*
377 * we do compression for mount -o compress and when the
378 * inode has not been flagged as nocompress. This flag can
379 * change at any time if we discover bad compression ratios.
c8b97818 380 */
6cbff00f 381 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
c8b97818
CM
382 btrfs_test_opt(root, COMPRESS)) {
383 WARN_ON(pages);
cfbc246e 384 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
c8b97818 385
c8b97818
CM
386 ret = btrfs_zlib_compress_pages(inode->i_mapping, start,
387 total_compressed, pages,
388 nr_pages, &nr_pages_ret,
389 &total_in,
390 &total_compressed,
391 max_compressed);
392
393 if (!ret) {
394 unsigned long offset = total_compressed &
395 (PAGE_CACHE_SIZE - 1);
396 struct page *page = pages[nr_pages_ret - 1];
397 char *kaddr;
398
399 /* zero the tail end of the last page, we might be
400 * sending it down to disk
401 */
402 if (offset) {
403 kaddr = kmap_atomic(page, KM_USER0);
404 memset(kaddr + offset, 0,
405 PAGE_CACHE_SIZE - offset);
406 kunmap_atomic(kaddr, KM_USER0);
407 }
408 will_compress = 1;
409 }
410 }
411 if (start == 0) {
771ed689
CM
412 trans = btrfs_join_transaction(root, 1);
413 BUG_ON(!trans);
414 btrfs_set_trans_block_group(trans, inode);
415
c8b97818 416 /* lets try to make an inline extent */
771ed689 417 if (ret || total_in < (actual_end - start)) {
c8b97818 418 /* we didn't compress the entire range, try
771ed689 419 * to make an uncompressed inline extent.
c8b97818
CM
420 */
421 ret = cow_file_range_inline(trans, root, inode,
422 start, end, 0, NULL);
423 } else {
771ed689 424 /* try making a compressed inline extent */
c8b97818
CM
425 ret = cow_file_range_inline(trans, root, inode,
426 start, end,
427 total_compressed, pages);
428 }
429 if (ret == 0) {
771ed689
CM
430 /*
431 * inline extent creation worked, we don't need
432 * to create any more async work items. Unlock
433 * and free up our temp pages.
434 */
c8b97818 435 extent_clear_unlock_delalloc(inode,
a791e35e
CM
436 &BTRFS_I(inode)->io_tree,
437 start, end, NULL,
438 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
a3429ab7 439 EXTENT_CLEAR_DELALLOC |
32c00aff 440 EXTENT_CLEAR_ACCOUNTING |
a791e35e 441 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
c2167754
YZ
442
443 btrfs_end_transaction(trans, root);
c8b97818
CM
444 goto free_pages_out;
445 }
c2167754 446 btrfs_end_transaction(trans, root);
c8b97818
CM
447 }
448
449 if (will_compress) {
450 /*
451 * we aren't doing an inline extent round the compressed size
452 * up to a block size boundary so the allocator does sane
453 * things
454 */
455 total_compressed = (total_compressed + blocksize - 1) &
456 ~(blocksize - 1);
457
458 /*
459 * one last check to make sure the compression is really a
460 * win, compare the page count read with the blocks on disk
461 */
462 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
463 ~(PAGE_CACHE_SIZE - 1);
464 if (total_compressed >= total_in) {
465 will_compress = 0;
466 } else {
467 disk_num_bytes = total_compressed;
468 num_bytes = total_in;
469 }
470 }
471 if (!will_compress && pages) {
472 /*
473 * the compression code ran but failed to make things smaller,
474 * free any pages it allocated and our page pointer array
475 */
476 for (i = 0; i < nr_pages_ret; i++) {
70b99e69 477 WARN_ON(pages[i]->mapping);
c8b97818
CM
478 page_cache_release(pages[i]);
479 }
480 kfree(pages);
481 pages = NULL;
482 total_compressed = 0;
483 nr_pages_ret = 0;
484
485 /* flag the file so we don't compress in the future */
a555f810
CM
486 if (!btrfs_test_opt(root, FORCE_COMPRESS))
487 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
c8b97818 488 }
771ed689
CM
489 if (will_compress) {
490 *num_added += 1;
c8b97818 491
771ed689
CM
492 /* the async work queues will take care of doing actual
493 * allocation on disk for these compressed pages,
494 * and will submit them to the elevator.
495 */
496 add_async_extent(async_cow, start, num_bytes,
497 total_compressed, pages, nr_pages_ret);
179e29e4 498
42dc7bab 499 if (start + num_bytes < end && start + num_bytes < actual_end) {
771ed689
CM
500 start += num_bytes;
501 pages = NULL;
502 cond_resched();
503 goto again;
504 }
505 } else {
f03d9301 506cleanup_and_bail_uncompressed:
771ed689
CM
507 /*
508 * No compression, but we still need to write the pages in
509 * the file we've been given so far. redirty the locked
510 * page if it corresponds to our extent and set things up
511 * for the async work queue to run cow_file_range to do
512 * the normal delalloc dance
513 */
514 if (page_offset(locked_page) >= start &&
515 page_offset(locked_page) <= end) {
516 __set_page_dirty_nobuffers(locked_page);
517 /* unlocked later on in the async handlers */
518 }
519 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0);
520 *num_added += 1;
521 }
3b951516 522
771ed689
CM
523out:
524 return 0;
525
526free_pages_out:
527 for (i = 0; i < nr_pages_ret; i++) {
528 WARN_ON(pages[i]->mapping);
529 page_cache_release(pages[i]);
530 }
d397712b 531 kfree(pages);
771ed689
CM
532
533 goto out;
534}
535
536/*
537 * phase two of compressed writeback. This is the ordered portion
538 * of the code, which only gets called in the order the work was
539 * queued. We walk all the async extents created by compress_file_range
540 * and send them down to the disk.
541 */
542static noinline int submit_compressed_extents(struct inode *inode,
543 struct async_cow *async_cow)
544{
545 struct async_extent *async_extent;
546 u64 alloc_hint = 0;
547 struct btrfs_trans_handle *trans;
548 struct btrfs_key ins;
549 struct extent_map *em;
550 struct btrfs_root *root = BTRFS_I(inode)->root;
551 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
552 struct extent_io_tree *io_tree;
f5a84ee3 553 int ret = 0;
771ed689
CM
554
555 if (list_empty(&async_cow->extents))
556 return 0;
557
771ed689 558
d397712b 559 while (!list_empty(&async_cow->extents)) {
771ed689
CM
560 async_extent = list_entry(async_cow->extents.next,
561 struct async_extent, list);
562 list_del(&async_extent->list);
c8b97818 563
771ed689
CM
564 io_tree = &BTRFS_I(inode)->io_tree;
565
f5a84ee3 566retry:
771ed689
CM
567 /* did the compression code fall back to uncompressed IO? */
568 if (!async_extent->pages) {
569 int page_started = 0;
570 unsigned long nr_written = 0;
571
572 lock_extent(io_tree, async_extent->start,
d397712b
CM
573 async_extent->start +
574 async_extent->ram_size - 1, GFP_NOFS);
771ed689
CM
575
576 /* allocate blocks */
f5a84ee3
JB
577 ret = cow_file_range(inode, async_cow->locked_page,
578 async_extent->start,
579 async_extent->start +
580 async_extent->ram_size - 1,
581 &page_started, &nr_written, 0);
771ed689
CM
582
583 /*
584 * if page_started, cow_file_range inserted an
585 * inline extent and took care of all the unlocking
586 * and IO for us. Otherwise, we need to submit
587 * all those pages down to the drive.
588 */
f5a84ee3 589 if (!page_started && !ret)
771ed689
CM
590 extent_write_locked_range(io_tree,
591 inode, async_extent->start,
d397712b 592 async_extent->start +
771ed689
CM
593 async_extent->ram_size - 1,
594 btrfs_get_extent,
595 WB_SYNC_ALL);
596 kfree(async_extent);
597 cond_resched();
598 continue;
599 }
600
601 lock_extent(io_tree, async_extent->start,
602 async_extent->start + async_extent->ram_size - 1,
603 GFP_NOFS);
771ed689 604
c2167754 605 trans = btrfs_join_transaction(root, 1);
771ed689
CM
606 ret = btrfs_reserve_extent(trans, root,
607 async_extent->compressed_size,
608 async_extent->compressed_size,
609 0, alloc_hint,
610 (u64)-1, &ins, 1);
c2167754
YZ
611 btrfs_end_transaction(trans, root);
612
f5a84ee3
JB
613 if (ret) {
614 int i;
615 for (i = 0; i < async_extent->nr_pages; i++) {
616 WARN_ON(async_extent->pages[i]->mapping);
617 page_cache_release(async_extent->pages[i]);
618 }
619 kfree(async_extent->pages);
620 async_extent->nr_pages = 0;
621 async_extent->pages = NULL;
622 unlock_extent(io_tree, async_extent->start,
623 async_extent->start +
624 async_extent->ram_size - 1, GFP_NOFS);
625 goto retry;
626 }
627
c2167754
YZ
628 /*
629 * here we're doing allocation and writeback of the
630 * compressed pages
631 */
632 btrfs_drop_extent_cache(inode, async_extent->start,
633 async_extent->start +
634 async_extent->ram_size - 1, 0);
635
771ed689
CM
636 em = alloc_extent_map(GFP_NOFS);
637 em->start = async_extent->start;
638 em->len = async_extent->ram_size;
445a6944 639 em->orig_start = em->start;
c8b97818 640
771ed689
CM
641 em->block_start = ins.objectid;
642 em->block_len = ins.offset;
643 em->bdev = root->fs_info->fs_devices->latest_bdev;
644 set_bit(EXTENT_FLAG_PINNED, &em->flags);
645 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
646
d397712b 647 while (1) {
890871be 648 write_lock(&em_tree->lock);
771ed689 649 ret = add_extent_mapping(em_tree, em);
890871be 650 write_unlock(&em_tree->lock);
771ed689
CM
651 if (ret != -EEXIST) {
652 free_extent_map(em);
653 break;
654 }
655 btrfs_drop_extent_cache(inode, async_extent->start,
656 async_extent->start +
657 async_extent->ram_size - 1, 0);
658 }
659
660 ret = btrfs_add_ordered_extent(inode, async_extent->start,
661 ins.objectid,
662 async_extent->ram_size,
663 ins.offset,
664 BTRFS_ORDERED_COMPRESSED);
665 BUG_ON(ret);
666
771ed689
CM
667 /*
668 * clear dirty, set writeback and unlock the pages.
669 */
670 extent_clear_unlock_delalloc(inode,
a791e35e
CM
671 &BTRFS_I(inode)->io_tree,
672 async_extent->start,
673 async_extent->start +
674 async_extent->ram_size - 1,
675 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
676 EXTENT_CLEAR_UNLOCK |
a3429ab7 677 EXTENT_CLEAR_DELALLOC |
a791e35e 678 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
771ed689
CM
679
680 ret = btrfs_submit_compressed_write(inode,
d397712b
CM
681 async_extent->start,
682 async_extent->ram_size,
683 ins.objectid,
684 ins.offset, async_extent->pages,
685 async_extent->nr_pages);
771ed689
CM
686
687 BUG_ON(ret);
771ed689
CM
688 alloc_hint = ins.objectid + ins.offset;
689 kfree(async_extent);
690 cond_resched();
691 }
692
771ed689
CM
693 return 0;
694}
695
696/*
697 * when extent_io.c finds a delayed allocation range in the file,
698 * the call backs end up in this code. The basic idea is to
699 * allocate extents on disk for the range, and create ordered data structs
700 * in ram to track those extents.
701 *
702 * locked_page is the page that writepage had locked already. We use
703 * it to make sure we don't do extra locks or unlocks.
704 *
705 * *page_started is set to one if we unlock locked_page and do everything
706 * required to start IO on it. It may be clean and already done with
707 * IO when we return.
708 */
709static noinline int cow_file_range(struct inode *inode,
710 struct page *locked_page,
711 u64 start, u64 end, int *page_started,
712 unsigned long *nr_written,
713 int unlock)
714{
715 struct btrfs_root *root = BTRFS_I(inode)->root;
716 struct btrfs_trans_handle *trans;
717 u64 alloc_hint = 0;
718 u64 num_bytes;
719 unsigned long ram_size;
720 u64 disk_num_bytes;
721 u64 cur_alloc_size;
722 u64 blocksize = root->sectorsize;
723 u64 actual_end;
42dc7bab 724 u64 isize = i_size_read(inode);
771ed689
CM
725 struct btrfs_key ins;
726 struct extent_map *em;
727 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
728 int ret = 0;
729
730 trans = btrfs_join_transaction(root, 1);
731 BUG_ON(!trans);
732 btrfs_set_trans_block_group(trans, inode);
733
42dc7bab 734 actual_end = min_t(u64, isize, end + 1);
771ed689
CM
735
736 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
737 num_bytes = max(blocksize, num_bytes);
738 disk_num_bytes = num_bytes;
739 ret = 0;
740
741 if (start == 0) {
742 /* lets try to make an inline extent */
743 ret = cow_file_range_inline(trans, root, inode,
744 start, end, 0, NULL);
745 if (ret == 0) {
746 extent_clear_unlock_delalloc(inode,
a791e35e
CM
747 &BTRFS_I(inode)->io_tree,
748 start, end, NULL,
749 EXTENT_CLEAR_UNLOCK_PAGE |
750 EXTENT_CLEAR_UNLOCK |
751 EXTENT_CLEAR_DELALLOC |
32c00aff 752 EXTENT_CLEAR_ACCOUNTING |
a791e35e
CM
753 EXTENT_CLEAR_DIRTY |
754 EXTENT_SET_WRITEBACK |
755 EXTENT_END_WRITEBACK);
c2167754 756
771ed689
CM
757 *nr_written = *nr_written +
758 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
759 *page_started = 1;
760 ret = 0;
761 goto out;
762 }
763 }
764
765 BUG_ON(disk_num_bytes >
766 btrfs_super_total_bytes(&root->fs_info->super_copy));
767
b917b7c3
CM
768
769 read_lock(&BTRFS_I(inode)->extent_tree.lock);
770 em = search_extent_mapping(&BTRFS_I(inode)->extent_tree,
771 start, num_bytes);
772 if (em) {
6346c939
JB
773 /*
774 * if block start isn't an actual block number then find the
775 * first block in this inode and use that as a hint. If that
776 * block is also bogus then just don't worry about it.
777 */
778 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
779 free_extent_map(em);
780 em = search_extent_mapping(em_tree, 0, 0);
781 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
782 alloc_hint = em->block_start;
783 if (em)
784 free_extent_map(em);
785 } else {
786 alloc_hint = em->block_start;
787 free_extent_map(em);
788 }
b917b7c3
CM
789 }
790 read_unlock(&BTRFS_I(inode)->extent_tree.lock);
771ed689
CM
791 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
792
d397712b 793 while (disk_num_bytes > 0) {
a791e35e
CM
794 unsigned long op;
795
c8b97818 796 cur_alloc_size = min(disk_num_bytes, root->fs_info->max_extent);
e6dcd2dc 797 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
771ed689 798 root->sectorsize, 0, alloc_hint,
e6dcd2dc 799 (u64)-1, &ins, 1);
d397712b
CM
800 BUG_ON(ret);
801
e6dcd2dc
CM
802 em = alloc_extent_map(GFP_NOFS);
803 em->start = start;
445a6944 804 em->orig_start = em->start;
771ed689
CM
805 ram_size = ins.offset;
806 em->len = ins.offset;
c8b97818 807
e6dcd2dc 808 em->block_start = ins.objectid;
c8b97818 809 em->block_len = ins.offset;
e6dcd2dc 810 em->bdev = root->fs_info->fs_devices->latest_bdev;
7f3c74fb 811 set_bit(EXTENT_FLAG_PINNED, &em->flags);
c8b97818 812
d397712b 813 while (1) {
890871be 814 write_lock(&em_tree->lock);
e6dcd2dc 815 ret = add_extent_mapping(em_tree, em);
890871be 816 write_unlock(&em_tree->lock);
e6dcd2dc
CM
817 if (ret != -EEXIST) {
818 free_extent_map(em);
819 break;
820 }
821 btrfs_drop_extent_cache(inode, start,
c8b97818 822 start + ram_size - 1, 0);
e6dcd2dc
CM
823 }
824
98d20f67 825 cur_alloc_size = ins.offset;
e6dcd2dc 826 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
771ed689 827 ram_size, cur_alloc_size, 0);
e6dcd2dc 828 BUG_ON(ret);
c8b97818 829
17d217fe
YZ
830 if (root->root_key.objectid ==
831 BTRFS_DATA_RELOC_TREE_OBJECTID) {
832 ret = btrfs_reloc_clone_csums(inode, start,
833 cur_alloc_size);
834 BUG_ON(ret);
835 }
836
d397712b 837 if (disk_num_bytes < cur_alloc_size)
3b951516 838 break;
d397712b 839
c8b97818
CM
840 /* we're not doing compressed IO, don't unlock the first
841 * page (which the caller expects to stay locked), don't
842 * clear any dirty bits and don't set any writeback bits
8b62b72b
CM
843 *
844 * Do set the Private2 bit so we know this page was properly
845 * setup for writepage
c8b97818 846 */
a791e35e
CM
847 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
848 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
849 EXTENT_SET_PRIVATE2;
850
c8b97818
CM
851 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
852 start, start + ram_size - 1,
a791e35e 853 locked_page, op);
c8b97818 854 disk_num_bytes -= cur_alloc_size;
c59f8951
CM
855 num_bytes -= cur_alloc_size;
856 alloc_hint = ins.objectid + ins.offset;
857 start += cur_alloc_size;
b888db2b 858 }
b888db2b 859out:
771ed689 860 ret = 0;
b888db2b 861 btrfs_end_transaction(trans, root);
c8b97818 862
be20aa9d 863 return ret;
771ed689 864}
c8b97818 865
771ed689
CM
866/*
867 * work queue call back to started compression on a file and pages
868 */
869static noinline void async_cow_start(struct btrfs_work *work)
870{
871 struct async_cow *async_cow;
872 int num_added = 0;
873 async_cow = container_of(work, struct async_cow, work);
874
875 compress_file_range(async_cow->inode, async_cow->locked_page,
876 async_cow->start, async_cow->end, async_cow,
877 &num_added);
878 if (num_added == 0)
879 async_cow->inode = NULL;
880}
881
882/*
883 * work queue call back to submit previously compressed pages
884 */
885static noinline void async_cow_submit(struct btrfs_work *work)
886{
887 struct async_cow *async_cow;
888 struct btrfs_root *root;
889 unsigned long nr_pages;
890
891 async_cow = container_of(work, struct async_cow, work);
892
893 root = async_cow->root;
894 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
895 PAGE_CACHE_SHIFT;
896
897 atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
898
899 if (atomic_read(&root->fs_info->async_delalloc_pages) <
900 5 * 1042 * 1024 &&
901 waitqueue_active(&root->fs_info->async_submit_wait))
902 wake_up(&root->fs_info->async_submit_wait);
903
d397712b 904 if (async_cow->inode)
771ed689 905 submit_compressed_extents(async_cow->inode, async_cow);
771ed689 906}
c8b97818 907
771ed689
CM
908static noinline void async_cow_free(struct btrfs_work *work)
909{
910 struct async_cow *async_cow;
911 async_cow = container_of(work, struct async_cow, work);
912 kfree(async_cow);
913}
914
915static int cow_file_range_async(struct inode *inode, struct page *locked_page,
916 u64 start, u64 end, int *page_started,
917 unsigned long *nr_written)
918{
919 struct async_cow *async_cow;
920 struct btrfs_root *root = BTRFS_I(inode)->root;
921 unsigned long nr_pages;
922 u64 cur_end;
923 int limit = 10 * 1024 * 1042;
924
a3429ab7
CM
925 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
926 1, 0, NULL, GFP_NOFS);
d397712b 927 while (start < end) {
771ed689
CM
928 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
929 async_cow->inode = inode;
930 async_cow->root = root;
931 async_cow->locked_page = locked_page;
932 async_cow->start = start;
933
6cbff00f 934 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
771ed689
CM
935 cur_end = end;
936 else
937 cur_end = min(end, start + 512 * 1024 - 1);
938
939 async_cow->end = cur_end;
940 INIT_LIST_HEAD(&async_cow->extents);
941
942 async_cow->work.func = async_cow_start;
943 async_cow->work.ordered_func = async_cow_submit;
944 async_cow->work.ordered_free = async_cow_free;
945 async_cow->work.flags = 0;
946
771ed689
CM
947 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
948 PAGE_CACHE_SHIFT;
949 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
950
951 btrfs_queue_worker(&root->fs_info->delalloc_workers,
952 &async_cow->work);
953
954 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
955 wait_event(root->fs_info->async_submit_wait,
956 (atomic_read(&root->fs_info->async_delalloc_pages) <
957 limit));
958 }
959
d397712b 960 while (atomic_read(&root->fs_info->async_submit_draining) &&
771ed689
CM
961 atomic_read(&root->fs_info->async_delalloc_pages)) {
962 wait_event(root->fs_info->async_submit_wait,
963 (atomic_read(&root->fs_info->async_delalloc_pages) ==
964 0));
965 }
966
967 *nr_written += nr_pages;
968 start = cur_end + 1;
969 }
970 *page_started = 1;
971 return 0;
be20aa9d
CM
972}
973
d397712b 974static noinline int csum_exist_in_range(struct btrfs_root *root,
17d217fe
YZ
975 u64 bytenr, u64 num_bytes)
976{
977 int ret;
978 struct btrfs_ordered_sum *sums;
979 LIST_HEAD(list);
980
07d400a6
YZ
981 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
982 bytenr + num_bytes - 1, &list);
17d217fe
YZ
983 if (ret == 0 && list_empty(&list))
984 return 0;
985
986 while (!list_empty(&list)) {
987 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
988 list_del(&sums->list);
989 kfree(sums);
990 }
991 return 1;
992}
993
d352ac68
CM
994/*
995 * when nowcow writeback call back. This checks for snapshots or COW copies
996 * of the extents that exist in the file, and COWs the file as required.
997 *
998 * If no cow copies or snapshots exist, we write directly to the existing
999 * blocks on disk
1000 */
7f366cfe
CM
1001static noinline int run_delalloc_nocow(struct inode *inode,
1002 struct page *locked_page,
771ed689
CM
1003 u64 start, u64 end, int *page_started, int force,
1004 unsigned long *nr_written)
be20aa9d 1005{
be20aa9d 1006 struct btrfs_root *root = BTRFS_I(inode)->root;
7ea394f1 1007 struct btrfs_trans_handle *trans;
be20aa9d 1008 struct extent_buffer *leaf;
be20aa9d 1009 struct btrfs_path *path;
80ff3856 1010 struct btrfs_file_extent_item *fi;
be20aa9d 1011 struct btrfs_key found_key;
80ff3856
YZ
1012 u64 cow_start;
1013 u64 cur_offset;
1014 u64 extent_end;
5d4f98a2 1015 u64 extent_offset;
80ff3856
YZ
1016 u64 disk_bytenr;
1017 u64 num_bytes;
1018 int extent_type;
1019 int ret;
d899e052 1020 int type;
80ff3856
YZ
1021 int nocow;
1022 int check_prev = 1;
be20aa9d
CM
1023
1024 path = btrfs_alloc_path();
1025 BUG_ON(!path);
7ea394f1
YZ
1026 trans = btrfs_join_transaction(root, 1);
1027 BUG_ON(!trans);
be20aa9d 1028
80ff3856
YZ
1029 cow_start = (u64)-1;
1030 cur_offset = start;
1031 while (1) {
1032 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
1033 cur_offset, 0);
1034 BUG_ON(ret < 0);
1035 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1036 leaf = path->nodes[0];
1037 btrfs_item_key_to_cpu(leaf, &found_key,
1038 path->slots[0] - 1);
1039 if (found_key.objectid == inode->i_ino &&
1040 found_key.type == BTRFS_EXTENT_DATA_KEY)
1041 path->slots[0]--;
1042 }
1043 check_prev = 0;
1044next_slot:
1045 leaf = path->nodes[0];
1046 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1047 ret = btrfs_next_leaf(root, path);
1048 if (ret < 0)
1049 BUG_ON(1);
1050 if (ret > 0)
1051 break;
1052 leaf = path->nodes[0];
1053 }
be20aa9d 1054
80ff3856
YZ
1055 nocow = 0;
1056 disk_bytenr = 0;
17d217fe 1057 num_bytes = 0;
80ff3856
YZ
1058 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1059
1060 if (found_key.objectid > inode->i_ino ||
1061 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1062 found_key.offset > end)
1063 break;
1064
1065 if (found_key.offset > cur_offset) {
1066 extent_end = found_key.offset;
e9061e21 1067 extent_type = 0;
80ff3856
YZ
1068 goto out_check;
1069 }
1070
1071 fi = btrfs_item_ptr(leaf, path->slots[0],
1072 struct btrfs_file_extent_item);
1073 extent_type = btrfs_file_extent_type(leaf, fi);
1074
d899e052
YZ
1075 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1076 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
80ff3856 1077 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5d4f98a2 1078 extent_offset = btrfs_file_extent_offset(leaf, fi);
80ff3856
YZ
1079 extent_end = found_key.offset +
1080 btrfs_file_extent_num_bytes(leaf, fi);
1081 if (extent_end <= start) {
1082 path->slots[0]++;
1083 goto next_slot;
1084 }
17d217fe
YZ
1085 if (disk_bytenr == 0)
1086 goto out_check;
80ff3856
YZ
1087 if (btrfs_file_extent_compression(leaf, fi) ||
1088 btrfs_file_extent_encryption(leaf, fi) ||
1089 btrfs_file_extent_other_encoding(leaf, fi))
1090 goto out_check;
d899e052
YZ
1091 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1092 goto out_check;
d2fb3437 1093 if (btrfs_extent_readonly(root, disk_bytenr))
80ff3856 1094 goto out_check;
17d217fe 1095 if (btrfs_cross_ref_exist(trans, root, inode->i_ino,
5d4f98a2
YZ
1096 found_key.offset -
1097 extent_offset, disk_bytenr))
17d217fe 1098 goto out_check;
5d4f98a2 1099 disk_bytenr += extent_offset;
17d217fe
YZ
1100 disk_bytenr += cur_offset - found_key.offset;
1101 num_bytes = min(end + 1, extent_end) - cur_offset;
1102 /*
1103 * force cow if csum exists in the range.
1104 * this ensure that csum for a given extent are
1105 * either valid or do not exist.
1106 */
1107 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1108 goto out_check;
80ff3856
YZ
1109 nocow = 1;
1110 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1111 extent_end = found_key.offset +
1112 btrfs_file_extent_inline_len(leaf, fi);
1113 extent_end = ALIGN(extent_end, root->sectorsize);
1114 } else {
1115 BUG_ON(1);
1116 }
1117out_check:
1118 if (extent_end <= start) {
1119 path->slots[0]++;
1120 goto next_slot;
1121 }
1122 if (!nocow) {
1123 if (cow_start == (u64)-1)
1124 cow_start = cur_offset;
1125 cur_offset = extent_end;
1126 if (cur_offset > end)
1127 break;
1128 path->slots[0]++;
1129 goto next_slot;
7ea394f1
YZ
1130 }
1131
1132 btrfs_release_path(root, path);
80ff3856
YZ
1133 if (cow_start != (u64)-1) {
1134 ret = cow_file_range(inode, locked_page, cow_start,
771ed689
CM
1135 found_key.offset - 1, page_started,
1136 nr_written, 1);
80ff3856
YZ
1137 BUG_ON(ret);
1138 cow_start = (u64)-1;
7ea394f1 1139 }
80ff3856 1140
d899e052
YZ
1141 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1142 struct extent_map *em;
1143 struct extent_map_tree *em_tree;
1144 em_tree = &BTRFS_I(inode)->extent_tree;
1145 em = alloc_extent_map(GFP_NOFS);
1146 em->start = cur_offset;
445a6944 1147 em->orig_start = em->start;
d899e052
YZ
1148 em->len = num_bytes;
1149 em->block_len = num_bytes;
1150 em->block_start = disk_bytenr;
1151 em->bdev = root->fs_info->fs_devices->latest_bdev;
1152 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1153 while (1) {
890871be 1154 write_lock(&em_tree->lock);
d899e052 1155 ret = add_extent_mapping(em_tree, em);
890871be 1156 write_unlock(&em_tree->lock);
d899e052
YZ
1157 if (ret != -EEXIST) {
1158 free_extent_map(em);
1159 break;
1160 }
1161 btrfs_drop_extent_cache(inode, em->start,
1162 em->start + em->len - 1, 0);
1163 }
1164 type = BTRFS_ORDERED_PREALLOC;
1165 } else {
1166 type = BTRFS_ORDERED_NOCOW;
1167 }
80ff3856
YZ
1168
1169 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
d899e052
YZ
1170 num_bytes, num_bytes, type);
1171 BUG_ON(ret);
771ed689 1172
d899e052 1173 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
a791e35e
CM
1174 cur_offset, cur_offset + num_bytes - 1,
1175 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1176 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1177 EXTENT_SET_PRIVATE2);
80ff3856
YZ
1178 cur_offset = extent_end;
1179 if (cur_offset > end)
1180 break;
be20aa9d 1181 }
80ff3856
YZ
1182 btrfs_release_path(root, path);
1183
1184 if (cur_offset <= end && cow_start == (u64)-1)
1185 cow_start = cur_offset;
1186 if (cow_start != (u64)-1) {
1187 ret = cow_file_range(inode, locked_page, cow_start, end,
771ed689 1188 page_started, nr_written, 1);
80ff3856
YZ
1189 BUG_ON(ret);
1190 }
1191
1192 ret = btrfs_end_transaction(trans, root);
1193 BUG_ON(ret);
7ea394f1 1194 btrfs_free_path(path);
80ff3856 1195 return 0;
be20aa9d
CM
1196}
1197
d352ac68
CM
1198/*
1199 * extent_io.c call back to do delayed allocation processing
1200 */
c8b97818 1201static int run_delalloc_range(struct inode *inode, struct page *locked_page,
771ed689
CM
1202 u64 start, u64 end, int *page_started,
1203 unsigned long *nr_written)
be20aa9d 1204{
be20aa9d 1205 int ret;
7f366cfe 1206 struct btrfs_root *root = BTRFS_I(inode)->root;
a2135011 1207
6cbff00f 1208 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
c8b97818 1209 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1210 page_started, 1, nr_written);
6cbff00f 1211 else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
d899e052 1212 ret = run_delalloc_nocow(inode, locked_page, start, end,
d397712b 1213 page_started, 0, nr_written);
7f366cfe
CM
1214 else if (!btrfs_test_opt(root, COMPRESS))
1215 ret = cow_file_range(inode, locked_page, start, end,
1216 page_started, nr_written, 1);
be20aa9d 1217 else
771ed689 1218 ret = cow_file_range_async(inode, locked_page, start, end,
d397712b 1219 page_started, nr_written);
b888db2b
CM
1220 return ret;
1221}
1222
9ed74f2d
JB
1223static int btrfs_split_extent_hook(struct inode *inode,
1224 struct extent_state *orig, u64 split)
1225{
1226 struct btrfs_root *root = BTRFS_I(inode)->root;
1227 u64 size;
1228
1229 if (!(orig->state & EXTENT_DELALLOC))
1230 return 0;
1231
1232 size = orig->end - orig->start + 1;
1233 if (size > root->fs_info->max_extent) {
1234 u64 num_extents;
1235 u64 new_size;
1236
1237 new_size = orig->end - split + 1;
1238 num_extents = div64_u64(size + root->fs_info->max_extent - 1,
1239 root->fs_info->max_extent);
1240
1241 /*
32c00aff
JB
1242 * if we break a large extent up then leave oustanding_extents
1243 * be, since we've already accounted for the large extent.
9ed74f2d
JB
1244 */
1245 if (div64_u64(new_size + root->fs_info->max_extent - 1,
1246 root->fs_info->max_extent) < num_extents)
1247 return 0;
1248 }
1249
32c00aff
JB
1250 spin_lock(&BTRFS_I(inode)->accounting_lock);
1251 BTRFS_I(inode)->outstanding_extents++;
1252 spin_unlock(&BTRFS_I(inode)->accounting_lock);
9ed74f2d
JB
1253
1254 return 0;
1255}
1256
1257/*
1258 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1259 * extents so we can keep track of new extents that are just merged onto old
1260 * extents, such as when we are doing sequential writes, so we can properly
1261 * account for the metadata space we'll need.
1262 */
1263static int btrfs_merge_extent_hook(struct inode *inode,
1264 struct extent_state *new,
1265 struct extent_state *other)
1266{
1267 struct btrfs_root *root = BTRFS_I(inode)->root;
1268 u64 new_size, old_size;
1269 u64 num_extents;
1270
1271 /* not delalloc, ignore it */
1272 if (!(other->state & EXTENT_DELALLOC))
1273 return 0;
1274
1275 old_size = other->end - other->start + 1;
1276 if (new->start < other->start)
1277 new_size = other->end - new->start + 1;
1278 else
1279 new_size = new->end - other->start + 1;
1280
1281 /* we're not bigger than the max, unreserve the space and go */
1282 if (new_size <= root->fs_info->max_extent) {
32c00aff
JB
1283 spin_lock(&BTRFS_I(inode)->accounting_lock);
1284 BTRFS_I(inode)->outstanding_extents--;
1285 spin_unlock(&BTRFS_I(inode)->accounting_lock);
9ed74f2d
JB
1286 return 0;
1287 }
1288
1289 /*
1290 * If we grew by another max_extent, just return, we want to keep that
1291 * reserved amount.
1292 */
1293 num_extents = div64_u64(old_size + root->fs_info->max_extent - 1,
1294 root->fs_info->max_extent);
1295 if (div64_u64(new_size + root->fs_info->max_extent - 1,
1296 root->fs_info->max_extent) > num_extents)
1297 return 0;
1298
32c00aff
JB
1299 spin_lock(&BTRFS_I(inode)->accounting_lock);
1300 BTRFS_I(inode)->outstanding_extents--;
1301 spin_unlock(&BTRFS_I(inode)->accounting_lock);
9ed74f2d
JB
1302
1303 return 0;
1304}
1305
d352ac68
CM
1306/*
1307 * extent_io.c set_bit_hook, used to track delayed allocation
1308 * bytes in this file, and to maintain the list of inodes that
1309 * have pending delalloc work to be done.
1310 */
b2950863 1311static int btrfs_set_bit_hook(struct inode *inode, u64 start, u64 end,
b0c68f8b 1312 unsigned long old, unsigned long bits)
291d673e 1313{
9ed74f2d 1314
75eff68e
CM
1315 /*
1316 * set_bit and clear bit hooks normally require _irqsave/restore
1317 * but in this case, we are only testeing for the DELALLOC
1318 * bit, which is only set or cleared with irqs on
1319 */
b0c68f8b 1320 if (!(old & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
291d673e 1321 struct btrfs_root *root = BTRFS_I(inode)->root;
9ed74f2d 1322
32c00aff
JB
1323 spin_lock(&BTRFS_I(inode)->accounting_lock);
1324 BTRFS_I(inode)->outstanding_extents++;
1325 spin_unlock(&BTRFS_I(inode)->accounting_lock);
6a63209f 1326 btrfs_delalloc_reserve_space(root, inode, end - start + 1);
75eff68e 1327 spin_lock(&root->fs_info->delalloc_lock);
9069218d 1328 BTRFS_I(inode)->delalloc_bytes += end - start + 1;
291d673e 1329 root->fs_info->delalloc_bytes += end - start + 1;
ea8c2819
CM
1330 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1331 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1332 &root->fs_info->delalloc_inodes);
1333 }
75eff68e 1334 spin_unlock(&root->fs_info->delalloc_lock);
291d673e
CM
1335 }
1336 return 0;
1337}
1338
d352ac68
CM
1339/*
1340 * extent_io.c clear_bit_hook, see set_bit_hook for why
1341 */
9ed74f2d
JB
1342static int btrfs_clear_bit_hook(struct inode *inode,
1343 struct extent_state *state, unsigned long bits)
291d673e 1344{
75eff68e
CM
1345 /*
1346 * set_bit and clear bit hooks normally require _irqsave/restore
1347 * but in this case, we are only testeing for the DELALLOC
1348 * bit, which is only set or cleared with irqs on
1349 */
9ed74f2d 1350 if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
291d673e 1351 struct btrfs_root *root = BTRFS_I(inode)->root;
bcbfce8a 1352
32c00aff
JB
1353 if (bits & EXTENT_DO_ACCOUNTING) {
1354 spin_lock(&BTRFS_I(inode)->accounting_lock);
1355 BTRFS_I(inode)->outstanding_extents--;
1356 spin_unlock(&BTRFS_I(inode)->accounting_lock);
1357 btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
1358 }
9ed74f2d 1359
75eff68e 1360 spin_lock(&root->fs_info->delalloc_lock);
9ed74f2d
JB
1361 if (state->end - state->start + 1 >
1362 root->fs_info->delalloc_bytes) {
d397712b
CM
1363 printk(KERN_INFO "btrfs warning: delalloc account "
1364 "%llu %llu\n",
9ed74f2d
JB
1365 (unsigned long long)
1366 state->end - state->start + 1,
d397712b
CM
1367 (unsigned long long)
1368 root->fs_info->delalloc_bytes);
6a63209f 1369 btrfs_delalloc_free_space(root, inode, (u64)-1);
b0c68f8b 1370 root->fs_info->delalloc_bytes = 0;
9069218d 1371 BTRFS_I(inode)->delalloc_bytes = 0;
b0c68f8b 1372 } else {
6a63209f 1373 btrfs_delalloc_free_space(root, inode,
9ed74f2d
JB
1374 state->end -
1375 state->start + 1);
1376 root->fs_info->delalloc_bytes -= state->end -
1377 state->start + 1;
1378 BTRFS_I(inode)->delalloc_bytes -= state->end -
1379 state->start + 1;
b0c68f8b 1380 }
ea8c2819
CM
1381 if (BTRFS_I(inode)->delalloc_bytes == 0 &&
1382 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1383 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1384 }
75eff68e 1385 spin_unlock(&root->fs_info->delalloc_lock);
291d673e
CM
1386 }
1387 return 0;
1388}
1389
d352ac68
CM
1390/*
1391 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1392 * we don't create bios that span stripes or chunks
1393 */
239b14b3 1394int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
c8b97818
CM
1395 size_t size, struct bio *bio,
1396 unsigned long bio_flags)
239b14b3
CM
1397{
1398 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1399 struct btrfs_mapping_tree *map_tree;
a62b9401 1400 u64 logical = (u64)bio->bi_sector << 9;
239b14b3
CM
1401 u64 length = 0;
1402 u64 map_length;
239b14b3
CM
1403 int ret;
1404
771ed689
CM
1405 if (bio_flags & EXTENT_BIO_COMPRESSED)
1406 return 0;
1407
f2d8d74d 1408 length = bio->bi_size;
239b14b3
CM
1409 map_tree = &root->fs_info->mapping_tree;
1410 map_length = length;
cea9e445 1411 ret = btrfs_map_block(map_tree, READ, logical,
f188591e 1412 &map_length, NULL, 0);
cea9e445 1413
d397712b 1414 if (map_length < length + size)
239b14b3 1415 return 1;
239b14b3
CM
1416 return 0;
1417}
1418
d352ac68
CM
1419/*
1420 * in order to insert checksums into the metadata in large chunks,
1421 * we wait until bio submission time. All the pages in the bio are
1422 * checksummed and sums are attached onto the ordered extent record.
1423 *
1424 * At IO completion time the cums attached on the ordered extent record
1425 * are inserted into the btree
1426 */
d397712b
CM
1427static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1428 struct bio *bio, int mirror_num,
1429 unsigned long bio_flags)
065631f6 1430{
065631f6 1431 struct btrfs_root *root = BTRFS_I(inode)->root;
065631f6 1432 int ret = 0;
e015640f 1433
d20f7043 1434 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
44b8bd7e 1435 BUG_ON(ret);
4a69a410
CM
1436 return 0;
1437}
e015640f 1438
4a69a410
CM
1439/*
1440 * in order to insert checksums into the metadata in large chunks,
1441 * we wait until bio submission time. All the pages in the bio are
1442 * checksummed and sums are attached onto the ordered extent record.
1443 *
1444 * At IO completion time the cums attached on the ordered extent record
1445 * are inserted into the btree
1446 */
b2950863 1447static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
4a69a410
CM
1448 int mirror_num, unsigned long bio_flags)
1449{
1450 struct btrfs_root *root = BTRFS_I(inode)->root;
8b712842 1451 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
44b8bd7e
CM
1452}
1453
d352ac68 1454/*
cad321ad
CM
1455 * extent_io.c submission hook. This does the right thing for csum calculation
1456 * on write, or reading the csums from the tree before a read
d352ac68 1457 */
b2950863 1458static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
c8b97818 1459 int mirror_num, unsigned long bio_flags)
44b8bd7e
CM
1460{
1461 struct btrfs_root *root = BTRFS_I(inode)->root;
1462 int ret = 0;
19b9bdb0 1463 int skip_sum;
44b8bd7e 1464
6cbff00f 1465 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
cad321ad 1466
e6dcd2dc
CM
1467 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1468 BUG_ON(ret);
065631f6 1469
4d1b5fb4 1470 if (!(rw & (1 << BIO_RW))) {
d20f7043 1471 if (bio_flags & EXTENT_BIO_COMPRESSED) {
c8b97818
CM
1472 return btrfs_submit_compressed_read(inode, bio,
1473 mirror_num, bio_flags);
d20f7043
CM
1474 } else if (!skip_sum)
1475 btrfs_lookup_bio_sums(root, inode, bio, NULL);
4d1b5fb4 1476 goto mapit;
19b9bdb0 1477 } else if (!skip_sum) {
17d217fe
YZ
1478 /* csum items have already been cloned */
1479 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1480 goto mapit;
19b9bdb0
CM
1481 /* we're doing a write, do the async checksumming */
1482 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
44b8bd7e 1483 inode, rw, bio, mirror_num,
4a69a410
CM
1484 bio_flags, __btrfs_submit_bio_start,
1485 __btrfs_submit_bio_done);
19b9bdb0
CM
1486 }
1487
0b86a832 1488mapit:
8b712842 1489 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
065631f6 1490}
6885f308 1491
d352ac68
CM
1492/*
1493 * given a list of ordered sums record them in the inode. This happens
1494 * at IO completion time based on sums calculated at bio submission time.
1495 */
ba1da2f4 1496static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
e6dcd2dc
CM
1497 struct inode *inode, u64 file_offset,
1498 struct list_head *list)
1499{
e6dcd2dc
CM
1500 struct btrfs_ordered_sum *sum;
1501
1502 btrfs_set_trans_block_group(trans, inode);
c6e30871
QF
1503
1504 list_for_each_entry(sum, list, list) {
d20f7043
CM
1505 btrfs_csum_file_blocks(trans,
1506 BTRFS_I(inode)->root->fs_info->csum_root, sum);
e6dcd2dc
CM
1507 }
1508 return 0;
1509}
1510
ea8c2819
CM
1511int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end)
1512{
d397712b 1513 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
771ed689 1514 WARN_ON(1);
ea8c2819
CM
1515 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1516 GFP_NOFS);
1517}
1518
d352ac68 1519/* see btrfs_writepage_start_hook for details on why this is required */
247e743c
CM
1520struct btrfs_writepage_fixup {
1521 struct page *page;
1522 struct btrfs_work work;
1523};
1524
b2950863 1525static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
247e743c
CM
1526{
1527 struct btrfs_writepage_fixup *fixup;
1528 struct btrfs_ordered_extent *ordered;
1529 struct page *page;
1530 struct inode *inode;
1531 u64 page_start;
1532 u64 page_end;
1533
1534 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1535 page = fixup->page;
4a096752 1536again:
247e743c
CM
1537 lock_page(page);
1538 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1539 ClearPageChecked(page);
1540 goto out_page;
1541 }
1542
1543 inode = page->mapping->host;
1544 page_start = page_offset(page);
1545 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1546
1547 lock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
4a096752
CM
1548
1549 /* already ordered? We're done */
8b62b72b 1550 if (PagePrivate2(page))
247e743c 1551 goto out;
4a096752
CM
1552
1553 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1554 if (ordered) {
1555 unlock_extent(&BTRFS_I(inode)->io_tree, page_start,
1556 page_end, GFP_NOFS);
1557 unlock_page(page);
1558 btrfs_start_ordered_extent(inode, ordered, 1);
1559 goto again;
1560 }
247e743c 1561
ea8c2819 1562 btrfs_set_extent_delalloc(inode, page_start, page_end);
247e743c
CM
1563 ClearPageChecked(page);
1564out:
1565 unlock_extent(&BTRFS_I(inode)->io_tree, page_start, page_end, GFP_NOFS);
1566out_page:
1567 unlock_page(page);
1568 page_cache_release(page);
1569}
1570
1571/*
1572 * There are a few paths in the higher layers of the kernel that directly
1573 * set the page dirty bit without asking the filesystem if it is a
1574 * good idea. This causes problems because we want to make sure COW
1575 * properly happens and the data=ordered rules are followed.
1576 *
c8b97818 1577 * In our case any range that doesn't have the ORDERED bit set
247e743c
CM
1578 * hasn't been properly setup for IO. We kick off an async process
1579 * to fix it up. The async helper will wait for ordered extents, set
1580 * the delalloc bit and make it safe to write the page.
1581 */
b2950863 1582static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
247e743c
CM
1583{
1584 struct inode *inode = page->mapping->host;
1585 struct btrfs_writepage_fixup *fixup;
1586 struct btrfs_root *root = BTRFS_I(inode)->root;
247e743c 1587
8b62b72b
CM
1588 /* this page is properly in the ordered list */
1589 if (TestClearPagePrivate2(page))
247e743c
CM
1590 return 0;
1591
1592 if (PageChecked(page))
1593 return -EAGAIN;
1594
1595 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1596 if (!fixup)
1597 return -EAGAIN;
f421950f 1598
247e743c
CM
1599 SetPageChecked(page);
1600 page_cache_get(page);
1601 fixup->work.func = btrfs_writepage_fixup_worker;
1602 fixup->page = page;
1603 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1604 return -EAGAIN;
1605}
1606
d899e052
YZ
1607static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1608 struct inode *inode, u64 file_pos,
1609 u64 disk_bytenr, u64 disk_num_bytes,
1610 u64 num_bytes, u64 ram_bytes,
1611 u8 compression, u8 encryption,
1612 u16 other_encoding, int extent_type)
1613{
1614 struct btrfs_root *root = BTRFS_I(inode)->root;
1615 struct btrfs_file_extent_item *fi;
1616 struct btrfs_path *path;
1617 struct extent_buffer *leaf;
1618 struct btrfs_key ins;
1619 u64 hint;
1620 int ret;
1621
1622 path = btrfs_alloc_path();
1623 BUG_ON(!path);
1624
b9473439 1625 path->leave_spinning = 1;
a1ed835e
CM
1626
1627 /*
1628 * we may be replacing one extent in the tree with another.
1629 * The new extent is pinned in the extent map, and we don't want
1630 * to drop it from the cache until it is completely in the btree.
1631 *
1632 * So, tell btrfs_drop_extents to leave this extent in the cache.
1633 * the caller is expected to unpin it and allow it to be merged
1634 * with the others.
1635 */
920bbbfb
YZ
1636 ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1637 &hint, 0);
d899e052
YZ
1638 BUG_ON(ret);
1639
1640 ins.objectid = inode->i_ino;
1641 ins.offset = file_pos;
1642 ins.type = BTRFS_EXTENT_DATA_KEY;
1643 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1644 BUG_ON(ret);
1645 leaf = path->nodes[0];
1646 fi = btrfs_item_ptr(leaf, path->slots[0],
1647 struct btrfs_file_extent_item);
1648 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1649 btrfs_set_file_extent_type(leaf, fi, extent_type);
1650 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1651 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1652 btrfs_set_file_extent_offset(leaf, fi, 0);
1653 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1654 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1655 btrfs_set_file_extent_compression(leaf, fi, compression);
1656 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1657 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
b9473439
CM
1658
1659 btrfs_unlock_up_safe(path, 1);
1660 btrfs_set_lock_blocking(leaf);
1661
d899e052
YZ
1662 btrfs_mark_buffer_dirty(leaf);
1663
1664 inode_add_bytes(inode, num_bytes);
d899e052
YZ
1665
1666 ins.objectid = disk_bytenr;
1667 ins.offset = disk_num_bytes;
1668 ins.type = BTRFS_EXTENT_ITEM_KEY;
5d4f98a2
YZ
1669 ret = btrfs_alloc_reserved_file_extent(trans, root,
1670 root->root_key.objectid,
1671 inode->i_ino, file_pos, &ins);
d899e052 1672 BUG_ON(ret);
d899e052 1673 btrfs_free_path(path);
b9473439 1674
d899e052
YZ
1675 return 0;
1676}
1677
5d13a98f
CM
1678/*
1679 * helper function for btrfs_finish_ordered_io, this
1680 * just reads in some of the csum leaves to prime them into ram
1681 * before we start the transaction. It limits the amount of btree
1682 * reads required while inside the transaction.
1683 */
d352ac68
CM
1684/* as ordered data IO finishes, this gets called so we can finish
1685 * an ordered extent if the range of bytes in the file it covers are
1686 * fully written.
1687 */
211f90e6 1688static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
e6dcd2dc 1689{
e6dcd2dc
CM
1690 struct btrfs_root *root = BTRFS_I(inode)->root;
1691 struct btrfs_trans_handle *trans;
5d13a98f 1692 struct btrfs_ordered_extent *ordered_extent = NULL;
e6dcd2dc 1693 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
d899e052 1694 int compressed = 0;
e6dcd2dc
CM
1695 int ret;
1696
1697 ret = btrfs_dec_test_ordered_pending(inode, start, end - start + 1);
ba1da2f4 1698 if (!ret)
e6dcd2dc 1699 return 0;
e6dcd2dc 1700
efd049fb 1701 ordered_extent = btrfs_lookup_ordered_extent(inode, start);
e6dcd2dc 1702 BUG_ON(!ordered_extent);
efd049fb 1703
c2167754
YZ
1704 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1705 BUG_ON(!list_empty(&ordered_extent->list));
1706 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1707 if (!ret) {
1708 trans = btrfs_join_transaction(root, 1);
1709 ret = btrfs_update_inode(trans, root, inode);
1710 BUG_ON(ret);
1711 btrfs_end_transaction(trans, root);
1712 }
1713 goto out;
1714 }
e6dcd2dc
CM
1715
1716 lock_extent(io_tree, ordered_extent->file_offset,
1717 ordered_extent->file_offset + ordered_extent->len - 1,
1718 GFP_NOFS);
1719
c2167754
YZ
1720 trans = btrfs_join_transaction(root, 1);
1721
c8b97818 1722 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
d899e052
YZ
1723 compressed = 1;
1724 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1725 BUG_ON(compressed);
920bbbfb 1726 ret = btrfs_mark_extent_written(trans, inode,
d899e052
YZ
1727 ordered_extent->file_offset,
1728 ordered_extent->file_offset +
1729 ordered_extent->len);
1730 BUG_ON(ret);
1731 } else {
1732 ret = insert_reserved_file_extent(trans, inode,
1733 ordered_extent->file_offset,
1734 ordered_extent->start,
1735 ordered_extent->disk_len,
1736 ordered_extent->len,
1737 ordered_extent->len,
1738 compressed, 0, 0,
1739 BTRFS_FILE_EXTENT_REG);
a1ed835e
CM
1740 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1741 ordered_extent->file_offset,
1742 ordered_extent->len);
d899e052
YZ
1743 BUG_ON(ret);
1744 }
e6dcd2dc
CM
1745 unlock_extent(io_tree, ordered_extent->file_offset,
1746 ordered_extent->file_offset + ordered_extent->len - 1,
1747 GFP_NOFS);
1748 add_pending_csums(trans, inode, ordered_extent->file_offset,
1749 &ordered_extent->list);
1750
c2167754
YZ
1751 /* this also removes the ordered extent from the tree */
1752 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1753 ret = btrfs_update_inode(trans, root, inode);
1754 BUG_ON(ret);
1755 btrfs_end_transaction(trans, root);
1756out:
e6dcd2dc
CM
1757 /* once for us */
1758 btrfs_put_ordered_extent(ordered_extent);
1759 /* once for the tree */
1760 btrfs_put_ordered_extent(ordered_extent);
1761
e6dcd2dc
CM
1762 return 0;
1763}
1764
b2950863 1765static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
211f90e6
CM
1766 struct extent_state *state, int uptodate)
1767{
8b62b72b 1768 ClearPagePrivate2(page);
211f90e6
CM
1769 return btrfs_finish_ordered_io(page->mapping->host, start, end);
1770}
1771
d352ac68
CM
1772/*
1773 * When IO fails, either with EIO or csum verification fails, we
1774 * try other mirrors that might have a good copy of the data. This
1775 * io_failure_record is used to record state as we go through all the
1776 * mirrors. If another mirror has good data, the page is set up to date
1777 * and things continue. If a good mirror can't be found, the original
1778 * bio end_io callback is called to indicate things have failed.
1779 */
7e38326f
CM
1780struct io_failure_record {
1781 struct page *page;
1782 u64 start;
1783 u64 len;
1784 u64 logical;
d20f7043 1785 unsigned long bio_flags;
7e38326f
CM
1786 int last_mirror;
1787};
1788
b2950863 1789static int btrfs_io_failed_hook(struct bio *failed_bio,
1259ab75
CM
1790 struct page *page, u64 start, u64 end,
1791 struct extent_state *state)
7e38326f
CM
1792{
1793 struct io_failure_record *failrec = NULL;
1794 u64 private;
1795 struct extent_map *em;
1796 struct inode *inode = page->mapping->host;
1797 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
3b951516 1798 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7e38326f
CM
1799 struct bio *bio;
1800 int num_copies;
1801 int ret;
1259ab75 1802 int rw;
7e38326f
CM
1803 u64 logical;
1804
1805 ret = get_state_private(failure_tree, start, &private);
1806 if (ret) {
7e38326f
CM
1807 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1808 if (!failrec)
1809 return -ENOMEM;
1810 failrec->start = start;
1811 failrec->len = end - start + 1;
1812 failrec->last_mirror = 0;
d20f7043 1813 failrec->bio_flags = 0;
7e38326f 1814
890871be 1815 read_lock(&em_tree->lock);
3b951516
CM
1816 em = lookup_extent_mapping(em_tree, start, failrec->len);
1817 if (em->start > start || em->start + em->len < start) {
1818 free_extent_map(em);
1819 em = NULL;
1820 }
890871be 1821 read_unlock(&em_tree->lock);
7e38326f
CM
1822
1823 if (!em || IS_ERR(em)) {
1824 kfree(failrec);
1825 return -EIO;
1826 }
1827 logical = start - em->start;
1828 logical = em->block_start + logical;
d20f7043
CM
1829 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1830 logical = em->block_start;
1831 failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1832 }
7e38326f
CM
1833 failrec->logical = logical;
1834 free_extent_map(em);
1835 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1836 EXTENT_DIRTY, GFP_NOFS);
587f7704
CM
1837 set_state_private(failure_tree, start,
1838 (u64)(unsigned long)failrec);
7e38326f 1839 } else {
587f7704 1840 failrec = (struct io_failure_record *)(unsigned long)private;
7e38326f
CM
1841 }
1842 num_copies = btrfs_num_copies(
1843 &BTRFS_I(inode)->root->fs_info->mapping_tree,
1844 failrec->logical, failrec->len);
1845 failrec->last_mirror++;
1846 if (!state) {
cad321ad 1847 spin_lock(&BTRFS_I(inode)->io_tree.lock);
7e38326f
CM
1848 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1849 failrec->start,
1850 EXTENT_LOCKED);
1851 if (state && state->start != failrec->start)
1852 state = NULL;
cad321ad 1853 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
7e38326f
CM
1854 }
1855 if (!state || failrec->last_mirror > num_copies) {
1856 set_state_private(failure_tree, failrec->start, 0);
1857 clear_extent_bits(failure_tree, failrec->start,
1858 failrec->start + failrec->len - 1,
1859 EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1860 kfree(failrec);
1861 return -EIO;
1862 }
1863 bio = bio_alloc(GFP_NOFS, 1);
1864 bio->bi_private = state;
1865 bio->bi_end_io = failed_bio->bi_end_io;
1866 bio->bi_sector = failrec->logical >> 9;
1867 bio->bi_bdev = failed_bio->bi_bdev;
e1c4b745 1868 bio->bi_size = 0;
d20f7043 1869
7e38326f 1870 bio_add_page(bio, page, failrec->len, start - page_offset(page));
1259ab75
CM
1871 if (failed_bio->bi_rw & (1 << BIO_RW))
1872 rw = WRITE;
1873 else
1874 rw = READ;
1875
1876 BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
c8b97818 1877 failrec->last_mirror,
d20f7043 1878 failrec->bio_flags);
1259ab75
CM
1879 return 0;
1880}
1881
d352ac68
CM
1882/*
1883 * each time an IO finishes, we do a fast check in the IO failure tree
1884 * to see if we need to process or clean up an io_failure_record
1885 */
b2950863 1886static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1259ab75
CM
1887{
1888 u64 private;
1889 u64 private_failure;
1890 struct io_failure_record *failure;
1891 int ret;
1892
1893 private = 0;
1894 if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1895 (u64)-1, 1, EXTENT_DIRTY)) {
1896 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1897 start, &private_failure);
1898 if (ret == 0) {
1899 failure = (struct io_failure_record *)(unsigned long)
1900 private_failure;
1901 set_state_private(&BTRFS_I(inode)->io_failure_tree,
1902 failure->start, 0);
1903 clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1904 failure->start,
1905 failure->start + failure->len - 1,
1906 EXTENT_DIRTY | EXTENT_LOCKED,
1907 GFP_NOFS);
1908 kfree(failure);
1909 }
1910 }
7e38326f
CM
1911 return 0;
1912}
1913
d352ac68
CM
1914/*
1915 * when reads are done, we need to check csums to verify the data is correct
1916 * if there's a match, we allow the bio to finish. If not, we go through
1917 * the io_failure_record routines to find good copies
1918 */
b2950863 1919static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
70dec807 1920 struct extent_state *state)
07157aac 1921{
35ebb934 1922 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
07157aac 1923 struct inode *inode = page->mapping->host;
d1310b2e 1924 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
07157aac 1925 char *kaddr;
aadfeb6e 1926 u64 private = ~(u32)0;
07157aac 1927 int ret;
ff79f819
CM
1928 struct btrfs_root *root = BTRFS_I(inode)->root;
1929 u32 csum = ~(u32)0;
d1310b2e 1930
d20f7043
CM
1931 if (PageChecked(page)) {
1932 ClearPageChecked(page);
1933 goto good;
1934 }
6cbff00f
CH
1935
1936 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
17d217fe
YZ
1937 return 0;
1938
1939 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
9655d298 1940 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
17d217fe
YZ
1941 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1942 GFP_NOFS);
b6cda9bc 1943 return 0;
17d217fe 1944 }
d20f7043 1945
c2e639f0 1946 if (state && state->start == start) {
70dec807
CM
1947 private = state->private;
1948 ret = 0;
1949 } else {
1950 ret = get_state_private(io_tree, start, &private);
1951 }
9ab86c8e 1952 kaddr = kmap_atomic(page, KM_USER0);
d397712b 1953 if (ret)
07157aac 1954 goto zeroit;
d397712b 1955
ff79f819
CM
1956 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
1957 btrfs_csum_final(csum, (char *)&csum);
d397712b 1958 if (csum != private)
07157aac 1959 goto zeroit;
d397712b 1960
9ab86c8e 1961 kunmap_atomic(kaddr, KM_USER0);
d20f7043 1962good:
7e38326f
CM
1963 /* if the io failure tree for this inode is non-empty,
1964 * check to see if we've recovered from a failed IO
1965 */
1259ab75 1966 btrfs_clean_io_failures(inode, start);
07157aac
CM
1967 return 0;
1968
1969zeroit:
193f284d
CM
1970 if (printk_ratelimit()) {
1971 printk(KERN_INFO "btrfs csum failed ino %lu off %llu csum %u "
1972 "private %llu\n", page->mapping->host->i_ino,
1973 (unsigned long long)start, csum,
1974 (unsigned long long)private);
1975 }
db94535d
CM
1976 memset(kaddr + offset, 1, end - start + 1);
1977 flush_dcache_page(page);
9ab86c8e 1978 kunmap_atomic(kaddr, KM_USER0);
3b951516
CM
1979 if (private == 0)
1980 return 0;
7e38326f 1981 return -EIO;
07157aac 1982}
b888db2b 1983
24bbcf04
YZ
1984struct delayed_iput {
1985 struct list_head list;
1986 struct inode *inode;
1987};
1988
1989void btrfs_add_delayed_iput(struct inode *inode)
1990{
1991 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1992 struct delayed_iput *delayed;
1993
1994 if (atomic_add_unless(&inode->i_count, -1, 1))
1995 return;
1996
1997 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
1998 delayed->inode = inode;
1999
2000 spin_lock(&fs_info->delayed_iput_lock);
2001 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2002 spin_unlock(&fs_info->delayed_iput_lock);
2003}
2004
2005void btrfs_run_delayed_iputs(struct btrfs_root *root)
2006{
2007 LIST_HEAD(list);
2008 struct btrfs_fs_info *fs_info = root->fs_info;
2009 struct delayed_iput *delayed;
2010 int empty;
2011
2012 spin_lock(&fs_info->delayed_iput_lock);
2013 empty = list_empty(&fs_info->delayed_iputs);
2014 spin_unlock(&fs_info->delayed_iput_lock);
2015 if (empty)
2016 return;
2017
2018 down_read(&root->fs_info->cleanup_work_sem);
2019 spin_lock(&fs_info->delayed_iput_lock);
2020 list_splice_init(&fs_info->delayed_iputs, &list);
2021 spin_unlock(&fs_info->delayed_iput_lock);
2022
2023 while (!list_empty(&list)) {
2024 delayed = list_entry(list.next, struct delayed_iput, list);
2025 list_del(&delayed->list);
2026 iput(delayed->inode);
2027 kfree(delayed);
2028 }
2029 up_read(&root->fs_info->cleanup_work_sem);
2030}
2031
7b128766
JB
2032/*
2033 * This creates an orphan entry for the given inode in case something goes
2034 * wrong in the middle of an unlink/truncate.
2035 */
2036int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2037{
2038 struct btrfs_root *root = BTRFS_I(inode)->root;
2039 int ret = 0;
2040
bcc63abb 2041 spin_lock(&root->list_lock);
7b128766
JB
2042
2043 /* already on the orphan list, we're good */
2044 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
bcc63abb 2045 spin_unlock(&root->list_lock);
7b128766
JB
2046 return 0;
2047 }
2048
2049 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2050
bcc63abb 2051 spin_unlock(&root->list_lock);
7b128766
JB
2052
2053 /*
2054 * insert an orphan item to track this unlinked/truncated file
2055 */
2056 ret = btrfs_insert_orphan_item(trans, root, inode->i_ino);
2057
2058 return ret;
2059}
2060
2061/*
2062 * We have done the truncate/delete so we can go ahead and remove the orphan
2063 * item for this particular inode.
2064 */
2065int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2066{
2067 struct btrfs_root *root = BTRFS_I(inode)->root;
2068 int ret = 0;
2069
bcc63abb 2070 spin_lock(&root->list_lock);
7b128766
JB
2071
2072 if (list_empty(&BTRFS_I(inode)->i_orphan)) {
bcc63abb 2073 spin_unlock(&root->list_lock);
7b128766
JB
2074 return 0;
2075 }
2076
2077 list_del_init(&BTRFS_I(inode)->i_orphan);
2078 if (!trans) {
bcc63abb 2079 spin_unlock(&root->list_lock);
7b128766
JB
2080 return 0;
2081 }
2082
bcc63abb 2083 spin_unlock(&root->list_lock);
7b128766
JB
2084
2085 ret = btrfs_del_orphan_item(trans, root, inode->i_ino);
2086
2087 return ret;
2088}
2089
2090/*
2091 * this cleans up any orphans that may be left on the list from the last use
2092 * of this root.
2093 */
2094void btrfs_orphan_cleanup(struct btrfs_root *root)
2095{
2096 struct btrfs_path *path;
2097 struct extent_buffer *leaf;
2098 struct btrfs_item *item;
2099 struct btrfs_key key, found_key;
2100 struct btrfs_trans_handle *trans;
2101 struct inode *inode;
2102 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2103
c71bf099 2104 if (!xchg(&root->clean_orphans, 0))
7b128766 2105 return;
c71bf099
YZ
2106
2107 path = btrfs_alloc_path();
2108 BUG_ON(!path);
7b128766
JB
2109 path->reada = -1;
2110
2111 key.objectid = BTRFS_ORPHAN_OBJECTID;
2112 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2113 key.offset = (u64)-1;
2114
7b128766
JB
2115 while (1) {
2116 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2117 if (ret < 0) {
2118 printk(KERN_ERR "Error searching slot for orphan: %d"
2119 "\n", ret);
2120 break;
2121 }
2122
2123 /*
2124 * if ret == 0 means we found what we were searching for, which
2125 * is weird, but possible, so only screw with path if we didnt
2126 * find the key and see if we have stuff that matches
2127 */
2128 if (ret > 0) {
2129 if (path->slots[0] == 0)
2130 break;
2131 path->slots[0]--;
2132 }
2133
2134 /* pull out the item */
2135 leaf = path->nodes[0];
2136 item = btrfs_item_nr(leaf, path->slots[0]);
2137 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2138
2139 /* make sure the item matches what we want */
2140 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2141 break;
2142 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2143 break;
2144
2145 /* release the path since we're done with it */
2146 btrfs_release_path(root, path);
2147
2148 /*
2149 * this is where we are basically btrfs_lookup, without the
2150 * crossing root thing. we store the inode number in the
2151 * offset of the orphan item.
2152 */
5d4f98a2
YZ
2153 found_key.objectid = found_key.offset;
2154 found_key.type = BTRFS_INODE_ITEM_KEY;
2155 found_key.offset = 0;
73f73415 2156 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
5d4f98a2 2157 if (IS_ERR(inode))
7b128766
JB
2158 break;
2159
7b128766
JB
2160 /*
2161 * add this inode to the orphan list so btrfs_orphan_del does
2162 * the proper thing when we hit it
2163 */
bcc63abb 2164 spin_lock(&root->list_lock);
7b128766 2165 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
bcc63abb 2166 spin_unlock(&root->list_lock);
7b128766
JB
2167
2168 /*
2169 * if this is a bad inode, means we actually succeeded in
2170 * removing the inode, but not the orphan record, which means
2171 * we need to manually delete the orphan since iput will just
2172 * do a destroy_inode
2173 */
2174 if (is_bad_inode(inode)) {
5b21f2ed 2175 trans = btrfs_start_transaction(root, 1);
7b128766 2176 btrfs_orphan_del(trans, inode);
5b21f2ed 2177 btrfs_end_transaction(trans, root);
7b128766
JB
2178 iput(inode);
2179 continue;
2180 }
2181
2182 /* if we have links, this was a truncate, lets do that */
2183 if (inode->i_nlink) {
2184 nr_truncate++;
2185 btrfs_truncate(inode);
2186 } else {
2187 nr_unlink++;
2188 }
2189
2190 /* this will do delete_inode and everything for us */
2191 iput(inode);
2192 }
2193
2194 if (nr_unlink)
2195 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2196 if (nr_truncate)
2197 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2198
2199 btrfs_free_path(path);
7b128766
JB
2200}
2201
46a53cca
CM
2202/*
2203 * very simple check to peek ahead in the leaf looking for xattrs. If we
2204 * don't find any xattrs, we know there can't be any acls.
2205 *
2206 * slot is the slot the inode is in, objectid is the objectid of the inode
2207 */
2208static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2209 int slot, u64 objectid)
2210{
2211 u32 nritems = btrfs_header_nritems(leaf);
2212 struct btrfs_key found_key;
2213 int scanned = 0;
2214
2215 slot++;
2216 while (slot < nritems) {
2217 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2218
2219 /* we found a different objectid, there must not be acls */
2220 if (found_key.objectid != objectid)
2221 return 0;
2222
2223 /* we found an xattr, assume we've got an acl */
2224 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2225 return 1;
2226
2227 /*
2228 * we found a key greater than an xattr key, there can't
2229 * be any acls later on
2230 */
2231 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2232 return 0;
2233
2234 slot++;
2235 scanned++;
2236
2237 /*
2238 * it goes inode, inode backrefs, xattrs, extents,
2239 * so if there are a ton of hard links to an inode there can
2240 * be a lot of backrefs. Don't waste time searching too hard,
2241 * this is just an optimization
2242 */
2243 if (scanned >= 8)
2244 break;
2245 }
2246 /* we hit the end of the leaf before we found an xattr or
2247 * something larger than an xattr. We have to assume the inode
2248 * has acls
2249 */
2250 return 1;
2251}
2252
d352ac68
CM
2253/*
2254 * read an inode from the btree into the in-memory inode
2255 */
5d4f98a2 2256static void btrfs_read_locked_inode(struct inode *inode)
39279cc3
CM
2257{
2258 struct btrfs_path *path;
5f39d397 2259 struct extent_buffer *leaf;
39279cc3 2260 struct btrfs_inode_item *inode_item;
0b86a832 2261 struct btrfs_timespec *tspec;
39279cc3
CM
2262 struct btrfs_root *root = BTRFS_I(inode)->root;
2263 struct btrfs_key location;
46a53cca 2264 int maybe_acls;
39279cc3 2265 u64 alloc_group_block;
618e21d5 2266 u32 rdev;
39279cc3
CM
2267 int ret;
2268
2269 path = btrfs_alloc_path();
2270 BUG_ON(!path);
39279cc3 2271 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
dc17ff8f 2272
39279cc3 2273 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
5f39d397 2274 if (ret)
39279cc3 2275 goto make_bad;
39279cc3 2276
5f39d397
CM
2277 leaf = path->nodes[0];
2278 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2279 struct btrfs_inode_item);
2280
2281 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2282 inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2283 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2284 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
dbe674a9 2285 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
5f39d397
CM
2286
2287 tspec = btrfs_inode_atime(inode_item);
2288 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2289 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2290
2291 tspec = btrfs_inode_mtime(inode_item);
2292 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2293 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2294
2295 tspec = btrfs_inode_ctime(inode_item);
2296 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2297 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2298
a76a3cd4 2299 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
e02119d5 2300 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
c3027eb5 2301 BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
e02119d5 2302 inode->i_generation = BTRFS_I(inode)->generation;
618e21d5 2303 inode->i_rdev = 0;
5f39d397
CM
2304 rdev = btrfs_inode_rdev(leaf, inode_item);
2305
aec7477b 2306 BTRFS_I(inode)->index_cnt = (u64)-1;
d2fb3437 2307 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
aec7477b 2308
5f39d397 2309 alloc_group_block = btrfs_inode_block_group(leaf, inode_item);
b4ce94de 2310
46a53cca
CM
2311 /*
2312 * try to precache a NULL acl entry for files that don't have
2313 * any xattrs or acls
2314 */
2315 maybe_acls = acls_after_inode_item(leaf, path->slots[0], inode->i_ino);
72c04902
AV
2316 if (!maybe_acls)
2317 cache_no_acl(inode);
46a53cca 2318
d2fb3437
YZ
2319 BTRFS_I(inode)->block_group = btrfs_find_block_group(root, 0,
2320 alloc_group_block, 0);
39279cc3
CM
2321 btrfs_free_path(path);
2322 inode_item = NULL;
2323
39279cc3 2324 switch (inode->i_mode & S_IFMT) {
39279cc3
CM
2325 case S_IFREG:
2326 inode->i_mapping->a_ops = &btrfs_aops;
04160088 2327 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d1310b2e 2328 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3
CM
2329 inode->i_fop = &btrfs_file_operations;
2330 inode->i_op = &btrfs_file_inode_operations;
2331 break;
2332 case S_IFDIR:
2333 inode->i_fop = &btrfs_dir_file_operations;
2334 if (root == root->fs_info->tree_root)
2335 inode->i_op = &btrfs_dir_ro_inode_operations;
2336 else
2337 inode->i_op = &btrfs_dir_inode_operations;
2338 break;
2339 case S_IFLNK:
2340 inode->i_op = &btrfs_symlink_inode_operations;
2341 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 2342 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3 2343 break;
618e21d5 2344 default:
0279b4cd 2345 inode->i_op = &btrfs_special_inode_operations;
618e21d5
JB
2346 init_special_inode(inode, inode->i_mode, rdev);
2347 break;
39279cc3 2348 }
6cbff00f
CH
2349
2350 btrfs_update_iflags(inode);
39279cc3
CM
2351 return;
2352
2353make_bad:
39279cc3 2354 btrfs_free_path(path);
39279cc3
CM
2355 make_bad_inode(inode);
2356}
2357
d352ac68
CM
2358/*
2359 * given a leaf and an inode, copy the inode fields into the leaf
2360 */
e02119d5
CM
2361static void fill_inode_item(struct btrfs_trans_handle *trans,
2362 struct extent_buffer *leaf,
5f39d397 2363 struct btrfs_inode_item *item,
39279cc3
CM
2364 struct inode *inode)
2365{
5f39d397
CM
2366 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2367 btrfs_set_inode_gid(leaf, item, inode->i_gid);
dbe674a9 2368 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
5f39d397
CM
2369 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2370 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2371
2372 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2373 inode->i_atime.tv_sec);
2374 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2375 inode->i_atime.tv_nsec);
2376
2377 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2378 inode->i_mtime.tv_sec);
2379 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2380 inode->i_mtime.tv_nsec);
2381
2382 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2383 inode->i_ctime.tv_sec);
2384 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2385 inode->i_ctime.tv_nsec);
2386
a76a3cd4 2387 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
e02119d5 2388 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
c3027eb5 2389 btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
e02119d5 2390 btrfs_set_inode_transid(leaf, item, trans->transid);
5f39d397 2391 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
b98b6767 2392 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
d2fb3437 2393 btrfs_set_inode_block_group(leaf, item, BTRFS_I(inode)->block_group);
39279cc3
CM
2394}
2395
d352ac68
CM
2396/*
2397 * copy everything in the in-memory inode into the btree.
2398 */
d397712b
CM
2399noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2400 struct btrfs_root *root, struct inode *inode)
39279cc3
CM
2401{
2402 struct btrfs_inode_item *inode_item;
2403 struct btrfs_path *path;
5f39d397 2404 struct extent_buffer *leaf;
39279cc3
CM
2405 int ret;
2406
2407 path = btrfs_alloc_path();
2408 BUG_ON(!path);
b9473439 2409 path->leave_spinning = 1;
39279cc3
CM
2410 ret = btrfs_lookup_inode(trans, root, path,
2411 &BTRFS_I(inode)->location, 1);
2412 if (ret) {
2413 if (ret > 0)
2414 ret = -ENOENT;
2415 goto failed;
2416 }
2417
b4ce94de 2418 btrfs_unlock_up_safe(path, 1);
5f39d397
CM
2419 leaf = path->nodes[0];
2420 inode_item = btrfs_item_ptr(leaf, path->slots[0],
39279cc3
CM
2421 struct btrfs_inode_item);
2422
e02119d5 2423 fill_inode_item(trans, leaf, inode_item, inode);
5f39d397 2424 btrfs_mark_buffer_dirty(leaf);
15ee9bc7 2425 btrfs_set_inode_last_trans(trans, inode);
39279cc3
CM
2426 ret = 0;
2427failed:
39279cc3
CM
2428 btrfs_free_path(path);
2429 return ret;
2430}
2431
2432
d352ac68
CM
2433/*
2434 * unlink helper that gets used here in inode.c and in the tree logging
2435 * recovery code. It remove a link in a directory with a given name, and
2436 * also drops the back refs in the inode to the directory
2437 */
e02119d5
CM
2438int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2439 struct btrfs_root *root,
2440 struct inode *dir, struct inode *inode,
2441 const char *name, int name_len)
39279cc3
CM
2442{
2443 struct btrfs_path *path;
39279cc3 2444 int ret = 0;
5f39d397 2445 struct extent_buffer *leaf;
39279cc3 2446 struct btrfs_dir_item *di;
5f39d397 2447 struct btrfs_key key;
aec7477b 2448 u64 index;
39279cc3
CM
2449
2450 path = btrfs_alloc_path();
54aa1f4d
CM
2451 if (!path) {
2452 ret = -ENOMEM;
2453 goto err;
2454 }
2455
b9473439 2456 path->leave_spinning = 1;
39279cc3
CM
2457 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2458 name, name_len, -1);
2459 if (IS_ERR(di)) {
2460 ret = PTR_ERR(di);
2461 goto err;
2462 }
2463 if (!di) {
2464 ret = -ENOENT;
2465 goto err;
2466 }
5f39d397
CM
2467 leaf = path->nodes[0];
2468 btrfs_dir_item_key_to_cpu(leaf, di, &key);
39279cc3 2469 ret = btrfs_delete_one_dir_name(trans, root, path, di);
54aa1f4d
CM
2470 if (ret)
2471 goto err;
39279cc3
CM
2472 btrfs_release_path(root, path);
2473
aec7477b 2474 ret = btrfs_del_inode_ref(trans, root, name, name_len,
e02119d5
CM
2475 inode->i_ino,
2476 dir->i_ino, &index);
aec7477b 2477 if (ret) {
d397712b 2478 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
aec7477b 2479 "inode %lu parent %lu\n", name_len, name,
e02119d5 2480 inode->i_ino, dir->i_ino);
aec7477b
JB
2481 goto err;
2482 }
2483
39279cc3 2484 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
aec7477b 2485 index, name, name_len, -1);
39279cc3
CM
2486 if (IS_ERR(di)) {
2487 ret = PTR_ERR(di);
2488 goto err;
2489 }
2490 if (!di) {
2491 ret = -ENOENT;
2492 goto err;
2493 }
2494 ret = btrfs_delete_one_dir_name(trans, root, path, di);
925baedd 2495 btrfs_release_path(root, path);
39279cc3 2496
e02119d5
CM
2497 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2498 inode, dir->i_ino);
49eb7e46 2499 BUG_ON(ret != 0 && ret != -ENOENT);
e02119d5
CM
2500
2501 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2502 dir, index);
2503 BUG_ON(ret);
39279cc3
CM
2504err:
2505 btrfs_free_path(path);
e02119d5
CM
2506 if (ret)
2507 goto out;
2508
2509 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2510 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2511 btrfs_update_inode(trans, root, dir);
2512 btrfs_drop_nlink(inode);
2513 ret = btrfs_update_inode(trans, root, inode);
e02119d5 2514out:
39279cc3
CM
2515 return ret;
2516}
2517
2518static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2519{
2520 struct btrfs_root *root;
2521 struct btrfs_trans_handle *trans;
7b128766 2522 struct inode *inode = dentry->d_inode;
39279cc3 2523 int ret;
1832a6d5 2524 unsigned long nr = 0;
39279cc3
CM
2525
2526 root = BTRFS_I(dir)->root;
1832a6d5 2527
5df6a9f6
JB
2528 /*
2529 * 5 items for unlink inode
2530 * 1 for orphan
2531 */
2532 ret = btrfs_reserve_metadata_space(root, 6);
2533 if (ret)
2534 return ret;
2535
39279cc3 2536 trans = btrfs_start_transaction(root, 1);
5df6a9f6
JB
2537 if (IS_ERR(trans)) {
2538 btrfs_unreserve_metadata_space(root, 6);
2539 return PTR_ERR(trans);
2540 }
5f39d397 2541
39279cc3 2542 btrfs_set_trans_block_group(trans, dir);
12fcfd22
CM
2543
2544 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2545
e02119d5
CM
2546 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2547 dentry->d_name.name, dentry->d_name.len);
7b128766
JB
2548
2549 if (inode->i_nlink == 0)
2550 ret = btrfs_orphan_add(trans, inode);
2551
d3c2fdcf 2552 nr = trans->blocks_used;
5f39d397 2553
89ce8a63 2554 btrfs_end_transaction_throttle(trans, root);
5df6a9f6 2555 btrfs_unreserve_metadata_space(root, 6);
d3c2fdcf 2556 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
2557 return ret;
2558}
2559
4df27c4d
YZ
2560int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
2561 struct btrfs_root *root,
2562 struct inode *dir, u64 objectid,
2563 const char *name, int name_len)
2564{
2565 struct btrfs_path *path;
2566 struct extent_buffer *leaf;
2567 struct btrfs_dir_item *di;
2568 struct btrfs_key key;
2569 u64 index;
2570 int ret;
2571
2572 path = btrfs_alloc_path();
2573 if (!path)
2574 return -ENOMEM;
2575
2576 di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
2577 name, name_len, -1);
2578 BUG_ON(!di || IS_ERR(di));
2579
2580 leaf = path->nodes[0];
2581 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2582 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2583 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2584 BUG_ON(ret);
2585 btrfs_release_path(root, path);
2586
2587 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
2588 objectid, root->root_key.objectid,
2589 dir->i_ino, &index, name, name_len);
2590 if (ret < 0) {
2591 BUG_ON(ret != -ENOENT);
2592 di = btrfs_search_dir_index_item(root, path, dir->i_ino,
2593 name, name_len);
2594 BUG_ON(!di || IS_ERR(di));
2595
2596 leaf = path->nodes[0];
2597 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2598 btrfs_release_path(root, path);
2599 index = key.offset;
2600 }
2601
2602 di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
2603 index, name, name_len, -1);
2604 BUG_ON(!di || IS_ERR(di));
2605
2606 leaf = path->nodes[0];
2607 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2608 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
2609 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2610 BUG_ON(ret);
2611 btrfs_release_path(root, path);
2612
2613 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2614 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2615 ret = btrfs_update_inode(trans, root, dir);
2616 BUG_ON(ret);
2617 dir->i_sb->s_dirt = 1;
2618
2619 btrfs_free_path(path);
2620 return 0;
2621}
2622
39279cc3
CM
2623static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
2624{
2625 struct inode *inode = dentry->d_inode;
1832a6d5 2626 int err = 0;
39279cc3
CM
2627 int ret;
2628 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3 2629 struct btrfs_trans_handle *trans;
1832a6d5 2630 unsigned long nr = 0;
39279cc3 2631
3394e160 2632 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
4df27c4d 2633 inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
134d4512
Y
2634 return -ENOTEMPTY;
2635
5df6a9f6
JB
2636 ret = btrfs_reserve_metadata_space(root, 5);
2637 if (ret)
2638 return ret;
2639
39279cc3 2640 trans = btrfs_start_transaction(root, 1);
5df6a9f6
JB
2641 if (IS_ERR(trans)) {
2642 btrfs_unreserve_metadata_space(root, 5);
2643 return PTR_ERR(trans);
2644 }
2645
39279cc3 2646 btrfs_set_trans_block_group(trans, dir);
39279cc3 2647
4df27c4d
YZ
2648 if (unlikely(inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
2649 err = btrfs_unlink_subvol(trans, root, dir,
2650 BTRFS_I(inode)->location.objectid,
2651 dentry->d_name.name,
2652 dentry->d_name.len);
2653 goto out;
2654 }
2655
7b128766
JB
2656 err = btrfs_orphan_add(trans, inode);
2657 if (err)
4df27c4d 2658 goto out;
7b128766 2659
39279cc3 2660 /* now the directory is empty */
e02119d5
CM
2661 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
2662 dentry->d_name.name, dentry->d_name.len);
d397712b 2663 if (!err)
dbe674a9 2664 btrfs_i_size_write(inode, 0);
4df27c4d 2665out:
d3c2fdcf 2666 nr = trans->blocks_used;
89ce8a63 2667 ret = btrfs_end_transaction_throttle(trans, root);
5df6a9f6 2668 btrfs_unreserve_metadata_space(root, 5);
d3c2fdcf 2669 btrfs_btree_balance_dirty(root, nr);
3954401f 2670
39279cc3
CM
2671 if (ret && !err)
2672 err = ret;
2673 return err;
2674}
2675
d20f7043 2676#if 0
323ac95b
CM
2677/*
2678 * when truncating bytes in a file, it is possible to avoid reading
2679 * the leaves that contain only checksum items. This can be the
2680 * majority of the IO required to delete a large file, but it must
2681 * be done carefully.
2682 *
2683 * The keys in the level just above the leaves are checked to make sure
2684 * the lowest key in a given leaf is a csum key, and starts at an offset
2685 * after the new size.
2686 *
2687 * Then the key for the next leaf is checked to make sure it also has
2688 * a checksum item for the same file. If it does, we know our target leaf
2689 * contains only checksum items, and it can be safely freed without reading
2690 * it.
2691 *
2692 * This is just an optimization targeted at large files. It may do
2693 * nothing. It will return 0 unless things went badly.
2694 */
2695static noinline int drop_csum_leaves(struct btrfs_trans_handle *trans,
2696 struct btrfs_root *root,
2697 struct btrfs_path *path,
2698 struct inode *inode, u64 new_size)
2699{
2700 struct btrfs_key key;
2701 int ret;
2702 int nritems;
2703 struct btrfs_key found_key;
2704 struct btrfs_key other_key;
5b84e8d6
YZ
2705 struct btrfs_leaf_ref *ref;
2706 u64 leaf_gen;
2707 u64 leaf_start;
323ac95b
CM
2708
2709 path->lowest_level = 1;
2710 key.objectid = inode->i_ino;
2711 key.type = BTRFS_CSUM_ITEM_KEY;
2712 key.offset = new_size;
2713again:
2714 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2715 if (ret < 0)
2716 goto out;
2717
2718 if (path->nodes[1] == NULL) {
2719 ret = 0;
2720 goto out;
2721 }
2722 ret = 0;
2723 btrfs_node_key_to_cpu(path->nodes[1], &found_key, path->slots[1]);
2724 nritems = btrfs_header_nritems(path->nodes[1]);
2725
2726 if (!nritems)
2727 goto out;
2728
2729 if (path->slots[1] >= nritems)
2730 goto next_node;
2731
2732 /* did we find a key greater than anything we want to delete? */
2733 if (found_key.objectid > inode->i_ino ||
2734 (found_key.objectid == inode->i_ino && found_key.type > key.type))
2735 goto out;
2736
2737 /* we check the next key in the node to make sure the leave contains
2738 * only checksum items. This comparison doesn't work if our
2739 * leaf is the last one in the node
2740 */
2741 if (path->slots[1] + 1 >= nritems) {
2742next_node:
2743 /* search forward from the last key in the node, this
2744 * will bring us into the next node in the tree
2745 */
2746 btrfs_node_key_to_cpu(path->nodes[1], &found_key, nritems - 1);
2747
2748 /* unlikely, but we inc below, so check to be safe */
2749 if (found_key.offset == (u64)-1)
2750 goto out;
2751
2752 /* search_forward needs a path with locks held, do the
2753 * search again for the original key. It is possible
2754 * this will race with a balance and return a path that
2755 * we could modify, but this drop is just an optimization
2756 * and is allowed to miss some leaves.
2757 */
2758 btrfs_release_path(root, path);
2759 found_key.offset++;
2760
2761 /* setup a max key for search_forward */
2762 other_key.offset = (u64)-1;
2763 other_key.type = key.type;
2764 other_key.objectid = key.objectid;
2765
2766 path->keep_locks = 1;
2767 ret = btrfs_search_forward(root, &found_key, &other_key,
2768 path, 0, 0);
2769 path->keep_locks = 0;
2770 if (ret || found_key.objectid != key.objectid ||
2771 found_key.type != key.type) {
2772 ret = 0;
2773 goto out;
2774 }
2775
2776 key.offset = found_key.offset;
2777 btrfs_release_path(root, path);
2778 cond_resched();
2779 goto again;
2780 }
2781
2782 /* we know there's one more slot after us in the tree,
2783 * read that key so we can verify it is also a checksum item
2784 */
2785 btrfs_node_key_to_cpu(path->nodes[1], &other_key, path->slots[1] + 1);
2786
2787 if (found_key.objectid < inode->i_ino)
2788 goto next_key;
2789
2790 if (found_key.type != key.type || found_key.offset < new_size)
2791 goto next_key;
2792
2793 /*
2794 * if the key for the next leaf isn't a csum key from this objectid,
2795 * we can't be sure there aren't good items inside this leaf.
2796 * Bail out
2797 */
2798 if (other_key.objectid != inode->i_ino || other_key.type != key.type)
2799 goto out;
2800
5b84e8d6
YZ
2801 leaf_start = btrfs_node_blockptr(path->nodes[1], path->slots[1]);
2802 leaf_gen = btrfs_node_ptr_generation(path->nodes[1], path->slots[1]);
323ac95b
CM
2803 /*
2804 * it is safe to delete this leaf, it contains only
2805 * csum items from this inode at an offset >= new_size
2806 */
5b84e8d6 2807 ret = btrfs_del_leaf(trans, root, path, leaf_start);
323ac95b
CM
2808 BUG_ON(ret);
2809
5b84e8d6
YZ
2810 if (root->ref_cows && leaf_gen < trans->transid) {
2811 ref = btrfs_alloc_leaf_ref(root, 0);
2812 if (ref) {
2813 ref->root_gen = root->root_key.offset;
2814 ref->bytenr = leaf_start;
2815 ref->owner = 0;
2816 ref->generation = leaf_gen;
2817 ref->nritems = 0;
2818
bd56b302
CM
2819 btrfs_sort_leaf_ref(ref);
2820
5b84e8d6
YZ
2821 ret = btrfs_add_leaf_ref(root, ref, 0);
2822 WARN_ON(ret);
2823 btrfs_free_leaf_ref(root, ref);
2824 } else {
2825 WARN_ON(1);
2826 }
2827 }
323ac95b
CM
2828next_key:
2829 btrfs_release_path(root, path);
2830
2831 if (other_key.objectid == inode->i_ino &&
2832 other_key.type == key.type && other_key.offset > key.offset) {
2833 key.offset = other_key.offset;
2834 cond_resched();
2835 goto again;
2836 }
2837 ret = 0;
2838out:
2839 /* fixup any changes we've made to the path */
2840 path->lowest_level = 0;
2841 path->keep_locks = 0;
2842 btrfs_release_path(root, path);
2843 return ret;
2844}
2845
d20f7043
CM
2846#endif
2847
39279cc3
CM
2848/*
2849 * this can truncate away extent items, csum items and directory items.
2850 * It starts at a high offset and removes keys until it can't find
d352ac68 2851 * any higher than new_size
39279cc3
CM
2852 *
2853 * csum items that cross the new i_size are truncated to the new size
2854 * as well.
7b128766
JB
2855 *
2856 * min_type is the minimum key type to truncate down to. If set to 0, this
2857 * will kill all the items on this inode, including the INODE_ITEM_KEY.
39279cc3 2858 */
8082510e
YZ
2859int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
2860 struct btrfs_root *root,
2861 struct inode *inode,
2862 u64 new_size, u32 min_type)
39279cc3 2863{
39279cc3 2864 struct btrfs_path *path;
5f39d397 2865 struct extent_buffer *leaf;
39279cc3 2866 struct btrfs_file_extent_item *fi;
8082510e
YZ
2867 struct btrfs_key key;
2868 struct btrfs_key found_key;
39279cc3 2869 u64 extent_start = 0;
db94535d 2870 u64 extent_num_bytes = 0;
5d4f98a2 2871 u64 extent_offset = 0;
39279cc3 2872 u64 item_end = 0;
8082510e
YZ
2873 u64 mask = root->sectorsize - 1;
2874 u32 found_type = (u8)-1;
39279cc3
CM
2875 int found_extent;
2876 int del_item;
85e21bac
CM
2877 int pending_del_nr = 0;
2878 int pending_del_slot = 0;
179e29e4 2879 int extent_type = -1;
771ed689 2880 int encoding;
8082510e
YZ
2881 int ret;
2882 int err = 0;
2883
2884 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
39279cc3 2885
e02119d5 2886 if (root->ref_cows)
5b21f2ed 2887 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
8082510e 2888
39279cc3
CM
2889 path = btrfs_alloc_path();
2890 BUG_ON(!path);
33c17ad5 2891 path->reada = -1;
5f39d397 2892
39279cc3
CM
2893 key.objectid = inode->i_ino;
2894 key.offset = (u64)-1;
5f39d397
CM
2895 key.type = (u8)-1;
2896
85e21bac 2897search_again:
b9473439 2898 path->leave_spinning = 1;
85e21bac 2899 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8082510e
YZ
2900 if (ret < 0) {
2901 err = ret;
2902 goto out;
2903 }
d397712b 2904
85e21bac 2905 if (ret > 0) {
e02119d5
CM
2906 /* there are no items in the tree for us to truncate, we're
2907 * done
2908 */
8082510e
YZ
2909 if (path->slots[0] == 0)
2910 goto out;
85e21bac
CM
2911 path->slots[0]--;
2912 }
2913
d397712b 2914 while (1) {
39279cc3 2915 fi = NULL;
5f39d397
CM
2916 leaf = path->nodes[0];
2917 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2918 found_type = btrfs_key_type(&found_key);
771ed689 2919 encoding = 0;
39279cc3 2920
5f39d397 2921 if (found_key.objectid != inode->i_ino)
39279cc3 2922 break;
5f39d397 2923
85e21bac 2924 if (found_type < min_type)
39279cc3
CM
2925 break;
2926
5f39d397 2927 item_end = found_key.offset;
39279cc3 2928 if (found_type == BTRFS_EXTENT_DATA_KEY) {
5f39d397 2929 fi = btrfs_item_ptr(leaf, path->slots[0],
39279cc3 2930 struct btrfs_file_extent_item);
179e29e4 2931 extent_type = btrfs_file_extent_type(leaf, fi);
771ed689
CM
2932 encoding = btrfs_file_extent_compression(leaf, fi);
2933 encoding |= btrfs_file_extent_encryption(leaf, fi);
2934 encoding |= btrfs_file_extent_other_encoding(leaf, fi);
2935
179e29e4 2936 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
5f39d397 2937 item_end +=
db94535d 2938 btrfs_file_extent_num_bytes(leaf, fi);
179e29e4 2939 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
179e29e4 2940 item_end += btrfs_file_extent_inline_len(leaf,
c8b97818 2941 fi);
39279cc3 2942 }
008630c1 2943 item_end--;
39279cc3 2944 }
8082510e
YZ
2945 if (found_type > min_type) {
2946 del_item = 1;
2947 } else {
2948 if (item_end < new_size)
b888db2b 2949 break;
8082510e
YZ
2950 if (found_key.offset >= new_size)
2951 del_item = 1;
2952 else
2953 del_item = 0;
39279cc3 2954 }
39279cc3 2955 found_extent = 0;
39279cc3 2956 /* FIXME, shrink the extent if the ref count is only 1 */
179e29e4
CM
2957 if (found_type != BTRFS_EXTENT_DATA_KEY)
2958 goto delete;
2959
2960 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
39279cc3 2961 u64 num_dec;
db94535d 2962 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
771ed689 2963 if (!del_item && !encoding) {
db94535d
CM
2964 u64 orig_num_bytes =
2965 btrfs_file_extent_num_bytes(leaf, fi);
e02119d5 2966 extent_num_bytes = new_size -
5f39d397 2967 found_key.offset + root->sectorsize - 1;
b1632b10
Y
2968 extent_num_bytes = extent_num_bytes &
2969 ~((u64)root->sectorsize - 1);
db94535d
CM
2970 btrfs_set_file_extent_num_bytes(leaf, fi,
2971 extent_num_bytes);
2972 num_dec = (orig_num_bytes -
9069218d 2973 extent_num_bytes);
e02119d5 2974 if (root->ref_cows && extent_start != 0)
a76a3cd4 2975 inode_sub_bytes(inode, num_dec);
5f39d397 2976 btrfs_mark_buffer_dirty(leaf);
39279cc3 2977 } else {
db94535d
CM
2978 extent_num_bytes =
2979 btrfs_file_extent_disk_num_bytes(leaf,
2980 fi);
5d4f98a2
YZ
2981 extent_offset = found_key.offset -
2982 btrfs_file_extent_offset(leaf, fi);
2983
39279cc3 2984 /* FIXME blocksize != 4096 */
9069218d 2985 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
39279cc3
CM
2986 if (extent_start != 0) {
2987 found_extent = 1;
e02119d5 2988 if (root->ref_cows)
a76a3cd4 2989 inode_sub_bytes(inode, num_dec);
e02119d5 2990 }
39279cc3 2991 }
9069218d 2992 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
c8b97818
CM
2993 /*
2994 * we can't truncate inline items that have had
2995 * special encodings
2996 */
2997 if (!del_item &&
2998 btrfs_file_extent_compression(leaf, fi) == 0 &&
2999 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3000 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
e02119d5
CM
3001 u32 size = new_size - found_key.offset;
3002
3003 if (root->ref_cows) {
a76a3cd4
YZ
3004 inode_sub_bytes(inode, item_end + 1 -
3005 new_size);
e02119d5
CM
3006 }
3007 size =
3008 btrfs_file_extent_calc_inline_size(size);
9069218d 3009 ret = btrfs_truncate_item(trans, root, path,
e02119d5 3010 size, 1);
9069218d 3011 BUG_ON(ret);
e02119d5 3012 } else if (root->ref_cows) {
a76a3cd4
YZ
3013 inode_sub_bytes(inode, item_end + 1 -
3014 found_key.offset);
9069218d 3015 }
39279cc3 3016 }
179e29e4 3017delete:
39279cc3 3018 if (del_item) {
85e21bac
CM
3019 if (!pending_del_nr) {
3020 /* no pending yet, add ourselves */
3021 pending_del_slot = path->slots[0];
3022 pending_del_nr = 1;
3023 } else if (pending_del_nr &&
3024 path->slots[0] + 1 == pending_del_slot) {
3025 /* hop on the pending chunk */
3026 pending_del_nr++;
3027 pending_del_slot = path->slots[0];
3028 } else {
d397712b 3029 BUG();
85e21bac 3030 }
39279cc3
CM
3031 } else {
3032 break;
3033 }
5d4f98a2 3034 if (found_extent && root->ref_cows) {
b9473439 3035 btrfs_set_path_blocking(path);
39279cc3 3036 ret = btrfs_free_extent(trans, root, extent_start,
5d4f98a2
YZ
3037 extent_num_bytes, 0,
3038 btrfs_header_owner(leaf),
3039 inode->i_ino, extent_offset);
39279cc3
CM
3040 BUG_ON(ret);
3041 }
85e21bac 3042
8082510e
YZ
3043 if (found_type == BTRFS_INODE_ITEM_KEY)
3044 break;
3045
3046 if (path->slots[0] == 0 ||
3047 path->slots[0] != pending_del_slot) {
3048 if (root->ref_cows) {
3049 err = -EAGAIN;
3050 goto out;
3051 }
3052 if (pending_del_nr) {
3053 ret = btrfs_del_items(trans, root, path,
3054 pending_del_slot,
3055 pending_del_nr);
3056 BUG_ON(ret);
3057 pending_del_nr = 0;
3058 }
85e21bac
CM
3059 btrfs_release_path(root, path);
3060 goto search_again;
8082510e
YZ
3061 } else {
3062 path->slots[0]--;
85e21bac 3063 }
39279cc3 3064 }
8082510e 3065out:
85e21bac
CM
3066 if (pending_del_nr) {
3067 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3068 pending_del_nr);
3069 }
39279cc3 3070 btrfs_free_path(path);
8082510e 3071 return err;
39279cc3
CM
3072}
3073
3074/*
3075 * taken from block_truncate_page, but does cow as it zeros out
3076 * any bytes left in the last page in the file.
3077 */
3078static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3079{
3080 struct inode *inode = mapping->host;
db94535d 3081 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
3082 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3083 struct btrfs_ordered_extent *ordered;
3084 char *kaddr;
db94535d 3085 u32 blocksize = root->sectorsize;
39279cc3
CM
3086 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3087 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3088 struct page *page;
39279cc3 3089 int ret = 0;
a52d9a80 3090 u64 page_start;
e6dcd2dc 3091 u64 page_end;
39279cc3
CM
3092
3093 if ((offset & (blocksize - 1)) == 0)
3094 goto out;
5d5e103a
JB
3095 ret = btrfs_check_data_free_space(root, inode, PAGE_CACHE_SIZE);
3096 if (ret)
3097 goto out;
3098
3099 ret = btrfs_reserve_metadata_for_delalloc(root, inode, 1);
3100 if (ret)
3101 goto out;
39279cc3
CM
3102
3103 ret = -ENOMEM;
211c17f5 3104again:
39279cc3 3105 page = grab_cache_page(mapping, index);
5d5e103a
JB
3106 if (!page) {
3107 btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
3108 btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
39279cc3 3109 goto out;
5d5e103a 3110 }
e6dcd2dc
CM
3111
3112 page_start = page_offset(page);
3113 page_end = page_start + PAGE_CACHE_SIZE - 1;
3114
39279cc3 3115 if (!PageUptodate(page)) {
9ebefb18 3116 ret = btrfs_readpage(NULL, page);
39279cc3 3117 lock_page(page);
211c17f5
CM
3118 if (page->mapping != mapping) {
3119 unlock_page(page);
3120 page_cache_release(page);
3121 goto again;
3122 }
39279cc3
CM
3123 if (!PageUptodate(page)) {
3124 ret = -EIO;
89642229 3125 goto out_unlock;
39279cc3
CM
3126 }
3127 }
211c17f5 3128 wait_on_page_writeback(page);
e6dcd2dc
CM
3129
3130 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
3131 set_page_extent_mapped(page);
3132
3133 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3134 if (ordered) {
3135 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3136 unlock_page(page);
3137 page_cache_release(page);
eb84ae03 3138 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
3139 btrfs_put_ordered_extent(ordered);
3140 goto again;
3141 }
3142
5d5e103a
JB
3143 clear_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
3144 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3145 GFP_NOFS);
3146
9ed74f2d
JB
3147 ret = btrfs_set_extent_delalloc(inode, page_start, page_end);
3148 if (ret) {
3149 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
3150 goto out_unlock;
3151 }
3152
e6dcd2dc
CM
3153 ret = 0;
3154 if (offset != PAGE_CACHE_SIZE) {
3155 kaddr = kmap(page);
3156 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3157 flush_dcache_page(page);
3158 kunmap(page);
3159 }
247e743c 3160 ClearPageChecked(page);
e6dcd2dc
CM
3161 set_page_dirty(page);
3162 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
39279cc3 3163
89642229 3164out_unlock:
5d5e103a
JB
3165 if (ret)
3166 btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
3167 btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
39279cc3
CM
3168 unlock_page(page);
3169 page_cache_release(page);
3170out:
3171 return ret;
3172}
3173
9036c102 3174int btrfs_cont_expand(struct inode *inode, loff_t size)
39279cc3 3175{
9036c102
YZ
3176 struct btrfs_trans_handle *trans;
3177 struct btrfs_root *root = BTRFS_I(inode)->root;
3178 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3179 struct extent_map *em;
3180 u64 mask = root->sectorsize - 1;
3181 u64 hole_start = (inode->i_size + mask) & ~mask;
3182 u64 block_end = (size + mask) & ~mask;
3183 u64 last_byte;
3184 u64 cur_offset;
3185 u64 hole_size;
9ed74f2d 3186 int err = 0;
39279cc3 3187
9036c102
YZ
3188 if (size <= hole_start)
3189 return 0;
3190
9036c102
YZ
3191 while (1) {
3192 struct btrfs_ordered_extent *ordered;
3193 btrfs_wait_ordered_range(inode, hole_start,
3194 block_end - hole_start);
3195 lock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
3196 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3197 if (!ordered)
3198 break;
3199 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
3200 btrfs_put_ordered_extent(ordered);
3201 }
39279cc3 3202
9036c102
YZ
3203 cur_offset = hole_start;
3204 while (1) {
3205 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3206 block_end - cur_offset, 0);
3207 BUG_ON(IS_ERR(em) || !em);
3208 last_byte = min(extent_map_end(em), block_end);
3209 last_byte = (last_byte + mask) & ~mask;
8082510e 3210 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
771ed689 3211 u64 hint_byte = 0;
9036c102 3212 hole_size = last_byte - cur_offset;
9ed74f2d 3213
8082510e 3214 err = btrfs_reserve_metadata_space(root, 2);
9ed74f2d
JB
3215 if (err)
3216 break;
3217
8082510e
YZ
3218 trans = btrfs_start_transaction(root, 1);
3219 btrfs_set_trans_block_group(trans, inode);
3220
3221 err = btrfs_drop_extents(trans, inode, cur_offset,
3222 cur_offset + hole_size,
3223 &hint_byte, 1);
3224 BUG_ON(err);
3225
9036c102
YZ
3226 err = btrfs_insert_file_extent(trans, root,
3227 inode->i_ino, cur_offset, 0,
3228 0, hole_size, 0, hole_size,
3229 0, 0, 0);
8082510e
YZ
3230 BUG_ON(err);
3231
9036c102
YZ
3232 btrfs_drop_extent_cache(inode, hole_start,
3233 last_byte - 1, 0);
8082510e
YZ
3234
3235 btrfs_end_transaction(trans, root);
3236 btrfs_unreserve_metadata_space(root, 2);
9036c102
YZ
3237 }
3238 free_extent_map(em);
3239 cur_offset = last_byte;
8082510e 3240 if (cur_offset >= block_end)
9036c102
YZ
3241 break;
3242 }
1832a6d5 3243
9036c102
YZ
3244 unlock_extent(io_tree, hole_start, block_end - 1, GFP_NOFS);
3245 return err;
3246}
39279cc3 3247
8082510e
YZ
3248static int btrfs_setattr_size(struct inode *inode, struct iattr *attr)
3249{
3250 struct btrfs_root *root = BTRFS_I(inode)->root;
3251 struct btrfs_trans_handle *trans;
3252 unsigned long nr;
3253 int ret;
3254
3255 if (attr->ia_size == inode->i_size)
3256 return 0;
3257
3258 if (attr->ia_size > inode->i_size) {
3259 unsigned long limit;
3260 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
3261 if (attr->ia_size > inode->i_sb->s_maxbytes)
3262 return -EFBIG;
3263 if (limit != RLIM_INFINITY && attr->ia_size > limit) {
3264 send_sig(SIGXFSZ, current, 0);
3265 return -EFBIG;
3266 }
3267 }
3268
3269 ret = btrfs_reserve_metadata_space(root, 1);
3270 if (ret)
3271 return ret;
3272
3273 trans = btrfs_start_transaction(root, 1);
3274 btrfs_set_trans_block_group(trans, inode);
3275
3276 ret = btrfs_orphan_add(trans, inode);
3277 BUG_ON(ret);
3278
3279 nr = trans->blocks_used;
3280 btrfs_end_transaction(trans, root);
3281 btrfs_unreserve_metadata_space(root, 1);
3282 btrfs_btree_balance_dirty(root, nr);
3283
3284 if (attr->ia_size > inode->i_size) {
3285 ret = btrfs_cont_expand(inode, attr->ia_size);
3286 if (ret) {
3287 btrfs_truncate(inode);
3288 return ret;
3289 }
3290
3291 i_size_write(inode, attr->ia_size);
3292 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
3293
3294 trans = btrfs_start_transaction(root, 1);
3295 btrfs_set_trans_block_group(trans, inode);
3296
3297 ret = btrfs_update_inode(trans, root, inode);
3298 BUG_ON(ret);
3299 if (inode->i_nlink > 0) {
3300 ret = btrfs_orphan_del(trans, inode);
3301 BUG_ON(ret);
3302 }
3303 nr = trans->blocks_used;
3304 btrfs_end_transaction(trans, root);
3305 btrfs_btree_balance_dirty(root, nr);
3306 return 0;
3307 }
3308
3309 /*
3310 * We're truncating a file that used to have good data down to
3311 * zero. Make sure it gets into the ordered flush list so that
3312 * any new writes get down to disk quickly.
3313 */
3314 if (attr->ia_size == 0)
3315 BTRFS_I(inode)->ordered_data_close = 1;
3316
3317 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3318 ret = vmtruncate(inode, attr->ia_size);
3319 BUG_ON(ret);
3320
3321 return 0;
3322}
3323
9036c102
YZ
3324static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3325{
3326 struct inode *inode = dentry->d_inode;
3327 int err;
39279cc3 3328
9036c102
YZ
3329 err = inode_change_ok(inode, attr);
3330 if (err)
3331 return err;
2bf5a725 3332
5a3f23d5 3333 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
8082510e
YZ
3334 err = btrfs_setattr_size(inode, attr);
3335 if (err)
3336 return err;
39279cc3 3337 }
8082510e 3338 attr->ia_valid &= ~ATTR_SIZE;
9036c102 3339
8082510e
YZ
3340 if (attr->ia_valid)
3341 err = inode_setattr(inode, attr);
33268eaf
JB
3342
3343 if (!err && ((attr->ia_valid & ATTR_MODE)))
3344 err = btrfs_acl_chmod(inode);
39279cc3
CM
3345 return err;
3346}
61295eb8 3347
39279cc3
CM
3348void btrfs_delete_inode(struct inode *inode)
3349{
3350 struct btrfs_trans_handle *trans;
3351 struct btrfs_root *root = BTRFS_I(inode)->root;
d3c2fdcf 3352 unsigned long nr;
39279cc3
CM
3353 int ret;
3354
3355 truncate_inode_pages(&inode->i_data, 0);
3356 if (is_bad_inode(inode)) {
7b128766 3357 btrfs_orphan_del(NULL, inode);
39279cc3
CM
3358 goto no_delete;
3359 }
4a096752 3360 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5f39d397 3361
c71bf099
YZ
3362 if (root->fs_info->log_root_recovering) {
3363 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3364 goto no_delete;
3365 }
3366
76dda93c
YZ
3367 if (inode->i_nlink > 0) {
3368 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3369 goto no_delete;
3370 }
3371
dbe674a9 3372 btrfs_i_size_write(inode, 0);
5f39d397 3373
8082510e
YZ
3374 while (1) {
3375 trans = btrfs_start_transaction(root, 1);
3376 btrfs_set_trans_block_group(trans, inode);
3377 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
7b128766 3378
8082510e
YZ
3379 if (ret != -EAGAIN)
3380 break;
85e21bac 3381
8082510e
YZ
3382 nr = trans->blocks_used;
3383 btrfs_end_transaction(trans, root);
3384 trans = NULL;
3385 btrfs_btree_balance_dirty(root, nr);
3386 }
5f39d397 3387
8082510e
YZ
3388 if (ret == 0) {
3389 ret = btrfs_orphan_del(trans, inode);
3390 BUG_ON(ret);
3391 }
54aa1f4d 3392
d3c2fdcf 3393 nr = trans->blocks_used;
54aa1f4d 3394 btrfs_end_transaction(trans, root);
d3c2fdcf 3395 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
3396no_delete:
3397 clear_inode(inode);
8082510e 3398 return;
39279cc3
CM
3399}
3400
3401/*
3402 * this returns the key found in the dir entry in the location pointer.
3403 * If no dir entries were found, location->objectid is 0.
3404 */
3405static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3406 struct btrfs_key *location)
3407{
3408 const char *name = dentry->d_name.name;
3409 int namelen = dentry->d_name.len;
3410 struct btrfs_dir_item *di;
3411 struct btrfs_path *path;
3412 struct btrfs_root *root = BTRFS_I(dir)->root;
0d9f7f3e 3413 int ret = 0;
39279cc3
CM
3414
3415 path = btrfs_alloc_path();
3416 BUG_ON(!path);
3954401f 3417
39279cc3
CM
3418 di = btrfs_lookup_dir_item(NULL, root, path, dir->i_ino, name,
3419 namelen, 0);
0d9f7f3e
Y
3420 if (IS_ERR(di))
3421 ret = PTR_ERR(di);
d397712b
CM
3422
3423 if (!di || IS_ERR(di))
3954401f 3424 goto out_err;
d397712b 3425
5f39d397 3426 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
39279cc3 3427out:
39279cc3
CM
3428 btrfs_free_path(path);
3429 return ret;
3954401f
CM
3430out_err:
3431 location->objectid = 0;
3432 goto out;
39279cc3
CM
3433}
3434
3435/*
3436 * when we hit a tree root in a directory, the btrfs part of the inode
3437 * needs to be changed to reflect the root directory of the tree root. This
3438 * is kind of like crossing a mount point.
3439 */
3440static int fixup_tree_root_location(struct btrfs_root *root,
4df27c4d
YZ
3441 struct inode *dir,
3442 struct dentry *dentry,
3443 struct btrfs_key *location,
3444 struct btrfs_root **sub_root)
39279cc3 3445{
4df27c4d
YZ
3446 struct btrfs_path *path;
3447 struct btrfs_root *new_root;
3448 struct btrfs_root_ref *ref;
3449 struct extent_buffer *leaf;
3450 int ret;
3451 int err = 0;
39279cc3 3452
4df27c4d
YZ
3453 path = btrfs_alloc_path();
3454 if (!path) {
3455 err = -ENOMEM;
3456 goto out;
3457 }
39279cc3 3458
4df27c4d
YZ
3459 err = -ENOENT;
3460 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3461 BTRFS_I(dir)->root->root_key.objectid,
3462 location->objectid);
3463 if (ret) {
3464 if (ret < 0)
3465 err = ret;
3466 goto out;
3467 }
39279cc3 3468
4df27c4d
YZ
3469 leaf = path->nodes[0];
3470 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3471 if (btrfs_root_ref_dirid(leaf, ref) != dir->i_ino ||
3472 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3473 goto out;
39279cc3 3474
4df27c4d
YZ
3475 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3476 (unsigned long)(ref + 1),
3477 dentry->d_name.len);
3478 if (ret)
3479 goto out;
3480
3481 btrfs_release_path(root->fs_info->tree_root, path);
3482
3483 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3484 if (IS_ERR(new_root)) {
3485 err = PTR_ERR(new_root);
3486 goto out;
3487 }
3488
3489 if (btrfs_root_refs(&new_root->root_item) == 0) {
3490 err = -ENOENT;
3491 goto out;
3492 }
3493
3494 *sub_root = new_root;
3495 location->objectid = btrfs_root_dirid(&new_root->root_item);
3496 location->type = BTRFS_INODE_ITEM_KEY;
3497 location->offset = 0;
3498 err = 0;
3499out:
3500 btrfs_free_path(path);
3501 return err;
39279cc3
CM
3502}
3503
5d4f98a2
YZ
3504static void inode_tree_add(struct inode *inode)
3505{
3506 struct btrfs_root *root = BTRFS_I(inode)->root;
3507 struct btrfs_inode *entry;
03e860bd
FNP
3508 struct rb_node **p;
3509 struct rb_node *parent;
03e860bd
FNP
3510again:
3511 p = &root->inode_tree.rb_node;
3512 parent = NULL;
5d4f98a2 3513
76dda93c
YZ
3514 if (hlist_unhashed(&inode->i_hash))
3515 return;
3516
5d4f98a2
YZ
3517 spin_lock(&root->inode_lock);
3518 while (*p) {
3519 parent = *p;
3520 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3521
3522 if (inode->i_ino < entry->vfs_inode.i_ino)
03e860bd 3523 p = &parent->rb_left;
5d4f98a2 3524 else if (inode->i_ino > entry->vfs_inode.i_ino)
03e860bd 3525 p = &parent->rb_right;
5d4f98a2
YZ
3526 else {
3527 WARN_ON(!(entry->vfs_inode.i_state &
3528 (I_WILL_FREE | I_FREEING | I_CLEAR)));
03e860bd
FNP
3529 rb_erase(parent, &root->inode_tree);
3530 RB_CLEAR_NODE(parent);
3531 spin_unlock(&root->inode_lock);
3532 goto again;
5d4f98a2
YZ
3533 }
3534 }
3535 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3536 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3537 spin_unlock(&root->inode_lock);
3538}
3539
3540static void inode_tree_del(struct inode *inode)
3541{
3542 struct btrfs_root *root = BTRFS_I(inode)->root;
76dda93c 3543 int empty = 0;
5d4f98a2 3544
03e860bd 3545 spin_lock(&root->inode_lock);
5d4f98a2 3546 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5d4f98a2 3547 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5d4f98a2 3548 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
76dda93c 3549 empty = RB_EMPTY_ROOT(&root->inode_tree);
5d4f98a2 3550 }
03e860bd 3551 spin_unlock(&root->inode_lock);
76dda93c
YZ
3552
3553 if (empty && btrfs_root_refs(&root->root_item) == 0) {
3554 synchronize_srcu(&root->fs_info->subvol_srcu);
3555 spin_lock(&root->inode_lock);
3556 empty = RB_EMPTY_ROOT(&root->inode_tree);
3557 spin_unlock(&root->inode_lock);
3558 if (empty)
3559 btrfs_add_dead_root(root);
3560 }
3561}
3562
3563int btrfs_invalidate_inodes(struct btrfs_root *root)
3564{
3565 struct rb_node *node;
3566 struct rb_node *prev;
3567 struct btrfs_inode *entry;
3568 struct inode *inode;
3569 u64 objectid = 0;
3570
3571 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3572
3573 spin_lock(&root->inode_lock);
3574again:
3575 node = root->inode_tree.rb_node;
3576 prev = NULL;
3577 while (node) {
3578 prev = node;
3579 entry = rb_entry(node, struct btrfs_inode, rb_node);
3580
3581 if (objectid < entry->vfs_inode.i_ino)
3582 node = node->rb_left;
3583 else if (objectid > entry->vfs_inode.i_ino)
3584 node = node->rb_right;
3585 else
3586 break;
3587 }
3588 if (!node) {
3589 while (prev) {
3590 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3591 if (objectid <= entry->vfs_inode.i_ino) {
3592 node = prev;
3593 break;
3594 }
3595 prev = rb_next(prev);
3596 }
3597 }
3598 while (node) {
3599 entry = rb_entry(node, struct btrfs_inode, rb_node);
3600 objectid = entry->vfs_inode.i_ino + 1;
3601 inode = igrab(&entry->vfs_inode);
3602 if (inode) {
3603 spin_unlock(&root->inode_lock);
3604 if (atomic_read(&inode->i_count) > 1)
3605 d_prune_aliases(inode);
3606 /*
3607 * btrfs_drop_inode will remove it from
3608 * the inode cache when its usage count
3609 * hits zero.
3610 */
3611 iput(inode);
3612 cond_resched();
3613 spin_lock(&root->inode_lock);
3614 goto again;
3615 }
3616
3617 if (cond_resched_lock(&root->inode_lock))
3618 goto again;
3619
3620 node = rb_next(node);
3621 }
3622 spin_unlock(&root->inode_lock);
3623 return 0;
5d4f98a2
YZ
3624}
3625
e02119d5 3626static noinline void init_btrfs_i(struct inode *inode)
39279cc3 3627{
e02119d5
CM
3628 struct btrfs_inode *bi = BTRFS_I(inode);
3629
e02119d5 3630 bi->generation = 0;
c3027eb5 3631 bi->sequence = 0;
e02119d5 3632 bi->last_trans = 0;
257c62e1 3633 bi->last_sub_trans = 0;
e02119d5
CM
3634 bi->logged_trans = 0;
3635 bi->delalloc_bytes = 0;
6a63209f 3636 bi->reserved_bytes = 0;
e02119d5
CM
3637 bi->disk_i_size = 0;
3638 bi->flags = 0;
3639 bi->index_cnt = (u64)-1;
12fcfd22 3640 bi->last_unlink_trans = 0;
2757495c 3641 bi->ordered_data_close = 0;
d1310b2e
CM
3642 extent_map_tree_init(&BTRFS_I(inode)->extent_tree, GFP_NOFS);
3643 extent_io_tree_init(&BTRFS_I(inode)->io_tree,
b888db2b 3644 inode->i_mapping, GFP_NOFS);
7e38326f
CM
3645 extent_io_tree_init(&BTRFS_I(inode)->io_failure_tree,
3646 inode->i_mapping, GFP_NOFS);
ea8c2819 3647 INIT_LIST_HEAD(&BTRFS_I(inode)->delalloc_inodes);
5a3f23d5 3648 INIT_LIST_HEAD(&BTRFS_I(inode)->ordered_operations);
5d4f98a2 3649 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
ba1da2f4 3650 btrfs_ordered_inode_tree_init(&BTRFS_I(inode)->ordered_tree);
e02119d5
CM
3651 mutex_init(&BTRFS_I(inode)->log_mutex);
3652}
3653
3654static int btrfs_init_locked_inode(struct inode *inode, void *p)
3655{
3656 struct btrfs_iget_args *args = p;
3657 inode->i_ino = args->ino;
3658 init_btrfs_i(inode);
3659 BTRFS_I(inode)->root = args->root;
6a63209f 3660 btrfs_set_inode_space_info(args->root, inode);
39279cc3
CM
3661 return 0;
3662}
3663
3664static int btrfs_find_actor(struct inode *inode, void *opaque)
3665{
3666 struct btrfs_iget_args *args = opaque;
d397712b
CM
3667 return args->ino == inode->i_ino &&
3668 args->root == BTRFS_I(inode)->root;
39279cc3
CM
3669}
3670
5d4f98a2
YZ
3671static struct inode *btrfs_iget_locked(struct super_block *s,
3672 u64 objectid,
3673 struct btrfs_root *root)
39279cc3
CM
3674{
3675 struct inode *inode;
3676 struct btrfs_iget_args args;
3677 args.ino = objectid;
3678 args.root = root;
3679
3680 inode = iget5_locked(s, objectid, btrfs_find_actor,
3681 btrfs_init_locked_inode,
3682 (void *)&args);
3683 return inode;
3684}
3685
1a54ef8c
BR
3686/* Get an inode object given its location and corresponding root.
3687 * Returns in *is_new if the inode was read from disk
3688 */
3689struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
73f73415 3690 struct btrfs_root *root, int *new)
1a54ef8c
BR
3691{
3692 struct inode *inode;
3693
3694 inode = btrfs_iget_locked(s, location->objectid, root);
3695 if (!inode)
5d4f98a2 3696 return ERR_PTR(-ENOMEM);
1a54ef8c
BR
3697
3698 if (inode->i_state & I_NEW) {
3699 BTRFS_I(inode)->root = root;
3700 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
3701 btrfs_read_locked_inode(inode);
5d4f98a2
YZ
3702
3703 inode_tree_add(inode);
1a54ef8c 3704 unlock_new_inode(inode);
73f73415
JB
3705 if (new)
3706 *new = 1;
1a54ef8c
BR
3707 }
3708
3709 return inode;
3710}
3711
4df27c4d
YZ
3712static struct inode *new_simple_dir(struct super_block *s,
3713 struct btrfs_key *key,
3714 struct btrfs_root *root)
3715{
3716 struct inode *inode = new_inode(s);
3717
3718 if (!inode)
3719 return ERR_PTR(-ENOMEM);
3720
3721 init_btrfs_i(inode);
3722
3723 BTRFS_I(inode)->root = root;
3724 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
3725 BTRFS_I(inode)->dummy_inode = 1;
3726
3727 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
3728 inode->i_op = &simple_dir_inode_operations;
3729 inode->i_fop = &simple_dir_operations;
3730 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
3731 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
3732
3733 return inode;
3734}
3735
3de4586c 3736struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
39279cc3 3737{
d397712b 3738 struct inode *inode;
4df27c4d 3739 struct btrfs_root *root = BTRFS_I(dir)->root;
39279cc3
CM
3740 struct btrfs_root *sub_root = root;
3741 struct btrfs_key location;
76dda93c 3742 int index;
5d4f98a2 3743 int ret;
39279cc3 3744
76dda93c
YZ
3745 dentry->d_op = &btrfs_dentry_operations;
3746
39279cc3
CM
3747 if (dentry->d_name.len > BTRFS_NAME_LEN)
3748 return ERR_PTR(-ENAMETOOLONG);
5f39d397 3749
39279cc3 3750 ret = btrfs_inode_by_name(dir, dentry, &location);
5f39d397 3751
39279cc3
CM
3752 if (ret < 0)
3753 return ERR_PTR(ret);
5f39d397 3754
4df27c4d
YZ
3755 if (location.objectid == 0)
3756 return NULL;
3757
3758 if (location.type == BTRFS_INODE_ITEM_KEY) {
73f73415 3759 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4df27c4d
YZ
3760 return inode;
3761 }
3762
3763 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
3764
76dda93c 3765 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4df27c4d
YZ
3766 ret = fixup_tree_root_location(root, dir, dentry,
3767 &location, &sub_root);
3768 if (ret < 0) {
3769 if (ret != -ENOENT)
3770 inode = ERR_PTR(ret);
3771 else
3772 inode = new_simple_dir(dir->i_sb, &location, sub_root);
3773 } else {
73f73415 3774 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
39279cc3 3775 }
76dda93c
YZ
3776 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
3777
c71bf099
YZ
3778 if (root != sub_root) {
3779 down_read(&root->fs_info->cleanup_work_sem);
3780 if (!(inode->i_sb->s_flags & MS_RDONLY))
3781 btrfs_orphan_cleanup(sub_root);
3782 up_read(&root->fs_info->cleanup_work_sem);
3783 }
3784
3de4586c
CM
3785 return inode;
3786}
3787
76dda93c
YZ
3788static int btrfs_dentry_delete(struct dentry *dentry)
3789{
3790 struct btrfs_root *root;
3791
efefb143
YZ
3792 if (!dentry->d_inode && !IS_ROOT(dentry))
3793 dentry = dentry->d_parent;
76dda93c 3794
efefb143
YZ
3795 if (dentry->d_inode) {
3796 root = BTRFS_I(dentry->d_inode)->root;
3797 if (btrfs_root_refs(&root->root_item) == 0)
3798 return 1;
3799 }
76dda93c
YZ
3800 return 0;
3801}
3802
3de4586c
CM
3803static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
3804 struct nameidata *nd)
3805{
3806 struct inode *inode;
3807
3de4586c
CM
3808 inode = btrfs_lookup_dentry(dir, dentry);
3809 if (IS_ERR(inode))
3810 return ERR_CAST(inode);
7b128766 3811
39279cc3
CM
3812 return d_splice_alias(inode, dentry);
3813}
3814
39279cc3
CM
3815static unsigned char btrfs_filetype_table[] = {
3816 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
3817};
3818
cbdf5a24
DW
3819static int btrfs_real_readdir(struct file *filp, void *dirent,
3820 filldir_t filldir)
39279cc3 3821{
6da6abae 3822 struct inode *inode = filp->f_dentry->d_inode;
39279cc3
CM
3823 struct btrfs_root *root = BTRFS_I(inode)->root;
3824 struct btrfs_item *item;
3825 struct btrfs_dir_item *di;
3826 struct btrfs_key key;
5f39d397 3827 struct btrfs_key found_key;
39279cc3
CM
3828 struct btrfs_path *path;
3829 int ret;
3830 u32 nritems;
5f39d397 3831 struct extent_buffer *leaf;
39279cc3
CM
3832 int slot;
3833 int advance;
3834 unsigned char d_type;
3835 int over = 0;
3836 u32 di_cur;
3837 u32 di_total;
3838 u32 di_len;
3839 int key_type = BTRFS_DIR_INDEX_KEY;
5f39d397
CM
3840 char tmp_name[32];
3841 char *name_ptr;
3842 int name_len;
39279cc3
CM
3843
3844 /* FIXME, use a real flag for deciding about the key type */
3845 if (root->fs_info->tree_root == root)
3846 key_type = BTRFS_DIR_ITEM_KEY;
5f39d397 3847
3954401f
CM
3848 /* special case for "." */
3849 if (filp->f_pos == 0) {
3850 over = filldir(dirent, ".", 1,
3851 1, inode->i_ino,
3852 DT_DIR);
3853 if (over)
3854 return 0;
3855 filp->f_pos = 1;
3856 }
3954401f
CM
3857 /* special case for .., just use the back ref */
3858 if (filp->f_pos == 1) {
5ecc7e5d 3859 u64 pino = parent_ino(filp->f_path.dentry);
3954401f 3860 over = filldir(dirent, "..", 2,
5ecc7e5d 3861 2, pino, DT_DIR);
3954401f 3862 if (over)
49593bfa 3863 return 0;
3954401f
CM
3864 filp->f_pos = 2;
3865 }
49593bfa
DW
3866 path = btrfs_alloc_path();
3867 path->reada = 2;
3868
39279cc3
CM
3869 btrfs_set_key_type(&key, key_type);
3870 key.offset = filp->f_pos;
49593bfa 3871 key.objectid = inode->i_ino;
5f39d397 3872
39279cc3
CM
3873 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3874 if (ret < 0)
3875 goto err;
3876 advance = 0;
49593bfa
DW
3877
3878 while (1) {
5f39d397
CM
3879 leaf = path->nodes[0];
3880 nritems = btrfs_header_nritems(leaf);
39279cc3
CM
3881 slot = path->slots[0];
3882 if (advance || slot >= nritems) {
49593bfa 3883 if (slot >= nritems - 1) {
39279cc3
CM
3884 ret = btrfs_next_leaf(root, path);
3885 if (ret)
3886 break;
5f39d397
CM
3887 leaf = path->nodes[0];
3888 nritems = btrfs_header_nritems(leaf);
39279cc3
CM
3889 slot = path->slots[0];
3890 } else {
3891 slot++;
3892 path->slots[0]++;
3893 }
3894 }
3de4586c 3895
39279cc3 3896 advance = 1;
5f39d397
CM
3897 item = btrfs_item_nr(leaf, slot);
3898 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3899
3900 if (found_key.objectid != key.objectid)
39279cc3 3901 break;
5f39d397 3902 if (btrfs_key_type(&found_key) != key_type)
39279cc3 3903 break;
5f39d397 3904 if (found_key.offset < filp->f_pos)
39279cc3 3905 continue;
5f39d397
CM
3906
3907 filp->f_pos = found_key.offset;
49593bfa 3908
39279cc3
CM
3909 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
3910 di_cur = 0;
5f39d397 3911 di_total = btrfs_item_size(leaf, item);
49593bfa
DW
3912
3913 while (di_cur < di_total) {
5f39d397
CM
3914 struct btrfs_key location;
3915
3916 name_len = btrfs_dir_name_len(leaf, di);
49593bfa 3917 if (name_len <= sizeof(tmp_name)) {
5f39d397
CM
3918 name_ptr = tmp_name;
3919 } else {
3920 name_ptr = kmalloc(name_len, GFP_NOFS);
49593bfa
DW
3921 if (!name_ptr) {
3922 ret = -ENOMEM;
3923 goto err;
3924 }
5f39d397
CM
3925 }
3926 read_extent_buffer(leaf, name_ptr,
3927 (unsigned long)(di + 1), name_len);
3928
3929 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
3930 btrfs_dir_item_key_to_cpu(leaf, di, &location);
3de4586c
CM
3931
3932 /* is this a reference to our own snapshot? If so
3933 * skip it
3934 */
3935 if (location.type == BTRFS_ROOT_ITEM_KEY &&
3936 location.objectid == root->root_key.objectid) {
3937 over = 0;
3938 goto skip;
3939 }
5f39d397 3940 over = filldir(dirent, name_ptr, name_len,
49593bfa 3941 found_key.offset, location.objectid,
39279cc3 3942 d_type);
5f39d397 3943
3de4586c 3944skip:
5f39d397
CM
3945 if (name_ptr != tmp_name)
3946 kfree(name_ptr);
3947
39279cc3
CM
3948 if (over)
3949 goto nopos;
5103e947 3950 di_len = btrfs_dir_name_len(leaf, di) +
49593bfa 3951 btrfs_dir_data_len(leaf, di) + sizeof(*di);
39279cc3
CM
3952 di_cur += di_len;
3953 di = (struct btrfs_dir_item *)((char *)di + di_len);
3954 }
3955 }
49593bfa
DW
3956
3957 /* Reached end of directory/root. Bump pos past the last item. */
5e591a07 3958 if (key_type == BTRFS_DIR_INDEX_KEY)
406266ab
JE
3959 /*
3960 * 32-bit glibc will use getdents64, but then strtol -
3961 * so the last number we can serve is this.
3962 */
3963 filp->f_pos = 0x7fffffff;
5e591a07
YZ
3964 else
3965 filp->f_pos++;
39279cc3
CM
3966nopos:
3967 ret = 0;
3968err:
39279cc3 3969 btrfs_free_path(path);
39279cc3
CM
3970 return ret;
3971}
3972
3973int btrfs_write_inode(struct inode *inode, int wait)
3974{
3975 struct btrfs_root *root = BTRFS_I(inode)->root;
3976 struct btrfs_trans_handle *trans;
3977 int ret = 0;
3978
c146afad 3979 if (root->fs_info->btree_inode == inode)
4ca8b41e
CM
3980 return 0;
3981
39279cc3 3982 if (wait) {
f9295749 3983 trans = btrfs_join_transaction(root, 1);
39279cc3
CM
3984 btrfs_set_trans_block_group(trans, inode);
3985 ret = btrfs_commit_transaction(trans, root);
39279cc3
CM
3986 }
3987 return ret;
3988}
3989
3990/*
54aa1f4d 3991 * This is somewhat expensive, updating the tree every time the
39279cc3
CM
3992 * inode changes. But, it is most likely to find the inode in cache.
3993 * FIXME, needs more benchmarking...there are no reasons other than performance
3994 * to keep or drop this code.
3995 */
3996void btrfs_dirty_inode(struct inode *inode)
3997{
3998 struct btrfs_root *root = BTRFS_I(inode)->root;
3999 struct btrfs_trans_handle *trans;
4000
f9295749 4001 trans = btrfs_join_transaction(root, 1);
39279cc3
CM
4002 btrfs_set_trans_block_group(trans, inode);
4003 btrfs_update_inode(trans, root, inode);
4004 btrfs_end_transaction(trans, root);
39279cc3
CM
4005}
4006
d352ac68
CM
4007/*
4008 * find the highest existing sequence number in a directory
4009 * and then set the in-memory index_cnt variable to reflect
4010 * free sequence numbers
4011 */
aec7477b
JB
4012static int btrfs_set_inode_index_count(struct inode *inode)
4013{
4014 struct btrfs_root *root = BTRFS_I(inode)->root;
4015 struct btrfs_key key, found_key;
4016 struct btrfs_path *path;
4017 struct extent_buffer *leaf;
4018 int ret;
4019
4020 key.objectid = inode->i_ino;
4021 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4022 key.offset = (u64)-1;
4023
4024 path = btrfs_alloc_path();
4025 if (!path)
4026 return -ENOMEM;
4027
4028 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4029 if (ret < 0)
4030 goto out;
4031 /* FIXME: we should be able to handle this */
4032 if (ret == 0)
4033 goto out;
4034 ret = 0;
4035
4036 /*
4037 * MAGIC NUMBER EXPLANATION:
4038 * since we search a directory based on f_pos we have to start at 2
4039 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4040 * else has to start at 2
4041 */
4042 if (path->slots[0] == 0) {
4043 BTRFS_I(inode)->index_cnt = 2;
4044 goto out;
4045 }
4046
4047 path->slots[0]--;
4048
4049 leaf = path->nodes[0];
4050 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4051
4052 if (found_key.objectid != inode->i_ino ||
4053 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4054 BTRFS_I(inode)->index_cnt = 2;
4055 goto out;
4056 }
4057
4058 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4059out:
4060 btrfs_free_path(path);
4061 return ret;
4062}
4063
d352ac68
CM
4064/*
4065 * helper to find a free sequence number in a given directory. This current
4066 * code is very simple, later versions will do smarter things in the btree
4067 */
3de4586c 4068int btrfs_set_inode_index(struct inode *dir, u64 *index)
aec7477b
JB
4069{
4070 int ret = 0;
4071
4072 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4073 ret = btrfs_set_inode_index_count(dir);
d397712b 4074 if (ret)
aec7477b
JB
4075 return ret;
4076 }
4077
00e4e6b3 4078 *index = BTRFS_I(dir)->index_cnt;
aec7477b
JB
4079 BTRFS_I(dir)->index_cnt++;
4080
4081 return ret;
4082}
4083
39279cc3
CM
4084static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4085 struct btrfs_root *root,
aec7477b 4086 struct inode *dir,
9c58309d 4087 const char *name, int name_len,
d2fb3437
YZ
4088 u64 ref_objectid, u64 objectid,
4089 u64 alloc_hint, int mode, u64 *index)
39279cc3
CM
4090{
4091 struct inode *inode;
5f39d397 4092 struct btrfs_inode_item *inode_item;
39279cc3 4093 struct btrfs_key *location;
5f39d397 4094 struct btrfs_path *path;
9c58309d
CM
4095 struct btrfs_inode_ref *ref;
4096 struct btrfs_key key[2];
4097 u32 sizes[2];
4098 unsigned long ptr;
39279cc3
CM
4099 int ret;
4100 int owner;
4101
5f39d397
CM
4102 path = btrfs_alloc_path();
4103 BUG_ON(!path);
4104
39279cc3
CM
4105 inode = new_inode(root->fs_info->sb);
4106 if (!inode)
4107 return ERR_PTR(-ENOMEM);
4108
aec7477b 4109 if (dir) {
3de4586c 4110 ret = btrfs_set_inode_index(dir, index);
09771430
SF
4111 if (ret) {
4112 iput(inode);
aec7477b 4113 return ERR_PTR(ret);
09771430 4114 }
aec7477b
JB
4115 }
4116 /*
4117 * index_cnt is ignored for everything but a dir,
4118 * btrfs_get_inode_index_count has an explanation for the magic
4119 * number
4120 */
e02119d5 4121 init_btrfs_i(inode);
aec7477b 4122 BTRFS_I(inode)->index_cnt = 2;
39279cc3 4123 BTRFS_I(inode)->root = root;
e02119d5 4124 BTRFS_I(inode)->generation = trans->transid;
6a63209f 4125 btrfs_set_inode_space_info(root, inode);
b888db2b 4126
39279cc3
CM
4127 if (mode & S_IFDIR)
4128 owner = 0;
4129 else
4130 owner = 1;
d2fb3437
YZ
4131 BTRFS_I(inode)->block_group =
4132 btrfs_find_block_group(root, 0, alloc_hint, owner);
9c58309d
CM
4133
4134 key[0].objectid = objectid;
4135 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4136 key[0].offset = 0;
4137
4138 key[1].objectid = objectid;
4139 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4140 key[1].offset = ref_objectid;
4141
4142 sizes[0] = sizeof(struct btrfs_inode_item);
4143 sizes[1] = name_len + sizeof(*ref);
4144
b9473439 4145 path->leave_spinning = 1;
9c58309d
CM
4146 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4147 if (ret != 0)
5f39d397
CM
4148 goto fail;
4149
79683f2d 4150 inode->i_uid = current_fsuid();
8c087b51 4151
42f15d77 4152 if (dir && (dir->i_mode & S_ISGID)) {
8c087b51
CB
4153 inode->i_gid = dir->i_gid;
4154 if (S_ISDIR(mode))
4155 mode |= S_ISGID;
4156 } else
4157 inode->i_gid = current_fsgid();
4158
39279cc3
CM
4159 inode->i_mode = mode;
4160 inode->i_ino = objectid;
a76a3cd4 4161 inode_set_bytes(inode, 0);
39279cc3 4162 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5f39d397
CM
4163 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4164 struct btrfs_inode_item);
e02119d5 4165 fill_inode_item(trans, path->nodes[0], inode_item, inode);
9c58309d
CM
4166
4167 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4168 struct btrfs_inode_ref);
4169 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
00e4e6b3 4170 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
9c58309d
CM
4171 ptr = (unsigned long)(ref + 1);
4172 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4173
5f39d397
CM
4174 btrfs_mark_buffer_dirty(path->nodes[0]);
4175 btrfs_free_path(path);
4176
39279cc3
CM
4177 location = &BTRFS_I(inode)->location;
4178 location->objectid = objectid;
39279cc3
CM
4179 location->offset = 0;
4180 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4181
6cbff00f
CH
4182 btrfs_inherit_iflags(inode, dir);
4183
94272164
CM
4184 if ((mode & S_IFREG)) {
4185 if (btrfs_test_opt(root, NODATASUM))
4186 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4187 if (btrfs_test_opt(root, NODATACOW))
4188 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4189 }
4190
39279cc3 4191 insert_inode_hash(inode);
5d4f98a2 4192 inode_tree_add(inode);
39279cc3 4193 return inode;
5f39d397 4194fail:
aec7477b
JB
4195 if (dir)
4196 BTRFS_I(dir)->index_cnt--;
5f39d397 4197 btrfs_free_path(path);
09771430 4198 iput(inode);
5f39d397 4199 return ERR_PTR(ret);
39279cc3
CM
4200}
4201
4202static inline u8 btrfs_inode_type(struct inode *inode)
4203{
4204 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4205}
4206
d352ac68
CM
4207/*
4208 * utility function to add 'inode' into 'parent_inode' with
4209 * a give name and a given sequence number.
4210 * if 'add_backref' is true, also insert a backref from the
4211 * inode to the parent directory.
4212 */
e02119d5
CM
4213int btrfs_add_link(struct btrfs_trans_handle *trans,
4214 struct inode *parent_inode, struct inode *inode,
4215 const char *name, int name_len, int add_backref, u64 index)
39279cc3 4216{
4df27c4d 4217 int ret = 0;
39279cc3 4218 struct btrfs_key key;
e02119d5 4219 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5f39d397 4220
4df27c4d
YZ
4221 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4222 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4223 } else {
4224 key.objectid = inode->i_ino;
4225 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4226 key.offset = 0;
4227 }
4228
4229 if (unlikely(inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4230 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4231 key.objectid, root->root_key.objectid,
4232 parent_inode->i_ino,
4233 index, name, name_len);
4234 } else if (add_backref) {
4235 ret = btrfs_insert_inode_ref(trans, root,
4236 name, name_len, inode->i_ino,
4237 parent_inode->i_ino, index);
4238 }
39279cc3 4239
39279cc3 4240 if (ret == 0) {
4df27c4d
YZ
4241 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4242 parent_inode->i_ino, &key,
4243 btrfs_inode_type(inode), index);
4244 BUG_ON(ret);
4245
dbe674a9 4246 btrfs_i_size_write(parent_inode, parent_inode->i_size +
e02119d5 4247 name_len * 2);
79c44584 4248 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
e02119d5 4249 ret = btrfs_update_inode(trans, root, parent_inode);
39279cc3
CM
4250 }
4251 return ret;
4252}
4253
4254static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
9c58309d 4255 struct dentry *dentry, struct inode *inode,
00e4e6b3 4256 int backref, u64 index)
39279cc3 4257{
e02119d5
CM
4258 int err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4259 inode, dentry->d_name.name,
4260 dentry->d_name.len, backref, index);
39279cc3
CM
4261 if (!err) {
4262 d_instantiate(dentry, inode);
4263 return 0;
4264 }
4265 if (err > 0)
4266 err = -EEXIST;
4267 return err;
4268}
4269
618e21d5
JB
4270static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4271 int mode, dev_t rdev)
4272{
4273 struct btrfs_trans_handle *trans;
4274 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4275 struct inode *inode = NULL;
618e21d5
JB
4276 int err;
4277 int drop_inode = 0;
4278 u64 objectid;
1832a6d5 4279 unsigned long nr = 0;
00e4e6b3 4280 u64 index = 0;
618e21d5
JB
4281
4282 if (!new_valid_dev(rdev))
4283 return -EINVAL;
4284
9ed74f2d
JB
4285 /*
4286 * 2 for inode item and ref
4287 * 2 for dir items
4288 * 1 for xattr if selinux is on
4289 */
4290 err = btrfs_reserve_metadata_space(root, 5);
1832a6d5 4291 if (err)
9ed74f2d 4292 return err;
1832a6d5 4293
618e21d5 4294 trans = btrfs_start_transaction(root, 1);
9ed74f2d
JB
4295 if (!trans)
4296 goto fail;
618e21d5
JB
4297 btrfs_set_trans_block_group(trans, dir);
4298
4299 err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
4300 if (err) {
4301 err = -ENOSPC;
4302 goto out_unlock;
4303 }
4304
aec7477b 4305 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9c58309d
CM
4306 dentry->d_name.len,
4307 dentry->d_parent->d_inode->i_ino, objectid,
00e4e6b3 4308 BTRFS_I(dir)->block_group, mode, &index);
618e21d5
JB
4309 err = PTR_ERR(inode);
4310 if (IS_ERR(inode))
4311 goto out_unlock;
4312
f34f57a3 4313 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4314 if (err) {
4315 drop_inode = 1;
4316 goto out_unlock;
4317 }
4318
618e21d5 4319 btrfs_set_trans_block_group(trans, inode);
00e4e6b3 4320 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
618e21d5
JB
4321 if (err)
4322 drop_inode = 1;
4323 else {
4324 inode->i_op = &btrfs_special_inode_operations;
4325 init_special_inode(inode, inode->i_mode, rdev);
1b4ab1bb 4326 btrfs_update_inode(trans, root, inode);
618e21d5 4327 }
618e21d5
JB
4328 btrfs_update_inode_block_group(trans, inode);
4329 btrfs_update_inode_block_group(trans, dir);
4330out_unlock:
d3c2fdcf 4331 nr = trans->blocks_used;
89ce8a63 4332 btrfs_end_transaction_throttle(trans, root);
1832a6d5 4333fail:
9ed74f2d 4334 btrfs_unreserve_metadata_space(root, 5);
618e21d5
JB
4335 if (drop_inode) {
4336 inode_dec_link_count(inode);
4337 iput(inode);
4338 }
d3c2fdcf 4339 btrfs_btree_balance_dirty(root, nr);
618e21d5
JB
4340 return err;
4341}
4342
39279cc3
CM
4343static int btrfs_create(struct inode *dir, struct dentry *dentry,
4344 int mode, struct nameidata *nd)
4345{
4346 struct btrfs_trans_handle *trans;
4347 struct btrfs_root *root = BTRFS_I(dir)->root;
1832a6d5 4348 struct inode *inode = NULL;
39279cc3
CM
4349 int err;
4350 int drop_inode = 0;
1832a6d5 4351 unsigned long nr = 0;
39279cc3 4352 u64 objectid;
00e4e6b3 4353 u64 index = 0;
39279cc3 4354
9ed74f2d
JB
4355 /*
4356 * 2 for inode item and ref
4357 * 2 for dir items
4358 * 1 for xattr if selinux is on
4359 */
4360 err = btrfs_reserve_metadata_space(root, 5);
1832a6d5 4361 if (err)
9ed74f2d
JB
4362 return err;
4363
39279cc3 4364 trans = btrfs_start_transaction(root, 1);
9ed74f2d
JB
4365 if (!trans)
4366 goto fail;
39279cc3
CM
4367 btrfs_set_trans_block_group(trans, dir);
4368
4369 err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
4370 if (err) {
4371 err = -ENOSPC;
4372 goto out_unlock;
4373 }
4374
aec7477b 4375 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9c58309d
CM
4376 dentry->d_name.len,
4377 dentry->d_parent->d_inode->i_ino,
00e4e6b3
CM
4378 objectid, BTRFS_I(dir)->block_group, mode,
4379 &index);
39279cc3
CM
4380 err = PTR_ERR(inode);
4381 if (IS_ERR(inode))
4382 goto out_unlock;
4383
f34f57a3 4384 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4385 if (err) {
4386 drop_inode = 1;
4387 goto out_unlock;
4388 }
4389
39279cc3 4390 btrfs_set_trans_block_group(trans, inode);
00e4e6b3 4391 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
39279cc3
CM
4392 if (err)
4393 drop_inode = 1;
4394 else {
4395 inode->i_mapping->a_ops = &btrfs_aops;
04160088 4396 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
4397 inode->i_fop = &btrfs_file_operations;
4398 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 4399 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 4400 }
39279cc3
CM
4401 btrfs_update_inode_block_group(trans, inode);
4402 btrfs_update_inode_block_group(trans, dir);
4403out_unlock:
d3c2fdcf 4404 nr = trans->blocks_used;
ab78c84d 4405 btrfs_end_transaction_throttle(trans, root);
1832a6d5 4406fail:
9ed74f2d 4407 btrfs_unreserve_metadata_space(root, 5);
39279cc3
CM
4408 if (drop_inode) {
4409 inode_dec_link_count(inode);
4410 iput(inode);
4411 }
d3c2fdcf 4412 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4413 return err;
4414}
4415
4416static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4417 struct dentry *dentry)
4418{
4419 struct btrfs_trans_handle *trans;
4420 struct btrfs_root *root = BTRFS_I(dir)->root;
4421 struct inode *inode = old_dentry->d_inode;
00e4e6b3 4422 u64 index;
1832a6d5 4423 unsigned long nr = 0;
39279cc3
CM
4424 int err;
4425 int drop_inode = 0;
4426
4427 if (inode->i_nlink == 0)
4428 return -ENOENT;
4429
4a8be425
TH
4430 /* do not allow sys_link's with other subvols of the same device */
4431 if (root->objectid != BTRFS_I(inode)->root->objectid)
4432 return -EPERM;
4433
9ed74f2d
JB
4434 /*
4435 * 1 item for inode ref
4436 * 2 items for dir items
4437 */
4438 err = btrfs_reserve_metadata_space(root, 3);
1832a6d5 4439 if (err)
9ed74f2d
JB
4440 return err;
4441
4442 btrfs_inc_nlink(inode);
4443
3de4586c 4444 err = btrfs_set_inode_index(dir, &index);
aec7477b
JB
4445 if (err)
4446 goto fail;
4447
39279cc3 4448 trans = btrfs_start_transaction(root, 1);
5f39d397 4449
39279cc3
CM
4450 btrfs_set_trans_block_group(trans, dir);
4451 atomic_inc(&inode->i_count);
aec7477b 4452
00e4e6b3 4453 err = btrfs_add_nondir(trans, dentry, inode, 1, index);
5f39d397 4454
a5719521 4455 if (err) {
54aa1f4d 4456 drop_inode = 1;
a5719521
YZ
4457 } else {
4458 btrfs_update_inode_block_group(trans, dir);
4459 err = btrfs_update_inode(trans, root, inode);
4460 BUG_ON(err);
4461 btrfs_log_new_name(trans, inode, NULL, dentry->d_parent);
4462 }
39279cc3 4463
d3c2fdcf 4464 nr = trans->blocks_used;
ab78c84d 4465 btrfs_end_transaction_throttle(trans, root);
1832a6d5 4466fail:
9ed74f2d 4467 btrfs_unreserve_metadata_space(root, 3);
39279cc3
CM
4468 if (drop_inode) {
4469 inode_dec_link_count(inode);
4470 iput(inode);
4471 }
d3c2fdcf 4472 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4473 return err;
4474}
4475
39279cc3
CM
4476static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
4477{
b9d86667 4478 struct inode *inode = NULL;
39279cc3
CM
4479 struct btrfs_trans_handle *trans;
4480 struct btrfs_root *root = BTRFS_I(dir)->root;
4481 int err = 0;
4482 int drop_on_err = 0;
b9d86667 4483 u64 objectid = 0;
00e4e6b3 4484 u64 index = 0;
d3c2fdcf 4485 unsigned long nr = 1;
39279cc3 4486
9ed74f2d
JB
4487 /*
4488 * 2 items for inode and ref
4489 * 2 items for dir items
4490 * 1 for xattr if selinux is on
4491 */
4492 err = btrfs_reserve_metadata_space(root, 5);
1832a6d5 4493 if (err)
9ed74f2d 4494 return err;
1832a6d5 4495
39279cc3 4496 trans = btrfs_start_transaction(root, 1);
9ed74f2d
JB
4497 if (!trans) {
4498 err = -ENOMEM;
39279cc3
CM
4499 goto out_unlock;
4500 }
9ed74f2d 4501 btrfs_set_trans_block_group(trans, dir);
39279cc3
CM
4502
4503 err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
4504 if (err) {
4505 err = -ENOSPC;
4506 goto out_unlock;
4507 }
4508
aec7477b 4509 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9c58309d
CM
4510 dentry->d_name.len,
4511 dentry->d_parent->d_inode->i_ino, objectid,
00e4e6b3
CM
4512 BTRFS_I(dir)->block_group, S_IFDIR | mode,
4513 &index);
39279cc3
CM
4514 if (IS_ERR(inode)) {
4515 err = PTR_ERR(inode);
4516 goto out_fail;
4517 }
5f39d397 4518
39279cc3 4519 drop_on_err = 1;
33268eaf 4520
f34f57a3 4521 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
4522 if (err)
4523 goto out_fail;
4524
39279cc3
CM
4525 inode->i_op = &btrfs_dir_inode_operations;
4526 inode->i_fop = &btrfs_dir_file_operations;
4527 btrfs_set_trans_block_group(trans, inode);
4528
dbe674a9 4529 btrfs_i_size_write(inode, 0);
39279cc3
CM
4530 err = btrfs_update_inode(trans, root, inode);
4531 if (err)
4532 goto out_fail;
5f39d397 4533
e02119d5
CM
4534 err = btrfs_add_link(trans, dentry->d_parent->d_inode,
4535 inode, dentry->d_name.name,
4536 dentry->d_name.len, 0, index);
39279cc3
CM
4537 if (err)
4538 goto out_fail;
5f39d397 4539
39279cc3
CM
4540 d_instantiate(dentry, inode);
4541 drop_on_err = 0;
39279cc3
CM
4542 btrfs_update_inode_block_group(trans, inode);
4543 btrfs_update_inode_block_group(trans, dir);
4544
4545out_fail:
d3c2fdcf 4546 nr = trans->blocks_used;
ab78c84d 4547 btrfs_end_transaction_throttle(trans, root);
5f39d397 4548
39279cc3 4549out_unlock:
9ed74f2d 4550 btrfs_unreserve_metadata_space(root, 5);
39279cc3
CM
4551 if (drop_on_err)
4552 iput(inode);
d3c2fdcf 4553 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
4554 return err;
4555}
4556
d352ac68
CM
4557/* helper for btfs_get_extent. Given an existing extent in the tree,
4558 * and an extent that you want to insert, deal with overlap and insert
4559 * the new extent into the tree.
4560 */
3b951516
CM
4561static int merge_extent_mapping(struct extent_map_tree *em_tree,
4562 struct extent_map *existing,
e6dcd2dc
CM
4563 struct extent_map *em,
4564 u64 map_start, u64 map_len)
3b951516
CM
4565{
4566 u64 start_diff;
3b951516 4567
e6dcd2dc
CM
4568 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
4569 start_diff = map_start - em->start;
4570 em->start = map_start;
4571 em->len = map_len;
c8b97818
CM
4572 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
4573 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
e6dcd2dc 4574 em->block_start += start_diff;
c8b97818
CM
4575 em->block_len -= start_diff;
4576 }
e6dcd2dc 4577 return add_extent_mapping(em_tree, em);
3b951516
CM
4578}
4579
c8b97818
CM
4580static noinline int uncompress_inline(struct btrfs_path *path,
4581 struct inode *inode, struct page *page,
4582 size_t pg_offset, u64 extent_offset,
4583 struct btrfs_file_extent_item *item)
4584{
4585 int ret;
4586 struct extent_buffer *leaf = path->nodes[0];
4587 char *tmp;
4588 size_t max_size;
4589 unsigned long inline_size;
4590 unsigned long ptr;
4591
4592 WARN_ON(pg_offset != 0);
4593 max_size = btrfs_file_extent_ram_bytes(leaf, item);
4594 inline_size = btrfs_file_extent_inline_item_len(leaf,
4595 btrfs_item_nr(leaf, path->slots[0]));
4596 tmp = kmalloc(inline_size, GFP_NOFS);
4597 ptr = btrfs_file_extent_inline_start(item);
4598
4599 read_extent_buffer(leaf, tmp, ptr, inline_size);
4600
5b050f04 4601 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
c8b97818
CM
4602 ret = btrfs_zlib_decompress(tmp, page, extent_offset,
4603 inline_size, max_size);
4604 if (ret) {
4605 char *kaddr = kmap_atomic(page, KM_USER0);
4606 unsigned long copy_size = min_t(u64,
4607 PAGE_CACHE_SIZE - pg_offset,
4608 max_size - extent_offset);
4609 memset(kaddr + pg_offset, 0, copy_size);
4610 kunmap_atomic(kaddr, KM_USER0);
4611 }
4612 kfree(tmp);
4613 return 0;
4614}
4615
d352ac68
CM
4616/*
4617 * a bit scary, this does extent mapping from logical file offset to the disk.
d397712b
CM
4618 * the ugly parts come from merging extents from the disk with the in-ram
4619 * representation. This gets more complex because of the data=ordered code,
d352ac68
CM
4620 * where the in-ram extents might be locked pending data=ordered completion.
4621 *
4622 * This also copies inline extents directly into the page.
4623 */
d397712b 4624
a52d9a80 4625struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
70dec807 4626 size_t pg_offset, u64 start, u64 len,
a52d9a80
CM
4627 int create)
4628{
4629 int ret;
4630 int err = 0;
db94535d 4631 u64 bytenr;
a52d9a80
CM
4632 u64 extent_start = 0;
4633 u64 extent_end = 0;
4634 u64 objectid = inode->i_ino;
4635 u32 found_type;
f421950f 4636 struct btrfs_path *path = NULL;
a52d9a80
CM
4637 struct btrfs_root *root = BTRFS_I(inode)->root;
4638 struct btrfs_file_extent_item *item;
5f39d397
CM
4639 struct extent_buffer *leaf;
4640 struct btrfs_key found_key;
a52d9a80
CM
4641 struct extent_map *em = NULL;
4642 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
d1310b2e 4643 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
a52d9a80 4644 struct btrfs_trans_handle *trans = NULL;
c8b97818 4645 int compressed;
a52d9a80 4646
a52d9a80 4647again:
890871be 4648 read_lock(&em_tree->lock);
d1310b2e 4649 em = lookup_extent_mapping(em_tree, start, len);
a061fc8d
CM
4650 if (em)
4651 em->bdev = root->fs_info->fs_devices->latest_bdev;
890871be 4652 read_unlock(&em_tree->lock);
d1310b2e 4653
a52d9a80 4654 if (em) {
e1c4b745
CM
4655 if (em->start > start || em->start + em->len <= start)
4656 free_extent_map(em);
4657 else if (em->block_start == EXTENT_MAP_INLINE && page)
70dec807
CM
4658 free_extent_map(em);
4659 else
4660 goto out;
a52d9a80 4661 }
d1310b2e 4662 em = alloc_extent_map(GFP_NOFS);
a52d9a80 4663 if (!em) {
d1310b2e
CM
4664 err = -ENOMEM;
4665 goto out;
a52d9a80 4666 }
e6dcd2dc 4667 em->bdev = root->fs_info->fs_devices->latest_bdev;
d1310b2e 4668 em->start = EXTENT_MAP_HOLE;
445a6944 4669 em->orig_start = EXTENT_MAP_HOLE;
d1310b2e 4670 em->len = (u64)-1;
c8b97818 4671 em->block_len = (u64)-1;
f421950f
CM
4672
4673 if (!path) {
4674 path = btrfs_alloc_path();
4675 BUG_ON(!path);
4676 }
4677
179e29e4
CM
4678 ret = btrfs_lookup_file_extent(trans, root, path,
4679 objectid, start, trans != NULL);
a52d9a80
CM
4680 if (ret < 0) {
4681 err = ret;
4682 goto out;
4683 }
4684
4685 if (ret != 0) {
4686 if (path->slots[0] == 0)
4687 goto not_found;
4688 path->slots[0]--;
4689 }
4690
5f39d397
CM
4691 leaf = path->nodes[0];
4692 item = btrfs_item_ptr(leaf, path->slots[0],
a52d9a80 4693 struct btrfs_file_extent_item);
a52d9a80 4694 /* are we inside the extent that was found? */
5f39d397
CM
4695 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4696 found_type = btrfs_key_type(&found_key);
4697 if (found_key.objectid != objectid ||
a52d9a80
CM
4698 found_type != BTRFS_EXTENT_DATA_KEY) {
4699 goto not_found;
4700 }
4701
5f39d397
CM
4702 found_type = btrfs_file_extent_type(leaf, item);
4703 extent_start = found_key.offset;
c8b97818 4704 compressed = btrfs_file_extent_compression(leaf, item);
d899e052
YZ
4705 if (found_type == BTRFS_FILE_EXTENT_REG ||
4706 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
a52d9a80 4707 extent_end = extent_start +
db94535d 4708 btrfs_file_extent_num_bytes(leaf, item);
9036c102
YZ
4709 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
4710 size_t size;
4711 size = btrfs_file_extent_inline_len(leaf, item);
4712 extent_end = (extent_start + size + root->sectorsize - 1) &
4713 ~((u64)root->sectorsize - 1);
4714 }
4715
4716 if (start >= extent_end) {
4717 path->slots[0]++;
4718 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
4719 ret = btrfs_next_leaf(root, path);
4720 if (ret < 0) {
4721 err = ret;
4722 goto out;
a52d9a80 4723 }
9036c102
YZ
4724 if (ret > 0)
4725 goto not_found;
4726 leaf = path->nodes[0];
a52d9a80 4727 }
9036c102
YZ
4728 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4729 if (found_key.objectid != objectid ||
4730 found_key.type != BTRFS_EXTENT_DATA_KEY)
4731 goto not_found;
4732 if (start + len <= found_key.offset)
4733 goto not_found;
4734 em->start = start;
4735 em->len = found_key.offset - start;
4736 goto not_found_em;
4737 }
4738
d899e052
YZ
4739 if (found_type == BTRFS_FILE_EXTENT_REG ||
4740 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
9036c102
YZ
4741 em->start = extent_start;
4742 em->len = extent_end - extent_start;
ff5b7ee3
YZ
4743 em->orig_start = extent_start -
4744 btrfs_file_extent_offset(leaf, item);
db94535d
CM
4745 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
4746 if (bytenr == 0) {
5f39d397 4747 em->block_start = EXTENT_MAP_HOLE;
a52d9a80
CM
4748 goto insert;
4749 }
c8b97818
CM
4750 if (compressed) {
4751 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
4752 em->block_start = bytenr;
4753 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
4754 item);
4755 } else {
4756 bytenr += btrfs_file_extent_offset(leaf, item);
4757 em->block_start = bytenr;
4758 em->block_len = em->len;
d899e052
YZ
4759 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
4760 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
c8b97818 4761 }
a52d9a80
CM
4762 goto insert;
4763 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5f39d397 4764 unsigned long ptr;
a52d9a80 4765 char *map;
3326d1b0
CM
4766 size_t size;
4767 size_t extent_offset;
4768 size_t copy_size;
a52d9a80 4769
689f9346 4770 em->block_start = EXTENT_MAP_INLINE;
c8b97818 4771 if (!page || create) {
689f9346 4772 em->start = extent_start;
9036c102 4773 em->len = extent_end - extent_start;
689f9346
Y
4774 goto out;
4775 }
5f39d397 4776
9036c102
YZ
4777 size = btrfs_file_extent_inline_len(leaf, item);
4778 extent_offset = page_offset(page) + pg_offset - extent_start;
70dec807 4779 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
3326d1b0 4780 size - extent_offset);
3326d1b0 4781 em->start = extent_start + extent_offset;
70dec807
CM
4782 em->len = (copy_size + root->sectorsize - 1) &
4783 ~((u64)root->sectorsize - 1);
ff5b7ee3 4784 em->orig_start = EXTENT_MAP_INLINE;
c8b97818
CM
4785 if (compressed)
4786 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
689f9346 4787 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
179e29e4 4788 if (create == 0 && !PageUptodate(page)) {
c8b97818
CM
4789 if (btrfs_file_extent_compression(leaf, item) ==
4790 BTRFS_COMPRESS_ZLIB) {
4791 ret = uncompress_inline(path, inode, page,
4792 pg_offset,
4793 extent_offset, item);
4794 BUG_ON(ret);
4795 } else {
4796 map = kmap(page);
4797 read_extent_buffer(leaf, map + pg_offset, ptr,
4798 copy_size);
93c82d57
CM
4799 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
4800 memset(map + pg_offset + copy_size, 0,
4801 PAGE_CACHE_SIZE - pg_offset -
4802 copy_size);
4803 }
c8b97818
CM
4804 kunmap(page);
4805 }
179e29e4
CM
4806 flush_dcache_page(page);
4807 } else if (create && PageUptodate(page)) {
4808 if (!trans) {
4809 kunmap(page);
4810 free_extent_map(em);
4811 em = NULL;
4812 btrfs_release_path(root, path);
f9295749 4813 trans = btrfs_join_transaction(root, 1);
179e29e4
CM
4814 goto again;
4815 }
c8b97818 4816 map = kmap(page);
70dec807 4817 write_extent_buffer(leaf, map + pg_offset, ptr,
179e29e4 4818 copy_size);
c8b97818 4819 kunmap(page);
179e29e4 4820 btrfs_mark_buffer_dirty(leaf);
a52d9a80 4821 }
d1310b2e
CM
4822 set_extent_uptodate(io_tree, em->start,
4823 extent_map_end(em) - 1, GFP_NOFS);
a52d9a80
CM
4824 goto insert;
4825 } else {
d397712b 4826 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
a52d9a80
CM
4827 WARN_ON(1);
4828 }
4829not_found:
4830 em->start = start;
d1310b2e 4831 em->len = len;
a52d9a80 4832not_found_em:
5f39d397 4833 em->block_start = EXTENT_MAP_HOLE;
9036c102 4834 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
a52d9a80
CM
4835insert:
4836 btrfs_release_path(root, path);
d1310b2e 4837 if (em->start > start || extent_map_end(em) <= start) {
d397712b
CM
4838 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
4839 "[%llu %llu]\n", (unsigned long long)em->start,
4840 (unsigned long long)em->len,
4841 (unsigned long long)start,
4842 (unsigned long long)len);
a52d9a80
CM
4843 err = -EIO;
4844 goto out;
4845 }
d1310b2e
CM
4846
4847 err = 0;
890871be 4848 write_lock(&em_tree->lock);
a52d9a80 4849 ret = add_extent_mapping(em_tree, em);
3b951516
CM
4850 /* it is possible that someone inserted the extent into the tree
4851 * while we had the lock dropped. It is also possible that
4852 * an overlapping map exists in the tree
4853 */
a52d9a80 4854 if (ret == -EEXIST) {
3b951516 4855 struct extent_map *existing;
e6dcd2dc
CM
4856
4857 ret = 0;
4858
3b951516 4859 existing = lookup_extent_mapping(em_tree, start, len);
e1c4b745
CM
4860 if (existing && (existing->start > start ||
4861 existing->start + existing->len <= start)) {
4862 free_extent_map(existing);
4863 existing = NULL;
4864 }
3b951516
CM
4865 if (!existing) {
4866 existing = lookup_extent_mapping(em_tree, em->start,
4867 em->len);
4868 if (existing) {
4869 err = merge_extent_mapping(em_tree, existing,
e6dcd2dc
CM
4870 em, start,
4871 root->sectorsize);
3b951516
CM
4872 free_extent_map(existing);
4873 if (err) {
4874 free_extent_map(em);
4875 em = NULL;
4876 }
4877 } else {
4878 err = -EIO;
3b951516
CM
4879 free_extent_map(em);
4880 em = NULL;
4881 }
4882 } else {
4883 free_extent_map(em);
4884 em = existing;
e6dcd2dc 4885 err = 0;
a52d9a80 4886 }
a52d9a80 4887 }
890871be 4888 write_unlock(&em_tree->lock);
a52d9a80 4889out:
f421950f
CM
4890 if (path)
4891 btrfs_free_path(path);
a52d9a80
CM
4892 if (trans) {
4893 ret = btrfs_end_transaction(trans, root);
d397712b 4894 if (!err)
a52d9a80
CM
4895 err = ret;
4896 }
a52d9a80
CM
4897 if (err) {
4898 free_extent_map(em);
a52d9a80
CM
4899 return ERR_PTR(err);
4900 }
4901 return em;
4902}
4903
16432985
CM
4904static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
4905 const struct iovec *iov, loff_t offset,
4906 unsigned long nr_segs)
4907{
e1c4b745 4908 return -EINVAL;
16432985
CM
4909}
4910
1506fcc8
YS
4911static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
4912 __u64 start, __u64 len)
4913{
4914 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent);
4915}
4916
a52d9a80 4917int btrfs_readpage(struct file *file, struct page *page)
9ebefb18 4918{
d1310b2e
CM
4919 struct extent_io_tree *tree;
4920 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 4921 return extent_read_full_page(tree, page, btrfs_get_extent);
9ebefb18 4922}
1832a6d5 4923
a52d9a80 4924static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
39279cc3 4925{
d1310b2e 4926 struct extent_io_tree *tree;
b888db2b
CM
4927
4928
4929 if (current->flags & PF_MEMALLOC) {
4930 redirty_page_for_writepage(wbc, page);
4931 unlock_page(page);
4932 return 0;
4933 }
d1310b2e 4934 tree = &BTRFS_I(page->mapping->host)->io_tree;
a52d9a80 4935 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
9ebefb18
CM
4936}
4937
f421950f
CM
4938int btrfs_writepages(struct address_space *mapping,
4939 struct writeback_control *wbc)
b293f02e 4940{
d1310b2e 4941 struct extent_io_tree *tree;
771ed689 4942
d1310b2e 4943 tree = &BTRFS_I(mapping->host)->io_tree;
b293f02e
CM
4944 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
4945}
4946
3ab2fb5a
CM
4947static int
4948btrfs_readpages(struct file *file, struct address_space *mapping,
4949 struct list_head *pages, unsigned nr_pages)
4950{
d1310b2e
CM
4951 struct extent_io_tree *tree;
4952 tree = &BTRFS_I(mapping->host)->io_tree;
3ab2fb5a
CM
4953 return extent_readpages(tree, mapping, pages, nr_pages,
4954 btrfs_get_extent);
4955}
e6dcd2dc 4956static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
9ebefb18 4957{
d1310b2e
CM
4958 struct extent_io_tree *tree;
4959 struct extent_map_tree *map;
a52d9a80 4960 int ret;
8c2383c3 4961
d1310b2e
CM
4962 tree = &BTRFS_I(page->mapping->host)->io_tree;
4963 map = &BTRFS_I(page->mapping->host)->extent_tree;
70dec807 4964 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
a52d9a80
CM
4965 if (ret == 1) {
4966 ClearPagePrivate(page);
4967 set_page_private(page, 0);
4968 page_cache_release(page);
39279cc3 4969 }
a52d9a80 4970 return ret;
39279cc3
CM
4971}
4972
e6dcd2dc
CM
4973static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
4974{
98509cfc
CM
4975 if (PageWriteback(page) || PageDirty(page))
4976 return 0;
b335b003 4977 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
e6dcd2dc
CM
4978}
4979
a52d9a80 4980static void btrfs_invalidatepage(struct page *page, unsigned long offset)
39279cc3 4981{
d1310b2e 4982 struct extent_io_tree *tree;
e6dcd2dc
CM
4983 struct btrfs_ordered_extent *ordered;
4984 u64 page_start = page_offset(page);
4985 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
39279cc3 4986
8b62b72b
CM
4987
4988 /*
4989 * we have the page locked, so new writeback can't start,
4990 * and the dirty bit won't be cleared while we are here.
4991 *
4992 * Wait for IO on this page so that we can safely clear
4993 * the PagePrivate2 bit and do ordered accounting
4994 */
e6dcd2dc 4995 wait_on_page_writeback(page);
8b62b72b 4996
d1310b2e 4997 tree = &BTRFS_I(page->mapping->host)->io_tree;
e6dcd2dc
CM
4998 if (offset) {
4999 btrfs_releasepage(page, GFP_NOFS);
5000 return;
5001 }
e6dcd2dc
CM
5002 lock_extent(tree, page_start, page_end, GFP_NOFS);
5003 ordered = btrfs_lookup_ordered_extent(page->mapping->host,
5004 page_offset(page));
5005 if (ordered) {
eb84ae03
CM
5006 /*
5007 * IO on this page will never be started, so we need
5008 * to account for any ordered extents now
5009 */
e6dcd2dc
CM
5010 clear_extent_bit(tree, page_start, page_end,
5011 EXTENT_DIRTY | EXTENT_DELALLOC |
32c00aff
JB
5012 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
5013 NULL, GFP_NOFS);
8b62b72b
CM
5014 /*
5015 * whoever cleared the private bit is responsible
5016 * for the finish_ordered_io
5017 */
5018 if (TestClearPagePrivate2(page)) {
5019 btrfs_finish_ordered_io(page->mapping->host,
5020 page_start, page_end);
5021 }
e6dcd2dc
CM
5022 btrfs_put_ordered_extent(ordered);
5023 lock_extent(tree, page_start, page_end, GFP_NOFS);
5024 }
5025 clear_extent_bit(tree, page_start, page_end,
32c00aff
JB
5026 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
5027 EXTENT_DO_ACCOUNTING, 1, 1, NULL, GFP_NOFS);
e6dcd2dc
CM
5028 __btrfs_releasepage(page, GFP_NOFS);
5029
4a096752 5030 ClearPageChecked(page);
9ad6b7bc 5031 if (PagePrivate(page)) {
9ad6b7bc
CM
5032 ClearPagePrivate(page);
5033 set_page_private(page, 0);
5034 page_cache_release(page);
5035 }
39279cc3
CM
5036}
5037
9ebefb18
CM
5038/*
5039 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
5040 * called from a page fault handler when a page is first dirtied. Hence we must
5041 * be careful to check for EOF conditions here. We set the page up correctly
5042 * for a written page which means we get ENOSPC checking when writing into
5043 * holes and correct delalloc and unwritten extent mapping on filesystems that
5044 * support these features.
5045 *
5046 * We are not allowed to take the i_mutex here so we have to play games to
5047 * protect against truncate races as the page could now be beyond EOF. Because
5048 * vmtruncate() writes the inode size before removing pages, once we have the
5049 * page lock we can determine safely if the page is beyond EOF. If it is not
5050 * beyond EOF, then the page is guaranteed safe against truncation until we
5051 * unlock the page.
5052 */
c2ec175c 5053int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
9ebefb18 5054{
c2ec175c 5055 struct page *page = vmf->page;
6da6abae 5056 struct inode *inode = fdentry(vma->vm_file)->d_inode;
1832a6d5 5057 struct btrfs_root *root = BTRFS_I(inode)->root;
e6dcd2dc
CM
5058 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5059 struct btrfs_ordered_extent *ordered;
5060 char *kaddr;
5061 unsigned long zero_start;
9ebefb18 5062 loff_t size;
1832a6d5 5063 int ret;
a52d9a80 5064 u64 page_start;
e6dcd2dc 5065 u64 page_end;
9ebefb18 5066
6a63209f 5067 ret = btrfs_check_data_free_space(root, inode, PAGE_CACHE_SIZE);
56a76f82
NP
5068 if (ret) {
5069 if (ret == -ENOMEM)
5070 ret = VM_FAULT_OOM;
5071 else /* -ENOSPC, -EIO, etc */
5072 ret = VM_FAULT_SIGBUS;
1832a6d5 5073 goto out;
56a76f82 5074 }
1832a6d5 5075
9ed74f2d
JB
5076 ret = btrfs_reserve_metadata_for_delalloc(root, inode, 1);
5077 if (ret) {
5078 btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
5079 ret = VM_FAULT_SIGBUS;
5080 goto out;
5081 }
5082
56a76f82 5083 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
e6dcd2dc 5084again:
9ebefb18 5085 lock_page(page);
9ebefb18 5086 size = i_size_read(inode);
e6dcd2dc
CM
5087 page_start = page_offset(page);
5088 page_end = page_start + PAGE_CACHE_SIZE - 1;
a52d9a80 5089
9ebefb18 5090 if ((page->mapping != inode->i_mapping) ||
e6dcd2dc 5091 (page_start >= size)) {
6a63209f 5092 btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
9ebefb18
CM
5093 /* page got truncated out from underneath us */
5094 goto out_unlock;
5095 }
e6dcd2dc
CM
5096 wait_on_page_writeback(page);
5097
5098 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
5099 set_page_extent_mapped(page);
5100
eb84ae03
CM
5101 /*
5102 * we can't set the delalloc bits if there are pending ordered
5103 * extents. Drop our locks and wait for them to finish
5104 */
e6dcd2dc
CM
5105 ordered = btrfs_lookup_ordered_extent(inode, page_start);
5106 if (ordered) {
5107 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
5108 unlock_page(page);
eb84ae03 5109 btrfs_start_ordered_extent(inode, ordered, 1);
e6dcd2dc
CM
5110 btrfs_put_ordered_extent(ordered);
5111 goto again;
5112 }
5113
fbf19087
JB
5114 /*
5115 * XXX - page_mkwrite gets called every time the page is dirtied, even
5116 * if it was already dirty, so for space accounting reasons we need to
5117 * clear any delalloc bits for the range we are fixing to save. There
5118 * is probably a better way to do this, but for now keep consistent with
5119 * prepare_pages in the normal write path.
5120 */
5121 clear_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
32c00aff
JB
5122 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
5123 GFP_NOFS);
fbf19087 5124
9ed74f2d
JB
5125 ret = btrfs_set_extent_delalloc(inode, page_start, page_end);
5126 if (ret) {
5127 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
5128 ret = VM_FAULT_SIGBUS;
fbf19087 5129 btrfs_free_reserved_data_space(root, inode, PAGE_CACHE_SIZE);
9ed74f2d
JB
5130 goto out_unlock;
5131 }
e6dcd2dc 5132 ret = 0;
9ebefb18
CM
5133
5134 /* page is wholly or partially inside EOF */
a52d9a80 5135 if (page_start + PAGE_CACHE_SIZE > size)
e6dcd2dc 5136 zero_start = size & ~PAGE_CACHE_MASK;
9ebefb18 5137 else
e6dcd2dc 5138 zero_start = PAGE_CACHE_SIZE;
9ebefb18 5139
e6dcd2dc
CM
5140 if (zero_start != PAGE_CACHE_SIZE) {
5141 kaddr = kmap(page);
5142 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
5143 flush_dcache_page(page);
5144 kunmap(page);
5145 }
247e743c 5146 ClearPageChecked(page);
e6dcd2dc 5147 set_page_dirty(page);
50a9b214 5148 SetPageUptodate(page);
5a3f23d5 5149
257c62e1
CM
5150 BTRFS_I(inode)->last_trans = root->fs_info->generation;
5151 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
5152
e6dcd2dc 5153 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
9ebefb18
CM
5154
5155out_unlock:
9ed74f2d 5156 btrfs_unreserve_metadata_for_delalloc(root, inode, 1);
50a9b214
CM
5157 if (!ret)
5158 return VM_FAULT_LOCKED;
9ebefb18 5159 unlock_page(page);
1832a6d5 5160out:
9ebefb18
CM
5161 return ret;
5162}
5163
39279cc3
CM
5164static void btrfs_truncate(struct inode *inode)
5165{
5166 struct btrfs_root *root = BTRFS_I(inode)->root;
5167 int ret;
5168 struct btrfs_trans_handle *trans;
d3c2fdcf 5169 unsigned long nr;
dbe674a9 5170 u64 mask = root->sectorsize - 1;
39279cc3 5171
8082510e
YZ
5172 if (!S_ISREG(inode->i_mode)) {
5173 WARN_ON(1);
39279cc3 5174 return;
8082510e 5175 }
39279cc3 5176
5d5e103a
JB
5177 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
5178 if (ret)
5179 return;
8082510e 5180
4a096752 5181 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
8082510e 5182 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
39279cc3 5183
39279cc3 5184 trans = btrfs_start_transaction(root, 1);
8082510e 5185 btrfs_set_trans_block_group(trans, inode);
5a3f23d5
CM
5186
5187 /*
5188 * setattr is responsible for setting the ordered_data_close flag,
5189 * but that is only tested during the last file release. That
5190 * could happen well after the next commit, leaving a great big
5191 * window where new writes may get lost if someone chooses to write
5192 * to this file after truncating to zero
5193 *
5194 * The inode doesn't have any dirty data here, and so if we commit
5195 * this is a noop. If someone immediately starts writing to the inode
5196 * it is very likely we'll catch some of their writes in this
5197 * transaction, and the commit will find this file on the ordered
5198 * data list with good things to send down.
5199 *
5200 * This is a best effort solution, there is still a window where
5201 * using truncate to replace the contents of the file will
5202 * end up with a zero length file after a crash.
5203 */
5204 if (inode->i_size == 0 && BTRFS_I(inode)->ordered_data_close)
5205 btrfs_add_ordered_operation(trans, root, inode);
5206
8082510e
YZ
5207 while (1) {
5208 ret = btrfs_truncate_inode_items(trans, root, inode,
5209 inode->i_size,
5210 BTRFS_EXTENT_DATA_KEY);
5211 if (ret != -EAGAIN)
5212 break;
39279cc3 5213
8082510e
YZ
5214 ret = btrfs_update_inode(trans, root, inode);
5215 BUG_ON(ret);
5f39d397 5216
8082510e
YZ
5217 nr = trans->blocks_used;
5218 btrfs_end_transaction(trans, root);
5219 btrfs_btree_balance_dirty(root, nr);
5220
5221 trans = btrfs_start_transaction(root, 1);
5222 btrfs_set_trans_block_group(trans, inode);
5223 }
5224
5225 if (ret == 0 && inode->i_nlink > 0) {
5226 ret = btrfs_orphan_del(trans, inode);
5227 BUG_ON(ret);
5228 }
5229
5230 ret = btrfs_update_inode(trans, root, inode);
7b128766
JB
5231 BUG_ON(ret);
5232
7b128766 5233 nr = trans->blocks_used;
89ce8a63 5234 ret = btrfs_end_transaction_throttle(trans, root);
39279cc3 5235 BUG_ON(ret);
d3c2fdcf 5236 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
5237}
5238
d352ac68
CM
5239/*
5240 * create a new subvolume directory/inode (helper for the ioctl).
5241 */
d2fb3437 5242int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
76dda93c 5243 struct btrfs_root *new_root,
d2fb3437 5244 u64 new_dirid, u64 alloc_hint)
39279cc3 5245{
39279cc3 5246 struct inode *inode;
76dda93c 5247 int err;
00e4e6b3 5248 u64 index = 0;
39279cc3 5249
aec7477b 5250 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid,
d2fb3437 5251 new_dirid, alloc_hint, S_IFDIR | 0700, &index);
54aa1f4d 5252 if (IS_ERR(inode))
f46b5a66 5253 return PTR_ERR(inode);
39279cc3
CM
5254 inode->i_op = &btrfs_dir_inode_operations;
5255 inode->i_fop = &btrfs_dir_file_operations;
5256
39279cc3 5257 inode->i_nlink = 1;
dbe674a9 5258 btrfs_i_size_write(inode, 0);
3b96362c 5259
76dda93c
YZ
5260 err = btrfs_update_inode(trans, new_root, inode);
5261 BUG_ON(err);
cb8e7090 5262
76dda93c 5263 iput(inode);
cb8e7090 5264 return 0;
39279cc3
CM
5265}
5266
d352ac68
CM
5267/* helper function for file defrag and space balancing. This
5268 * forces readahead on a given range of bytes in an inode
5269 */
edbd8d4e 5270unsigned long btrfs_force_ra(struct address_space *mapping,
86479a04
CM
5271 struct file_ra_state *ra, struct file *file,
5272 pgoff_t offset, pgoff_t last_index)
5273{
8e7bf94f 5274 pgoff_t req_size = last_index - offset + 1;
86479a04 5275
86479a04
CM
5276 page_cache_sync_readahead(mapping, ra, file, offset, req_size);
5277 return offset + req_size;
86479a04
CM
5278}
5279
39279cc3
CM
5280struct inode *btrfs_alloc_inode(struct super_block *sb)
5281{
5282 struct btrfs_inode *ei;
5283
5284 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
5285 if (!ei)
5286 return NULL;
15ee9bc7 5287 ei->last_trans = 0;
257c62e1 5288 ei->last_sub_trans = 0;
e02119d5 5289 ei->logged_trans = 0;
32c00aff
JB
5290 ei->outstanding_extents = 0;
5291 ei->reserved_extents = 0;
a6dbd429 5292 ei->root = NULL;
32c00aff 5293 spin_lock_init(&ei->accounting_lock);
e6dcd2dc 5294 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7b128766 5295 INIT_LIST_HEAD(&ei->i_orphan);
5a3f23d5 5296 INIT_LIST_HEAD(&ei->ordered_operations);
39279cc3
CM
5297 return &ei->vfs_inode;
5298}
5299
5300void btrfs_destroy_inode(struct inode *inode)
5301{
e6dcd2dc 5302 struct btrfs_ordered_extent *ordered;
5a3f23d5
CM
5303 struct btrfs_root *root = BTRFS_I(inode)->root;
5304
39279cc3
CM
5305 WARN_ON(!list_empty(&inode->i_dentry));
5306 WARN_ON(inode->i_data.nrpages);
5307
a6dbd429
JB
5308 /*
5309 * This can happen where we create an inode, but somebody else also
5310 * created the same inode and we need to destroy the one we already
5311 * created.
5312 */
5313 if (!root)
5314 goto free;
5315
5a3f23d5
CM
5316 /*
5317 * Make sure we're properly removed from the ordered operation
5318 * lists.
5319 */
5320 smp_mb();
5321 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
5322 spin_lock(&root->fs_info->ordered_extent_lock);
5323 list_del_init(&BTRFS_I(inode)->ordered_operations);
5324 spin_unlock(&root->fs_info->ordered_extent_lock);
5325 }
5326
5327 spin_lock(&root->list_lock);
7b128766 5328 if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
8082510e
YZ
5329 printk(KERN_INFO "BTRFS: inode %lu still on the orphan list\n",
5330 inode->i_ino);
5331 list_del_init(&BTRFS_I(inode)->i_orphan);
7b128766 5332 }
5a3f23d5 5333 spin_unlock(&root->list_lock);
7b128766 5334
d397712b 5335 while (1) {
e6dcd2dc
CM
5336 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
5337 if (!ordered)
5338 break;
5339 else {
d397712b
CM
5340 printk(KERN_ERR "btrfs found ordered "
5341 "extent %llu %llu on inode cleanup\n",
5342 (unsigned long long)ordered->file_offset,
5343 (unsigned long long)ordered->len);
e6dcd2dc
CM
5344 btrfs_remove_ordered_extent(inode, ordered);
5345 btrfs_put_ordered_extent(ordered);
5346 btrfs_put_ordered_extent(ordered);
5347 }
5348 }
5d4f98a2 5349 inode_tree_del(inode);
5b21f2ed 5350 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
a6dbd429 5351free:
39279cc3
CM
5352 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
5353}
5354
76dda93c
YZ
5355void btrfs_drop_inode(struct inode *inode)
5356{
5357 struct btrfs_root *root = BTRFS_I(inode)->root;
5358
5359 if (inode->i_nlink > 0 && btrfs_root_refs(&root->root_item) == 0)
5360 generic_delete_inode(inode);
5361 else
5362 generic_drop_inode(inode);
5363}
5364
0ee0fda0 5365static void init_once(void *foo)
39279cc3
CM
5366{
5367 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
5368
5369 inode_init_once(&ei->vfs_inode);
5370}
5371
5372void btrfs_destroy_cachep(void)
5373{
5374 if (btrfs_inode_cachep)
5375 kmem_cache_destroy(btrfs_inode_cachep);
5376 if (btrfs_trans_handle_cachep)
5377 kmem_cache_destroy(btrfs_trans_handle_cachep);
5378 if (btrfs_transaction_cachep)
5379 kmem_cache_destroy(btrfs_transaction_cachep);
39279cc3
CM
5380 if (btrfs_path_cachep)
5381 kmem_cache_destroy(btrfs_path_cachep);
5382}
5383
5384int btrfs_init_cachep(void)
5385{
9601e3f6
CH
5386 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
5387 sizeof(struct btrfs_inode), 0,
5388 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
39279cc3
CM
5389 if (!btrfs_inode_cachep)
5390 goto fail;
9601e3f6
CH
5391
5392 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
5393 sizeof(struct btrfs_trans_handle), 0,
5394 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
5395 if (!btrfs_trans_handle_cachep)
5396 goto fail;
9601e3f6
CH
5397
5398 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
5399 sizeof(struct btrfs_transaction), 0,
5400 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
5401 if (!btrfs_transaction_cachep)
5402 goto fail;
9601e3f6
CH
5403
5404 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
5405 sizeof(struct btrfs_path), 0,
5406 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
39279cc3
CM
5407 if (!btrfs_path_cachep)
5408 goto fail;
9601e3f6 5409
39279cc3
CM
5410 return 0;
5411fail:
5412 btrfs_destroy_cachep();
5413 return -ENOMEM;
5414}
5415
5416static int btrfs_getattr(struct vfsmount *mnt,
5417 struct dentry *dentry, struct kstat *stat)
5418{
5419 struct inode *inode = dentry->d_inode;
5420 generic_fillattr(inode, stat);
3394e160 5421 stat->dev = BTRFS_I(inode)->root->anon_super.s_dev;
d6667462 5422 stat->blksize = PAGE_CACHE_SIZE;
a76a3cd4
YZ
5423 stat->blocks = (inode_get_bytes(inode) +
5424 BTRFS_I(inode)->delalloc_bytes) >> 9;
39279cc3
CM
5425 return 0;
5426}
5427
d397712b
CM
5428static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
5429 struct inode *new_dir, struct dentry *new_dentry)
39279cc3
CM
5430{
5431 struct btrfs_trans_handle *trans;
5432 struct btrfs_root *root = BTRFS_I(old_dir)->root;
4df27c4d 5433 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
39279cc3
CM
5434 struct inode *new_inode = new_dentry->d_inode;
5435 struct inode *old_inode = old_dentry->d_inode;
5436 struct timespec ctime = CURRENT_TIME;
00e4e6b3 5437 u64 index = 0;
4df27c4d 5438 u64 root_objectid;
39279cc3
CM
5439 int ret;
5440
f679a840
YZ
5441 if (new_dir->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5442 return -EPERM;
5443
4df27c4d
YZ
5444 /* we only allow rename subvolume link between subvolumes */
5445 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
3394e160
CM
5446 return -EXDEV;
5447
4df27c4d
YZ
5448 if (old_inode->i_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
5449 (new_inode && new_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID))
39279cc3 5450 return -ENOTEMPTY;
5f39d397 5451
4df27c4d
YZ
5452 if (S_ISDIR(old_inode->i_mode) && new_inode &&
5453 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
5454 return -ENOTEMPTY;
0660b5af 5455
9ed74f2d 5456 /*
5df6a9f6
JB
5457 * We want to reserve the absolute worst case amount of items. So if
5458 * both inodes are subvols and we need to unlink them then that would
5459 * require 4 item modifications, but if they are both normal inodes it
5460 * would require 5 item modifications, so we'll assume their normal
5461 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
5462 * should cover the worst case number of items we'll modify.
9ed74f2d 5463 */
5df6a9f6 5464 ret = btrfs_reserve_metadata_space(root, 11);
1832a6d5 5465 if (ret)
4df27c4d 5466 return ret;
1832a6d5 5467
5a3f23d5
CM
5468 /*
5469 * we're using rename to replace one file with another.
5470 * and the replacement file is large. Start IO on it now so
5471 * we don't add too much work to the end of the transaction
5472 */
4baf8c92 5473 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
5a3f23d5
CM
5474 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
5475 filemap_flush(old_inode->i_mapping);
5476
76dda93c
YZ
5477 /* close the racy window with snapshot create/destroy ioctl */
5478 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
5479 down_read(&root->fs_info->subvol_sem);
5480
39279cc3 5481 trans = btrfs_start_transaction(root, 1);
a5719521 5482 btrfs_set_trans_block_group(trans, new_dir);
5f39d397 5483
4df27c4d
YZ
5484 if (dest != root)
5485 btrfs_record_root_in_trans(trans, dest);
5f39d397 5486
a5719521
YZ
5487 ret = btrfs_set_inode_index(new_dir, &index);
5488 if (ret)
5489 goto out_fail;
5a3f23d5 5490
a5719521 5491 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
4df27c4d
YZ
5492 /* force full log commit if subvolume involved. */
5493 root->fs_info->last_trans_log_full_commit = trans->transid;
5494 } else {
a5719521
YZ
5495 ret = btrfs_insert_inode_ref(trans, dest,
5496 new_dentry->d_name.name,
5497 new_dentry->d_name.len,
5498 old_inode->i_ino,
5499 new_dir->i_ino, index);
5500 if (ret)
5501 goto out_fail;
4df27c4d
YZ
5502 /*
5503 * this is an ugly little race, but the rename is required
5504 * to make sure that if we crash, the inode is either at the
5505 * old name or the new one. pinning the log transaction lets
5506 * us make sure we don't allow a log commit to come in after
5507 * we unlink the name but before we add the new name back in.
5508 */
5509 btrfs_pin_log_trans(root);
5510 }
5a3f23d5
CM
5511 /*
5512 * make sure the inode gets flushed if it is replacing
5513 * something.
5514 */
5515 if (new_inode && new_inode->i_size &&
5516 old_inode && S_ISREG(old_inode->i_mode)) {
5517 btrfs_add_ordered_operation(trans, root, old_inode);
5518 }
5519
39279cc3
CM
5520 old_dir->i_ctime = old_dir->i_mtime = ctime;
5521 new_dir->i_ctime = new_dir->i_mtime = ctime;
5522 old_inode->i_ctime = ctime;
5f39d397 5523
12fcfd22
CM
5524 if (old_dentry->d_parent != new_dentry->d_parent)
5525 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
5526
4df27c4d
YZ
5527 if (unlikely(old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)) {
5528 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
5529 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
5530 old_dentry->d_name.name,
5531 old_dentry->d_name.len);
5532 } else {
5533 btrfs_inc_nlink(old_dentry->d_inode);
5534 ret = btrfs_unlink_inode(trans, root, old_dir,
5535 old_dentry->d_inode,
5536 old_dentry->d_name.name,
5537 old_dentry->d_name.len);
5538 }
5539 BUG_ON(ret);
39279cc3
CM
5540
5541 if (new_inode) {
5542 new_inode->i_ctime = CURRENT_TIME;
4df27c4d
YZ
5543 if (unlikely(new_inode->i_ino ==
5544 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
5545 root_objectid = BTRFS_I(new_inode)->location.objectid;
5546 ret = btrfs_unlink_subvol(trans, dest, new_dir,
5547 root_objectid,
5548 new_dentry->d_name.name,
5549 new_dentry->d_name.len);
5550 BUG_ON(new_inode->i_nlink == 0);
5551 } else {
5552 ret = btrfs_unlink_inode(trans, dest, new_dir,
5553 new_dentry->d_inode,
5554 new_dentry->d_name.name,
5555 new_dentry->d_name.len);
5556 }
5557 BUG_ON(ret);
7b128766 5558 if (new_inode->i_nlink == 0) {
e02119d5 5559 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
4df27c4d 5560 BUG_ON(ret);
7b128766 5561 }
39279cc3 5562 }
aec7477b 5563
4df27c4d
YZ
5564 ret = btrfs_add_link(trans, new_dir, old_inode,
5565 new_dentry->d_name.name,
a5719521 5566 new_dentry->d_name.len, 0, index);
4df27c4d 5567 BUG_ON(ret);
39279cc3 5568
4df27c4d
YZ
5569 if (old_inode->i_ino != BTRFS_FIRST_FREE_OBJECTID) {
5570 btrfs_log_new_name(trans, old_inode, old_dir,
5571 new_dentry->d_parent);
5572 btrfs_end_log_trans(root);
5573 }
39279cc3 5574out_fail:
ab78c84d 5575 btrfs_end_transaction_throttle(trans, root);
4df27c4d 5576
76dda93c
YZ
5577 if (old_inode->i_ino == BTRFS_FIRST_FREE_OBJECTID)
5578 up_read(&root->fs_info->subvol_sem);
9ed74f2d 5579
5df6a9f6 5580 btrfs_unreserve_metadata_space(root, 11);
39279cc3
CM
5581 return ret;
5582}
5583
d352ac68
CM
5584/*
5585 * some fairly slow code that needs optimization. This walks the list
5586 * of all the inodes with pending delalloc and forces them to disk.
5587 */
24bbcf04 5588int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
ea8c2819
CM
5589{
5590 struct list_head *head = &root->fs_info->delalloc_inodes;
5591 struct btrfs_inode *binode;
5b21f2ed 5592 struct inode *inode;
ea8c2819 5593
c146afad
YZ
5594 if (root->fs_info->sb->s_flags & MS_RDONLY)
5595 return -EROFS;
5596
75eff68e 5597 spin_lock(&root->fs_info->delalloc_lock);
d397712b 5598 while (!list_empty(head)) {
ea8c2819
CM
5599 binode = list_entry(head->next, struct btrfs_inode,
5600 delalloc_inodes);
5b21f2ed
ZY
5601 inode = igrab(&binode->vfs_inode);
5602 if (!inode)
5603 list_del_init(&binode->delalloc_inodes);
75eff68e 5604 spin_unlock(&root->fs_info->delalloc_lock);
5b21f2ed 5605 if (inode) {
8c8bee1d 5606 filemap_flush(inode->i_mapping);
24bbcf04
YZ
5607 if (delay_iput)
5608 btrfs_add_delayed_iput(inode);
5609 else
5610 iput(inode);
5b21f2ed
ZY
5611 }
5612 cond_resched();
75eff68e 5613 spin_lock(&root->fs_info->delalloc_lock);
ea8c2819 5614 }
75eff68e 5615 spin_unlock(&root->fs_info->delalloc_lock);
8c8bee1d
CM
5616
5617 /* the filemap_flush will queue IO into the worker threads, but
5618 * we have to make sure the IO is actually started and that
5619 * ordered extents get created before we return
5620 */
5621 atomic_inc(&root->fs_info->async_submit_draining);
d397712b 5622 while (atomic_read(&root->fs_info->nr_async_submits) ||
771ed689 5623 atomic_read(&root->fs_info->async_delalloc_pages)) {
8c8bee1d 5624 wait_event(root->fs_info->async_submit_wait,
771ed689
CM
5625 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
5626 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8c8bee1d
CM
5627 }
5628 atomic_dec(&root->fs_info->async_submit_draining);
ea8c2819
CM
5629 return 0;
5630}
5631
39279cc3
CM
5632static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
5633 const char *symname)
5634{
5635 struct btrfs_trans_handle *trans;
5636 struct btrfs_root *root = BTRFS_I(dir)->root;
5637 struct btrfs_path *path;
5638 struct btrfs_key key;
1832a6d5 5639 struct inode *inode = NULL;
39279cc3
CM
5640 int err;
5641 int drop_inode = 0;
5642 u64 objectid;
00e4e6b3 5643 u64 index = 0 ;
39279cc3
CM
5644 int name_len;
5645 int datasize;
5f39d397 5646 unsigned long ptr;
39279cc3 5647 struct btrfs_file_extent_item *ei;
5f39d397 5648 struct extent_buffer *leaf;
1832a6d5 5649 unsigned long nr = 0;
39279cc3
CM
5650
5651 name_len = strlen(symname) + 1;
5652 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
5653 return -ENAMETOOLONG;
1832a6d5 5654
9ed74f2d
JB
5655 /*
5656 * 2 items for inode item and ref
5657 * 2 items for dir items
5658 * 1 item for xattr if selinux is on
5659 */
5660 err = btrfs_reserve_metadata_space(root, 5);
1832a6d5 5661 if (err)
9ed74f2d 5662 return err;
1832a6d5 5663
39279cc3 5664 trans = btrfs_start_transaction(root, 1);
9ed74f2d
JB
5665 if (!trans)
5666 goto out_fail;
39279cc3
CM
5667 btrfs_set_trans_block_group(trans, dir);
5668
5669 err = btrfs_find_free_objectid(trans, root, dir->i_ino, &objectid);
5670 if (err) {
5671 err = -ENOSPC;
5672 goto out_unlock;
5673 }
5674
aec7477b 5675 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9c58309d
CM
5676 dentry->d_name.len,
5677 dentry->d_parent->d_inode->i_ino, objectid,
00e4e6b3
CM
5678 BTRFS_I(dir)->block_group, S_IFLNK|S_IRWXUGO,
5679 &index);
39279cc3
CM
5680 err = PTR_ERR(inode);
5681 if (IS_ERR(inode))
5682 goto out_unlock;
5683
f34f57a3 5684 err = btrfs_init_inode_security(trans, inode, dir);
33268eaf
JB
5685 if (err) {
5686 drop_inode = 1;
5687 goto out_unlock;
5688 }
5689
39279cc3 5690 btrfs_set_trans_block_group(trans, inode);
00e4e6b3 5691 err = btrfs_add_nondir(trans, dentry, inode, 0, index);
39279cc3
CM
5692 if (err)
5693 drop_inode = 1;
5694 else {
5695 inode->i_mapping->a_ops = &btrfs_aops;
04160088 5696 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
39279cc3
CM
5697 inode->i_fop = &btrfs_file_operations;
5698 inode->i_op = &btrfs_file_inode_operations;
d1310b2e 5699 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
39279cc3 5700 }
39279cc3
CM
5701 btrfs_update_inode_block_group(trans, inode);
5702 btrfs_update_inode_block_group(trans, dir);
5703 if (drop_inode)
5704 goto out_unlock;
5705
5706 path = btrfs_alloc_path();
5707 BUG_ON(!path);
5708 key.objectid = inode->i_ino;
5709 key.offset = 0;
39279cc3
CM
5710 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
5711 datasize = btrfs_file_extent_calc_inline_size(name_len);
5712 err = btrfs_insert_empty_item(trans, root, path, &key,
5713 datasize);
54aa1f4d
CM
5714 if (err) {
5715 drop_inode = 1;
5716 goto out_unlock;
5717 }
5f39d397
CM
5718 leaf = path->nodes[0];
5719 ei = btrfs_item_ptr(leaf, path->slots[0],
5720 struct btrfs_file_extent_item);
5721 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
5722 btrfs_set_file_extent_type(leaf, ei,
39279cc3 5723 BTRFS_FILE_EXTENT_INLINE);
c8b97818
CM
5724 btrfs_set_file_extent_encryption(leaf, ei, 0);
5725 btrfs_set_file_extent_compression(leaf, ei, 0);
5726 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
5727 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
5728
39279cc3 5729 ptr = btrfs_file_extent_inline_start(ei);
5f39d397
CM
5730 write_extent_buffer(leaf, symname, ptr, name_len);
5731 btrfs_mark_buffer_dirty(leaf);
39279cc3 5732 btrfs_free_path(path);
5f39d397 5733
39279cc3
CM
5734 inode->i_op = &btrfs_symlink_inode_operations;
5735 inode->i_mapping->a_ops = &btrfs_symlink_aops;
04160088 5736 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
d899e052 5737 inode_set_bytes(inode, name_len);
dbe674a9 5738 btrfs_i_size_write(inode, name_len - 1);
54aa1f4d
CM
5739 err = btrfs_update_inode(trans, root, inode);
5740 if (err)
5741 drop_inode = 1;
39279cc3
CM
5742
5743out_unlock:
d3c2fdcf 5744 nr = trans->blocks_used;
ab78c84d 5745 btrfs_end_transaction_throttle(trans, root);
1832a6d5 5746out_fail:
9ed74f2d 5747 btrfs_unreserve_metadata_space(root, 5);
39279cc3
CM
5748 if (drop_inode) {
5749 inode_dec_link_count(inode);
5750 iput(inode);
5751 }
d3c2fdcf 5752 btrfs_btree_balance_dirty(root, nr);
39279cc3
CM
5753 return err;
5754}
16432985 5755
5a303d5d 5756static int prealloc_file_range(struct inode *inode, u64 start, u64 end,
d1ea6a61 5757 u64 alloc_hint, int mode, loff_t actual_len)
d899e052 5758{
5a303d5d 5759 struct btrfs_trans_handle *trans;
d899e052
YZ
5760 struct btrfs_root *root = BTRFS_I(inode)->root;
5761 struct btrfs_key ins;
5762 u64 alloc_size;
5763 u64 cur_offset = start;
5764 u64 num_bytes = end - start;
5765 int ret = 0;
d1ea6a61 5766 u64 i_size;
d899e052 5767
d899e052
YZ
5768 while (num_bytes > 0) {
5769 alloc_size = min(num_bytes, root->fs_info->max_extent);
9ed74f2d 5770
3a1abec9
CM
5771 trans = btrfs_start_transaction(root, 1);
5772
d899e052
YZ
5773 ret = btrfs_reserve_extent(trans, root, alloc_size,
5774 root->sectorsize, 0, alloc_hint,
5775 (u64)-1, &ins, 1);
5776 if (ret) {
5777 WARN_ON(1);
3a1abec9 5778 goto stop_trans;
5a303d5d
YZ
5779 }
5780
5781 ret = btrfs_reserve_metadata_space(root, 3);
5782 if (ret) {
5783 btrfs_free_reserved_extent(root, ins.objectid,
5784 ins.offset);
3a1abec9 5785 goto stop_trans;
d899e052 5786 }
5a303d5d 5787
d899e052
YZ
5788 ret = insert_reserved_file_extent(trans, inode,
5789 cur_offset, ins.objectid,
5790 ins.offset, ins.offset,
920bbbfb 5791 ins.offset, 0, 0, 0,
d899e052
YZ
5792 BTRFS_FILE_EXTENT_PREALLOC);
5793 BUG_ON(ret);
a1ed835e
CM
5794 btrfs_drop_extent_cache(inode, cur_offset,
5795 cur_offset + ins.offset -1, 0);
5a303d5d 5796
d899e052
YZ
5797 num_bytes -= ins.offset;
5798 cur_offset += ins.offset;
5799 alloc_hint = ins.objectid + ins.offset;
5a303d5d 5800
d899e052 5801 inode->i_ctime = CURRENT_TIME;
6cbff00f 5802 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
d899e052 5803 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
23b5c509
AK
5804 (actual_len > inode->i_size) &&
5805 (cur_offset > inode->i_size)) {
5806
d1ea6a61
AK
5807 if (cur_offset > actual_len)
5808 i_size = actual_len;
5809 else
5810 i_size = cur_offset;
5811 i_size_write(inode, i_size);
5812 btrfs_ordered_update_i_size(inode, i_size, NULL);
5a303d5d
YZ
5813 }
5814
d899e052
YZ
5815 ret = btrfs_update_inode(trans, root, inode);
5816 BUG_ON(ret);
d899e052 5817
5a303d5d
YZ
5818 btrfs_end_transaction(trans, root);
5819 btrfs_unreserve_metadata_space(root, 3);
5820 }
d899e052 5821 return ret;
3a1abec9
CM
5822
5823stop_trans:
5824 btrfs_end_transaction(trans, root);
5825 return ret;
5826
d899e052
YZ
5827}
5828
5829static long btrfs_fallocate(struct inode *inode, int mode,
5830 loff_t offset, loff_t len)
5831{
5832 u64 cur_offset;
5833 u64 last_byte;
5834 u64 alloc_start;
5835 u64 alloc_end;
5836 u64 alloc_hint = 0;
e980b50c 5837 u64 locked_end;
d899e052
YZ
5838 u64 mask = BTRFS_I(inode)->root->sectorsize - 1;
5839 struct extent_map *em;
5840 int ret;
5841
5842 alloc_start = offset & ~mask;
5843 alloc_end = (offset + len + mask) & ~mask;
5844
546888da
CM
5845 /*
5846 * wait for ordered IO before we have any locks. We'll loop again
5847 * below with the locks held.
5848 */
5849 btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
5850
d899e052
YZ
5851 mutex_lock(&inode->i_mutex);
5852 if (alloc_start > inode->i_size) {
5853 ret = btrfs_cont_expand(inode, alloc_start);
5854 if (ret)
5855 goto out;
5856 }
5857
5a303d5d 5858 ret = btrfs_check_data_free_space(BTRFS_I(inode)->root, inode,
a970b0a1
JB
5859 alloc_end - alloc_start);
5860 if (ret)
5861 goto out;
5862
e980b50c 5863 locked_end = alloc_end - 1;
d899e052
YZ
5864 while (1) {
5865 struct btrfs_ordered_extent *ordered;
546888da 5866
546888da
CM
5867 /* the extent lock is ordered inside the running
5868 * transaction
5869 */
e980b50c
CM
5870 lock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
5871 GFP_NOFS);
d899e052
YZ
5872 ordered = btrfs_lookup_first_ordered_extent(inode,
5873 alloc_end - 1);
5874 if (ordered &&
5875 ordered->file_offset + ordered->len > alloc_start &&
5876 ordered->file_offset < alloc_end) {
5877 btrfs_put_ordered_extent(ordered);
5878 unlock_extent(&BTRFS_I(inode)->io_tree,
e980b50c 5879 alloc_start, locked_end, GFP_NOFS);
546888da
CM
5880 /*
5881 * we can't wait on the range with the transaction
5882 * running or with the extent lock held
5883 */
d899e052
YZ
5884 btrfs_wait_ordered_range(inode, alloc_start,
5885 alloc_end - alloc_start);
5886 } else {
5887 if (ordered)
5888 btrfs_put_ordered_extent(ordered);
5889 break;
5890 }
5891 }
5892
5893 cur_offset = alloc_start;
5894 while (1) {
5895 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5896 alloc_end - cur_offset, 0);
5897 BUG_ON(IS_ERR(em) || !em);
5898 last_byte = min(extent_map_end(em), alloc_end);
5899 last_byte = (last_byte + mask) & ~mask;
5a303d5d
YZ
5900 if (em->block_start == EXTENT_MAP_HOLE ||
5901 (cur_offset >= inode->i_size &&
5902 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5903 ret = prealloc_file_range(inode,
5904 cur_offset, last_byte,
d1ea6a61 5905 alloc_hint, mode, offset+len);
d899e052
YZ
5906 if (ret < 0) {
5907 free_extent_map(em);
5908 break;
5909 }
5910 }
5911 if (em->block_start <= EXTENT_MAP_LAST_BYTE)
5912 alloc_hint = em->block_start;
5913 free_extent_map(em);
5914
5915 cur_offset = last_byte;
5916 if (cur_offset >= alloc_end) {
5917 ret = 0;
5918 break;
5919 }
5920 }
e980b50c 5921 unlock_extent(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
d899e052 5922 GFP_NOFS);
546888da 5923
5a303d5d
YZ
5924 btrfs_free_reserved_data_space(BTRFS_I(inode)->root, inode,
5925 alloc_end - alloc_start);
d899e052
YZ
5926out:
5927 mutex_unlock(&inode->i_mutex);
5928 return ret;
5929}
5930
e6dcd2dc
CM
5931static int btrfs_set_page_dirty(struct page *page)
5932{
e6dcd2dc
CM
5933 return __set_page_dirty_nobuffers(page);
5934}
5935
0ee0fda0 5936static int btrfs_permission(struct inode *inode, int mask)
fdebe2bd 5937{
6cbff00f 5938 if ((BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) && (mask & MAY_WRITE))
fdebe2bd 5939 return -EACCES;
33268eaf 5940 return generic_permission(inode, mask, btrfs_check_acl);
fdebe2bd 5941}
39279cc3 5942
6e1d5dcc 5943static const struct inode_operations btrfs_dir_inode_operations = {
3394e160 5944 .getattr = btrfs_getattr,
39279cc3
CM
5945 .lookup = btrfs_lookup,
5946 .create = btrfs_create,
5947 .unlink = btrfs_unlink,
5948 .link = btrfs_link,
5949 .mkdir = btrfs_mkdir,
5950 .rmdir = btrfs_rmdir,
5951 .rename = btrfs_rename,
5952 .symlink = btrfs_symlink,
5953 .setattr = btrfs_setattr,
618e21d5 5954 .mknod = btrfs_mknod,
95819c05
CH
5955 .setxattr = btrfs_setxattr,
5956 .getxattr = btrfs_getxattr,
5103e947 5957 .listxattr = btrfs_listxattr,
95819c05 5958 .removexattr = btrfs_removexattr,
fdebe2bd 5959 .permission = btrfs_permission,
39279cc3 5960};
6e1d5dcc 5961static const struct inode_operations btrfs_dir_ro_inode_operations = {
39279cc3 5962 .lookup = btrfs_lookup,
fdebe2bd 5963 .permission = btrfs_permission,
39279cc3 5964};
76dda93c 5965
828c0950 5966static const struct file_operations btrfs_dir_file_operations = {
39279cc3
CM
5967 .llseek = generic_file_llseek,
5968 .read = generic_read_dir,
cbdf5a24 5969 .readdir = btrfs_real_readdir,
34287aa3 5970 .unlocked_ioctl = btrfs_ioctl,
39279cc3 5971#ifdef CONFIG_COMPAT
34287aa3 5972 .compat_ioctl = btrfs_ioctl,
39279cc3 5973#endif
6bf13c0c 5974 .release = btrfs_release_file,
e02119d5 5975 .fsync = btrfs_sync_file,
39279cc3
CM
5976};
5977
d1310b2e 5978static struct extent_io_ops btrfs_extent_io_ops = {
07157aac 5979 .fill_delalloc = run_delalloc_range,
065631f6 5980 .submit_bio_hook = btrfs_submit_bio_hook,
239b14b3 5981 .merge_bio_hook = btrfs_merge_bio_hook,
07157aac 5982 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
e6dcd2dc 5983 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
247e743c 5984 .writepage_start_hook = btrfs_writepage_start_hook,
1259ab75 5985 .readpage_io_failed_hook = btrfs_io_failed_hook,
b0c68f8b
CM
5986 .set_bit_hook = btrfs_set_bit_hook,
5987 .clear_bit_hook = btrfs_clear_bit_hook,
9ed74f2d
JB
5988 .merge_extent_hook = btrfs_merge_extent_hook,
5989 .split_extent_hook = btrfs_split_extent_hook,
07157aac
CM
5990};
5991
35054394
CM
5992/*
5993 * btrfs doesn't support the bmap operation because swapfiles
5994 * use bmap to make a mapping of extents in the file. They assume
5995 * these extents won't change over the life of the file and they
5996 * use the bmap result to do IO directly to the drive.
5997 *
5998 * the btrfs bmap call would return logical addresses that aren't
5999 * suitable for IO and they also will change frequently as COW
6000 * operations happen. So, swapfile + btrfs == corruption.
6001 *
6002 * For now we're avoiding this by dropping bmap.
6003 */
7f09410b 6004static const struct address_space_operations btrfs_aops = {
39279cc3
CM
6005 .readpage = btrfs_readpage,
6006 .writepage = btrfs_writepage,
b293f02e 6007 .writepages = btrfs_writepages,
3ab2fb5a 6008 .readpages = btrfs_readpages,
39279cc3 6009 .sync_page = block_sync_page,
16432985 6010 .direct_IO = btrfs_direct_IO,
a52d9a80
CM
6011 .invalidatepage = btrfs_invalidatepage,
6012 .releasepage = btrfs_releasepage,
e6dcd2dc 6013 .set_page_dirty = btrfs_set_page_dirty,
465fdd97 6014 .error_remove_page = generic_error_remove_page,
39279cc3
CM
6015};
6016
7f09410b 6017static const struct address_space_operations btrfs_symlink_aops = {
39279cc3
CM
6018 .readpage = btrfs_readpage,
6019 .writepage = btrfs_writepage,
2bf5a725
CM
6020 .invalidatepage = btrfs_invalidatepage,
6021 .releasepage = btrfs_releasepage,
39279cc3
CM
6022};
6023
6e1d5dcc 6024static const struct inode_operations btrfs_file_inode_operations = {
39279cc3
CM
6025 .truncate = btrfs_truncate,
6026 .getattr = btrfs_getattr,
6027 .setattr = btrfs_setattr,
95819c05
CH
6028 .setxattr = btrfs_setxattr,
6029 .getxattr = btrfs_getxattr,
5103e947 6030 .listxattr = btrfs_listxattr,
95819c05 6031 .removexattr = btrfs_removexattr,
fdebe2bd 6032 .permission = btrfs_permission,
d899e052 6033 .fallocate = btrfs_fallocate,
1506fcc8 6034 .fiemap = btrfs_fiemap,
39279cc3 6035};
6e1d5dcc 6036static const struct inode_operations btrfs_special_inode_operations = {
618e21d5
JB
6037 .getattr = btrfs_getattr,
6038 .setattr = btrfs_setattr,
fdebe2bd 6039 .permission = btrfs_permission,
95819c05
CH
6040 .setxattr = btrfs_setxattr,
6041 .getxattr = btrfs_getxattr,
33268eaf 6042 .listxattr = btrfs_listxattr,
95819c05 6043 .removexattr = btrfs_removexattr,
618e21d5 6044};
6e1d5dcc 6045static const struct inode_operations btrfs_symlink_inode_operations = {
39279cc3
CM
6046 .readlink = generic_readlink,
6047 .follow_link = page_follow_link_light,
6048 .put_link = page_put_link,
fdebe2bd 6049 .permission = btrfs_permission,
0279b4cd
JO
6050 .setxattr = btrfs_setxattr,
6051 .getxattr = btrfs_getxattr,
6052 .listxattr = btrfs_listxattr,
6053 .removexattr = btrfs_removexattr,
39279cc3 6054};
76dda93c 6055
82d339d9 6056const struct dentry_operations btrfs_dentry_operations = {
76dda93c
YZ
6057 .d_delete = btrfs_dentry_delete,
6058};