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