btrfs: factor out a btrfs_free_compressed_pages helper
[linux-block.git] / fs / btrfs / compression.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
c8b97818
CM
2/*
3 * Copyright (C) 2008 Oracle. All rights reserved.
c8b97818
CM
4 */
5
6#include <linux/kernel.h>
7#include <linux/bio.h>
c8b97818
CM
8#include <linux/file.h>
9#include <linux/fs.h>
10#include <linux/pagemap.h>
a75b81c3 11#include <linux/pagevec.h>
c8b97818 12#include <linux/highmem.h>
e41d12f5 13#include <linux/kthread.h>
c8b97818
CM
14#include <linux/time.h>
15#include <linux/init.h>
16#include <linux/string.h>
c8b97818 17#include <linux/backing-dev.h>
c8b97818 18#include <linux/writeback.h>
4088a47e 19#include <linux/psi.h>
5a0e3ad6 20#include <linux/slab.h>
fe308533 21#include <linux/sched/mm.h>
19562430 22#include <linux/log2.h>
d5178578 23#include <crypto/hash.h>
602cbe91 24#include "misc.h"
c8b97818 25#include "ctree.h"
ec8eb376 26#include "fs.h"
c8b97818
CM
27#include "disk-io.h"
28#include "transaction.h"
29#include "btrfs_inode.h"
103c1972 30#include "bio.h"
c8b97818 31#include "ordered-data.h"
c8b97818
CM
32#include "compression.h"
33#include "extent_io.h"
34#include "extent_map.h"
6a404910 35#include "subpage.h"
764c7c9a 36#include "zoned.h"
7c8ede16 37#include "file-item.h"
7f0add25 38#include "super.h"
c8b97818 39
544fe4a9
CH
40struct bio_set btrfs_compressed_bioset;
41
e128f9c3
DS
42static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
43
44const char* btrfs_compress_type2str(enum btrfs_compression_type type)
45{
46 switch (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];
ce96b7ff
CX
52 default:
53 break;
e128f9c3
DS
54 }
55
56 return NULL;
57}
58
544fe4a9
CH
59static inline struct compressed_bio *to_compressed_bio(struct btrfs_bio *bbio)
60{
61 return container_of(bbio, struct compressed_bio, bbio);
62}
63
64static 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)
67{
68 struct btrfs_bio *bbio;
69
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, end_io, NULL);
73 bbio->file_offset = start;
74 return to_compressed_bio(bbio);
75}
76
aa53e3bf
JT
77bool btrfs_compress_is_valid_type(const char *str, size_t len)
78{
79 int i;
80
81 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
82 size_t comp_len = strlen(btrfs_compress_types[i]);
83
84 if (len < comp_len)
85 continue;
86
87 if (!strncmp(btrfs_compress_types[i], str, comp_len))
88 return true;
89 }
90 return false;
91}
92
1e4eb746
DS
93static int compression_compress_pages(int type, struct list_head *ws,
94 struct address_space *mapping, u64 start, struct page **pages,
95 unsigned long *out_pages, unsigned long *total_in,
96 unsigned long *total_out)
97{
98 switch (type) {
99 case BTRFS_COMPRESS_ZLIB:
100 return zlib_compress_pages(ws, mapping, start, pages,
101 out_pages, total_in, total_out);
102 case BTRFS_COMPRESS_LZO:
103 return lzo_compress_pages(ws, mapping, start, pages,
104 out_pages, total_in, total_out);
105 case BTRFS_COMPRESS_ZSTD:
106 return zstd_compress_pages(ws, mapping, start, pages,
107 out_pages, total_in, total_out);
108 case BTRFS_COMPRESS_NONE:
109 default:
110 /*
1d8ba9e7
QW
111 * This can happen when compression races with remount setting
112 * it to 'no compress', while caller doesn't call
113 * inode_need_compress() to check if we really need to
114 * compress.
115 *
116 * Not a big deal, just need to inform caller that we
117 * haven't allocated any pages yet.
1e4eb746 118 */
1d8ba9e7 119 *out_pages = 0;
1e4eb746
DS
120 return -E2BIG;
121 }
122}
123
4a9e803e
SY
124static int compression_decompress_bio(struct list_head *ws,
125 struct compressed_bio *cb)
1e4eb746 126{
4a9e803e 127 switch (cb->compress_type) {
1e4eb746
DS
128 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
129 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
130 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
131 case BTRFS_COMPRESS_NONE:
132 default:
133 /*
134 * This can't happen, the type is validated several times
135 * before we get here.
136 */
137 BUG();
138 }
139}
140
141static int compression_decompress(int type, struct list_head *ws,
3e09b5b2 142 const u8 *data_in, struct page *dest_page,
1e4eb746
DS
143 unsigned long start_byte, size_t srclen, size_t destlen)
144{
145 switch (type) {
146 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
147 start_byte, srclen, destlen);
148 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
149 start_byte, srclen, destlen);
150 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
151 start_byte, srclen, destlen);
152 case BTRFS_COMPRESS_NONE:
153 default:
154 /*
155 * This can't happen, the type is validated several times
156 * before we get here.
157 */
158 BUG();
159 }
160}
161
32586c5b
CH
162static void btrfs_free_compressed_pages(struct compressed_bio *cb)
163{
164 for (unsigned int i = 0; i < cb->nr_pages; i++) {
165 struct page *page = cb->compressed_pages[i];
166
167 page->mapping = NULL;
168 put_page(page);
169 }
170 kfree(cb->compressed_pages);
171}
172
8140dc30 173static int btrfs_decompress_bio(struct compressed_bio *cb);
48a3b636 174
30493ff4 175static void end_compressed_bio_read(struct btrfs_bio *bbio)
86ccbb4d 176{
544fe4a9
CH
177 struct compressed_bio *cb = to_compressed_bio(bbio);
178 blk_status_t status = bbio->bio.bi_status;
86ccbb4d 179
544fe4a9
CH
180 if (!status)
181 status = errno_to_blk_status(btrfs_decompress_bio(cb));
81bd9328 182
32586c5b 183 btrfs_free_compressed_pages(cb);
544fe4a9 184 btrfs_bio_end_io(btrfs_bio(cb->orig_bio), status);
917f32a2 185 bio_put(&bbio->bio);
c8b97818
CM
186}
187
188/*
189 * Clear the writeback bits on all of the file
190 * pages for a compressed write
191 */
544fe4a9 192static noinline void end_compressed_writeback(const struct compressed_bio *cb)
c8b97818 193{
544fe4a9 194 struct inode *inode = &cb->bbio.inode->vfs_inode;
741ec653 195 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
09cbfeaf
KS
196 unsigned long index = cb->start >> PAGE_SHIFT;
197 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
a75b81c3 198 struct folio_batch fbatch;
544fe4a9 199 const int errno = blk_status_to_errno(cb->bbio.bio.bi_status);
c8b97818
CM
200 int i;
201 int ret;
202
606f82e7
JB
203 if (errno)
204 mapping_set_error(inode->i_mapping, errno);
7bdcefc1 205
a75b81c3
VMO
206 folio_batch_init(&fbatch);
207 while (index <= end_index) {
208 ret = filemap_get_folios(inode->i_mapping, &index, end_index,
209 &fbatch);
210
211 if (ret == 0)
212 return;
213
c8b97818 214 for (i = 0; i < ret; i++) {
a75b81c3
VMO
215 struct folio *folio = fbatch.folios[i];
216
606f82e7 217 if (errno)
a75b81c3
VMO
218 folio_set_error(folio);
219 btrfs_page_clamp_clear_writeback(fs_info, &folio->page,
741ec653 220 cb->start, cb->len);
c8b97818 221 }
a75b81c3 222 folio_batch_release(&fbatch);
c8b97818
CM
223 }
224 /* the inode may be gone now */
c8b97818
CM
225}
226
6853c64a 227static void finish_compressed_bio_write(struct compressed_bio *cb)
c8b97818 228{
6853c64a
QW
229 /*
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.
c8b97818 232 */
544fe4a9 233 btrfs_writepage_endio_finish_ordered(cb->bbio.inode, NULL,
c629732d 234 cb->start, cb->start + cb->len - 1,
544fe4a9 235 cb->bbio.bio.bi_status == BLK_STS_OK);
c8b97818 236
7c0c7269 237 if (cb->writeback)
544fe4a9 238 end_compressed_writeback(cb);
6853c64a 239 /* Note, our inode could be gone now */
c8b97818 240
32586c5b 241 btrfs_free_compressed_pages(cb);
544fe4a9 242 bio_put(&cb->bbio.bio);
6853c64a
QW
243}
244
fed8a72d
CH
245static void btrfs_finish_compressed_write_work(struct work_struct *work)
246{
247 struct compressed_bio *cb =
248 container_of(work, struct compressed_bio, write_end_work);
249
250 finish_compressed_bio_write(cb);
251}
252
6853c64a
QW
253/*
254 * Do the cleanup once all the compressed pages hit the disk. This will clear
255 * writeback on the file pages and free the compressed pages.
256 *
257 * This also calls the writeback end hooks for the file pages so that metadata
258 * and checksums can be updated in the file.
259 */
917f32a2 260static void end_compressed_bio_write(struct btrfs_bio *bbio)
6853c64a 261{
544fe4a9
CH
262 struct compressed_bio *cb = to_compressed_bio(bbio);
263 struct btrfs_fs_info *fs_info = bbio->inode->root->fs_info;
6853c64a 264
d5e4377d 265 queue_work(fs_info->compressed_write_workers, &cb->write_end_work);
c8b97818
CM
266}
267
10e924bc
CH
268static void btrfs_add_compressed_bio_pages(struct compressed_bio *cb,
269 u64 disk_bytenr)
270{
271 struct btrfs_fs_info *fs_info = cb->bbio.inode->root->fs_info;
272 struct bio *bio = &cb->bbio.bio;
273 u64 cur_disk_byte = disk_bytenr;
274
275 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
276 while (cur_disk_byte < disk_bytenr + cb->compressed_len) {
277 u64 offset = cur_disk_byte - disk_bytenr;
278 unsigned int index = offset >> PAGE_SHIFT;
279 unsigned int real_size;
280 unsigned int added;
281 struct page *page = cb->compressed_pages[index];
282
283 /*
284 * We have various limit on the real read size:
285 * - page boundary
286 * - compressed length boundary
287 */
288 real_size = min_t(u64, U32_MAX, PAGE_SIZE - offset_in_page(offset));
289 real_size = min_t(u64, real_size, cb->compressed_len - offset);
290 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
291
292 added = bio_add_page(bio, page, real_size, offset_in_page(offset));
293 /*
294 * Maximum compressed extent is smaller than bio size limit,
295 * thus bio_add_page() should always success.
296 */
297 ASSERT(added == real_size);
298 cur_disk_byte += added;
299 }
300
301 ASSERT(bio->bi_iter.bi_size);
302}
303
c8b97818
CM
304/*
305 * worker function to build and submit bios for previously compressed pages.
306 * The corresponding pages in the inode should be marked for writeback
307 * and the compressed pages should have a reference on them for dropping
308 * when the IO is complete.
309 *
310 * This also checksums the file bytes and gets things ready for
311 * the end io hooks.
312 */
544fe4a9 313void btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
65b5355f
AJ
314 unsigned int len, u64 disk_start,
315 unsigned int compressed_len,
c8b97818 316 struct page **compressed_pages,
65b5355f 317 unsigned int nr_pages,
bf9486d6 318 blk_opf_t write_flags,
7c0c7269
OS
319 struct cgroup_subsys_state *blkcg_css,
320 bool writeback)
c8b97818 321{
c7ee1819 322 struct btrfs_fs_info *fs_info = inode->root->fs_info;
c8b97818 323 struct compressed_bio *cb;
c8b97818 324
bbbff01a
QW
325 ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
326 IS_ALIGNED(len, fs_info->sectorsize));
544fe4a9
CH
327
328 if (blkcg_css) {
329 kthread_associate_blkcg(blkcg_css);
330 write_flags |= REQ_CGROUP_PUNT;
331 }
332 write_flags |= REQ_BTRFS_ONE_ORDERED;
333
334 cb = alloc_compressed_bio(inode, start, REQ_OP_WRITE | write_flags,
335 end_compressed_bio_write);
c8b97818
CM
336 cb->start = start;
337 cb->len = len;
338 cb->compressed_pages = compressed_pages;
339 cb->compressed_len = compressed_len;
7c0c7269 340 cb->writeback = writeback;
fed8a72d 341 INIT_WORK(&cb->write_end_work, btrfs_finish_compressed_write_work);
c8b97818
CM
342 cb->nr_pages = nr_pages;
343
10e924bc
CH
344 btrfs_add_compressed_bio_pages(cb, disk_start);
345 btrfs_submit_bio(&cb->bbio.bio, 0);
d20f7043 346
acee08aa
DZ
347 if (blkcg_css)
348 kthread_associate_blkcg(NULL);
c8b97818
CM
349}
350
6a404910
QW
351/*
352 * Add extra pages in the same compressed file extent so that we don't need to
353 * re-read the same extent again and again.
354 *
355 * NOTE: this won't work well for subpage, as for subpage read, we lock the
356 * full page then submit bio for each compressed/regular extents.
357 *
358 * This means, if we have several sectors in the same page points to the same
359 * on-disk compressed data, we will re-read the same extent many times and
360 * this function can only help for the next page.
361 */
771ed689
CM
362static noinline int add_ra_bio_pages(struct inode *inode,
363 u64 compressed_end,
4088a47e 364 struct compressed_bio *cb,
82e60d00 365 int *memstall, unsigned long *pflags)
771ed689 366{
6a404910 367 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
771ed689 368 unsigned long end_index;
d7294e4d 369 u64 cur = btrfs_bio(cb->orig_bio)->file_offset + cb->orig_bio->bi_iter.bi_size;
771ed689
CM
370 u64 isize = i_size_read(inode);
371 int ret;
372 struct page *page;
771ed689
CM
373 struct extent_map *em;
374 struct address_space *mapping = inode->i_mapping;
771ed689
CM
375 struct extent_map_tree *em_tree;
376 struct extent_io_tree *tree;
6a404910 377 int sectors_missed = 0;
771ed689 378
771ed689
CM
379 em_tree = &BTRFS_I(inode)->extent_tree;
380 tree = &BTRFS_I(inode)->io_tree;
381
382 if (isize == 0)
383 return 0;
384
ca62e85d
QW
385 /*
386 * For current subpage support, we only support 64K page size,
387 * which means maximum compressed extent size (128K) is just 2x page
388 * size.
389 * This makes readahead less effective, so here disable readahead for
390 * subpage for now, until full compressed write is supported.
391 */
392 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
393 return 0;
394
09cbfeaf 395 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
771ed689 396
6a404910
QW
397 while (cur < compressed_end) {
398 u64 page_end;
399 u64 pg_index = cur >> PAGE_SHIFT;
400 u32 add_size;
771ed689 401
306e16ce 402 if (pg_index > end_index)
771ed689
CM
403 break;
404
0a943c65 405 page = xa_load(&mapping->i_pages, pg_index);
3159f943 406 if (page && !xa_is_value(page)) {
6a404910
QW
407 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
408 fs_info->sectorsize_bits;
409
410 /* Beyond threshold, no need to continue */
411 if (sectors_missed > 4)
771ed689 412 break;
6a404910
QW
413
414 /*
415 * Jump to next page start as we already have page for
416 * current offset.
417 */
418 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
419 continue;
771ed689
CM
420 }
421
c62d2555
MH
422 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
423 ~__GFP_FS));
771ed689
CM
424 if (!page)
425 break;
426
c62d2555 427 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
09cbfeaf 428 put_page(page);
6a404910
QW
429 /* There is already a page, skip to page end */
430 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
431 continue;
771ed689
CM
432 }
433
82e60d00 434 if (!*memstall && PageWorkingset(page)) {
4088a47e 435 psi_memstall_enter(pflags);
82e60d00
JW
436 *memstall = 1;
437 }
4088a47e 438
32443de3
QW
439 ret = set_page_extent_mapped(page);
440 if (ret < 0) {
441 unlock_page(page);
442 put_page(page);
443 break;
444 }
445
6a404910 446 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
570eb97b 447 lock_extent(tree, cur, page_end, NULL);
890871be 448 read_lock(&em_tree->lock);
6a404910 449 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
890871be 450 read_unlock(&em_tree->lock);
771ed689 451
6a404910
QW
452 /*
453 * At this point, we have a locked page in the page cache for
454 * these bytes in the file. But, we have to make sure they map
455 * to this compressed extent on disk.
456 */
457 if (!em || cur < em->start ||
458 (cur + fs_info->sectorsize > extent_map_end(em)) ||
4f024f37 459 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
771ed689 460 free_extent_map(em);
570eb97b 461 unlock_extent(tree, cur, page_end, NULL);
771ed689 462 unlock_page(page);
09cbfeaf 463 put_page(page);
771ed689
CM
464 break;
465 }
466 free_extent_map(em);
467
468 if (page->index == end_index) {
7073017a 469 size_t zero_offset = offset_in_page(isize);
771ed689
CM
470
471 if (zero_offset) {
472 int zeros;
09cbfeaf 473 zeros = PAGE_SIZE - zero_offset;
d048b9c2 474 memzero_page(page, zero_offset, zeros);
771ed689
CM
475 }
476 }
477
6a404910
QW
478 add_size = min(em->start + em->len, page_end + 1) - cur;
479 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
480 if (ret != add_size) {
570eb97b 481 unlock_extent(tree, cur, page_end, NULL);
771ed689 482 unlock_page(page);
09cbfeaf 483 put_page(page);
771ed689
CM
484 break;
485 }
6a404910
QW
486 /*
487 * If it's subpage, we also need to increase its
488 * subpage::readers number, as at endio we will decrease
489 * subpage::readers and to unlock the page.
490 */
491 if (fs_info->sectorsize < PAGE_SIZE)
492 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
493 put_page(page);
494 cur += add_size;
771ed689 495 }
771ed689
CM
496 return 0;
497}
498
c8b97818
CM
499/*
500 * for a compressed read, the bio we get passed has all the inode pages
501 * in it. We don't actually do IO on those pages but allocate new ones
502 * to hold the compressed pages on disk.
503 *
4f024f37 504 * bio->bi_iter.bi_sector points to the compressed extent on disk
c8b97818 505 * bio->bi_io_vec points to all of the inode pages
c8b97818
CM
506 *
507 * After the compressed pages are read, we copy the bytes into the
508 * bio we were passed and then call the bio end_io calls
509 */
544fe4a9 510void btrfs_submit_compressed_read(struct bio *bio, int mirror_num)
c8b97818 511{
544fe4a9
CH
512 struct btrfs_inode *inode = btrfs_bio(bio)->inode;
513 struct btrfs_fs_info *fs_info = inode->root->fs_info;
514 struct extent_map_tree *em_tree = &inode->extent_tree;
c8b97818 515 struct compressed_bio *cb;
356b4a2d 516 unsigned int compressed_len;
f472c28f 517 const u64 disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
e7aff33e 518 u64 file_offset = btrfs_bio(bio)->file_offset;
e04ca626
CM
519 u64 em_len;
520 u64 em_start;
c8b97818 521 struct extent_map *em;
82e60d00
JW
522 unsigned long pflags;
523 int memstall = 0;
f9f15de8 524 blk_status_t ret;
dd137dd1 525 int ret2;
c8b97818
CM
526
527 /* we need the actual starting offset of this extent in the file */
890871be 528 read_lock(&em_tree->lock);
557023ea 529 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
890871be 530 read_unlock(&em_tree->lock);
f9f15de8
JB
531 if (!em) {
532 ret = BLK_STS_IOERR;
533 goto out;
534 }
c8b97818 535
557023ea 536 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
d20f7043 537 compressed_len = em->block_len;
6b82ce8d 538
544fe4a9
CH
539 cb = alloc_compressed_bio(inode, file_offset, REQ_OP_READ,
540 end_compressed_bio_read);
c8b97818 541
ff5b7ee3 542 cb->start = em->orig_start;
e04ca626
CM
543 em_len = em->len;
544 em_start = em->start;
d20f7043 545
81381053 546 cb->len = bio->bi_iter.bi_size;
c8b97818 547 cb->compressed_len = compressed_len;
1d8fa2e2 548 cb->compress_type = em->compress_type;
c8b97818
CM
549 cb->orig_bio = bio;
550
1d8fa2e2 551 free_extent_map(em);
1d8fa2e2 552
dd137dd1
STD
553 cb->nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
554 cb->compressed_pages = kcalloc(cb->nr_pages, sizeof(struct page *), GFP_NOFS);
f9f15de8
JB
555 if (!cb->compressed_pages) {
556 ret = BLK_STS_RESOURCE;
544fe4a9 557 goto out_free_bio;
f9f15de8 558 }
6b82ce8d 559
dd137dd1
STD
560 ret2 = btrfs_alloc_page_array(cb->nr_pages, cb->compressed_pages);
561 if (ret2) {
562 ret = BLK_STS_RESOURCE;
544fe4a9 563 goto out_free_compressed_pages;
c8b97818 564 }
c8b97818 565
544fe4a9
CH
566 add_ra_bio_pages(&inode->vfs_inode, em_start + em_len, cb, &memstall,
567 &pflags);
771ed689 568
771ed689 569 /* include any pages we added in add_ra-bio_pages */
81381053 570 cb->len = bio->bi_iter.bi_size;
771ed689 571
10e924bc 572 btrfs_add_compressed_bio_pages(cb, disk_bytenr);
524bcd1e 573
82e60d00 574 if (memstall)
4088a47e
CH
575 psi_memstall_leave(&pflags);
576
10e924bc 577 btrfs_submit_bio(&cb->bbio.bio, mirror_num);
cb4411dd 578 return;
6b82ce8d 579
544fe4a9 580out_free_compressed_pages:
6b82ce8d 581 kfree(cb->compressed_pages);
544fe4a9 582out_free_bio:
10e924bc 583 bio_put(&cb->bbio.bio);
544fe4a9 584out:
917f32a2 585 btrfs_bio_end_io(btrfs_bio(bio), ret);
c8b97818 586}
261507a0 587
17b5a6c1
TT
588/*
589 * Heuristic uses systematic sampling to collect data from the input data
590 * range, the logic can be tuned by the following constants:
591 *
592 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
593 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
594 */
595#define SAMPLING_READ_SIZE (16)
596#define SAMPLING_INTERVAL (256)
597
598/*
599 * For statistical analysis of the input data we consider bytes that form a
600 * Galois Field of 256 objects. Each object has an attribute count, ie. how
601 * many times the object appeared in the sample.
602 */
603#define BUCKET_SIZE (256)
604
605/*
606 * The size of the sample is based on a statistical sampling rule of thumb.
607 * The common way is to perform sampling tests as long as the number of
608 * elements in each cell is at least 5.
609 *
610 * Instead of 5, we choose 32 to obtain more accurate results.
611 * If the data contain the maximum number of symbols, which is 256, we obtain a
612 * sample size bound by 8192.
613 *
614 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
615 * from up to 512 locations.
616 */
617#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
618 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
619
620struct bucket_item {
621 u32 count;
622};
4e439a0b
TT
623
624struct heuristic_ws {
17b5a6c1
TT
625 /* Partial copy of input data */
626 u8 *sample;
a440d48c 627 u32 sample_size;
17b5a6c1
TT
628 /* Buckets store counters for each byte value */
629 struct bucket_item *bucket;
440c840c
TT
630 /* Sorting buffer */
631 struct bucket_item *bucket_b;
4e439a0b
TT
632 struct list_head list;
633};
634
92ee5530
DZ
635static struct workspace_manager heuristic_wsm;
636
4e439a0b
TT
637static void free_heuristic_ws(struct list_head *ws)
638{
639 struct heuristic_ws *workspace;
640
641 workspace = list_entry(ws, struct heuristic_ws, list);
642
17b5a6c1
TT
643 kvfree(workspace->sample);
644 kfree(workspace->bucket);
440c840c 645 kfree(workspace->bucket_b);
4e439a0b
TT
646 kfree(workspace);
647}
648
7bf49943 649static struct list_head *alloc_heuristic_ws(unsigned int level)
4e439a0b
TT
650{
651 struct heuristic_ws *ws;
652
653 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
654 if (!ws)
655 return ERR_PTR(-ENOMEM);
656
17b5a6c1
TT
657 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
658 if (!ws->sample)
659 goto fail;
660
661 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
662 if (!ws->bucket)
663 goto fail;
4e439a0b 664
440c840c
TT
665 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
666 if (!ws->bucket_b)
667 goto fail;
668
17b5a6c1 669 INIT_LIST_HEAD(&ws->list);
4e439a0b 670 return &ws->list;
17b5a6c1
TT
671fail:
672 free_heuristic_ws(&ws->list);
673 return ERR_PTR(-ENOMEM);
4e439a0b
TT
674}
675
ca4ac360 676const struct btrfs_compress_op btrfs_heuristic_compress = {
be951045 677 .workspace_manager = &heuristic_wsm,
ca4ac360
DZ
678};
679
e8c9f186 680static const struct btrfs_compress_op * const btrfs_compress_op[] = {
ca4ac360
DZ
681 /* The heuristic is represented as compression type 0 */
682 &btrfs_heuristic_compress,
261507a0 683 &btrfs_zlib_compress,
a6fa6fae 684 &btrfs_lzo_compress,
5c1aab1d 685 &btrfs_zstd_compress,
261507a0
LZ
686};
687
c778df14
DS
688static struct list_head *alloc_workspace(int type, unsigned int level)
689{
690 switch (type) {
691 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
692 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
693 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
694 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
695 default:
696 /*
697 * This can't happen, the type is validated several times
698 * before we get here.
699 */
700 BUG();
701 }
702}
703
1e002351
DS
704static void free_workspace(int type, struct list_head *ws)
705{
706 switch (type) {
707 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
708 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
709 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
710 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
711 default:
712 /*
713 * This can't happen, the type is validated several times
714 * before we get here.
715 */
716 BUG();
717 }
718}
719
d5517033 720static void btrfs_init_workspace_manager(int type)
261507a0 721{
0cf25213 722 struct workspace_manager *wsm;
4e439a0b 723 struct list_head *workspace;
261507a0 724
0cf25213 725 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
726 INIT_LIST_HEAD(&wsm->idle_ws);
727 spin_lock_init(&wsm->ws_lock);
728 atomic_set(&wsm->total_ws, 0);
729 init_waitqueue_head(&wsm->ws_wait);
f77dd0d6 730
1666edab
DZ
731 /*
732 * Preallocate one workspace for each compression type so we can
733 * guarantee forward progress in the worst case
734 */
c778df14 735 workspace = alloc_workspace(type, 0);
1666edab
DZ
736 if (IS_ERR(workspace)) {
737 pr_warn(
738 "BTRFS: cannot preallocate compression workspace, will try later\n");
739 } else {
92ee5530
DZ
740 atomic_set(&wsm->total_ws, 1);
741 wsm->free_ws = 1;
742 list_add(workspace, &wsm->idle_ws);
1666edab
DZ
743 }
744}
745
2510307e 746static void btrfs_cleanup_workspace_manager(int type)
1666edab 747{
2dba7143 748 struct workspace_manager *wsman;
1666edab
DZ
749 struct list_head *ws;
750
2dba7143 751 wsman = btrfs_compress_op[type]->workspace_manager;
1666edab
DZ
752 while (!list_empty(&wsman->idle_ws)) {
753 ws = wsman->idle_ws.next;
754 list_del(ws);
1e002351 755 free_workspace(type, ws);
1666edab 756 atomic_dec(&wsman->total_ws);
261507a0 757 }
261507a0
LZ
758}
759
760/*
e721e49d
DS
761 * This finds an available workspace or allocates a new one.
762 * If it's not possible to allocate a new one, waits until there's one.
763 * Preallocation makes a forward progress guarantees and we do not return
764 * errors.
261507a0 765 */
5907a9bb 766struct list_head *btrfs_get_workspace(int type, unsigned int level)
261507a0 767{
5907a9bb 768 struct workspace_manager *wsm;
261507a0
LZ
769 struct list_head *workspace;
770 int cpus = num_online_cpus();
fe308533 771 unsigned nofs_flag;
4e439a0b
TT
772 struct list_head *idle_ws;
773 spinlock_t *ws_lock;
774 atomic_t *total_ws;
775 wait_queue_head_t *ws_wait;
776 int *free_ws;
777
5907a9bb 778 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
779 idle_ws = &wsm->idle_ws;
780 ws_lock = &wsm->ws_lock;
781 total_ws = &wsm->total_ws;
782 ws_wait = &wsm->ws_wait;
783 free_ws = &wsm->free_ws;
261507a0 784
261507a0 785again:
d9187649
BL
786 spin_lock(ws_lock);
787 if (!list_empty(idle_ws)) {
788 workspace = idle_ws->next;
261507a0 789 list_del(workspace);
6ac10a6a 790 (*free_ws)--;
d9187649 791 spin_unlock(ws_lock);
261507a0
LZ
792 return workspace;
793
794 }
6ac10a6a 795 if (atomic_read(total_ws) > cpus) {
261507a0
LZ
796 DEFINE_WAIT(wait);
797
d9187649
BL
798 spin_unlock(ws_lock);
799 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
6ac10a6a 800 if (atomic_read(total_ws) > cpus && !*free_ws)
261507a0 801 schedule();
d9187649 802 finish_wait(ws_wait, &wait);
261507a0
LZ
803 goto again;
804 }
6ac10a6a 805 atomic_inc(total_ws);
d9187649 806 spin_unlock(ws_lock);
261507a0 807
fe308533
DS
808 /*
809 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
810 * to turn it off here because we might get called from the restricted
811 * context of btrfs_compress_bio/btrfs_compress_pages
812 */
813 nofs_flag = memalloc_nofs_save();
c778df14 814 workspace = alloc_workspace(type, level);
fe308533
DS
815 memalloc_nofs_restore(nofs_flag);
816
261507a0 817 if (IS_ERR(workspace)) {
6ac10a6a 818 atomic_dec(total_ws);
d9187649 819 wake_up(ws_wait);
e721e49d
DS
820
821 /*
822 * Do not return the error but go back to waiting. There's a
823 * workspace preallocated for each type and the compression
824 * time is bounded so we get to a workspace eventually. This
825 * makes our caller's life easier.
52356716
DS
826 *
827 * To prevent silent and low-probability deadlocks (when the
828 * initial preallocation fails), check if there are any
829 * workspaces at all.
e721e49d 830 */
52356716
DS
831 if (atomic_read(total_ws) == 0) {
832 static DEFINE_RATELIMIT_STATE(_rs,
833 /* once per minute */ 60 * HZ,
834 /* no burst */ 1);
835
836 if (__ratelimit(&_rs)) {
ab8d0fc4 837 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
52356716
DS
838 }
839 }
e721e49d 840 goto again;
261507a0
LZ
841 }
842 return workspace;
843}
844
7bf49943 845static struct list_head *get_workspace(int type, int level)
929f4baf 846{
6a0d1272 847 switch (type) {
5907a9bb 848 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
6a0d1272 849 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
5907a9bb 850 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
6a0d1272
DS
851 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
852 default:
853 /*
854 * This can't happen, the type is validated several times
855 * before we get here.
856 */
857 BUG();
858 }
929f4baf
DZ
859}
860
261507a0
LZ
861/*
862 * put a workspace struct back on the list or free it if we have enough
863 * idle ones sitting around
864 */
a3bbd2a9 865void btrfs_put_workspace(int type, struct list_head *ws)
261507a0 866{
a3bbd2a9 867 struct workspace_manager *wsm;
4e439a0b
TT
868 struct list_head *idle_ws;
869 spinlock_t *ws_lock;
870 atomic_t *total_ws;
871 wait_queue_head_t *ws_wait;
872 int *free_ws;
873
a3bbd2a9 874 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
875 idle_ws = &wsm->idle_ws;
876 ws_lock = &wsm->ws_lock;
877 total_ws = &wsm->total_ws;
878 ws_wait = &wsm->ws_wait;
879 free_ws = &wsm->free_ws;
d9187649
BL
880
881 spin_lock(ws_lock);
26b28dce 882 if (*free_ws <= num_online_cpus()) {
929f4baf 883 list_add(ws, idle_ws);
6ac10a6a 884 (*free_ws)++;
d9187649 885 spin_unlock(ws_lock);
261507a0
LZ
886 goto wake;
887 }
d9187649 888 spin_unlock(ws_lock);
261507a0 889
1e002351 890 free_workspace(type, ws);
6ac10a6a 891 atomic_dec(total_ws);
261507a0 892wake:
093258e6 893 cond_wake_up(ws_wait);
261507a0
LZ
894}
895
929f4baf
DZ
896static void put_workspace(int type, struct list_head *ws)
897{
bd3a5287 898 switch (type) {
a3bbd2a9
DS
899 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
900 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
901 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
bd3a5287
DS
902 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
903 default:
904 /*
905 * This can't happen, the type is validated several times
906 * before we get here.
907 */
908 BUG();
909 }
929f4baf
DZ
910}
911
adbab642
AJ
912/*
913 * Adjust @level according to the limits of the compression algorithm or
914 * fallback to default
915 */
916static unsigned int btrfs_compress_set_level(int type, unsigned level)
917{
918 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
919
920 if (level == 0)
921 level = ops->default_level;
922 else
923 level = min(level, ops->max_level);
924
925 return level;
926}
927
261507a0 928/*
38c31464
DS
929 * Given an address space and start and length, compress the bytes into @pages
930 * that are allocated on demand.
261507a0 931 *
f51d2b59
DS
932 * @type_level is encoded algorithm and level, where level 0 means whatever
933 * default the algorithm chooses and is opaque here;
934 * - compression algo are 0-3
935 * - the level are bits 4-7
936 *
4d3a800e
DS
937 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
938 * and returns number of actually allocated pages
261507a0 939 *
38c31464
DS
940 * @total_in is used to return the number of bytes actually read. It
941 * may be smaller than the input length if we had to exit early because we
261507a0
LZ
942 * ran out of room in the pages array or because we cross the
943 * max_out threshold.
944 *
38c31464
DS
945 * @total_out is an in/out parameter, must be set to the input length and will
946 * be also used to return the total number of compressed bytes
261507a0 947 */
f51d2b59 948int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
38c31464 949 u64 start, struct page **pages,
261507a0
LZ
950 unsigned long *out_pages,
951 unsigned long *total_in,
e5d74902 952 unsigned long *total_out)
261507a0 953{
1972708a 954 int type = btrfs_compress_type(type_level);
7bf49943 955 int level = btrfs_compress_level(type_level);
261507a0
LZ
956 struct list_head *workspace;
957 int ret;
958
b0c1fe1e 959 level = btrfs_compress_set_level(type, level);
7bf49943 960 workspace = get_workspace(type, level);
1e4eb746
DS
961 ret = compression_compress_pages(type, workspace, mapping, start, pages,
962 out_pages, total_in, total_out);
929f4baf 963 put_workspace(type, workspace);
261507a0
LZ
964 return ret;
965}
966
8140dc30 967static int btrfs_decompress_bio(struct compressed_bio *cb)
261507a0
LZ
968{
969 struct list_head *workspace;
970 int ret;
8140dc30 971 int type = cb->compress_type;
261507a0 972
7bf49943 973 workspace = get_workspace(type, 0);
4a9e803e 974 ret = compression_decompress_bio(workspace, cb);
929f4baf 975 put_workspace(type, workspace);
e1ddce71 976
261507a0
LZ
977 return ret;
978}
979
980/*
981 * a less complex decompression routine. Our compressed data fits in a
982 * single page, and we want to read a single page out of it.
983 * start_byte tells us the offset into the compressed data we're interested in
984 */
3e09b5b2 985int btrfs_decompress(int type, const u8 *data_in, struct page *dest_page,
261507a0
LZ
986 unsigned long start_byte, size_t srclen, size_t destlen)
987{
988 struct list_head *workspace;
989 int ret;
990
7bf49943 991 workspace = get_workspace(type, 0);
1e4eb746
DS
992 ret = compression_decompress(type, workspace, data_in, dest_page,
993 start_byte, srclen, destlen);
929f4baf 994 put_workspace(type, workspace);
7bf49943 995
261507a0
LZ
996 return ret;
997}
998
5565b8e0 999int __init btrfs_init_compress(void)
1666edab 1000{
544fe4a9
CH
1001 if (bioset_init(&btrfs_compressed_bioset, BIO_POOL_SIZE,
1002 offsetof(struct compressed_bio, bbio.bio),
1003 BIOSET_NEED_BVECS))
1004 return -ENOMEM;
d5517033
DS
1005 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1006 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1007 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1008 zstd_init_workspace_manager();
5565b8e0 1009 return 0;
1666edab
DZ
1010}
1011
e67c718b 1012void __cold btrfs_exit_compress(void)
261507a0 1013{
2510307e
DS
1014 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1015 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1016 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1017 zstd_cleanup_workspace_manager();
544fe4a9 1018 bioset_exit(&btrfs_compressed_bioset);
261507a0 1019}
3a39c18d
LZ
1020
1021/*
1c3dc173 1022 * Copy decompressed data from working buffer to pages.
3a39c18d 1023 *
1c3dc173
QW
1024 * @buf: The decompressed data buffer
1025 * @buf_len: The decompressed data length
1026 * @decompressed: Number of bytes that are already decompressed inside the
1027 * compressed extent
1028 * @cb: The compressed extent descriptor
1029 * @orig_bio: The original bio that the caller wants to read for
3a39c18d 1030 *
1c3dc173
QW
1031 * An easier to understand graph is like below:
1032 *
1033 * |<- orig_bio ->| |<- orig_bio->|
1034 * |<------- full decompressed extent ----->|
1035 * |<----------- @cb range ---->|
1036 * | |<-- @buf_len -->|
1037 * |<--- @decompressed --->|
1038 *
1039 * Note that, @cb can be a subpage of the full decompressed extent, but
1040 * @cb->start always has the same as the orig_file_offset value of the full
1041 * decompressed extent.
1042 *
1043 * When reading compressed extent, we have to read the full compressed extent,
1044 * while @orig_bio may only want part of the range.
1045 * Thus this function will ensure only data covered by @orig_bio will be copied
1046 * to.
1047 *
1048 * Return 0 if we have copied all needed contents for @orig_bio.
1049 * Return >0 if we need continue decompress.
3a39c18d 1050 */
1c3dc173
QW
1051int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1052 struct compressed_bio *cb, u32 decompressed)
3a39c18d 1053{
1c3dc173
QW
1054 struct bio *orig_bio = cb->orig_bio;
1055 /* Offset inside the full decompressed extent */
1056 u32 cur_offset;
1057
1058 cur_offset = decompressed;
1059 /* The main loop to do the copy */
1060 while (cur_offset < decompressed + buf_len) {
1061 struct bio_vec bvec;
1062 size_t copy_len;
1063 u32 copy_start;
1064 /* Offset inside the full decompressed extent */
1065 u32 bvec_offset;
1066
1067 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1068 /*
1069 * cb->start may underflow, but subtracting that value can still
1070 * give us correct offset inside the full decompressed extent.
1071 */
1072 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
974b1adc 1073
1c3dc173
QW
1074 /* Haven't reached the bvec range, exit */
1075 if (decompressed + buf_len <= bvec_offset)
1076 return 1;
3a39c18d 1077
1c3dc173
QW
1078 copy_start = max(cur_offset, bvec_offset);
1079 copy_len = min(bvec_offset + bvec.bv_len,
1080 decompressed + buf_len) - copy_start;
1081 ASSERT(copy_len);
3a39c18d 1082
974b1adc 1083 /*
1c3dc173
QW
1084 * Extra range check to ensure we didn't go beyond
1085 * @buf + @buf_len.
974b1adc 1086 */
1c3dc173
QW
1087 ASSERT(copy_start - decompressed < buf_len);
1088 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1089 buf + copy_start - decompressed, copy_len);
1c3dc173 1090 cur_offset += copy_len;
3a39c18d 1091
1c3dc173
QW
1092 bio_advance(orig_bio, copy_len);
1093 /* Finished the bio */
1094 if (!orig_bio->bi_iter.bi_size)
1095 return 0;
3a39c18d 1096 }
3a39c18d
LZ
1097 return 1;
1098}
c2fcdcdf 1099
19562430
TT
1100/*
1101 * Shannon Entropy calculation
1102 *
52042d8e 1103 * Pure byte distribution analysis fails to determine compressibility of data.
19562430
TT
1104 * Try calculating entropy to estimate the average minimum number of bits
1105 * needed to encode the sampled data.
1106 *
1107 * For convenience, return the percentage of needed bits, instead of amount of
1108 * bits directly.
1109 *
1110 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1111 * and can be compressible with high probability
1112 *
1113 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1114 *
1115 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1116 */
1117#define ENTROPY_LVL_ACEPTABLE (65)
1118#define ENTROPY_LVL_HIGH (80)
1119
1120/*
1121 * For increasead precision in shannon_entropy calculation,
1122 * let's do pow(n, M) to save more digits after comma:
1123 *
1124 * - maximum int bit length is 64
1125 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1126 * - 13 * 4 = 52 < 64 -> M = 4
1127 *
1128 * So use pow(n, 4).
1129 */
1130static inline u32 ilog2_w(u64 n)
1131{
1132 return ilog2(n * n * n * n);
1133}
1134
1135static u32 shannon_entropy(struct heuristic_ws *ws)
1136{
1137 const u32 entropy_max = 8 * ilog2_w(2);
1138 u32 entropy_sum = 0;
1139 u32 p, p_base, sz_base;
1140 u32 i;
1141
1142 sz_base = ilog2_w(ws->sample_size);
1143 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1144 p = ws->bucket[i].count;
1145 p_base = ilog2_w(p);
1146 entropy_sum += p * (sz_base - p_base);
1147 }
1148
1149 entropy_sum /= ws->sample_size;
1150 return entropy_sum * 100 / entropy_max;
1151}
1152
440c840c
TT
1153#define RADIX_BASE 4U
1154#define COUNTERS_SIZE (1U << RADIX_BASE)
1155
1156static u8 get4bits(u64 num, int shift) {
1157 u8 low4bits;
1158
1159 num >>= shift;
1160 /* Reverse order */
1161 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1162 return low4bits;
1163}
1164
440c840c
TT
1165/*
1166 * Use 4 bits as radix base
52042d8e 1167 * Use 16 u32 counters for calculating new position in buf array
440c840c
TT
1168 *
1169 * @array - array that will be sorted
1170 * @array_buf - buffer array to store sorting results
1171 * must be equal in size to @array
1172 * @num - array size
440c840c 1173 */
23ae8c63 1174static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
36243c91 1175 int num)
858177d3 1176{
440c840c
TT
1177 u64 max_num;
1178 u64 buf_num;
1179 u32 counters[COUNTERS_SIZE];
1180 u32 new_addr;
1181 u32 addr;
1182 int bitlen;
1183 int shift;
1184 int i;
858177d3 1185
440c840c
TT
1186 /*
1187 * Try avoid useless loop iterations for small numbers stored in big
1188 * counters. Example: 48 33 4 ... in 64bit array
1189 */
23ae8c63 1190 max_num = array[0].count;
440c840c 1191 for (i = 1; i < num; i++) {
23ae8c63 1192 buf_num = array[i].count;
440c840c
TT
1193 if (buf_num > max_num)
1194 max_num = buf_num;
1195 }
1196
1197 buf_num = ilog2(max_num);
1198 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1199
1200 shift = 0;
1201 while (shift < bitlen) {
1202 memset(counters, 0, sizeof(counters));
1203
1204 for (i = 0; i < num; i++) {
23ae8c63 1205 buf_num = array[i].count;
440c840c
TT
1206 addr = get4bits(buf_num, shift);
1207 counters[addr]++;
1208 }
1209
1210 for (i = 1; i < COUNTERS_SIZE; i++)
1211 counters[i] += counters[i - 1];
1212
1213 for (i = num - 1; i >= 0; i--) {
23ae8c63 1214 buf_num = array[i].count;
440c840c
TT
1215 addr = get4bits(buf_num, shift);
1216 counters[addr]--;
1217 new_addr = counters[addr];
7add17be 1218 array_buf[new_addr] = array[i];
440c840c
TT
1219 }
1220
1221 shift += RADIX_BASE;
1222
1223 /*
1224 * Normal radix expects to move data from a temporary array, to
1225 * the main one. But that requires some CPU time. Avoid that
1226 * by doing another sort iteration to original array instead of
1227 * memcpy()
1228 */
1229 memset(counters, 0, sizeof(counters));
1230
1231 for (i = 0; i < num; i ++) {
23ae8c63 1232 buf_num = array_buf[i].count;
440c840c
TT
1233 addr = get4bits(buf_num, shift);
1234 counters[addr]++;
1235 }
1236
1237 for (i = 1; i < COUNTERS_SIZE; i++)
1238 counters[i] += counters[i - 1];
1239
1240 for (i = num - 1; i >= 0; i--) {
23ae8c63 1241 buf_num = array_buf[i].count;
440c840c
TT
1242 addr = get4bits(buf_num, shift);
1243 counters[addr]--;
1244 new_addr = counters[addr];
7add17be 1245 array[new_addr] = array_buf[i];
440c840c
TT
1246 }
1247
1248 shift += RADIX_BASE;
1249 }
858177d3
TT
1250}
1251
1252/*
1253 * Size of the core byte set - how many bytes cover 90% of the sample
1254 *
1255 * There are several types of structured binary data that use nearly all byte
1256 * values. The distribution can be uniform and counts in all buckets will be
1257 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1258 *
1259 * Other possibility is normal (Gaussian) distribution, where the data could
1260 * be potentially compressible, but we have to take a few more steps to decide
1261 * how much.
1262 *
1263 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1264 * compression algo can easy fix that
1265 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1266 * probability is not compressible
1267 */
1268#define BYTE_CORE_SET_LOW (64)
1269#define BYTE_CORE_SET_HIGH (200)
1270
1271static int byte_core_set_size(struct heuristic_ws *ws)
1272{
1273 u32 i;
1274 u32 coreset_sum = 0;
1275 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1276 struct bucket_item *bucket = ws->bucket;
1277
1278 /* Sort in reverse order */
36243c91 1279 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
858177d3
TT
1280
1281 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1282 coreset_sum += bucket[i].count;
1283
1284 if (coreset_sum > core_set_threshold)
1285 return i;
1286
1287 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1288 coreset_sum += bucket[i].count;
1289 if (coreset_sum > core_set_threshold)
1290 break;
1291 }
1292
1293 return i;
1294}
1295
a288e92c
TT
1296/*
1297 * Count byte values in buckets.
1298 * This heuristic can detect textual data (configs, xml, json, html, etc).
1299 * Because in most text-like data byte set is restricted to limited number of
1300 * possible characters, and that restriction in most cases makes data easy to
1301 * compress.
1302 *
1303 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1304 * less - compressible
1305 * more - need additional analysis
1306 */
1307#define BYTE_SET_THRESHOLD (64)
1308
1309static u32 byte_set_size(const struct heuristic_ws *ws)
1310{
1311 u32 i;
1312 u32 byte_set_size = 0;
1313
1314 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1315 if (ws->bucket[i].count > 0)
1316 byte_set_size++;
1317 }
1318
1319 /*
1320 * Continue collecting count of byte values in buckets. If the byte
1321 * set size is bigger then the threshold, it's pointless to continue,
1322 * the detection technique would fail for this type of data.
1323 */
1324 for (; i < BUCKET_SIZE; i++) {
1325 if (ws->bucket[i].count > 0) {
1326 byte_set_size++;
1327 if (byte_set_size > BYTE_SET_THRESHOLD)
1328 return byte_set_size;
1329 }
1330 }
1331
1332 return byte_set_size;
1333}
1334
1fe4f6fa
TT
1335static bool sample_repeated_patterns(struct heuristic_ws *ws)
1336{
1337 const u32 half_of_sample = ws->sample_size / 2;
1338 const u8 *data = ws->sample;
1339
1340 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1341}
1342
a440d48c
TT
1343static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1344 struct heuristic_ws *ws)
1345{
1346 struct page *page;
1347 u64 index, index_end;
1348 u32 i, curr_sample_pos;
1349 u8 *in_data;
1350
1351 /*
1352 * Compression handles the input data by chunks of 128KiB
1353 * (defined by BTRFS_MAX_UNCOMPRESSED)
1354 *
1355 * We do the same for the heuristic and loop over the whole range.
1356 *
1357 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1358 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1359 */
1360 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1361 end = start + BTRFS_MAX_UNCOMPRESSED;
1362
1363 index = start >> PAGE_SHIFT;
1364 index_end = end >> PAGE_SHIFT;
1365
1366 /* Don't miss unaligned end */
ce394a7f 1367 if (!PAGE_ALIGNED(end))
a440d48c
TT
1368 index_end++;
1369
1370 curr_sample_pos = 0;
1371 while (index < index_end) {
1372 page = find_get_page(inode->i_mapping, index);
58c1a35c 1373 in_data = kmap_local_page(page);
a440d48c
TT
1374 /* Handle case where the start is not aligned to PAGE_SIZE */
1375 i = start % PAGE_SIZE;
1376 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1377 /* Don't sample any garbage from the last page */
1378 if (start > end - SAMPLING_READ_SIZE)
1379 break;
1380 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1381 SAMPLING_READ_SIZE);
1382 i += SAMPLING_INTERVAL;
1383 start += SAMPLING_INTERVAL;
1384 curr_sample_pos += SAMPLING_READ_SIZE;
1385 }
58c1a35c 1386 kunmap_local(in_data);
a440d48c
TT
1387 put_page(page);
1388
1389 index++;
1390 }
1391
1392 ws->sample_size = curr_sample_pos;
1393}
1394
c2fcdcdf
TT
1395/*
1396 * Compression heuristic.
1397 *
1398 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1399 * quickly (compared to direct compression) detect data characteristics
67da05b3 1400 * (compressible/incompressible) to avoid wasting CPU time on incompressible
c2fcdcdf
TT
1401 * data.
1402 *
1403 * The following types of analysis can be performed:
1404 * - detect mostly zero data
1405 * - detect data with low "byte set" size (text, etc)
1406 * - detect data with low/high "core byte" set
1407 *
1408 * Return non-zero if the compression should be done, 0 otherwise.
1409 */
1410int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1411{
7bf49943 1412 struct list_head *ws_list = get_workspace(0, 0);
4e439a0b 1413 struct heuristic_ws *ws;
a440d48c
TT
1414 u32 i;
1415 u8 byte;
19562430 1416 int ret = 0;
c2fcdcdf 1417
4e439a0b
TT
1418 ws = list_entry(ws_list, struct heuristic_ws, list);
1419
a440d48c
TT
1420 heuristic_collect_sample(inode, start, end, ws);
1421
1fe4f6fa
TT
1422 if (sample_repeated_patterns(ws)) {
1423 ret = 1;
1424 goto out;
1425 }
1426
a440d48c
TT
1427 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1428
1429 for (i = 0; i < ws->sample_size; i++) {
1430 byte = ws->sample[i];
1431 ws->bucket[byte].count++;
c2fcdcdf
TT
1432 }
1433
a288e92c
TT
1434 i = byte_set_size(ws);
1435 if (i < BYTE_SET_THRESHOLD) {
1436 ret = 2;
1437 goto out;
1438 }
1439
858177d3
TT
1440 i = byte_core_set_size(ws);
1441 if (i <= BYTE_CORE_SET_LOW) {
1442 ret = 3;
1443 goto out;
1444 }
1445
1446 if (i >= BYTE_CORE_SET_HIGH) {
1447 ret = 0;
1448 goto out;
1449 }
1450
19562430
TT
1451 i = shannon_entropy(ws);
1452 if (i <= ENTROPY_LVL_ACEPTABLE) {
1453 ret = 4;
1454 goto out;
1455 }
1456
1457 /*
1458 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1459 * needed to give green light to compression.
1460 *
1461 * For now just assume that compression at that level is not worth the
1462 * resources because:
1463 *
1464 * 1. it is possible to defrag the data later
1465 *
1466 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1467 * values, every bucket has counter at level ~54. The heuristic would
1468 * be confused. This can happen when data have some internal repeated
1469 * patterns like "abbacbbc...". This can be detected by analyzing
1470 * pairs of bytes, which is too costly.
1471 */
1472 if (i < ENTROPY_LVL_HIGH) {
1473 ret = 5;
1474 goto out;
1475 } else {
1476 ret = 0;
1477 goto out;
1478 }
1479
1fe4f6fa 1480out:
929f4baf 1481 put_workspace(0, ws_list);
c2fcdcdf
TT
1482 return ret;
1483}
f51d2b59 1484
d0ab62ce
DZ
1485/*
1486 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1487 * level, unrecognized string will set the default level
1488 */
1489unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
f51d2b59 1490{
d0ab62ce
DZ
1491 unsigned int level = 0;
1492 int ret;
1493
1494 if (!type)
f51d2b59
DS
1495 return 0;
1496
d0ab62ce
DZ
1497 if (str[0] == ':') {
1498 ret = kstrtouint(str + 1, 10, &level);
1499 if (ret)
1500 level = 0;
1501 }
1502
b0c1fe1e
DS
1503 level = btrfs_compress_set_level(type, level);
1504
1505 return level;
1506}