1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2008 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/file.h>
10 #include <linux/pagemap.h>
11 #include <linux/highmem.h>
12 #include <linux/kthread.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/slab.h>
19 #include <linux/sched/mm.h>
20 #include <linux/log2.h>
21 #include <crypto/hash.h>
25 #include "transaction.h"
26 #include "btrfs_inode.h"
28 #include "ordered-data.h"
29 #include "compression.h"
30 #include "extent_io.h"
31 #include "extent_map.h"
35 static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
37 const char* btrfs_compress_type2str(enum btrfs_compression_type type)
40 case BTRFS_COMPRESS_ZLIB:
41 case BTRFS_COMPRESS_LZO:
42 case BTRFS_COMPRESS_ZSTD:
43 case BTRFS_COMPRESS_NONE:
44 return btrfs_compress_types[type];
52 bool btrfs_compress_is_valid_type(const char *str, size_t len)
56 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
57 size_t comp_len = strlen(btrfs_compress_types[i]);
62 if (!strncmp(btrfs_compress_types[i], str, comp_len))
68 static int compression_compress_pages(int type, struct list_head *ws,
69 struct address_space *mapping, u64 start, struct page **pages,
70 unsigned long *out_pages, unsigned long *total_in,
71 unsigned long *total_out)
74 case BTRFS_COMPRESS_ZLIB:
75 return zlib_compress_pages(ws, mapping, start, pages,
76 out_pages, total_in, total_out);
77 case BTRFS_COMPRESS_LZO:
78 return lzo_compress_pages(ws, mapping, start, pages,
79 out_pages, total_in, total_out);
80 case BTRFS_COMPRESS_ZSTD:
81 return zstd_compress_pages(ws, mapping, start, pages,
82 out_pages, total_in, total_out);
83 case BTRFS_COMPRESS_NONE:
86 * This can happen when compression races with remount setting
87 * it to 'no compress', while caller doesn't call
88 * inode_need_compress() to check if we really need to
91 * Not a big deal, just need to inform caller that we
92 * haven't allocated any pages yet.
99 static int compression_decompress_bio(struct list_head *ws,
100 struct compressed_bio *cb)
102 switch (cb->compress_type) {
103 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
104 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
105 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
106 case BTRFS_COMPRESS_NONE:
109 * This can't happen, the type is validated several times
110 * before we get here.
116 static int compression_decompress(int type, struct list_head *ws,
117 unsigned char *data_in, struct page *dest_page,
118 unsigned long start_byte, size_t srclen, size_t destlen)
121 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
122 start_byte, srclen, destlen);
123 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
124 start_byte, srclen, destlen);
125 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
126 start_byte, srclen, destlen);
127 case BTRFS_COMPRESS_NONE:
130 * This can't happen, the type is validated several times
131 * before we get here.
137 static int btrfs_decompress_bio(struct compressed_bio *cb);
139 static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
140 unsigned long disk_size)
142 return sizeof(struct compressed_bio) +
143 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
146 static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
149 struct btrfs_fs_info *fs_info = inode->root->fs_info;
150 const u32 csum_size = fs_info->csum_size;
151 const u32 sectorsize = fs_info->sectorsize;
154 u8 csum[BTRFS_CSUM_SIZE];
155 struct compressed_bio *cb = bio->bi_private;
156 u8 *cb_sum = cb->sums;
158 if ((inode->flags & BTRFS_INODE_NODATASUM) ||
159 test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state))
162 for (i = 0; i < cb->nr_pages; i++) {
164 u32 bytes_left = PAGE_SIZE;
165 page = cb->compressed_pages[i];
167 /* Determine the remaining bytes inside the page first */
168 if (i == cb->nr_pages - 1)
169 bytes_left = cb->compressed_len - i * PAGE_SIZE;
171 /* Hash through the page sector by sector */
172 for (pg_offset = 0; pg_offset < bytes_left;
173 pg_offset += sectorsize) {
176 ret = btrfs_check_sector_csum(fs_info, page, pg_offset,
179 btrfs_print_data_csum_error(inode, disk_start,
180 csum, cb_sum, cb->mirror_num);
181 if (btrfs_bio(bio)->device)
182 btrfs_dev_stat_inc_and_print(
183 btrfs_bio(bio)->device,
184 BTRFS_DEV_STAT_CORRUPTION_ERRS);
188 disk_start += sectorsize;
195 * Reduce bio and io accounting for a compressed_bio with its corresponding bio.
197 * Return true if there is no pending bio nor io.
198 * Return false otherwise.
200 static bool dec_and_test_compressed_bio(struct compressed_bio *cb, struct bio *bio)
202 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
203 unsigned int bi_size = 0;
204 bool last_io = false;
205 struct bio_vec *bvec;
206 struct bvec_iter_all iter_all;
209 * At endio time, bi_iter.bi_size doesn't represent the real bio size.
210 * Thus here we have to iterate through all segments to grab correct
213 bio_for_each_segment_all(bvec, bio, iter_all)
214 bi_size += bvec->bv_len;
217 cb->status = bio->bi_status;
219 ASSERT(bi_size && bi_size <= cb->compressed_len);
220 last_io = refcount_sub_and_test(bi_size >> fs_info->sectorsize_bits,
221 &cb->pending_sectors);
223 * Here we must wake up the possible error handler after all other
224 * operations on @cb finished, or we can race with
225 * finish_compressed_bio_*() which may free @cb.
232 static void finish_compressed_bio_read(struct compressed_bio *cb)
237 /* Release the compressed pages */
238 for (index = 0; index < cb->nr_pages; index++) {
239 page = cb->compressed_pages[index];
240 page->mapping = NULL;
244 /* Do io completion on the original bio */
245 if (cb->status != BLK_STS_OK) {
246 cb->orig_bio->bi_status = cb->status;
247 bio_endio(cb->orig_bio);
249 struct bio_vec *bvec;
250 struct bvec_iter_all iter_all;
253 * We have verified the checksum already, set page checked so
254 * the end_io handlers know about it
256 ASSERT(!bio_flagged(cb->orig_bio, BIO_CLONED));
257 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all) {
258 u64 bvec_start = page_offset(bvec->bv_page) +
261 btrfs_page_set_checked(btrfs_sb(cb->inode->i_sb),
262 bvec->bv_page, bvec_start,
266 bio_endio(cb->orig_bio);
269 /* Finally free the cb struct */
270 kfree(cb->compressed_pages);
274 /* when we finish reading compressed pages from the disk, we
275 * decompress them and then run the bio end_io routines on the
276 * decompressed pages (in the inode address space).
278 * This allows the checksumming and other IO error handling routines
281 * The compressed pages are freed here, and it must be run
284 static void end_compressed_bio_read(struct bio *bio)
286 struct compressed_bio *cb = bio->bi_private;
288 unsigned int mirror = btrfs_bio(bio)->mirror_num;
291 if (!dec_and_test_compressed_bio(cb, bio))
295 * Record the correct mirror_num in cb->orig_bio so that
296 * read-repair can work properly.
298 btrfs_bio(cb->orig_bio)->mirror_num = mirror;
299 cb->mirror_num = mirror;
302 * Some IO in this cb have failed, just skip checksum as there
303 * is no way it could be correct.
305 if (cb->status != BLK_STS_OK)
309 ret = check_compressed_csum(BTRFS_I(inode), bio,
310 bio->bi_iter.bi_sector << 9);
314 /* ok, we're the last bio for this extent, lets start
317 ret = btrfs_decompress_bio(cb);
321 cb->status = errno_to_blk_status(ret);
322 finish_compressed_bio_read(cb);
328 * Clear the writeback bits on all of the file
329 * pages for a compressed write
331 static noinline void end_compressed_writeback(struct inode *inode,
332 const struct compressed_bio *cb)
334 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
335 unsigned long index = cb->start >> PAGE_SHIFT;
336 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
337 struct page *pages[16];
338 unsigned long nr_pages = end_index - index + 1;
339 const int errno = blk_status_to_errno(cb->status);
344 mapping_set_error(inode->i_mapping, errno);
346 while (nr_pages > 0) {
347 ret = find_get_pages_contig(inode->i_mapping, index,
349 nr_pages, ARRAY_SIZE(pages)), pages);
355 for (i = 0; i < ret; i++) {
357 SetPageError(pages[i]);
358 btrfs_page_clamp_clear_writeback(fs_info, pages[i],
365 /* the inode may be gone now */
368 static void finish_compressed_bio_write(struct compressed_bio *cb)
370 struct inode *inode = cb->inode;
374 * Ok, we're the last bio for this extent, step one is to call back
375 * into the FS and do all the end_io operations.
377 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
378 cb->start, cb->start + cb->len - 1,
379 cb->status == BLK_STS_OK);
382 end_compressed_writeback(inode, cb);
383 /* Note, our inode could be gone now */
386 * Release the compressed pages, these came from alloc_page and
387 * are not attached to the inode at all
389 for (index = 0; index < cb->nr_pages; index++) {
390 struct page *page = cb->compressed_pages[index];
392 page->mapping = NULL;
396 /* Finally free the cb struct */
397 kfree(cb->compressed_pages);
401 static void btrfs_finish_compressed_write_work(struct work_struct *work)
403 struct compressed_bio *cb =
404 container_of(work, struct compressed_bio, write_end_work);
406 finish_compressed_bio_write(cb);
410 * Do the cleanup once all the compressed pages hit the disk. This will clear
411 * writeback on the file pages and free the compressed pages.
413 * This also calls the writeback end hooks for the file pages so that metadata
414 * and checksums can be updated in the file.
416 static void end_compressed_bio_write(struct bio *bio)
418 struct compressed_bio *cb = bio->bi_private;
420 if (dec_and_test_compressed_bio(cb, bio)) {
421 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
423 btrfs_record_physical_zoned(cb->inode, cb->start, bio);
424 queue_work(fs_info->compressed_write_workers, &cb->write_end_work);
430 * Allocate a compressed_bio, which will be used to read/write on-disk
431 * (aka, compressed) * data.
433 * @cb: The compressed_bio structure, which records all the needed
434 * information to bind the compressed data to the uncompressed
436 * @disk_byten: The logical bytenr where the compressed data will be read
437 * from or written to.
438 * @endio_func: The endio function to call after the IO for compressed data
440 * @next_stripe_start: Return value of logical bytenr of where next stripe starts.
441 * Let the caller know to only fill the bio up to the stripe
446 static struct bio *alloc_compressed_bio(struct compressed_bio *cb, u64 disk_bytenr,
447 unsigned int opf, bio_end_io_t endio_func,
448 u64 *next_stripe_start)
450 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
451 struct btrfs_io_geometry geom;
452 struct extent_map *em;
456 bio = btrfs_bio_alloc(BIO_MAX_VECS);
458 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
460 bio->bi_private = cb;
461 bio->bi_end_io = endio_func;
463 em = btrfs_get_chunk_map(fs_info, disk_bytenr, fs_info->sectorsize);
469 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
470 bio_set_dev(bio, em->map_lookup->stripes[0].dev->bdev);
472 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), disk_bytenr, &geom);
478 *next_stripe_start = disk_bytenr + geom.len;
484 * worker function to build and submit bios for previously compressed pages.
485 * The corresponding pages in the inode should be marked for writeback
486 * and the compressed pages should have a reference on them for dropping
487 * when the IO is complete.
489 * This also checksums the file bytes and gets things ready for
492 blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
493 unsigned int len, u64 disk_start,
494 unsigned int compressed_len,
495 struct page **compressed_pages,
496 unsigned int nr_pages,
497 unsigned int write_flags,
498 struct cgroup_subsys_state *blkcg_css,
501 struct btrfs_fs_info *fs_info = inode->root->fs_info;
502 struct bio *bio = NULL;
503 struct compressed_bio *cb;
504 u64 cur_disk_bytenr = disk_start;
505 u64 next_stripe_start;
507 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
508 const bool use_append = btrfs_use_zone_append(inode, disk_start);
509 const unsigned int bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
511 ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
512 IS_ALIGNED(len, fs_info->sectorsize));
513 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
515 return BLK_STS_RESOURCE;
516 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
517 cb->status = BLK_STS_OK;
518 cb->inode = &inode->vfs_inode;
522 cb->compressed_pages = compressed_pages;
523 cb->compressed_len = compressed_len;
524 cb->writeback = writeback;
525 INIT_WORK(&cb->write_end_work, btrfs_finish_compressed_write_work);
526 cb->nr_pages = nr_pages;
529 kthread_associate_blkcg(blkcg_css);
531 while (cur_disk_bytenr < disk_start + compressed_len) {
532 u64 offset = cur_disk_bytenr - disk_start;
533 unsigned int index = offset >> PAGE_SHIFT;
534 unsigned int real_size;
536 struct page *page = compressed_pages[index];
539 /* Allocate new bio if submitted or not yet allocated */
541 bio = alloc_compressed_bio(cb, cur_disk_bytenr,
542 bio_op | write_flags, end_compressed_bio_write,
545 ret = errno_to_blk_status(PTR_ERR(bio));
550 bio->bi_opf |= REQ_CGROUP_PUNT;
553 * We should never reach next_stripe_start start as we will
554 * submit comp_bio when reach the boundary immediately.
556 ASSERT(cur_disk_bytenr != next_stripe_start);
559 * We have various limits on the real read size:
562 * - compressed length boundary
564 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_bytenr);
565 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
566 real_size = min_t(u64, real_size, compressed_len - offset);
567 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
570 added = bio_add_zone_append_page(bio, page, real_size,
571 offset_in_page(offset));
573 added = bio_add_page(bio, page, real_size,
574 offset_in_page(offset));
575 /* Reached zoned boundary */
579 cur_disk_bytenr += added;
580 /* Reached stripe boundary */
581 if (cur_disk_bytenr == next_stripe_start)
584 /* Finished the range */
585 if (cur_disk_bytenr == disk_start + compressed_len)
590 ret = btrfs_csum_one_bio(inode, bio, start, true);
595 ASSERT(bio->bi_iter.bi_size);
596 ret = btrfs_map_bio(fs_info, bio, 0);
604 kthread_associate_blkcg(NULL);
610 kthread_associate_blkcg(NULL);
613 bio->bi_status = ret;
616 /* Last byte of @cb is submitted, endio will free @cb */
617 if (cur_disk_bytenr == disk_start + compressed_len)
620 wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
621 (disk_start + compressed_len - cur_disk_bytenr) >>
622 fs_info->sectorsize_bits);
624 * Even with previous bio ended, we should still have io not yet
625 * submitted, thus need to finish manually.
627 ASSERT(refcount_read(&cb->pending_sectors));
628 /* Now we are the only one referring @cb, can finish it safely. */
629 finish_compressed_bio_write(cb);
633 static u64 bio_end_offset(struct bio *bio)
635 struct bio_vec *last = bio_last_bvec_all(bio);
637 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
641 * Add extra pages in the same compressed file extent so that we don't need to
642 * re-read the same extent again and again.
644 * NOTE: this won't work well for subpage, as for subpage read, we lock the
645 * full page then submit bio for each compressed/regular extents.
647 * This means, if we have several sectors in the same page points to the same
648 * on-disk compressed data, we will re-read the same extent many times and
649 * this function can only help for the next page.
651 static noinline int add_ra_bio_pages(struct inode *inode,
653 struct compressed_bio *cb)
655 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
656 unsigned long end_index;
657 u64 cur = bio_end_offset(cb->orig_bio);
658 u64 isize = i_size_read(inode);
661 struct extent_map *em;
662 struct address_space *mapping = inode->i_mapping;
663 struct extent_map_tree *em_tree;
664 struct extent_io_tree *tree;
665 int sectors_missed = 0;
667 em_tree = &BTRFS_I(inode)->extent_tree;
668 tree = &BTRFS_I(inode)->io_tree;
674 * For current subpage support, we only support 64K page size,
675 * which means maximum compressed extent size (128K) is just 2x page
677 * This makes readahead less effective, so here disable readahead for
678 * subpage for now, until full compressed write is supported.
680 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
683 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
685 while (cur < compressed_end) {
687 u64 pg_index = cur >> PAGE_SHIFT;
690 if (pg_index > end_index)
693 page = xa_load(&mapping->i_pages, pg_index);
694 if (page && !xa_is_value(page)) {
695 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
696 fs_info->sectorsize_bits;
698 /* Beyond threshold, no need to continue */
699 if (sectors_missed > 4)
703 * Jump to next page start as we already have page for
706 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
710 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
715 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
717 /* There is already a page, skip to page end */
718 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
722 ret = set_page_extent_mapped(page);
729 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
730 lock_extent(tree, cur, page_end);
731 read_lock(&em_tree->lock);
732 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
733 read_unlock(&em_tree->lock);
736 * At this point, we have a locked page in the page cache for
737 * these bytes in the file. But, we have to make sure they map
738 * to this compressed extent on disk.
740 if (!em || cur < em->start ||
741 (cur + fs_info->sectorsize > extent_map_end(em)) ||
742 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
744 unlock_extent(tree, cur, page_end);
751 if (page->index == end_index) {
752 size_t zero_offset = offset_in_page(isize);
756 zeros = PAGE_SIZE - zero_offset;
757 memzero_page(page, zero_offset, zeros);
761 add_size = min(em->start + em->len, page_end + 1) - cur;
762 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
763 if (ret != add_size) {
764 unlock_extent(tree, cur, page_end);
770 * If it's subpage, we also need to increase its
771 * subpage::readers number, as at endio we will decrease
772 * subpage::readers and to unlock the page.
774 if (fs_info->sectorsize < PAGE_SIZE)
775 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
783 * for a compressed read, the bio we get passed has all the inode pages
784 * in it. We don't actually do IO on those pages but allocate new ones
785 * to hold the compressed pages on disk.
787 * bio->bi_iter.bi_sector points to the compressed extent on disk
788 * bio->bi_io_vec points to all of the inode pages
790 * After the compressed pages are read, we copy the bytes into the
791 * bio we were passed and then call the bio end_io calls
793 void btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
796 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
797 struct extent_map_tree *em_tree;
798 struct compressed_bio *cb;
799 unsigned int compressed_len;
800 struct bio *comp_bio = NULL;
801 const u64 disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
802 u64 cur_disk_byte = disk_bytenr;
803 u64 next_stripe_start;
807 struct extent_map *em;
813 em_tree = &BTRFS_I(inode)->extent_tree;
815 file_offset = bio_first_bvec_all(bio)->bv_offset +
816 page_offset(bio_first_page_all(bio));
818 /* we need the actual starting offset of this extent in the file */
819 read_lock(&em_tree->lock);
820 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
821 read_unlock(&em_tree->lock);
827 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
828 compressed_len = em->block_len;
829 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
831 ret = BLK_STS_RESOURCE;
835 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
836 cb->status = BLK_STS_OK;
838 cb->mirror_num = mirror_num;
841 cb->start = em->orig_start;
843 em_start = em->start;
845 cb->len = bio->bi_iter.bi_size;
846 cb->compressed_len = compressed_len;
847 cb->compress_type = em->compress_type;
853 cb->nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
854 cb->compressed_pages = kcalloc(cb->nr_pages, sizeof(struct page *), GFP_NOFS);
855 if (!cb->compressed_pages) {
856 ret = BLK_STS_RESOURCE;
860 ret2 = btrfs_alloc_page_array(cb->nr_pages, cb->compressed_pages);
862 ret = BLK_STS_RESOURCE;
866 add_ra_bio_pages(inode, em_start + em_len, cb);
868 /* include any pages we added in add_ra-bio_pages */
869 cb->len = bio->bi_iter.bi_size;
871 while (cur_disk_byte < disk_bytenr + compressed_len) {
872 u64 offset = cur_disk_byte - disk_bytenr;
873 unsigned int index = offset >> PAGE_SHIFT;
874 unsigned int real_size;
876 struct page *page = cb->compressed_pages[index];
879 /* Allocate new bio if submitted or not yet allocated */
881 comp_bio = alloc_compressed_bio(cb, cur_disk_byte,
882 REQ_OP_READ, end_compressed_bio_read,
884 if (IS_ERR(comp_bio)) {
885 ret = errno_to_blk_status(PTR_ERR(comp_bio));
891 * We should never reach next_stripe_start start as we will
892 * submit comp_bio when reach the boundary immediately.
894 ASSERT(cur_disk_byte != next_stripe_start);
896 * We have various limit on the real read size:
899 * - compressed length boundary
901 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_byte);
902 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
903 real_size = min_t(u64, real_size, compressed_len - offset);
904 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
906 added = bio_add_page(comp_bio, page, real_size, offset_in_page(offset));
908 * Maximum compressed extent is smaller than bio size limit,
909 * thus bio_add_page() should always success.
911 ASSERT(added == real_size);
912 cur_disk_byte += added;
914 /* Reached stripe boundary, need to submit */
915 if (cur_disk_byte == next_stripe_start)
918 /* Has finished the range, need to submit */
919 if (cur_disk_byte == disk_bytenr + compressed_len)
923 unsigned int nr_sectors;
925 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
929 nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
930 fs_info->sectorsize);
931 sums += fs_info->csum_size * nr_sectors;
933 ASSERT(comp_bio->bi_iter.bi_size);
934 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
935 BTRFS_WQ_ENDIO_DATA);
938 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
947 if (cb->compressed_pages) {
948 for (i = 0; i < cb->nr_pages; i++) {
949 if (cb->compressed_pages[i])
950 __free_page(cb->compressed_pages[i]);
954 kfree(cb->compressed_pages);
958 bio->bi_status = ret;
963 comp_bio->bi_status = ret;
966 /* All bytes of @cb is submitted, endio will free @cb */
967 if (cur_disk_byte == disk_bytenr + compressed_len)
970 wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
971 (disk_bytenr + compressed_len - cur_disk_byte) >>
972 fs_info->sectorsize_bits);
974 * Even with previous bio ended, we should still have io not yet
975 * submitted, thus need to finish @cb manually.
977 ASSERT(refcount_read(&cb->pending_sectors));
978 /* Now we are the only one referring @cb, can finish it safely. */
979 finish_compressed_bio_read(cb);
983 * Heuristic uses systematic sampling to collect data from the input data
984 * range, the logic can be tuned by the following constants:
986 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
987 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
989 #define SAMPLING_READ_SIZE (16)
990 #define SAMPLING_INTERVAL (256)
993 * For statistical analysis of the input data we consider bytes that form a
994 * Galois Field of 256 objects. Each object has an attribute count, ie. how
995 * many times the object appeared in the sample.
997 #define BUCKET_SIZE (256)
1000 * The size of the sample is based on a statistical sampling rule of thumb.
1001 * The common way is to perform sampling tests as long as the number of
1002 * elements in each cell is at least 5.
1004 * Instead of 5, we choose 32 to obtain more accurate results.
1005 * If the data contain the maximum number of symbols, which is 256, we obtain a
1006 * sample size bound by 8192.
1008 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
1009 * from up to 512 locations.
1011 #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
1012 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
1014 struct bucket_item {
1018 struct heuristic_ws {
1019 /* Partial copy of input data */
1022 /* Buckets store counters for each byte value */
1023 struct bucket_item *bucket;
1024 /* Sorting buffer */
1025 struct bucket_item *bucket_b;
1026 struct list_head list;
1029 static struct workspace_manager heuristic_wsm;
1031 static void free_heuristic_ws(struct list_head *ws)
1033 struct heuristic_ws *workspace;
1035 workspace = list_entry(ws, struct heuristic_ws, list);
1037 kvfree(workspace->sample);
1038 kfree(workspace->bucket);
1039 kfree(workspace->bucket_b);
1043 static struct list_head *alloc_heuristic_ws(unsigned int level)
1045 struct heuristic_ws *ws;
1047 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
1049 return ERR_PTR(-ENOMEM);
1051 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
1055 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
1059 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
1063 INIT_LIST_HEAD(&ws->list);
1066 free_heuristic_ws(&ws->list);
1067 return ERR_PTR(-ENOMEM);
1070 const struct btrfs_compress_op btrfs_heuristic_compress = {
1071 .workspace_manager = &heuristic_wsm,
1074 static const struct btrfs_compress_op * const btrfs_compress_op[] = {
1075 /* The heuristic is represented as compression type 0 */
1076 &btrfs_heuristic_compress,
1077 &btrfs_zlib_compress,
1078 &btrfs_lzo_compress,
1079 &btrfs_zstd_compress,
1082 static struct list_head *alloc_workspace(int type, unsigned int level)
1085 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
1086 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
1087 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
1088 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
1091 * This can't happen, the type is validated several times
1092 * before we get here.
1098 static void free_workspace(int type, struct list_head *ws)
1101 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
1102 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
1103 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
1104 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
1107 * This can't happen, the type is validated several times
1108 * before we get here.
1114 static void btrfs_init_workspace_manager(int type)
1116 struct workspace_manager *wsm;
1117 struct list_head *workspace;
1119 wsm = btrfs_compress_op[type]->workspace_manager;
1120 INIT_LIST_HEAD(&wsm->idle_ws);
1121 spin_lock_init(&wsm->ws_lock);
1122 atomic_set(&wsm->total_ws, 0);
1123 init_waitqueue_head(&wsm->ws_wait);
1126 * Preallocate one workspace for each compression type so we can
1127 * guarantee forward progress in the worst case
1129 workspace = alloc_workspace(type, 0);
1130 if (IS_ERR(workspace)) {
1132 "BTRFS: cannot preallocate compression workspace, will try later\n");
1134 atomic_set(&wsm->total_ws, 1);
1136 list_add(workspace, &wsm->idle_ws);
1140 static void btrfs_cleanup_workspace_manager(int type)
1142 struct workspace_manager *wsman;
1143 struct list_head *ws;
1145 wsman = btrfs_compress_op[type]->workspace_manager;
1146 while (!list_empty(&wsman->idle_ws)) {
1147 ws = wsman->idle_ws.next;
1149 free_workspace(type, ws);
1150 atomic_dec(&wsman->total_ws);
1155 * This finds an available workspace or allocates a new one.
1156 * If it's not possible to allocate a new one, waits until there's one.
1157 * Preallocation makes a forward progress guarantees and we do not return
1160 struct list_head *btrfs_get_workspace(int type, unsigned int level)
1162 struct workspace_manager *wsm;
1163 struct list_head *workspace;
1164 int cpus = num_online_cpus();
1166 struct list_head *idle_ws;
1167 spinlock_t *ws_lock;
1169 wait_queue_head_t *ws_wait;
1172 wsm = btrfs_compress_op[type]->workspace_manager;
1173 idle_ws = &wsm->idle_ws;
1174 ws_lock = &wsm->ws_lock;
1175 total_ws = &wsm->total_ws;
1176 ws_wait = &wsm->ws_wait;
1177 free_ws = &wsm->free_ws;
1181 if (!list_empty(idle_ws)) {
1182 workspace = idle_ws->next;
1183 list_del(workspace);
1185 spin_unlock(ws_lock);
1189 if (atomic_read(total_ws) > cpus) {
1192 spin_unlock(ws_lock);
1193 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
1194 if (atomic_read(total_ws) > cpus && !*free_ws)
1196 finish_wait(ws_wait, &wait);
1199 atomic_inc(total_ws);
1200 spin_unlock(ws_lock);
1203 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1204 * to turn it off here because we might get called from the restricted
1205 * context of btrfs_compress_bio/btrfs_compress_pages
1207 nofs_flag = memalloc_nofs_save();
1208 workspace = alloc_workspace(type, level);
1209 memalloc_nofs_restore(nofs_flag);
1211 if (IS_ERR(workspace)) {
1212 atomic_dec(total_ws);
1216 * Do not return the error but go back to waiting. There's a
1217 * workspace preallocated for each type and the compression
1218 * time is bounded so we get to a workspace eventually. This
1219 * makes our caller's life easier.
1221 * To prevent silent and low-probability deadlocks (when the
1222 * initial preallocation fails), check if there are any
1223 * workspaces at all.
1225 if (atomic_read(total_ws) == 0) {
1226 static DEFINE_RATELIMIT_STATE(_rs,
1227 /* once per minute */ 60 * HZ,
1230 if (__ratelimit(&_rs)) {
1231 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
1239 static struct list_head *get_workspace(int type, int level)
1242 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
1243 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
1244 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
1245 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1248 * This can't happen, the type is validated several times
1249 * before we get here.
1256 * put a workspace struct back on the list or free it if we have enough
1257 * idle ones sitting around
1259 void btrfs_put_workspace(int type, struct list_head *ws)
1261 struct workspace_manager *wsm;
1262 struct list_head *idle_ws;
1263 spinlock_t *ws_lock;
1265 wait_queue_head_t *ws_wait;
1268 wsm = btrfs_compress_op[type]->workspace_manager;
1269 idle_ws = &wsm->idle_ws;
1270 ws_lock = &wsm->ws_lock;
1271 total_ws = &wsm->total_ws;
1272 ws_wait = &wsm->ws_wait;
1273 free_ws = &wsm->free_ws;
1276 if (*free_ws <= num_online_cpus()) {
1277 list_add(ws, idle_ws);
1279 spin_unlock(ws_lock);
1282 spin_unlock(ws_lock);
1284 free_workspace(type, ws);
1285 atomic_dec(total_ws);
1287 cond_wake_up(ws_wait);
1290 static void put_workspace(int type, struct list_head *ws)
1293 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1294 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1295 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
1296 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1299 * This can't happen, the type is validated several times
1300 * before we get here.
1307 * Adjust @level according to the limits of the compression algorithm or
1308 * fallback to default
1310 static unsigned int btrfs_compress_set_level(int type, unsigned level)
1312 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1315 level = ops->default_level;
1317 level = min(level, ops->max_level);
1323 * Given an address space and start and length, compress the bytes into @pages
1324 * that are allocated on demand.
1326 * @type_level is encoded algorithm and level, where level 0 means whatever
1327 * default the algorithm chooses and is opaque here;
1328 * - compression algo are 0-3
1329 * - the level are bits 4-7
1331 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1332 * and returns number of actually allocated pages
1334 * @total_in is used to return the number of bytes actually read. It
1335 * may be smaller than the input length if we had to exit early because we
1336 * ran out of room in the pages array or because we cross the
1337 * max_out threshold.
1339 * @total_out is an in/out parameter, must be set to the input length and will
1340 * be also used to return the total number of compressed bytes
1342 int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
1343 u64 start, struct page **pages,
1344 unsigned long *out_pages,
1345 unsigned long *total_in,
1346 unsigned long *total_out)
1348 int type = btrfs_compress_type(type_level);
1349 int level = btrfs_compress_level(type_level);
1350 struct list_head *workspace;
1353 level = btrfs_compress_set_level(type, level);
1354 workspace = get_workspace(type, level);
1355 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1356 out_pages, total_in, total_out);
1357 put_workspace(type, workspace);
1361 static int btrfs_decompress_bio(struct compressed_bio *cb)
1363 struct list_head *workspace;
1365 int type = cb->compress_type;
1367 workspace = get_workspace(type, 0);
1368 ret = compression_decompress_bio(workspace, cb);
1369 put_workspace(type, workspace);
1375 * a less complex decompression routine. Our compressed data fits in a
1376 * single page, and we want to read a single page out of it.
1377 * start_byte tells us the offset into the compressed data we're interested in
1379 int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1380 unsigned long start_byte, size_t srclen, size_t destlen)
1382 struct list_head *workspace;
1385 workspace = get_workspace(type, 0);
1386 ret = compression_decompress(type, workspace, data_in, dest_page,
1387 start_byte, srclen, destlen);
1388 put_workspace(type, workspace);
1393 void __init btrfs_init_compress(void)
1395 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1396 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1397 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1398 zstd_init_workspace_manager();
1401 void __cold btrfs_exit_compress(void)
1403 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1404 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1405 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1406 zstd_cleanup_workspace_manager();
1410 * Copy decompressed data from working buffer to pages.
1412 * @buf: The decompressed data buffer
1413 * @buf_len: The decompressed data length
1414 * @decompressed: Number of bytes that are already decompressed inside the
1416 * @cb: The compressed extent descriptor
1417 * @orig_bio: The original bio that the caller wants to read for
1419 * An easier to understand graph is like below:
1421 * |<- orig_bio ->| |<- orig_bio->|
1422 * |<------- full decompressed extent ----->|
1423 * |<----------- @cb range ---->|
1424 * | |<-- @buf_len -->|
1425 * |<--- @decompressed --->|
1427 * Note that, @cb can be a subpage of the full decompressed extent, but
1428 * @cb->start always has the same as the orig_file_offset value of the full
1429 * decompressed extent.
1431 * When reading compressed extent, we have to read the full compressed extent,
1432 * while @orig_bio may only want part of the range.
1433 * Thus this function will ensure only data covered by @orig_bio will be copied
1436 * Return 0 if we have copied all needed contents for @orig_bio.
1437 * Return >0 if we need continue decompress.
1439 int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1440 struct compressed_bio *cb, u32 decompressed)
1442 struct bio *orig_bio = cb->orig_bio;
1443 /* Offset inside the full decompressed extent */
1446 cur_offset = decompressed;
1447 /* The main loop to do the copy */
1448 while (cur_offset < decompressed + buf_len) {
1449 struct bio_vec bvec;
1452 /* Offset inside the full decompressed extent */
1455 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1457 * cb->start may underflow, but subtracting that value can still
1458 * give us correct offset inside the full decompressed extent.
1460 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
1462 /* Haven't reached the bvec range, exit */
1463 if (decompressed + buf_len <= bvec_offset)
1466 copy_start = max(cur_offset, bvec_offset);
1467 copy_len = min(bvec_offset + bvec.bv_len,
1468 decompressed + buf_len) - copy_start;
1472 * Extra range check to ensure we didn't go beyond
1475 ASSERT(copy_start - decompressed < buf_len);
1476 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1477 buf + copy_start - decompressed, copy_len);
1478 cur_offset += copy_len;
1480 bio_advance(orig_bio, copy_len);
1481 /* Finished the bio */
1482 if (!orig_bio->bi_iter.bi_size)
1489 * Shannon Entropy calculation
1491 * Pure byte distribution analysis fails to determine compressibility of data.
1492 * Try calculating entropy to estimate the average minimum number of bits
1493 * needed to encode the sampled data.
1495 * For convenience, return the percentage of needed bits, instead of amount of
1498 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1499 * and can be compressible with high probability
1501 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1503 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1505 #define ENTROPY_LVL_ACEPTABLE (65)
1506 #define ENTROPY_LVL_HIGH (80)
1509 * For increasead precision in shannon_entropy calculation,
1510 * let's do pow(n, M) to save more digits after comma:
1512 * - maximum int bit length is 64
1513 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1514 * - 13 * 4 = 52 < 64 -> M = 4
1518 static inline u32 ilog2_w(u64 n)
1520 return ilog2(n * n * n * n);
1523 static u32 shannon_entropy(struct heuristic_ws *ws)
1525 const u32 entropy_max = 8 * ilog2_w(2);
1526 u32 entropy_sum = 0;
1527 u32 p, p_base, sz_base;
1530 sz_base = ilog2_w(ws->sample_size);
1531 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1532 p = ws->bucket[i].count;
1533 p_base = ilog2_w(p);
1534 entropy_sum += p * (sz_base - p_base);
1537 entropy_sum /= ws->sample_size;
1538 return entropy_sum * 100 / entropy_max;
1541 #define RADIX_BASE 4U
1542 #define COUNTERS_SIZE (1U << RADIX_BASE)
1544 static u8 get4bits(u64 num, int shift) {
1549 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1554 * Use 4 bits as radix base
1555 * Use 16 u32 counters for calculating new position in buf array
1557 * @array - array that will be sorted
1558 * @array_buf - buffer array to store sorting results
1559 * must be equal in size to @array
1562 static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
1567 u32 counters[COUNTERS_SIZE];
1575 * Try avoid useless loop iterations for small numbers stored in big
1576 * counters. Example: 48 33 4 ... in 64bit array
1578 max_num = array[0].count;
1579 for (i = 1; i < num; i++) {
1580 buf_num = array[i].count;
1581 if (buf_num > max_num)
1585 buf_num = ilog2(max_num);
1586 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1589 while (shift < bitlen) {
1590 memset(counters, 0, sizeof(counters));
1592 for (i = 0; i < num; i++) {
1593 buf_num = array[i].count;
1594 addr = get4bits(buf_num, shift);
1598 for (i = 1; i < COUNTERS_SIZE; i++)
1599 counters[i] += counters[i - 1];
1601 for (i = num - 1; i >= 0; i--) {
1602 buf_num = array[i].count;
1603 addr = get4bits(buf_num, shift);
1605 new_addr = counters[addr];
1606 array_buf[new_addr] = array[i];
1609 shift += RADIX_BASE;
1612 * Normal radix expects to move data from a temporary array, to
1613 * the main one. But that requires some CPU time. Avoid that
1614 * by doing another sort iteration to original array instead of
1617 memset(counters, 0, sizeof(counters));
1619 for (i = 0; i < num; i ++) {
1620 buf_num = array_buf[i].count;
1621 addr = get4bits(buf_num, shift);
1625 for (i = 1; i < COUNTERS_SIZE; i++)
1626 counters[i] += counters[i - 1];
1628 for (i = num - 1; i >= 0; i--) {
1629 buf_num = array_buf[i].count;
1630 addr = get4bits(buf_num, shift);
1632 new_addr = counters[addr];
1633 array[new_addr] = array_buf[i];
1636 shift += RADIX_BASE;
1641 * Size of the core byte set - how many bytes cover 90% of the sample
1643 * There are several types of structured binary data that use nearly all byte
1644 * values. The distribution can be uniform and counts in all buckets will be
1645 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1647 * Other possibility is normal (Gaussian) distribution, where the data could
1648 * be potentially compressible, but we have to take a few more steps to decide
1651 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1652 * compression algo can easy fix that
1653 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1654 * probability is not compressible
1656 #define BYTE_CORE_SET_LOW (64)
1657 #define BYTE_CORE_SET_HIGH (200)
1659 static int byte_core_set_size(struct heuristic_ws *ws)
1662 u32 coreset_sum = 0;
1663 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1664 struct bucket_item *bucket = ws->bucket;
1666 /* Sort in reverse order */
1667 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
1669 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1670 coreset_sum += bucket[i].count;
1672 if (coreset_sum > core_set_threshold)
1675 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1676 coreset_sum += bucket[i].count;
1677 if (coreset_sum > core_set_threshold)
1685 * Count byte values in buckets.
1686 * This heuristic can detect textual data (configs, xml, json, html, etc).
1687 * Because in most text-like data byte set is restricted to limited number of
1688 * possible characters, and that restriction in most cases makes data easy to
1691 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1692 * less - compressible
1693 * more - need additional analysis
1695 #define BYTE_SET_THRESHOLD (64)
1697 static u32 byte_set_size(const struct heuristic_ws *ws)
1700 u32 byte_set_size = 0;
1702 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1703 if (ws->bucket[i].count > 0)
1708 * Continue collecting count of byte values in buckets. If the byte
1709 * set size is bigger then the threshold, it's pointless to continue,
1710 * the detection technique would fail for this type of data.
1712 for (; i < BUCKET_SIZE; i++) {
1713 if (ws->bucket[i].count > 0) {
1715 if (byte_set_size > BYTE_SET_THRESHOLD)
1716 return byte_set_size;
1720 return byte_set_size;
1723 static bool sample_repeated_patterns(struct heuristic_ws *ws)
1725 const u32 half_of_sample = ws->sample_size / 2;
1726 const u8 *data = ws->sample;
1728 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1731 static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1732 struct heuristic_ws *ws)
1735 u64 index, index_end;
1736 u32 i, curr_sample_pos;
1740 * Compression handles the input data by chunks of 128KiB
1741 * (defined by BTRFS_MAX_UNCOMPRESSED)
1743 * We do the same for the heuristic and loop over the whole range.
1745 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1746 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1748 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1749 end = start + BTRFS_MAX_UNCOMPRESSED;
1751 index = start >> PAGE_SHIFT;
1752 index_end = end >> PAGE_SHIFT;
1754 /* Don't miss unaligned end */
1755 if (!IS_ALIGNED(end, PAGE_SIZE))
1758 curr_sample_pos = 0;
1759 while (index < index_end) {
1760 page = find_get_page(inode->i_mapping, index);
1761 in_data = kmap_local_page(page);
1762 /* Handle case where the start is not aligned to PAGE_SIZE */
1763 i = start % PAGE_SIZE;
1764 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1765 /* Don't sample any garbage from the last page */
1766 if (start > end - SAMPLING_READ_SIZE)
1768 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1769 SAMPLING_READ_SIZE);
1770 i += SAMPLING_INTERVAL;
1771 start += SAMPLING_INTERVAL;
1772 curr_sample_pos += SAMPLING_READ_SIZE;
1774 kunmap_local(in_data);
1780 ws->sample_size = curr_sample_pos;
1784 * Compression heuristic.
1786 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1787 * quickly (compared to direct compression) detect data characteristics
1788 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1791 * The following types of analysis can be performed:
1792 * - detect mostly zero data
1793 * - detect data with low "byte set" size (text, etc)
1794 * - detect data with low/high "core byte" set
1796 * Return non-zero if the compression should be done, 0 otherwise.
1798 int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1800 struct list_head *ws_list = get_workspace(0, 0);
1801 struct heuristic_ws *ws;
1806 ws = list_entry(ws_list, struct heuristic_ws, list);
1808 heuristic_collect_sample(inode, start, end, ws);
1810 if (sample_repeated_patterns(ws)) {
1815 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1817 for (i = 0; i < ws->sample_size; i++) {
1818 byte = ws->sample[i];
1819 ws->bucket[byte].count++;
1822 i = byte_set_size(ws);
1823 if (i < BYTE_SET_THRESHOLD) {
1828 i = byte_core_set_size(ws);
1829 if (i <= BYTE_CORE_SET_LOW) {
1834 if (i >= BYTE_CORE_SET_HIGH) {
1839 i = shannon_entropy(ws);
1840 if (i <= ENTROPY_LVL_ACEPTABLE) {
1846 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1847 * needed to give green light to compression.
1849 * For now just assume that compression at that level is not worth the
1850 * resources because:
1852 * 1. it is possible to defrag the data later
1854 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1855 * values, every bucket has counter at level ~54. The heuristic would
1856 * be confused. This can happen when data have some internal repeated
1857 * patterns like "abbacbbc...". This can be detected by analyzing
1858 * pairs of bytes, which is too costly.
1860 if (i < ENTROPY_LVL_HIGH) {
1869 put_workspace(0, ws_list);
1874 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1875 * level, unrecognized string will set the default level
1877 unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
1879 unsigned int level = 0;
1885 if (str[0] == ':') {
1886 ret = kstrtouint(str + 1, 10, &level);
1891 level = btrfs_compress_set_level(type, level);