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