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