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