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