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