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