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