~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/compression.c

Version: ~ [ linux-5.15-rc1 ] ~ [ linux-5.14.5 ] ~ [ linux-5.13.18 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.66 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.147 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.206 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.246 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.282 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.283 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp