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