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