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