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