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