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