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 void finish_compressed_bio_read(struct compressed_bio *cb)
144 if (cb->status == BLK_STS_OK)
145 cb->status = errno_to_blk_status(btrfs_decompress_bio(cb));
147 /* Release the compressed pages */
148 for (index = 0; index < cb->nr_pages; index++) {
149 page = cb->compressed_pages[index];
150 page->mapping = NULL;
154 /* Do io completion on the original bio */
155 if (cb->status != BLK_STS_OK)
156 cb->orig_bio->bi_status = cb->status;
157 bio_endio(cb->orig_bio);
159 /* Finally free the cb struct */
160 kfree(cb->compressed_pages);
165 * Verify the checksums and kick off repair if needed on the uncompressed data
166 * before decompressing it into the original bio and freeing the uncompressed
169 static void end_compressed_bio_read(struct bio *bio)
171 struct compressed_bio *cb = bio->bi_private;
172 struct inode *inode = cb->inode;
173 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
174 struct btrfs_inode *bi = BTRFS_I(inode);
175 bool csum = !(bi->flags & BTRFS_INODE_NODATASUM) &&
176 !test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state);
177 blk_status_t status = bio->bi_status;
178 struct btrfs_bio *bbio = btrfs_bio(bio);
179 struct bvec_iter iter;
183 btrfs_bio_for_each_sector(fs_info, bv, bbio, iter, offset) {
184 u64 start = bbio->file_offset + offset;
187 (!csum || !btrfs_check_data_csum(inode, bbio, offset,
188 bv.bv_page, bv.bv_offset))) {
189 clean_io_failure(fs_info, &bi->io_failure_tree,
190 &bi->io_tree, start, bv.bv_page,
191 btrfs_ino(bi), bv.bv_offset);
195 refcount_inc(&cb->pending_ios);
196 ret = btrfs_repair_one_sector(inode, bbio, offset,
197 bv.bv_page, bv.bv_offset,
198 btrfs_submit_data_read_bio);
200 refcount_dec(&cb->pending_ios);
201 status = errno_to_blk_status(ret);
209 if (refcount_dec_and_test(&cb->pending_ios))
210 finish_compressed_bio_read(cb);
211 btrfs_bio_free_csum(bbio);
216 * Clear the writeback bits on all of the file
217 * pages for a compressed write
219 static noinline void end_compressed_writeback(struct inode *inode,
220 const struct compressed_bio *cb)
222 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
223 unsigned long index = cb->start >> PAGE_SHIFT;
224 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
225 struct page *pages[16];
226 unsigned long nr_pages = end_index - index + 1;
227 const int errno = blk_status_to_errno(cb->status);
232 mapping_set_error(inode->i_mapping, errno);
234 while (nr_pages > 0) {
235 ret = find_get_pages_contig(inode->i_mapping, index,
237 nr_pages, ARRAY_SIZE(pages)), pages);
243 for (i = 0; i < ret; i++) {
245 SetPageError(pages[i]);
246 btrfs_page_clamp_clear_writeback(fs_info, pages[i],
253 /* the inode may be gone now */
256 static void finish_compressed_bio_write(struct compressed_bio *cb)
258 struct inode *inode = cb->inode;
262 * Ok, we're the last bio for this extent, step one is to call back
263 * into the FS and do all the end_io operations.
265 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
266 cb->start, cb->start + cb->len - 1,
267 cb->status == BLK_STS_OK);
270 end_compressed_writeback(inode, cb);
271 /* Note, our inode could be gone now */
274 * Release the compressed pages, these came from alloc_page and
275 * are not attached to the inode at all
277 for (index = 0; index < cb->nr_pages; index++) {
278 struct page *page = cb->compressed_pages[index];
280 page->mapping = NULL;
284 /* Finally free the cb struct */
285 kfree(cb->compressed_pages);
289 static void btrfs_finish_compressed_write_work(struct work_struct *work)
291 struct compressed_bio *cb =
292 container_of(work, struct compressed_bio, write_end_work);
294 finish_compressed_bio_write(cb);
298 * Do the cleanup once all the compressed pages hit the disk. This will clear
299 * writeback on the file pages and free the compressed pages.
301 * This also calls the writeback end hooks for the file pages so that metadata
302 * and checksums can be updated in the file.
304 static void end_compressed_bio_write(struct bio *bio)
306 struct compressed_bio *cb = bio->bi_private;
309 cb->status = bio->bi_status;
311 if (refcount_dec_and_test(&cb->pending_ios)) {
312 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
314 btrfs_record_physical_zoned(cb->inode, cb->start, bio);
315 queue_work(fs_info->compressed_write_workers, &cb->write_end_work);
321 * Allocate a compressed_bio, which will be used to read/write on-disk
322 * (aka, compressed) * data.
324 * @cb: The compressed_bio structure, which records all the needed
325 * information to bind the compressed data to the uncompressed
327 * @disk_byten: The logical bytenr where the compressed data will be read
328 * from or written to.
329 * @endio_func: The endio function to call after the IO for compressed data
331 * @next_stripe_start: Return value of logical bytenr of where next stripe starts.
332 * Let the caller know to only fill the bio up to the stripe
337 static struct bio *alloc_compressed_bio(struct compressed_bio *cb, u64 disk_bytenr,
338 blk_opf_t opf, bio_end_io_t endio_func,
339 u64 *next_stripe_start)
341 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
342 struct btrfs_io_geometry geom;
343 struct extent_map *em;
347 bio = btrfs_bio_alloc(BIO_MAX_VECS);
349 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
351 bio->bi_private = cb;
352 bio->bi_end_io = endio_func;
354 em = btrfs_get_chunk_map(fs_info, disk_bytenr, fs_info->sectorsize);
360 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
361 bio_set_dev(bio, em->map_lookup->stripes[0].dev->bdev);
363 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), disk_bytenr, &geom);
369 *next_stripe_start = disk_bytenr + geom.len;
370 refcount_inc(&cb->pending_ios);
375 * worker function to build and submit bios for previously compressed pages.
376 * The corresponding pages in the inode should be marked for writeback
377 * and the compressed pages should have a reference on them for dropping
378 * when the IO is complete.
380 * This also checksums the file bytes and gets things ready for
383 blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
384 unsigned int len, u64 disk_start,
385 unsigned int compressed_len,
386 struct page **compressed_pages,
387 unsigned int nr_pages,
388 blk_opf_t write_flags,
389 struct cgroup_subsys_state *blkcg_css,
392 struct btrfs_fs_info *fs_info = inode->root->fs_info;
393 struct bio *bio = NULL;
394 struct compressed_bio *cb;
395 u64 cur_disk_bytenr = disk_start;
396 u64 next_stripe_start;
397 blk_status_t ret = BLK_STS_OK;
398 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
399 const bool use_append = btrfs_use_zone_append(inode, disk_start);
400 const enum req_op bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
402 ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
403 IS_ALIGNED(len, fs_info->sectorsize));
404 cb = kmalloc(sizeof(struct compressed_bio), GFP_NOFS);
406 return BLK_STS_RESOURCE;
407 refcount_set(&cb->pending_ios, 1);
408 cb->status = BLK_STS_OK;
409 cb->inode = &inode->vfs_inode;
412 cb->compressed_pages = compressed_pages;
413 cb->compressed_len = compressed_len;
414 cb->writeback = writeback;
415 INIT_WORK(&cb->write_end_work, btrfs_finish_compressed_write_work);
416 cb->nr_pages = nr_pages;
419 kthread_associate_blkcg(blkcg_css);
421 while (cur_disk_bytenr < disk_start + compressed_len) {
422 u64 offset = cur_disk_bytenr - disk_start;
423 unsigned int index = offset >> PAGE_SHIFT;
424 unsigned int real_size;
426 struct page *page = compressed_pages[index];
429 /* Allocate new bio if submitted or not yet allocated */
431 bio = alloc_compressed_bio(cb, cur_disk_bytenr,
432 bio_op | write_flags, end_compressed_bio_write,
435 ret = errno_to_blk_status(PTR_ERR(bio));
439 bio->bi_opf |= REQ_CGROUP_PUNT;
442 * We should never reach next_stripe_start start as we will
443 * submit comp_bio when reach the boundary immediately.
445 ASSERT(cur_disk_bytenr != next_stripe_start);
448 * We have various limits on the real read size:
451 * - compressed length boundary
453 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_bytenr);
454 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
455 real_size = min_t(u64, real_size, compressed_len - offset);
456 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
459 added = bio_add_zone_append_page(bio, page, real_size,
460 offset_in_page(offset));
462 added = bio_add_page(bio, page, real_size,
463 offset_in_page(offset));
464 /* Reached zoned boundary */
468 cur_disk_bytenr += added;
469 /* Reached stripe boundary */
470 if (cur_disk_bytenr == next_stripe_start)
473 /* Finished the range */
474 if (cur_disk_bytenr == disk_start + compressed_len)
479 ret = btrfs_csum_one_bio(inode, bio, start, true);
481 bio->bi_status = ret;
487 ASSERT(bio->bi_iter.bi_size);
488 btrfs_submit_bio(fs_info, bio, 0);
495 kthread_associate_blkcg(NULL);
497 if (refcount_dec_and_test(&cb->pending_ios))
498 finish_compressed_bio_write(cb);
502 static u64 bio_end_offset(struct bio *bio)
504 struct bio_vec *last = bio_last_bvec_all(bio);
506 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
510 * Add extra pages in the same compressed file extent so that we don't need to
511 * re-read the same extent again and again.
513 * NOTE: this won't work well for subpage, as for subpage read, we lock the
514 * full page then submit bio for each compressed/regular extents.
516 * This means, if we have several sectors in the same page points to the same
517 * on-disk compressed data, we will re-read the same extent many times and
518 * this function can only help for the next page.
520 static noinline int add_ra_bio_pages(struct inode *inode,
522 struct compressed_bio *cb)
524 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
525 unsigned long end_index;
526 u64 cur = bio_end_offset(cb->orig_bio);
527 u64 isize = i_size_read(inode);
530 struct extent_map *em;
531 struct address_space *mapping = inode->i_mapping;
532 struct extent_map_tree *em_tree;
533 struct extent_io_tree *tree;
534 int sectors_missed = 0;
536 em_tree = &BTRFS_I(inode)->extent_tree;
537 tree = &BTRFS_I(inode)->io_tree;
543 * For current subpage support, we only support 64K page size,
544 * which means maximum compressed extent size (128K) is just 2x page
546 * This makes readahead less effective, so here disable readahead for
547 * subpage for now, until full compressed write is supported.
549 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
552 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
554 while (cur < compressed_end) {
556 u64 pg_index = cur >> PAGE_SHIFT;
559 if (pg_index > end_index)
562 page = xa_load(&mapping->i_pages, pg_index);
563 if (page && !xa_is_value(page)) {
564 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
565 fs_info->sectorsize_bits;
567 /* Beyond threshold, no need to continue */
568 if (sectors_missed > 4)
572 * Jump to next page start as we already have page for
575 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
579 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
584 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
586 /* There is already a page, skip to page end */
587 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
591 ret = set_page_extent_mapped(page);
598 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
599 lock_extent(tree, cur, page_end);
600 read_lock(&em_tree->lock);
601 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
602 read_unlock(&em_tree->lock);
605 * At this point, we have a locked page in the page cache for
606 * these bytes in the file. But, we have to make sure they map
607 * to this compressed extent on disk.
609 if (!em || cur < em->start ||
610 (cur + fs_info->sectorsize > extent_map_end(em)) ||
611 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
613 unlock_extent(tree, cur, page_end);
620 if (page->index == end_index) {
621 size_t zero_offset = offset_in_page(isize);
625 zeros = PAGE_SIZE - zero_offset;
626 memzero_page(page, zero_offset, zeros);
630 add_size = min(em->start + em->len, page_end + 1) - cur;
631 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
632 if (ret != add_size) {
633 unlock_extent(tree, cur, page_end);
639 * If it's subpage, we also need to increase its
640 * subpage::readers number, as at endio we will decrease
641 * subpage::readers and to unlock the page.
643 if (fs_info->sectorsize < PAGE_SIZE)
644 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
652 * for a compressed read, the bio we get passed has all the inode pages
653 * in it. We don't actually do IO on those pages but allocate new ones
654 * to hold the compressed pages on disk.
656 * bio->bi_iter.bi_sector points to the compressed extent on disk
657 * bio->bi_io_vec points to all of the inode pages
659 * After the compressed pages are read, we copy the bytes into the
660 * bio we were passed and then call the bio end_io calls
662 void btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
665 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
666 struct extent_map_tree *em_tree;
667 struct compressed_bio *cb;
668 unsigned int compressed_len;
669 struct bio *comp_bio = NULL;
670 const u64 disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
671 u64 cur_disk_byte = disk_bytenr;
672 u64 next_stripe_start;
676 struct extent_map *em;
681 em_tree = &BTRFS_I(inode)->extent_tree;
683 file_offset = bio_first_bvec_all(bio)->bv_offset +
684 page_offset(bio_first_page_all(bio));
686 /* we need the actual starting offset of this extent in the file */
687 read_lock(&em_tree->lock);
688 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
689 read_unlock(&em_tree->lock);
695 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
696 compressed_len = em->block_len;
697 cb = kmalloc(sizeof(struct compressed_bio), GFP_NOFS);
699 ret = BLK_STS_RESOURCE;
703 refcount_set(&cb->pending_ios, 1);
704 cb->status = BLK_STS_OK;
707 cb->start = em->orig_start;
709 em_start = em->start;
711 cb->len = bio->bi_iter.bi_size;
712 cb->compressed_len = compressed_len;
713 cb->compress_type = em->compress_type;
719 cb->nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
720 cb->compressed_pages = kcalloc(cb->nr_pages, sizeof(struct page *), GFP_NOFS);
721 if (!cb->compressed_pages) {
722 ret = BLK_STS_RESOURCE;
726 ret2 = btrfs_alloc_page_array(cb->nr_pages, cb->compressed_pages);
728 ret = BLK_STS_RESOURCE;
732 add_ra_bio_pages(inode, em_start + em_len, cb);
734 /* include any pages we added in add_ra-bio_pages */
735 cb->len = bio->bi_iter.bi_size;
737 while (cur_disk_byte < disk_bytenr + compressed_len) {
738 u64 offset = cur_disk_byte - disk_bytenr;
739 unsigned int index = offset >> PAGE_SHIFT;
740 unsigned int real_size;
742 struct page *page = cb->compressed_pages[index];
745 /* Allocate new bio if submitted or not yet allocated */
747 comp_bio = alloc_compressed_bio(cb, cur_disk_byte,
748 REQ_OP_READ, end_compressed_bio_read,
750 if (IS_ERR(comp_bio)) {
751 cb->status = errno_to_blk_status(PTR_ERR(comp_bio));
756 * We should never reach next_stripe_start start as we will
757 * submit comp_bio when reach the boundary immediately.
759 ASSERT(cur_disk_byte != next_stripe_start);
761 * We have various limit on the real read size:
764 * - compressed length boundary
766 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_byte);
767 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
768 real_size = min_t(u64, real_size, compressed_len - offset);
769 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
771 added = bio_add_page(comp_bio, page, real_size, offset_in_page(offset));
773 * Maximum compressed extent is smaller than bio size limit,
774 * thus bio_add_page() should always success.
776 ASSERT(added == real_size);
777 cur_disk_byte += added;
779 /* Reached stripe boundary, need to submit */
780 if (cur_disk_byte == next_stripe_start)
783 /* Has finished the range, need to submit */
784 if (cur_disk_byte == disk_bytenr + compressed_len)
788 /* Save the original iter for read repair */
789 if (bio_op(comp_bio) == REQ_OP_READ)
790 btrfs_bio(comp_bio)->iter = comp_bio->bi_iter;
793 * Save the initial offset of this chunk, as there
794 * is no direct correlation between compressed pages and
795 * the original file offset. The field is only used for
796 * priting error messages.
798 btrfs_bio(comp_bio)->file_offset = file_offset;
800 ret = btrfs_lookup_bio_sums(inode, comp_bio, NULL);
802 comp_bio->bi_status = ret;
807 ASSERT(comp_bio->bi_iter.bi_size);
808 btrfs_submit_bio(fs_info, comp_bio, mirror_num);
813 if (refcount_dec_and_test(&cb->pending_ios))
814 finish_compressed_bio_read(cb);
818 if (cb->compressed_pages) {
819 for (i = 0; i < cb->nr_pages; i++) {
820 if (cb->compressed_pages[i])
821 __free_page(cb->compressed_pages[i]);
825 kfree(cb->compressed_pages);
829 bio->bi_status = ret;
835 * Heuristic uses systematic sampling to collect data from the input data
836 * range, the logic can be tuned by the following constants:
838 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
839 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
841 #define SAMPLING_READ_SIZE (16)
842 #define SAMPLING_INTERVAL (256)
845 * For statistical analysis of the input data we consider bytes that form a
846 * Galois Field of 256 objects. Each object has an attribute count, ie. how
847 * many times the object appeared in the sample.
849 #define BUCKET_SIZE (256)
852 * The size of the sample is based on a statistical sampling rule of thumb.
853 * The common way is to perform sampling tests as long as the number of
854 * elements in each cell is at least 5.
856 * Instead of 5, we choose 32 to obtain more accurate results.
857 * If the data contain the maximum number of symbols, which is 256, we obtain a
858 * sample size bound by 8192.
860 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
861 * from up to 512 locations.
863 #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
864 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
870 struct heuristic_ws {
871 /* Partial copy of input data */
874 /* Buckets store counters for each byte value */
875 struct bucket_item *bucket;
877 struct bucket_item *bucket_b;
878 struct list_head list;
881 static struct workspace_manager heuristic_wsm;
883 static void free_heuristic_ws(struct list_head *ws)
885 struct heuristic_ws *workspace;
887 workspace = list_entry(ws, struct heuristic_ws, list);
889 kvfree(workspace->sample);
890 kfree(workspace->bucket);
891 kfree(workspace->bucket_b);
895 static struct list_head *alloc_heuristic_ws(unsigned int level)
897 struct heuristic_ws *ws;
899 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
901 return ERR_PTR(-ENOMEM);
903 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
907 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
911 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
915 INIT_LIST_HEAD(&ws->list);
918 free_heuristic_ws(&ws->list);
919 return ERR_PTR(-ENOMEM);
922 const struct btrfs_compress_op btrfs_heuristic_compress = {
923 .workspace_manager = &heuristic_wsm,
926 static const struct btrfs_compress_op * const btrfs_compress_op[] = {
927 /* The heuristic is represented as compression type 0 */
928 &btrfs_heuristic_compress,
929 &btrfs_zlib_compress,
931 &btrfs_zstd_compress,
934 static struct list_head *alloc_workspace(int type, unsigned int level)
937 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
938 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
939 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
940 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
943 * This can't happen, the type is validated several times
944 * before we get here.
950 static void free_workspace(int type, struct list_head *ws)
953 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
954 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
955 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
956 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
959 * This can't happen, the type is validated several times
960 * before we get here.
966 static void btrfs_init_workspace_manager(int type)
968 struct workspace_manager *wsm;
969 struct list_head *workspace;
971 wsm = btrfs_compress_op[type]->workspace_manager;
972 INIT_LIST_HEAD(&wsm->idle_ws);
973 spin_lock_init(&wsm->ws_lock);
974 atomic_set(&wsm->total_ws, 0);
975 init_waitqueue_head(&wsm->ws_wait);
978 * Preallocate one workspace for each compression type so we can
979 * guarantee forward progress in the worst case
981 workspace = alloc_workspace(type, 0);
982 if (IS_ERR(workspace)) {
984 "BTRFS: cannot preallocate compression workspace, will try later\n");
986 atomic_set(&wsm->total_ws, 1);
988 list_add(workspace, &wsm->idle_ws);
992 static void btrfs_cleanup_workspace_manager(int type)
994 struct workspace_manager *wsman;
995 struct list_head *ws;
997 wsman = btrfs_compress_op[type]->workspace_manager;
998 while (!list_empty(&wsman->idle_ws)) {
999 ws = wsman->idle_ws.next;
1001 free_workspace(type, ws);
1002 atomic_dec(&wsman->total_ws);
1007 * This finds an available workspace or allocates a new one.
1008 * If it's not possible to allocate a new one, waits until there's one.
1009 * Preallocation makes a forward progress guarantees and we do not return
1012 struct list_head *btrfs_get_workspace(int type, unsigned int level)
1014 struct workspace_manager *wsm;
1015 struct list_head *workspace;
1016 int cpus = num_online_cpus();
1018 struct list_head *idle_ws;
1019 spinlock_t *ws_lock;
1021 wait_queue_head_t *ws_wait;
1024 wsm = btrfs_compress_op[type]->workspace_manager;
1025 idle_ws = &wsm->idle_ws;
1026 ws_lock = &wsm->ws_lock;
1027 total_ws = &wsm->total_ws;
1028 ws_wait = &wsm->ws_wait;
1029 free_ws = &wsm->free_ws;
1033 if (!list_empty(idle_ws)) {
1034 workspace = idle_ws->next;
1035 list_del(workspace);
1037 spin_unlock(ws_lock);
1041 if (atomic_read(total_ws) > cpus) {
1044 spin_unlock(ws_lock);
1045 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
1046 if (atomic_read(total_ws) > cpus && !*free_ws)
1048 finish_wait(ws_wait, &wait);
1051 atomic_inc(total_ws);
1052 spin_unlock(ws_lock);
1055 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1056 * to turn it off here because we might get called from the restricted
1057 * context of btrfs_compress_bio/btrfs_compress_pages
1059 nofs_flag = memalloc_nofs_save();
1060 workspace = alloc_workspace(type, level);
1061 memalloc_nofs_restore(nofs_flag);
1063 if (IS_ERR(workspace)) {
1064 atomic_dec(total_ws);
1068 * Do not return the error but go back to waiting. There's a
1069 * workspace preallocated for each type and the compression
1070 * time is bounded so we get to a workspace eventually. This
1071 * makes our caller's life easier.
1073 * To prevent silent and low-probability deadlocks (when the
1074 * initial preallocation fails), check if there are any
1075 * workspaces at all.
1077 if (atomic_read(total_ws) == 0) {
1078 static DEFINE_RATELIMIT_STATE(_rs,
1079 /* once per minute */ 60 * HZ,
1082 if (__ratelimit(&_rs)) {
1083 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
1091 static struct list_head *get_workspace(int type, int level)
1094 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
1095 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
1096 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
1097 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1100 * This can't happen, the type is validated several times
1101 * before we get here.
1108 * put a workspace struct back on the list or free it if we have enough
1109 * idle ones sitting around
1111 void btrfs_put_workspace(int type, struct list_head *ws)
1113 struct workspace_manager *wsm;
1114 struct list_head *idle_ws;
1115 spinlock_t *ws_lock;
1117 wait_queue_head_t *ws_wait;
1120 wsm = btrfs_compress_op[type]->workspace_manager;
1121 idle_ws = &wsm->idle_ws;
1122 ws_lock = &wsm->ws_lock;
1123 total_ws = &wsm->total_ws;
1124 ws_wait = &wsm->ws_wait;
1125 free_ws = &wsm->free_ws;
1128 if (*free_ws <= num_online_cpus()) {
1129 list_add(ws, idle_ws);
1131 spin_unlock(ws_lock);
1134 spin_unlock(ws_lock);
1136 free_workspace(type, ws);
1137 atomic_dec(total_ws);
1139 cond_wake_up(ws_wait);
1142 static void put_workspace(int type, struct list_head *ws)
1145 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1146 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1147 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
1148 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1151 * This can't happen, the type is validated several times
1152 * before we get here.
1159 * Adjust @level according to the limits of the compression algorithm or
1160 * fallback to default
1162 static unsigned int btrfs_compress_set_level(int type, unsigned level)
1164 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1167 level = ops->default_level;
1169 level = min(level, ops->max_level);
1175 * Given an address space and start and length, compress the bytes into @pages
1176 * that are allocated on demand.
1178 * @type_level is encoded algorithm and level, where level 0 means whatever
1179 * default the algorithm chooses and is opaque here;
1180 * - compression algo are 0-3
1181 * - the level are bits 4-7
1183 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1184 * and returns number of actually allocated pages
1186 * @total_in is used to return the number of bytes actually read. It
1187 * may be smaller than the input length if we had to exit early because we
1188 * ran out of room in the pages array or because we cross the
1189 * max_out threshold.
1191 * @total_out is an in/out parameter, must be set to the input length and will
1192 * be also used to return the total number of compressed bytes
1194 int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
1195 u64 start, struct page **pages,
1196 unsigned long *out_pages,
1197 unsigned long *total_in,
1198 unsigned long *total_out)
1200 int type = btrfs_compress_type(type_level);
1201 int level = btrfs_compress_level(type_level);
1202 struct list_head *workspace;
1205 level = btrfs_compress_set_level(type, level);
1206 workspace = get_workspace(type, level);
1207 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1208 out_pages, total_in, total_out);
1209 put_workspace(type, workspace);
1213 static int btrfs_decompress_bio(struct compressed_bio *cb)
1215 struct list_head *workspace;
1217 int type = cb->compress_type;
1219 workspace = get_workspace(type, 0);
1220 ret = compression_decompress_bio(workspace, cb);
1221 put_workspace(type, workspace);
1227 * a less complex decompression routine. Our compressed data fits in a
1228 * single page, and we want to read a single page out of it.
1229 * start_byte tells us the offset into the compressed data we're interested in
1231 int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1232 unsigned long start_byte, size_t srclen, size_t destlen)
1234 struct list_head *workspace;
1237 workspace = get_workspace(type, 0);
1238 ret = compression_decompress(type, workspace, data_in, dest_page,
1239 start_byte, srclen, destlen);
1240 put_workspace(type, workspace);
1245 void __init btrfs_init_compress(void)
1247 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1248 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1249 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1250 zstd_init_workspace_manager();
1253 void __cold btrfs_exit_compress(void)
1255 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1256 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1257 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1258 zstd_cleanup_workspace_manager();
1262 * Copy decompressed data from working buffer to pages.
1264 * @buf: The decompressed data buffer
1265 * @buf_len: The decompressed data length
1266 * @decompressed: Number of bytes that are already decompressed inside the
1268 * @cb: The compressed extent descriptor
1269 * @orig_bio: The original bio that the caller wants to read for
1271 * An easier to understand graph is like below:
1273 * |<- orig_bio ->| |<- orig_bio->|
1274 * |<------- full decompressed extent ----->|
1275 * |<----------- @cb range ---->|
1276 * | |<-- @buf_len -->|
1277 * |<--- @decompressed --->|
1279 * Note that, @cb can be a subpage of the full decompressed extent, but
1280 * @cb->start always has the same as the orig_file_offset value of the full
1281 * decompressed extent.
1283 * When reading compressed extent, we have to read the full compressed extent,
1284 * while @orig_bio may only want part of the range.
1285 * Thus this function will ensure only data covered by @orig_bio will be copied
1288 * Return 0 if we have copied all needed contents for @orig_bio.
1289 * Return >0 if we need continue decompress.
1291 int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1292 struct compressed_bio *cb, u32 decompressed)
1294 struct bio *orig_bio = cb->orig_bio;
1295 /* Offset inside the full decompressed extent */
1298 cur_offset = decompressed;
1299 /* The main loop to do the copy */
1300 while (cur_offset < decompressed + buf_len) {
1301 struct bio_vec bvec;
1304 /* Offset inside the full decompressed extent */
1307 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1309 * cb->start may underflow, but subtracting that value can still
1310 * give us correct offset inside the full decompressed extent.
1312 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
1314 /* Haven't reached the bvec range, exit */
1315 if (decompressed + buf_len <= bvec_offset)
1318 copy_start = max(cur_offset, bvec_offset);
1319 copy_len = min(bvec_offset + bvec.bv_len,
1320 decompressed + buf_len) - copy_start;
1324 * Extra range check to ensure we didn't go beyond
1327 ASSERT(copy_start - decompressed < buf_len);
1328 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1329 buf + copy_start - decompressed, copy_len);
1330 cur_offset += copy_len;
1332 bio_advance(orig_bio, copy_len);
1333 /* Finished the bio */
1334 if (!orig_bio->bi_iter.bi_size)
1341 * Shannon Entropy calculation
1343 * Pure byte distribution analysis fails to determine compressibility of data.
1344 * Try calculating entropy to estimate the average minimum number of bits
1345 * needed to encode the sampled data.
1347 * For convenience, return the percentage of needed bits, instead of amount of
1350 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1351 * and can be compressible with high probability
1353 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1355 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1357 #define ENTROPY_LVL_ACEPTABLE (65)
1358 #define ENTROPY_LVL_HIGH (80)
1361 * For increasead precision in shannon_entropy calculation,
1362 * let's do pow(n, M) to save more digits after comma:
1364 * - maximum int bit length is 64
1365 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1366 * - 13 * 4 = 52 < 64 -> M = 4
1370 static inline u32 ilog2_w(u64 n)
1372 return ilog2(n * n * n * n);
1375 static u32 shannon_entropy(struct heuristic_ws *ws)
1377 const u32 entropy_max = 8 * ilog2_w(2);
1378 u32 entropy_sum = 0;
1379 u32 p, p_base, sz_base;
1382 sz_base = ilog2_w(ws->sample_size);
1383 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1384 p = ws->bucket[i].count;
1385 p_base = ilog2_w(p);
1386 entropy_sum += p * (sz_base - p_base);
1389 entropy_sum /= ws->sample_size;
1390 return entropy_sum * 100 / entropy_max;
1393 #define RADIX_BASE 4U
1394 #define COUNTERS_SIZE (1U << RADIX_BASE)
1396 static u8 get4bits(u64 num, int shift) {
1401 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1406 * Use 4 bits as radix base
1407 * Use 16 u32 counters for calculating new position in buf array
1409 * @array - array that will be sorted
1410 * @array_buf - buffer array to store sorting results
1411 * must be equal in size to @array
1414 static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
1419 u32 counters[COUNTERS_SIZE];
1427 * Try avoid useless loop iterations for small numbers stored in big
1428 * counters. Example: 48 33 4 ... in 64bit array
1430 max_num = array[0].count;
1431 for (i = 1; i < num; i++) {
1432 buf_num = array[i].count;
1433 if (buf_num > max_num)
1437 buf_num = ilog2(max_num);
1438 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1441 while (shift < bitlen) {
1442 memset(counters, 0, sizeof(counters));
1444 for (i = 0; i < num; i++) {
1445 buf_num = array[i].count;
1446 addr = get4bits(buf_num, shift);
1450 for (i = 1; i < COUNTERS_SIZE; i++)
1451 counters[i] += counters[i - 1];
1453 for (i = num - 1; i >= 0; i--) {
1454 buf_num = array[i].count;
1455 addr = get4bits(buf_num, shift);
1457 new_addr = counters[addr];
1458 array_buf[new_addr] = array[i];
1461 shift += RADIX_BASE;
1464 * Normal radix expects to move data from a temporary array, to
1465 * the main one. But that requires some CPU time. Avoid that
1466 * by doing another sort iteration to original array instead of
1469 memset(counters, 0, sizeof(counters));
1471 for (i = 0; i < num; i ++) {
1472 buf_num = array_buf[i].count;
1473 addr = get4bits(buf_num, shift);
1477 for (i = 1; i < COUNTERS_SIZE; i++)
1478 counters[i] += counters[i - 1];
1480 for (i = num - 1; i >= 0; i--) {
1481 buf_num = array_buf[i].count;
1482 addr = get4bits(buf_num, shift);
1484 new_addr = counters[addr];
1485 array[new_addr] = array_buf[i];
1488 shift += RADIX_BASE;
1493 * Size of the core byte set - how many bytes cover 90% of the sample
1495 * There are several types of structured binary data that use nearly all byte
1496 * values. The distribution can be uniform and counts in all buckets will be
1497 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1499 * Other possibility is normal (Gaussian) distribution, where the data could
1500 * be potentially compressible, but we have to take a few more steps to decide
1503 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1504 * compression algo can easy fix that
1505 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1506 * probability is not compressible
1508 #define BYTE_CORE_SET_LOW (64)
1509 #define BYTE_CORE_SET_HIGH (200)
1511 static int byte_core_set_size(struct heuristic_ws *ws)
1514 u32 coreset_sum = 0;
1515 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1516 struct bucket_item *bucket = ws->bucket;
1518 /* Sort in reverse order */
1519 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
1521 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1522 coreset_sum += bucket[i].count;
1524 if (coreset_sum > core_set_threshold)
1527 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1528 coreset_sum += bucket[i].count;
1529 if (coreset_sum > core_set_threshold)
1537 * Count byte values in buckets.
1538 * This heuristic can detect textual data (configs, xml, json, html, etc).
1539 * Because in most text-like data byte set is restricted to limited number of
1540 * possible characters, and that restriction in most cases makes data easy to
1543 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1544 * less - compressible
1545 * more - need additional analysis
1547 #define BYTE_SET_THRESHOLD (64)
1549 static u32 byte_set_size(const struct heuristic_ws *ws)
1552 u32 byte_set_size = 0;
1554 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1555 if (ws->bucket[i].count > 0)
1560 * Continue collecting count of byte values in buckets. If the byte
1561 * set size is bigger then the threshold, it's pointless to continue,
1562 * the detection technique would fail for this type of data.
1564 for (; i < BUCKET_SIZE; i++) {
1565 if (ws->bucket[i].count > 0) {
1567 if (byte_set_size > BYTE_SET_THRESHOLD)
1568 return byte_set_size;
1572 return byte_set_size;
1575 static bool sample_repeated_patterns(struct heuristic_ws *ws)
1577 const u32 half_of_sample = ws->sample_size / 2;
1578 const u8 *data = ws->sample;
1580 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1583 static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1584 struct heuristic_ws *ws)
1587 u64 index, index_end;
1588 u32 i, curr_sample_pos;
1592 * Compression handles the input data by chunks of 128KiB
1593 * (defined by BTRFS_MAX_UNCOMPRESSED)
1595 * We do the same for the heuristic and loop over the whole range.
1597 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1598 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1600 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1601 end = start + BTRFS_MAX_UNCOMPRESSED;
1603 index = start >> PAGE_SHIFT;
1604 index_end = end >> PAGE_SHIFT;
1606 /* Don't miss unaligned end */
1607 if (!IS_ALIGNED(end, PAGE_SIZE))
1610 curr_sample_pos = 0;
1611 while (index < index_end) {
1612 page = find_get_page(inode->i_mapping, index);
1613 in_data = kmap_local_page(page);
1614 /* Handle case where the start is not aligned to PAGE_SIZE */
1615 i = start % PAGE_SIZE;
1616 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1617 /* Don't sample any garbage from the last page */
1618 if (start > end - SAMPLING_READ_SIZE)
1620 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1621 SAMPLING_READ_SIZE);
1622 i += SAMPLING_INTERVAL;
1623 start += SAMPLING_INTERVAL;
1624 curr_sample_pos += SAMPLING_READ_SIZE;
1626 kunmap_local(in_data);
1632 ws->sample_size = curr_sample_pos;
1636 * Compression heuristic.
1638 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1639 * quickly (compared to direct compression) detect data characteristics
1640 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1643 * The following types of analysis can be performed:
1644 * - detect mostly zero data
1645 * - detect data with low "byte set" size (text, etc)
1646 * - detect data with low/high "core byte" set
1648 * Return non-zero if the compression should be done, 0 otherwise.
1650 int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1652 struct list_head *ws_list = get_workspace(0, 0);
1653 struct heuristic_ws *ws;
1658 ws = list_entry(ws_list, struct heuristic_ws, list);
1660 heuristic_collect_sample(inode, start, end, ws);
1662 if (sample_repeated_patterns(ws)) {
1667 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1669 for (i = 0; i < ws->sample_size; i++) {
1670 byte = ws->sample[i];
1671 ws->bucket[byte].count++;
1674 i = byte_set_size(ws);
1675 if (i < BYTE_SET_THRESHOLD) {
1680 i = byte_core_set_size(ws);
1681 if (i <= BYTE_CORE_SET_LOW) {
1686 if (i >= BYTE_CORE_SET_HIGH) {
1691 i = shannon_entropy(ws);
1692 if (i <= ENTROPY_LVL_ACEPTABLE) {
1698 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1699 * needed to give green light to compression.
1701 * For now just assume that compression at that level is not worth the
1702 * resources because:
1704 * 1. it is possible to defrag the data later
1706 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1707 * values, every bucket has counter at level ~54. The heuristic would
1708 * be confused. This can happen when data have some internal repeated
1709 * patterns like "abbacbbc...". This can be detected by analyzing
1710 * pairs of bytes, which is too costly.
1712 if (i < ENTROPY_LVL_HIGH) {
1721 put_workspace(0, ws_list);
1726 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1727 * level, unrecognized string will set the default level
1729 unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
1731 unsigned int level = 0;
1737 if (str[0] == ':') {
1738 ret = kstrtouint(str + 1, 10, &level);
1743 level = btrfs_compress_set_level(type, level);