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