btrfs: remove btrfs_find_ordered_sum call from btrfs_lookup_bio_sums
[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>
11#include <linux/highmem.h>
12#include <linux/time.h>
13#include <linux/init.h>
14#include <linux/string.h>
c8b97818 15#include <linux/backing-dev.h>
c8b97818 16#include <linux/writeback.h>
5a0e3ad6 17#include <linux/slab.h>
fe308533 18#include <linux/sched/mm.h>
19562430 19#include <linux/log2.h>
d5178578 20#include <crypto/hash.h>
602cbe91 21#include "misc.h"
c8b97818
CM
22#include "ctree.h"
23#include "disk-io.h"
24#include "transaction.h"
25#include "btrfs_inode.h"
26#include "volumes.h"
27#include "ordered-data.h"
c8b97818
CM
28#include "compression.h"
29#include "extent_io.h"
30#include "extent_map.h"
31
e128f9c3
DS
32static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
33
34const char* btrfs_compress_type2str(enum btrfs_compression_type type)
35{
36 switch (type) {
37 case BTRFS_COMPRESS_ZLIB:
38 case BTRFS_COMPRESS_LZO:
39 case BTRFS_COMPRESS_ZSTD:
40 case BTRFS_COMPRESS_NONE:
41 return btrfs_compress_types[type];
ce96b7ff
CX
42 default:
43 break;
e128f9c3
DS
44 }
45
46 return NULL;
47}
48
aa53e3bf
JT
49bool btrfs_compress_is_valid_type(const char *str, size_t len)
50{
51 int i;
52
53 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
54 size_t comp_len = strlen(btrfs_compress_types[i]);
55
56 if (len < comp_len)
57 continue;
58
59 if (!strncmp(btrfs_compress_types[i], str, comp_len))
60 return true;
61 }
62 return false;
63}
64
1e4eb746
DS
65static int compression_compress_pages(int type, struct list_head *ws,
66 struct address_space *mapping, u64 start, struct page **pages,
67 unsigned long *out_pages, unsigned long *total_in,
68 unsigned long *total_out)
69{
70 switch (type) {
71 case BTRFS_COMPRESS_ZLIB:
72 return zlib_compress_pages(ws, mapping, start, pages,
73 out_pages, total_in, total_out);
74 case BTRFS_COMPRESS_LZO:
75 return lzo_compress_pages(ws, mapping, start, pages,
76 out_pages, total_in, total_out);
77 case BTRFS_COMPRESS_ZSTD:
78 return zstd_compress_pages(ws, mapping, start, pages,
79 out_pages, total_in, total_out);
80 case BTRFS_COMPRESS_NONE:
81 default:
82 /*
83 * This can't happen, the type is validated several times
84 * before we get here. As a sane fallback, return what the
85 * callers will understand as 'no compression happened'.
86 */
87 return -E2BIG;
88 }
89}
90
91static int compression_decompress_bio(int type, struct list_head *ws,
92 struct compressed_bio *cb)
93{
94 switch (type) {
95 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
96 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
97 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
98 case BTRFS_COMPRESS_NONE:
99 default:
100 /*
101 * This can't happen, the type is validated several times
102 * before we get here.
103 */
104 BUG();
105 }
106}
107
108static int compression_decompress(int type, struct list_head *ws,
109 unsigned char *data_in, struct page *dest_page,
110 unsigned long start_byte, size_t srclen, size_t destlen)
111{
112 switch (type) {
113 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
114 start_byte, srclen, destlen);
115 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
116 start_byte, srclen, destlen);
117 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
118 start_byte, srclen, destlen);
119 case BTRFS_COMPRESS_NONE:
120 default:
121 /*
122 * This can't happen, the type is validated several times
123 * before we get here.
124 */
125 BUG();
126 }
127}
128
8140dc30 129static int btrfs_decompress_bio(struct compressed_bio *cb);
48a3b636 130
2ff7e61e 131static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
d20f7043
CM
132 unsigned long disk_size)
133{
d20f7043 134 return sizeof(struct compressed_bio) +
713cebfb 135 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
d20f7043
CM
136}
137
5a9472fe 138static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
d20f7043
CM
139 u64 disk_start)
140{
10fe6ca8 141 struct btrfs_fs_info *fs_info = inode->root->fs_info;
d5178578 142 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
223486c2 143 const u32 csum_size = fs_info->csum_size;
d20f7043
CM
144 struct page *page;
145 unsigned long i;
146 char *kaddr;
d5178578 147 u8 csum[BTRFS_CSUM_SIZE];
5a9472fe 148 struct compressed_bio *cb = bio->bi_private;
10fe6ca8 149 u8 *cb_sum = cb->sums;
d20f7043 150
42437a63 151 if (!fs_info->csum_root || (inode->flags & BTRFS_INODE_NODATASUM))
d20f7043
CM
152 return 0;
153
d5178578
JT
154 shash->tfm = fs_info->csum_shash;
155
d20f7043
CM
156 for (i = 0; i < cb->nr_pages; i++) {
157 page = cb->compressed_pages[i];
d20f7043 158
7ac687d9 159 kaddr = kmap_atomic(page);
fd08001f 160 crypto_shash_digest(shash, kaddr, PAGE_SIZE, csum);
7ac687d9 161 kunmap_atomic(kaddr);
d20f7043 162
10fe6ca8 163 if (memcmp(&csum, cb_sum, csum_size)) {
d5178578 164 btrfs_print_data_csum_error(inode, disk_start,
ea41d6b2 165 csum, cb_sum, cb->mirror_num);
5a9472fe
NB
166 if (btrfs_io_bio(bio)->device)
167 btrfs_dev_stat_inc_and_print(
168 btrfs_io_bio(bio)->device,
169 BTRFS_DEV_STAT_CORRUPTION_ERRS);
93c4c033 170 return -EIO;
d20f7043 171 }
10fe6ca8 172 cb_sum += csum_size;
d20f7043 173 }
93c4c033 174 return 0;
d20f7043
CM
175}
176
c8b97818
CM
177/* when we finish reading compressed pages from the disk, we
178 * decompress them and then run the bio end_io routines on the
179 * decompressed pages (in the inode address space).
180 *
181 * This allows the checksumming and other IO error handling routines
182 * to work normally
183 *
184 * The compressed pages are freed here, and it must be run
185 * in process context
186 */
4246a0b6 187static void end_compressed_bio_read(struct bio *bio)
c8b97818 188{
c8b97818
CM
189 struct compressed_bio *cb = bio->bi_private;
190 struct inode *inode;
191 struct page *page;
192 unsigned long index;
cf1167d5 193 unsigned int mirror = btrfs_io_bio(bio)->mirror_num;
e6311f24 194 int ret = 0;
c8b97818 195
4e4cbee9 196 if (bio->bi_status)
c8b97818
CM
197 cb->errors = 1;
198
199 /* if there are more bios still pending for this compressed
200 * extent, just exit
201 */
a50299ae 202 if (!refcount_dec_and_test(&cb->pending_bios))
c8b97818
CM
203 goto out;
204
cf1167d5
LB
205 /*
206 * Record the correct mirror_num in cb->orig_bio so that
207 * read-repair can work properly.
208 */
cf1167d5
LB
209 btrfs_io_bio(cb->orig_bio)->mirror_num = mirror;
210 cb->mirror_num = mirror;
211
e6311f24
LB
212 /*
213 * Some IO in this cb have failed, just skip checksum as there
214 * is no way it could be correct.
215 */
216 if (cb->errors == 1)
217 goto csum_failed;
218
d20f7043 219 inode = cb->inode;
5a9472fe 220 ret = check_compressed_csum(BTRFS_I(inode), bio,
1201b58b 221 bio->bi_iter.bi_sector << 9);
d20f7043
CM
222 if (ret)
223 goto csum_failed;
224
c8b97818
CM
225 /* ok, we're the last bio for this extent, lets start
226 * the decompression.
227 */
8140dc30
AJ
228 ret = btrfs_decompress_bio(cb);
229
d20f7043 230csum_failed:
c8b97818
CM
231 if (ret)
232 cb->errors = 1;
233
234 /* release the compressed pages */
235 index = 0;
236 for (index = 0; index < cb->nr_pages; index++) {
237 page = cb->compressed_pages[index];
238 page->mapping = NULL;
09cbfeaf 239 put_page(page);
c8b97818
CM
240 }
241
242 /* do io completion on the original bio */
771ed689 243 if (cb->errors) {
c8b97818 244 bio_io_error(cb->orig_bio);
d20f7043 245 } else {
2c30c71b 246 struct bio_vec *bvec;
6dc4f100 247 struct bvec_iter_all iter_all;
d20f7043
CM
248
249 /*
250 * we have verified the checksum already, set page
251 * checked so the end_io handlers know about it
252 */
c09abff8 253 ASSERT(!bio_flagged(bio, BIO_CLONED));
2b070cfe 254 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all)
d20f7043 255 SetPageChecked(bvec->bv_page);
2c30c71b 256
4246a0b6 257 bio_endio(cb->orig_bio);
d20f7043 258 }
c8b97818
CM
259
260 /* finally free the cb struct */
261 kfree(cb->compressed_pages);
262 kfree(cb);
263out:
264 bio_put(bio);
265}
266
267/*
268 * Clear the writeback bits on all of the file
269 * pages for a compressed write
270 */
7bdcefc1
FM
271static noinline void end_compressed_writeback(struct inode *inode,
272 const struct compressed_bio *cb)
c8b97818 273{
09cbfeaf
KS
274 unsigned long index = cb->start >> PAGE_SHIFT;
275 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
c8b97818
CM
276 struct page *pages[16];
277 unsigned long nr_pages = end_index - index + 1;
278 int i;
279 int ret;
280
7bdcefc1
FM
281 if (cb->errors)
282 mapping_set_error(inode->i_mapping, -EIO);
283
d397712b 284 while (nr_pages > 0) {
c8b97818 285 ret = find_get_pages_contig(inode->i_mapping, index,
5b050f04
CM
286 min_t(unsigned long,
287 nr_pages, ARRAY_SIZE(pages)), pages);
c8b97818
CM
288 if (ret == 0) {
289 nr_pages -= 1;
290 index += 1;
291 continue;
292 }
293 for (i = 0; i < ret; i++) {
7bdcefc1
FM
294 if (cb->errors)
295 SetPageError(pages[i]);
c8b97818 296 end_page_writeback(pages[i]);
09cbfeaf 297 put_page(pages[i]);
c8b97818
CM
298 }
299 nr_pages -= ret;
300 index += ret;
301 }
302 /* the inode may be gone now */
c8b97818
CM
303}
304
305/*
306 * do the cleanup once all the compressed pages hit the disk.
307 * This will clear writeback on the file pages and free the compressed
308 * pages.
309 *
310 * This also calls the writeback end hooks for the file pages so that
311 * metadata and checksums can be updated in the file.
312 */
4246a0b6 313static void end_compressed_bio_write(struct bio *bio)
c8b97818 314{
c8b97818
CM
315 struct compressed_bio *cb = bio->bi_private;
316 struct inode *inode;
317 struct page *page;
318 unsigned long index;
319
4e4cbee9 320 if (bio->bi_status)
c8b97818
CM
321 cb->errors = 1;
322
323 /* if there are more bios still pending for this compressed
324 * extent, just exit
325 */
a50299ae 326 if (!refcount_dec_and_test(&cb->pending_bios))
c8b97818
CM
327 goto out;
328
329 /* ok, we're the last bio for this extent, step one is to
330 * call back into the FS and do all the end_io operations
331 */
332 inode = cb->inode;
70b99e69 333 cb->compressed_pages[0]->mapping = cb->inode->i_mapping;
7087a9d8 334 btrfs_writepage_endio_finish_ordered(cb->compressed_pages[0],
c629732d 335 cb->start, cb->start + cb->len - 1,
6a8d2136 336 bio->bi_status == BLK_STS_OK);
70b99e69 337 cb->compressed_pages[0]->mapping = NULL;
c8b97818 338
7bdcefc1 339 end_compressed_writeback(inode, cb);
c8b97818
CM
340 /* note, our inode could be gone now */
341
342 /*
343 * release the compressed pages, these came from alloc_page and
344 * are not attached to the inode at all
345 */
346 index = 0;
347 for (index = 0; index < cb->nr_pages; index++) {
348 page = cb->compressed_pages[index];
349 page->mapping = NULL;
09cbfeaf 350 put_page(page);
c8b97818
CM
351 }
352
353 /* finally free the cb struct */
354 kfree(cb->compressed_pages);
355 kfree(cb);
356out:
357 bio_put(bio);
358}
359
360/*
361 * worker function to build and submit bios for previously compressed pages.
362 * The corresponding pages in the inode should be marked for writeback
363 * and the compressed pages should have a reference on them for dropping
364 * when the IO is complete.
365 *
366 * This also checksums the file bytes and gets things ready for
367 * the end io hooks.
368 */
c7ee1819 369blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
c8b97818
CM
370 unsigned long len, u64 disk_start,
371 unsigned long compressed_len,
372 struct page **compressed_pages,
f82b7359 373 unsigned long nr_pages,
ec39f769
CM
374 unsigned int write_flags,
375 struct cgroup_subsys_state *blkcg_css)
c8b97818 376{
c7ee1819 377 struct btrfs_fs_info *fs_info = inode->root->fs_info;
c8b97818 378 struct bio *bio = NULL;
c8b97818
CM
379 struct compressed_bio *cb;
380 unsigned long bytes_left;
306e16ce 381 int pg_index = 0;
c8b97818
CM
382 struct page *page;
383 u64 first_byte = disk_start;
4e4cbee9 384 blk_status_t ret;
c7ee1819 385 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
c8b97818 386
fdb1e121 387 WARN_ON(!PAGE_ALIGNED(start));
2ff7e61e 388 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
dac97e51 389 if (!cb)
4e4cbee9 390 return BLK_STS_RESOURCE;
a50299ae 391 refcount_set(&cb->pending_bios, 0);
c8b97818 392 cb->errors = 0;
c7ee1819 393 cb->inode = &inode->vfs_inode;
c8b97818
CM
394 cb->start = start;
395 cb->len = len;
d20f7043 396 cb->mirror_num = 0;
c8b97818
CM
397 cb->compressed_pages = compressed_pages;
398 cb->compressed_len = compressed_len;
399 cb->orig_bio = NULL;
400 cb->nr_pages = nr_pages;
401
e749af44 402 bio = btrfs_bio_alloc(first_byte);
f82b7359 403 bio->bi_opf = REQ_OP_WRITE | write_flags;
c8b97818
CM
404 bio->bi_private = cb;
405 bio->bi_end_io = end_compressed_bio_write;
ec39f769
CM
406
407 if (blkcg_css) {
408 bio->bi_opf |= REQ_CGROUP_PUNT;
46bcff2b 409 kthread_associate_blkcg(blkcg_css);
ec39f769 410 }
a50299ae 411 refcount_set(&cb->pending_bios, 1);
c8b97818
CM
412
413 /* create and submit bios for the compressed pages */
414 bytes_left = compressed_len;
306e16ce 415 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
4e4cbee9
CH
416 int submit = 0;
417
306e16ce 418 page = compressed_pages[pg_index];
c7ee1819 419 page->mapping = inode->vfs_inode.i_mapping;
4f024f37 420 if (bio->bi_iter.bi_size)
da12fe54
NB
421 submit = btrfs_bio_fits_in_stripe(page, PAGE_SIZE, bio,
422 0);
c8b97818 423
70b99e69 424 page->mapping = NULL;
4e4cbee9 425 if (submit || bio_add_page(bio, page, PAGE_SIZE, 0) <
09cbfeaf 426 PAGE_SIZE) {
af09abfe
CM
427 /*
428 * inc the count before we submit the bio so
429 * we know the end IO handler won't happen before
430 * we inc the count. Otherwise, the cb might get
431 * freed before we're done setting it up
432 */
a50299ae 433 refcount_inc(&cb->pending_bios);
0b246afa
JM
434 ret = btrfs_bio_wq_end_io(fs_info, bio,
435 BTRFS_WQ_ENDIO_DATA);
79787eaa 436 BUG_ON(ret); /* -ENOMEM */
c8b97818 437
e55179b3 438 if (!skip_sum) {
c7ee1819 439 ret = btrfs_csum_one_bio(inode, bio, start, 1);
79787eaa 440 BUG_ON(ret); /* -ENOMEM */
e55179b3 441 }
d20f7043 442
08635bae 443 ret = btrfs_map_bio(fs_info, bio, 0);
f5daf2c7 444 if (ret) {
4e4cbee9 445 bio->bi_status = ret;
f5daf2c7
LB
446 bio_endio(bio);
447 }
c8b97818 448
e749af44 449 bio = btrfs_bio_alloc(first_byte);
f82b7359 450 bio->bi_opf = REQ_OP_WRITE | write_flags;
c8b97818
CM
451 bio->bi_private = cb;
452 bio->bi_end_io = end_compressed_bio_write;
46bcff2b 453 if (blkcg_css)
7b62e66c 454 bio->bi_opf |= REQ_CGROUP_PUNT;
09cbfeaf 455 bio_add_page(bio, page, PAGE_SIZE, 0);
c8b97818 456 }
09cbfeaf 457 if (bytes_left < PAGE_SIZE) {
0b246afa 458 btrfs_info(fs_info,
efe120a0 459 "bytes left %lu compress len %lu nr %lu",
cfbc246e
CM
460 bytes_left, cb->compressed_len, cb->nr_pages);
461 }
09cbfeaf
KS
462 bytes_left -= PAGE_SIZE;
463 first_byte += PAGE_SIZE;
771ed689 464 cond_resched();
c8b97818 465 }
c8b97818 466
0b246afa 467 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
79787eaa 468 BUG_ON(ret); /* -ENOMEM */
c8b97818 469
e55179b3 470 if (!skip_sum) {
c7ee1819 471 ret = btrfs_csum_one_bio(inode, bio, start, 1);
79787eaa 472 BUG_ON(ret); /* -ENOMEM */
e55179b3 473 }
d20f7043 474
08635bae 475 ret = btrfs_map_bio(fs_info, bio, 0);
f5daf2c7 476 if (ret) {
4e4cbee9 477 bio->bi_status = ret;
f5daf2c7
LB
478 bio_endio(bio);
479 }
c8b97818 480
46bcff2b
DZ
481 if (blkcg_css)
482 kthread_associate_blkcg(NULL);
483
c8b97818
CM
484 return 0;
485}
486
2a4d0c90
CH
487static u64 bio_end_offset(struct bio *bio)
488{
c45a8f2d 489 struct bio_vec *last = bio_last_bvec_all(bio);
2a4d0c90
CH
490
491 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
492}
493
771ed689
CM
494static noinline int add_ra_bio_pages(struct inode *inode,
495 u64 compressed_end,
496 struct compressed_bio *cb)
497{
498 unsigned long end_index;
306e16ce 499 unsigned long pg_index;
771ed689
CM
500 u64 last_offset;
501 u64 isize = i_size_read(inode);
502 int ret;
503 struct page *page;
504 unsigned long nr_pages = 0;
505 struct extent_map *em;
506 struct address_space *mapping = inode->i_mapping;
771ed689
CM
507 struct extent_map_tree *em_tree;
508 struct extent_io_tree *tree;
509 u64 end;
510 int misses = 0;
511
2a4d0c90 512 last_offset = bio_end_offset(cb->orig_bio);
771ed689
CM
513 em_tree = &BTRFS_I(inode)->extent_tree;
514 tree = &BTRFS_I(inode)->io_tree;
515
516 if (isize == 0)
517 return 0;
518
09cbfeaf 519 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
771ed689 520
d397712b 521 while (last_offset < compressed_end) {
09cbfeaf 522 pg_index = last_offset >> PAGE_SHIFT;
771ed689 523
306e16ce 524 if (pg_index > end_index)
771ed689
CM
525 break;
526
0a943c65 527 page = xa_load(&mapping->i_pages, pg_index);
3159f943 528 if (page && !xa_is_value(page)) {
771ed689
CM
529 misses++;
530 if (misses > 4)
531 break;
532 goto next;
533 }
534
c62d2555
MH
535 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
536 ~__GFP_FS));
771ed689
CM
537 if (!page)
538 break;
539
c62d2555 540 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
09cbfeaf 541 put_page(page);
771ed689
CM
542 goto next;
543 }
544
09cbfeaf 545 end = last_offset + PAGE_SIZE - 1;
771ed689
CM
546 /*
547 * at this point, we have a locked page in the page cache
548 * for these bytes in the file. But, we have to make
549 * sure they map to this compressed extent on disk.
550 */
551 set_page_extent_mapped(page);
d0082371 552 lock_extent(tree, last_offset, end);
890871be 553 read_lock(&em_tree->lock);
771ed689 554 em = lookup_extent_mapping(em_tree, last_offset,
09cbfeaf 555 PAGE_SIZE);
890871be 556 read_unlock(&em_tree->lock);
771ed689
CM
557
558 if (!em || last_offset < em->start ||
09cbfeaf 559 (last_offset + PAGE_SIZE > extent_map_end(em)) ||
4f024f37 560 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
771ed689 561 free_extent_map(em);
d0082371 562 unlock_extent(tree, last_offset, end);
771ed689 563 unlock_page(page);
09cbfeaf 564 put_page(page);
771ed689
CM
565 break;
566 }
567 free_extent_map(em);
568
569 if (page->index == end_index) {
570 char *userpage;
7073017a 571 size_t zero_offset = offset_in_page(isize);
771ed689
CM
572
573 if (zero_offset) {
574 int zeros;
09cbfeaf 575 zeros = PAGE_SIZE - zero_offset;
7ac687d9 576 userpage = kmap_atomic(page);
771ed689
CM
577 memset(userpage + zero_offset, 0, zeros);
578 flush_dcache_page(page);
7ac687d9 579 kunmap_atomic(userpage);
771ed689
CM
580 }
581 }
582
583 ret = bio_add_page(cb->orig_bio, page,
09cbfeaf 584 PAGE_SIZE, 0);
771ed689 585
09cbfeaf 586 if (ret == PAGE_SIZE) {
771ed689 587 nr_pages++;
09cbfeaf 588 put_page(page);
771ed689 589 } else {
d0082371 590 unlock_extent(tree, last_offset, end);
771ed689 591 unlock_page(page);
09cbfeaf 592 put_page(page);
771ed689
CM
593 break;
594 }
595next:
09cbfeaf 596 last_offset += PAGE_SIZE;
771ed689 597 }
771ed689
CM
598 return 0;
599}
600
c8b97818
CM
601/*
602 * for a compressed read, the bio we get passed has all the inode pages
603 * in it. We don't actually do IO on those pages but allocate new ones
604 * to hold the compressed pages on disk.
605 *
4f024f37 606 * bio->bi_iter.bi_sector points to the compressed extent on disk
c8b97818 607 * bio->bi_io_vec points to all of the inode pages
c8b97818
CM
608 *
609 * After the compressed pages are read, we copy the bytes into the
610 * bio we were passed and then call the bio end_io calls
611 */
4e4cbee9 612blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
c8b97818
CM
613 int mirror_num, unsigned long bio_flags)
614{
0b246afa 615 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
c8b97818
CM
616 struct extent_map_tree *em_tree;
617 struct compressed_bio *cb;
c8b97818
CM
618 unsigned long compressed_len;
619 unsigned long nr_pages;
306e16ce 620 unsigned long pg_index;
c8b97818 621 struct page *page;
c8b97818 622 struct bio *comp_bio;
1201b58b 623 u64 cur_disk_byte = bio->bi_iter.bi_sector << 9;
e04ca626
CM
624 u64 em_len;
625 u64 em_start;
c8b97818 626 struct extent_map *em;
4e4cbee9 627 blk_status_t ret = BLK_STS_RESOURCE;
15e3004a 628 int faili = 0;
10fe6ca8 629 u8 *sums;
c8b97818 630
c8b97818
CM
631 em_tree = &BTRFS_I(inode)->extent_tree;
632
633 /* we need the actual starting offset of this extent in the file */
890871be 634 read_lock(&em_tree->lock);
c8b97818 635 em = lookup_extent_mapping(em_tree,
263663cd 636 page_offset(bio_first_page_all(bio)),
09cbfeaf 637 PAGE_SIZE);
890871be 638 read_unlock(&em_tree->lock);
285190d9 639 if (!em)
4e4cbee9 640 return BLK_STS_IOERR;
c8b97818 641
d20f7043 642 compressed_len = em->block_len;
2ff7e61e 643 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
6b82ce8d 644 if (!cb)
645 goto out;
646
a50299ae 647 refcount_set(&cb->pending_bios, 0);
c8b97818
CM
648 cb->errors = 0;
649 cb->inode = inode;
d20f7043 650 cb->mirror_num = mirror_num;
10fe6ca8 651 sums = cb->sums;
c8b97818 652
ff5b7ee3 653 cb->start = em->orig_start;
e04ca626
CM
654 em_len = em->len;
655 em_start = em->start;
d20f7043 656
c8b97818 657 free_extent_map(em);
e04ca626 658 em = NULL;
c8b97818 659
81381053 660 cb->len = bio->bi_iter.bi_size;
c8b97818 661 cb->compressed_len = compressed_len;
261507a0 662 cb->compress_type = extent_compress_type(bio_flags);
c8b97818
CM
663 cb->orig_bio = bio;
664
09cbfeaf 665 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
31e818fe 666 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
c8b97818 667 GFP_NOFS);
6b82ce8d 668 if (!cb->compressed_pages)
669 goto fail1;
670
306e16ce
DS
671 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
672 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS |
c8b97818 673 __GFP_HIGHMEM);
15e3004a
JB
674 if (!cb->compressed_pages[pg_index]) {
675 faili = pg_index - 1;
0e9350de 676 ret = BLK_STS_RESOURCE;
6b82ce8d 677 goto fail2;
15e3004a 678 }
c8b97818 679 }
15e3004a 680 faili = nr_pages - 1;
c8b97818
CM
681 cb->nr_pages = nr_pages;
682
7f042a83 683 add_ra_bio_pages(inode, em_start + em_len, cb);
771ed689 684
771ed689 685 /* include any pages we added in add_ra-bio_pages */
81381053 686 cb->len = bio->bi_iter.bi_size;
771ed689 687
e749af44 688 comp_bio = btrfs_bio_alloc(cur_disk_byte);
ebcc3263 689 comp_bio->bi_opf = REQ_OP_READ;
c8b97818
CM
690 comp_bio->bi_private = cb;
691 comp_bio->bi_end_io = end_compressed_bio_read;
a50299ae 692 refcount_set(&cb->pending_bios, 1);
c8b97818 693
306e16ce 694 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
4e4cbee9
CH
695 int submit = 0;
696
306e16ce 697 page = cb->compressed_pages[pg_index];
c8b97818 698 page->mapping = inode->i_mapping;
09cbfeaf 699 page->index = em_start >> PAGE_SHIFT;
d20f7043 700
4f024f37 701 if (comp_bio->bi_iter.bi_size)
da12fe54
NB
702 submit = btrfs_bio_fits_in_stripe(page, PAGE_SIZE,
703 comp_bio, 0);
c8b97818 704
70b99e69 705 page->mapping = NULL;
4e4cbee9 706 if (submit || bio_add_page(comp_bio, page, PAGE_SIZE, 0) <
09cbfeaf 707 PAGE_SIZE) {
10fe6ca8
JT
708 unsigned int nr_sectors;
709
0b246afa
JM
710 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
711 BTRFS_WQ_ENDIO_DATA);
79787eaa 712 BUG_ON(ret); /* -ENOMEM */
c8b97818 713
af09abfe
CM
714 /*
715 * inc the count before we submit the bio so
716 * we know the end IO handler won't happen before
717 * we inc the count. Otherwise, the cb might get
718 * freed before we're done setting it up
719 */
a50299ae 720 refcount_inc(&cb->pending_bios);
af09abfe 721
334c16d8
JB
722 ret = btrfs_lookup_bio_sums(inode, comp_bio, (u64)-1,
723 sums);
724 BUG_ON(ret); /* -ENOMEM */
10fe6ca8
JT
725
726 nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
727 fs_info->sectorsize);
713cebfb 728 sums += fs_info->csum_size * nr_sectors;
d20f7043 729
08635bae 730 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
4246a0b6 731 if (ret) {
4e4cbee9 732 comp_bio->bi_status = ret;
4246a0b6
CH
733 bio_endio(comp_bio);
734 }
c8b97818 735
e749af44 736 comp_bio = btrfs_bio_alloc(cur_disk_byte);
ebcc3263 737 comp_bio->bi_opf = REQ_OP_READ;
771ed689
CM
738 comp_bio->bi_private = cb;
739 comp_bio->bi_end_io = end_compressed_bio_read;
740
09cbfeaf 741 bio_add_page(comp_bio, page, PAGE_SIZE, 0);
c8b97818 742 }
09cbfeaf 743 cur_disk_byte += PAGE_SIZE;
c8b97818 744 }
c8b97818 745
0b246afa 746 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
79787eaa 747 BUG_ON(ret); /* -ENOMEM */
c8b97818 748
334c16d8
JB
749 ret = btrfs_lookup_bio_sums(inode, comp_bio, (u64)-1, sums);
750 BUG_ON(ret); /* -ENOMEM */
d20f7043 751
08635bae 752 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
4246a0b6 753 if (ret) {
4e4cbee9 754 comp_bio->bi_status = ret;
4246a0b6
CH
755 bio_endio(comp_bio);
756 }
c8b97818 757
c8b97818 758 return 0;
6b82ce8d 759
760fail2:
15e3004a
JB
761 while (faili >= 0) {
762 __free_page(cb->compressed_pages[faili]);
763 faili--;
764 }
6b82ce8d 765
766 kfree(cb->compressed_pages);
767fail1:
768 kfree(cb);
769out:
770 free_extent_map(em);
771 return ret;
c8b97818 772}
261507a0 773
17b5a6c1
TT
774/*
775 * Heuristic uses systematic sampling to collect data from the input data
776 * range, the logic can be tuned by the following constants:
777 *
778 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
779 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
780 */
781#define SAMPLING_READ_SIZE (16)
782#define SAMPLING_INTERVAL (256)
783
784/*
785 * For statistical analysis of the input data we consider bytes that form a
786 * Galois Field of 256 objects. Each object has an attribute count, ie. how
787 * many times the object appeared in the sample.
788 */
789#define BUCKET_SIZE (256)
790
791/*
792 * The size of the sample is based on a statistical sampling rule of thumb.
793 * The common way is to perform sampling tests as long as the number of
794 * elements in each cell is at least 5.
795 *
796 * Instead of 5, we choose 32 to obtain more accurate results.
797 * If the data contain the maximum number of symbols, which is 256, we obtain a
798 * sample size bound by 8192.
799 *
800 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
801 * from up to 512 locations.
802 */
803#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
804 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
805
806struct bucket_item {
807 u32 count;
808};
4e439a0b
TT
809
810struct heuristic_ws {
17b5a6c1
TT
811 /* Partial copy of input data */
812 u8 *sample;
a440d48c 813 u32 sample_size;
17b5a6c1
TT
814 /* Buckets store counters for each byte value */
815 struct bucket_item *bucket;
440c840c
TT
816 /* Sorting buffer */
817 struct bucket_item *bucket_b;
4e439a0b
TT
818 struct list_head list;
819};
820
92ee5530
DZ
821static struct workspace_manager heuristic_wsm;
822
4e439a0b
TT
823static void free_heuristic_ws(struct list_head *ws)
824{
825 struct heuristic_ws *workspace;
826
827 workspace = list_entry(ws, struct heuristic_ws, list);
828
17b5a6c1
TT
829 kvfree(workspace->sample);
830 kfree(workspace->bucket);
440c840c 831 kfree(workspace->bucket_b);
4e439a0b
TT
832 kfree(workspace);
833}
834
7bf49943 835static struct list_head *alloc_heuristic_ws(unsigned int level)
4e439a0b
TT
836{
837 struct heuristic_ws *ws;
838
839 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
840 if (!ws)
841 return ERR_PTR(-ENOMEM);
842
17b5a6c1
TT
843 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
844 if (!ws->sample)
845 goto fail;
846
847 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
848 if (!ws->bucket)
849 goto fail;
4e439a0b 850
440c840c
TT
851 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
852 if (!ws->bucket_b)
853 goto fail;
854
17b5a6c1 855 INIT_LIST_HEAD(&ws->list);
4e439a0b 856 return &ws->list;
17b5a6c1
TT
857fail:
858 free_heuristic_ws(&ws->list);
859 return ERR_PTR(-ENOMEM);
4e439a0b
TT
860}
861
ca4ac360 862const struct btrfs_compress_op btrfs_heuristic_compress = {
be951045 863 .workspace_manager = &heuristic_wsm,
ca4ac360
DZ
864};
865
e8c9f186 866static const struct btrfs_compress_op * const btrfs_compress_op[] = {
ca4ac360
DZ
867 /* The heuristic is represented as compression type 0 */
868 &btrfs_heuristic_compress,
261507a0 869 &btrfs_zlib_compress,
a6fa6fae 870 &btrfs_lzo_compress,
5c1aab1d 871 &btrfs_zstd_compress,
261507a0
LZ
872};
873
c778df14
DS
874static struct list_head *alloc_workspace(int type, unsigned int level)
875{
876 switch (type) {
877 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
878 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
879 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
880 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
881 default:
882 /*
883 * This can't happen, the type is validated several times
884 * before we get here.
885 */
886 BUG();
887 }
888}
889
1e002351
DS
890static void free_workspace(int type, struct list_head *ws)
891{
892 switch (type) {
893 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
894 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
895 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
896 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
897 default:
898 /*
899 * This can't happen, the type is validated several times
900 * before we get here.
901 */
902 BUG();
903 }
904}
905
d5517033 906static void btrfs_init_workspace_manager(int type)
261507a0 907{
0cf25213 908 struct workspace_manager *wsm;
4e439a0b 909 struct list_head *workspace;
261507a0 910
0cf25213 911 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
912 INIT_LIST_HEAD(&wsm->idle_ws);
913 spin_lock_init(&wsm->ws_lock);
914 atomic_set(&wsm->total_ws, 0);
915 init_waitqueue_head(&wsm->ws_wait);
f77dd0d6 916
1666edab
DZ
917 /*
918 * Preallocate one workspace for each compression type so we can
919 * guarantee forward progress in the worst case
920 */
c778df14 921 workspace = alloc_workspace(type, 0);
1666edab
DZ
922 if (IS_ERR(workspace)) {
923 pr_warn(
924 "BTRFS: cannot preallocate compression workspace, will try later\n");
925 } else {
92ee5530
DZ
926 atomic_set(&wsm->total_ws, 1);
927 wsm->free_ws = 1;
928 list_add(workspace, &wsm->idle_ws);
1666edab
DZ
929 }
930}
931
2510307e 932static void btrfs_cleanup_workspace_manager(int type)
1666edab 933{
2dba7143 934 struct workspace_manager *wsman;
1666edab
DZ
935 struct list_head *ws;
936
2dba7143 937 wsman = btrfs_compress_op[type]->workspace_manager;
1666edab
DZ
938 while (!list_empty(&wsman->idle_ws)) {
939 ws = wsman->idle_ws.next;
940 list_del(ws);
1e002351 941 free_workspace(type, ws);
1666edab 942 atomic_dec(&wsman->total_ws);
261507a0 943 }
261507a0
LZ
944}
945
946/*
e721e49d
DS
947 * This finds an available workspace or allocates a new one.
948 * If it's not possible to allocate a new one, waits until there's one.
949 * Preallocation makes a forward progress guarantees and we do not return
950 * errors.
261507a0 951 */
5907a9bb 952struct list_head *btrfs_get_workspace(int type, unsigned int level)
261507a0 953{
5907a9bb 954 struct workspace_manager *wsm;
261507a0
LZ
955 struct list_head *workspace;
956 int cpus = num_online_cpus();
fe308533 957 unsigned nofs_flag;
4e439a0b
TT
958 struct list_head *idle_ws;
959 spinlock_t *ws_lock;
960 atomic_t *total_ws;
961 wait_queue_head_t *ws_wait;
962 int *free_ws;
963
5907a9bb 964 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
965 idle_ws = &wsm->idle_ws;
966 ws_lock = &wsm->ws_lock;
967 total_ws = &wsm->total_ws;
968 ws_wait = &wsm->ws_wait;
969 free_ws = &wsm->free_ws;
261507a0 970
261507a0 971again:
d9187649
BL
972 spin_lock(ws_lock);
973 if (!list_empty(idle_ws)) {
974 workspace = idle_ws->next;
261507a0 975 list_del(workspace);
6ac10a6a 976 (*free_ws)--;
d9187649 977 spin_unlock(ws_lock);
261507a0
LZ
978 return workspace;
979
980 }
6ac10a6a 981 if (atomic_read(total_ws) > cpus) {
261507a0
LZ
982 DEFINE_WAIT(wait);
983
d9187649
BL
984 spin_unlock(ws_lock);
985 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
6ac10a6a 986 if (atomic_read(total_ws) > cpus && !*free_ws)
261507a0 987 schedule();
d9187649 988 finish_wait(ws_wait, &wait);
261507a0
LZ
989 goto again;
990 }
6ac10a6a 991 atomic_inc(total_ws);
d9187649 992 spin_unlock(ws_lock);
261507a0 993
fe308533
DS
994 /*
995 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
996 * to turn it off here because we might get called from the restricted
997 * context of btrfs_compress_bio/btrfs_compress_pages
998 */
999 nofs_flag = memalloc_nofs_save();
c778df14 1000 workspace = alloc_workspace(type, level);
fe308533
DS
1001 memalloc_nofs_restore(nofs_flag);
1002
261507a0 1003 if (IS_ERR(workspace)) {
6ac10a6a 1004 atomic_dec(total_ws);
d9187649 1005 wake_up(ws_wait);
e721e49d
DS
1006
1007 /*
1008 * Do not return the error but go back to waiting. There's a
1009 * workspace preallocated for each type and the compression
1010 * time is bounded so we get to a workspace eventually. This
1011 * makes our caller's life easier.
52356716
DS
1012 *
1013 * To prevent silent and low-probability deadlocks (when the
1014 * initial preallocation fails), check if there are any
1015 * workspaces at all.
e721e49d 1016 */
52356716
DS
1017 if (atomic_read(total_ws) == 0) {
1018 static DEFINE_RATELIMIT_STATE(_rs,
1019 /* once per minute */ 60 * HZ,
1020 /* no burst */ 1);
1021
1022 if (__ratelimit(&_rs)) {
ab8d0fc4 1023 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
52356716
DS
1024 }
1025 }
e721e49d 1026 goto again;
261507a0
LZ
1027 }
1028 return workspace;
1029}
1030
7bf49943 1031static struct list_head *get_workspace(int type, int level)
929f4baf 1032{
6a0d1272 1033 switch (type) {
5907a9bb 1034 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
6a0d1272 1035 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
5907a9bb 1036 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
6a0d1272
DS
1037 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1038 default:
1039 /*
1040 * This can't happen, the type is validated several times
1041 * before we get here.
1042 */
1043 BUG();
1044 }
929f4baf
DZ
1045}
1046
261507a0
LZ
1047/*
1048 * put a workspace struct back on the list or free it if we have enough
1049 * idle ones sitting around
1050 */
a3bbd2a9 1051void btrfs_put_workspace(int type, struct list_head *ws)
261507a0 1052{
a3bbd2a9 1053 struct workspace_manager *wsm;
4e439a0b
TT
1054 struct list_head *idle_ws;
1055 spinlock_t *ws_lock;
1056 atomic_t *total_ws;
1057 wait_queue_head_t *ws_wait;
1058 int *free_ws;
1059
a3bbd2a9 1060 wsm = btrfs_compress_op[type]->workspace_manager;
92ee5530
DZ
1061 idle_ws = &wsm->idle_ws;
1062 ws_lock = &wsm->ws_lock;
1063 total_ws = &wsm->total_ws;
1064 ws_wait = &wsm->ws_wait;
1065 free_ws = &wsm->free_ws;
d9187649
BL
1066
1067 spin_lock(ws_lock);
26b28dce 1068 if (*free_ws <= num_online_cpus()) {
929f4baf 1069 list_add(ws, idle_ws);
6ac10a6a 1070 (*free_ws)++;
d9187649 1071 spin_unlock(ws_lock);
261507a0
LZ
1072 goto wake;
1073 }
d9187649 1074 spin_unlock(ws_lock);
261507a0 1075
1e002351 1076 free_workspace(type, ws);
6ac10a6a 1077 atomic_dec(total_ws);
261507a0 1078wake:
093258e6 1079 cond_wake_up(ws_wait);
261507a0
LZ
1080}
1081
929f4baf
DZ
1082static void put_workspace(int type, struct list_head *ws)
1083{
bd3a5287 1084 switch (type) {
a3bbd2a9
DS
1085 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1086 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1087 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
bd3a5287
DS
1088 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1089 default:
1090 /*
1091 * This can't happen, the type is validated several times
1092 * before we get here.
1093 */
1094 BUG();
1095 }
929f4baf
DZ
1096}
1097
adbab642
AJ
1098/*
1099 * Adjust @level according to the limits of the compression algorithm or
1100 * fallback to default
1101 */
1102static unsigned int btrfs_compress_set_level(int type, unsigned level)
1103{
1104 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1105
1106 if (level == 0)
1107 level = ops->default_level;
1108 else
1109 level = min(level, ops->max_level);
1110
1111 return level;
1112}
1113
261507a0 1114/*
38c31464
DS
1115 * Given an address space and start and length, compress the bytes into @pages
1116 * that are allocated on demand.
261507a0 1117 *
f51d2b59
DS
1118 * @type_level is encoded algorithm and level, where level 0 means whatever
1119 * default the algorithm chooses and is opaque here;
1120 * - compression algo are 0-3
1121 * - the level are bits 4-7
1122 *
4d3a800e
DS
1123 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1124 * and returns number of actually allocated pages
261507a0 1125 *
38c31464
DS
1126 * @total_in is used to return the number of bytes actually read. It
1127 * may be smaller than the input length if we had to exit early because we
261507a0
LZ
1128 * ran out of room in the pages array or because we cross the
1129 * max_out threshold.
1130 *
38c31464
DS
1131 * @total_out is an in/out parameter, must be set to the input length and will
1132 * be also used to return the total number of compressed bytes
261507a0 1133 *
38c31464 1134 * @max_out tells us the max number of bytes that we're allowed to
261507a0
LZ
1135 * stuff into pages
1136 */
f51d2b59 1137int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
38c31464 1138 u64 start, struct page **pages,
261507a0
LZ
1139 unsigned long *out_pages,
1140 unsigned long *total_in,
e5d74902 1141 unsigned long *total_out)
261507a0 1142{
1972708a 1143 int type = btrfs_compress_type(type_level);
7bf49943 1144 int level = btrfs_compress_level(type_level);
261507a0
LZ
1145 struct list_head *workspace;
1146 int ret;
1147
b0c1fe1e 1148 level = btrfs_compress_set_level(type, level);
7bf49943 1149 workspace = get_workspace(type, level);
1e4eb746
DS
1150 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1151 out_pages, total_in, total_out);
929f4baf 1152 put_workspace(type, workspace);
261507a0
LZ
1153 return ret;
1154}
1155
1156/*
1157 * pages_in is an array of pages with compressed data.
1158 *
1159 * disk_start is the starting logical offset of this array in the file
1160 *
974b1adc 1161 * orig_bio contains the pages from the file that we want to decompress into
261507a0
LZ
1162 *
1163 * srclen is the number of bytes in pages_in
1164 *
1165 * The basic idea is that we have a bio that was created by readpages.
1166 * The pages in the bio are for the uncompressed data, and they may not
1167 * be contiguous. They all correspond to the range of bytes covered by
1168 * the compressed extent.
1169 */
8140dc30 1170static int btrfs_decompress_bio(struct compressed_bio *cb)
261507a0
LZ
1171{
1172 struct list_head *workspace;
1173 int ret;
8140dc30 1174 int type = cb->compress_type;
261507a0 1175
7bf49943 1176 workspace = get_workspace(type, 0);
1e4eb746 1177 ret = compression_decompress_bio(type, workspace, cb);
929f4baf 1178 put_workspace(type, workspace);
e1ddce71 1179
261507a0
LZ
1180 return ret;
1181}
1182
1183/*
1184 * a less complex decompression routine. Our compressed data fits in a
1185 * single page, and we want to read a single page out of it.
1186 * start_byte tells us the offset into the compressed data we're interested in
1187 */
1188int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1189 unsigned long start_byte, size_t srclen, size_t destlen)
1190{
1191 struct list_head *workspace;
1192 int ret;
1193
7bf49943 1194 workspace = get_workspace(type, 0);
1e4eb746
DS
1195 ret = compression_decompress(type, workspace, data_in, dest_page,
1196 start_byte, srclen, destlen);
929f4baf 1197 put_workspace(type, workspace);
7bf49943 1198
261507a0
LZ
1199 return ret;
1200}
1201
1666edab
DZ
1202void __init btrfs_init_compress(void)
1203{
d5517033
DS
1204 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1205 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1206 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1207 zstd_init_workspace_manager();
1666edab
DZ
1208}
1209
e67c718b 1210void __cold btrfs_exit_compress(void)
261507a0 1211{
2510307e
DS
1212 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1213 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1214 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1215 zstd_cleanup_workspace_manager();
261507a0 1216}
3a39c18d
LZ
1217
1218/*
1219 * Copy uncompressed data from working buffer to pages.
1220 *
1221 * buf_start is the byte offset we're of the start of our workspace buffer.
1222 *
1223 * total_out is the last byte of the buffer
1224 */
14a3357b 1225int btrfs_decompress_buf2page(const char *buf, unsigned long buf_start,
3a39c18d 1226 unsigned long total_out, u64 disk_start,
974b1adc 1227 struct bio *bio)
3a39c18d
LZ
1228{
1229 unsigned long buf_offset;
1230 unsigned long current_buf_start;
1231 unsigned long start_byte;
6e78b3f7 1232 unsigned long prev_start_byte;
3a39c18d
LZ
1233 unsigned long working_bytes = total_out - buf_start;
1234 unsigned long bytes;
1235 char *kaddr;
974b1adc 1236 struct bio_vec bvec = bio_iter_iovec(bio, bio->bi_iter);
3a39c18d
LZ
1237
1238 /*
1239 * start byte is the first byte of the page we're currently
1240 * copying into relative to the start of the compressed data.
1241 */
974b1adc 1242 start_byte = page_offset(bvec.bv_page) - disk_start;
3a39c18d
LZ
1243
1244 /* we haven't yet hit data corresponding to this page */
1245 if (total_out <= start_byte)
1246 return 1;
1247
1248 /*
1249 * the start of the data we care about is offset into
1250 * the middle of our working buffer
1251 */
1252 if (total_out > start_byte && buf_start < start_byte) {
1253 buf_offset = start_byte - buf_start;
1254 working_bytes -= buf_offset;
1255 } else {
1256 buf_offset = 0;
1257 }
1258 current_buf_start = buf_start;
1259
1260 /* copy bytes from the working buffer into the pages */
1261 while (working_bytes > 0) {
974b1adc 1262 bytes = min_t(unsigned long, bvec.bv_len,
3fd396af 1263 PAGE_SIZE - (buf_offset % PAGE_SIZE));
3a39c18d 1264 bytes = min(bytes, working_bytes);
974b1adc
CH
1265
1266 kaddr = kmap_atomic(bvec.bv_page);
1267 memcpy(kaddr + bvec.bv_offset, buf + buf_offset, bytes);
7ac687d9 1268 kunmap_atomic(kaddr);
974b1adc 1269 flush_dcache_page(bvec.bv_page);
3a39c18d 1270
3a39c18d
LZ
1271 buf_offset += bytes;
1272 working_bytes -= bytes;
1273 current_buf_start += bytes;
1274
1275 /* check if we need to pick another page */
974b1adc
CH
1276 bio_advance(bio, bytes);
1277 if (!bio->bi_iter.bi_size)
1278 return 0;
1279 bvec = bio_iter_iovec(bio, bio->bi_iter);
6e78b3f7 1280 prev_start_byte = start_byte;
974b1adc 1281 start_byte = page_offset(bvec.bv_page) - disk_start;
3a39c18d 1282
974b1adc 1283 /*
6e78b3f7
OS
1284 * We need to make sure we're only adjusting
1285 * our offset into compression working buffer when
1286 * we're switching pages. Otherwise we can incorrectly
1287 * keep copying when we were actually done.
974b1adc 1288 */
6e78b3f7
OS
1289 if (start_byte != prev_start_byte) {
1290 /*
1291 * make sure our new page is covered by this
1292 * working buffer
1293 */
1294 if (total_out <= start_byte)
1295 return 1;
3a39c18d 1296
6e78b3f7
OS
1297 /*
1298 * the next page in the biovec might not be adjacent
1299 * to the last page, but it might still be found
1300 * inside this working buffer. bump our offset pointer
1301 */
1302 if (total_out > start_byte &&
1303 current_buf_start < start_byte) {
1304 buf_offset = start_byte - buf_start;
1305 working_bytes = total_out - start_byte;
1306 current_buf_start = buf_start + buf_offset;
1307 }
3a39c18d
LZ
1308 }
1309 }
1310
1311 return 1;
1312}
c2fcdcdf 1313
19562430
TT
1314/*
1315 * Shannon Entropy calculation
1316 *
52042d8e 1317 * Pure byte distribution analysis fails to determine compressibility of data.
19562430
TT
1318 * Try calculating entropy to estimate the average minimum number of bits
1319 * needed to encode the sampled data.
1320 *
1321 * For convenience, return the percentage of needed bits, instead of amount of
1322 * bits directly.
1323 *
1324 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1325 * and can be compressible with high probability
1326 *
1327 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1328 *
1329 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1330 */
1331#define ENTROPY_LVL_ACEPTABLE (65)
1332#define ENTROPY_LVL_HIGH (80)
1333
1334/*
1335 * For increasead precision in shannon_entropy calculation,
1336 * let's do pow(n, M) to save more digits after comma:
1337 *
1338 * - maximum int bit length is 64
1339 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1340 * - 13 * 4 = 52 < 64 -> M = 4
1341 *
1342 * So use pow(n, 4).
1343 */
1344static inline u32 ilog2_w(u64 n)
1345{
1346 return ilog2(n * n * n * n);
1347}
1348
1349static u32 shannon_entropy(struct heuristic_ws *ws)
1350{
1351 const u32 entropy_max = 8 * ilog2_w(2);
1352 u32 entropy_sum = 0;
1353 u32 p, p_base, sz_base;
1354 u32 i;
1355
1356 sz_base = ilog2_w(ws->sample_size);
1357 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1358 p = ws->bucket[i].count;
1359 p_base = ilog2_w(p);
1360 entropy_sum += p * (sz_base - p_base);
1361 }
1362
1363 entropy_sum /= ws->sample_size;
1364 return entropy_sum * 100 / entropy_max;
1365}
1366
440c840c
TT
1367#define RADIX_BASE 4U
1368#define COUNTERS_SIZE (1U << RADIX_BASE)
1369
1370static u8 get4bits(u64 num, int shift) {
1371 u8 low4bits;
1372
1373 num >>= shift;
1374 /* Reverse order */
1375 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1376 return low4bits;
1377}
1378
440c840c
TT
1379/*
1380 * Use 4 bits as radix base
52042d8e 1381 * Use 16 u32 counters for calculating new position in buf array
440c840c
TT
1382 *
1383 * @array - array that will be sorted
1384 * @array_buf - buffer array to store sorting results
1385 * must be equal in size to @array
1386 * @num - array size
440c840c 1387 */
23ae8c63 1388static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
36243c91 1389 int num)
858177d3 1390{
440c840c
TT
1391 u64 max_num;
1392 u64 buf_num;
1393 u32 counters[COUNTERS_SIZE];
1394 u32 new_addr;
1395 u32 addr;
1396 int bitlen;
1397 int shift;
1398 int i;
858177d3 1399
440c840c
TT
1400 /*
1401 * Try avoid useless loop iterations for small numbers stored in big
1402 * counters. Example: 48 33 4 ... in 64bit array
1403 */
23ae8c63 1404 max_num = array[0].count;
440c840c 1405 for (i = 1; i < num; i++) {
23ae8c63 1406 buf_num = array[i].count;
440c840c
TT
1407 if (buf_num > max_num)
1408 max_num = buf_num;
1409 }
1410
1411 buf_num = ilog2(max_num);
1412 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1413
1414 shift = 0;
1415 while (shift < bitlen) {
1416 memset(counters, 0, sizeof(counters));
1417
1418 for (i = 0; i < num; i++) {
23ae8c63 1419 buf_num = array[i].count;
440c840c
TT
1420 addr = get4bits(buf_num, shift);
1421 counters[addr]++;
1422 }
1423
1424 for (i = 1; i < COUNTERS_SIZE; i++)
1425 counters[i] += counters[i - 1];
1426
1427 for (i = num - 1; i >= 0; i--) {
23ae8c63 1428 buf_num = array[i].count;
440c840c
TT
1429 addr = get4bits(buf_num, shift);
1430 counters[addr]--;
1431 new_addr = counters[addr];
7add17be 1432 array_buf[new_addr] = array[i];
440c840c
TT
1433 }
1434
1435 shift += RADIX_BASE;
1436
1437 /*
1438 * Normal radix expects to move data from a temporary array, to
1439 * the main one. But that requires some CPU time. Avoid that
1440 * by doing another sort iteration to original array instead of
1441 * memcpy()
1442 */
1443 memset(counters, 0, sizeof(counters));
1444
1445 for (i = 0; i < num; i ++) {
23ae8c63 1446 buf_num = array_buf[i].count;
440c840c
TT
1447 addr = get4bits(buf_num, shift);
1448 counters[addr]++;
1449 }
1450
1451 for (i = 1; i < COUNTERS_SIZE; i++)
1452 counters[i] += counters[i - 1];
1453
1454 for (i = num - 1; i >= 0; i--) {
23ae8c63 1455 buf_num = array_buf[i].count;
440c840c
TT
1456 addr = get4bits(buf_num, shift);
1457 counters[addr]--;
1458 new_addr = counters[addr];
7add17be 1459 array[new_addr] = array_buf[i];
440c840c
TT
1460 }
1461
1462 shift += RADIX_BASE;
1463 }
858177d3
TT
1464}
1465
1466/*
1467 * Size of the core byte set - how many bytes cover 90% of the sample
1468 *
1469 * There are several types of structured binary data that use nearly all byte
1470 * values. The distribution can be uniform and counts in all buckets will be
1471 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1472 *
1473 * Other possibility is normal (Gaussian) distribution, where the data could
1474 * be potentially compressible, but we have to take a few more steps to decide
1475 * how much.
1476 *
1477 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1478 * compression algo can easy fix that
1479 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1480 * probability is not compressible
1481 */
1482#define BYTE_CORE_SET_LOW (64)
1483#define BYTE_CORE_SET_HIGH (200)
1484
1485static int byte_core_set_size(struct heuristic_ws *ws)
1486{
1487 u32 i;
1488 u32 coreset_sum = 0;
1489 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1490 struct bucket_item *bucket = ws->bucket;
1491
1492 /* Sort in reverse order */
36243c91 1493 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
858177d3
TT
1494
1495 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1496 coreset_sum += bucket[i].count;
1497
1498 if (coreset_sum > core_set_threshold)
1499 return i;
1500
1501 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1502 coreset_sum += bucket[i].count;
1503 if (coreset_sum > core_set_threshold)
1504 break;
1505 }
1506
1507 return i;
1508}
1509
a288e92c
TT
1510/*
1511 * Count byte values in buckets.
1512 * This heuristic can detect textual data (configs, xml, json, html, etc).
1513 * Because in most text-like data byte set is restricted to limited number of
1514 * possible characters, and that restriction in most cases makes data easy to
1515 * compress.
1516 *
1517 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1518 * less - compressible
1519 * more - need additional analysis
1520 */
1521#define BYTE_SET_THRESHOLD (64)
1522
1523static u32 byte_set_size(const struct heuristic_ws *ws)
1524{
1525 u32 i;
1526 u32 byte_set_size = 0;
1527
1528 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1529 if (ws->bucket[i].count > 0)
1530 byte_set_size++;
1531 }
1532
1533 /*
1534 * Continue collecting count of byte values in buckets. If the byte
1535 * set size is bigger then the threshold, it's pointless to continue,
1536 * the detection technique would fail for this type of data.
1537 */
1538 for (; i < BUCKET_SIZE; i++) {
1539 if (ws->bucket[i].count > 0) {
1540 byte_set_size++;
1541 if (byte_set_size > BYTE_SET_THRESHOLD)
1542 return byte_set_size;
1543 }
1544 }
1545
1546 return byte_set_size;
1547}
1548
1fe4f6fa
TT
1549static bool sample_repeated_patterns(struct heuristic_ws *ws)
1550{
1551 const u32 half_of_sample = ws->sample_size / 2;
1552 const u8 *data = ws->sample;
1553
1554 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1555}
1556
a440d48c
TT
1557static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1558 struct heuristic_ws *ws)
1559{
1560 struct page *page;
1561 u64 index, index_end;
1562 u32 i, curr_sample_pos;
1563 u8 *in_data;
1564
1565 /*
1566 * Compression handles the input data by chunks of 128KiB
1567 * (defined by BTRFS_MAX_UNCOMPRESSED)
1568 *
1569 * We do the same for the heuristic and loop over the whole range.
1570 *
1571 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1572 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1573 */
1574 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1575 end = start + BTRFS_MAX_UNCOMPRESSED;
1576
1577 index = start >> PAGE_SHIFT;
1578 index_end = end >> PAGE_SHIFT;
1579
1580 /* Don't miss unaligned end */
1581 if (!IS_ALIGNED(end, PAGE_SIZE))
1582 index_end++;
1583
1584 curr_sample_pos = 0;
1585 while (index < index_end) {
1586 page = find_get_page(inode->i_mapping, index);
1587 in_data = kmap(page);
1588 /* Handle case where the start is not aligned to PAGE_SIZE */
1589 i = start % PAGE_SIZE;
1590 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1591 /* Don't sample any garbage from the last page */
1592 if (start > end - SAMPLING_READ_SIZE)
1593 break;
1594 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1595 SAMPLING_READ_SIZE);
1596 i += SAMPLING_INTERVAL;
1597 start += SAMPLING_INTERVAL;
1598 curr_sample_pos += SAMPLING_READ_SIZE;
1599 }
1600 kunmap(page);
1601 put_page(page);
1602
1603 index++;
1604 }
1605
1606 ws->sample_size = curr_sample_pos;
1607}
1608
c2fcdcdf
TT
1609/*
1610 * Compression heuristic.
1611 *
1612 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1613 * quickly (compared to direct compression) detect data characteristics
1614 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1615 * data.
1616 *
1617 * The following types of analysis can be performed:
1618 * - detect mostly zero data
1619 * - detect data with low "byte set" size (text, etc)
1620 * - detect data with low/high "core byte" set
1621 *
1622 * Return non-zero if the compression should be done, 0 otherwise.
1623 */
1624int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1625{
7bf49943 1626 struct list_head *ws_list = get_workspace(0, 0);
4e439a0b 1627 struct heuristic_ws *ws;
a440d48c
TT
1628 u32 i;
1629 u8 byte;
19562430 1630 int ret = 0;
c2fcdcdf 1631
4e439a0b
TT
1632 ws = list_entry(ws_list, struct heuristic_ws, list);
1633
a440d48c
TT
1634 heuristic_collect_sample(inode, start, end, ws);
1635
1fe4f6fa
TT
1636 if (sample_repeated_patterns(ws)) {
1637 ret = 1;
1638 goto out;
1639 }
1640
a440d48c
TT
1641 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1642
1643 for (i = 0; i < ws->sample_size; i++) {
1644 byte = ws->sample[i];
1645 ws->bucket[byte].count++;
c2fcdcdf
TT
1646 }
1647
a288e92c
TT
1648 i = byte_set_size(ws);
1649 if (i < BYTE_SET_THRESHOLD) {
1650 ret = 2;
1651 goto out;
1652 }
1653
858177d3
TT
1654 i = byte_core_set_size(ws);
1655 if (i <= BYTE_CORE_SET_LOW) {
1656 ret = 3;
1657 goto out;
1658 }
1659
1660 if (i >= BYTE_CORE_SET_HIGH) {
1661 ret = 0;
1662 goto out;
1663 }
1664
19562430
TT
1665 i = shannon_entropy(ws);
1666 if (i <= ENTROPY_LVL_ACEPTABLE) {
1667 ret = 4;
1668 goto out;
1669 }
1670
1671 /*
1672 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1673 * needed to give green light to compression.
1674 *
1675 * For now just assume that compression at that level is not worth the
1676 * resources because:
1677 *
1678 * 1. it is possible to defrag the data later
1679 *
1680 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1681 * values, every bucket has counter at level ~54. The heuristic would
1682 * be confused. This can happen when data have some internal repeated
1683 * patterns like "abbacbbc...". This can be detected by analyzing
1684 * pairs of bytes, which is too costly.
1685 */
1686 if (i < ENTROPY_LVL_HIGH) {
1687 ret = 5;
1688 goto out;
1689 } else {
1690 ret = 0;
1691 goto out;
1692 }
1693
1fe4f6fa 1694out:
929f4baf 1695 put_workspace(0, ws_list);
c2fcdcdf
TT
1696 return ret;
1697}
f51d2b59 1698
d0ab62ce
DZ
1699/*
1700 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1701 * level, unrecognized string will set the default level
1702 */
1703unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
f51d2b59 1704{
d0ab62ce
DZ
1705 unsigned int level = 0;
1706 int ret;
1707
1708 if (!type)
f51d2b59
DS
1709 return 0;
1710
d0ab62ce
DZ
1711 if (str[0] == ':') {
1712 ret = kstrtouint(str + 1, 10, &level);
1713 if (ret)
1714 level = 0;
1715 }
1716
b0c1fe1e
DS
1717 level = btrfs_compress_set_level(type, level);
1718
1719 return level;
1720}