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