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