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