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