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