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