blob: f7a6c3cda85e3c4046eb2ec585a2a4a54816b745 [file] [log] [blame]
David Sterbac1d7c512018-04-03 19:23:33 +02001// SPDX-License-Identifier: GPL-2.0
Chris Masonc8b97812008-10-29 14:49:59 -04002/*
3 * Copyright (C) 2008 Oracle. All rights reserved.
Chris Masonc8b97812008-10-29 14:49:59 -04004 */
5
6#include <linux/kernel.h>
7#include <linux/bio.h>
Chris Masonc8b97812008-10-29 14:49:59 -04008#include <linux/file.h>
9#include <linux/fs.h>
10#include <linux/pagemap.h>
11#include <linux/highmem.h>
12#include <linux/time.h>
13#include <linux/init.h>
14#include <linux/string.h>
Chris Masonc8b97812008-10-29 14:49:59 -040015#include <linux/backing-dev.h>
Chris Masonc8b97812008-10-29 14:49:59 -040016#include <linux/writeback.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090017#include <linux/slab.h>
David Sterbafe308532017-05-31 17:14:56 +020018#include <linux/sched/mm.h>
Timofey Titovets19562432017-10-08 16:11:59 +030019#include <linux/log2.h>
Johannes Thumshirnd5178572019-06-03 16:58:57 +020020#include <crypto/hash.h>
David Sterba602cbe92019-08-21 18:48:25 +020021#include "misc.h"
Chris Masonc8b97812008-10-29 14:49:59 -040022#include "ctree.h"
23#include "disk-io.h"
24#include "transaction.h"
25#include "btrfs_inode.h"
26#include "volumes.h"
27#include "ordered-data.h"
Chris Masonc8b97812008-10-29 14:49:59 -040028#include "compression.h"
29#include "extent_io.h"
30#include "extent_map.h"
Qu Wenruo6a404912021-09-27 15:21:47 +080031#include "subpage.h"
Johannes Thumshirn764c7c92021-05-19 00:40:28 +090032#include "zoned.h"
Chris Masonc8b97812008-10-29 14:49:59 -040033
David Sterbae128f9c2017-10-31 17:24:26 +010034static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
35
36const char* btrfs_compress_type2str(enum btrfs_compression_type type)
37{
38 switch (type) {
39 case BTRFS_COMPRESS_ZLIB:
40 case BTRFS_COMPRESS_LZO:
41 case BTRFS_COMPRESS_ZSTD:
42 case BTRFS_COMPRESS_NONE:
43 return btrfs_compress_types[type];
Chengguang Xuce96b7f2019-10-10 15:59:57 +080044 default:
45 break;
David Sterbae128f9c2017-10-31 17:24:26 +010046 }
47
48 return NULL;
49}
50
Johannes Thumshirnaa53e3b2019-06-06 12:07:15 +020051bool btrfs_compress_is_valid_type(const char *str, size_t len)
52{
53 int i;
54
55 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
56 size_t comp_len = strlen(btrfs_compress_types[i]);
57
58 if (len < comp_len)
59 continue;
60
61 if (!strncmp(btrfs_compress_types[i], str, comp_len))
62 return true;
63 }
64 return false;
65}
66
David Sterba1e4eb742019-10-02 00:06:15 +020067static int compression_compress_pages(int type, struct list_head *ws,
68 struct address_space *mapping, u64 start, struct page **pages,
69 unsigned long *out_pages, unsigned long *total_in,
70 unsigned long *total_out)
71{
72 switch (type) {
73 case BTRFS_COMPRESS_ZLIB:
74 return zlib_compress_pages(ws, mapping, start, pages,
75 out_pages, total_in, total_out);
76 case BTRFS_COMPRESS_LZO:
77 return lzo_compress_pages(ws, mapping, start, pages,
78 out_pages, total_in, total_out);
79 case BTRFS_COMPRESS_ZSTD:
80 return zstd_compress_pages(ws, mapping, start, pages,
81 out_pages, total_in, total_out);
82 case BTRFS_COMPRESS_NONE:
83 default:
84 /*
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080085 * This can happen when compression races with remount setting
86 * it to 'no compress', while caller doesn't call
87 * inode_need_compress() to check if we really need to
88 * compress.
89 *
90 * Not a big deal, just need to inform caller that we
91 * haven't allocated any pages yet.
David Sterba1e4eb742019-10-02 00:06:15 +020092 */
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080093 *out_pages = 0;
David Sterba1e4eb742019-10-02 00:06:15 +020094 return -E2BIG;
95 }
96}
97
98static int compression_decompress_bio(int type, struct list_head *ws,
99 struct compressed_bio *cb)
100{
101 switch (type) {
102 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
103 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
104 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
105 case BTRFS_COMPRESS_NONE:
106 default:
107 /*
108 * This can't happen, the type is validated several times
109 * before we get here.
110 */
111 BUG();
112 }
113}
114
115static int compression_decompress(int type, struct list_head *ws,
116 unsigned char *data_in, struct page *dest_page,
117 unsigned long start_byte, size_t srclen, size_t destlen)
118{
119 switch (type) {
120 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
121 start_byte, srclen, destlen);
122 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
123 start_byte, srclen, destlen);
124 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
125 start_byte, srclen, destlen);
126 case BTRFS_COMPRESS_NONE:
127 default:
128 /*
129 * This can't happen, the type is validated several times
130 * before we get here.
131 */
132 BUG();
133 }
134}
135
Anand Jain8140dc32017-05-26 15:44:58 +0800136static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +0000137
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400138static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -0500139 unsigned long disk_size)
140{
Chris Masond20f7042008-12-08 16:58:54 -0500141 return sizeof(struct compressed_bio) +
David Sterba713cebf2020-06-30 18:04:02 +0200142 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
Chris Masond20f7042008-12-08 16:58:54 -0500143}
144
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300145static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
Chris Masond20f7042008-12-08 16:58:54 -0500146 u64 disk_start)
147{
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200148 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200149 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
David Sterba223486c2020-07-02 11:27:30 +0200150 const u32 csum_size = fs_info->csum_size;
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800151 const u32 sectorsize = fs_info->sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500152 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800153 unsigned int i;
Chris Masond20f7042008-12-08 16:58:54 -0500154 char *kaddr;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200155 u8 csum[BTRFS_CSUM_SIZE];
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300156 struct compressed_bio *cb = bio->bi_private;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200157 u8 *cb_sum = cb->sums;
Chris Masond20f7042008-12-08 16:58:54 -0500158
Josef Bacik42437a62020-10-16 11:29:18 -0400159 if (!fs_info->csum_root || (inode->flags & BTRFS_INODE_NODATASUM))
Chris Masond20f7042008-12-08 16:58:54 -0500160 return 0;
161
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200162 shash->tfm = fs_info->csum_shash;
163
Chris Masond20f7042008-12-08 16:58:54 -0500164 for (i = 0; i < cb->nr_pages; i++) {
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800165 u32 pg_offset;
166 u32 bytes_left = PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500167 page = cb->compressed_pages[i];
Chris Masond20f7042008-12-08 16:58:54 -0500168
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800169 /* Determine the remaining bytes inside the page first */
170 if (i == cb->nr_pages - 1)
171 bytes_left = cb->compressed_len - i * PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500172
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800173 /* Hash through the page sector by sector */
174 for (pg_offset = 0; pg_offset < bytes_left;
175 pg_offset += sectorsize) {
David Sterba4c2bf272021-06-15 17:15:38 +0200176 kaddr = page_address(page);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800177 crypto_shash_digest(shash, kaddr + pg_offset,
178 sectorsize, csum);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800179
180 if (memcmp(&csum, cb_sum, csum_size) != 0) {
181 btrfs_print_data_csum_error(inode, disk_start,
182 csum, cb_sum, cb->mirror_num);
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800183 if (btrfs_bio(bio)->device)
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800184 btrfs_dev_stat_inc_and_print(
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800185 btrfs_bio(bio)->device,
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800186 BTRFS_DEV_STAT_CORRUPTION_ERRS);
187 return -EIO;
188 }
189 cb_sum += csum_size;
190 disk_start += sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500191 }
Chris Masond20f7042008-12-08 16:58:54 -0500192 }
Nikolay Borisov93c4c032020-07-02 16:46:47 +0300193 return 0;
Chris Masond20f7042008-12-08 16:58:54 -0500194}
195
Qu Wenruo6ec97652021-09-27 15:21:48 +0800196/*
197 * Reduce bio and io accounting for a compressed_bio with its corresponding bio.
198 *
199 * Return true if there is no pending bio nor io.
200 * Return false otherwise.
201 */
202static bool dec_and_test_compressed_bio(struct compressed_bio *cb, struct bio *bio)
203{
204 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
205 unsigned int bi_size = 0;
206 bool last_io = false;
207 struct bio_vec *bvec;
208 struct bvec_iter_all iter_all;
209
210 /*
211 * At endio time, bi_iter.bi_size doesn't represent the real bio size.
212 * Thus here we have to iterate through all segments to grab correct
213 * bio size.
214 */
215 bio_for_each_segment_all(bvec, bio, iter_all)
216 bi_size += bvec->bv_len;
217
218 if (bio->bi_status)
219 cb->errors = 1;
220
221 ASSERT(bi_size && bi_size <= cb->compressed_len);
222 last_io = refcount_sub_and_test(bi_size >> fs_info->sectorsize_bits,
223 &cb->pending_sectors);
224 atomic_dec(&cb->pending_bios);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800225 /*
226 * Here we must wake up the possible error handler after all other
227 * operations on @cb finished, or we can race with
228 * finish_compressed_bio_*() which may free @cb.
229 */
230 wake_up_var(cb);
231
Qu Wenruo6ec97652021-09-27 15:21:48 +0800232 return last_io;
233}
234
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800235static void finish_compressed_bio_read(struct compressed_bio *cb, struct bio *bio)
236{
237 unsigned int index;
238 struct page *page;
239
240 /* Release the compressed pages */
241 for (index = 0; index < cb->nr_pages; index++) {
242 page = cb->compressed_pages[index];
243 page->mapping = NULL;
244 put_page(page);
245 }
246
247 /* Do io completion on the original bio */
248 if (cb->errors) {
249 bio_io_error(cb->orig_bio);
250 } else {
251 struct bio_vec *bvec;
252 struct bvec_iter_all iter_all;
253
254 ASSERT(bio);
255 ASSERT(!bio->bi_status);
256 /*
257 * We have verified the checksum already, set page checked so
258 * the end_io handlers know about it
259 */
260 ASSERT(!bio_flagged(bio, BIO_CLONED));
261 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all) {
262 u64 bvec_start = page_offset(bvec->bv_page) +
263 bvec->bv_offset;
264
265 btrfs_page_set_checked(btrfs_sb(cb->inode->i_sb),
266 bvec->bv_page, bvec_start,
267 bvec->bv_len);
268 }
269
270 bio_endio(cb->orig_bio);
271 }
272
273 /* Finally free the cb struct */
274 kfree(cb->compressed_pages);
275 kfree(cb);
276}
277
Chris Masonc8b97812008-10-29 14:49:59 -0400278/* when we finish reading compressed pages from the disk, we
279 * decompress them and then run the bio end_io routines on the
280 * decompressed pages (in the inode address space).
281 *
282 * This allows the checksumming and other IO error handling routines
283 * to work normally
284 *
285 * The compressed pages are freed here, and it must be run
286 * in process context
287 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200288static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400289{
Chris Masonc8b97812008-10-29 14:49:59 -0400290 struct compressed_bio *cb = bio->bi_private;
291 struct inode *inode;
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800292 unsigned int mirror = btrfs_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600293 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400294
Qu Wenruo6ec97652021-09-27 15:21:48 +0800295 if (!dec_and_test_compressed_bio(cb, bio))
Chris Masonc8b97812008-10-29 14:49:59 -0400296 goto out;
297
Liu Bocf1167d2017-09-20 17:50:18 -0600298 /*
299 * Record the correct mirror_num in cb->orig_bio so that
300 * read-repair can work properly.
301 */
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800302 btrfs_bio(cb->orig_bio)->mirror_num = mirror;
Liu Bocf1167d2017-09-20 17:50:18 -0600303 cb->mirror_num = mirror;
304
Liu Boe6311f22017-09-20 17:50:19 -0600305 /*
306 * Some IO in this cb have failed, just skip checksum as there
307 * is no way it could be correct.
308 */
309 if (cb->errors == 1)
310 goto csum_failed;
311
Chris Masond20f7042008-12-08 16:58:54 -0500312 inode = cb->inode;
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300313 ret = check_compressed_csum(BTRFS_I(inode), bio,
David Sterba1201b582020-11-26 15:41:27 +0100314 bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500315 if (ret)
316 goto csum_failed;
317
Chris Masonc8b97812008-10-29 14:49:59 -0400318 /* ok, we're the last bio for this extent, lets start
319 * the decompression.
320 */
Anand Jain8140dc32017-05-26 15:44:58 +0800321 ret = btrfs_decompress_bio(cb);
322
Chris Masond20f7042008-12-08 16:58:54 -0500323csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400324 if (ret)
325 cb->errors = 1;
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800326 finish_compressed_bio_read(cb, bio);
Chris Masonc8b97812008-10-29 14:49:59 -0400327out:
328 bio_put(bio);
329}
330
331/*
332 * Clear the writeback bits on all of the file
333 * pages for a compressed write
334 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100335static noinline void end_compressed_writeback(struct inode *inode,
336 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400337{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300338 unsigned long index = cb->start >> PAGE_SHIFT;
339 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400340 struct page *pages[16];
341 unsigned long nr_pages = end_index - index + 1;
342 int i;
343 int ret;
344
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100345 if (cb->errors)
346 mapping_set_error(inode->i_mapping, -EIO);
347
Chris Masond3977122009-01-05 21:25:51 -0500348 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400349 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500350 min_t(unsigned long,
351 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400352 if (ret == 0) {
353 nr_pages -= 1;
354 index += 1;
355 continue;
356 }
357 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100358 if (cb->errors)
359 SetPageError(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400360 end_page_writeback(pages[i]);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300361 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400362 }
363 nr_pages -= ret;
364 index += ret;
365 }
366 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400367}
368
369/*
370 * do the cleanup once all the compressed pages hit the disk.
371 * This will clear writeback on the file pages and free the compressed
372 * pages.
373 *
374 * This also calls the writeback end hooks for the file pages so that
375 * metadata and checksums can be updated in the file.
376 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200377static void end_compressed_bio_write(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400378{
Chris Masonc8b97812008-10-29 14:49:59 -0400379 struct compressed_bio *cb = bio->bi_private;
380 struct inode *inode;
381 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800382 unsigned int index;
Chris Masonc8b97812008-10-29 14:49:59 -0400383
Qu Wenruo6ec97652021-09-27 15:21:48 +0800384 if (!dec_and_test_compressed_bio(cb, bio))
Chris Masonc8b97812008-10-29 14:49:59 -0400385 goto out;
386
387 /* ok, we're the last bio for this extent, step one is to
388 * call back into the FS and do all the end_io operations
389 */
390 inode = cb->inode;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900391 btrfs_record_physical_zoned(inode, cb->start, bio);
Qu Wenruo38a39ac72021-04-08 20:32:27 +0800392 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
Nikolay Borisovc6297322018-11-08 10:18:08 +0200393 cb->start, cb->start + cb->len - 1,
Goldwyn Rodrigues240246f2021-07-09 11:29:22 -0500394 !cb->errors);
Chris Masonc8b97812008-10-29 14:49:59 -0400395
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100396 end_compressed_writeback(inode, cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400397 /* note, our inode could be gone now */
398
399 /*
400 * release the compressed pages, these came from alloc_page and
401 * are not attached to the inode at all
402 */
403 index = 0;
404 for (index = 0; index < cb->nr_pages; index++) {
405 page = cb->compressed_pages[index];
406 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300407 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400408 }
409
410 /* finally free the cb struct */
411 kfree(cb->compressed_pages);
412 kfree(cb);
413out:
414 bio_put(bio);
415}
416
417/*
418 * worker function to build and submit bios for previously compressed pages.
419 * The corresponding pages in the inode should be marked for writeback
420 * and the compressed pages should have a reference on them for dropping
421 * when the IO is complete.
422 *
423 * This also checksums the file bytes and gets things ready for
424 * the end io hooks.
425 */
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300426blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
Anand Jain65b53552021-05-29 17:48:35 +0800427 unsigned int len, u64 disk_start,
428 unsigned int compressed_len,
Chris Masonc8b97812008-10-29 14:49:59 -0400429 struct page **compressed_pages,
Anand Jain65b53552021-05-29 17:48:35 +0800430 unsigned int nr_pages,
Chris Masonec39f762019-07-10 12:28:17 -0700431 unsigned int write_flags,
432 struct cgroup_subsys_state *blkcg_css)
Chris Masonc8b97812008-10-29 14:49:59 -0400433{
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300434 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Chris Masonc8b97812008-10-29 14:49:59 -0400435 struct bio *bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400436 struct compressed_bio *cb;
437 unsigned long bytes_left;
David Sterba306e16c2011-04-19 14:29:38 +0200438 int pg_index = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400439 struct page *page;
440 u64 first_byte = disk_start;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200441 blk_status_t ret;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300442 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900443 const bool use_append = btrfs_use_zone_append(inode, disk_start);
444 const unsigned int bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
Chris Masonc8b97812008-10-29 14:49:59 -0400445
Johannes Thumshirnfdb1e122018-12-05 15:23:04 +0100446 WARN_ON(!PAGE_ALIGNED(start));
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400447 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
Yoshinori Sanodac97e52011-02-15 12:01:42 +0000448 if (!cb)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200449 return BLK_STS_RESOURCE;
Qu Wenruo6ec97652021-09-27 15:21:48 +0800450 atomic_set(&cb->pending_bios, 0);
451 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
Chris Masonc8b97812008-10-29 14:49:59 -0400452 cb->errors = 0;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300453 cb->inode = &inode->vfs_inode;
Chris Masonc8b97812008-10-29 14:49:59 -0400454 cb->start = start;
455 cb->len = len;
Chris Masond20f7042008-12-08 16:58:54 -0500456 cb->mirror_num = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400457 cb->compressed_pages = compressed_pages;
458 cb->compressed_len = compressed_len;
459 cb->orig_bio = NULL;
460 cb->nr_pages = nr_pages;
461
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800462 bio = btrfs_bio_alloc(BIO_MAX_VECS);
Qu Wenruocd8e0cc2021-09-15 15:17:17 +0800463 bio->bi_iter.bi_sector = first_byte >> SECTOR_SHIFT;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900464 bio->bi_opf = bio_op | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400465 bio->bi_private = cb;
466 bio->bi_end_io = end_compressed_bio_write;
Chris Masonec39f762019-07-10 12:28:17 -0700467
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900468 if (use_append) {
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900469 struct btrfs_device *device;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900470
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900471 device = btrfs_zoned_get_device(fs_info, disk_start, PAGE_SIZE);
472 if (IS_ERR(device)) {
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900473 kfree(cb);
474 bio_put(bio);
475 return BLK_STS_NOTSUPP;
476 }
477
Johannes Thumshirne7ff9e62021-05-19 00:40:29 +0900478 bio_set_dev(bio, device->bdev);
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900479 }
480
Chris Masonec39f762019-07-10 12:28:17 -0700481 if (blkcg_css) {
482 bio->bi_opf |= REQ_CGROUP_PUNT;
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800483 kthread_associate_blkcg(blkcg_css);
Chris Masonec39f762019-07-10 12:28:17 -0700484 }
Chris Masonc8b97812008-10-29 14:49:59 -0400485
486 /* create and submit bios for the compressed pages */
487 bytes_left = compressed_len;
David Sterba306e16c2011-04-19 14:29:38 +0200488 for (pg_index = 0; pg_index < cb->nr_pages; pg_index++) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200489 int submit = 0;
Qu Wenruo4c80a972021-05-25 13:52:43 +0800490 int len = 0;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200491
David Sterba306e16c2011-04-19 14:29:38 +0200492 page = compressed_pages[pg_index];
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300493 page->mapping = inode->vfs_inode.i_mapping;
Kent Overstreet4f024f32013-10-11 15:44:27 -0700494 if (bio->bi_iter.bi_size)
Nikolay Borisovda12fe52018-11-27 20:57:58 +0200495 submit = btrfs_bio_fits_in_stripe(page, PAGE_SIZE, bio,
496 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400497
Qu Wenruo4c80a972021-05-25 13:52:43 +0800498 /*
499 * Page can only be added to bio if the current bio fits in
500 * stripe.
501 */
502 if (!submit) {
503 if (pg_index == 0 && use_append)
504 len = bio_add_zone_append_page(bio, page,
505 PAGE_SIZE, 0);
506 else
507 len = bio_add_page(bio, page, PAGE_SIZE, 0);
508 }
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900509
Chris Mason70b99e62008-10-31 12:46:39 -0400510 page->mapping = NULL;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900511 if (submit || len < PAGE_SIZE) {
Qu Wenruo6ec97652021-09-27 15:21:48 +0800512 atomic_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400513 ret = btrfs_bio_wq_end_io(fs_info, bio,
514 BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100515 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400516
Li Zefane55179b2011-07-14 03:16:47 +0000517 if (!skip_sum) {
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300518 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100519 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000520 }
Chris Masond20f7042008-12-08 16:58:54 -0500521
Chris Mason08635ba2019-07-10 12:28:14 -0700522 ret = btrfs_map_bio(fs_info, bio, 0);
Liu Bof5daf2c2016-06-22 18:32:06 -0700523 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200524 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700525 bio_endio(bio);
526 }
Chris Masonc8b97812008-10-29 14:49:59 -0400527
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800528 bio = btrfs_bio_alloc(BIO_MAX_VECS);
Qu Wenruocd8e0cc2021-09-15 15:17:17 +0800529 bio->bi_iter.bi_sector = first_byte >> SECTOR_SHIFT;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900530 bio->bi_opf = bio_op | write_flags;
Chris Masonc8b97812008-10-29 14:49:59 -0400531 bio->bi_private = cb;
532 bio->bi_end_io = end_compressed_bio_write;
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800533 if (blkcg_css)
Dennis Zhou7b62e662019-12-11 16:07:06 -0800534 bio->bi_opf |= REQ_CGROUP_PUNT;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900535 /*
536 * Use bio_add_page() to ensure the bio has at least one
537 * page.
538 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300539 bio_add_page(bio, page, PAGE_SIZE, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400540 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300541 if (bytes_left < PAGE_SIZE) {
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400542 btrfs_info(fs_info,
David Sterba282ab3f2019-10-14 14:38:33 +0200543 "bytes left %lu compress len %u nr %u",
Chris Masoncfbc2462008-10-30 13:22:14 -0400544 bytes_left, cb->compressed_len, cb->nr_pages);
545 }
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300546 bytes_left -= PAGE_SIZE;
547 first_byte += PAGE_SIZE;
Chris Mason771ed682008-11-06 22:02:51 -0500548 cond_resched();
Chris Masonc8b97812008-10-29 14:49:59 -0400549 }
Chris Masonc8b97812008-10-29 14:49:59 -0400550
Qu Wenruo6ec97652021-09-27 15:21:48 +0800551 atomic_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400552 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100553 BUG_ON(ret); /* -ENOMEM */
Chris Masonc8b97812008-10-29 14:49:59 -0400554
Li Zefane55179b2011-07-14 03:16:47 +0000555 if (!skip_sum) {
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300556 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Jeff Mahoney79787ea2012-03-12 16:03:00 +0100557 BUG_ON(ret); /* -ENOMEM */
Li Zefane55179b2011-07-14 03:16:47 +0000558 }
Chris Masond20f7042008-12-08 16:58:54 -0500559
Chris Mason08635ba2019-07-10 12:28:14 -0700560 ret = btrfs_map_bio(fs_info, bio, 0);
Liu Bof5daf2c2016-06-22 18:32:06 -0700561 if (ret) {
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200562 bio->bi_status = ret;
Liu Bof5daf2c2016-06-22 18:32:06 -0700563 bio_endio(bio);
564 }
Chris Masonc8b97812008-10-29 14:49:59 -0400565
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800566 if (blkcg_css)
567 kthread_associate_blkcg(NULL);
568
Chris Masonc8b97812008-10-29 14:49:59 -0400569 return 0;
570}
571
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100572static u64 bio_end_offset(struct bio *bio)
573{
Ming Leic45a8f22017-12-18 20:22:05 +0800574 struct bio_vec *last = bio_last_bvec_all(bio);
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100575
576 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
577}
578
Qu Wenruo6a404912021-09-27 15:21:47 +0800579/*
580 * Add extra pages in the same compressed file extent so that we don't need to
581 * re-read the same extent again and again.
582 *
583 * NOTE: this won't work well for subpage, as for subpage read, we lock the
584 * full page then submit bio for each compressed/regular extents.
585 *
586 * This means, if we have several sectors in the same page points to the same
587 * on-disk compressed data, we will re-read the same extent many times and
588 * this function can only help for the next page.
589 */
Chris Mason771ed682008-11-06 22:02:51 -0500590static noinline int add_ra_bio_pages(struct inode *inode,
591 u64 compressed_end,
592 struct compressed_bio *cb)
593{
Qu Wenruo6a404912021-09-27 15:21:47 +0800594 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Mason771ed682008-11-06 22:02:51 -0500595 unsigned long end_index;
Qu Wenruo6a404912021-09-27 15:21:47 +0800596 u64 cur = bio_end_offset(cb->orig_bio);
Chris Mason771ed682008-11-06 22:02:51 -0500597 u64 isize = i_size_read(inode);
598 int ret;
599 struct page *page;
Chris Mason771ed682008-11-06 22:02:51 -0500600 struct extent_map *em;
601 struct address_space *mapping = inode->i_mapping;
Chris Mason771ed682008-11-06 22:02:51 -0500602 struct extent_map_tree *em_tree;
603 struct extent_io_tree *tree;
Qu Wenruo6a404912021-09-27 15:21:47 +0800604 int sectors_missed = 0;
Chris Mason771ed682008-11-06 22:02:51 -0500605
Chris Mason771ed682008-11-06 22:02:51 -0500606 em_tree = &BTRFS_I(inode)->extent_tree;
607 tree = &BTRFS_I(inode)->io_tree;
608
609 if (isize == 0)
610 return 0;
611
Qu Wenruoca62e852021-07-26 14:34:52 +0800612 /*
613 * For current subpage support, we only support 64K page size,
614 * which means maximum compressed extent size (128K) is just 2x page
615 * size.
616 * This makes readahead less effective, so here disable readahead for
617 * subpage for now, until full compressed write is supported.
618 */
619 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
620 return 0;
621
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300622 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500623
Qu Wenruo6a404912021-09-27 15:21:47 +0800624 while (cur < compressed_end) {
625 u64 page_end;
626 u64 pg_index = cur >> PAGE_SHIFT;
627 u32 add_size;
Chris Mason771ed682008-11-06 22:02:51 -0500628
David Sterba306e16c2011-04-19 14:29:38 +0200629 if (pg_index > end_index)
Chris Mason771ed682008-11-06 22:02:51 -0500630 break;
631
Matthew Wilcox0a943c62017-12-04 10:37:22 -0500632 page = xa_load(&mapping->i_pages, pg_index);
Matthew Wilcox3159f942017-11-03 13:30:42 -0400633 if (page && !xa_is_value(page)) {
Qu Wenruo6a404912021-09-27 15:21:47 +0800634 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
635 fs_info->sectorsize_bits;
636
637 /* Beyond threshold, no need to continue */
638 if (sectors_missed > 4)
Chris Mason771ed682008-11-06 22:02:51 -0500639 break;
Qu Wenruo6a404912021-09-27 15:21:47 +0800640
641 /*
642 * Jump to next page start as we already have page for
643 * current offset.
644 */
645 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
646 continue;
Chris Mason771ed682008-11-06 22:02:51 -0500647 }
648
Michal Hockoc62d2552015-11-06 16:28:49 -0800649 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
650 ~__GFP_FS));
Chris Mason771ed682008-11-06 22:02:51 -0500651 if (!page)
652 break;
653
Michal Hockoc62d2552015-11-06 16:28:49 -0800654 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300655 put_page(page);
Qu Wenruo6a404912021-09-27 15:21:47 +0800656 /* There is already a page, skip to page end */
657 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
658 continue;
Chris Mason771ed682008-11-06 22:02:51 -0500659 }
660
Qu Wenruo32443de2021-01-26 16:34:00 +0800661 ret = set_page_extent_mapped(page);
662 if (ret < 0) {
663 unlock_page(page);
664 put_page(page);
665 break;
666 }
667
Qu Wenruo6a404912021-09-27 15:21:47 +0800668 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
669 lock_extent(tree, cur, page_end);
Chris Mason890871b2009-09-02 16:24:52 -0400670 read_lock(&em_tree->lock);
Qu Wenruo6a404912021-09-27 15:21:47 +0800671 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
Chris Mason890871b2009-09-02 16:24:52 -0400672 read_unlock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500673
Qu Wenruo6a404912021-09-27 15:21:47 +0800674 /*
675 * At this point, we have a locked page in the page cache for
676 * these bytes in the file. But, we have to make sure they map
677 * to this compressed extent on disk.
678 */
679 if (!em || cur < em->start ||
680 (cur + fs_info->sectorsize > extent_map_end(em)) ||
Kent Overstreet4f024f32013-10-11 15:44:27 -0700681 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
Chris Mason771ed682008-11-06 22:02:51 -0500682 free_extent_map(em);
Qu Wenruo6a404912021-09-27 15:21:47 +0800683 unlock_extent(tree, cur, page_end);
Chris Mason771ed682008-11-06 22:02:51 -0500684 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300685 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500686 break;
687 }
688 free_extent_map(em);
689
690 if (page->index == end_index) {
Johannes Thumshirn70730172018-12-05 15:23:03 +0100691 size_t zero_offset = offset_in_page(isize);
Chris Mason771ed682008-11-06 22:02:51 -0500692
693 if (zero_offset) {
694 int zeros;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300695 zeros = PAGE_SIZE - zero_offset;
Ira Weinyd048b9c2021-05-04 18:40:07 -0700696 memzero_page(page, zero_offset, zeros);
Chris Mason771ed682008-11-06 22:02:51 -0500697 flush_dcache_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500698 }
699 }
700
Qu Wenruo6a404912021-09-27 15:21:47 +0800701 add_size = min(em->start + em->len, page_end + 1) - cur;
702 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
703 if (ret != add_size) {
704 unlock_extent(tree, cur, page_end);
Chris Mason771ed682008-11-06 22:02:51 -0500705 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300706 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500707 break;
708 }
Qu Wenruo6a404912021-09-27 15:21:47 +0800709 /*
710 * If it's subpage, we also need to increase its
711 * subpage::readers number, as at endio we will decrease
712 * subpage::readers and to unlock the page.
713 */
714 if (fs_info->sectorsize < PAGE_SIZE)
715 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
716 put_page(page);
717 cur += add_size;
Chris Mason771ed682008-11-06 22:02:51 -0500718 }
Chris Mason771ed682008-11-06 22:02:51 -0500719 return 0;
720}
721
Chris Masonc8b97812008-10-29 14:49:59 -0400722/*
723 * for a compressed read, the bio we get passed has all the inode pages
724 * in it. We don't actually do IO on those pages but allocate new ones
725 * to hold the compressed pages on disk.
726 *
Kent Overstreet4f024f32013-10-11 15:44:27 -0700727 * bio->bi_iter.bi_sector points to the compressed extent on disk
Chris Masonc8b97812008-10-29 14:49:59 -0400728 * bio->bi_io_vec points to all of the inode pages
Chris Masonc8b97812008-10-29 14:49:59 -0400729 *
730 * After the compressed pages are read, we copy the bytes into the
731 * bio we were passed and then call the bio end_io calls
732 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200733blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
Chris Masonc8b97812008-10-29 14:49:59 -0400734 int mirror_num, unsigned long bio_flags)
735{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400736 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400737 struct extent_map_tree *em_tree;
738 struct compressed_bio *cb;
Anand Jain356b4a22021-05-29 17:48:34 +0800739 unsigned int compressed_len;
740 unsigned int nr_pages;
741 unsigned int pg_index;
Chris Masonc8b97812008-10-29 14:49:59 -0400742 struct page *page;
Chris Masonc8b97812008-10-29 14:49:59 -0400743 struct bio *comp_bio;
David Sterba1201b582020-11-26 15:41:27 +0100744 u64 cur_disk_byte = bio->bi_iter.bi_sector << 9;
Qu Wenruo557023e2021-07-05 10:00:56 +0800745 u64 file_offset;
Chris Masone04ca622008-11-10 11:44:58 -0500746 u64 em_len;
747 u64 em_start;
Chris Masonc8b97812008-10-29 14:49:59 -0400748 struct extent_map *em;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200749 blk_status_t ret = BLK_STS_RESOURCE;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400750 int faili = 0;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200751 u8 *sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400752
Chris Masonc8b97812008-10-29 14:49:59 -0400753 em_tree = &BTRFS_I(inode)->extent_tree;
754
Qu Wenruo557023e2021-07-05 10:00:56 +0800755 file_offset = bio_first_bvec_all(bio)->bv_offset +
756 page_offset(bio_first_page_all(bio));
757
Chris Masonc8b97812008-10-29 14:49:59 -0400758 /* we need the actual starting offset of this extent in the file */
Chris Mason890871b2009-09-02 16:24:52 -0400759 read_lock(&em_tree->lock);
Qu Wenruo557023e2021-07-05 10:00:56 +0800760 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
Chris Mason890871b2009-09-02 16:24:52 -0400761 read_unlock(&em_tree->lock);
Tsutomu Itoh285190d2012-02-16 16:23:58 +0900762 if (!em)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200763 return BLK_STS_IOERR;
Chris Masonc8b97812008-10-29 14:49:59 -0400764
Qu Wenruo557023e2021-07-05 10:00:56 +0800765 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
Chris Masond20f7042008-12-08 16:58:54 -0500766 compressed_len = em->block_len;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400767 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000768 if (!cb)
769 goto out;
770
Qu Wenruo6ec97652021-09-27 15:21:48 +0800771 atomic_set(&cb->pending_bios, 0);
772 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
Chris Masonc8b97812008-10-29 14:49:59 -0400773 cb->errors = 0;
774 cb->inode = inode;
Chris Masond20f7042008-12-08 16:58:54 -0500775 cb->mirror_num = mirror_num;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200776 sums = cb->sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400777
Yan Zhengff5b7ee2008-11-10 07:34:43 -0500778 cb->start = em->orig_start;
Chris Masone04ca622008-11-10 11:44:58 -0500779 em_len = em->len;
780 em_start = em->start;
Chris Masond20f7042008-12-08 16:58:54 -0500781
Chris Masonc8b97812008-10-29 14:49:59 -0400782 free_extent_map(em);
Chris Masone04ca622008-11-10 11:44:58 -0500783 em = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400784
Christoph Hellwig81381052016-11-25 09:07:50 +0100785 cb->len = bio->bi_iter.bi_size;
Chris Masonc8b97812008-10-29 14:49:59 -0400786 cb->compressed_len = compressed_len;
Li Zefan261507a02010-12-17 14:21:50 +0800787 cb->compress_type = extent_compress_type(bio_flags);
Chris Masonc8b97812008-10-29 14:49:59 -0400788 cb->orig_bio = bio;
789
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300790 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
David Sterba31e818f2015-02-20 18:00:26 +0100791 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
Chris Masonc8b97812008-10-29 14:49:59 -0400792 GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000793 if (!cb->compressed_pages)
794 goto fail1;
795
David Sterba306e16c2011-04-19 14:29:38 +0200796 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
David Sterbab0ee5e12021-06-14 22:22:22 +0200797 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS);
Josef Bacik15e3004a2012-10-05 13:39:50 -0400798 if (!cb->compressed_pages[pg_index]) {
799 faili = pg_index - 1;
Dan Carpenter0e9350d2017-06-19 13:55:37 +0300800 ret = BLK_STS_RESOURCE;
liubo6b82ce82011-01-26 06:21:39 +0000801 goto fail2;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400802 }
Chris Masonc8b97812008-10-29 14:49:59 -0400803 }
Josef Bacik15e3004a2012-10-05 13:39:50 -0400804 faili = nr_pages - 1;
Chris Masonc8b97812008-10-29 14:49:59 -0400805 cb->nr_pages = nr_pages;
806
Filipe Manana7f042a82016-01-27 19:17:20 +0000807 add_ra_bio_pages(inode, em_start + em_len, cb);
Chris Mason771ed682008-11-06 22:02:51 -0500808
Chris Mason771ed682008-11-06 22:02:51 -0500809 /* include any pages we added in add_ra-bio_pages */
Christoph Hellwig81381052016-11-25 09:07:50 +0100810 cb->len = bio->bi_iter.bi_size;
Chris Mason771ed682008-11-06 22:02:51 -0500811
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800812 comp_bio = btrfs_bio_alloc(BIO_MAX_VECS);
Qu Wenruocd8e0cc2021-09-15 15:17:17 +0800813 comp_bio->bi_iter.bi_sector = cur_disk_byte >> SECTOR_SHIFT;
David Sterbaebcc3262018-06-29 10:56:53 +0200814 comp_bio->bi_opf = REQ_OP_READ;
Chris Masonc8b97812008-10-29 14:49:59 -0400815 comp_bio->bi_private = cb;
816 comp_bio->bi_end_io = end_compressed_bio_read;
Chris Masonc8b97812008-10-29 14:49:59 -0400817
David Sterba306e16c2011-04-19 14:29:38 +0200818 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
Qu Wenruobe6a1362021-02-04 15:03:23 +0800819 u32 pg_len = PAGE_SIZE;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200820 int submit = 0;
821
Qu Wenruobe6a1362021-02-04 15:03:23 +0800822 /*
823 * To handle subpage case, we need to make sure the bio only
824 * covers the range we need.
825 *
826 * If we're at the last page, truncate the length to only cover
827 * the remaining part.
828 */
829 if (pg_index == nr_pages - 1)
830 pg_len = min_t(u32, PAGE_SIZE,
831 compressed_len - pg_index * PAGE_SIZE);
832
David Sterba306e16c2011-04-19 14:29:38 +0200833 page = cb->compressed_pages[pg_index];
Chris Masonc8b97812008-10-29 14:49:59 -0400834 page->mapping = inode->i_mapping;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300835 page->index = em_start >> PAGE_SHIFT;
Chris Masond20f7042008-12-08 16:58:54 -0500836
Kent Overstreet4f024f32013-10-11 15:44:27 -0700837 if (comp_bio->bi_iter.bi_size)
Qu Wenruobe6a1362021-02-04 15:03:23 +0800838 submit = btrfs_bio_fits_in_stripe(page, pg_len,
Nikolay Borisovda12fe52018-11-27 20:57:58 +0200839 comp_bio, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400840
Chris Mason70b99e62008-10-31 12:46:39 -0400841 page->mapping = NULL;
Qu Wenruobe6a1362021-02-04 15:03:23 +0800842 if (submit || bio_add_page(comp_bio, page, pg_len, 0) < pg_len) {
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200843 unsigned int nr_sectors;
844
Qu Wenruo6ec97652021-09-27 15:21:48 +0800845 atomic_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400846 ret = btrfs_bio_wq_end_io(fs_info, comp_bio,
847 BTRFS_WQ_ENDIO_DATA);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800848 if (ret)
849 goto finish_cb;
Chris Masonc8b97812008-10-29 14:49:59 -0400850
Qu Wenruo62751932020-12-02 14:48:06 +0800851 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800852 if (ret)
853 goto finish_cb;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200854
855 nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
856 fs_info->sectorsize);
David Sterba713cebf2020-06-30 18:04:02 +0200857 sums += fs_info->csum_size * nr_sectors;
Chris Masond20f7042008-12-08 16:58:54 -0500858
Chris Mason08635ba2019-07-10 12:28:14 -0700859 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800860 if (ret)
861 goto finish_cb;
Chris Masonc8b97812008-10-29 14:49:59 -0400862
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800863 comp_bio = btrfs_bio_alloc(BIO_MAX_VECS);
Qu Wenruocd8e0cc2021-09-15 15:17:17 +0800864 comp_bio->bi_iter.bi_sector = cur_disk_byte >> SECTOR_SHIFT;
David Sterbaebcc3262018-06-29 10:56:53 +0200865 comp_bio->bi_opf = REQ_OP_READ;
Chris Mason771ed682008-11-06 22:02:51 -0500866 comp_bio->bi_private = cb;
867 comp_bio->bi_end_io = end_compressed_bio_read;
868
Qu Wenruobe6a1362021-02-04 15:03:23 +0800869 bio_add_page(comp_bio, page, pg_len, 0);
Chris Masonc8b97812008-10-29 14:49:59 -0400870 }
Qu Wenruobe6a1362021-02-04 15:03:23 +0800871 cur_disk_byte += pg_len;
Chris Masonc8b97812008-10-29 14:49:59 -0400872 }
Chris Masonc8b97812008-10-29 14:49:59 -0400873
Qu Wenruo6ec97652021-09-27 15:21:48 +0800874 atomic_inc(&cb->pending_bios);
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400875 ret = btrfs_bio_wq_end_io(fs_info, comp_bio, BTRFS_WQ_ENDIO_DATA);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800876 if (ret)
877 goto last_bio;
Chris Masonc8b97812008-10-29 14:49:59 -0400878
Qu Wenruo62751932020-12-02 14:48:06 +0800879 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800880 if (ret)
881 goto last_bio;
Chris Masond20f7042008-12-08 16:58:54 -0500882
Chris Mason08635ba2019-07-10 12:28:14 -0700883 ret = btrfs_map_bio(fs_info, comp_bio, mirror_num);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800884 if (ret)
885 goto last_bio;
Chris Masonc8b97812008-10-29 14:49:59 -0400886
Chris Masonc8b97812008-10-29 14:49:59 -0400887 return 0;
liubo6b82ce82011-01-26 06:21:39 +0000888
889fail2:
Josef Bacik15e3004a2012-10-05 13:39:50 -0400890 while (faili >= 0) {
891 __free_page(cb->compressed_pages[faili]);
892 faili--;
893 }
liubo6b82ce82011-01-26 06:21:39 +0000894
895 kfree(cb->compressed_pages);
896fail1:
897 kfree(cb);
898out:
899 free_extent_map(em);
900 return ret;
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800901last_bio:
902 comp_bio->bi_status = ret;
903 /* This is the last bio, endio functions will free @cb */
904 bio_endio(comp_bio);
905 return ret;
906
907finish_cb:
908 if (comp_bio) {
909 comp_bio->bi_status = ret;
910 bio_endio(comp_bio);
911 }
912 wait_var_event(cb, atomic_read(&cb->pending_bios) == 0);
913 /*
914 * Even with previous bio ended, we should still have io not yet
915 * submitted, thus need to finish @cb manually.
916 */
917 ASSERT(refcount_read(&cb->pending_sectors));
918 /* Now we are the only one referring @cb, can finish it safely. */
919 finish_compressed_bio_read(cb, NULL);
920 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400921}
Li Zefan261507a02010-12-17 14:21:50 +0800922
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300923/*
924 * Heuristic uses systematic sampling to collect data from the input data
925 * range, the logic can be tuned by the following constants:
926 *
927 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
928 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
929 */
930#define SAMPLING_READ_SIZE (16)
931#define SAMPLING_INTERVAL (256)
932
933/*
934 * For statistical analysis of the input data we consider bytes that form a
935 * Galois Field of 256 objects. Each object has an attribute count, ie. how
936 * many times the object appeared in the sample.
937 */
938#define BUCKET_SIZE (256)
939
940/*
941 * The size of the sample is based on a statistical sampling rule of thumb.
942 * The common way is to perform sampling tests as long as the number of
943 * elements in each cell is at least 5.
944 *
945 * Instead of 5, we choose 32 to obtain more accurate results.
946 * If the data contain the maximum number of symbols, which is 256, we obtain a
947 * sample size bound by 8192.
948 *
949 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
950 * from up to 512 locations.
951 */
952#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
953 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
954
955struct bucket_item {
956 u32 count;
957};
Timofey Titovets4e439a02017-09-28 17:33:36 +0300958
959struct heuristic_ws {
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300960 /* Partial copy of input data */
961 u8 *sample;
Timofey Titovetsa440d482017-09-28 17:33:38 +0300962 u32 sample_size;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300963 /* Buckets store counters for each byte value */
964 struct bucket_item *bucket;
Timofey Titovets440c8402017-12-04 00:30:33 +0300965 /* Sorting buffer */
966 struct bucket_item *bucket_b;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300967 struct list_head list;
968};
969
Dennis Zhou92ee55302019-02-04 15:20:03 -0500970static struct workspace_manager heuristic_wsm;
971
Timofey Titovets4e439a02017-09-28 17:33:36 +0300972static void free_heuristic_ws(struct list_head *ws)
973{
974 struct heuristic_ws *workspace;
975
976 workspace = list_entry(ws, struct heuristic_ws, list);
977
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300978 kvfree(workspace->sample);
979 kfree(workspace->bucket);
Timofey Titovets440c8402017-12-04 00:30:33 +0300980 kfree(workspace->bucket_b);
Timofey Titovets4e439a02017-09-28 17:33:36 +0300981 kfree(workspace);
982}
983
Dennis Zhou7bf49942019-02-04 15:20:04 -0500984static struct list_head *alloc_heuristic_ws(unsigned int level)
Timofey Titovets4e439a02017-09-28 17:33:36 +0300985{
986 struct heuristic_ws *ws;
987
988 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
989 if (!ws)
990 return ERR_PTR(-ENOMEM);
991
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300992 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
993 if (!ws->sample)
994 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +0300995
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300996 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
997 if (!ws->bucket)
998 goto fail;
999
Timofey Titovets440c8402017-12-04 00:30:33 +03001000 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
1001 if (!ws->bucket_b)
1002 goto fail;
1003
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001004 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001005 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001006fail:
1007 free_heuristic_ws(&ws->list);
1008 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001009}
1010
Dennis Zhouca4ac362019-02-04 15:19:59 -05001011const struct btrfs_compress_op btrfs_heuristic_compress = {
David Sterbabe9510452019-10-02 00:53:31 +02001012 .workspace_manager = &heuristic_wsm,
Dennis Zhouca4ac362019-02-04 15:19:59 -05001013};
1014
David Sterbae8c9f182015-01-02 18:23:10 +01001015static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Dennis Zhouca4ac362019-02-04 15:19:59 -05001016 /* The heuristic is represented as compression type 0 */
1017 &btrfs_heuristic_compress,
Li Zefan261507a02010-12-17 14:21:50 +08001018 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +08001019 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -07001020 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +08001021};
1022
David Sterbac778df12019-10-04 02:47:39 +02001023static struct list_head *alloc_workspace(int type, unsigned int level)
1024{
1025 switch (type) {
1026 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
1027 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
1028 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
1029 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
1030 default:
1031 /*
1032 * This can't happen, the type is validated several times
1033 * before we get here.
1034 */
1035 BUG();
1036 }
1037}
1038
David Sterba1e002352019-10-04 02:57:22 +02001039static void free_workspace(int type, struct list_head *ws)
1040{
1041 switch (type) {
1042 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
1043 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
1044 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
1045 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
1046 default:
1047 /*
1048 * This can't happen, the type is validated several times
1049 * before we get here.
1050 */
1051 BUG();
1052 }
1053}
1054
David Sterbad5517032019-10-02 01:08:03 +02001055static void btrfs_init_workspace_manager(int type)
Li Zefan261507a02010-12-17 14:21:50 +08001056{
David Sterba0cf25212019-10-04 03:09:55 +02001057 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001058 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +08001059
David Sterba0cf25212019-10-04 03:09:55 +02001060 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001061 INIT_LIST_HEAD(&wsm->idle_ws);
1062 spin_lock_init(&wsm->ws_lock);
1063 atomic_set(&wsm->total_ws, 0);
1064 init_waitqueue_head(&wsm->ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +02001065
Dennis Zhou1666eda2019-02-04 15:20:01 -05001066 /*
1067 * Preallocate one workspace for each compression type so we can
1068 * guarantee forward progress in the worst case
1069 */
David Sterbac778df12019-10-04 02:47:39 +02001070 workspace = alloc_workspace(type, 0);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001071 if (IS_ERR(workspace)) {
1072 pr_warn(
1073 "BTRFS: cannot preallocate compression workspace, will try later\n");
1074 } else {
Dennis Zhou92ee55302019-02-04 15:20:03 -05001075 atomic_set(&wsm->total_ws, 1);
1076 wsm->free_ws = 1;
1077 list_add(workspace, &wsm->idle_ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001078 }
1079}
1080
David Sterba25103072019-10-02 01:08:03 +02001081static void btrfs_cleanup_workspace_manager(int type)
Dennis Zhou1666eda2019-02-04 15:20:01 -05001082{
David Sterba2dba7142019-10-04 01:40:58 +02001083 struct workspace_manager *wsman;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001084 struct list_head *ws;
1085
David Sterba2dba7142019-10-04 01:40:58 +02001086 wsman = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001087 while (!list_empty(&wsman->idle_ws)) {
1088 ws = wsman->idle_ws.next;
1089 list_del(ws);
David Sterba1e002352019-10-04 02:57:22 +02001090 free_workspace(type, ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001091 atomic_dec(&wsman->total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001092 }
Li Zefan261507a02010-12-17 14:21:50 +08001093}
1094
1095/*
David Sterbae721e492016-04-27 02:41:17 +02001096 * This finds an available workspace or allocates a new one.
1097 * If it's not possible to allocate a new one, waits until there's one.
1098 * Preallocation makes a forward progress guarantees and we do not return
1099 * errors.
Li Zefan261507a02010-12-17 14:21:50 +08001100 */
David Sterba5907a9b2019-10-04 02:50:28 +02001101struct list_head *btrfs_get_workspace(int type, unsigned int level)
Li Zefan261507a02010-12-17 14:21:50 +08001102{
David Sterba5907a9b2019-10-04 02:50:28 +02001103 struct workspace_manager *wsm;
Li Zefan261507a02010-12-17 14:21:50 +08001104 struct list_head *workspace;
1105 int cpus = num_online_cpus();
David Sterbafe308532017-05-31 17:14:56 +02001106 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001107 struct list_head *idle_ws;
1108 spinlock_t *ws_lock;
1109 atomic_t *total_ws;
1110 wait_queue_head_t *ws_wait;
1111 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001112
David Sterba5907a9b2019-10-04 02:50:28 +02001113 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001114 idle_ws = &wsm->idle_ws;
1115 ws_lock = &wsm->ws_lock;
1116 total_ws = &wsm->total_ws;
1117 ws_wait = &wsm->ws_wait;
1118 free_ws = &wsm->free_ws;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001119
Li Zefan261507a02010-12-17 14:21:50 +08001120again:
Byongho Leed9187642015-10-14 14:05:24 +09001121 spin_lock(ws_lock);
1122 if (!list_empty(idle_ws)) {
1123 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +08001124 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001125 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +09001126 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001127 return workspace;
1128
1129 }
David Sterba6ac10a62016-04-27 02:15:15 +02001130 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +08001131 DEFINE_WAIT(wait);
1132
Byongho Leed9187642015-10-14 14:05:24 +09001133 spin_unlock(ws_lock);
1134 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +02001135 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +08001136 schedule();
Byongho Leed9187642015-10-14 14:05:24 +09001137 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +08001138 goto again;
1139 }
David Sterba6ac10a62016-04-27 02:15:15 +02001140 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001141 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001142
David Sterbafe308532017-05-31 17:14:56 +02001143 /*
1144 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1145 * to turn it off here because we might get called from the restricted
1146 * context of btrfs_compress_bio/btrfs_compress_pages
1147 */
1148 nofs_flag = memalloc_nofs_save();
David Sterbac778df12019-10-04 02:47:39 +02001149 workspace = alloc_workspace(type, level);
David Sterbafe308532017-05-31 17:14:56 +02001150 memalloc_nofs_restore(nofs_flag);
1151
Li Zefan261507a02010-12-17 14:21:50 +08001152 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +02001153 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001154 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +02001155
1156 /*
1157 * Do not return the error but go back to waiting. There's a
1158 * workspace preallocated for each type and the compression
1159 * time is bounded so we get to a workspace eventually. This
1160 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +02001161 *
1162 * To prevent silent and low-probability deadlocks (when the
1163 * initial preallocation fails), check if there are any
1164 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +02001165 */
David Sterba523567162016-04-27 03:07:39 +02001166 if (atomic_read(total_ws) == 0) {
1167 static DEFINE_RATELIMIT_STATE(_rs,
1168 /* once per minute */ 60 * HZ,
1169 /* no burst */ 1);
1170
1171 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04001172 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +02001173 }
1174 }
David Sterbae721e492016-04-27 02:41:17 +02001175 goto again;
Li Zefan261507a02010-12-17 14:21:50 +08001176 }
1177 return workspace;
1178}
1179
Dennis Zhou7bf49942019-02-04 15:20:04 -05001180static struct list_head *get_workspace(int type, int level)
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001181{
David Sterba6a0d1272019-10-04 02:36:16 +02001182 switch (type) {
David Sterba5907a9b2019-10-04 02:50:28 +02001183 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001184 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
David Sterba5907a9b2019-10-04 02:50:28 +02001185 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001186 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1187 default:
1188 /*
1189 * This can't happen, the type is validated several times
1190 * before we get here.
1191 */
1192 BUG();
1193 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001194}
1195
Li Zefan261507a02010-12-17 14:21:50 +08001196/*
1197 * put a workspace struct back on the list or free it if we have enough
1198 * idle ones sitting around
1199 */
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001200void btrfs_put_workspace(int type, struct list_head *ws)
Li Zefan261507a02010-12-17 14:21:50 +08001201{
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001202 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001203 struct list_head *idle_ws;
1204 spinlock_t *ws_lock;
1205 atomic_t *total_ws;
1206 wait_queue_head_t *ws_wait;
1207 int *free_ws;
1208
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001209 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001210 idle_ws = &wsm->idle_ws;
1211 ws_lock = &wsm->ws_lock;
1212 total_ws = &wsm->total_ws;
1213 ws_wait = &wsm->ws_wait;
1214 free_ws = &wsm->free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001215
Byongho Leed9187642015-10-14 14:05:24 +09001216 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -07001217 if (*free_ws <= num_online_cpus()) {
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001218 list_add(ws, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001219 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +09001220 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001221 goto wake;
1222 }
Byongho Leed9187642015-10-14 14:05:24 +09001223 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001224
David Sterba1e002352019-10-04 02:57:22 +02001225 free_workspace(type, ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001226 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001227wake:
David Sterba093258e2018-02-26 16:15:17 +01001228 cond_wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001229}
1230
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001231static void put_workspace(int type, struct list_head *ws)
1232{
David Sterbabd3a5282019-10-04 02:42:03 +02001233 switch (type) {
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001234 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1235 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1236 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
David Sterbabd3a5282019-10-04 02:42:03 +02001237 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1238 default:
1239 /*
1240 * This can't happen, the type is validated several times
1241 * before we get here.
1242 */
1243 BUG();
1244 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001245}
1246
Li Zefan261507a02010-12-17 14:21:50 +08001247/*
Anand Jainadbab642020-05-11 22:37:51 -07001248 * Adjust @level according to the limits of the compression algorithm or
1249 * fallback to default
1250 */
1251static unsigned int btrfs_compress_set_level(int type, unsigned level)
1252{
1253 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1254
1255 if (level == 0)
1256 level = ops->default_level;
1257 else
1258 level = min(level, ops->max_level);
1259
1260 return level;
1261}
1262
1263/*
David Sterba38c31462017-02-14 19:04:07 +01001264 * Given an address space and start and length, compress the bytes into @pages
1265 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001266 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001267 * @type_level is encoded algorithm and level, where level 0 means whatever
1268 * default the algorithm chooses and is opaque here;
1269 * - compression algo are 0-3
1270 * - the level are bits 4-7
1271 *
David Sterba4d3a8002017-02-14 19:04:07 +01001272 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1273 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001274 *
David Sterba38c31462017-02-14 19:04:07 +01001275 * @total_in is used to return the number of bytes actually read. It
1276 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001277 * ran out of room in the pages array or because we cross the
1278 * max_out threshold.
1279 *
David Sterba38c31462017-02-14 19:04:07 +01001280 * @total_out is an in/out parameter, must be set to the input length and will
1281 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001282 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001283int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001284 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001285 unsigned long *out_pages,
1286 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001287 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001288{
Dennis Zhou19727082019-02-04 15:19:57 -05001289 int type = btrfs_compress_type(type_level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001290 int level = btrfs_compress_level(type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001291 struct list_head *workspace;
1292 int ret;
1293
David Sterbab0c1fe12019-08-09 16:49:06 +02001294 level = btrfs_compress_set_level(type, level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001295 workspace = get_workspace(type, level);
David Sterba1e4eb742019-10-02 00:06:15 +02001296 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1297 out_pages, total_in, total_out);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001298 put_workspace(type, workspace);
Li Zefan261507a02010-12-17 14:21:50 +08001299 return ret;
1300}
1301
Anand Jain8140dc32017-05-26 15:44:58 +08001302static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001303{
1304 struct list_head *workspace;
1305 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001306 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001307
Dennis Zhou7bf49942019-02-04 15:20:04 -05001308 workspace = get_workspace(type, 0);
David Sterba1e4eb742019-10-02 00:06:15 +02001309 ret = compression_decompress_bio(type, workspace, cb);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001310 put_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001311
Li Zefan261507a02010-12-17 14:21:50 +08001312 return ret;
1313}
1314
1315/*
1316 * a less complex decompression routine. Our compressed data fits in a
1317 * single page, and we want to read a single page out of it.
1318 * start_byte tells us the offset into the compressed data we're interested in
1319 */
1320int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1321 unsigned long start_byte, size_t srclen, size_t destlen)
1322{
1323 struct list_head *workspace;
1324 int ret;
1325
Dennis Zhou7bf49942019-02-04 15:20:04 -05001326 workspace = get_workspace(type, 0);
David Sterba1e4eb742019-10-02 00:06:15 +02001327 ret = compression_decompress(type, workspace, data_in, dest_page,
1328 start_byte, srclen, destlen);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001329 put_workspace(type, workspace);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001330
Li Zefan261507a02010-12-17 14:21:50 +08001331 return ret;
1332}
1333
Dennis Zhou1666eda2019-02-04 15:20:01 -05001334void __init btrfs_init_compress(void)
1335{
David Sterbad5517032019-10-02 01:08:03 +02001336 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1337 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1338 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1339 zstd_init_workspace_manager();
Dennis Zhou1666eda2019-02-04 15:20:01 -05001340}
1341
David Sterbae67c7182018-02-19 17:24:18 +01001342void __cold btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001343{
David Sterba25103072019-10-02 01:08:03 +02001344 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1345 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1346 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1347 zstd_cleanup_workspace_manager();
Li Zefan261507a02010-12-17 14:21:50 +08001348}
Li Zefan3a39c182010-11-08 15:22:19 +08001349
1350/*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001351 * Copy decompressed data from working buffer to pages.
Li Zefan3a39c182010-11-08 15:22:19 +08001352 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001353 * @buf: The decompressed data buffer
1354 * @buf_len: The decompressed data length
1355 * @decompressed: Number of bytes that are already decompressed inside the
1356 * compressed extent
1357 * @cb: The compressed extent descriptor
1358 * @orig_bio: The original bio that the caller wants to read for
Li Zefan3a39c182010-11-08 15:22:19 +08001359 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001360 * An easier to understand graph is like below:
1361 *
1362 * |<- orig_bio ->| |<- orig_bio->|
1363 * |<------- full decompressed extent ----->|
1364 * |<----------- @cb range ---->|
1365 * | |<-- @buf_len -->|
1366 * |<--- @decompressed --->|
1367 *
1368 * Note that, @cb can be a subpage of the full decompressed extent, but
1369 * @cb->start always has the same as the orig_file_offset value of the full
1370 * decompressed extent.
1371 *
1372 * When reading compressed extent, we have to read the full compressed extent,
1373 * while @orig_bio may only want part of the range.
1374 * Thus this function will ensure only data covered by @orig_bio will be copied
1375 * to.
1376 *
1377 * Return 0 if we have copied all needed contents for @orig_bio.
1378 * Return >0 if we need continue decompress.
Li Zefan3a39c182010-11-08 15:22:19 +08001379 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001380int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1381 struct compressed_bio *cb, u32 decompressed)
Li Zefan3a39c182010-11-08 15:22:19 +08001382{
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001383 struct bio *orig_bio = cb->orig_bio;
1384 /* Offset inside the full decompressed extent */
1385 u32 cur_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001386
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001387 cur_offset = decompressed;
1388 /* The main loop to do the copy */
1389 while (cur_offset < decompressed + buf_len) {
1390 struct bio_vec bvec;
1391 size_t copy_len;
1392 u32 copy_start;
1393 /* Offset inside the full decompressed extent */
1394 u32 bvec_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001395
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001396 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1397 /*
1398 * cb->start may underflow, but subtracting that value can still
1399 * give us correct offset inside the full decompressed extent.
1400 */
1401 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
Li Zefan3a39c182010-11-08 15:22:19 +08001402
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001403 /* Haven't reached the bvec range, exit */
1404 if (decompressed + buf_len <= bvec_offset)
1405 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001406
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001407 copy_start = max(cur_offset, bvec_offset);
1408 copy_len = min(bvec_offset + bvec.bv_len,
1409 decompressed + buf_len) - copy_start;
1410 ASSERT(copy_len);
Li Zefan3a39c182010-11-08 15:22:19 +08001411
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001412 /*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001413 * Extra range check to ensure we didn't go beyond
1414 * @buf + @buf_len.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001415 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001416 ASSERT(copy_start - decompressed < buf_len);
1417 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1418 buf + copy_start - decompressed, copy_len);
1419 flush_dcache_page(bvec.bv_page);
1420 cur_offset += copy_len;
Li Zefan3a39c182010-11-08 15:22:19 +08001421
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001422 bio_advance(orig_bio, copy_len);
1423 /* Finished the bio */
1424 if (!orig_bio->bi_iter.bi_size)
1425 return 0;
Li Zefan3a39c182010-11-08 15:22:19 +08001426 }
Li Zefan3a39c182010-11-08 15:22:19 +08001427 return 1;
1428}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001429
Timofey Titovets19562432017-10-08 16:11:59 +03001430/*
1431 * Shannon Entropy calculation
1432 *
Andrea Gelmini52042d82018-11-28 12:05:13 +01001433 * Pure byte distribution analysis fails to determine compressibility of data.
Timofey Titovets19562432017-10-08 16:11:59 +03001434 * Try calculating entropy to estimate the average minimum number of bits
1435 * needed to encode the sampled data.
1436 *
1437 * For convenience, return the percentage of needed bits, instead of amount of
1438 * bits directly.
1439 *
1440 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1441 * and can be compressible with high probability
1442 *
1443 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1444 *
1445 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1446 */
1447#define ENTROPY_LVL_ACEPTABLE (65)
1448#define ENTROPY_LVL_HIGH (80)
1449
1450/*
1451 * For increasead precision in shannon_entropy calculation,
1452 * let's do pow(n, M) to save more digits after comma:
1453 *
1454 * - maximum int bit length is 64
1455 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1456 * - 13 * 4 = 52 < 64 -> M = 4
1457 *
1458 * So use pow(n, 4).
1459 */
1460static inline u32 ilog2_w(u64 n)
1461{
1462 return ilog2(n * n * n * n);
1463}
1464
1465static u32 shannon_entropy(struct heuristic_ws *ws)
1466{
1467 const u32 entropy_max = 8 * ilog2_w(2);
1468 u32 entropy_sum = 0;
1469 u32 p, p_base, sz_base;
1470 u32 i;
1471
1472 sz_base = ilog2_w(ws->sample_size);
1473 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1474 p = ws->bucket[i].count;
1475 p_base = ilog2_w(p);
1476 entropy_sum += p * (sz_base - p_base);
1477 }
1478
1479 entropy_sum /= ws->sample_size;
1480 return entropy_sum * 100 / entropy_max;
1481}
1482
Timofey Titovets440c8402017-12-04 00:30:33 +03001483#define RADIX_BASE 4U
1484#define COUNTERS_SIZE (1U << RADIX_BASE)
Timofey Titovets858177d2017-09-28 17:33:41 +03001485
Timofey Titovets440c8402017-12-04 00:30:33 +03001486static u8 get4bits(u64 num, int shift) {
1487 u8 low4bits;
1488
1489 num >>= shift;
1490 /* Reverse order */
1491 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1492 return low4bits;
1493}
1494
Timofey Titovets440c8402017-12-04 00:30:33 +03001495/*
1496 * Use 4 bits as radix base
Andrea Gelmini52042d82018-11-28 12:05:13 +01001497 * Use 16 u32 counters for calculating new position in buf array
Timofey Titovets440c8402017-12-04 00:30:33 +03001498 *
1499 * @array - array that will be sorted
1500 * @array_buf - buffer array to store sorting results
1501 * must be equal in size to @array
1502 * @num - array size
Timofey Titovets440c8402017-12-04 00:30:33 +03001503 */
David Sterba23ae8c62017-12-12 20:35:02 +01001504static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
David Sterba36243c92017-12-12 20:35:02 +01001505 int num)
Timofey Titovets440c8402017-12-04 00:30:33 +03001506{
1507 u64 max_num;
1508 u64 buf_num;
1509 u32 counters[COUNTERS_SIZE];
1510 u32 new_addr;
1511 u32 addr;
1512 int bitlen;
1513 int shift;
1514 int i;
1515
1516 /*
1517 * Try avoid useless loop iterations for small numbers stored in big
1518 * counters. Example: 48 33 4 ... in 64bit array
1519 */
David Sterba23ae8c62017-12-12 20:35:02 +01001520 max_num = array[0].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001521 for (i = 1; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001522 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001523 if (buf_num > max_num)
1524 max_num = buf_num;
1525 }
1526
1527 buf_num = ilog2(max_num);
1528 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1529
1530 shift = 0;
1531 while (shift < bitlen) {
1532 memset(counters, 0, sizeof(counters));
1533
1534 for (i = 0; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001535 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001536 addr = get4bits(buf_num, shift);
1537 counters[addr]++;
1538 }
1539
1540 for (i = 1; i < COUNTERS_SIZE; i++)
1541 counters[i] += counters[i - 1];
1542
1543 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001544 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001545 addr = get4bits(buf_num, shift);
1546 counters[addr]--;
1547 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001548 array_buf[new_addr] = array[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001549 }
1550
1551 shift += RADIX_BASE;
1552
1553 /*
1554 * Normal radix expects to move data from a temporary array, to
1555 * the main one. But that requires some CPU time. Avoid that
1556 * by doing another sort iteration to original array instead of
1557 * memcpy()
1558 */
1559 memset(counters, 0, sizeof(counters));
1560
1561 for (i = 0; i < num; i ++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001562 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001563 addr = get4bits(buf_num, shift);
1564 counters[addr]++;
1565 }
1566
1567 for (i = 1; i < COUNTERS_SIZE; i++)
1568 counters[i] += counters[i - 1];
1569
1570 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001571 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001572 addr = get4bits(buf_num, shift);
1573 counters[addr]--;
1574 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001575 array[new_addr] = array_buf[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001576 }
1577
1578 shift += RADIX_BASE;
1579 }
Timofey Titovets858177d2017-09-28 17:33:41 +03001580}
1581
1582/*
1583 * Size of the core byte set - how many bytes cover 90% of the sample
1584 *
1585 * There are several types of structured binary data that use nearly all byte
1586 * values. The distribution can be uniform and counts in all buckets will be
1587 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1588 *
1589 * Other possibility is normal (Gaussian) distribution, where the data could
1590 * be potentially compressible, but we have to take a few more steps to decide
1591 * how much.
1592 *
1593 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1594 * compression algo can easy fix that
1595 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1596 * probability is not compressible
1597 */
1598#define BYTE_CORE_SET_LOW (64)
1599#define BYTE_CORE_SET_HIGH (200)
1600
1601static int byte_core_set_size(struct heuristic_ws *ws)
1602{
1603 u32 i;
1604 u32 coreset_sum = 0;
1605 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1606 struct bucket_item *bucket = ws->bucket;
1607
1608 /* Sort in reverse order */
David Sterba36243c92017-12-12 20:35:02 +01001609 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
Timofey Titovets858177d2017-09-28 17:33:41 +03001610
1611 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1612 coreset_sum += bucket[i].count;
1613
1614 if (coreset_sum > core_set_threshold)
1615 return i;
1616
1617 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1618 coreset_sum += bucket[i].count;
1619 if (coreset_sum > core_set_threshold)
1620 break;
1621 }
1622
1623 return i;
1624}
1625
Timofey Titovetsa288e922017-09-28 17:33:40 +03001626/*
1627 * Count byte values in buckets.
1628 * This heuristic can detect textual data (configs, xml, json, html, etc).
1629 * Because in most text-like data byte set is restricted to limited number of
1630 * possible characters, and that restriction in most cases makes data easy to
1631 * compress.
1632 *
1633 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1634 * less - compressible
1635 * more - need additional analysis
1636 */
1637#define BYTE_SET_THRESHOLD (64)
1638
1639static u32 byte_set_size(const struct heuristic_ws *ws)
1640{
1641 u32 i;
1642 u32 byte_set_size = 0;
1643
1644 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1645 if (ws->bucket[i].count > 0)
1646 byte_set_size++;
1647 }
1648
1649 /*
1650 * Continue collecting count of byte values in buckets. If the byte
1651 * set size is bigger then the threshold, it's pointless to continue,
1652 * the detection technique would fail for this type of data.
1653 */
1654 for (; i < BUCKET_SIZE; i++) {
1655 if (ws->bucket[i].count > 0) {
1656 byte_set_size++;
1657 if (byte_set_size > BYTE_SET_THRESHOLD)
1658 return byte_set_size;
1659 }
1660 }
1661
1662 return byte_set_size;
1663}
1664
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001665static bool sample_repeated_patterns(struct heuristic_ws *ws)
1666{
1667 const u32 half_of_sample = ws->sample_size / 2;
1668 const u8 *data = ws->sample;
1669
1670 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1671}
1672
Timofey Titovetsa440d482017-09-28 17:33:38 +03001673static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1674 struct heuristic_ws *ws)
1675{
1676 struct page *page;
1677 u64 index, index_end;
1678 u32 i, curr_sample_pos;
1679 u8 *in_data;
1680
1681 /*
1682 * Compression handles the input data by chunks of 128KiB
1683 * (defined by BTRFS_MAX_UNCOMPRESSED)
1684 *
1685 * We do the same for the heuristic and loop over the whole range.
1686 *
1687 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1688 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1689 */
1690 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1691 end = start + BTRFS_MAX_UNCOMPRESSED;
1692
1693 index = start >> PAGE_SHIFT;
1694 index_end = end >> PAGE_SHIFT;
1695
1696 /* Don't miss unaligned end */
1697 if (!IS_ALIGNED(end, PAGE_SIZE))
1698 index_end++;
1699
1700 curr_sample_pos = 0;
1701 while (index < index_end) {
1702 page = find_get_page(inode->i_mapping, index);
Ira Weiny58c1a352021-02-16 18:48:23 -08001703 in_data = kmap_local_page(page);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001704 /* Handle case where the start is not aligned to PAGE_SIZE */
1705 i = start % PAGE_SIZE;
1706 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1707 /* Don't sample any garbage from the last page */
1708 if (start > end - SAMPLING_READ_SIZE)
1709 break;
1710 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1711 SAMPLING_READ_SIZE);
1712 i += SAMPLING_INTERVAL;
1713 start += SAMPLING_INTERVAL;
1714 curr_sample_pos += SAMPLING_READ_SIZE;
1715 }
Ira Weiny58c1a352021-02-16 18:48:23 -08001716 kunmap_local(in_data);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001717 put_page(page);
1718
1719 index++;
1720 }
1721
1722 ws->sample_size = curr_sample_pos;
1723}
1724
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001725/*
1726 * Compression heuristic.
1727 *
1728 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1729 * quickly (compared to direct compression) detect data characteristics
1730 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1731 * data.
1732 *
1733 * The following types of analysis can be performed:
1734 * - detect mostly zero data
1735 * - detect data with low "byte set" size (text, etc)
1736 * - detect data with low/high "core byte" set
1737 *
1738 * Return non-zero if the compression should be done, 0 otherwise.
1739 */
1740int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1741{
Dennis Zhou7bf49942019-02-04 15:20:04 -05001742 struct list_head *ws_list = get_workspace(0, 0);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001743 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001744 u32 i;
1745 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001746 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001747
Timofey Titovets4e439a02017-09-28 17:33:36 +03001748 ws = list_entry(ws_list, struct heuristic_ws, list);
1749
Timofey Titovetsa440d482017-09-28 17:33:38 +03001750 heuristic_collect_sample(inode, start, end, ws);
1751
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001752 if (sample_repeated_patterns(ws)) {
1753 ret = 1;
1754 goto out;
1755 }
1756
Timofey Titovetsa440d482017-09-28 17:33:38 +03001757 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1758
1759 for (i = 0; i < ws->sample_size; i++) {
1760 byte = ws->sample[i];
1761 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001762 }
1763
Timofey Titovetsa288e922017-09-28 17:33:40 +03001764 i = byte_set_size(ws);
1765 if (i < BYTE_SET_THRESHOLD) {
1766 ret = 2;
1767 goto out;
1768 }
1769
Timofey Titovets858177d2017-09-28 17:33:41 +03001770 i = byte_core_set_size(ws);
1771 if (i <= BYTE_CORE_SET_LOW) {
1772 ret = 3;
1773 goto out;
1774 }
1775
1776 if (i >= BYTE_CORE_SET_HIGH) {
1777 ret = 0;
1778 goto out;
1779 }
1780
Timofey Titovets19562432017-10-08 16:11:59 +03001781 i = shannon_entropy(ws);
1782 if (i <= ENTROPY_LVL_ACEPTABLE) {
1783 ret = 4;
1784 goto out;
1785 }
1786
1787 /*
1788 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1789 * needed to give green light to compression.
1790 *
1791 * For now just assume that compression at that level is not worth the
1792 * resources because:
1793 *
1794 * 1. it is possible to defrag the data later
1795 *
1796 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1797 * values, every bucket has counter at level ~54. The heuristic would
1798 * be confused. This can happen when data have some internal repeated
1799 * patterns like "abbacbbc...". This can be detected by analyzing
1800 * pairs of bytes, which is too costly.
1801 */
1802 if (i < ENTROPY_LVL_HIGH) {
1803 ret = 5;
1804 goto out;
1805 } else {
1806 ret = 0;
1807 goto out;
1808 }
1809
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001810out:
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001811 put_workspace(0, ws_list);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001812 return ret;
1813}
David Sterbaf51d2b52017-09-15 17:36:57 +02001814
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001815/*
1816 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1817 * level, unrecognized string will set the default level
1818 */
1819unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
David Sterbaf51d2b52017-09-15 17:36:57 +02001820{
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001821 unsigned int level = 0;
1822 int ret;
1823
1824 if (!type)
David Sterbaf51d2b52017-09-15 17:36:57 +02001825 return 0;
1826
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001827 if (str[0] == ':') {
1828 ret = kstrtouint(str + 1, 10, &level);
1829 if (ret)
1830 level = 0;
1831 }
David Sterbaf51d2b52017-09-15 17:36:57 +02001832
David Sterbab0c1fe12019-08-09 16:49:06 +02001833 level = btrfs_compress_set_level(type, level);
1834
1835 return level;
1836}