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