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