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