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