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/pagevec.h>
12 #include <linux/highmem.h>
13 #include <linux/kthread.h>
14 #include <linux/time.h>
15 #include <linux/init.h>
16 #include <linux/string.h>
17 #include <linux/backing-dev.h>
18 #include <linux/writeback.h>
19 #include <linux/psi.h>
20 #include <linux/slab.h>
21 #include <linux/sched/mm.h>
22 #include <linux/log2.h>
23 #include <crypto/hash.h>
28 #include "transaction.h"
29 #include "btrfs_inode.h"
31 #include "ordered-data.h"
32 #include "compression.h"
33 #include "extent_io.h"
34 #include "extent_map.h"
37 #include "file-item.h"
40 struct bio_set btrfs_compressed_bioset;
42 static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
44 const char* btrfs_compress_type2str(enum btrfs_compression_type type)
47 case BTRFS_COMPRESS_ZLIB:
48 case BTRFS_COMPRESS_LZO:
49 case BTRFS_COMPRESS_ZSTD:
50 case BTRFS_COMPRESS_NONE:
51 return btrfs_compress_types[type];
59 static inline struct compressed_bio *to_compressed_bio(struct btrfs_bio *bbio)
61 return container_of(bbio, struct compressed_bio, bbio);
64 static struct compressed_bio *alloc_compressed_bio(struct btrfs_inode *inode,
65 u64 start, blk_opf_t op,
66 btrfs_bio_end_io_t end_io)
68 struct btrfs_bio *bbio;
70 bbio = btrfs_bio(bio_alloc_bioset(NULL, BTRFS_MAX_COMPRESSED_PAGES, op,
71 GFP_NOFS, &btrfs_compressed_bioset));
72 btrfs_bio_init(bbio, inode->root->fs_info, end_io, NULL);
74 bbio->file_offset = start;
75 return to_compressed_bio(bbio);
78 bool btrfs_compress_is_valid_type(const char *str, size_t len)
82 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
83 size_t comp_len = strlen(btrfs_compress_types[i]);
88 if (!strncmp(btrfs_compress_types[i], str, comp_len))
94 static int compression_compress_pages(int type, struct list_head *ws,
95 struct address_space *mapping, u64 start, struct page **pages,
96 unsigned long *out_pages, unsigned long *total_in,
97 unsigned long *total_out)
100 case BTRFS_COMPRESS_ZLIB:
101 return zlib_compress_pages(ws, mapping, start, pages,
102 out_pages, total_in, total_out);
103 case BTRFS_COMPRESS_LZO:
104 return lzo_compress_pages(ws, mapping, start, pages,
105 out_pages, total_in, total_out);
106 case BTRFS_COMPRESS_ZSTD:
107 return zstd_compress_pages(ws, mapping, start, pages,
108 out_pages, total_in, total_out);
109 case BTRFS_COMPRESS_NONE:
112 * This can happen when compression races with remount setting
113 * it to 'no compress', while caller doesn't call
114 * inode_need_compress() to check if we really need to
117 * Not a big deal, just need to inform caller that we
118 * haven't allocated any pages yet.
125 static int compression_decompress_bio(struct list_head *ws,
126 struct compressed_bio *cb)
128 switch (cb->compress_type) {
129 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
130 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
131 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
132 case BTRFS_COMPRESS_NONE:
135 * This can't happen, the type is validated several times
136 * before we get here.
142 static int compression_decompress(int type, struct list_head *ws,
143 const u8 *data_in, struct page *dest_page,
144 unsigned long start_byte, size_t srclen, size_t destlen)
147 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
148 start_byte, srclen, destlen);
149 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
150 start_byte, srclen, destlen);
151 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
152 start_byte, srclen, destlen);
153 case BTRFS_COMPRESS_NONE:
156 * This can't happen, the type is validated several times
157 * before we get here.
163 static void btrfs_free_compressed_pages(struct compressed_bio *cb)
165 for (unsigned int i = 0; i < cb->nr_pages; i++)
166 put_page(cb->compressed_pages[i]);
167 kfree(cb->compressed_pages);
170 static int btrfs_decompress_bio(struct compressed_bio *cb);
172 static void end_compressed_bio_read(struct btrfs_bio *bbio)
174 struct compressed_bio *cb = to_compressed_bio(bbio);
175 blk_status_t status = bbio->bio.bi_status;
178 status = errno_to_blk_status(btrfs_decompress_bio(cb));
180 btrfs_free_compressed_pages(cb);
181 btrfs_bio_end_io(cb->orig_bbio, status);
186 * Clear the writeback bits on all of the file
187 * pages for a compressed write
189 static noinline void end_compressed_writeback(const struct compressed_bio *cb)
191 struct inode *inode = &cb->bbio.inode->vfs_inode;
192 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
193 unsigned long index = cb->start >> PAGE_SHIFT;
194 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
195 struct folio_batch fbatch;
196 const int errno = blk_status_to_errno(cb->bbio.bio.bi_status);
201 mapping_set_error(inode->i_mapping, errno);
203 folio_batch_init(&fbatch);
204 while (index <= end_index) {
205 ret = filemap_get_folios(inode->i_mapping, &index, end_index,
211 for (i = 0; i < ret; i++) {
212 struct folio *folio = fbatch.folios[i];
215 folio_set_error(folio);
216 btrfs_page_clamp_clear_writeback(fs_info, &folio->page,
219 folio_batch_release(&fbatch);
221 /* the inode may be gone now */
224 static void btrfs_finish_compressed_write_work(struct work_struct *work)
226 struct compressed_bio *cb =
227 container_of(work, struct compressed_bio, write_end_work);
230 * Ok, we're the last bio for this extent, step one is to call back
231 * into the FS and do all the end_io operations.
233 btrfs_writepage_endio_finish_ordered(cb->bbio.inode, NULL,
234 cb->start, cb->start + cb->len - 1,
235 cb->bbio.bio.bi_status == BLK_STS_OK);
238 end_compressed_writeback(cb);
239 /* Note, our inode could be gone now */
241 btrfs_free_compressed_pages(cb);
242 bio_put(&cb->bbio.bio);
246 * Do the cleanup once all the compressed pages hit the disk. This will clear
247 * writeback on the file pages and free the compressed pages.
249 * This also calls the writeback end hooks for the file pages so that metadata
250 * and checksums can be updated in the file.
252 static void end_compressed_bio_write(struct btrfs_bio *bbio)
254 struct compressed_bio *cb = to_compressed_bio(bbio);
255 struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
257 queue_work(fs_info->compressed_write_workers, &cb->write_end_work);
260 static void btrfs_add_compressed_bio_pages(struct compressed_bio *cb)
262 struct bio *bio = &cb->bbio.bio;
265 while (offset < cb->compressed_len) {
266 u32 len = min_t(u32, cb->compressed_len - offset, PAGE_SIZE);
268 /* Maximum compressed extent is smaller than bio size limit. */
269 __bio_add_page(bio, cb->compressed_pages[offset >> PAGE_SHIFT],
276 * worker function to build and submit bios for previously compressed pages.
277 * The corresponding pages in the inode should be marked for writeback
278 * and the compressed pages should have a reference on them for dropping
279 * when the IO is complete.
281 * This also checksums the file bytes and gets things ready for
284 void btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
285 unsigned int len, u64 disk_start,
286 unsigned int compressed_len,
287 struct page **compressed_pages,
288 unsigned int nr_pages,
289 blk_opf_t write_flags,
292 struct btrfs_fs_info *fs_info = inode->root->fs_info;
293 struct compressed_bio *cb;
295 ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
296 IS_ALIGNED(len, fs_info->sectorsize));
298 write_flags |= REQ_BTRFS_ONE_ORDERED;
300 cb = alloc_compressed_bio(inode, start, REQ_OP_WRITE | write_flags,
301 end_compressed_bio_write);
304 cb->compressed_pages = compressed_pages;
305 cb->compressed_len = compressed_len;
306 cb->writeback = writeback;
307 INIT_WORK(&cb->write_end_work, btrfs_finish_compressed_write_work);
308 cb->nr_pages = nr_pages;
309 cb->bbio.bio.bi_iter.bi_sector = disk_start >> SECTOR_SHIFT;
310 btrfs_add_compressed_bio_pages(cb);
312 btrfs_submit_bio(&cb->bbio, 0);
316 * Add extra pages in the same compressed file extent so that we don't need to
317 * re-read the same extent again and again.
319 * NOTE: this won't work well for subpage, as for subpage read, we lock the
320 * full page then submit bio for each compressed/regular extents.
322 * This means, if we have several sectors in the same page points to the same
323 * on-disk compressed data, we will re-read the same extent many times and
324 * this function can only help for the next page.
326 static noinline int add_ra_bio_pages(struct inode *inode,
328 struct compressed_bio *cb,
329 int *memstall, unsigned long *pflags)
331 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
332 unsigned long end_index;
333 struct bio *orig_bio = &cb->orig_bbio->bio;
334 u64 cur = cb->orig_bbio->file_offset + orig_bio->bi_iter.bi_size;
335 u64 isize = i_size_read(inode);
338 struct extent_map *em;
339 struct address_space *mapping = inode->i_mapping;
340 struct extent_map_tree *em_tree;
341 struct extent_io_tree *tree;
342 int sectors_missed = 0;
344 em_tree = &BTRFS_I(inode)->extent_tree;
345 tree = &BTRFS_I(inode)->io_tree;
351 * For current subpage support, we only support 64K page size,
352 * which means maximum compressed extent size (128K) is just 2x page
354 * This makes readahead less effective, so here disable readahead for
355 * subpage for now, until full compressed write is supported.
357 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
360 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
362 while (cur < compressed_end) {
364 u64 pg_index = cur >> PAGE_SHIFT;
367 if (pg_index > end_index)
370 page = xa_load(&mapping->i_pages, pg_index);
371 if (page && !xa_is_value(page)) {
372 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
373 fs_info->sectorsize_bits;
375 /* Beyond threshold, no need to continue */
376 if (sectors_missed > 4)
380 * Jump to next page start as we already have page for
383 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
387 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
392 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
394 /* There is already a page, skip to page end */
395 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
399 if (!*memstall && PageWorkingset(page)) {
400 psi_memstall_enter(pflags);
404 ret = set_page_extent_mapped(page);
411 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
412 lock_extent(tree, cur, page_end, NULL);
413 read_lock(&em_tree->lock);
414 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
415 read_unlock(&em_tree->lock);
418 * At this point, we have a locked page in the page cache for
419 * these bytes in the file. But, we have to make sure they map
420 * to this compressed extent on disk.
422 if (!em || cur < em->start ||
423 (cur + fs_info->sectorsize > extent_map_end(em)) ||
424 (em->block_start >> 9) != orig_bio->bi_iter.bi_sector) {
426 unlock_extent(tree, cur, page_end, NULL);
433 if (page->index == end_index) {
434 size_t zero_offset = offset_in_page(isize);
438 zeros = PAGE_SIZE - zero_offset;
439 memzero_page(page, zero_offset, zeros);
443 add_size = min(em->start + em->len, page_end + 1) - cur;
444 ret = bio_add_page(orig_bio, page, add_size, offset_in_page(cur));
445 if (ret != add_size) {
446 unlock_extent(tree, cur, page_end, NULL);
452 * If it's subpage, we also need to increase its
453 * subpage::readers number, as at endio we will decrease
454 * subpage::readers and to unlock the page.
456 if (fs_info->sectorsize < PAGE_SIZE)
457 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
465 * for a compressed read, the bio we get passed has all the inode pages
466 * in it. We don't actually do IO on those pages but allocate new ones
467 * to hold the compressed pages on disk.
469 * bio->bi_iter.bi_sector points to the compressed extent on disk
470 * bio->bi_io_vec points to all of the inode pages
472 * After the compressed pages are read, we copy the bytes into the
473 * bio we were passed and then call the bio end_io calls
475 void btrfs_submit_compressed_read(struct btrfs_bio *bbio, int mirror_num)
477 struct btrfs_inode *inode = bbio->inode;
478 struct btrfs_fs_info *fs_info = inode->root->fs_info;
479 struct extent_map_tree *em_tree = &inode->extent_tree;
480 struct compressed_bio *cb;
481 unsigned int compressed_len;
482 u64 file_offset = bbio->file_offset;
485 struct extent_map *em;
486 unsigned long pflags;
491 /* we need the actual starting offset of this extent in the file */
492 read_lock(&em_tree->lock);
493 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
494 read_unlock(&em_tree->lock);
500 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
501 compressed_len = em->block_len;
503 cb = alloc_compressed_bio(inode, file_offset, REQ_OP_READ,
504 end_compressed_bio_read);
506 cb->start = em->orig_start;
508 em_start = em->start;
510 cb->len = bbio->bio.bi_iter.bi_size;
511 cb->compressed_len = compressed_len;
512 cb->compress_type = em->compress_type;
513 cb->orig_bbio = bbio;
517 cb->nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
518 cb->compressed_pages = kcalloc(cb->nr_pages, sizeof(struct page *), GFP_NOFS);
519 if (!cb->compressed_pages) {
520 ret = BLK_STS_RESOURCE;
524 ret2 = btrfs_alloc_page_array(cb->nr_pages, cb->compressed_pages);
526 ret = BLK_STS_RESOURCE;
527 goto out_free_compressed_pages;
530 add_ra_bio_pages(&inode->vfs_inode, em_start + em_len, cb, &memstall,
533 /* include any pages we added in add_ra-bio_pages */
534 cb->len = bbio->bio.bi_iter.bi_size;
535 cb->bbio.bio.bi_iter.bi_sector = bbio->bio.bi_iter.bi_sector;
536 btrfs_add_compressed_bio_pages(cb);
539 psi_memstall_leave(&pflags);
541 btrfs_submit_bio(&cb->bbio, mirror_num);
544 out_free_compressed_pages:
545 kfree(cb->compressed_pages);
547 bio_put(&cb->bbio.bio);
549 btrfs_bio_end_io(bbio, ret);
553 * Heuristic uses systematic sampling to collect data from the input data
554 * range, the logic can be tuned by the following constants:
556 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
557 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
559 #define SAMPLING_READ_SIZE (16)
560 #define SAMPLING_INTERVAL (256)
563 * For statistical analysis of the input data we consider bytes that form a
564 * Galois Field of 256 objects. Each object has an attribute count, ie. how
565 * many times the object appeared in the sample.
567 #define BUCKET_SIZE (256)
570 * The size of the sample is based on a statistical sampling rule of thumb.
571 * The common way is to perform sampling tests as long as the number of
572 * elements in each cell is at least 5.
574 * Instead of 5, we choose 32 to obtain more accurate results.
575 * If the data contain the maximum number of symbols, which is 256, we obtain a
576 * sample size bound by 8192.
578 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
579 * from up to 512 locations.
581 #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
582 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
588 struct heuristic_ws {
589 /* Partial copy of input data */
592 /* Buckets store counters for each byte value */
593 struct bucket_item *bucket;
595 struct bucket_item *bucket_b;
596 struct list_head list;
599 static struct workspace_manager heuristic_wsm;
601 static void free_heuristic_ws(struct list_head *ws)
603 struct heuristic_ws *workspace;
605 workspace = list_entry(ws, struct heuristic_ws, list);
607 kvfree(workspace->sample);
608 kfree(workspace->bucket);
609 kfree(workspace->bucket_b);
613 static struct list_head *alloc_heuristic_ws(unsigned int level)
615 struct heuristic_ws *ws;
617 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
619 return ERR_PTR(-ENOMEM);
621 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
625 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
629 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
633 INIT_LIST_HEAD(&ws->list);
636 free_heuristic_ws(&ws->list);
637 return ERR_PTR(-ENOMEM);
640 const struct btrfs_compress_op btrfs_heuristic_compress = {
641 .workspace_manager = &heuristic_wsm,
644 static const struct btrfs_compress_op * const btrfs_compress_op[] = {
645 /* The heuristic is represented as compression type 0 */
646 &btrfs_heuristic_compress,
647 &btrfs_zlib_compress,
649 &btrfs_zstd_compress,
652 static struct list_head *alloc_workspace(int type, unsigned int level)
655 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
656 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
657 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
658 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
661 * This can't happen, the type is validated several times
662 * before we get here.
668 static void free_workspace(int type, struct list_head *ws)
671 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
672 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
673 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
674 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
677 * This can't happen, the type is validated several times
678 * before we get here.
684 static void btrfs_init_workspace_manager(int type)
686 struct workspace_manager *wsm;
687 struct list_head *workspace;
689 wsm = btrfs_compress_op[type]->workspace_manager;
690 INIT_LIST_HEAD(&wsm->idle_ws);
691 spin_lock_init(&wsm->ws_lock);
692 atomic_set(&wsm->total_ws, 0);
693 init_waitqueue_head(&wsm->ws_wait);
696 * Preallocate one workspace for each compression type so we can
697 * guarantee forward progress in the worst case
699 workspace = alloc_workspace(type, 0);
700 if (IS_ERR(workspace)) {
702 "BTRFS: cannot preallocate compression workspace, will try later\n");
704 atomic_set(&wsm->total_ws, 1);
706 list_add(workspace, &wsm->idle_ws);
710 static void btrfs_cleanup_workspace_manager(int type)
712 struct workspace_manager *wsman;
713 struct list_head *ws;
715 wsman = btrfs_compress_op[type]->workspace_manager;
716 while (!list_empty(&wsman->idle_ws)) {
717 ws = wsman->idle_ws.next;
719 free_workspace(type, ws);
720 atomic_dec(&wsman->total_ws);
725 * This finds an available workspace or allocates a new one.
726 * If it's not possible to allocate a new one, waits until there's one.
727 * Preallocation makes a forward progress guarantees and we do not return
730 struct list_head *btrfs_get_workspace(int type, unsigned int level)
732 struct workspace_manager *wsm;
733 struct list_head *workspace;
734 int cpus = num_online_cpus();
736 struct list_head *idle_ws;
739 wait_queue_head_t *ws_wait;
742 wsm = btrfs_compress_op[type]->workspace_manager;
743 idle_ws = &wsm->idle_ws;
744 ws_lock = &wsm->ws_lock;
745 total_ws = &wsm->total_ws;
746 ws_wait = &wsm->ws_wait;
747 free_ws = &wsm->free_ws;
751 if (!list_empty(idle_ws)) {
752 workspace = idle_ws->next;
755 spin_unlock(ws_lock);
759 if (atomic_read(total_ws) > cpus) {
762 spin_unlock(ws_lock);
763 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
764 if (atomic_read(total_ws) > cpus && !*free_ws)
766 finish_wait(ws_wait, &wait);
769 atomic_inc(total_ws);
770 spin_unlock(ws_lock);
773 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
774 * to turn it off here because we might get called from the restricted
775 * context of btrfs_compress_bio/btrfs_compress_pages
777 nofs_flag = memalloc_nofs_save();
778 workspace = alloc_workspace(type, level);
779 memalloc_nofs_restore(nofs_flag);
781 if (IS_ERR(workspace)) {
782 atomic_dec(total_ws);
786 * Do not return the error but go back to waiting. There's a
787 * workspace preallocated for each type and the compression
788 * time is bounded so we get to a workspace eventually. This
789 * makes our caller's life easier.
791 * To prevent silent and low-probability deadlocks (when the
792 * initial preallocation fails), check if there are any
795 if (atomic_read(total_ws) == 0) {
796 static DEFINE_RATELIMIT_STATE(_rs,
797 /* once per minute */ 60 * HZ,
800 if (__ratelimit(&_rs)) {
801 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
809 static struct list_head *get_workspace(int type, int level)
812 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
813 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
814 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
815 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
818 * This can't happen, the type is validated several times
819 * before we get here.
826 * put a workspace struct back on the list or free it if we have enough
827 * idle ones sitting around
829 void btrfs_put_workspace(int type, struct list_head *ws)
831 struct workspace_manager *wsm;
832 struct list_head *idle_ws;
835 wait_queue_head_t *ws_wait;
838 wsm = btrfs_compress_op[type]->workspace_manager;
839 idle_ws = &wsm->idle_ws;
840 ws_lock = &wsm->ws_lock;
841 total_ws = &wsm->total_ws;
842 ws_wait = &wsm->ws_wait;
843 free_ws = &wsm->free_ws;
846 if (*free_ws <= num_online_cpus()) {
847 list_add(ws, idle_ws);
849 spin_unlock(ws_lock);
852 spin_unlock(ws_lock);
854 free_workspace(type, ws);
855 atomic_dec(total_ws);
857 cond_wake_up(ws_wait);
860 static void put_workspace(int type, struct list_head *ws)
863 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
864 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
865 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
866 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
869 * This can't happen, the type is validated several times
870 * before we get here.
877 * Adjust @level according to the limits of the compression algorithm or
878 * fallback to default
880 static unsigned int btrfs_compress_set_level(int type, unsigned level)
882 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
885 level = ops->default_level;
887 level = min(level, ops->max_level);
893 * Given an address space and start and length, compress the bytes into @pages
894 * that are allocated on demand.
896 * @type_level is encoded algorithm and level, where level 0 means whatever
897 * default the algorithm chooses and is opaque here;
898 * - compression algo are 0-3
899 * - the level are bits 4-7
901 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
902 * and returns number of actually allocated pages
904 * @total_in is used to return the number of bytes actually read. It
905 * may be smaller than the input length if we had to exit early because we
906 * ran out of room in the pages array or because we cross the
909 * @total_out is an in/out parameter, must be set to the input length and will
910 * be also used to return the total number of compressed bytes
912 int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
913 u64 start, struct page **pages,
914 unsigned long *out_pages,
915 unsigned long *total_in,
916 unsigned long *total_out)
918 int type = btrfs_compress_type(type_level);
919 int level = btrfs_compress_level(type_level);
920 struct list_head *workspace;
923 level = btrfs_compress_set_level(type, level);
924 workspace = get_workspace(type, level);
925 ret = compression_compress_pages(type, workspace, mapping, start, pages,
926 out_pages, total_in, total_out);
927 put_workspace(type, workspace);
931 static int btrfs_decompress_bio(struct compressed_bio *cb)
933 struct list_head *workspace;
935 int type = cb->compress_type;
937 workspace = get_workspace(type, 0);
938 ret = compression_decompress_bio(workspace, cb);
939 put_workspace(type, workspace);
942 zero_fill_bio(&cb->orig_bbio->bio);
947 * a less complex decompression routine. Our compressed data fits in a
948 * single page, and we want to read a single page out of it.
949 * start_byte tells us the offset into the compressed data we're interested in
951 int btrfs_decompress(int type, const u8 *data_in, struct page *dest_page,
952 unsigned long start_byte, size_t srclen, size_t destlen)
954 struct list_head *workspace;
957 workspace = get_workspace(type, 0);
958 ret = compression_decompress(type, workspace, data_in, dest_page,
959 start_byte, srclen, destlen);
960 put_workspace(type, workspace);
965 int __init btrfs_init_compress(void)
967 if (bioset_init(&btrfs_compressed_bioset, BIO_POOL_SIZE,
968 offsetof(struct compressed_bio, bbio.bio),
971 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
972 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
973 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
974 zstd_init_workspace_manager();
978 void __cold btrfs_exit_compress(void)
980 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
981 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
982 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
983 zstd_cleanup_workspace_manager();
984 bioset_exit(&btrfs_compressed_bioset);
988 * Copy decompressed data from working buffer to pages.
990 * @buf: The decompressed data buffer
991 * @buf_len: The decompressed data length
992 * @decompressed: Number of bytes that are already decompressed inside the
994 * @cb: The compressed extent descriptor
995 * @orig_bio: The original bio that the caller wants to read for
997 * An easier to understand graph is like below:
999 * |<- orig_bio ->| |<- orig_bio->|
1000 * |<------- full decompressed extent ----->|
1001 * |<----------- @cb range ---->|
1002 * | |<-- @buf_len -->|
1003 * |<--- @decompressed --->|
1005 * Note that, @cb can be a subpage of the full decompressed extent, but
1006 * @cb->start always has the same as the orig_file_offset value of the full
1007 * decompressed extent.
1009 * When reading compressed extent, we have to read the full compressed extent,
1010 * while @orig_bio may only want part of the range.
1011 * Thus this function will ensure only data covered by @orig_bio will be copied
1014 * Return 0 if we have copied all needed contents for @orig_bio.
1015 * Return >0 if we need continue decompress.
1017 int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1018 struct compressed_bio *cb, u32 decompressed)
1020 struct bio *orig_bio = &cb->orig_bbio->bio;
1021 /* Offset inside the full decompressed extent */
1024 cur_offset = decompressed;
1025 /* The main loop to do the copy */
1026 while (cur_offset < decompressed + buf_len) {
1027 struct bio_vec bvec;
1030 /* Offset inside the full decompressed extent */
1033 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1035 * cb->start may underflow, but subtracting that value can still
1036 * give us correct offset inside the full decompressed extent.
1038 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
1040 /* Haven't reached the bvec range, exit */
1041 if (decompressed + buf_len <= bvec_offset)
1044 copy_start = max(cur_offset, bvec_offset);
1045 copy_len = min(bvec_offset + bvec.bv_len,
1046 decompressed + buf_len) - copy_start;
1050 * Extra range check to ensure we didn't go beyond
1053 ASSERT(copy_start - decompressed < buf_len);
1054 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1055 buf + copy_start - decompressed, copy_len);
1056 cur_offset += copy_len;
1058 bio_advance(orig_bio, copy_len);
1059 /* Finished the bio */
1060 if (!orig_bio->bi_iter.bi_size)
1067 * Shannon Entropy calculation
1069 * Pure byte distribution analysis fails to determine compressibility of data.
1070 * Try calculating entropy to estimate the average minimum number of bits
1071 * needed to encode the sampled data.
1073 * For convenience, return the percentage of needed bits, instead of amount of
1076 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1077 * and can be compressible with high probability
1079 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1081 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1083 #define ENTROPY_LVL_ACEPTABLE (65)
1084 #define ENTROPY_LVL_HIGH (80)
1087 * For increasead precision in shannon_entropy calculation,
1088 * let's do pow(n, M) to save more digits after comma:
1090 * - maximum int bit length is 64
1091 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1092 * - 13 * 4 = 52 < 64 -> M = 4
1096 static inline u32 ilog2_w(u64 n)
1098 return ilog2(n * n * n * n);
1101 static u32 shannon_entropy(struct heuristic_ws *ws)
1103 const u32 entropy_max = 8 * ilog2_w(2);
1104 u32 entropy_sum = 0;
1105 u32 p, p_base, sz_base;
1108 sz_base = ilog2_w(ws->sample_size);
1109 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1110 p = ws->bucket[i].count;
1111 p_base = ilog2_w(p);
1112 entropy_sum += p * (sz_base - p_base);
1115 entropy_sum /= ws->sample_size;
1116 return entropy_sum * 100 / entropy_max;
1119 #define RADIX_BASE 4U
1120 #define COUNTERS_SIZE (1U << RADIX_BASE)
1122 static u8 get4bits(u64 num, int shift) {
1127 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1132 * Use 4 bits as radix base
1133 * Use 16 u32 counters for calculating new position in buf array
1135 * @array - array that will be sorted
1136 * @array_buf - buffer array to store sorting results
1137 * must be equal in size to @array
1140 static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
1145 u32 counters[COUNTERS_SIZE];
1153 * Try avoid useless loop iterations for small numbers stored in big
1154 * counters. Example: 48 33 4 ... in 64bit array
1156 max_num = array[0].count;
1157 for (i = 1; i < num; i++) {
1158 buf_num = array[i].count;
1159 if (buf_num > max_num)
1163 buf_num = ilog2(max_num);
1164 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1167 while (shift < bitlen) {
1168 memset(counters, 0, sizeof(counters));
1170 for (i = 0; i < num; i++) {
1171 buf_num = array[i].count;
1172 addr = get4bits(buf_num, shift);
1176 for (i = 1; i < COUNTERS_SIZE; i++)
1177 counters[i] += counters[i - 1];
1179 for (i = num - 1; i >= 0; i--) {
1180 buf_num = array[i].count;
1181 addr = get4bits(buf_num, shift);
1183 new_addr = counters[addr];
1184 array_buf[new_addr] = array[i];
1187 shift += RADIX_BASE;
1190 * Normal radix expects to move data from a temporary array, to
1191 * the main one. But that requires some CPU time. Avoid that
1192 * by doing another sort iteration to original array instead of
1195 memset(counters, 0, sizeof(counters));
1197 for (i = 0; i < num; i ++) {
1198 buf_num = array_buf[i].count;
1199 addr = get4bits(buf_num, shift);
1203 for (i = 1; i < COUNTERS_SIZE; i++)
1204 counters[i] += counters[i - 1];
1206 for (i = num - 1; i >= 0; i--) {
1207 buf_num = array_buf[i].count;
1208 addr = get4bits(buf_num, shift);
1210 new_addr = counters[addr];
1211 array[new_addr] = array_buf[i];
1214 shift += RADIX_BASE;
1219 * Size of the core byte set - how many bytes cover 90% of the sample
1221 * There are several types of structured binary data that use nearly all byte
1222 * values. The distribution can be uniform and counts in all buckets will be
1223 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1225 * Other possibility is normal (Gaussian) distribution, where the data could
1226 * be potentially compressible, but we have to take a few more steps to decide
1229 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1230 * compression algo can easy fix that
1231 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1232 * probability is not compressible
1234 #define BYTE_CORE_SET_LOW (64)
1235 #define BYTE_CORE_SET_HIGH (200)
1237 static int byte_core_set_size(struct heuristic_ws *ws)
1240 u32 coreset_sum = 0;
1241 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1242 struct bucket_item *bucket = ws->bucket;
1244 /* Sort in reverse order */
1245 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
1247 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1248 coreset_sum += bucket[i].count;
1250 if (coreset_sum > core_set_threshold)
1253 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1254 coreset_sum += bucket[i].count;
1255 if (coreset_sum > core_set_threshold)
1263 * Count byte values in buckets.
1264 * This heuristic can detect textual data (configs, xml, json, html, etc).
1265 * Because in most text-like data byte set is restricted to limited number of
1266 * possible characters, and that restriction in most cases makes data easy to
1269 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1270 * less - compressible
1271 * more - need additional analysis
1273 #define BYTE_SET_THRESHOLD (64)
1275 static u32 byte_set_size(const struct heuristic_ws *ws)
1278 u32 byte_set_size = 0;
1280 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1281 if (ws->bucket[i].count > 0)
1286 * Continue collecting count of byte values in buckets. If the byte
1287 * set size is bigger then the threshold, it's pointless to continue,
1288 * the detection technique would fail for this type of data.
1290 for (; i < BUCKET_SIZE; i++) {
1291 if (ws->bucket[i].count > 0) {
1293 if (byte_set_size > BYTE_SET_THRESHOLD)
1294 return byte_set_size;
1298 return byte_set_size;
1301 static bool sample_repeated_patterns(struct heuristic_ws *ws)
1303 const u32 half_of_sample = ws->sample_size / 2;
1304 const u8 *data = ws->sample;
1306 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1309 static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1310 struct heuristic_ws *ws)
1313 u64 index, index_end;
1314 u32 i, curr_sample_pos;
1318 * Compression handles the input data by chunks of 128KiB
1319 * (defined by BTRFS_MAX_UNCOMPRESSED)
1321 * We do the same for the heuristic and loop over the whole range.
1323 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1324 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1326 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1327 end = start + BTRFS_MAX_UNCOMPRESSED;
1329 index = start >> PAGE_SHIFT;
1330 index_end = end >> PAGE_SHIFT;
1332 /* Don't miss unaligned end */
1333 if (!PAGE_ALIGNED(end))
1336 curr_sample_pos = 0;
1337 while (index < index_end) {
1338 page = find_get_page(inode->i_mapping, index);
1339 in_data = kmap_local_page(page);
1340 /* Handle case where the start is not aligned to PAGE_SIZE */
1341 i = start % PAGE_SIZE;
1342 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1343 /* Don't sample any garbage from the last page */
1344 if (start > end - SAMPLING_READ_SIZE)
1346 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1347 SAMPLING_READ_SIZE);
1348 i += SAMPLING_INTERVAL;
1349 start += SAMPLING_INTERVAL;
1350 curr_sample_pos += SAMPLING_READ_SIZE;
1352 kunmap_local(in_data);
1358 ws->sample_size = curr_sample_pos;
1362 * Compression heuristic.
1364 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1365 * quickly (compared to direct compression) detect data characteristics
1366 * (compressible/incompressible) to avoid wasting CPU time on incompressible
1369 * The following types of analysis can be performed:
1370 * - detect mostly zero data
1371 * - detect data with low "byte set" size (text, etc)
1372 * - detect data with low/high "core byte" set
1374 * Return non-zero if the compression should be done, 0 otherwise.
1376 int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1378 struct list_head *ws_list = get_workspace(0, 0);
1379 struct heuristic_ws *ws;
1384 ws = list_entry(ws_list, struct heuristic_ws, list);
1386 heuristic_collect_sample(inode, start, end, ws);
1388 if (sample_repeated_patterns(ws)) {
1393 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1395 for (i = 0; i < ws->sample_size; i++) {
1396 byte = ws->sample[i];
1397 ws->bucket[byte].count++;
1400 i = byte_set_size(ws);
1401 if (i < BYTE_SET_THRESHOLD) {
1406 i = byte_core_set_size(ws);
1407 if (i <= BYTE_CORE_SET_LOW) {
1412 if (i >= BYTE_CORE_SET_HIGH) {
1417 i = shannon_entropy(ws);
1418 if (i <= ENTROPY_LVL_ACEPTABLE) {
1424 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1425 * needed to give green light to compression.
1427 * For now just assume that compression at that level is not worth the
1428 * resources because:
1430 * 1. it is possible to defrag the data later
1432 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1433 * values, every bucket has counter at level ~54. The heuristic would
1434 * be confused. This can happen when data have some internal repeated
1435 * patterns like "abbacbbc...". This can be detected by analyzing
1436 * pairs of bytes, which is too costly.
1438 if (i < ENTROPY_LVL_HIGH) {
1447 put_workspace(0, ws_list);
1452 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1453 * level, unrecognized string will set the default level
1455 unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
1457 unsigned int level = 0;
1463 if (str[0] == ':') {
1464 ret = kstrtouint(str + 1, 10, &level);
1469 level = btrfs_compress_set_level(type, level);