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/time.h>
13 #include <linux/init.h>
14 #include <linux/string.h>
15 #include <linux/backing-dev.h>
16 #include <linux/writeback.h>
17 #include <linux/slab.h>
18 #include <linux/sched/mm.h>
19 #include <linux/log2.h>
22 #include "transaction.h"
23 #include "btrfs_inode.h"
25 #include "ordered-data.h"
26 #include "compression.h"
27 #include "extent_io.h"
28 #include "extent_map.h"
30 static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
32 const char* btrfs_compress_type2str(enum btrfs_compression_type type)
35 case BTRFS_COMPRESS_ZLIB:
36 case BTRFS_COMPRESS_LZO:
37 case BTRFS_COMPRESS_ZSTD:
38 case BTRFS_COMPRESS_NONE:
39 return btrfs_compress_types[type];
45 bool btrfs_compress_is_valid_type(const char *str, size_t len)
49 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
50 size_t comp_len = strlen(btrfs_compress_types[i]);
55 if (!strncmp(btrfs_compress_types[i], str, comp_len))
61 static int btrfs_decompress_bio(struct compressed_bio *cb);
63 static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
64 unsigned long disk_size)
66 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
68 return sizeof(struct compressed_bio) +
69 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * csum_size;
72 static int check_compressed_csum(struct btrfs_inode *inode,
73 struct compressed_bio *cb,
81 u32 *cb_sum = &cb->sums;
83 if (inode->flags & BTRFS_INODE_NODATASUM)
86 for (i = 0; i < cb->nr_pages; i++) {
87 page = cb->compressed_pages[i];
90 kaddr = kmap_atomic(page);
91 csum = btrfs_csum_data(kaddr, csum, PAGE_SIZE);
92 btrfs_csum_final(csum, (u8 *)&csum);
95 if (csum != *cb_sum) {
96 btrfs_print_data_csum_error(inode, disk_start, csum,
97 *cb_sum, cb->mirror_num);
109 /* when we finish reading compressed pages from the disk, we
110 * decompress them and then run the bio end_io routines on the
111 * decompressed pages (in the inode address space).
113 * This allows the checksumming and other IO error handling routines
116 * The compressed pages are freed here, and it must be run
119 static void end_compressed_bio_read(struct bio *bio)
121 struct compressed_bio *cb = bio->bi_private;
125 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
131 /* if there are more bios still pending for this compressed
134 if (!refcount_dec_and_test(&cb->pending_bios))
138 * Record the correct mirror_num in cb->orig_bio so that
139 * read-repair can work properly.
141 ASSERT(btrfs_io_bio(cb->orig_bio));
142 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
143 cb->mirror_num = mirror;
146 * Some IO in this cb have failed, just skip checksum as there
147 * is no way it could be correct.
153 ret = check_compressed_csum(BTRFS_I(inode), cb,
154 (u64)bio->bi_iter.bi_sector << 9);
158 /* ok, we're the last bio for this extent, lets start
161 ret = btrfs_decompress_bio(cb);
167 /* release the compressed pages */
169 for (index = 0; index < cb->nr_pages; index++) {
170 page = cb->compressed_pages[index];
171 page->mapping = NULL;
175 /* do io completion on the original bio */
177 bio_io_error(cb->orig_bio);
180 struct bio_vec *bvec;
183 * we have verified the checksum already, set page
184 * checked so the end_io handlers know about it
186 ASSERT(!bio_flagged(bio, BIO_CLONED));
187 bio_for_each_segment_all(bvec, cb->orig_bio, i)
188 SetPageChecked(bvec->bv_page);
190 bio_endio(cb->orig_bio);
193 /* finally free the cb struct */
194 kfree(cb->compressed_pages);
201 * Clear the writeback bits on all of the file
202 * pages for a compressed write
204 static noinline void end_compressed_writeback(struct inode *inode,
205 const struct compressed_bio *cb)
207 unsigned long index = cb->start >> PAGE_SHIFT;
208 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
209 struct page *pages[16];
210 unsigned long nr_pages = end_index - index + 1;
215 mapping_set_error(inode->i_mapping, -EIO);
217 while (nr_pages > 0) {
218 ret = find_get_pages_contig(inode->i_mapping, index,
220 nr_pages, ARRAY_SIZE(pages)), pages);
226 for (i = 0; i < ret; i++) {
228 SetPageError(pages[i]);
229 end_page_writeback(pages[i]);
235 /* the inode may be gone now */
239 * do the cleanup once all the compressed pages hit the disk.
240 * This will clear writeback on the file pages and free the compressed
243 * This also calls the writeback end hooks for the file pages so that
244 * metadata and checksums can be updated in the file.
246 static void end_compressed_bio_write(struct bio *bio)
248 struct extent_io_tree *tree;
249 struct compressed_bio *cb = bio->bi_private;
257 /* if there are more bios still pending for this compressed
260 if (!refcount_dec_and_test(&cb->pending_bios))
263 /* ok, we're the last bio for this extent, step one is to
264 * call back into the FS and do all the end_io operations
267 tree = &BTRFS_I(inode)->io_tree;
268 cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
269 tree->ops->writepage_end_io_hook(cb->compressed_pages[0],
271 cb->start + cb->len - 1,
274 cb->compressed_pages[0]->mapping = NULL;
276 end_compressed_writeback(inode, cb);
277 /* note, our inode could be gone now */
280 * release the compressed pages, these came from alloc_page and
281 * are not attached to the inode at all
284 for (index = 0; index < cb->nr_pages; index++) {
285 page = cb->compressed_pages[index];
286 page->mapping = NULL;
290 /* finally free the cb struct */
291 kfree(cb->compressed_pages);
298 * worker function to build and submit bios for previously compressed pages.
299 * The corresponding pages in the inode should be marked for writeback
300 * and the compressed pages should have a reference on them for dropping
301 * when the IO is complete.
303 * This also checksums the file bytes and gets things ready for
306 blk_status_t btrfs_submit_compressed_write(struct inode *inode, u64 start,
307 unsigned long len, u64 disk_start,
308 unsigned long compressed_len,
309 struct page **compressed_pages,
310 unsigned long nr_pages,
311 unsigned int write_flags)
313 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
314 struct bio *bio = NULL;
315 struct compressed_bio *cb;
316 unsigned long bytes_left;
319 u64 first_byte = disk_start;
320 struct block_device *bdev;
322 int skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
324 WARN_ON(start & ((u64)PAGE_SIZE - 1));
325 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
327 return BLK_STS_RESOURCE;
328 refcount_set(&cb->pending_bios, 0);
334 cb->compressed_pages = compressed_pages;
335 cb->compressed_len = compressed_len;
337 cb->nr_pages = nr_pages;
339 bdev = fs_info->fs_devices->latest_bdev;
341 bio = btrfs_bio_alloc(bdev, first_byte);
342 bio->bi_opf = REQ_OP_WRITE | write_flags;
343 bio->bi_private = cb;
344 bio->bi_end_io = end_compressed_bio_write;
345 refcount_set(&cb->pending_bios, 1);
347 /* create and submit bios for the compressed pages */
348 bytes_left = compressed_len;
349 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
352 page = compressed_pages[pg_index];
353 page->mapping = inode->i_mapping;
354 if (bio->bi_iter.bi_size)
355 submit = btrfs_merge_bio_hook(page, 0, PAGE_SIZE, bio, 0);
357 page->mapping = NULL;
358 if (submit || bio_add_page(bio, page, PAGE_SIZE, 0) <
361 * inc the count before we submit the bio so
362 * we know the end IO handler won't happen before
363 * we inc the count. Otherwise, the cb might get
364 * freed before we're done setting it up
366 refcount_inc(&cb->pending_bios);
367 ret = btrfs_bio_wq_end_io(fs_info, bio,
368 BTRFS_WQ_ENDIO_DATA);
369 BUG_ON(ret); /* -ENOMEM */
372 ret = btrfs_csum_one_bio(inode, bio, start, 1);
373 BUG_ON(ret); /* -ENOMEM */
376 ret = btrfs_map_bio(fs_info, bio, 0, 1);
378 bio->bi_status = ret;
382 bio = btrfs_bio_alloc(bdev, first_byte);
383 bio->bi_opf = REQ_OP_WRITE | write_flags;
384 bio->bi_private = cb;
385 bio->bi_end_io = end_compressed_bio_write;
386 bio_add_page(bio, page, PAGE_SIZE, 0);
388 if (bytes_left < PAGE_SIZE) {
390 "bytes left %lu compress len %lu nr %lu",
391 bytes_left, cb->compressed_len, cb->nr_pages);
393 bytes_left -= PAGE_SIZE;
394 first_byte += PAGE_SIZE;
398 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
399 BUG_ON(ret); /* -ENOMEM */
402 ret = btrfs_csum_one_bio(inode, bio, start, 1);
403 BUG_ON(ret); /* -ENOMEM */
406 ret = btrfs_map_bio(fs_info, bio, 0, 1);
408 bio->bi_status = ret;
415 static u64 bio_end_offset(struct bio *bio)
417 struct bio_vec *last = bio_last_bvec_all(bio);
419 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
422 static noinline int add_ra_bio_pages(struct inode *inode,
424 struct compressed_bio *cb)
426 unsigned long end_index;
427 unsigned long pg_index;
429 u64 isize = i_size_read(inode);
432 unsigned long nr_pages = 0;
433 struct extent_map *em;
434 struct address_space *mapping = inode->i_mapping;
435 struct extent_map_tree *em_tree;
436 struct extent_io_tree *tree;
440 last_offset = bio_end_offset(cb->orig_bio);
441 em_tree = &BTRFS_I(inode)->extent_tree;
442 tree = &BTRFS_I(inode)->io_tree;
447 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
449 while (last_offset < compressed_end) {
450 pg_index = last_offset >> PAGE_SHIFT;
452 if (pg_index > end_index)
456 page = radix_tree_lookup(&mapping->i_pages, pg_index);
458 if (page && !radix_tree_exceptional_entry(page)) {
465 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
470 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
475 end = last_offset + PAGE_SIZE - 1;
477 * at this point, we have a locked page in the page cache
478 * for these bytes in the file. But, we have to make
479 * sure they map to this compressed extent on disk.
481 set_page_extent_mapped(page);
482 lock_extent(tree, last_offset, end);
483 read_lock(&em_tree->lock);
484 em = lookup_extent_mapping(em_tree, last_offset,
486 read_unlock(&em_tree->lock);
488 if (!em || last_offset < em->start ||
489 (last_offset + PAGE_SIZE > extent_map_end(em)) ||
490 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
492 unlock_extent(tree, last_offset, end);
499 if (page->index == end_index) {
501 size_t zero_offset = isize & (PAGE_SIZE - 1);
505 zeros = PAGE_SIZE - zero_offset;
506 userpage = kmap_atomic(page);
507 memset(userpage + zero_offset, 0, zeros);
508 flush_dcache_page(page);
509 kunmap_atomic(userpage);
513 ret = bio_add_page(cb->orig_bio, page,
516 if (ret == PAGE_SIZE) {
520 unlock_extent(tree, last_offset, end);
526 last_offset += PAGE_SIZE;
532 * for a compressed read, the bio we get passed has all the inode pages
533 * in it. We don't actually do IO on those pages but allocate new ones
534 * to hold the compressed pages on disk.
536 * bio->bi_iter.bi_sector points to the compressed extent on disk
537 * bio->bi_io_vec points to all of the inode pages
539 * After the compressed pages are read, we copy the bytes into the
540 * bio we were passed and then call the bio end_io calls
542 blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
543 int mirror_num, unsigned long bio_flags)
545 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
546 struct extent_io_tree *tree;
547 struct extent_map_tree *em_tree;
548 struct compressed_bio *cb;
549 unsigned long compressed_len;
550 unsigned long nr_pages;
551 unsigned long pg_index;
553 struct block_device *bdev;
554 struct bio *comp_bio;
555 u64 cur_disk_byte = (u64)bio->bi_iter.bi_sector << 9;
558 struct extent_map *em;
559 blk_status_t ret = BLK_STS_RESOURCE;
563 tree = &BTRFS_I(inode)->io_tree;
564 em_tree = &BTRFS_I(inode)->extent_tree;
566 /* we need the actual starting offset of this extent in the file */
567 read_lock(&em_tree->lock);
568 em = lookup_extent_mapping(em_tree,
569 page_offset(bio_first_page_all(bio)),
571 read_unlock(&em_tree->lock);
573 return BLK_STS_IOERR;
575 compressed_len = em->block_len;
576 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
580 refcount_set(&cb->pending_bios, 0);
583 cb->mirror_num = mirror_num;
586 cb->start = em->orig_start;
588 em_start = em->start;
593 cb->len = bio->bi_iter.bi_size;
594 cb->compressed_len = compressed_len;
595 cb->compress_type = extent_compress_type(bio_flags);
598 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
599 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
601 if (!cb->compressed_pages)
604 bdev = fs_info->fs_devices->latest_bdev;
606 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
607 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
609 if (!cb->compressed_pages[pg_index]) {
610 faili = pg_index - 1;
611 ret = BLK_STS_RESOURCE;
615 faili = nr_pages - 1;
616 cb->nr_pages = nr_pages;
618 add_ra_bio_pages(inode, em_start + em_len, cb);
620 /* include any pages we added in add_ra-bio_pages */
621 cb->len = bio->bi_iter.bi_size;
623 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
624 comp_bio->bi_opf = REQ_OP_READ;
625 comp_bio->bi_private = cb;
626 comp_bio->bi_end_io = end_compressed_bio_read;
627 refcount_set(&cb->pending_bios, 1);
629 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
632 page = cb->compressed_pages[pg_index];
633 page->mapping = inode->i_mapping;
634 page->index = em_start >> PAGE_SHIFT;
636 if (comp_bio->bi_iter.bi_size)
637 submit = btrfs_merge_bio_hook(page, 0, PAGE_SIZE,
640 page->mapping = NULL;
641 if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
643 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
644 BTRFS_WQ_ENDIO_DATA);
645 BUG_ON(ret); /* -ENOMEM */
648 * inc the count before we submit the bio so
649 * we know the end IO handler won't happen before
650 * we inc the count. Otherwise, the cb might get
651 * freed before we're done setting it up
653 refcount_inc(&cb->pending_bios);
655 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
656 ret = btrfs_lookup_bio_sums(inode, comp_bio,
658 BUG_ON(ret); /* -ENOMEM */
660 sums += DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
661 fs_info->sectorsize);
663 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
665 comp_bio->bi_status = ret;
669 comp_bio = btrfs_bio_alloc(bdev, cur_disk_byte);
670 comp_bio->bi_opf = REQ_OP_READ;
671 comp_bio->bi_private = cb;
672 comp_bio->bi_end_io = end_compressed_bio_read;
674 bio_add_page(comp_bio, page, PAGE_SIZE, 0);
676 cur_disk_byte += PAGE_SIZE;
679 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
680 BUG_ON(ret); /* -ENOMEM */
682 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
683 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
684 BUG_ON(ret); /* -ENOMEM */
687 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num, 0);
689 comp_bio->bi_status = ret;
697 __free_page(cb->compressed_pages[faili]);
701 kfree(cb->compressed_pages);
710 * Heuristic uses systematic sampling to collect data from the input data
711 * range, the logic can be tuned by the following constants:
713 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
714 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
716 #define SAMPLING_READ_SIZE (16)
717 #define SAMPLING_INTERVAL (256)
720 * For statistical analysis of the input data we consider bytes that form a
721 * Galois Field of 256 objects. Each object has an attribute count, ie. how
722 * many times the object appeared in the sample.
724 #define BUCKET_SIZE (256)
727 * The size of the sample is based on a statistical sampling rule of thumb.
728 * The common way is to perform sampling tests as long as the number of
729 * elements in each cell is at least 5.
731 * Instead of 5, we choose 32 to obtain more accurate results.
732 * If the data contain the maximum number of symbols, which is 256, we obtain a
733 * sample size bound by 8192.
735 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
736 * from up to 512 locations.
738 #define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
739 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
745 struct heuristic_ws {
746 /* Partial copy of input data */
749 /* Buckets store counters for each byte value */
750 struct bucket_item *bucket;
752 struct bucket_item *bucket_b;
753 struct list_head list;
756 static void free_heuristic_ws(struct list_head *ws)
758 struct heuristic_ws *workspace;
760 workspace = list_entry(ws, struct heuristic_ws, list);
762 kvfree(workspace->sample);
763 kfree(workspace->bucket);
764 kfree(workspace->bucket_b);
768 static struct list_head *alloc_heuristic_ws(void)
770 struct heuristic_ws *ws;
772 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
774 return ERR_PTR(-ENOMEM);
776 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
780 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
784 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
788 INIT_LIST_HEAD(&ws->list);
791 free_heuristic_ws(&ws->list);
792 return ERR_PTR(-ENOMEM);
795 struct workspaces_list {
796 struct list_head idle_ws;
798 /* Number of free workspaces */
800 /* Total number of allocated workspaces */
802 /* Waiters for a free workspace */
803 wait_queue_head_t ws_wait;
806 static struct workspaces_list btrfs_comp_ws[BTRFS_COMPRESS_TYPES];
808 static struct workspaces_list btrfs_heuristic_ws;
810 static const struct btrfs_compress_op * const btrfs_compress_op[] = {
811 &btrfs_zlib_compress,
813 &btrfs_zstd_compress,
816 void __init btrfs_init_compress(void)
818 struct list_head *workspace;
821 INIT_LIST_HEAD(&btrfs_heuristic_ws.idle_ws);
822 spin_lock_init(&btrfs_heuristic_ws.ws_lock);
823 atomic_set(&btrfs_heuristic_ws.total_ws, 0);
824 init_waitqueue_head(&btrfs_heuristic_ws.ws_wait);
826 workspace = alloc_heuristic_ws();
827 if (IS_ERR(workspace)) {
829 "BTRFS: cannot preallocate heuristic workspace, will try later\n");
831 atomic_set(&btrfs_heuristic_ws.total_ws, 1);
832 btrfs_heuristic_ws.free_ws = 1;
833 list_add(workspace, &btrfs_heuristic_ws.idle_ws);
836 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
837 INIT_LIST_HEAD(&btrfs_comp_ws[i].idle_ws);
838 spin_lock_init(&btrfs_comp_ws[i].ws_lock);
839 atomic_set(&btrfs_comp_ws[i].total_ws, 0);
840 init_waitqueue_head(&btrfs_comp_ws[i].ws_wait);
843 * Preallocate one workspace for each compression type so
844 * we can guarantee forward progress in the worst case
846 workspace = btrfs_compress_op[i]->alloc_workspace();
847 if (IS_ERR(workspace)) {
848 pr_warn("BTRFS: cannot preallocate compression workspace, will try later\n");
850 atomic_set(&btrfs_comp_ws[i].total_ws, 1);
851 btrfs_comp_ws[i].free_ws = 1;
852 list_add(workspace, &btrfs_comp_ws[i].idle_ws);
858 * This finds an available workspace or allocates a new one.
859 * If it's not possible to allocate a new one, waits until there's one.
860 * Preallocation makes a forward progress guarantees and we do not return
863 static struct list_head *__find_workspace(int type, bool heuristic)
865 struct list_head *workspace;
866 int cpus = num_online_cpus();
869 struct list_head *idle_ws;
872 wait_queue_head_t *ws_wait;
876 idle_ws = &btrfs_heuristic_ws.idle_ws;
877 ws_lock = &btrfs_heuristic_ws.ws_lock;
878 total_ws = &btrfs_heuristic_ws.total_ws;
879 ws_wait = &btrfs_heuristic_ws.ws_wait;
880 free_ws = &btrfs_heuristic_ws.free_ws;
882 idle_ws = &btrfs_comp_ws[idx].idle_ws;
883 ws_lock = &btrfs_comp_ws[idx].ws_lock;
884 total_ws = &btrfs_comp_ws[idx].total_ws;
885 ws_wait = &btrfs_comp_ws[idx].ws_wait;
886 free_ws = &btrfs_comp_ws[idx].free_ws;
891 if (!list_empty(idle_ws)) {
892 workspace = idle_ws->next;
895 spin_unlock(ws_lock);
899 if (atomic_read(total_ws) > cpus) {
902 spin_unlock(ws_lock);
903 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
904 if (atomic_read(total_ws) > cpus && !*free_ws)
906 finish_wait(ws_wait, &wait);
909 atomic_inc(total_ws);
910 spin_unlock(ws_lock);
913 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
914 * to turn it off here because we might get called from the restricted
915 * context of btrfs_compress_bio/btrfs_compress_pages
917 nofs_flag = memalloc_nofs_save();
919 workspace = alloc_heuristic_ws();
921 workspace = btrfs_compress_op[idx]->alloc_workspace();
922 memalloc_nofs_restore(nofs_flag);
924 if (IS_ERR(workspace)) {
925 atomic_dec(total_ws);
929 * Do not return the error but go back to waiting. There's a
930 * workspace preallocated for each type and the compression
931 * time is bounded so we get to a workspace eventually. This
932 * makes our caller's life easier.
934 * To prevent silent and low-probability deadlocks (when the
935 * initial preallocation fails), check if there are any
938 if (atomic_read(total_ws) == 0) {
939 static DEFINE_RATELIMIT_STATE(_rs,
940 /* once per minute */ 60 * HZ,
943 if (__ratelimit(&_rs)) {
944 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
952 static struct list_head *find_workspace(int type)
954 return __find_workspace(type, false);
958 * put a workspace struct back on the list or free it if we have enough
959 * idle ones sitting around
961 static void __free_workspace(int type, struct list_head *workspace,
965 struct list_head *idle_ws;
968 wait_queue_head_t *ws_wait;
972 idle_ws = &btrfs_heuristic_ws.idle_ws;
973 ws_lock = &btrfs_heuristic_ws.ws_lock;
974 total_ws = &btrfs_heuristic_ws.total_ws;
975 ws_wait = &btrfs_heuristic_ws.ws_wait;
976 free_ws = &btrfs_heuristic_ws.free_ws;
978 idle_ws = &btrfs_comp_ws[idx].idle_ws;
979 ws_lock = &btrfs_comp_ws[idx].ws_lock;
980 total_ws = &btrfs_comp_ws[idx].total_ws;
981 ws_wait = &btrfs_comp_ws[idx].ws_wait;
982 free_ws = &btrfs_comp_ws[idx].free_ws;
986 if (*free_ws <= num_online_cpus()) {
987 list_add(workspace, idle_ws);
989 spin_unlock(ws_lock);
992 spin_unlock(ws_lock);
995 free_heuristic_ws(workspace);
997 btrfs_compress_op[idx]->free_workspace(workspace);
998 atomic_dec(total_ws);
1000 cond_wake_up(ws_wait);
1003 static void free_workspace(int type, struct list_head *ws)
1005 return __free_workspace(type, ws, false);
1009 * cleanup function for module exit
1011 static void free_workspaces(void)
1013 struct list_head *workspace;
1016 while (!list_empty(&btrfs_heuristic_ws.idle_ws)) {
1017 workspace = btrfs_heuristic_ws.idle_ws.next;
1018 list_del(workspace);
1019 free_heuristic_ws(workspace);
1020 atomic_dec(&btrfs_heuristic_ws.total_ws);
1023 for (i = 0; i < BTRFS_COMPRESS_TYPES; i++) {
1024 while (!list_empty(&btrfs_comp_ws[i].idle_ws)) {
1025 workspace = btrfs_comp_ws[i].idle_ws.next;
1026 list_del(workspace);
1027 btrfs_compress_op[i]->free_workspace(workspace);
1028 atomic_dec(&btrfs_comp_ws[i].total_ws);
1034 * Given an address space and start and length, compress the bytes into @pages
1035 * that are allocated on demand.
1037 * @type_level is encoded algorithm and level, where level 0 means whatever
1038 * default the algorithm chooses and is opaque here;
1039 * - compression algo are 0-3
1040 * - the level are bits 4-7
1042 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1043 * and returns number of actually allocated pages
1045 * @total_in is used to return the number of bytes actually read. It
1046 * may be smaller than the input length if we had to exit early because we
1047 * ran out of room in the pages array or because we cross the
1048 * max_out threshold.
1050 * @total_out is an in/out parameter, must be set to the input length and will
1051 * be also used to return the total number of compressed bytes
1053 * @max_out tells us the max number of bytes that we're allowed to
1056 int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
1057 u64 start, struct page **pages,
1058 unsigned long *out_pages,
1059 unsigned long *total_in,
1060 unsigned long *total_out)
1062 struct list_head *workspace;
1064 int type = type_level & 0xF;
1066 workspace = find_workspace(type);
1068 btrfs_compress_op[type - 1]->set_level(workspace, type_level);
1069 ret = btrfs_compress_op[type-1]->compress_pages(workspace, mapping,
1072 total_in, total_out);
1073 free_workspace(type, workspace);
1078 * pages_in is an array of pages with compressed data.
1080 * disk_start is the starting logical offset of this array in the file
1082 * orig_bio contains the pages from the file that we want to decompress into
1084 * srclen is the number of bytes in pages_in
1086 * The basic idea is that we have a bio that was created by readpages.
1087 * The pages in the bio are for the uncompressed data, and they may not
1088 * be contiguous. They all correspond to the range of bytes covered by
1089 * the compressed extent.
1091 static int btrfs_decompress_bio(struct compressed_bio *cb)
1093 struct list_head *workspace;
1095 int type = cb->compress_type;
1097 workspace = find_workspace(type);
1098 ret = btrfs_compress_op[type - 1]->decompress_bio(workspace, cb);
1099 free_workspace(type, workspace);
1105 * a less complex decompression routine. Our compressed data fits in a
1106 * single page, and we want to read a single page out of it.
1107 * start_byte tells us the offset into the compressed data we're interested in
1109 int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1110 unsigned long start_byte, size_t srclen, size_t destlen)
1112 struct list_head *workspace;
1115 workspace = find_workspace(type);
1117 ret = btrfs_compress_op[type-1]->decompress(workspace, data_in,
1118 dest_page, start_byte,
1121 free_workspace(type, workspace);
1125 void __cold btrfs_exit_compress(void)
1131 * Copy uncompressed data from working buffer to pages.
1133 * buf_start is the byte offset we're of the start of our workspace buffer.
1135 * total_out is the last byte of the buffer
1137 int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
1138 unsigned long total_out, u64 disk_start,
1141 unsigned long buf_offset;
1142 unsigned long current_buf_start;
1143 unsigned long start_byte;
1144 unsigned long prev_start_byte;
1145 unsigned long working_bytes = total_out - buf_start;
1146 unsigned long bytes;
1148 struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
1151 * start byte is the first byte of the page we're currently
1152 * copying into relative to the start of the compressed data.
1154 start_byte = page_offset(bvec.bv_page) - disk_start;
1156 /* we haven't yet hit data corresponding to this page */
1157 if (total_out <= start_byte)
1161 * the start of the data we care about is offset into
1162 * the middle of our working buffer
1164 if (total_out > start_byte && buf_start < start_byte) {
1165 buf_offset = start_byte - buf_start;
1166 working_bytes -= buf_offset;
1170 current_buf_start = buf_start;
1172 /* copy bytes from the working buffer into the pages */
1173 while (working_bytes > 0) {
1174 bytes = min_t(unsigned long, bvec.bv_len,
1175 PAGE_SIZE - buf_offset);
1176 bytes = min(bytes, working_bytes);
1178 kaddr = kmap_atomic(bvec.bv_page);
1179 memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
1180 kunmap_atomic(kaddr);
1181 flush_dcache_page(bvec.bv_page);
1183 buf_offset += bytes;
1184 working_bytes -= bytes;
1185 current_buf_start += bytes;
1187 /* check if we need to pick another page */
1188 bio_advance(bio, bytes);
1189 if (!bio->bi_iter.bi_size)
1191 bvec = bio_iter_iovec(bio, bio->bi_iter);
1192 prev_start_byte = start_byte;
1193 start_byte = page_offset(bvec.bv_page) - disk_start;
1196 * We need to make sure we're only adjusting
1197 * our offset into compression working buffer when
1198 * we're switching pages. Otherwise we can incorrectly
1199 * keep copying when we were actually done.
1201 if (start_byte != prev_start_byte) {
1203 * make sure our new page is covered by this
1206 if (total_out <= start_byte)
1210 * the next page in the biovec might not be adjacent
1211 * to the last page, but it might still be found
1212 * inside this working buffer. bump our offset pointer
1214 if (total_out > start_byte &&
1215 current_buf_start < start_byte) {
1216 buf_offset = start_byte - buf_start;
1217 working_bytes = total_out - start_byte;
1218 current_buf_start = buf_start + buf_offset;
1227 * Shannon Entropy calculation
1229 * Pure byte distribution analysis fails to determine compressiability of data.
1230 * Try calculating entropy to estimate the average minimum number of bits
1231 * needed to encode the sampled data.
1233 * For convenience, return the percentage of needed bits, instead of amount of
1236 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1237 * and can be compressible with high probability
1239 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1241 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1243 #define ENTROPY_LVL_ACEPTABLE (65)
1244 #define ENTROPY_LVL_HIGH (80)
1247 * For increasead precision in shannon_entropy calculation,
1248 * let's do pow(n, M) to save more digits after comma:
1250 * - maximum int bit length is 64
1251 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1252 * - 13 * 4 = 52 < 64 -> M = 4
1256 static inline u32 ilog2_w(u64 n)
1258 return ilog2(n * n * n * n);
1261 static u32 shannon_entropy(struct heuristic_ws *ws)
1263 const u32 entropy_max = 8 * ilog2_w(2);
1264 u32 entropy_sum = 0;
1265 u32 p, p_base, sz_base;
1268 sz_base = ilog2_w(ws->sample_size);
1269 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1270 p = ws->bucket[i].count;
1271 p_base = ilog2_w(p);
1272 entropy_sum += p * (sz_base - p_base);
1275 entropy_sum /= ws->sample_size;
1276 return entropy_sum * 100 / entropy_max;
1279 #define RADIX_BASE 4U
1280 #define COUNTERS_SIZE (1U << RADIX_BASE)
1282 static u8 get4bits(u64 num, int shift) {
1287 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1292 * Use 4 bits as radix base
1293 * Use 16 u32 counters for calculating new possition in buf array
1295 * @array - array that will be sorted
1296 * @array_buf - buffer array to store sorting results
1297 * must be equal in size to @array
1300 static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
1305 u32 counters[COUNTERS_SIZE];
1313 * Try avoid useless loop iterations for small numbers stored in big
1314 * counters. Example: 48 33 4 ... in 64bit array
1316 max_num = array[0].count;
1317 for (i = 1; i < num; i++) {
1318 buf_num = array[i].count;
1319 if (buf_num > max_num)
1323 buf_num = ilog2(max_num);
1324 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1327 while (shift < bitlen) {
1328 memset(counters, 0, sizeof(counters));
1330 for (i = 0; i < num; i++) {
1331 buf_num = array[i].count;
1332 addr = get4bits(buf_num, shift);
1336 for (i = 1; i < COUNTERS_SIZE; i++)
1337 counters[i] += counters[i - 1];
1339 for (i = num - 1; i >= 0; i--) {
1340 buf_num = array[i].count;
1341 addr = get4bits(buf_num, shift);
1343 new_addr = counters[addr];
1344 array_buf[new_addr] = array[i];
1347 shift += RADIX_BASE;
1350 * Normal radix expects to move data from a temporary array, to
1351 * the main one. But that requires some CPU time. Avoid that
1352 * by doing another sort iteration to original array instead of
1355 memset(counters, 0, sizeof(counters));
1357 for (i = 0; i < num; i ++) {
1358 buf_num = array_buf[i].count;
1359 addr = get4bits(buf_num, shift);
1363 for (i = 1; i < COUNTERS_SIZE; i++)
1364 counters[i] += counters[i - 1];
1366 for (i = num - 1; i >= 0; i--) {
1367 buf_num = array_buf[i].count;
1368 addr = get4bits(buf_num, shift);
1370 new_addr = counters[addr];
1371 array[new_addr] = array_buf[i];
1374 shift += RADIX_BASE;
1379 * Size of the core byte set - how many bytes cover 90% of the sample
1381 * There are several types of structured binary data that use nearly all byte
1382 * values. The distribution can be uniform and counts in all buckets will be
1383 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1385 * Other possibility is normal (Gaussian) distribution, where the data could
1386 * be potentially compressible, but we have to take a few more steps to decide
1389 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1390 * compression algo can easy fix that
1391 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1392 * probability is not compressible
1394 #define BYTE_CORE_SET_LOW (64)
1395 #define BYTE_CORE_SET_HIGH (200)
1397 static int byte_core_set_size(struct heuristic_ws *ws)
1400 u32 coreset_sum = 0;
1401 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1402 struct bucket_item *bucket = ws->bucket;
1404 /* Sort in reverse order */
1405 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
1407 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1408 coreset_sum += bucket[i].count;
1410 if (coreset_sum > core_set_threshold)
1413 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1414 coreset_sum += bucket[i].count;
1415 if (coreset_sum > core_set_threshold)
1423 * Count byte values in buckets.
1424 * This heuristic can detect textual data (configs, xml, json, html, etc).
1425 * Because in most text-like data byte set is restricted to limited number of
1426 * possible characters, and that restriction in most cases makes data easy to
1429 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1430 * less - compressible
1431 * more - need additional analysis
1433 #define BYTE_SET_THRESHOLD (64)
1435 static u32 byte_set_size(const struct heuristic_ws *ws)
1438 u32 byte_set_size = 0;
1440 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1441 if (ws->bucket[i].count > 0)
1446 * Continue collecting count of byte values in buckets. If the byte
1447 * set size is bigger then the threshold, it's pointless to continue,
1448 * the detection technique would fail for this type of data.
1450 for (; i < BUCKET_SIZE; i++) {
1451 if (ws->bucket[i].count > 0) {
1453 if (byte_set_size > BYTE_SET_THRESHOLD)
1454 return byte_set_size;
1458 return byte_set_size;
1461 static bool sample_repeated_patterns(struct heuristic_ws *ws)
1463 const u32 half_of_sample = ws->sample_size / 2;
1464 const u8 *data = ws->sample;
1466 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1469 static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1470 struct heuristic_ws *ws)
1473 u64 index, index_end;
1474 u32 i, curr_sample_pos;
1478 * Compression handles the input data by chunks of 128KiB
1479 * (defined by BTRFS_MAX_UNCOMPRESSED)
1481 * We do the same for the heuristic and loop over the whole range.
1483 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1484 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1486 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1487 end = start + BTRFS_MAX_UNCOMPRESSED;
1489 index = start >> PAGE_SHIFT;
1490 index_end = end >> PAGE_SHIFT;
1492 /* Don't miss unaligned end */
1493 if (!IS_ALIGNED(end, PAGE_SIZE))
1496 curr_sample_pos = 0;
1497 while (index < index_end) {
1498 page = find_get_page(inode->i_mapping, index);
1499 in_data = kmap(page);
1500 /* Handle case where the start is not aligned to PAGE_SIZE */
1501 i = start % PAGE_SIZE;
1502 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1503 /* Don't sample any garbage from the last page */
1504 if (start > end - SAMPLING_READ_SIZE)
1506 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1507 SAMPLING_READ_SIZE);
1508 i += SAMPLING_INTERVAL;
1509 start += SAMPLING_INTERVAL;
1510 curr_sample_pos += SAMPLING_READ_SIZE;
1518 ws->sample_size = curr_sample_pos;
1522 * Compression heuristic.
1524 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1525 * quickly (compared to direct compression) detect data characteristics
1526 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1529 * The following types of analysis can be performed:
1530 * - detect mostly zero data
1531 * - detect data with low "byte set" size (text, etc)
1532 * - detect data with low/high "core byte" set
1534 * Return non-zero if the compression should be done, 0 otherwise.
1536 int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1538 struct list_head *ws_list = __find_workspace(0, true);
1539 struct heuristic_ws *ws;
1544 ws = list_entry(ws_list, struct heuristic_ws, list);
1546 heuristic_collect_sample(inode, start, end, ws);
1548 if (sample_repeated_patterns(ws)) {
1553 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1555 for (i = 0; i < ws->sample_size; i++) {
1556 byte = ws->sample[i];
1557 ws->bucket[byte].count++;
1560 i = byte_set_size(ws);
1561 if (i < BYTE_SET_THRESHOLD) {
1566 i = byte_core_set_size(ws);
1567 if (i <= BYTE_CORE_SET_LOW) {
1572 if (i >= BYTE_CORE_SET_HIGH) {
1577 i = shannon_entropy(ws);
1578 if (i <= ENTROPY_LVL_ACEPTABLE) {
1584 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1585 * needed to give green light to compression.
1587 * For now just assume that compression at that level is not worth the
1588 * resources because:
1590 * 1. it is possible to defrag the data later
1592 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1593 * values, every bucket has counter at level ~54. The heuristic would
1594 * be confused. This can happen when data have some internal repeated
1595 * patterns like "abbacbbc...". This can be detected by analyzing
1596 * pairs of bytes, which is too costly.
1598 if (i < ENTROPY_LVL_HIGH) {
1607 __free_workspace(0, ws_list, true);
1611 unsigned int btrfs_compress_str2level(const char *str)
1613 if (strncmp(str, "zlib", 4) != 0)
1616 /* Accepted form: zlib:1 up to zlib:9 and nothing left after the number */
1617 if (str[4] == ':' && '1' <= str[5] && str[5] <= '9' && str[6] == 0)
1618 return str[5] - '0';
1620 return BTRFS_ZLIB_DEFAULT_LEVEL;