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