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