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