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