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