blob: 71e5b2e9a1ba822b51049ca466bfeeb505bc277c [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>
Christoph Hellwige41d12f2021-09-20 14:33:13 +020012#include <linux/kthread.h>
Chris Masonc8b97812008-10-29 14:49:59 -040013#include <linux/time.h>
14#include <linux/init.h>
15#include <linux/string.h>
Chris Masonc8b97812008-10-29 14:49:59 -040016#include <linux/backing-dev.h>
Chris Masonc8b97812008-10-29 14:49:59 -040017#include <linux/writeback.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/slab.h>
David Sterbafe308532017-05-31 17:14:56 +020019#include <linux/sched/mm.h>
Timofey Titovets19562432017-10-08 16:11:59 +030020#include <linux/log2.h>
Johannes Thumshirnd5178572019-06-03 16:58:57 +020021#include <crypto/hash.h>
David Sterba602cbe92019-08-21 18:48:25 +020022#include "misc.h"
Chris Masonc8b97812008-10-29 14:49:59 -040023#include "ctree.h"
24#include "disk-io.h"
25#include "transaction.h"
26#include "btrfs_inode.h"
27#include "volumes.h"
28#include "ordered-data.h"
Chris Masonc8b97812008-10-29 14:49:59 -040029#include "compression.h"
30#include "extent_io.h"
31#include "extent_map.h"
Qu Wenruo6a404912021-09-27 15:21:47 +080032#include "subpage.h"
Johannes Thumshirn764c7c92021-05-19 00:40:28 +090033#include "zoned.h"
Chris Masonc8b97812008-10-29 14:49:59 -040034
David Sterbae128f9c2017-10-31 17:24:26 +010035static const char* const btrfs_compress_types[] = { "", "zlib", "lzo", "zstd" };
36
37const char* btrfs_compress_type2str(enum btrfs_compression_type type)
38{
39 switch (type) {
40 case BTRFS_COMPRESS_ZLIB:
41 case BTRFS_COMPRESS_LZO:
42 case BTRFS_COMPRESS_ZSTD:
43 case BTRFS_COMPRESS_NONE:
44 return btrfs_compress_types[type];
Chengguang Xuce96b7f2019-10-10 15:59:57 +080045 default:
46 break;
David Sterbae128f9c2017-10-31 17:24:26 +010047 }
48
49 return NULL;
50}
51
Johannes Thumshirnaa53e3b2019-06-06 12:07:15 +020052bool btrfs_compress_is_valid_type(const char *str, size_t len)
53{
54 int i;
55
56 for (i = 1; i < ARRAY_SIZE(btrfs_compress_types); i++) {
57 size_t comp_len = strlen(btrfs_compress_types[i]);
58
59 if (len < comp_len)
60 continue;
61
62 if (!strncmp(btrfs_compress_types[i], str, comp_len))
63 return true;
64 }
65 return false;
66}
67
David Sterba1e4eb742019-10-02 00:06:15 +020068static int compression_compress_pages(int type, struct list_head *ws,
69 struct address_space *mapping, u64 start, struct page **pages,
70 unsigned long *out_pages, unsigned long *total_in,
71 unsigned long *total_out)
72{
73 switch (type) {
74 case BTRFS_COMPRESS_ZLIB:
75 return zlib_compress_pages(ws, mapping, start, pages,
76 out_pages, total_in, total_out);
77 case BTRFS_COMPRESS_LZO:
78 return lzo_compress_pages(ws, mapping, start, pages,
79 out_pages, total_in, total_out);
80 case BTRFS_COMPRESS_ZSTD:
81 return zstd_compress_pages(ws, mapping, start, pages,
82 out_pages, total_in, total_out);
83 case BTRFS_COMPRESS_NONE:
84 default:
85 /*
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080086 * This can happen when compression races with remount setting
87 * it to 'no compress', while caller doesn't call
88 * inode_need_compress() to check if we really need to
89 * compress.
90 *
91 * Not a big deal, just need to inform caller that we
92 * haven't allocated any pages yet.
David Sterba1e4eb742019-10-02 00:06:15 +020093 */
Qu Wenruo1d8ba9e2020-08-04 15:25:47 +080094 *out_pages = 0;
David Sterba1e4eb742019-10-02 00:06:15 +020095 return -E2BIG;
96 }
97}
98
Su Yue4a9e8032021-12-27 18:18:39 +080099static int compression_decompress_bio(struct list_head *ws,
100 struct compressed_bio *cb)
David Sterba1e4eb742019-10-02 00:06:15 +0200101{
Su Yue4a9e8032021-12-27 18:18:39 +0800102 switch (cb->compress_type) {
David Sterba1e4eb742019-10-02 00:06:15 +0200103 case BTRFS_COMPRESS_ZLIB: return zlib_decompress_bio(ws, cb);
104 case BTRFS_COMPRESS_LZO: return lzo_decompress_bio(ws, cb);
105 case BTRFS_COMPRESS_ZSTD: return zstd_decompress_bio(ws, cb);
106 case BTRFS_COMPRESS_NONE:
107 default:
108 /*
109 * This can't happen, the type is validated several times
110 * before we get here.
111 */
112 BUG();
113 }
114}
115
116static int compression_decompress(int type, struct list_head *ws,
117 unsigned char *data_in, struct page *dest_page,
118 unsigned long start_byte, size_t srclen, size_t destlen)
119{
120 switch (type) {
121 case BTRFS_COMPRESS_ZLIB: return zlib_decompress(ws, data_in, dest_page,
122 start_byte, srclen, destlen);
123 case BTRFS_COMPRESS_LZO: return lzo_decompress(ws, data_in, dest_page,
124 start_byte, srclen, destlen);
125 case BTRFS_COMPRESS_ZSTD: return zstd_decompress(ws, data_in, dest_page,
126 start_byte, srclen, destlen);
127 case BTRFS_COMPRESS_NONE:
128 default:
129 /*
130 * This can't happen, the type is validated several times
131 * before we get here.
132 */
133 BUG();
134 }
135}
136
Anand Jain8140dc32017-05-26 15:44:58 +0800137static int btrfs_decompress_bio(struct compressed_bio *cb);
Eric Sandeen48a3b632013-04-25 20:41:01 +0000138
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400139static inline int compressed_bio_size(struct btrfs_fs_info *fs_info,
Chris Masond20f7042008-12-08 16:58:54 -0500140 unsigned long disk_size)
141{
Chris Masond20f7042008-12-08 16:58:54 -0500142 return sizeof(struct compressed_bio) +
David Sterba713cebf2020-06-30 18:04:02 +0200143 (DIV_ROUND_UP(disk_size, fs_info->sectorsize)) * fs_info->csum_size;
Chris Masond20f7042008-12-08 16:58:54 -0500144}
145
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300146static int check_compressed_csum(struct btrfs_inode *inode, struct bio *bio,
Chris Masond20f7042008-12-08 16:58:54 -0500147 u64 disk_start)
148{
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200149 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200150 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
David Sterba223486c2020-07-02 11:27:30 +0200151 const u32 csum_size = fs_info->csum_size;
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800152 const u32 sectorsize = fs_info->sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500153 struct page *page;
Anand Jain1d08ce582021-05-29 17:48:33 +0800154 unsigned int i;
Chris Masond20f7042008-12-08 16:58:54 -0500155 char *kaddr;
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200156 u8 csum[BTRFS_CSUM_SIZE];
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300157 struct compressed_bio *cb = bio->bi_private;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200158 u8 *cb_sum = cb->sums;
Chris Masond20f7042008-12-08 16:58:54 -0500159
Josef Bacik056c8312021-11-05 16:45:47 -0400160 if ((inode->flags & BTRFS_INODE_NODATASUM) ||
161 test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state))
Chris Masond20f7042008-12-08 16:58:54 -0500162 return 0;
163
Johannes Thumshirnd5178572019-06-03 16:58:57 +0200164 shash->tfm = fs_info->csum_shash;
165
Chris Masond20f7042008-12-08 16:58:54 -0500166 for (i = 0; i < cb->nr_pages; i++) {
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800167 u32 pg_offset;
168 u32 bytes_left = PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500169 page = cb->compressed_pages[i];
Chris Masond20f7042008-12-08 16:58:54 -0500170
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800171 /* Determine the remaining bytes inside the page first */
172 if (i == cb->nr_pages - 1)
173 bytes_left = cb->compressed_len - i * PAGE_SIZE;
Chris Masond20f7042008-12-08 16:58:54 -0500174
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800175 /* Hash through the page sector by sector */
176 for (pg_offset = 0; pg_offset < bytes_left;
177 pg_offset += sectorsize) {
David Sterba3a60f652021-10-27 10:39:03 +0200178 kaddr = kmap_atomic(page);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800179 crypto_shash_digest(shash, kaddr + pg_offset,
180 sectorsize, csum);
David Sterba3a60f652021-10-27 10:39:03 +0200181 kunmap_atomic(kaddr);
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800182
183 if (memcmp(&csum, cb_sum, csum_size) != 0) {
184 btrfs_print_data_csum_error(inode, disk_start,
185 csum, cb_sum, cb->mirror_num);
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800186 if (btrfs_bio(bio)->device)
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800187 btrfs_dev_stat_inc_and_print(
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800188 btrfs_bio(bio)->device,
Qu Wenruo04d4ba4c2021-02-04 15:03:24 +0800189 BTRFS_DEV_STAT_CORRUPTION_ERRS);
190 return -EIO;
191 }
192 cb_sum += csum_size;
193 disk_start += sectorsize;
Chris Masond20f7042008-12-08 16:58:54 -0500194 }
Chris Masond20f7042008-12-08 16:58:54 -0500195 }
Nikolay Borisov93c4c032020-07-02 16:46:47 +0300196 return 0;
Chris Masond20f7042008-12-08 16:58:54 -0500197}
198
Qu Wenruo6ec97652021-09-27 15:21:48 +0800199/*
200 * Reduce bio and io accounting for a compressed_bio with its corresponding bio.
201 *
202 * Return true if there is no pending bio nor io.
203 * Return false otherwise.
204 */
205static bool dec_and_test_compressed_bio(struct compressed_bio *cb, struct bio *bio)
206{
207 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
208 unsigned int bi_size = 0;
209 bool last_io = false;
210 struct bio_vec *bvec;
211 struct bvec_iter_all iter_all;
212
213 /*
214 * At endio time, bi_iter.bi_size doesn't represent the real bio size.
215 * Thus here we have to iterate through all segments to grab correct
216 * bio size.
217 */
218 bio_for_each_segment_all(bvec, bio, iter_all)
219 bi_size += bvec->bv_len;
220
221 if (bio->bi_status)
222 cb->errors = 1;
223
224 ASSERT(bi_size && bi_size <= cb->compressed_len);
225 last_io = refcount_sub_and_test(bi_size >> fs_info->sectorsize_bits,
226 &cb->pending_sectors);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800227 /*
228 * Here we must wake up the possible error handler after all other
229 * operations on @cb finished, or we can race with
230 * finish_compressed_bio_*() which may free @cb.
231 */
232 wake_up_var(cb);
233
Qu Wenruo6ec97652021-09-27 15:21:48 +0800234 return last_io;
235}
236
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800237static void finish_compressed_bio_read(struct compressed_bio *cb, struct bio *bio)
238{
239 unsigned int index;
240 struct page *page;
241
242 /* Release the compressed pages */
243 for (index = 0; index < cb->nr_pages; index++) {
244 page = cb->compressed_pages[index];
245 page->mapping = NULL;
246 put_page(page);
247 }
248
249 /* Do io completion on the original bio */
250 if (cb->errors) {
251 bio_io_error(cb->orig_bio);
252 } else {
253 struct bio_vec *bvec;
254 struct bvec_iter_all iter_all;
255
256 ASSERT(bio);
257 ASSERT(!bio->bi_status);
258 /*
259 * We have verified the checksum already, set page checked so
260 * the end_io handlers know about it
261 */
262 ASSERT(!bio_flagged(bio, BIO_CLONED));
263 bio_for_each_segment_all(bvec, cb->orig_bio, iter_all) {
264 u64 bvec_start = page_offset(bvec->bv_page) +
265 bvec->bv_offset;
266
267 btrfs_page_set_checked(btrfs_sb(cb->inode->i_sb),
268 bvec->bv_page, bvec_start,
269 bvec->bv_len);
270 }
271
272 bio_endio(cb->orig_bio);
273 }
274
275 /* Finally free the cb struct */
276 kfree(cb->compressed_pages);
277 kfree(cb);
278}
279
Chris Masonc8b97812008-10-29 14:49:59 -0400280/* when we finish reading compressed pages from the disk, we
281 * decompress them and then run the bio end_io routines on the
282 * decompressed pages (in the inode address space).
283 *
284 * This allows the checksumming and other IO error handling routines
285 * to work normally
286 *
287 * The compressed pages are freed here, and it must be run
288 * in process context
289 */
Christoph Hellwig4246a0b2015-07-20 15:29:37 +0200290static void end_compressed_bio_read(struct bio *bio)
Chris Masonc8b97812008-10-29 14:49:59 -0400291{
Chris Masonc8b97812008-10-29 14:49:59 -0400292 struct compressed_bio *cb = bio->bi_private;
293 struct inode *inode;
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800294 unsigned int mirror = btrfs_bio(bio)->mirror_num;
Liu Boe6311f22017-09-20 17:50:19 -0600295 int ret = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400296
Qu Wenruo6ec97652021-09-27 15:21:48 +0800297 if (!dec_and_test_compressed_bio(cb, bio))
Chris Masonc8b97812008-10-29 14:49:59 -0400298 goto out;
299
Liu Bocf1167d2017-09-20 17:50:18 -0600300 /*
301 * Record the correct mirror_num in cb->orig_bio so that
302 * read-repair can work properly.
303 */
Qu Wenruoc3a3b192021-09-15 15:17:18 +0800304 btrfs_bio(cb->orig_bio)->mirror_num = mirror;
Liu Bocf1167d2017-09-20 17:50:18 -0600305 cb->mirror_num = mirror;
306
Liu Boe6311f22017-09-20 17:50:19 -0600307 /*
308 * Some IO in this cb have failed, just skip checksum as there
309 * is no way it could be correct.
310 */
311 if (cb->errors == 1)
312 goto csum_failed;
313
Chris Masond20f7042008-12-08 16:58:54 -0500314 inode = cb->inode;
Nikolay Borisov5a9472f2020-07-02 15:23:34 +0300315 ret = check_compressed_csum(BTRFS_I(inode), bio,
David Sterba1201b582020-11-26 15:41:27 +0100316 bio->bi_iter.bi_sector << 9);
Chris Masond20f7042008-12-08 16:58:54 -0500317 if (ret)
318 goto csum_failed;
319
Chris Masonc8b97812008-10-29 14:49:59 -0400320 /* ok, we're the last bio for this extent, lets start
321 * the decompression.
322 */
Anand Jain8140dc32017-05-26 15:44:58 +0800323 ret = btrfs_decompress_bio(cb);
324
Chris Masond20f7042008-12-08 16:58:54 -0500325csum_failed:
Chris Masonc8b97812008-10-29 14:49:59 -0400326 if (ret)
327 cb->errors = 1;
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800328 finish_compressed_bio_read(cb, bio);
Chris Masonc8b97812008-10-29 14:49:59 -0400329out:
330 bio_put(bio);
331}
332
333/*
334 * Clear the writeback bits on all of the file
335 * pages for a compressed write
336 */
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100337static noinline void end_compressed_writeback(struct inode *inode,
338 const struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400339{
Qu Wenruo741ec652021-09-27 15:22:01 +0800340 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300341 unsigned long index = cb->start >> PAGE_SHIFT;
342 unsigned long end_index = (cb->start + cb->len - 1) >> PAGE_SHIFT;
Chris Masonc8b97812008-10-29 14:49:59 -0400343 struct page *pages[16];
344 unsigned long nr_pages = end_index - index + 1;
345 int i;
346 int ret;
347
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100348 if (cb->errors)
349 mapping_set_error(inode->i_mapping, -EIO);
350
Chris Masond3977122009-01-05 21:25:51 -0500351 while (nr_pages > 0) {
Chris Masonc8b97812008-10-29 14:49:59 -0400352 ret = find_get_pages_contig(inode->i_mapping, index,
Chris Mason5b050f02008-11-11 09:34:41 -0500353 min_t(unsigned long,
354 nr_pages, ARRAY_SIZE(pages)), pages);
Chris Masonc8b97812008-10-29 14:49:59 -0400355 if (ret == 0) {
356 nr_pages -= 1;
357 index += 1;
358 continue;
359 }
360 for (i = 0; i < ret; i++) {
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100361 if (cb->errors)
362 SetPageError(pages[i]);
Qu Wenruo741ec652021-09-27 15:22:01 +0800363 btrfs_page_clamp_clear_writeback(fs_info, pages[i],
364 cb->start, cb->len);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300365 put_page(pages[i]);
Chris Masonc8b97812008-10-29 14:49:59 -0400366 }
367 nr_pages -= ret;
368 index += ret;
369 }
370 /* the inode may be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400371}
372
Qu Wenruo6853c642021-09-27 15:21:51 +0800373static void finish_compressed_bio_write(struct compressed_bio *cb)
Chris Masonc8b97812008-10-29 14:49:59 -0400374{
Qu Wenruo6853c642021-09-27 15:21:51 +0800375 struct inode *inode = cb->inode;
Anand Jain1d08ce582021-05-29 17:48:33 +0800376 unsigned int index;
Chris Masonc8b97812008-10-29 14:49:59 -0400377
Qu Wenruo6853c642021-09-27 15:21:51 +0800378 /*
379 * Ok, we're the last bio for this extent, step one is to call back
380 * into the FS and do all the end_io operations.
Chris Masonc8b97812008-10-29 14:49:59 -0400381 */
Qu Wenruo38a39ac72021-04-08 20:32:27 +0800382 btrfs_writepage_endio_finish_ordered(BTRFS_I(inode), NULL,
Nikolay Borisovc6297322018-11-08 10:18:08 +0200383 cb->start, cb->start + cb->len - 1,
Goldwyn Rodrigues240246f2021-07-09 11:29:22 -0500384 !cb->errors);
Chris Masonc8b97812008-10-29 14:49:59 -0400385
Filipe Manana7bdcefc2014-10-07 01:48:26 +0100386 end_compressed_writeback(inode, cb);
Qu Wenruo6853c642021-09-27 15:21:51 +0800387 /* Note, our inode could be gone now */
Chris Masonc8b97812008-10-29 14:49:59 -0400388
389 /*
Qu Wenruo6853c642021-09-27 15:21:51 +0800390 * Release the compressed pages, these came from alloc_page and
Chris Masonc8b97812008-10-29 14:49:59 -0400391 * are not attached to the inode at all
392 */
Chris Masonc8b97812008-10-29 14:49:59 -0400393 for (index = 0; index < cb->nr_pages; index++) {
Qu Wenruo6853c642021-09-27 15:21:51 +0800394 struct page *page = cb->compressed_pages[index];
395
Chris Masonc8b97812008-10-29 14:49:59 -0400396 page->mapping = NULL;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300397 put_page(page);
Chris Masonc8b97812008-10-29 14:49:59 -0400398 }
399
Qu Wenruo6853c642021-09-27 15:21:51 +0800400 /* Finally free the cb struct */
Chris Masonc8b97812008-10-29 14:49:59 -0400401 kfree(cb->compressed_pages);
402 kfree(cb);
Qu Wenruo6853c642021-09-27 15:21:51 +0800403}
404
405/*
406 * Do the cleanup once all the compressed pages hit the disk. This will clear
407 * writeback on the file pages and free the compressed pages.
408 *
409 * This also calls the writeback end hooks for the file pages so that metadata
410 * and checksums can be updated in the file.
411 */
412static void end_compressed_bio_write(struct bio *bio)
413{
414 struct compressed_bio *cb = bio->bi_private;
415
416 if (!dec_and_test_compressed_bio(cb, bio))
417 goto out;
418
419 btrfs_record_physical_zoned(cb->inode, cb->start, bio);
420
421 finish_compressed_bio_write(cb);
Chris Masonc8b97812008-10-29 14:49:59 -0400422out:
423 bio_put(bio);
424}
425
Qu Wenruo2d4e0b82021-09-27 15:21:52 +0800426static blk_status_t submit_compressed_bio(struct btrfs_fs_info *fs_info,
427 struct compressed_bio *cb,
428 struct bio *bio, int mirror_num)
429{
430 blk_status_t ret;
431
432 ASSERT(bio->bi_iter.bi_size);
Qu Wenruo2d4e0b82021-09-27 15:21:52 +0800433 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
434 if (ret)
435 return ret;
436 ret = btrfs_map_bio(fs_info, bio, mirror_num);
437 return ret;
438}
439
Chris Masonc8b97812008-10-29 14:49:59 -0400440/*
Qu Wenruof472c28f2021-09-27 15:21:54 +0800441 * Allocate a compressed_bio, which will be used to read/write on-disk
442 * (aka, compressed) * data.
443 *
444 * @cb: The compressed_bio structure, which records all the needed
445 * information to bind the compressed data to the uncompressed
446 * page cache.
447 * @disk_byten: The logical bytenr where the compressed data will be read
448 * from or written to.
449 * @endio_func: The endio function to call after the IO for compressed data
450 * is finished.
451 * @next_stripe_start: Return value of logical bytenr of where next stripe starts.
452 * Let the caller know to only fill the bio up to the stripe
453 * boundary.
Qu Wenruo22c306f2021-09-27 15:21:53 +0800454 */
Qu Wenruof472c28f2021-09-27 15:21:54 +0800455
456
Qu Wenruo22c306f2021-09-27 15:21:53 +0800457static struct bio *alloc_compressed_bio(struct compressed_bio *cb, u64 disk_bytenr,
Qu Wenruof472c28f2021-09-27 15:21:54 +0800458 unsigned int opf, bio_end_io_t endio_func,
459 u64 *next_stripe_start)
Qu Wenruo22c306f2021-09-27 15:21:53 +0800460{
Qu Wenruof472c28f2021-09-27 15:21:54 +0800461 struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb);
462 struct btrfs_io_geometry geom;
463 struct extent_map *em;
Qu Wenruo22c306f2021-09-27 15:21:53 +0800464 struct bio *bio;
Qu Wenruof472c28f2021-09-27 15:21:54 +0800465 int ret;
Qu Wenruo22c306f2021-09-27 15:21:53 +0800466
467 bio = btrfs_bio_alloc(BIO_MAX_VECS);
468
469 bio->bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
470 bio->bi_opf = opf;
471 bio->bi_private = cb;
472 bio->bi_end_io = endio_func;
473
Qu Wenruof472c28f2021-09-27 15:21:54 +0800474 em = btrfs_get_chunk_map(fs_info, disk_bytenr, fs_info->sectorsize);
475 if (IS_ERR(em)) {
476 bio_put(bio);
477 return ERR_CAST(em);
Qu Wenruo22c306f2021-09-27 15:21:53 +0800478 }
Qu Wenruof472c28f2021-09-27 15:21:54 +0800479
480 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
481 bio_set_dev(bio, em->map_lookup->stripes[0].dev->bdev);
482
483 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), disk_bytenr, &geom);
484 free_extent_map(em);
485 if (ret < 0) {
486 bio_put(bio);
487 return ERR_PTR(ret);
488 }
489 *next_stripe_start = disk_bytenr + geom.len;
490
Qu Wenruo22c306f2021-09-27 15:21:53 +0800491 return bio;
492}
493
Chris Masonc8b97812008-10-29 14:49:59 -0400494/*
495 * worker function to build and submit bios for previously compressed pages.
496 * The corresponding pages in the inode should be marked for writeback
497 * and the compressed pages should have a reference on them for dropping
498 * when the IO is complete.
499 *
500 * This also checksums the file bytes and gets things ready for
501 * the end io hooks.
502 */
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300503blk_status_t btrfs_submit_compressed_write(struct btrfs_inode *inode, u64 start,
Anand Jain65b53552021-05-29 17:48:35 +0800504 unsigned int len, u64 disk_start,
505 unsigned int compressed_len,
Chris Masonc8b97812008-10-29 14:49:59 -0400506 struct page **compressed_pages,
Anand Jain65b53552021-05-29 17:48:35 +0800507 unsigned int nr_pages,
Chris Masonec39f762019-07-10 12:28:17 -0700508 unsigned int write_flags,
509 struct cgroup_subsys_state *blkcg_css)
Chris Masonc8b97812008-10-29 14:49:59 -0400510{
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300511 struct btrfs_fs_info *fs_info = inode->root->fs_info;
Chris Masonc8b97812008-10-29 14:49:59 -0400512 struct bio *bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400513 struct compressed_bio *cb;
Qu Wenruo91507242021-09-27 15:21:55 +0800514 u64 cur_disk_bytenr = disk_start;
Qu Wenruof472c28f2021-09-27 15:21:54 +0800515 u64 next_stripe_start;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200516 blk_status_t ret;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300517 int skip_sum = inode->flags & BTRFS_INODE_NODATASUM;
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900518 const bool use_append = btrfs_use_zone_append(inode, disk_start);
519 const unsigned int bio_op = use_append ? REQ_OP_ZONE_APPEND : REQ_OP_WRITE;
Chris Masonc8b97812008-10-29 14:49:59 -0400520
Qu Wenruobbbff012021-09-27 15:22:00 +0800521 ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
522 IS_ALIGNED(len, fs_info->sectorsize));
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400523 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
Yoshinori Sanodac97e52011-02-15 12:01:42 +0000524 if (!cb)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200525 return BLK_STS_RESOURCE;
Qu Wenruo6ec97652021-09-27 15:21:48 +0800526 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
Chris Masonc8b97812008-10-29 14:49:59 -0400527 cb->errors = 0;
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300528 cb->inode = &inode->vfs_inode;
Chris Masonc8b97812008-10-29 14:49:59 -0400529 cb->start = start;
530 cb->len = len;
Chris Masond20f7042008-12-08 16:58:54 -0500531 cb->mirror_num = 0;
Chris Masonc8b97812008-10-29 14:49:59 -0400532 cb->compressed_pages = compressed_pages;
533 cb->compressed_len = compressed_len;
534 cb->orig_bio = NULL;
535 cb->nr_pages = nr_pages;
536
Qu Wenruo91507242021-09-27 15:21:55 +0800537 while (cur_disk_bytenr < disk_start + compressed_len) {
538 u64 offset = cur_disk_bytenr - disk_start;
539 unsigned int index = offset >> PAGE_SHIFT;
540 unsigned int real_size;
541 unsigned int added;
542 struct page *page = compressed_pages[index];
543 bool submit = false;
Chris Masonec39f762019-07-10 12:28:17 -0700544
Qu Wenruo91507242021-09-27 15:21:55 +0800545 /* Allocate new bio if submitted or not yet allocated */
546 if (!bio) {
547 bio = alloc_compressed_bio(cb, cur_disk_bytenr,
548 bio_op | write_flags, end_compressed_bio_write,
549 &next_stripe_start);
550 if (IS_ERR(bio)) {
551 ret = errno_to_blk_status(PTR_ERR(bio));
552 bio = NULL;
553 goto finish_cb;
554 }
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900555 }
Qu Wenruo91507242021-09-27 15:21:55 +0800556 /*
557 * We should never reach next_stripe_start start as we will
558 * submit comp_bio when reach the boundary immediately.
559 */
560 ASSERT(cur_disk_bytenr != next_stripe_start);
Chris Masonc8b97812008-10-29 14:49:59 -0400561
Qu Wenruo4c80a972021-05-25 13:52:43 +0800562 /*
Qu Wenruo91507242021-09-27 15:21:55 +0800563 * We have various limits on the real read size:
564 * - stripe boundary
565 * - page boundary
566 * - compressed length boundary
Qu Wenruo4c80a972021-05-25 13:52:43 +0800567 */
Qu Wenruo91507242021-09-27 15:21:55 +0800568 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_bytenr);
569 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
570 real_size = min_t(u64, real_size, compressed_len - offset);
571 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
Johannes Thumshirn764c7c92021-05-19 00:40:28 +0900572
Qu Wenruo91507242021-09-27 15:21:55 +0800573 if (use_append)
574 added = bio_add_zone_append_page(bio, page, real_size,
575 offset_in_page(offset));
576 else
577 added = bio_add_page(bio, page, real_size,
578 offset_in_page(offset));
579 /* Reached zoned boundary */
580 if (added == 0)
581 submit = true;
Chris Masonc8b97812008-10-29 14:49:59 -0400582
Qu Wenruo91507242021-09-27 15:21:55 +0800583 cur_disk_bytenr += added;
584 /* Reached stripe boundary */
585 if (cur_disk_bytenr == next_stripe_start)
586 submit = true;
587
588 /* Finished the range */
589 if (cur_disk_bytenr == disk_start + compressed_len)
590 submit = true;
591
592 if (submit) {
Li Zefane55179b2011-07-14 03:16:47 +0000593 if (!skip_sum) {
Nikolay Borisovc7ee1812020-06-03 08:55:16 +0300594 ret = btrfs_csum_one_bio(inode, bio, start, 1);
Qu Wenruo6853c642021-09-27 15:21:51 +0800595 if (ret)
596 goto finish_cb;
Li Zefane55179b2011-07-14 03:16:47 +0000597 }
Chris Masond20f7042008-12-08 16:58:54 -0500598
Qu Wenruo2d4e0b82021-09-27 15:21:52 +0800599 ret = submit_compressed_bio(fs_info, cb, bio, 0);
Qu Wenruo6853c642021-09-27 15:21:51 +0800600 if (ret)
601 goto finish_cb;
Qu Wenruo91507242021-09-27 15:21:55 +0800602 bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400603 }
Chris Mason771ed682008-11-06 22:02:51 -0500604 cond_resched();
Chris Masonc8b97812008-10-29 14:49:59 -0400605 }
Dennis Zhou46bcff2b2019-12-11 15:20:15 -0800606 if (blkcg_css)
607 kthread_associate_blkcg(NULL);
608
Chris Masonc8b97812008-10-29 14:49:59 -0400609 return 0;
Qu Wenruo6853c642021-09-27 15:21:51 +0800610
611finish_cb:
612 if (bio) {
613 bio->bi_status = ret;
614 bio_endio(bio);
615 }
Qu Wenruo91507242021-09-27 15:21:55 +0800616 /* Last byte of @cb is submitted, endio will free @cb */
617 if (cur_disk_bytenr == disk_start + compressed_len)
618 return ret;
Qu Wenruo6853c642021-09-27 15:21:51 +0800619
Qu Wenruo91507242021-09-27 15:21:55 +0800620 wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
621 (disk_start + compressed_len - cur_disk_bytenr) >>
622 fs_info->sectorsize_bits);
Qu Wenruo6853c642021-09-27 15:21:51 +0800623 /*
624 * Even with previous bio ended, we should still have io not yet
625 * submitted, thus need to finish manually.
626 */
627 ASSERT(refcount_read(&cb->pending_sectors));
628 /* Now we are the only one referring @cb, can finish it safely. */
629 finish_compressed_bio_write(cb);
630 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400631}
632
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100633static u64 bio_end_offset(struct bio *bio)
634{
Ming Leic45a8f22017-12-18 20:22:05 +0800635 struct bio_vec *last = bio_last_bvec_all(bio);
Christoph Hellwig2a4d0c92016-11-25 09:07:51 +0100636
637 return page_offset(last->bv_page) + last->bv_len + last->bv_offset;
638}
639
Qu Wenruo6a404912021-09-27 15:21:47 +0800640/*
641 * Add extra pages in the same compressed file extent so that we don't need to
642 * re-read the same extent again and again.
643 *
644 * NOTE: this won't work well for subpage, as for subpage read, we lock the
645 * full page then submit bio for each compressed/regular extents.
646 *
647 * This means, if we have several sectors in the same page points to the same
648 * on-disk compressed data, we will re-read the same extent many times and
649 * this function can only help for the next page.
650 */
Chris Mason771ed682008-11-06 22:02:51 -0500651static noinline int add_ra_bio_pages(struct inode *inode,
652 u64 compressed_end,
653 struct compressed_bio *cb)
654{
Qu Wenruo6a404912021-09-27 15:21:47 +0800655 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Mason771ed682008-11-06 22:02:51 -0500656 unsigned long end_index;
Qu Wenruo6a404912021-09-27 15:21:47 +0800657 u64 cur = bio_end_offset(cb->orig_bio);
Chris Mason771ed682008-11-06 22:02:51 -0500658 u64 isize = i_size_read(inode);
659 int ret;
660 struct page *page;
Chris Mason771ed682008-11-06 22:02:51 -0500661 struct extent_map *em;
662 struct address_space *mapping = inode->i_mapping;
Chris Mason771ed682008-11-06 22:02:51 -0500663 struct extent_map_tree *em_tree;
664 struct extent_io_tree *tree;
Qu Wenruo6a404912021-09-27 15:21:47 +0800665 int sectors_missed = 0;
Chris Mason771ed682008-11-06 22:02:51 -0500666
Chris Mason771ed682008-11-06 22:02:51 -0500667 em_tree = &BTRFS_I(inode)->extent_tree;
668 tree = &BTRFS_I(inode)->io_tree;
669
670 if (isize == 0)
671 return 0;
672
Qu Wenruoca62e852021-07-26 14:34:52 +0800673 /*
674 * For current subpage support, we only support 64K page size,
675 * which means maximum compressed extent size (128K) is just 2x page
676 * size.
677 * This makes readahead less effective, so here disable readahead for
678 * subpage for now, until full compressed write is supported.
679 */
680 if (btrfs_sb(inode->i_sb)->sectorsize < PAGE_SIZE)
681 return 0;
682
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300683 end_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
Chris Mason771ed682008-11-06 22:02:51 -0500684
Qu Wenruo6a404912021-09-27 15:21:47 +0800685 while (cur < compressed_end) {
686 u64 page_end;
687 u64 pg_index = cur >> PAGE_SHIFT;
688 u32 add_size;
Chris Mason771ed682008-11-06 22:02:51 -0500689
David Sterba306e16c2011-04-19 14:29:38 +0200690 if (pg_index > end_index)
Chris Mason771ed682008-11-06 22:02:51 -0500691 break;
692
Matthew Wilcox0a943c62017-12-04 10:37:22 -0500693 page = xa_load(&mapping->i_pages, pg_index);
Matthew Wilcox3159f942017-11-03 13:30:42 -0400694 if (page && !xa_is_value(page)) {
Qu Wenruo6a404912021-09-27 15:21:47 +0800695 sectors_missed += (PAGE_SIZE - offset_in_page(cur)) >>
696 fs_info->sectorsize_bits;
697
698 /* Beyond threshold, no need to continue */
699 if (sectors_missed > 4)
Chris Mason771ed682008-11-06 22:02:51 -0500700 break;
Qu Wenruo6a404912021-09-27 15:21:47 +0800701
702 /*
703 * Jump to next page start as we already have page for
704 * current offset.
705 */
706 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
707 continue;
Chris Mason771ed682008-11-06 22:02:51 -0500708 }
709
Michal Hockoc62d2552015-11-06 16:28:49 -0800710 page = __page_cache_alloc(mapping_gfp_constraint(mapping,
711 ~__GFP_FS));
Chris Mason771ed682008-11-06 22:02:51 -0500712 if (!page)
713 break;
714
Michal Hockoc62d2552015-11-06 16:28:49 -0800715 if (add_to_page_cache_lru(page, mapping, pg_index, GFP_NOFS)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300716 put_page(page);
Qu Wenruo6a404912021-09-27 15:21:47 +0800717 /* There is already a page, skip to page end */
718 cur = (pg_index << PAGE_SHIFT) + PAGE_SIZE;
719 continue;
Chris Mason771ed682008-11-06 22:02:51 -0500720 }
721
Qu Wenruo32443de2021-01-26 16:34:00 +0800722 ret = set_page_extent_mapped(page);
723 if (ret < 0) {
724 unlock_page(page);
725 put_page(page);
726 break;
727 }
728
Qu Wenruo6a404912021-09-27 15:21:47 +0800729 page_end = (pg_index << PAGE_SHIFT) + PAGE_SIZE - 1;
730 lock_extent(tree, cur, page_end);
Chris Mason890871b2009-09-02 16:24:52 -0400731 read_lock(&em_tree->lock);
Qu Wenruo6a404912021-09-27 15:21:47 +0800732 em = lookup_extent_mapping(em_tree, cur, page_end + 1 - cur);
Chris Mason890871b2009-09-02 16:24:52 -0400733 read_unlock(&em_tree->lock);
Chris Mason771ed682008-11-06 22:02:51 -0500734
Qu Wenruo6a404912021-09-27 15:21:47 +0800735 /*
736 * At this point, we have a locked page in the page cache for
737 * these bytes in the file. But, we have to make sure they map
738 * to this compressed extent on disk.
739 */
740 if (!em || cur < em->start ||
741 (cur + fs_info->sectorsize > extent_map_end(em)) ||
Kent Overstreet4f024f32013-10-11 15:44:27 -0700742 (em->block_start >> 9) != cb->orig_bio->bi_iter.bi_sector) {
Chris Mason771ed682008-11-06 22:02:51 -0500743 free_extent_map(em);
Qu Wenruo6a404912021-09-27 15:21:47 +0800744 unlock_extent(tree, cur, page_end);
Chris Mason771ed682008-11-06 22:02:51 -0500745 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300746 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500747 break;
748 }
749 free_extent_map(em);
750
751 if (page->index == end_index) {
Johannes Thumshirn70730172018-12-05 15:23:03 +0100752 size_t zero_offset = offset_in_page(isize);
Chris Mason771ed682008-11-06 22:02:51 -0500753
754 if (zero_offset) {
755 int zeros;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300756 zeros = PAGE_SIZE - zero_offset;
Ira Weinyd048b9c2021-05-04 18:40:07 -0700757 memzero_page(page, zero_offset, zeros);
Chris Mason771ed682008-11-06 22:02:51 -0500758 flush_dcache_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500759 }
760 }
761
Qu Wenruo6a404912021-09-27 15:21:47 +0800762 add_size = min(em->start + em->len, page_end + 1) - cur;
763 ret = bio_add_page(cb->orig_bio, page, add_size, offset_in_page(cur));
764 if (ret != add_size) {
765 unlock_extent(tree, cur, page_end);
Chris Mason771ed682008-11-06 22:02:51 -0500766 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300767 put_page(page);
Chris Mason771ed682008-11-06 22:02:51 -0500768 break;
769 }
Qu Wenruo6a404912021-09-27 15:21:47 +0800770 /*
771 * If it's subpage, we also need to increase its
772 * subpage::readers number, as at endio we will decrease
773 * subpage::readers and to unlock the page.
774 */
775 if (fs_info->sectorsize < PAGE_SIZE)
776 btrfs_subpage_start_reader(fs_info, page, cur, add_size);
777 put_page(page);
778 cur += add_size;
Chris Mason771ed682008-11-06 22:02:51 -0500779 }
Chris Mason771ed682008-11-06 22:02:51 -0500780 return 0;
781}
782
Chris Masonc8b97812008-10-29 14:49:59 -0400783/*
784 * for a compressed read, the bio we get passed has all the inode pages
785 * in it. We don't actually do IO on those pages but allocate new ones
786 * to hold the compressed pages on disk.
787 *
Kent Overstreet4f024f32013-10-11 15:44:27 -0700788 * bio->bi_iter.bi_sector points to the compressed extent on disk
Chris Masonc8b97812008-10-29 14:49:59 -0400789 * bio->bi_io_vec points to all of the inode pages
Chris Masonc8b97812008-10-29 14:49:59 -0400790 *
791 * After the compressed pages are read, we copy the bytes into the
792 * bio we were passed and then call the bio end_io calls
793 */
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200794blk_status_t btrfs_submit_compressed_read(struct inode *inode, struct bio *bio,
Chris Masonc8b97812008-10-29 14:49:59 -0400795 int mirror_num, unsigned long bio_flags)
796{
Jeff Mahoney0b246af2016-06-22 18:54:23 -0400797 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
Chris Masonc8b97812008-10-29 14:49:59 -0400798 struct extent_map_tree *em_tree;
799 struct compressed_bio *cb;
Anand Jain356b4a22021-05-29 17:48:34 +0800800 unsigned int compressed_len;
801 unsigned int nr_pages;
802 unsigned int pg_index;
Qu Wenruof472c28f2021-09-27 15:21:54 +0800803 struct bio *comp_bio = NULL;
804 const u64 disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
805 u64 cur_disk_byte = disk_bytenr;
806 u64 next_stripe_start;
Qu Wenruo557023e2021-07-05 10:00:56 +0800807 u64 file_offset;
Chris Masone04ca622008-11-10 11:44:58 -0500808 u64 em_len;
809 u64 em_start;
Chris Masonc8b97812008-10-29 14:49:59 -0400810 struct extent_map *em;
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200811 blk_status_t ret = BLK_STS_RESOURCE;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400812 int faili = 0;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200813 u8 *sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400814
Chris Masonc8b97812008-10-29 14:49:59 -0400815 em_tree = &BTRFS_I(inode)->extent_tree;
816
Qu Wenruo557023e2021-07-05 10:00:56 +0800817 file_offset = bio_first_bvec_all(bio)->bv_offset +
818 page_offset(bio_first_page_all(bio));
819
Chris Masonc8b97812008-10-29 14:49:59 -0400820 /* we need the actual starting offset of this extent in the file */
Chris Mason890871b2009-09-02 16:24:52 -0400821 read_lock(&em_tree->lock);
Qu Wenruo557023e2021-07-05 10:00:56 +0800822 em = lookup_extent_mapping(em_tree, file_offset, fs_info->sectorsize);
Chris Mason890871b2009-09-02 16:24:52 -0400823 read_unlock(&em_tree->lock);
Tsutomu Itoh285190d2012-02-16 16:23:58 +0900824 if (!em)
Christoph Hellwig4e4cbee2017-06-03 09:38:06 +0200825 return BLK_STS_IOERR;
Chris Masonc8b97812008-10-29 14:49:59 -0400826
Qu Wenruo557023e2021-07-05 10:00:56 +0800827 ASSERT(em->compress_type != BTRFS_COMPRESS_NONE);
Chris Masond20f7042008-12-08 16:58:54 -0500828 compressed_len = em->block_len;
Jeff Mahoney2ff7e612016-06-22 18:54:24 -0400829 cb = kmalloc(compressed_bio_size(fs_info, compressed_len), GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000830 if (!cb)
831 goto out;
832
Qu Wenruo6ec97652021-09-27 15:21:48 +0800833 refcount_set(&cb->pending_sectors, compressed_len >> fs_info->sectorsize_bits);
Chris Masonc8b97812008-10-29 14:49:59 -0400834 cb->errors = 0;
835 cb->inode = inode;
Chris Masond20f7042008-12-08 16:58:54 -0500836 cb->mirror_num = mirror_num;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200837 sums = cb->sums;
Chris Masonc8b97812008-10-29 14:49:59 -0400838
Yan Zhengff5b7ee2008-11-10 07:34:43 -0500839 cb->start = em->orig_start;
Chris Masone04ca622008-11-10 11:44:58 -0500840 em_len = em->len;
841 em_start = em->start;
Chris Masond20f7042008-12-08 16:58:54 -0500842
Chris Masonc8b97812008-10-29 14:49:59 -0400843 free_extent_map(em);
Chris Masone04ca622008-11-10 11:44:58 -0500844 em = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400845
Christoph Hellwig81381052016-11-25 09:07:50 +0100846 cb->len = bio->bi_iter.bi_size;
Chris Masonc8b97812008-10-29 14:49:59 -0400847 cb->compressed_len = compressed_len;
Li Zefan261507a02010-12-17 14:21:50 +0800848 cb->compress_type = extent_compress_type(bio_flags);
Chris Masonc8b97812008-10-29 14:49:59 -0400849 cb->orig_bio = bio;
850
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300851 nr_pages = DIV_ROUND_UP(compressed_len, PAGE_SIZE);
David Sterba31e818f2015-02-20 18:00:26 +0100852 cb->compressed_pages = kcalloc(nr_pages, sizeof(struct page *),
Chris Masonc8b97812008-10-29 14:49:59 -0400853 GFP_NOFS);
liubo6b82ce82011-01-26 06:21:39 +0000854 if (!cb->compressed_pages)
855 goto fail1;
856
David Sterba306e16c2011-04-19 14:29:38 +0200857 for (pg_index = 0; pg_index < nr_pages; pg_index++) {
David Sterbab0ee5e12021-06-14 22:22:22 +0200858 cb->compressed_pages[pg_index] = alloc_page(GFP_NOFS);
Josef Bacik15e3004a2012-10-05 13:39:50 -0400859 if (!cb->compressed_pages[pg_index]) {
860 faili = pg_index - 1;
Dan Carpenter0e9350d2017-06-19 13:55:37 +0300861 ret = BLK_STS_RESOURCE;
liubo6b82ce82011-01-26 06:21:39 +0000862 goto fail2;
Josef Bacik15e3004a2012-10-05 13:39:50 -0400863 }
Chris Masonc8b97812008-10-29 14:49:59 -0400864 }
Josef Bacik15e3004a2012-10-05 13:39:50 -0400865 faili = nr_pages - 1;
Chris Masonc8b97812008-10-29 14:49:59 -0400866 cb->nr_pages = nr_pages;
867
Filipe Manana7f042a82016-01-27 19:17:20 +0000868 add_ra_bio_pages(inode, em_start + em_len, cb);
Chris Mason771ed682008-11-06 22:02:51 -0500869
Chris Mason771ed682008-11-06 22:02:51 -0500870 /* include any pages we added in add_ra-bio_pages */
Christoph Hellwig81381052016-11-25 09:07:50 +0100871 cb->len = bio->bi_iter.bi_size;
Chris Mason771ed682008-11-06 22:02:51 -0500872
Qu Wenruof472c28f2021-09-27 15:21:54 +0800873 while (cur_disk_byte < disk_bytenr + compressed_len) {
874 u64 offset = cur_disk_byte - disk_bytenr;
875 unsigned int index = offset >> PAGE_SHIFT;
876 unsigned int real_size;
877 unsigned int added;
878 struct page *page = cb->compressed_pages[index];
879 bool submit = false;
Chris Masonc8b97812008-10-29 14:49:59 -0400880
Qu Wenruof472c28f2021-09-27 15:21:54 +0800881 /* Allocate new bio if submitted or not yet allocated */
882 if (!comp_bio) {
883 comp_bio = alloc_compressed_bio(cb, cur_disk_byte,
884 REQ_OP_READ, end_compressed_bio_read,
885 &next_stripe_start);
886 if (IS_ERR(comp_bio)) {
887 ret = errno_to_blk_status(PTR_ERR(comp_bio));
888 comp_bio = NULL;
889 goto finish_cb;
890 }
891 }
Qu Wenruobe6a1362021-02-04 15:03:23 +0800892 /*
Qu Wenruof472c28f2021-09-27 15:21:54 +0800893 * We should never reach next_stripe_start start as we will
894 * submit comp_bio when reach the boundary immediately.
Qu Wenruobe6a1362021-02-04 15:03:23 +0800895 */
Qu Wenruof472c28f2021-09-27 15:21:54 +0800896 ASSERT(cur_disk_byte != next_stripe_start);
897 /*
898 * We have various limit on the real read size:
899 * - stripe boundary
900 * - page boundary
901 * - compressed length boundary
902 */
903 real_size = min_t(u64, U32_MAX, next_stripe_start - cur_disk_byte);
904 real_size = min_t(u64, real_size, PAGE_SIZE - offset_in_page(offset));
905 real_size = min_t(u64, real_size, compressed_len - offset);
906 ASSERT(IS_ALIGNED(real_size, fs_info->sectorsize));
Qu Wenruobe6a1362021-02-04 15:03:23 +0800907
Qu Wenruof472c28f2021-09-27 15:21:54 +0800908 added = bio_add_page(comp_bio, page, real_size, offset_in_page(offset));
909 /*
910 * Maximum compressed extent is smaller than bio size limit,
911 * thus bio_add_page() should always success.
912 */
913 ASSERT(added == real_size);
914 cur_disk_byte += added;
Chris Masond20f7042008-12-08 16:58:54 -0500915
Qu Wenruof472c28f2021-09-27 15:21:54 +0800916 /* Reached stripe boundary, need to submit */
917 if (cur_disk_byte == next_stripe_start)
918 submit = true;
Chris Masonc8b97812008-10-29 14:49:59 -0400919
Qu Wenruof472c28f2021-09-27 15:21:54 +0800920 /* Has finished the range, need to submit */
921 if (cur_disk_byte == disk_bytenr + compressed_len)
922 submit = true;
923
924 if (submit) {
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200925 unsigned int nr_sectors;
926
Qu Wenruo62751932020-12-02 14:48:06 +0800927 ret = btrfs_lookup_bio_sums(inode, comp_bio, sums);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800928 if (ret)
929 goto finish_cb;
Johannes Thumshirn10fe6ca2019-05-22 10:19:02 +0200930
931 nr_sectors = DIV_ROUND_UP(comp_bio->bi_iter.bi_size,
932 fs_info->sectorsize);
David Sterba713cebf2020-06-30 18:04:02 +0200933 sums += fs_info->csum_size * nr_sectors;
Chris Masond20f7042008-12-08 16:58:54 -0500934
Qu Wenruo2d4e0b82021-09-27 15:21:52 +0800935 ret = submit_compressed_bio(fs_info, cb, comp_bio, mirror_num);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800936 if (ret)
937 goto finish_cb;
Qu Wenruof472c28f2021-09-27 15:21:54 +0800938 comp_bio = NULL;
Chris Masonc8b97812008-10-29 14:49:59 -0400939 }
Chris Masonc8b97812008-10-29 14:49:59 -0400940 }
Chris Masonc8b97812008-10-29 14:49:59 -0400941 return 0;
liubo6b82ce82011-01-26 06:21:39 +0000942
943fail2:
Josef Bacik15e3004a2012-10-05 13:39:50 -0400944 while (faili >= 0) {
945 __free_page(cb->compressed_pages[faili]);
946 faili--;
947 }
liubo6b82ce82011-01-26 06:21:39 +0000948
949 kfree(cb->compressed_pages);
950fail1:
951 kfree(cb);
952out:
953 free_extent_map(em);
954 return ret;
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800955finish_cb:
956 if (comp_bio) {
957 comp_bio->bi_status = ret;
958 bio_endio(comp_bio);
959 }
Qu Wenruof472c28f2021-09-27 15:21:54 +0800960 /* All bytes of @cb is submitted, endio will free @cb */
961 if (cur_disk_byte == disk_bytenr + compressed_len)
962 return ret;
963
964 wait_var_event(cb, refcount_read(&cb->pending_sectors) ==
965 (disk_bytenr + compressed_len - cur_disk_byte) >>
966 fs_info->sectorsize_bits);
Qu Wenruo86ccbb42021-09-27 15:21:50 +0800967 /*
968 * Even with previous bio ended, we should still have io not yet
969 * submitted, thus need to finish @cb manually.
970 */
971 ASSERT(refcount_read(&cb->pending_sectors));
972 /* Now we are the only one referring @cb, can finish it safely. */
973 finish_compressed_bio_read(cb, NULL);
974 return ret;
Chris Masonc8b97812008-10-29 14:49:59 -0400975}
Li Zefan261507a02010-12-17 14:21:50 +0800976
Timofey Titovets17b5a6c2017-09-28 17:33:37 +0300977/*
978 * Heuristic uses systematic sampling to collect data from the input data
979 * range, the logic can be tuned by the following constants:
980 *
981 * @SAMPLING_READ_SIZE - how many bytes will be copied from for each sample
982 * @SAMPLING_INTERVAL - range from which the sampled data can be collected
983 */
984#define SAMPLING_READ_SIZE (16)
985#define SAMPLING_INTERVAL (256)
986
987/*
988 * For statistical analysis of the input data we consider bytes that form a
989 * Galois Field of 256 objects. Each object has an attribute count, ie. how
990 * many times the object appeared in the sample.
991 */
992#define BUCKET_SIZE (256)
993
994/*
995 * The size of the sample is based on a statistical sampling rule of thumb.
996 * The common way is to perform sampling tests as long as the number of
997 * elements in each cell is at least 5.
998 *
999 * Instead of 5, we choose 32 to obtain more accurate results.
1000 * If the data contain the maximum number of symbols, which is 256, we obtain a
1001 * sample size bound by 8192.
1002 *
1003 * For a sample of at most 8KB of data per data range: 16 consecutive bytes
1004 * from up to 512 locations.
1005 */
1006#define MAX_SAMPLE_SIZE (BTRFS_MAX_UNCOMPRESSED * \
1007 SAMPLING_READ_SIZE / SAMPLING_INTERVAL)
1008
1009struct bucket_item {
1010 u32 count;
1011};
Timofey Titovets4e439a02017-09-28 17:33:36 +03001012
1013struct heuristic_ws {
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001014 /* Partial copy of input data */
1015 u8 *sample;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001016 u32 sample_size;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001017 /* Buckets store counters for each byte value */
1018 struct bucket_item *bucket;
Timofey Titovets440c8402017-12-04 00:30:33 +03001019 /* Sorting buffer */
1020 struct bucket_item *bucket_b;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001021 struct list_head list;
1022};
1023
Dennis Zhou92ee55302019-02-04 15:20:03 -05001024static struct workspace_manager heuristic_wsm;
1025
Timofey Titovets4e439a02017-09-28 17:33:36 +03001026static void free_heuristic_ws(struct list_head *ws)
1027{
1028 struct heuristic_ws *workspace;
1029
1030 workspace = list_entry(ws, struct heuristic_ws, list);
1031
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001032 kvfree(workspace->sample);
1033 kfree(workspace->bucket);
Timofey Titovets440c8402017-12-04 00:30:33 +03001034 kfree(workspace->bucket_b);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001035 kfree(workspace);
1036}
1037
Dennis Zhou7bf49942019-02-04 15:20:04 -05001038static struct list_head *alloc_heuristic_ws(unsigned int level)
Timofey Titovets4e439a02017-09-28 17:33:36 +03001039{
1040 struct heuristic_ws *ws;
1041
1042 ws = kzalloc(sizeof(*ws), GFP_KERNEL);
1043 if (!ws)
1044 return ERR_PTR(-ENOMEM);
1045
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001046 ws->sample = kvmalloc(MAX_SAMPLE_SIZE, GFP_KERNEL);
1047 if (!ws->sample)
1048 goto fail;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001049
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001050 ws->bucket = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket), GFP_KERNEL);
1051 if (!ws->bucket)
1052 goto fail;
1053
Timofey Titovets440c8402017-12-04 00:30:33 +03001054 ws->bucket_b = kcalloc(BUCKET_SIZE, sizeof(*ws->bucket_b), GFP_KERNEL);
1055 if (!ws->bucket_b)
1056 goto fail;
1057
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001058 INIT_LIST_HEAD(&ws->list);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001059 return &ws->list;
Timofey Titovets17b5a6c2017-09-28 17:33:37 +03001060fail:
1061 free_heuristic_ws(&ws->list);
1062 return ERR_PTR(-ENOMEM);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001063}
1064
Dennis Zhouca4ac362019-02-04 15:19:59 -05001065const struct btrfs_compress_op btrfs_heuristic_compress = {
David Sterbabe9510452019-10-02 00:53:31 +02001066 .workspace_manager = &heuristic_wsm,
Dennis Zhouca4ac362019-02-04 15:19:59 -05001067};
1068
David Sterbae8c9f182015-01-02 18:23:10 +01001069static const struct btrfs_compress_op * const btrfs_compress_op[] = {
Dennis Zhouca4ac362019-02-04 15:19:59 -05001070 /* The heuristic is represented as compression type 0 */
1071 &btrfs_heuristic_compress,
Li Zefan261507a02010-12-17 14:21:50 +08001072 &btrfs_zlib_compress,
Li Zefana6fa6fa2010-10-25 15:12:26 +08001073 &btrfs_lzo_compress,
Nick Terrell5c1aab12017-08-09 19:39:02 -07001074 &btrfs_zstd_compress,
Li Zefan261507a02010-12-17 14:21:50 +08001075};
1076
David Sterbac778df12019-10-04 02:47:39 +02001077static struct list_head *alloc_workspace(int type, unsigned int level)
1078{
1079 switch (type) {
1080 case BTRFS_COMPRESS_NONE: return alloc_heuristic_ws(level);
1081 case BTRFS_COMPRESS_ZLIB: return zlib_alloc_workspace(level);
1082 case BTRFS_COMPRESS_LZO: return lzo_alloc_workspace(level);
1083 case BTRFS_COMPRESS_ZSTD: return zstd_alloc_workspace(level);
1084 default:
1085 /*
1086 * This can't happen, the type is validated several times
1087 * before we get here.
1088 */
1089 BUG();
1090 }
1091}
1092
David Sterba1e002352019-10-04 02:57:22 +02001093static void free_workspace(int type, struct list_head *ws)
1094{
1095 switch (type) {
1096 case BTRFS_COMPRESS_NONE: return free_heuristic_ws(ws);
1097 case BTRFS_COMPRESS_ZLIB: return zlib_free_workspace(ws);
1098 case BTRFS_COMPRESS_LZO: return lzo_free_workspace(ws);
1099 case BTRFS_COMPRESS_ZSTD: return zstd_free_workspace(ws);
1100 default:
1101 /*
1102 * This can't happen, the type is validated several times
1103 * before we get here.
1104 */
1105 BUG();
1106 }
1107}
1108
David Sterbad5517032019-10-02 01:08:03 +02001109static void btrfs_init_workspace_manager(int type)
Li Zefan261507a02010-12-17 14:21:50 +08001110{
David Sterba0cf25212019-10-04 03:09:55 +02001111 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001112 struct list_head *workspace;
Li Zefan261507a02010-12-17 14:21:50 +08001113
David Sterba0cf25212019-10-04 03:09:55 +02001114 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001115 INIT_LIST_HEAD(&wsm->idle_ws);
1116 spin_lock_init(&wsm->ws_lock);
1117 atomic_set(&wsm->total_ws, 0);
1118 init_waitqueue_head(&wsm->ws_wait);
David Sterbaf77dd0d2016-04-27 02:55:15 +02001119
Dennis Zhou1666eda2019-02-04 15:20:01 -05001120 /*
1121 * Preallocate one workspace for each compression type so we can
1122 * guarantee forward progress in the worst case
1123 */
David Sterbac778df12019-10-04 02:47:39 +02001124 workspace = alloc_workspace(type, 0);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001125 if (IS_ERR(workspace)) {
1126 pr_warn(
1127 "BTRFS: cannot preallocate compression workspace, will try later\n");
1128 } else {
Dennis Zhou92ee55302019-02-04 15:20:03 -05001129 atomic_set(&wsm->total_ws, 1);
1130 wsm->free_ws = 1;
1131 list_add(workspace, &wsm->idle_ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001132 }
1133}
1134
David Sterba25103072019-10-02 01:08:03 +02001135static void btrfs_cleanup_workspace_manager(int type)
Dennis Zhou1666eda2019-02-04 15:20:01 -05001136{
David Sterba2dba7142019-10-04 01:40:58 +02001137 struct workspace_manager *wsman;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001138 struct list_head *ws;
1139
David Sterba2dba7142019-10-04 01:40:58 +02001140 wsman = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou1666eda2019-02-04 15:20:01 -05001141 while (!list_empty(&wsman->idle_ws)) {
1142 ws = wsman->idle_ws.next;
1143 list_del(ws);
David Sterba1e002352019-10-04 02:57:22 +02001144 free_workspace(type, ws);
Dennis Zhou1666eda2019-02-04 15:20:01 -05001145 atomic_dec(&wsman->total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001146 }
Li Zefan261507a02010-12-17 14:21:50 +08001147}
1148
1149/*
David Sterbae721e492016-04-27 02:41:17 +02001150 * This finds an available workspace or allocates a new one.
1151 * If it's not possible to allocate a new one, waits until there's one.
1152 * Preallocation makes a forward progress guarantees and we do not return
1153 * errors.
Li Zefan261507a02010-12-17 14:21:50 +08001154 */
David Sterba5907a9b2019-10-04 02:50:28 +02001155struct list_head *btrfs_get_workspace(int type, unsigned int level)
Li Zefan261507a02010-12-17 14:21:50 +08001156{
David Sterba5907a9b2019-10-04 02:50:28 +02001157 struct workspace_manager *wsm;
Li Zefan261507a02010-12-17 14:21:50 +08001158 struct list_head *workspace;
1159 int cpus = num_online_cpus();
David Sterbafe308532017-05-31 17:14:56 +02001160 unsigned nofs_flag;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001161 struct list_head *idle_ws;
1162 spinlock_t *ws_lock;
1163 atomic_t *total_ws;
1164 wait_queue_head_t *ws_wait;
1165 int *free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001166
David Sterba5907a9b2019-10-04 02:50:28 +02001167 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001168 idle_ws = &wsm->idle_ws;
1169 ws_lock = &wsm->ws_lock;
1170 total_ws = &wsm->total_ws;
1171 ws_wait = &wsm->ws_wait;
1172 free_ws = &wsm->free_ws;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001173
Li Zefan261507a02010-12-17 14:21:50 +08001174again:
Byongho Leed9187642015-10-14 14:05:24 +09001175 spin_lock(ws_lock);
1176 if (!list_empty(idle_ws)) {
1177 workspace = idle_ws->next;
Li Zefan261507a02010-12-17 14:21:50 +08001178 list_del(workspace);
David Sterba6ac10a62016-04-27 02:15:15 +02001179 (*free_ws)--;
Byongho Leed9187642015-10-14 14:05:24 +09001180 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001181 return workspace;
1182
1183 }
David Sterba6ac10a62016-04-27 02:15:15 +02001184 if (atomic_read(total_ws) > cpus) {
Li Zefan261507a02010-12-17 14:21:50 +08001185 DEFINE_WAIT(wait);
1186
Byongho Leed9187642015-10-14 14:05:24 +09001187 spin_unlock(ws_lock);
1188 prepare_to_wait(ws_wait, &wait, TASK_UNINTERRUPTIBLE);
David Sterba6ac10a62016-04-27 02:15:15 +02001189 if (atomic_read(total_ws) > cpus && !*free_ws)
Li Zefan261507a02010-12-17 14:21:50 +08001190 schedule();
Byongho Leed9187642015-10-14 14:05:24 +09001191 finish_wait(ws_wait, &wait);
Li Zefan261507a02010-12-17 14:21:50 +08001192 goto again;
1193 }
David Sterba6ac10a62016-04-27 02:15:15 +02001194 atomic_inc(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001195 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001196
David Sterbafe308532017-05-31 17:14:56 +02001197 /*
1198 * Allocation helpers call vmalloc that can't use GFP_NOFS, so we have
1199 * to turn it off here because we might get called from the restricted
1200 * context of btrfs_compress_bio/btrfs_compress_pages
1201 */
1202 nofs_flag = memalloc_nofs_save();
David Sterbac778df12019-10-04 02:47:39 +02001203 workspace = alloc_workspace(type, level);
David Sterbafe308532017-05-31 17:14:56 +02001204 memalloc_nofs_restore(nofs_flag);
1205
Li Zefan261507a02010-12-17 14:21:50 +08001206 if (IS_ERR(workspace)) {
David Sterba6ac10a62016-04-27 02:15:15 +02001207 atomic_dec(total_ws);
Byongho Leed9187642015-10-14 14:05:24 +09001208 wake_up(ws_wait);
David Sterbae721e492016-04-27 02:41:17 +02001209
1210 /*
1211 * Do not return the error but go back to waiting. There's a
1212 * workspace preallocated for each type and the compression
1213 * time is bounded so we get to a workspace eventually. This
1214 * makes our caller's life easier.
David Sterba523567162016-04-27 03:07:39 +02001215 *
1216 * To prevent silent and low-probability deadlocks (when the
1217 * initial preallocation fails), check if there are any
1218 * workspaces at all.
David Sterbae721e492016-04-27 02:41:17 +02001219 */
David Sterba523567162016-04-27 03:07:39 +02001220 if (atomic_read(total_ws) == 0) {
1221 static DEFINE_RATELIMIT_STATE(_rs,
1222 /* once per minute */ 60 * HZ,
1223 /* no burst */ 1);
1224
1225 if (__ratelimit(&_rs)) {
Jeff Mahoneyab8d0fc2016-09-20 10:05:02 -04001226 pr_warn("BTRFS: no compression workspaces, low memory, retrying\n");
David Sterba523567162016-04-27 03:07:39 +02001227 }
1228 }
David Sterbae721e492016-04-27 02:41:17 +02001229 goto again;
Li Zefan261507a02010-12-17 14:21:50 +08001230 }
1231 return workspace;
1232}
1233
Dennis Zhou7bf49942019-02-04 15:20:04 -05001234static struct list_head *get_workspace(int type, int level)
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001235{
David Sterba6a0d1272019-10-04 02:36:16 +02001236 switch (type) {
David Sterba5907a9b2019-10-04 02:50:28 +02001237 case BTRFS_COMPRESS_NONE: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001238 case BTRFS_COMPRESS_ZLIB: return zlib_get_workspace(level);
David Sterba5907a9b2019-10-04 02:50:28 +02001239 case BTRFS_COMPRESS_LZO: return btrfs_get_workspace(type, level);
David Sterba6a0d1272019-10-04 02:36:16 +02001240 case BTRFS_COMPRESS_ZSTD: return zstd_get_workspace(level);
1241 default:
1242 /*
1243 * This can't happen, the type is validated several times
1244 * before we get here.
1245 */
1246 BUG();
1247 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001248}
1249
Li Zefan261507a02010-12-17 14:21:50 +08001250/*
1251 * put a workspace struct back on the list or free it if we have enough
1252 * idle ones sitting around
1253 */
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001254void btrfs_put_workspace(int type, struct list_head *ws)
Li Zefan261507a02010-12-17 14:21:50 +08001255{
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001256 struct workspace_manager *wsm;
Timofey Titovets4e439a02017-09-28 17:33:36 +03001257 struct list_head *idle_ws;
1258 spinlock_t *ws_lock;
1259 atomic_t *total_ws;
1260 wait_queue_head_t *ws_wait;
1261 int *free_ws;
1262
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001263 wsm = btrfs_compress_op[type]->workspace_manager;
Dennis Zhou92ee55302019-02-04 15:20:03 -05001264 idle_ws = &wsm->idle_ws;
1265 ws_lock = &wsm->ws_lock;
1266 total_ws = &wsm->total_ws;
1267 ws_wait = &wsm->ws_wait;
1268 free_ws = &wsm->free_ws;
Li Zefan261507a02010-12-17 14:21:50 +08001269
Byongho Leed9187642015-10-14 14:05:24 +09001270 spin_lock(ws_lock);
Nick Terrell26b28dc2017-06-29 10:57:26 -07001271 if (*free_ws <= num_online_cpus()) {
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001272 list_add(ws, idle_ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001273 (*free_ws)++;
Byongho Leed9187642015-10-14 14:05:24 +09001274 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001275 goto wake;
1276 }
Byongho Leed9187642015-10-14 14:05:24 +09001277 spin_unlock(ws_lock);
Li Zefan261507a02010-12-17 14:21:50 +08001278
David Sterba1e002352019-10-04 02:57:22 +02001279 free_workspace(type, ws);
David Sterba6ac10a62016-04-27 02:15:15 +02001280 atomic_dec(total_ws);
Li Zefan261507a02010-12-17 14:21:50 +08001281wake:
David Sterba093258e2018-02-26 16:15:17 +01001282 cond_wake_up(ws_wait);
Li Zefan261507a02010-12-17 14:21:50 +08001283}
1284
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001285static void put_workspace(int type, struct list_head *ws)
1286{
David Sterbabd3a5282019-10-04 02:42:03 +02001287 switch (type) {
David Sterbaa3bbd2a2019-10-04 02:50:28 +02001288 case BTRFS_COMPRESS_NONE: return btrfs_put_workspace(type, ws);
1289 case BTRFS_COMPRESS_ZLIB: return btrfs_put_workspace(type, ws);
1290 case BTRFS_COMPRESS_LZO: return btrfs_put_workspace(type, ws);
David Sterbabd3a5282019-10-04 02:42:03 +02001291 case BTRFS_COMPRESS_ZSTD: return zstd_put_workspace(ws);
1292 default:
1293 /*
1294 * This can't happen, the type is validated several times
1295 * before we get here.
1296 */
1297 BUG();
1298 }
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001299}
1300
Li Zefan261507a02010-12-17 14:21:50 +08001301/*
Anand Jainadbab642020-05-11 22:37:51 -07001302 * Adjust @level according to the limits of the compression algorithm or
1303 * fallback to default
1304 */
1305static unsigned int btrfs_compress_set_level(int type, unsigned level)
1306{
1307 const struct btrfs_compress_op *ops = btrfs_compress_op[type];
1308
1309 if (level == 0)
1310 level = ops->default_level;
1311 else
1312 level = min(level, ops->max_level);
1313
1314 return level;
1315}
1316
1317/*
David Sterba38c31462017-02-14 19:04:07 +01001318 * Given an address space and start and length, compress the bytes into @pages
1319 * that are allocated on demand.
Li Zefan261507a02010-12-17 14:21:50 +08001320 *
David Sterbaf51d2b52017-09-15 17:36:57 +02001321 * @type_level is encoded algorithm and level, where level 0 means whatever
1322 * default the algorithm chooses and is opaque here;
1323 * - compression algo are 0-3
1324 * - the level are bits 4-7
1325 *
David Sterba4d3a8002017-02-14 19:04:07 +01001326 * @out_pages is an in/out parameter, holds maximum number of pages to allocate
1327 * and returns number of actually allocated pages
Li Zefan261507a02010-12-17 14:21:50 +08001328 *
David Sterba38c31462017-02-14 19:04:07 +01001329 * @total_in is used to return the number of bytes actually read. It
1330 * may be smaller than the input length if we had to exit early because we
Li Zefan261507a02010-12-17 14:21:50 +08001331 * ran out of room in the pages array or because we cross the
1332 * max_out threshold.
1333 *
David Sterba38c31462017-02-14 19:04:07 +01001334 * @total_out is an in/out parameter, must be set to the input length and will
1335 * be also used to return the total number of compressed bytes
Li Zefan261507a02010-12-17 14:21:50 +08001336 */
David Sterbaf51d2b52017-09-15 17:36:57 +02001337int btrfs_compress_pages(unsigned int type_level, struct address_space *mapping,
David Sterba38c31462017-02-14 19:04:07 +01001338 u64 start, struct page **pages,
Li Zefan261507a02010-12-17 14:21:50 +08001339 unsigned long *out_pages,
1340 unsigned long *total_in,
David Sterbae5d74902017-02-14 19:45:05 +01001341 unsigned long *total_out)
Li Zefan261507a02010-12-17 14:21:50 +08001342{
Dennis Zhou19727082019-02-04 15:19:57 -05001343 int type = btrfs_compress_type(type_level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001344 int level = btrfs_compress_level(type_level);
Li Zefan261507a02010-12-17 14:21:50 +08001345 struct list_head *workspace;
1346 int ret;
1347
David Sterbab0c1fe12019-08-09 16:49:06 +02001348 level = btrfs_compress_set_level(type, level);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001349 workspace = get_workspace(type, level);
David Sterba1e4eb742019-10-02 00:06:15 +02001350 ret = compression_compress_pages(type, workspace, mapping, start, pages,
1351 out_pages, total_in, total_out);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001352 put_workspace(type, workspace);
Li Zefan261507a02010-12-17 14:21:50 +08001353 return ret;
1354}
1355
Anand Jain8140dc32017-05-26 15:44:58 +08001356static int btrfs_decompress_bio(struct compressed_bio *cb)
Li Zefan261507a02010-12-17 14:21:50 +08001357{
1358 struct list_head *workspace;
1359 int ret;
Anand Jain8140dc32017-05-26 15:44:58 +08001360 int type = cb->compress_type;
Li Zefan261507a02010-12-17 14:21:50 +08001361
Dennis Zhou7bf49942019-02-04 15:20:04 -05001362 workspace = get_workspace(type, 0);
Su Yue4a9e8032021-12-27 18:18:39 +08001363 ret = compression_decompress_bio(workspace, cb);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001364 put_workspace(type, workspace);
Anand Jaine1ddce72017-05-26 15:44:59 +08001365
Li Zefan261507a02010-12-17 14:21:50 +08001366 return ret;
1367}
1368
1369/*
1370 * a less complex decompression routine. Our compressed data fits in a
1371 * single page, and we want to read a single page out of it.
1372 * start_byte tells us the offset into the compressed data we're interested in
1373 */
1374int btrfs_decompress(int type, unsigned char *data_in, struct page *dest_page,
1375 unsigned long start_byte, size_t srclen, size_t destlen)
1376{
1377 struct list_head *workspace;
1378 int ret;
1379
Dennis Zhou7bf49942019-02-04 15:20:04 -05001380 workspace = get_workspace(type, 0);
David Sterba1e4eb742019-10-02 00:06:15 +02001381 ret = compression_decompress(type, workspace, data_in, dest_page,
1382 start_byte, srclen, destlen);
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001383 put_workspace(type, workspace);
Dennis Zhou7bf49942019-02-04 15:20:04 -05001384
Li Zefan261507a02010-12-17 14:21:50 +08001385 return ret;
1386}
1387
Dennis Zhou1666eda2019-02-04 15:20:01 -05001388void __init btrfs_init_compress(void)
1389{
David Sterbad5517032019-10-02 01:08:03 +02001390 btrfs_init_workspace_manager(BTRFS_COMPRESS_NONE);
1391 btrfs_init_workspace_manager(BTRFS_COMPRESS_ZLIB);
1392 btrfs_init_workspace_manager(BTRFS_COMPRESS_LZO);
1393 zstd_init_workspace_manager();
Dennis Zhou1666eda2019-02-04 15:20:01 -05001394}
1395
David Sterbae67c7182018-02-19 17:24:18 +01001396void __cold btrfs_exit_compress(void)
Li Zefan261507a02010-12-17 14:21:50 +08001397{
David Sterba25103072019-10-02 01:08:03 +02001398 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_NONE);
1399 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_ZLIB);
1400 btrfs_cleanup_workspace_manager(BTRFS_COMPRESS_LZO);
1401 zstd_cleanup_workspace_manager();
Li Zefan261507a02010-12-17 14:21:50 +08001402}
Li Zefan3a39c182010-11-08 15:22:19 +08001403
1404/*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001405 * Copy decompressed data from working buffer to pages.
Li Zefan3a39c182010-11-08 15:22:19 +08001406 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001407 * @buf: The decompressed data buffer
1408 * @buf_len: The decompressed data length
1409 * @decompressed: Number of bytes that are already decompressed inside the
1410 * compressed extent
1411 * @cb: The compressed extent descriptor
1412 * @orig_bio: The original bio that the caller wants to read for
Li Zefan3a39c182010-11-08 15:22:19 +08001413 *
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001414 * An easier to understand graph is like below:
1415 *
1416 * |<- orig_bio ->| |<- orig_bio->|
1417 * |<------- full decompressed extent ----->|
1418 * |<----------- @cb range ---->|
1419 * | |<-- @buf_len -->|
1420 * |<--- @decompressed --->|
1421 *
1422 * Note that, @cb can be a subpage of the full decompressed extent, but
1423 * @cb->start always has the same as the orig_file_offset value of the full
1424 * decompressed extent.
1425 *
1426 * When reading compressed extent, we have to read the full compressed extent,
1427 * while @orig_bio may only want part of the range.
1428 * Thus this function will ensure only data covered by @orig_bio will be copied
1429 * to.
1430 *
1431 * Return 0 if we have copied all needed contents for @orig_bio.
1432 * Return >0 if we need continue decompress.
Li Zefan3a39c182010-11-08 15:22:19 +08001433 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001434int btrfs_decompress_buf2page(const char *buf, u32 buf_len,
1435 struct compressed_bio *cb, u32 decompressed)
Li Zefan3a39c182010-11-08 15:22:19 +08001436{
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001437 struct bio *orig_bio = cb->orig_bio;
1438 /* Offset inside the full decompressed extent */
1439 u32 cur_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001440
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001441 cur_offset = decompressed;
1442 /* The main loop to do the copy */
1443 while (cur_offset < decompressed + buf_len) {
1444 struct bio_vec bvec;
1445 size_t copy_len;
1446 u32 copy_start;
1447 /* Offset inside the full decompressed extent */
1448 u32 bvec_offset;
Li Zefan3a39c182010-11-08 15:22:19 +08001449
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001450 bvec = bio_iter_iovec(orig_bio, orig_bio->bi_iter);
1451 /*
1452 * cb->start may underflow, but subtracting that value can still
1453 * give us correct offset inside the full decompressed extent.
1454 */
1455 bvec_offset = page_offset(bvec.bv_page) + bvec.bv_offset - cb->start;
Li Zefan3a39c182010-11-08 15:22:19 +08001456
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001457 /* Haven't reached the bvec range, exit */
1458 if (decompressed + buf_len <= bvec_offset)
1459 return 1;
Li Zefan3a39c182010-11-08 15:22:19 +08001460
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001461 copy_start = max(cur_offset, bvec_offset);
1462 copy_len = min(bvec_offset + bvec.bv_len,
1463 decompressed + buf_len) - copy_start;
1464 ASSERT(copy_len);
Li Zefan3a39c182010-11-08 15:22:19 +08001465
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001466 /*
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001467 * Extra range check to ensure we didn't go beyond
1468 * @buf + @buf_len.
Christoph Hellwig974b1ad2016-11-25 09:07:46 +01001469 */
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001470 ASSERT(copy_start - decompressed < buf_len);
1471 memcpy_to_page(bvec.bv_page, bvec.bv_offset,
1472 buf + copy_start - decompressed, copy_len);
1473 flush_dcache_page(bvec.bv_page);
1474 cur_offset += copy_len;
Li Zefan3a39c182010-11-08 15:22:19 +08001475
Qu Wenruo1c3dc172021-07-05 10:00:58 +08001476 bio_advance(orig_bio, copy_len);
1477 /* Finished the bio */
1478 if (!orig_bio->bi_iter.bi_size)
1479 return 0;
Li Zefan3a39c182010-11-08 15:22:19 +08001480 }
Li Zefan3a39c182010-11-08 15:22:19 +08001481 return 1;
1482}
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001483
Timofey Titovets19562432017-10-08 16:11:59 +03001484/*
1485 * Shannon Entropy calculation
1486 *
Andrea Gelmini52042d82018-11-28 12:05:13 +01001487 * Pure byte distribution analysis fails to determine compressibility of data.
Timofey Titovets19562432017-10-08 16:11:59 +03001488 * Try calculating entropy to estimate the average minimum number of bits
1489 * needed to encode the sampled data.
1490 *
1491 * For convenience, return the percentage of needed bits, instead of amount of
1492 * bits directly.
1493 *
1494 * @ENTROPY_LVL_ACEPTABLE - below that threshold, sample has low byte entropy
1495 * and can be compressible with high probability
1496 *
1497 * @ENTROPY_LVL_HIGH - data are not compressible with high probability
1498 *
1499 * Use of ilog2() decreases precision, we lower the LVL to 5 to compensate.
1500 */
1501#define ENTROPY_LVL_ACEPTABLE (65)
1502#define ENTROPY_LVL_HIGH (80)
1503
1504/*
1505 * For increasead precision in shannon_entropy calculation,
1506 * let's do pow(n, M) to save more digits after comma:
1507 *
1508 * - maximum int bit length is 64
1509 * - ilog2(MAX_SAMPLE_SIZE) -> 13
1510 * - 13 * 4 = 52 < 64 -> M = 4
1511 *
1512 * So use pow(n, 4).
1513 */
1514static inline u32 ilog2_w(u64 n)
1515{
1516 return ilog2(n * n * n * n);
1517}
1518
1519static u32 shannon_entropy(struct heuristic_ws *ws)
1520{
1521 const u32 entropy_max = 8 * ilog2_w(2);
1522 u32 entropy_sum = 0;
1523 u32 p, p_base, sz_base;
1524 u32 i;
1525
1526 sz_base = ilog2_w(ws->sample_size);
1527 for (i = 0; i < BUCKET_SIZE && ws->bucket[i].count > 0; i++) {
1528 p = ws->bucket[i].count;
1529 p_base = ilog2_w(p);
1530 entropy_sum += p * (sz_base - p_base);
1531 }
1532
1533 entropy_sum /= ws->sample_size;
1534 return entropy_sum * 100 / entropy_max;
1535}
1536
Timofey Titovets440c8402017-12-04 00:30:33 +03001537#define RADIX_BASE 4U
1538#define COUNTERS_SIZE (1U << RADIX_BASE)
Timofey Titovets858177d2017-09-28 17:33:41 +03001539
Timofey Titovets440c8402017-12-04 00:30:33 +03001540static u8 get4bits(u64 num, int shift) {
1541 u8 low4bits;
1542
1543 num >>= shift;
1544 /* Reverse order */
1545 low4bits = (COUNTERS_SIZE - 1) - (num % COUNTERS_SIZE);
1546 return low4bits;
1547}
1548
Timofey Titovets440c8402017-12-04 00:30:33 +03001549/*
1550 * Use 4 bits as radix base
Andrea Gelmini52042d82018-11-28 12:05:13 +01001551 * Use 16 u32 counters for calculating new position in buf array
Timofey Titovets440c8402017-12-04 00:30:33 +03001552 *
1553 * @array - array that will be sorted
1554 * @array_buf - buffer array to store sorting results
1555 * must be equal in size to @array
1556 * @num - array size
Timofey Titovets440c8402017-12-04 00:30:33 +03001557 */
David Sterba23ae8c62017-12-12 20:35:02 +01001558static void radix_sort(struct bucket_item *array, struct bucket_item *array_buf,
David Sterba36243c92017-12-12 20:35:02 +01001559 int num)
Timofey Titovets440c8402017-12-04 00:30:33 +03001560{
1561 u64 max_num;
1562 u64 buf_num;
1563 u32 counters[COUNTERS_SIZE];
1564 u32 new_addr;
1565 u32 addr;
1566 int bitlen;
1567 int shift;
1568 int i;
1569
1570 /*
1571 * Try avoid useless loop iterations for small numbers stored in big
1572 * counters. Example: 48 33 4 ... in 64bit array
1573 */
David Sterba23ae8c62017-12-12 20:35:02 +01001574 max_num = array[0].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001575 for (i = 1; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001576 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001577 if (buf_num > max_num)
1578 max_num = buf_num;
1579 }
1580
1581 buf_num = ilog2(max_num);
1582 bitlen = ALIGN(buf_num, RADIX_BASE * 2);
1583
1584 shift = 0;
1585 while (shift < bitlen) {
1586 memset(counters, 0, sizeof(counters));
1587
1588 for (i = 0; i < num; i++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001589 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001590 addr = get4bits(buf_num, shift);
1591 counters[addr]++;
1592 }
1593
1594 for (i = 1; i < COUNTERS_SIZE; i++)
1595 counters[i] += counters[i - 1];
1596
1597 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001598 buf_num = array[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001599 addr = get4bits(buf_num, shift);
1600 counters[addr]--;
1601 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001602 array_buf[new_addr] = array[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001603 }
1604
1605 shift += RADIX_BASE;
1606
1607 /*
1608 * Normal radix expects to move data from a temporary array, to
1609 * the main one. But that requires some CPU time. Avoid that
1610 * by doing another sort iteration to original array instead of
1611 * memcpy()
1612 */
1613 memset(counters, 0, sizeof(counters));
1614
1615 for (i = 0; i < num; i ++) {
David Sterba23ae8c62017-12-12 20:35:02 +01001616 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001617 addr = get4bits(buf_num, shift);
1618 counters[addr]++;
1619 }
1620
1621 for (i = 1; i < COUNTERS_SIZE; i++)
1622 counters[i] += counters[i - 1];
1623
1624 for (i = num - 1; i >= 0; i--) {
David Sterba23ae8c62017-12-12 20:35:02 +01001625 buf_num = array_buf[i].count;
Timofey Titovets440c8402017-12-04 00:30:33 +03001626 addr = get4bits(buf_num, shift);
1627 counters[addr]--;
1628 new_addr = counters[addr];
David Sterba7add17b2017-12-12 20:35:02 +01001629 array[new_addr] = array_buf[i];
Timofey Titovets440c8402017-12-04 00:30:33 +03001630 }
1631
1632 shift += RADIX_BASE;
1633 }
Timofey Titovets858177d2017-09-28 17:33:41 +03001634}
1635
1636/*
1637 * Size of the core byte set - how many bytes cover 90% of the sample
1638 *
1639 * There are several types of structured binary data that use nearly all byte
1640 * values. The distribution can be uniform and counts in all buckets will be
1641 * nearly the same (eg. encrypted data). Unlikely to be compressible.
1642 *
1643 * Other possibility is normal (Gaussian) distribution, where the data could
1644 * be potentially compressible, but we have to take a few more steps to decide
1645 * how much.
1646 *
1647 * @BYTE_CORE_SET_LOW - main part of byte values repeated frequently,
1648 * compression algo can easy fix that
1649 * @BYTE_CORE_SET_HIGH - data have uniform distribution and with high
1650 * probability is not compressible
1651 */
1652#define BYTE_CORE_SET_LOW (64)
1653#define BYTE_CORE_SET_HIGH (200)
1654
1655static int byte_core_set_size(struct heuristic_ws *ws)
1656{
1657 u32 i;
1658 u32 coreset_sum = 0;
1659 const u32 core_set_threshold = ws->sample_size * 90 / 100;
1660 struct bucket_item *bucket = ws->bucket;
1661
1662 /* Sort in reverse order */
David Sterba36243c92017-12-12 20:35:02 +01001663 radix_sort(ws->bucket, ws->bucket_b, BUCKET_SIZE);
Timofey Titovets858177d2017-09-28 17:33:41 +03001664
1665 for (i = 0; i < BYTE_CORE_SET_LOW; i++)
1666 coreset_sum += bucket[i].count;
1667
1668 if (coreset_sum > core_set_threshold)
1669 return i;
1670
1671 for (; i < BYTE_CORE_SET_HIGH && bucket[i].count > 0; i++) {
1672 coreset_sum += bucket[i].count;
1673 if (coreset_sum > core_set_threshold)
1674 break;
1675 }
1676
1677 return i;
1678}
1679
Timofey Titovetsa288e922017-09-28 17:33:40 +03001680/*
1681 * Count byte values in buckets.
1682 * This heuristic can detect textual data (configs, xml, json, html, etc).
1683 * Because in most text-like data byte set is restricted to limited number of
1684 * possible characters, and that restriction in most cases makes data easy to
1685 * compress.
1686 *
1687 * @BYTE_SET_THRESHOLD - consider all data within this byte set size:
1688 * less - compressible
1689 * more - need additional analysis
1690 */
1691#define BYTE_SET_THRESHOLD (64)
1692
1693static u32 byte_set_size(const struct heuristic_ws *ws)
1694{
1695 u32 i;
1696 u32 byte_set_size = 0;
1697
1698 for (i = 0; i < BYTE_SET_THRESHOLD; i++) {
1699 if (ws->bucket[i].count > 0)
1700 byte_set_size++;
1701 }
1702
1703 /*
1704 * Continue collecting count of byte values in buckets. If the byte
1705 * set size is bigger then the threshold, it's pointless to continue,
1706 * the detection technique would fail for this type of data.
1707 */
1708 for (; i < BUCKET_SIZE; i++) {
1709 if (ws->bucket[i].count > 0) {
1710 byte_set_size++;
1711 if (byte_set_size > BYTE_SET_THRESHOLD)
1712 return byte_set_size;
1713 }
1714 }
1715
1716 return byte_set_size;
1717}
1718
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001719static bool sample_repeated_patterns(struct heuristic_ws *ws)
1720{
1721 const u32 half_of_sample = ws->sample_size / 2;
1722 const u8 *data = ws->sample;
1723
1724 return memcmp(&data[0], &data[half_of_sample], half_of_sample) == 0;
1725}
1726
Timofey Titovetsa440d482017-09-28 17:33:38 +03001727static void heuristic_collect_sample(struct inode *inode, u64 start, u64 end,
1728 struct heuristic_ws *ws)
1729{
1730 struct page *page;
1731 u64 index, index_end;
1732 u32 i, curr_sample_pos;
1733 u8 *in_data;
1734
1735 /*
1736 * Compression handles the input data by chunks of 128KiB
1737 * (defined by BTRFS_MAX_UNCOMPRESSED)
1738 *
1739 * We do the same for the heuristic and loop over the whole range.
1740 *
1741 * MAX_SAMPLE_SIZE - calculated under assumption that heuristic will
1742 * process no more than BTRFS_MAX_UNCOMPRESSED at a time.
1743 */
1744 if (end - start > BTRFS_MAX_UNCOMPRESSED)
1745 end = start + BTRFS_MAX_UNCOMPRESSED;
1746
1747 index = start >> PAGE_SHIFT;
1748 index_end = end >> PAGE_SHIFT;
1749
1750 /* Don't miss unaligned end */
1751 if (!IS_ALIGNED(end, PAGE_SIZE))
1752 index_end++;
1753
1754 curr_sample_pos = 0;
1755 while (index < index_end) {
1756 page = find_get_page(inode->i_mapping, index);
Ira Weiny58c1a352021-02-16 18:48:23 -08001757 in_data = kmap_local_page(page);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001758 /* Handle case where the start is not aligned to PAGE_SIZE */
1759 i = start % PAGE_SIZE;
1760 while (i < PAGE_SIZE - SAMPLING_READ_SIZE) {
1761 /* Don't sample any garbage from the last page */
1762 if (start > end - SAMPLING_READ_SIZE)
1763 break;
1764 memcpy(&ws->sample[curr_sample_pos], &in_data[i],
1765 SAMPLING_READ_SIZE);
1766 i += SAMPLING_INTERVAL;
1767 start += SAMPLING_INTERVAL;
1768 curr_sample_pos += SAMPLING_READ_SIZE;
1769 }
Ira Weiny58c1a352021-02-16 18:48:23 -08001770 kunmap_local(in_data);
Timofey Titovetsa440d482017-09-28 17:33:38 +03001771 put_page(page);
1772
1773 index++;
1774 }
1775
1776 ws->sample_size = curr_sample_pos;
1777}
1778
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001779/*
1780 * Compression heuristic.
1781 *
1782 * For now is's a naive and optimistic 'return true', we'll extend the logic to
1783 * quickly (compared to direct compression) detect data characteristics
1784 * (compressible/uncompressible) to avoid wasting CPU time on uncompressible
1785 * data.
1786 *
1787 * The following types of analysis can be performed:
1788 * - detect mostly zero data
1789 * - detect data with low "byte set" size (text, etc)
1790 * - detect data with low/high "core byte" set
1791 *
1792 * Return non-zero if the compression should be done, 0 otherwise.
1793 */
1794int btrfs_compress_heuristic(struct inode *inode, u64 start, u64 end)
1795{
Dennis Zhou7bf49942019-02-04 15:20:04 -05001796 struct list_head *ws_list = get_workspace(0, 0);
Timofey Titovets4e439a02017-09-28 17:33:36 +03001797 struct heuristic_ws *ws;
Timofey Titovetsa440d482017-09-28 17:33:38 +03001798 u32 i;
1799 u8 byte;
Timofey Titovets19562432017-10-08 16:11:59 +03001800 int ret = 0;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001801
Timofey Titovets4e439a02017-09-28 17:33:36 +03001802 ws = list_entry(ws_list, struct heuristic_ws, list);
1803
Timofey Titovetsa440d482017-09-28 17:33:38 +03001804 heuristic_collect_sample(inode, start, end, ws);
1805
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001806 if (sample_repeated_patterns(ws)) {
1807 ret = 1;
1808 goto out;
1809 }
1810
Timofey Titovetsa440d482017-09-28 17:33:38 +03001811 memset(ws->bucket, 0, sizeof(*ws->bucket)*BUCKET_SIZE);
1812
1813 for (i = 0; i < ws->sample_size; i++) {
1814 byte = ws->sample[i];
1815 ws->bucket[byte].count++;
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001816 }
1817
Timofey Titovetsa288e922017-09-28 17:33:40 +03001818 i = byte_set_size(ws);
1819 if (i < BYTE_SET_THRESHOLD) {
1820 ret = 2;
1821 goto out;
1822 }
1823
Timofey Titovets858177d2017-09-28 17:33:41 +03001824 i = byte_core_set_size(ws);
1825 if (i <= BYTE_CORE_SET_LOW) {
1826 ret = 3;
1827 goto out;
1828 }
1829
1830 if (i >= BYTE_CORE_SET_HIGH) {
1831 ret = 0;
1832 goto out;
1833 }
1834
Timofey Titovets19562432017-10-08 16:11:59 +03001835 i = shannon_entropy(ws);
1836 if (i <= ENTROPY_LVL_ACEPTABLE) {
1837 ret = 4;
1838 goto out;
1839 }
1840
1841 /*
1842 * For the levels below ENTROPY_LVL_HIGH, additional analysis would be
1843 * needed to give green light to compression.
1844 *
1845 * For now just assume that compression at that level is not worth the
1846 * resources because:
1847 *
1848 * 1. it is possible to defrag the data later
1849 *
1850 * 2. the data would turn out to be hardly compressible, eg. 150 byte
1851 * values, every bucket has counter at level ~54. The heuristic would
1852 * be confused. This can happen when data have some internal repeated
1853 * patterns like "abbacbbc...". This can be detected by analyzing
1854 * pairs of bytes, which is too costly.
1855 */
1856 if (i < ENTROPY_LVL_HIGH) {
1857 ret = 5;
1858 goto out;
1859 } else {
1860 ret = 0;
1861 goto out;
1862 }
1863
Timofey Titovets1fe4f6f2017-09-28 17:33:39 +03001864out:
Dennis Zhou929f4ba2019-02-04 15:20:02 -05001865 put_workspace(0, ws_list);
Timofey Titovetsc2fcdcd2017-07-17 16:52:58 +03001866 return ret;
1867}
David Sterbaf51d2b52017-09-15 17:36:57 +02001868
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001869/*
1870 * Convert the compression suffix (eg. after "zlib" starting with ":") to
1871 * level, unrecognized string will set the default level
1872 */
1873unsigned int btrfs_compress_str2level(unsigned int type, const char *str)
David Sterbaf51d2b52017-09-15 17:36:57 +02001874{
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001875 unsigned int level = 0;
1876 int ret;
1877
1878 if (!type)
David Sterbaf51d2b52017-09-15 17:36:57 +02001879 return 0;
1880
Dennis Zhoud0ab62c2019-02-04 15:20:05 -05001881 if (str[0] == ':') {
1882 ret = kstrtouint(str + 1, 10, &level);
1883 if (ret)
1884 level = 0;
1885 }
David Sterbaf51d2b52017-09-15 17:36:57 +02001886
David Sterbab0c1fe12019-08-09 16:49:06 +02001887 level = btrfs_compress_set_level(type, level);
1888
1889 return level;
1890}