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