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