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