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