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