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