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