2ea5cf5ae210017dd97931412fe6a5770e207f5a
[linux-2.6-microblaze.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/kthread.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/slab.h>
19 #include <linux/sched/mm.h>
20 #include <linux/log2.h>
21 #include <crypto/hash.h>
22 #include "misc.h"
23 #include "ctree.h"
24 #include "disk-io.h"
25 #include "transaction.h"
26 #include "btrfs_inode.h"
27 #include "volumes.h"
28 #include "ordered-data.h"
29 #include "compression.h"
30 #include "extent_io.h"
31 #include "extent_map.h"
32 #include "subpage.h"
33 #include "zoned.h"
34
35 static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
36
37 const char* btrfs_compress_type2str(enum btrfs_compression_type type)
38 {
39         switch (type) {
40         case BTRFS_COMPRESS_ZLIB:
41         case BTRFS_COMPRESS_LZO:
42         case BTRFS_COMPRESS_ZSTD:
43         case BTRFS_COMPRESS_NONE:
44                 return btrfs_compress_types[type];
45         default:
46                 break;
47         }
48
49         return NULL;
50 }
51
52 bool btrfs_compress_is_valid_type(const char *str, size_t len)
53 {
54         int i;
55
56         for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
57                 size_t comp_len = strlen(btrfs_compress_types[i]);
58
59                 if (len < comp_len)
60                         continue;
61
62                 if (!strncmp(btrfs_compress_types[i], str, comp_len))
63                         return true;
64         }
65         return false;
66 }
67
68 static int compression_compress_pages(int type, struct list_head *ws,
69                struct address_space *mapping, u64 start, struct page **pages,
70                unsigned long *out_pages, unsigned long *total_in,
71                unsigned long *total_out)
72 {
73         switch (type) {
74         case BTRFS_COMPRESS_ZLIB:
75                 return zlib_compress_pages(ws, mapping, start, pages,
76                                 out_pages, total_in, total_out);
77         case BTRFS_COMPRESS_LZO:
78                 return lzo_compress_pages(ws, mapping, start, pages,
79                                 out_pages, total_in, total_out);
80         case BTRFS_COMPRESS_ZSTD:
81                 return zstd_compress_pages(ws, mapping, start, pages,
82                                 out_pages, total_in, total_out);
83         case BTRFS_COMPRESS_NONE:
84         default:
85                 /*
86                  * This can happen when compression races with remount setting
87                  * it to 'no compress', while caller doesn't call
88                  * inode_need_compress() to check if we really need to
89                  * compress.
90                  *
91                  * Not a big deal, just need to inform caller that we
92                  * haven't allocated any pages yet.
93                  */
94                 *out_pages = 0;
95                 return -E2BIG;
96         }
97 }
98
99 static int compression_decompress_bio(struct list_head *ws,
100                                       struct compressed_bio *cb)
101 {
102         switch (cb->compress_type) {
103         case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
104         case BTRFS_COMPRESS_LZO:  return lzo_decompress_bio(ws, cb);
105         case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
106         case BTRFS_COMPRESS_NONE:
107         default:
108                 /*
109                  * This can't happen, the type is validated several times
110                  * before we get here.
111                  */
112                 BUG();
113         }
114 }
115
116 static int compression_decompress(int type, struct list_head *ws,
117                unsigned char *data_in, struct page *dest_page,
118                unsigned long start_byte, size_t srclen, size_t destlen)
119 {
120         switch (type) {
121         case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
122                                                 start_byte, srclen, destlen);
123         case BTRFS_COMPRESS_LZO:  return lzo_decompress(ws, data_in, dest_page,
124                                                 start_byte, srclen, destlen);
125         case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
126                                                 start_byte, srclen, destlen);
127         case BTRFS_COMPRESS_NONE:
128         default:
129                 /*
130                  * This can't happen, the type is validated several times
131                  * before we get here.
132                  */
133                 BUG();
134         }
135 }
136
137 static int btrfs_decompress_bio(struct compressed_bio *cb);
138
139 static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
140                                       unsigned long disk_size)
141 {
142         return sizeof(struct compressed_bio) +
143                 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
144 }
145
146 static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
147                                  u64 disk_start)
148 {
149         struct btrfs_fs_info *fs_info = inode->root->fs_info;
150         const u32 csum_size = fs_info->csum_size;
151         const u32 sectorsize = fs_info->sectorsize;
152         struct page *page;
153         unsigned int i;
154         u8 csum[BTRFS_CSUM_SIZE];
155         struct compressed_bio *cb = bio->bi_private;
156         u8 *cb_sum = cb->sums;
157
158         if ((inode->flags & BTRFS_INODE_NODATASUM) ||
159             test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state))
160                 return 0;
161
162         for (i = 0; i < cb->nr_pages; i++) {
163                 u32 pg_offset;
164                 u32 bytes_left = PAGE_SIZE;
165                 page = cb->compressed_pages[i];
166
167                 /* Determine the remaining bytes inside the page first */
168                 if (i == cb->nr_pages - 1)
169                         bytes_left = cb->compressed_len - i * PAGE_SIZE;
170
171                 /* Hash through the page sector by sector */
172                 for (pg_offset = 0; pg_offset < bytes_left;
173                      pg_offset += sectorsize) {
174                         int ret;
175
176                         ret = btrfs_check_sector_csum(fs_info, page, pg_offset,
177                                                       csum, cb_sum);
178                         if (ret) {
179                                 btrfs_print_data_csum_error(inode, disk_start,
180                                                 csum, cb_sum, cb->mirror_num);
181                                 if (btrfs_bio(bio)->device)
182                                         btrfs_dev_stat_inc_and_print(
183                                                 btrfs_bio(bio)->device,
184                                                 BTRFS_DEV_STAT_CORRUPTION_ERRS);
185                                 return -EIO;
186                         }
187                         cb_sum += csum_size;
188                         disk_start += sectorsize;
189                 }
190         }
191         return 0;
192 }
193
194 /*
195  * Reduce bio and io accounting for a compressed_bio with its corresponding bio.
196  *
197  * Return true if there is no pending bio nor io.
198  * Return false otherwise.
199  */
200 static bool dec_and_test_compressed_bio(struct compressed_bio *cb, struct bio *bio)
201 {
202         struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
203         unsigned int bi_size = 0;
204         bool last_io = false;
205         struct bio_vec *bvec;
206         struct bvec_iter_all iter_all;
207
208         /*
209          * At endio time, bi_iter.bi_size doesn't represent the real bio size.
210          * Thus here we have to iterate through all segments to grab correct
211          * bio size.
212          */
213         bio_for_each_segment_all(bvec, bio, iter_all)
214                 bi_size += bvec->bv_len;
215
216         if (bio->bi_status)
217                 cb->status = bio->bi_status;
218
219         ASSERT(bi_size && bi_size <= cb->compressed_len);
220         last_io = refcount_sub_and_test(bi_size >> fs_info->sectorsize_bits,
221                                         &cb->pending_sectors);
222         /*
223          * Here we must wake up the possible error handler after all other
224          * operations on @cb finished, or we can race with
225          * finish_compressed_bio_*() which may free @cb.
226          */
227         wake_up_var(cb);
228
229         return last_io;
230 }
231
232 static void finish_compressed_bio_read(struct compressed_bio *cb)
233 {
234         unsigned int index;
235         struct page *page;
236
237         /* Release the compressed pages */
238         for (index = 0; index < cb->nr_pages; index++) {
239                 page = cb->compressed_pages[index];
240                 page->mapping = NULL;
241                 put_page(page);
242         }
243
244         /* Do io completion on the original bio */
245         if (cb->status != BLK_STS_OK) {
246                 cb->orig_bio->bi_status = cb->status;
247                 bio_endio(cb->orig_bio);
248         } else {
249                 struct bio_vec *bvec;
250                 struct bvec_iter_all iter_all;
251
252                 /*
253                  * We have verified the checksum already, set page checked so
254                  * the end_io handlers know about it
255                  */
256                 ASSERT(!bio_flagged(cb->orig_bio, BIO_CLONED));
257                 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all) {
258                         u64 bvec_start = page_offset(bvec->bv_page) +
259                                          bvec->bv_offset;
260
261                         btrfs_page_set_checked(btrfs_sb(cb->inode->i_sb),
262                                         bvec->bv_page, bvec_start,
263                                         bvec->bv_len);
264                 }
265
266                 bio_endio(cb->orig_bio);
267         }
268
269         /* Finally free the cb struct */
270         kfree(cb->compressed_pages);
271         kfree(cb);
272 }
273
274 /* when we finish reading compressed pages from the disk, we
275  * decompress them and then run the bio end_io routines on the
276  * decompressed pages (in the inode address space).
277  *
278  * This allows the checksumming and other IO error handling routines
279  * to work normally
280  *
281  * The compressed pages are freed here, and it must be run
282  * in process context
283  */
284 static void end_compressed_bio_read(struct bio *bio)
285 {
286         struct compressed_bio *cb = bio->bi_private;
287         struct inode *inode;
288         unsigned int mirror = btrfs_bio(bio)->mirror_num;
289         int ret = 0;
290
291         if (!dec_and_test_compressed_bio(cb, bio))
292                 goto out;
293
294         /*
295          * Record the correct mirror_num in cb->orig_bio so that
296          * read-repair can work properly.
297          */
298         btrfs_bio(cb->orig_bio)->mirror_num = mirror;
299         cb->mirror_num = mirror;
300
301         /*
302          * Some IO in this cb have failed, just skip checksum as there
303          * is no way it could be correct.
304          */
305         if (cb->status != BLK_STS_OK)
306                 goto csum_failed;
307
308         inode = cb->inode;
309         ret = check_compressed_csum(BTRFS_I(inode), bio,
310                                     bio->bi_iter.bi_sector << 9);
311         if (ret)
312                 goto csum_failed;
313
314         /* ok, we're the last bio for this extent, lets start
315          * the decompression.
316          */
317         ret = btrfs_decompress_bio(cb);
318
319 csum_failed:
320         if (ret)
321                 cb->status = errno_to_blk_status(ret);
322         finish_compressed_bio_read(cb);
323 out:
324         bio_put(bio);
325 }
326
327 /*
328  * Clear the writeback bits on all of the file
329  * pages for a compressed write
330  */
331 static noinline void end_compressed_writeback(struct inode *inode,
332                                               const struct compressed_bio *cb)
333 {
334         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
335         unsigned long index = cb->start >> PAGE_SHIFT;
336         unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
337         struct page *pages[16];
338         unsigned long nr_pages = end_index - index + 1;
339         const int errno = blk_status_to_errno(cb->status);
340         int i;
341         int ret;
342
343         if (errno)
344                 mapping_set_error(inode->i_mapping, errno);
345
346         while (nr_pages > 0) {
347                 ret = find_get_pages_contig(inode->i_mapping, index,
348                                      min_t(unsigned long,
349                                      nr_pages, ARRAY_SIZE(pages)), pages);
350                 if (ret == 0) {
351                         nr_pages -= 1;
352                         index += 1;
353                         continue;
354                 }
355                 for (i = 0; i < ret; i++) {
356                         if (errno)
357                                 SetPageError(pages[i]);
358                         btrfs_page_clamp_clear_writeback(fs_info, pages[i],
359                                                          cb->start, cb->len);
360                         put_page(pages[i]);
361                 }
362                 nr_pages -= ret;
363                 index += ret;
364         }
365         /* the inode may be gone now */
366 }
367
368 static void finish_compressed_bio_write(struct compressed_bio *cb)
369 {
370         struct inode *inode = cb->inode;
371         unsigned int index;
372
373         /*
374          * Ok, we're the last bio for this extent, step one is to call back
375          * into the FS and do all the end_io operations.
376          */
377         btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
378                         cb->start, cb->start + cb->len - 1,
379                         cb->status == BLK_STS_OK);
380
381         if (cb->writeback)
382                 end_compressed_writeback(inode, cb);
383         /* Note, our inode could be gone now */
384
385         /*
386          * Release the compressed pages, these came from alloc_page and
387          * are not attached to the inode at all
388          */
389         for (index = 0; index < cb->nr_pages; index++) {
390                 struct page *page = cb->compressed_pages[index];
391
392                 page->mapping = NULL;
393                 put_page(page);
394         }
395
396         /* Finally free the cb struct */
397         kfree(cb->compressed_pages);
398         kfree(cb);
399 }
400
401 static void btrfs_finish_compressed_write_work(struct work_struct *work)
402 {
403         struct compressed_bio *cb =
404                 container_of(work, struct compressed_bio, write_end_work);
405
406         finish_compressed_bio_write(cb);
407 }
408
409 /*
410  * Do the cleanup once all the compressed pages hit the disk.  This will clear
411  * writeback on the file pages and free the compressed pages.
412  *
413  * This also calls the writeback end hooks for the file pages so that metadata
414  * and checksums can be updated in the file.
415  */
416 static void end_compressed_bio_write(struct bio *bio)
417 {
418         struct compressed_bio *cb = bio->bi_private;
419
420         if (dec_and_test_compressed_bio(cb, bio)) {
421                 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
422
423                 btrfs_record_physical_zoned(cb->inode, cb->start, bio);
424                 queue_work(fs_info->compressed_write_workers, &cb->write_end_work);
425         }
426         bio_put(bio);
427 }
428
429 /*
430  * Allocate a compressed_bio, which will be used to read/write on-disk
431  * (aka, compressed) * data.
432  *
433  * @cb:                 The compressed_bio structure, which records all the needed
434  *                      information to bind the compressed data to the uncompressed
435  *                      page cache.
436  * @disk_byten:         The logical bytenr where the compressed data will be read
437  *                      from or written to.
438  * @endio_func:         The endio function to call after the IO for compressed data
439  *                      is finished.
440  * @next_stripe_start:  Return value of logical bytenr of where next stripe starts.
441  *                      Let the caller know to only fill the bio up to the stripe
442  *                      boundary.
443  */
444
445
446 static struct bio *alloc_compressed_bio(struct compressed_bio *cb, u64 disk_bytenr,
447                                         unsigned int opf, bio_end_io_t endio_func,
448                                         u64 *next_stripe_start)
449 {
450         struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
451         struct btrfs_io_geometry geom;
452         struct extent_map *em;
453         struct bio *bio;
454         int ret;
455
456         bio = btrfs_bio_alloc(BIO_MAX_VECS);
457
458         bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
459         bio->bi_opf = opf;
460         bio->bi_private = cb;
461         bio->bi_end_io = endio_func;
462
463         em = btrfs_get_chunk_map(fs_info, disk_bytenr, fs_info->sectorsize);
464         if (IS_ERR(em)) {
465                 bio_put(bio);
466                 return ERR_CAST(em);
467         }
468
469         if (bio_op(bio) == REQ_OP_ZONE_APPEND)
470                 bio_set_dev(bio, em->map_lookup->stripes[0].dev->bdev);
471
472         ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), disk_bytenr, &geom);
473         free_extent_map(em);
474         if (ret < 0) {
475                 bio_put(bio);
476                 return ERR_PTR(ret);
477         }
478         *next_stripe_start = disk_bytenr + geom.len;
479
480         return bio;
481 }
482
483 /*
484  * worker function to build and submit bios for previously compressed pages.
485  * The corresponding pages in the inode should be marked for writeback
486  * and the compressed pages should have a reference on them for dropping
487  * when the IO is complete.
488  *
489  * This also checksums the file bytes and gets things ready for
490  * the end io hooks.
491  */
492 blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
493                                  unsigned int len, u64 disk_start,
494                                  unsigned int compressed_len,
495                                  struct page **compressed_pages,
496                                  unsigned int nr_pages,
497                                  unsigned int write_flags,
498                                  struct cgroup_subsys_state *blkcg_css,
499                                  bool writeback)
500 {
501         struct btrfs_fs_info *fs_info = inode->root->fs_info;
502         struct bio *bio = NULL;
503         struct compressed_bio *cb;
504         u64 cur_disk_bytenr = disk_start;
505         u64 next_stripe_start;
506         blk_status_t ret;
507         int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
508         const bool use_append = btrfs_use_zone_append(inode, disk_start);
509         const unsigned int bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
510
511         ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
512                IS_ALIGNED(len, fs_info->sectorsize));
513         cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
514         if (!cb)
515                 return BLK_STS_RESOURCE;
516         refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
517         cb->status = BLK_STS_OK;
518         cb->inode = &inode->vfs_inode;
519         cb->start = start;
520         cb->len = len;
521         cb->mirror_num = 0;
522         cb->compressed_pages = compressed_pages;
523         cb->compressed_len = compressed_len;
524         cb->writeback = writeback;
525         INIT_WORK(&cb->write_end_work, btrfs_finish_compressed_write_work);
526         cb->nr_pages = nr_pages;
527
528         if (blkcg_css)
529                 kthread_associate_blkcg(blkcg_css);
530
531         while (cur_disk_bytenr < disk_start + compressed_len) {
532                 u64 offset = cur_disk_bytenr - disk_start;
533                 unsigned int index = offset >> PAGE_SHIFT;
534                 unsigned int real_size;
535                 unsigned int added;
536                 struct page *page = compressed_pages[index];
537                 bool submit = false;
538
539                 /* Allocate new bio if submitted or not yet allocated */
540                 if (!bio) {
541                         bio = alloc_compressed_bio(cb, cur_disk_bytenr,
542                                 bio_op | write_flags, end_compressed_bio_write,
543                                 &next_stripe_start);
544                         if (IS_ERR(bio)) {
545                                 ret = errno_to_blk_status(PTR_ERR(bio));
546                                 bio = NULL;
547                                 goto finish_cb;
548                         }
549                         if (blkcg_css)
550                                 bio->bi_opf |= REQ_CGROUP_PUNT;
551                 }
552                 /*
553                  * We should never reach next_stripe_start start as we will
554                  * submit comp_bio when reach the boundary immediately.
555                  */
556                 ASSERT(cur_disk_bytenr != next_stripe_start);
557
558                 /*
559                  * We have various limits on the real read size:
560                  * - stripe boundary
561                  * - page boundary
562                  * - compressed length boundary
563                  */
564                 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_bytenr);
565                 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
566                 real_size = min_t(u64, real_size, compressed_len - offset);
567                 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
568
569                 if (use_append)
570                         added = bio_add_zone_append_page(bio, page, real_size,
571                                         offset_in_page(offset));
572                 else
573                         added = bio_add_page(bio, page, real_size,
574                                         offset_in_page(offset));
575                 /* Reached zoned boundary */
576                 if (added == 0)
577                         submit = true;
578
579                 cur_disk_bytenr += added;
580                 /* Reached stripe boundary */
581                 if (cur_disk_bytenr == next_stripe_start)
582                         submit = true;
583
584                 /* Finished the range */
585                 if (cur_disk_bytenr == disk_start + compressed_len)
586                         submit = true;
587
588                 if (submit) {
589                         if (!skip_sum) {
590                                 ret = btrfs_csum_one_bio(inode, bio, start, true);
591                                 if (ret)
592                                         goto finish_cb;
593                         }
594
595                         ASSERT(bio->bi_iter.bi_size);
596                         ret = btrfs_map_bio(fs_info, bio, 0);
597                         if (ret)
598                                 goto finish_cb;
599                         bio = NULL;
600                 }
601                 cond_resched();
602         }
603         if (blkcg_css)
604                 kthread_associate_blkcg(NULL);
605
606         return 0;
607
608 finish_cb:
609         if (blkcg_css)
610                 kthread_associate_blkcg(NULL);
611
612         if (bio) {
613                 bio->bi_status = ret;
614                 bio_endio(bio);
615         }
616         /* Last byte of @cb is submitted, endio will free @cb */
617         if (cur_disk_bytenr == disk_start + compressed_len)
618                 return ret;
619
620         wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
621                            (disk_start + compressed_len - cur_disk_bytenr) >>
622                            fs_info->sectorsize_bits);
623         /*
624          * Even with previous bio ended, we should still have io not yet
625          * submitted, thus need to finish manually.
626          */
627         ASSERT(refcount_read(&cb->pending_sectors));
628         /* Now we are the only one referring @cb, can finish it safely. */
629         finish_compressed_bio_write(cb);
630         return ret;
631 }
632
633 static u64 bio_end_offset(struct bio *bio)
634 {
635         struct bio_vec *last = bio_last_bvec_all(bio);
636
637         return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
638 }
639
640 /*
641  * Add extra pages in the same compressed file extent so that we don't need to
642  * re-read the same extent again and again.
643  *
644  * NOTE: this won't work well for subpage, as for subpage read, we lock the
645  * full page then submit bio for each compressed/regular extents.
646  *
647  * This means, if we have several sectors in the same page points to the same
648  * on-disk compressed data, we will re-read the same extent many times and
649  * this function can only help for the next page.
650  */
651 static noinline int add_ra_bio_pages(struct inode *inode,
652                                      u64 compressed_end,
653                                      struct compressed_bio *cb)
654 {
655         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
656         unsigned long end_index;
657         u64 cur = bio_end_offset(cb->orig_bio);
658         u64 isize = i_size_read(inode);
659         int ret;
660         struct page *page;
661         struct extent_map *em;
662         struct address_space *mapping = inode->i_mapping;
663         struct extent_map_tree *em_tree;
664         struct extent_io_tree *tree;
665         int sectors_missed = 0;
666
667         em_tree = &BTRFS_I(inode)->extent_tree;
668         tree = &BTRFS_I(inode)->io_tree;
669
670         if (isize == 0)
671                 return 0;
672
673         /*
674          * For current subpage support, we only support 64K page size,
675          * which means maximum compressed extent size (128K) is just 2x page
676          * size.
677          * This makes readahead less effective, so here disable readahead for
678          * subpage for now, until full compressed write is supported.
679          */
680         if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
681                 return 0;
682
683         end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
684
685         while (cur < compressed_end) {
686                 u64 page_end;
687                 u64 pg_index = cur >> PAGE_SHIFT;
688                 u32 add_size;
689
690                 if (pg_index > end_index)
691                         break;
692
693                 page = xa_load(&mapping->i_pages, pg_index);
694                 if (page && !xa_is_value(page)) {
695                         sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
696                                           fs_info->sectorsize_bits;
697
698                         /* Beyond threshold, no need to continue */
699                         if (sectors_missed > 4)
700                                 break;
701
702                         /*
703                          * Jump to next page start as we already have page for
704                          * current offset.
705                          */
706                         cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
707                         continue;
708                 }
709
710                 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
711                                                                  ~__GFP_FS));
712                 if (!page)
713                         break;
714
715                 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
716                         put_page(page);
717                         /* There is already a page, skip to page end */
718                         cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
719                         continue;
720                 }
721
722                 ret = set_page_extent_mapped(page);
723                 if (ret < 0) {
724                         unlock_page(page);
725                         put_page(page);
726                         break;
727                 }
728
729                 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
730                 lock_extent(tree, cur, page_end);
731                 read_lock(&em_tree->lock);
732                 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
733                 read_unlock(&em_tree->lock);
734
735                 /*
736                  * At this point, we have a locked page in the page cache for
737                  * these bytes in the file.  But, we have to make sure they map
738                  * to this compressed extent on disk.
739                  */
740                 if (!em || cur < em->start ||
741                     (cur + fs_info->sectorsize > extent_map_end(em)) ||
742                     (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
743                         free_extent_map(em);
744                         unlock_extent(tree, cur, page_end);
745                         unlock_page(page);
746                         put_page(page);
747                         break;
748                 }
749                 free_extent_map(em);
750
751                 if (page->index == end_index) {
752                         size_t zero_offset = offset_in_page(isize);
753
754                         if (zero_offset) {
755                                 int zeros;
756                                 zeros = PAGE_SIZE - zero_offset;
757                                 memzero_page(page, zero_offset, zeros);
758                         }
759                 }
760
761                 add_size = min(em->start + em->len, page_end + 1) - cur;
762                 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
763                 if (ret != add_size) {
764                         unlock_extent(tree, cur, page_end);
765                         unlock_page(page);
766                         put_page(page);
767                         break;
768                 }
769                 /*
770                  * If it's subpage, we also need to increase its
771                  * subpage::readers number, as at endio we will decrease
772                  * subpage::readers and to unlock the page.
773                  */
774                 if (fs_info->sectorsize < PAGE_SIZE)
775                         btrfs_subpage_start_reader(fs_info, page, cur, add_size);
776                 put_page(page);
777                 cur += add_size;
778         }
779         return 0;
780 }
781
782 /*
783  * for a compressed read, the bio we get passed has all the inode pages
784  * in it.  We don't actually do IO on those pages but allocate new ones
785  * to hold the compressed pages on disk.
786  *
787  * bio->bi_iter.bi_sector points to the compressed extent on disk
788  * bio->bi_io_vec points to all of the inode pages
789  *
790  * After the compressed pages are read, we copy the bytes into the
791  * bio we were passed and then call the bio end_io calls
792  */
793 void btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
794                                   int mirror_num)
795 {
796         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
797         struct extent_map_tree *em_tree;
798         struct compressed_bio *cb;
799         unsigned int compressed_len;
800         struct bio *comp_bio = NULL;
801         const u64 disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
802         u64 cur_disk_byte = disk_bytenr;
803         u64 next_stripe_start;
804         u64 file_offset;
805         u64 em_len;
806         u64 em_start;
807         struct extent_map *em;
808         blk_status_t ret;
809         int ret2;
810         int i;
811         u8 *sums;
812
813         em_tree = &BTRFS_I(inode)->extent_tree;
814
815         file_offset = bio_first_bvec_all(bio)->bv_offset +
816                       page_offset(bio_first_page_all(bio));
817
818         /* we need the actual starting offset of this extent in the file */
819         read_lock(&em_tree->lock);
820         em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
821         read_unlock(&em_tree->lock);
822         if (!em) {
823                 ret = BLK_STS_IOERR;
824                 goto out;
825         }
826
827         ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
828         compressed_len = em->block_len;
829         cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
830         if (!cb) {
831                 ret = BLK_STS_RESOURCE;
832                 goto out;
833         }
834
835         refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
836         cb->status = BLK_STS_OK;
837         cb->inode = inode;
838         cb->mirror_num = mirror_num;
839         sums = cb->sums;
840
841         cb->start = em->orig_start;
842         em_len = em->len;
843         em_start = em->start;
844
845         cb->len = bio->bi_iter.bi_size;
846         cb->compressed_len = compressed_len;
847         cb->compress_type = em->compress_type;
848         cb->orig_bio = bio;
849
850         free_extent_map(em);
851         em = NULL;
852
853         cb->nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
854         cb->compressed_pages = kcalloc(cb->nr_pages, sizeof(struct page *), GFP_NOFS);
855         if (!cb->compressed_pages) {
856                 ret = BLK_STS_RESOURCE;
857                 goto fail;
858         }
859
860         ret2 = btrfs_alloc_page_array(cb->nr_pages, cb->compressed_pages);
861         if (ret2) {
862                 ret = BLK_STS_RESOURCE;
863                 goto fail;
864         }
865
866         add_ra_bio_pages(inode, em_start + em_len, cb);
867
868         /* include any pages we added in add_ra-bio_pages */
869         cb->len = bio->bi_iter.bi_size;
870
871         while (cur_disk_byte < disk_bytenr + compressed_len) {
872                 u64 offset = cur_disk_byte - disk_bytenr;
873                 unsigned int index = offset >> PAGE_SHIFT;
874                 unsigned int real_size;
875                 unsigned int added;
876                 struct page *page = cb->compressed_pages[index];
877                 bool submit = false;
878
879                 /* Allocate new bio if submitted or not yet allocated */
880                 if (!comp_bio) {
881                         comp_bio = alloc_compressed_bio(cb, cur_disk_byte,
882                                         REQ_OP_READ, end_compressed_bio_read,
883                                         &next_stripe_start);
884                         if (IS_ERR(comp_bio)) {
885                                 ret = errno_to_blk_status(PTR_ERR(comp_bio));
886                                 comp_bio = NULL;
887                                 goto finish_cb;
888                         }
889                 }
890                 /*
891                  * We should never reach next_stripe_start start as we will
892                  * submit comp_bio when reach the boundary immediately.
893                  */
894                 ASSERT(cur_disk_byte != next_stripe_start);
895                 /*
896                  * We have various limit on the real read size:
897                  * - stripe boundary
898                  * - page boundary
899                  * - compressed length boundary
900                  */
901                 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_byte);
902                 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
903                 real_size = min_t(u64, real_size, compressed_len - offset);
904                 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
905
906                 added = bio_add_page(comp_bio, page, real_size, offset_in_page(offset));
907                 /*
908                  * Maximum compressed extent is smaller than bio size limit,
909                  * thus bio_add_page() should always success.
910                  */
911                 ASSERT(added == real_size);
912                 cur_disk_byte += added;
913
914                 /* Reached stripe boundary, need to submit */
915                 if (cur_disk_byte == next_stripe_start)
916                         submit = true;
917
918                 /* Has finished the range, need to submit */
919                 if (cur_disk_byte == disk_bytenr + compressed_len)
920                         submit = true;
921
922                 if (submit) {
923                         unsigned int nr_sectors;
924
925                         ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
926                         if (ret)
927                                 goto finish_cb;
928
929                         nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
930                                                   fs_info->sectorsize);
931                         sums += fs_info->csum_size * nr_sectors;
932
933                         ASSERT(comp_bio->bi_iter.bi_size);
934                         ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
935                                                   BTRFS_WQ_ENDIO_DATA);
936                         if (ret)
937                                 goto finish_cb;
938                         ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
939                         if (ret)
940                                 goto finish_cb;
941                         comp_bio = NULL;
942                 }
943         }
944         return;
945
946 fail:
947         if (cb->compressed_pages) {
948                 for (i = 0; i < cb->nr_pages; i++) {
949                         if (cb->compressed_pages[i])
950                                 __free_page(cb->compressed_pages[i]);
951                 }
952         }
953
954         kfree(cb->compressed_pages);
955         kfree(cb);
956 out:
957         free_extent_map(em);
958         bio->bi_status = ret;
959         bio_endio(bio);
960         return;
961 finish_cb:
962         if (comp_bio) {
963                 comp_bio->bi_status = ret;
964                 bio_endio(comp_bio);
965         }
966         /* All bytes of @cb is submitted, endio will free @cb */
967         if (cur_disk_byte == disk_bytenr + compressed_len)
968                 return;
969
970         wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
971                            (disk_bytenr + compressed_len - cur_disk_byte) >>
972                            fs_info->sectorsize_bits);
973         /*
974          * Even with previous bio ended, we should still have io not yet
975          * submitted, thus need to finish @cb manually.
976          */
977         ASSERT(refcount_read(&cb->pending_sectors));
978         /* Now we are the only one referring @cb, can finish it safely. */
979         finish_compressed_bio_read(cb);
980 }
981
982 /*
983  * Heuristic uses systematic sampling to collect data from the input data
984  * range, the logic can be tuned by the following constants:
985  *
986  * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
987  * @SAMPLING_INTERVAL  - range from which the sampled data can be collected
988  */
989 #define SAMPLING_READ_SIZE      (16)
990 #define SAMPLING_INTERVAL       (256)
991
992 /*
993  * For statistical analysis of the input data we consider bytes that form a
994  * Galois Field of 256 objects. Each object has an attribute count, ie. how
995  * many times the object appeared in the sample.
996  */
997 #define BUCKET_SIZE             (256)
998
999 /*
1000  * The size of the sample is based on a statistical sampling rule of thumb.
1001  * The common way is to perform sampling tests as long as the number of
1002  * elements in each cell is at least 5.
1003  *
1004  * Instead of 5, we choose 32 to obtain more accurate results.
1005  * If the data contain the maximum number of symbols, which is 256, we obtain a
1006  * sample size bound by 8192.
1007  *
1008  * For a sample of at most 8KB of data per data range: 16 consecutive bytes
1009  * from up to 512 locations.
1010  */
1011 #define MAX_SAMPLE_SIZE         (BTRFS_MAX_UNCOMPRESSED *               \
1012                                  SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
1013
1014 struct bucket_item {
1015         u32 count;
1016 };
1017
1018 struct heuristic_ws {
1019         /* Partial copy of input data */
1020         u8 *sample;
1021         u32 sample_size;
1022         /* Buckets store counters for each byte value */
1023         struct bucket_item *bucket;
1024         /* Sorting buffer */
1025         struct bucket_item *bucket_b;
1026         struct list_head list;
1027 };
1028
1029 static struct workspace_manager heuristic_wsm;
1030
1031 static void free_heuristic_ws(struct list_head *ws)
1032 {
1033         struct heuristic_ws *workspace;
1034
1035         workspace = list_entry(ws, struct heuristic_ws, list);
1036
1037         kvfree(workspace->sample);
1038         kfree(workspace->bucket);
1039         kfree(workspace->bucket_b);
1040         kfree(workspace);
1041 }
1042
1043 static struct list_head *alloc_heuristic_ws(unsigned int level)
1044 {
1045         struct heuristic_ws *ws;
1046
1047         ws = kzalloc(sizeof(*ws), GFP_KERNEL);
1048         if (!ws)
1049                 return ERR_PTR(-ENOMEM);
1050
1051         ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
1052         if (!ws->sample)
1053                 goto fail;
1054
1055         ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
1056         if (!ws->bucket)
1057                 goto fail;
1058
1059         ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
1060         if (!ws->bucket_b)
1061                 goto fail;
1062
1063         INIT_LIST_HEAD(&ws->list);
1064         return &ws->list;
1065 fail:
1066         free_heuristic_ws(&ws->list);
1067         return ERR_PTR(-ENOMEM);
1068 }
1069
1070 const struct btrfs_compress_op btrfs_heuristic_compress = {
1071         .workspace_manager = &heuristic_wsm,
1072 };
1073
1074 static const struct btrfs_compress_op * const btrfs_compress_op[] = {
1075         /* The heuristic is represented as compression type 0 */
1076         &btrfs_heuristic_compress,
1077         &btrfs_zlib_compress,
1078         &btrfs_lzo_compress,
1079         &btrfs_zstd_compress,
1080 };
1081
1082 static struct list_head *alloc_workspace(int type, unsigned int level)
1083 {
1084         switch (type) {
1085         case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
1086         case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
1087         case BTRFS_COMPRESS_LZO:  return lzo_alloc_workspace(level);
1088         case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
1089         default:
1090                 /*
1091                  * This can't happen, the type is validated several times
1092                  * before we get here.
1093                  */
1094                 BUG();
1095         }
1096 }
1097
1098 static void free_workspace(int type, struct list_head *ws)
1099 {
1100         switch (type) {
1101         case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
1102         case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
1103         case BTRFS_COMPRESS_LZO:  return lzo_free_workspace(ws);
1104         case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
1105         default:
1106                 /*
1107                  * This can't happen, the type is validated several times
1108                  * before we get here.
1109                  */
1110                 BUG();
1111         }
1112 }
1113
1114 static void btrfs_init_workspace_manager(int type)
1115 {
1116         struct workspace_manager *wsm;
1117         struct list_head *workspace;
1118
1119         wsm = btrfs_compress_op[type]->workspace_manager;
1120         INIT_LIST_HEAD(&wsm->idle_ws);
1121         spin_lock_init(&wsm->ws_lock);
1122         atomic_set(&wsm->total_ws, 0);
1123         init_waitqueue_head(&wsm->ws_wait);
1124
1125         /*
1126          * Preallocate one workspace for each compression type so we can
1127          * guarantee forward progress in the worst case
1128          */
1129         workspace = alloc_workspace(type, 0);
1130         if (IS_ERR(workspace)) {
1131                 pr_warn(
1132         "BTRFS: cannot preallocate compression workspace, will try later\n");
1133         } else {
1134                 atomic_set(&wsm->total_ws, 1);
1135                 wsm->free_ws = 1;
1136                 list_add(workspace, &wsm->idle_ws);
1137         }
1138 }
1139
1140 static void btrfs_cleanup_workspace_manager(int type)
1141 {
1142         struct workspace_manager *wsman;
1143         struct list_head *ws;
1144
1145         wsman = btrfs_compress_op[type]->workspace_manager;
1146         while (!list_empty(&wsman->idle_ws)) {
1147                 ws = wsman->idle_ws.next;
1148                 list_del(ws);
1149                 free_workspace(type, ws);
1150                 atomic_dec(&wsman->total_ws);
1151         }
1152 }
1153
1154 /*
1155  * This finds an available workspace or allocates a new one.
1156  * If it's not possible to allocate a new one, waits until there's one.
1157  * Preallocation makes a forward progress guarantees and we do not return
1158  * errors.
1159  */
1160 struct list_head *btrfs_get_workspace(int type, unsigned int level)
1161 {
1162         struct workspace_manager *wsm;
1163         struct list_head *workspace;
1164         int cpus = num_online_cpus();
1165         unsigned nofs_flag;
1166         struct list_head *idle_ws;
1167         spinlock_t *ws_lock;
1168         atomic_t *total_ws;
1169         wait_queue_head_t *ws_wait;
1170         int *free_ws;
1171
1172         wsm = btrfs_compress_op[type]->workspace_manager;
1173         idle_ws  = &wsm->idle_ws;
1174         ws_lock  = &wsm->ws_lock;
1175         total_ws = &wsm->total_ws;
1176         ws_wait  = &wsm->ws_wait;
1177         free_ws  = &wsm->free_ws;
1178
1179 again:
1180         spin_lock(ws_lock);
1181         if (!list_empty(idle_ws)) {
1182                 workspace = idle_ws->next;
1183                 list_del(workspace);
1184                 (*free_ws)--;
1185                 spin_unlock(ws_lock);
1186                 return workspace;
1187
1188         }
1189         if (atomic_read(total_ws) > cpus) {
1190                 DEFINE_WAIT(wait);
1191
1192                 spin_unlock(ws_lock);
1193                 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
1194                 if (atomic_read(total_ws) > cpus && !*free_ws)
1195                         schedule();
1196                 finish_wait(ws_wait, &wait);
1197                 goto again;
1198         }
1199         atomic_inc(total_ws);
1200         spin_unlock(ws_lock);
1201
1202         /*
1203          * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1204          * to turn it off here because we might get called from the restricted
1205          * context of btrfs_compress_bio/btrfs_compress_pages
1206          */
1207         nofs_flag = memalloc_nofs_save();
1208         workspace = alloc_workspace(type, level);
1209         memalloc_nofs_restore(nofs_flag);
1210
1211         if (IS_ERR(workspace)) {
1212                 atomic_dec(total_ws);
1213                 wake_up(ws_wait);
1214
1215                 /*
1216                  * Do not return the error but go back to waiting. There's a
1217                  * workspace preallocated for each type and the compression
1218                  * time is bounded so we get to a workspace eventually. This
1219                  * makes our caller's life easier.
1220                  *
1221                  * To prevent silent and low-probability deadlocks (when the
1222                  * initial preallocation fails), check if there are any
1223                  * workspaces at all.
1224                  */
1225                 if (atomic_read(total_ws) == 0) {
1226                         static DEFINE_RATELIMIT_STATE(_rs,
1227                                         /* once per minute */ 60 * HZ,
1228                                         /* no burst */ 1);
1229
1230                         if (__ratelimit(&_rs)) {
1231                                 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
1232                         }
1233                 }
1234                 goto again;
1235         }
1236         return workspace;
1237 }
1238
1239 static struct list_head *get_workspace(int type, int level)
1240 {
1241         switch (type) {
1242         case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
1243         case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
1244         case BTRFS_COMPRESS_LZO:  return btrfs_get_workspace(type, level);
1245         case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1246         default:
1247                 /*
1248                  * This can't happen, the type is validated several times
1249                  * before we get here.
1250                  */
1251                 BUG();
1252         }
1253 }
1254
1255 /*
1256  * put a workspace struct back on the list or free it if we have enough
1257  * idle ones sitting around
1258  */
1259 void btrfs_put_workspace(int type, struct list_head *ws)
1260 {
1261         struct workspace_manager *wsm;
1262         struct list_head *idle_ws;
1263         spinlock_t *ws_lock;
1264         atomic_t *total_ws;
1265         wait_queue_head_t *ws_wait;
1266         int *free_ws;
1267
1268         wsm = btrfs_compress_op[type]->workspace_manager;
1269         idle_ws  = &wsm->idle_ws;
1270         ws_lock  = &wsm->ws_lock;
1271         total_ws = &wsm->total_ws;
1272         ws_wait  = &wsm->ws_wait;
1273         free_ws  = &wsm->free_ws;
1274
1275         spin_lock(ws_lock);
1276         if (*free_ws <= num_online_cpus()) {
1277                 list_add(ws, idle_ws);
1278                 (*free_ws)++;
1279                 spin_unlock(ws_lock);
1280                 goto wake;
1281         }
1282         spin_unlock(ws_lock);
1283
1284         free_workspace(type, ws);
1285         atomic_dec(total_ws);
1286 wake:
1287         cond_wake_up(ws_wait);
1288 }
1289
1290 static void put_workspace(int type, struct list_head *ws)
1291 {
1292         switch (type) {
1293         case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1294         case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1295         case BTRFS_COMPRESS_LZO:  return btrfs_put_workspace(type, ws);
1296         case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1297         default:
1298                 /*
1299                  * This can't happen, the type is validated several times
1300                  * before we get here.
1301                  */
1302                 BUG();
1303         }
1304 }
1305
1306 /*
1307  * Adjust @level according to the limits of the compression algorithm or
1308  * fallback to default
1309  */
1310 static unsigned int btrfs_compress_set_level(int type, unsigned level)
1311 {
1312         const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1313
1314         if (level == 0)
1315                 level = ops->default_level;
1316         else
1317                 level = min(level, ops->max_level);
1318
1319         return level;
1320 }
1321
1322 /*
1323  * Given an address space and start and length, compress the bytes into @pages
1324  * that are allocated on demand.
1325  *
1326  * @type_level is encoded algorithm and level, where level 0 means whatever
1327  * default the algorithm chooses and is opaque here;
1328  * - compression algo are 0-3
1329  * - the level are bits 4-7
1330  *
1331  * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1332  * and returns number of actually allocated pages
1333  *
1334  * @total_in is used to return the number of bytes actually read.  It
1335  * may be smaller than the input length if we had to exit early because we
1336  * ran out of room in the pages array or because we cross the
1337  * max_out threshold.
1338  *
1339  * @total_out is an in/out parameter, must be set to the input length and will
1340  * be also used to return the total number of compressed bytes
1341  */
1342 int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
1343                          u64 start, struct page **pages,
1344                          unsigned long *out_pages,
1345                          unsigned long *total_in,
1346                          unsigned long *total_out)
1347 {
1348         int type = btrfs_compress_type(type_level);
1349         int level = btrfs_compress_level(type_level);
1350         struct list_head *workspace;
1351         int ret;
1352
1353         level = btrfs_compress_set_level(type, level);
1354         workspace = get_workspace(type, level);
1355         ret = compression_compress_pages(type, workspace, mapping, start, pages,
1356                                          out_pages, total_in, total_out);
1357         put_workspace(type, workspace);
1358         return ret;
1359 }
1360
1361 static int btrfs_decompress_bio(struct compressed_bio *cb)
1362 {
1363         struct list_head *workspace;
1364         int ret;
1365         int type = cb->compress_type;
1366
1367         workspace = get_workspace(type, 0);
1368         ret = compression_decompress_bio(workspace, cb);
1369         put_workspace(type, workspace);
1370
1371         return ret;
1372 }
1373
1374 /*
1375  * a less complex decompression routine.  Our compressed data fits in a
1376  * single page, and we want to read a single page out of it.
1377  * start_byte tells us the offset into the compressed data we're interested in
1378  */
1379 int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1380                      unsigned long start_byte, size_t srclen, size_t destlen)
1381 {
1382         struct list_head *workspace;
1383         int ret;
1384
1385         workspace = get_workspace(type, 0);
1386         ret = compression_decompress(type, workspace, data_in, dest_page,
1387                                      start_byte, srclen, destlen);
1388         put_workspace(type, workspace);
1389
1390         return ret;
1391 }
1392
1393 void __init btrfs_init_compress(void)
1394 {
1395         btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1396         btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1397         btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1398         zstd_init_workspace_manager();
1399 }
1400
1401 void __cold btrfs_exit_compress(void)
1402 {
1403         btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1404         btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1405         btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1406         zstd_cleanup_workspace_manager();
1407 }
1408
1409 /*
1410  * Copy decompressed data from working buffer to pages.
1411  *
1412  * @buf:                The decompressed data buffer
1413  * @buf_len:            The decompressed data length
1414  * @decompressed:       Number of bytes that are already decompressed inside the
1415  *                      compressed extent
1416  * @cb:                 The compressed extent descriptor
1417  * @orig_bio:           The original bio that the caller wants to read for
1418  *
1419  * An easier to understand graph is like below:
1420  *
1421  *              |<- orig_bio ->|     |<- orig_bio->|
1422  *      |<-------      full decompressed extent      ----->|
1423  *      |<-----------    @cb range   ---->|
1424  *      |                       |<-- @buf_len -->|
1425  *      |<--- @decompressed --->|
1426  *
1427  * Note that, @cb can be a subpage of the full decompressed extent, but
1428  * @cb->start always has the same as the orig_file_offset value of the full
1429  * decompressed extent.
1430  *
1431  * When reading compressed extent, we have to read the full compressed extent,
1432  * while @orig_bio may only want part of the range.
1433  * Thus this function will ensure only data covered by @orig_bio will be copied
1434  * to.
1435  *
1436  * Return 0 if we have copied all needed contents for @orig_bio.
1437  * Return >0 if we need continue decompress.
1438  */
1439 int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1440                               struct compressed_bio *cb, u32 decompressed)
1441 {
1442         struct bio *orig_bio = cb->orig_bio;
1443         /* Offset inside the full decompressed extent */
1444         u32 cur_offset;
1445
1446         cur_offset = decompressed;
1447         /* The main loop to do the copy */
1448         while (cur_offset < decompressed + buf_len) {
1449                 struct bio_vec bvec;
1450                 size_t copy_len;
1451                 u32 copy_start;
1452                 /* Offset inside the full decompressed extent */
1453                 u32 bvec_offset;
1454
1455                 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1456                 /*
1457                  * cb->start may underflow, but subtracting that value can still
1458                  * give us correct offset inside the full decompressed extent.
1459                  */
1460                 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
1461
1462                 /* Haven't reached the bvec range, exit */
1463                 if (decompressed + buf_len <= bvec_offset)
1464                         return 1;
1465
1466                 copy_start = max(cur_offset, bvec_offset);
1467                 copy_len = min(bvec_offset + bvec.bv_len,
1468                                decompressed + buf_len) - copy_start;
1469                 ASSERT(copy_len);
1470
1471                 /*
1472                  * Extra range check to ensure we didn't go beyond
1473                  * @buf + @buf_len.
1474                  */
1475                 ASSERT(copy_start - decompressed < buf_len);
1476                 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1477                                buf + copy_start - decompressed, copy_len);
1478                 cur_offset += copy_len;
1479
1480                 bio_advance(orig_bio, copy_len);
1481                 /* Finished the bio */
1482                 if (!orig_bio->bi_iter.bi_size)
1483                         return 0;
1484         }
1485         return 1;
1486 }
1487
1488 /*
1489  * Shannon Entropy calculation
1490  *
1491  * Pure byte distribution analysis fails to determine compressibility of data.
1492  * Try calculating entropy to estimate the average minimum number of bits
1493  * needed to encode the sampled data.
1494  *
1495  * For convenience, return the percentage of needed bits, instead of amount of
1496  * bits directly.
1497  *
1498  * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1499  *                          and can be compressible with high probability
1500  *
1501  * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1502  *
1503  * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1504  */
1505 #define ENTROPY_LVL_ACEPTABLE           (65)
1506 #define ENTROPY_LVL_HIGH                (80)
1507
1508 /*
1509  * For increasead precision in shannon_entropy calculation,
1510  * let's do pow(n, M) to save more digits after comma:
1511  *
1512  * - maximum int bit length is 64
1513  * - ilog2(MAX_SAMPLE_SIZE)     -> 13
1514  * - 13 * 4 = 52 < 64           -> M = 4
1515  *
1516  * So use pow(n, 4).
1517  */
1518 static inline u32 ilog2_w(u64 n)
1519 {
1520         return ilog2(n * n * n * n);
1521 }
1522
1523 static u32 shannon_entropy(struct heuristic_ws *ws)
1524 {
1525         const u32 entropy_max = 8 * ilog2_w(2);
1526         u32 entropy_sum = 0;
1527         u32 p, p_base, sz_base;
1528         u32 i;
1529
1530         sz_base = ilog2_w(ws->sample_size);
1531         for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1532                 p = ws->bucket[i].count;
1533                 p_base = ilog2_w(p);
1534                 entropy_sum += p * (sz_base - p_base);
1535         }
1536
1537         entropy_sum /= ws->sample_size;
1538         return entropy_sum * 100 / entropy_max;
1539 }
1540
1541 #define RADIX_BASE              4U
1542 #define COUNTERS_SIZE           (1U << RADIX_BASE)
1543
1544 static u8 get4bits(u64 num, int shift) {
1545         u8 low4bits;
1546
1547         num >>= shift;
1548         /* Reverse order */
1549         low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1550         return low4bits;
1551 }
1552
1553 /*
1554  * Use 4 bits as radix base
1555  * Use 16 u32 counters for calculating new position in buf array
1556  *
1557  * @array     - array that will be sorted
1558  * @array_buf - buffer array to store sorting results
1559  *              must be equal in size to @array
1560  * @num       - array size
1561  */
1562 static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
1563                        int num)
1564 {
1565         u64 max_num;
1566         u64 buf_num;
1567         u32 counters[COUNTERS_SIZE];
1568         u32 new_addr;
1569         u32 addr;
1570         int bitlen;
1571         int shift;
1572         int i;
1573
1574         /*
1575          * Try avoid useless loop iterations for small numbers stored in big
1576          * counters.  Example: 48 33 4 ... in 64bit array
1577          */
1578         max_num = array[0].count;
1579         for (i = 1; i < num; i++) {
1580                 buf_num = array[i].count;
1581                 if (buf_num > max_num)
1582                         max_num = buf_num;
1583         }
1584
1585         buf_num = ilog2(max_num);
1586         bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1587
1588         shift = 0;
1589         while (shift < bitlen) {
1590                 memset(counters, 0, sizeof(counters));
1591
1592                 for (i = 0; i < num; i++) {
1593                         buf_num = array[i].count;
1594                         addr = get4bits(buf_num, shift);
1595                         counters[addr]++;
1596                 }
1597
1598                 for (i = 1; i < COUNTERS_SIZE; i++)
1599                         counters[i] += counters[i - 1];
1600
1601                 for (i = num - 1; i >= 0; i--) {
1602                         buf_num = array[i].count;
1603                         addr = get4bits(buf_num, shift);
1604                         counters[addr]--;
1605                         new_addr = counters[addr];
1606                         array_buf[new_addr] = array[i];
1607                 }
1608
1609                 shift += RADIX_BASE;
1610
1611                 /*
1612                  * Normal radix expects to move data from a temporary array, to
1613                  * the main one.  But that requires some CPU time. Avoid that
1614                  * by doing another sort iteration to original array instead of
1615                  * memcpy()
1616                  */
1617                 memset(counters, 0, sizeof(counters));
1618
1619                 for (i = 0; i < num; i ++) {
1620                         buf_num = array_buf[i].count;
1621                         addr = get4bits(buf_num, shift);
1622                         counters[addr]++;
1623                 }
1624
1625                 for (i = 1; i < COUNTERS_SIZE; i++)
1626                         counters[i] += counters[i - 1];
1627
1628                 for (i = num - 1; i >= 0; i--) {
1629                         buf_num = array_buf[i].count;
1630                         addr = get4bits(buf_num, shift);
1631                         counters[addr]--;
1632                         new_addr = counters[addr];
1633                         array[new_addr] = array_buf[i];
1634                 }
1635
1636                 shift += RADIX_BASE;
1637         }
1638 }
1639
1640 /*
1641  * Size of the core byte set - how many bytes cover 90% of the sample
1642  *
1643  * There are several types of structured binary data that use nearly all byte
1644  * values. The distribution can be uniform and counts in all buckets will be
1645  * nearly the same (eg. encrypted data). Unlikely to be compressible.
1646  *
1647  * Other possibility is normal (Gaussian) distribution, where the data could
1648  * be potentially compressible, but we have to take a few more steps to decide
1649  * how much.
1650  *
1651  * @BYTE_CORE_SET_LOW  - main part of byte values repeated frequently,
1652  *                       compression algo can easy fix that
1653  * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1654  *                       probability is not compressible
1655  */
1656 #define BYTE_CORE_SET_LOW               (64)
1657 #define BYTE_CORE_SET_HIGH              (200)
1658
1659 static int byte_core_set_size(struct heuristic_ws *ws)
1660 {
1661         u32 i;
1662         u32 coreset_sum = 0;
1663         const u32 core_set_threshold = ws->sample_size * 90 / 100;
1664         struct bucket_item *bucket = ws->bucket;
1665
1666         /* Sort in reverse order */
1667         radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
1668
1669         for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1670                 coreset_sum += bucket[i].count;
1671
1672         if (coreset_sum > core_set_threshold)
1673                 return i;
1674
1675         for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1676                 coreset_sum += bucket[i].count;
1677                 if (coreset_sum > core_set_threshold)
1678                         break;
1679         }
1680
1681         return i;
1682 }
1683
1684 /*
1685  * Count byte values in buckets.
1686  * This heuristic can detect textual data (configs, xml, json, html, etc).
1687  * Because in most text-like data byte set is restricted to limited number of
1688  * possible characters, and that restriction in most cases makes data easy to
1689  * compress.
1690  *
1691  * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1692  *      less - compressible
1693  *      more - need additional analysis
1694  */
1695 #define BYTE_SET_THRESHOLD              (64)
1696
1697 static u32 byte_set_size(const struct heuristic_ws *ws)
1698 {
1699         u32 i;
1700         u32 byte_set_size = 0;
1701
1702         for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1703                 if (ws->bucket[i].count > 0)
1704                         byte_set_size++;
1705         }
1706
1707         /*
1708          * Continue collecting count of byte values in buckets.  If the byte
1709          * set size is bigger then the threshold, it's pointless to continue,
1710          * the detection technique would fail for this type of data.
1711          */
1712         for (; i < BUCKET_SIZE; i++) {
1713                 if (ws->bucket[i].count > 0) {
1714                         byte_set_size++;
1715                         if (byte_set_size > BYTE_SET_THRESHOLD)
1716                                 return byte_set_size;
1717                 }
1718         }
1719
1720         return byte_set_size;
1721 }
1722
1723 static bool sample_repeated_patterns(struct heuristic_ws *ws)
1724 {
1725         const u32 half_of_sample = ws->sample_size / 2;
1726         const u8 *data = ws->sample;
1727
1728         return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1729 }
1730
1731 static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1732                                      struct heuristic_ws *ws)
1733 {
1734         struct page *page;
1735         u64 index, index_end;
1736         u32 i, curr_sample_pos;
1737         u8 *in_data;
1738
1739         /*
1740          * Compression handles the input data by chunks of 128KiB
1741          * (defined by BTRFS_MAX_UNCOMPRESSED)
1742          *
1743          * We do the same for the heuristic and loop over the whole range.
1744          *
1745          * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1746          * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1747          */
1748         if (end - start > BTRFS_MAX_UNCOMPRESSED)
1749                 end = start + BTRFS_MAX_UNCOMPRESSED;
1750
1751         index = start >> PAGE_SHIFT;
1752         index_end = end >> PAGE_SHIFT;
1753
1754         /* Don't miss unaligned end */
1755         if (!IS_ALIGNED(end, PAGE_SIZE))
1756                 index_end++;
1757
1758         curr_sample_pos = 0;
1759         while (index < index_end) {
1760                 page = find_get_page(inode->i_mapping, index);
1761                 in_data = kmap_local_page(page);
1762                 /* Handle case where the start is not aligned to PAGE_SIZE */
1763                 i = start % PAGE_SIZE;
1764                 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1765                         /* Don't sample any garbage from the last page */
1766                         if (start > end - SAMPLING_READ_SIZE)
1767                                 break;
1768                         memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1769                                         SAMPLING_READ_SIZE);
1770                         i += SAMPLING_INTERVAL;
1771                         start += SAMPLING_INTERVAL;
1772                         curr_sample_pos += SAMPLING_READ_SIZE;
1773                 }
1774                 kunmap_local(in_data);
1775                 put_page(page);
1776
1777                 index++;
1778         }
1779
1780         ws->sample_size = curr_sample_pos;
1781 }
1782
1783 /*
1784  * Compression heuristic.
1785  *
1786  * For now is's a naive and optimistic 'return true', we'll extend the logic to
1787  * quickly (compared to direct compression) detect data characteristics
1788  * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1789  * data.
1790  *
1791  * The following types of analysis can be performed:
1792  * - detect mostly zero data
1793  * - detect data with low "byte set" size (text, etc)
1794  * - detect data with low/high "core byte" set
1795  *
1796  * Return non-zero if the compression should be done, 0 otherwise.
1797  */
1798 int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1799 {
1800         struct list_head *ws_list = get_workspace(0, 0);
1801         struct heuristic_ws *ws;
1802         u32 i;
1803         u8 byte;
1804         int ret = 0;
1805
1806         ws = list_entry(ws_list, struct heuristic_ws, list);
1807
1808         heuristic_collect_sample(inode, start, end, ws);
1809
1810         if (sample_repeated_patterns(ws)) {
1811                 ret = 1;
1812                 goto out;
1813         }
1814
1815         memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1816
1817         for (i = 0; i < ws->sample_size; i++) {
1818                 byte = ws->sample[i];
1819                 ws->bucket[byte].count++;
1820         }
1821
1822         i = byte_set_size(ws);
1823         if (i < BYTE_SET_THRESHOLD) {
1824                 ret = 2;
1825                 goto out;
1826         }
1827
1828         i = byte_core_set_size(ws);
1829         if (i <= BYTE_CORE_SET_LOW) {
1830                 ret = 3;
1831                 goto out;
1832         }
1833
1834         if (i >= BYTE_CORE_SET_HIGH) {
1835                 ret = 0;
1836                 goto out;
1837         }
1838
1839         i = shannon_entropy(ws);
1840         if (i <= ENTROPY_LVL_ACEPTABLE) {
1841                 ret = 4;
1842                 goto out;
1843         }
1844
1845         /*
1846          * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1847          * needed to give green light to compression.
1848          *
1849          * For now just assume that compression at that level is not worth the
1850          * resources because:
1851          *
1852          * 1. it is possible to defrag the data later
1853          *
1854          * 2. the data would turn out to be hardly compressible, eg. 150 byte
1855          * values, every bucket has counter at level ~54. The heuristic would
1856          * be confused. This can happen when data have some internal repeated
1857          * patterns like "abbacbbc...". This can be detected by analyzing
1858          * pairs of bytes, which is too costly.
1859          */
1860         if (i < ENTROPY_LVL_HIGH) {
1861                 ret = 5;
1862                 goto out;
1863         } else {
1864                 ret = 0;
1865                 goto out;
1866         }
1867
1868 out:
1869         put_workspace(0, ws_list);
1870         return ret;
1871 }
1872
1873 /*
1874  * Convert the compression suffix (eg. after "zlib" starting with ":") to
1875  * level, unrecognized string will set the default level
1876  */
1877 unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
1878 {
1879         unsigned int level = 0;
1880         int ret;
1881
1882         if (!type)
1883                 return 0;
1884
1885         if (str[0] == ':') {
1886                 ret = kstrtouint(str + 1, 10, &level);
1887                 if (ret)
1888                         level = 0;
1889         }
1890
1891         level = btrfs_compress_set_level(type, level);
1892
1893         return level;
1894 }