]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/compress.c
Update bcachefs sources to e48731a188 bcachefs: Fix BTREE_TRIGGER_WANTS_OLD_AND_NEW
[bcachefs-tools-debian] / libbcachefs / compress.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include "bcachefs.h"
3 #include "checksum.h"
4 #include "compress.h"
5 #include "extents.h"
6 #include "io.h"
7 #include "super-io.h"
8
9 #include <linux/lz4.h>
10 #include <linux/zlib.h>
11 #include <linux/zstd.h>
12
13 /* Bounce buffer: */
14 struct bbuf {
15         void            *b;
16         enum {
17                 BB_NONE,
18                 BB_VMAP,
19                 BB_KMALLOC,
20                 BB_MEMPOOL,
21         }               type;
22         int             rw;
23 };
24
25 static struct bbuf __bounce_alloc(struct bch_fs *c, unsigned size, int rw)
26 {
27         void *b;
28
29         BUG_ON(size > c->opts.encoded_extent_max);
30
31         b = kmalloc(size, GFP_NOIO|__GFP_NOWARN);
32         if (b)
33                 return (struct bbuf) { .b = b, .type = BB_KMALLOC, .rw = rw };
34
35         b = mempool_alloc(&c->compression_bounce[rw], GFP_NOIO);
36         if (b)
37                 return (struct bbuf) { .b = b, .type = BB_MEMPOOL, .rw = rw };
38
39         BUG();
40 }
41
42 static bool bio_phys_contig(struct bio *bio, struct bvec_iter start)
43 {
44         struct bio_vec bv;
45         struct bvec_iter iter;
46         void *expected_start = NULL;
47
48         __bio_for_each_bvec(bv, bio, iter, start) {
49                 if (expected_start &&
50                     expected_start != page_address(bv.bv_page) + bv.bv_offset)
51                         return false;
52
53                 expected_start = page_address(bv.bv_page) +
54                         bv.bv_offset + bv.bv_len;
55         }
56
57         return true;
58 }
59
60 static struct bbuf __bio_map_or_bounce(struct bch_fs *c, struct bio *bio,
61                                        struct bvec_iter start, int rw)
62 {
63         struct bbuf ret;
64         struct bio_vec bv;
65         struct bvec_iter iter;
66         unsigned nr_pages = 0;
67         struct page *stack_pages[16];
68         struct page **pages = NULL;
69         void *data;
70
71         BUG_ON(start.bi_size > c->opts.encoded_extent_max);
72
73         if (!PageHighMem(bio_iter_page(bio, start)) &&
74             bio_phys_contig(bio, start))
75                 return (struct bbuf) {
76                         .b = page_address(bio_iter_page(bio, start)) +
77                                 bio_iter_offset(bio, start),
78                         .type = BB_NONE, .rw = rw
79                 };
80
81         /* check if we can map the pages contiguously: */
82         __bio_for_each_segment(bv, bio, iter, start) {
83                 if (iter.bi_size != start.bi_size &&
84                     bv.bv_offset)
85                         goto bounce;
86
87                 if (bv.bv_len < iter.bi_size &&
88                     bv.bv_offset + bv.bv_len < PAGE_SIZE)
89                         goto bounce;
90
91                 nr_pages++;
92         }
93
94         BUG_ON(DIV_ROUND_UP(start.bi_size, PAGE_SIZE) > nr_pages);
95
96         pages = nr_pages > ARRAY_SIZE(stack_pages)
97                 ? kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOIO)
98                 : stack_pages;
99         if (!pages)
100                 goto bounce;
101
102         nr_pages = 0;
103         __bio_for_each_segment(bv, bio, iter, start)
104                 pages[nr_pages++] = bv.bv_page;
105
106         data = vmap(pages, nr_pages, VM_MAP, PAGE_KERNEL);
107         if (pages != stack_pages)
108                 kfree(pages);
109
110         if (data)
111                 return (struct bbuf) {
112                         .b = data + bio_iter_offset(bio, start),
113                         .type = BB_VMAP, .rw = rw
114                 };
115 bounce:
116         ret = __bounce_alloc(c, start.bi_size, rw);
117
118         if (rw == READ)
119                 memcpy_from_bio(ret.b, bio, start);
120
121         return ret;
122 }
123
124 static struct bbuf bio_map_or_bounce(struct bch_fs *c, struct bio *bio, int rw)
125 {
126         return __bio_map_or_bounce(c, bio, bio->bi_iter, rw);
127 }
128
129 static void bio_unmap_or_unbounce(struct bch_fs *c, struct bbuf buf)
130 {
131         switch (buf.type) {
132         case BB_NONE:
133                 break;
134         case BB_VMAP:
135                 vunmap((void *) ((unsigned long) buf.b & PAGE_MASK));
136                 break;
137         case BB_KMALLOC:
138                 kfree(buf.b);
139                 break;
140         case BB_MEMPOOL:
141                 mempool_free(buf.b, &c->compression_bounce[buf.rw]);
142                 break;
143         }
144 }
145
146 static inline void zlib_set_workspace(z_stream *strm, void *workspace)
147 {
148 #ifdef __KERNEL__
149         strm->workspace = workspace;
150 #endif
151 }
152
153 static int __bio_uncompress(struct bch_fs *c, struct bio *src,
154                             void *dst_data, struct bch_extent_crc_unpacked crc)
155 {
156         struct bbuf src_data = { NULL };
157         size_t src_len = src->bi_iter.bi_size;
158         size_t dst_len = crc.uncompressed_size << 9;
159         void *workspace;
160         int ret;
161
162         src_data = bio_map_or_bounce(c, src, READ);
163
164         switch (crc.compression_type) {
165         case BCH_COMPRESSION_TYPE_lz4_old:
166         case BCH_COMPRESSION_TYPE_lz4:
167                 ret = LZ4_decompress_safe_partial(src_data.b, dst_data,
168                                                   src_len, dst_len, dst_len);
169                 if (ret != dst_len)
170                         goto err;
171                 break;
172         case BCH_COMPRESSION_TYPE_gzip: {
173                 z_stream strm = {
174                         .next_in        = src_data.b,
175                         .avail_in       = src_len,
176                         .next_out       = dst_data,
177                         .avail_out      = dst_len,
178                 };
179
180                 workspace = mempool_alloc(&c->decompress_workspace, GFP_NOIO);
181
182                 zlib_set_workspace(&strm, workspace);
183                 zlib_inflateInit2(&strm, -MAX_WBITS);
184                 ret = zlib_inflate(&strm, Z_FINISH);
185
186                 mempool_free(workspace, &c->decompress_workspace);
187
188                 if (ret != Z_STREAM_END)
189                         goto err;
190                 break;
191         }
192         case BCH_COMPRESSION_TYPE_zstd: {
193                 ZSTD_DCtx *ctx;
194                 size_t real_src_len = le32_to_cpup(src_data.b);
195
196                 if (real_src_len > src_len - 4)
197                         goto err;
198
199                 workspace = mempool_alloc(&c->decompress_workspace, GFP_NOIO);
200                 ctx = zstd_init_dctx(workspace, zstd_dctx_workspace_bound());
201
202                 src_len = le32_to_cpup(src_data.b);
203
204                 ret = zstd_decompress_dctx(ctx,
205                                 dst_data,       dst_len,
206                                 src_data.b + 4, real_src_len);
207
208                 mempool_free(workspace, &c->decompress_workspace);
209
210                 if (ret != dst_len)
211                         goto err;
212                 break;
213         }
214         default:
215                 BUG();
216         }
217         ret = 0;
218 out:
219         bio_unmap_or_unbounce(c, src_data);
220         return ret;
221 err:
222         ret = -EIO;
223         goto out;
224 }
225
226 int bch2_bio_uncompress_inplace(struct bch_fs *c, struct bio *bio,
227                                 struct bch_extent_crc_unpacked *crc)
228 {
229         struct bbuf data = { NULL };
230         size_t dst_len = crc->uncompressed_size << 9;
231
232         /* bio must own its pages: */
233         BUG_ON(!bio->bi_vcnt);
234         BUG_ON(DIV_ROUND_UP(crc->live_size, PAGE_SECTORS) > bio->bi_max_vecs);
235
236         if (crc->uncompressed_size << 9 > c->opts.encoded_extent_max ||
237             crc->compressed_size << 9   > c->opts.encoded_extent_max) {
238                 bch_err(c, "error rewriting existing data: extent too big");
239                 return -EIO;
240         }
241
242         data = __bounce_alloc(c, dst_len, WRITE);
243
244         if (__bio_uncompress(c, bio, data.b, *crc)) {
245                 bch_err(c, "error rewriting existing data: decompression error");
246                 bio_unmap_or_unbounce(c, data);
247                 return -EIO;
248         }
249
250         /*
251          * XXX: don't have a good way to assert that the bio was allocated with
252          * enough space, we depend on bch2_move_extent doing the right thing
253          */
254         bio->bi_iter.bi_size = crc->live_size << 9;
255
256         memcpy_to_bio(bio, bio->bi_iter, data.b + (crc->offset << 9));
257
258         crc->csum_type          = 0;
259         crc->compression_type   = 0;
260         crc->compressed_size    = crc->live_size;
261         crc->uncompressed_size  = crc->live_size;
262         crc->offset             = 0;
263         crc->csum               = (struct bch_csum) { 0, 0 };
264
265         bio_unmap_or_unbounce(c, data);
266         return 0;
267 }
268
269 int bch2_bio_uncompress(struct bch_fs *c, struct bio *src,
270                        struct bio *dst, struct bvec_iter dst_iter,
271                        struct bch_extent_crc_unpacked crc)
272 {
273         struct bbuf dst_data = { NULL };
274         size_t dst_len = crc.uncompressed_size << 9;
275         int ret = -ENOMEM;
276
277         if (crc.uncompressed_size << 9  > c->opts.encoded_extent_max ||
278             crc.compressed_size << 9    > c->opts.encoded_extent_max)
279                 return -EIO;
280
281         dst_data = dst_len == dst_iter.bi_size
282                 ? __bio_map_or_bounce(c, dst, dst_iter, WRITE)
283                 : __bounce_alloc(c, dst_len, WRITE);
284
285         ret = __bio_uncompress(c, src, dst_data.b, crc);
286         if (ret)
287                 goto err;
288
289         if (dst_data.type != BB_NONE &&
290             dst_data.type != BB_VMAP)
291                 memcpy_to_bio(dst, dst_iter, dst_data.b + (crc.offset << 9));
292 err:
293         bio_unmap_or_unbounce(c, dst_data);
294         return ret;
295 }
296
297 static int attempt_compress(struct bch_fs *c,
298                             void *workspace,
299                             void *dst, size_t dst_len,
300                             void *src, size_t src_len,
301                             enum bch_compression_type compression_type)
302 {
303         switch (compression_type) {
304         case BCH_COMPRESSION_TYPE_lz4: {
305                 int len = src_len;
306                 int ret = LZ4_compress_destSize(
307                                 src,            dst,
308                                 &len,           dst_len,
309                                 workspace);
310
311                 if (len < src_len)
312                         return -len;
313
314                 return ret;
315         }
316         case BCH_COMPRESSION_TYPE_gzip: {
317                 z_stream strm = {
318                         .next_in        = src,
319                         .avail_in       = src_len,
320                         .next_out       = dst,
321                         .avail_out      = dst_len,
322                 };
323
324                 zlib_set_workspace(&strm, workspace);
325                 zlib_deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
326                                   Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL,
327                                   Z_DEFAULT_STRATEGY);
328
329                 if (zlib_deflate(&strm, Z_FINISH) != Z_STREAM_END)
330                         return 0;
331
332                 if (zlib_deflateEnd(&strm) != Z_OK)
333                         return 0;
334
335                 return strm.total_out;
336         }
337         case BCH_COMPRESSION_TYPE_zstd: {
338                 ZSTD_CCtx *ctx = zstd_init_cctx(workspace,
339                         zstd_cctx_workspace_bound(&c->zstd_params.cParams));
340
341                 /*
342                  * ZSTD requires that when we decompress we pass in the exact
343                  * compressed size - rounding it up to the nearest sector
344                  * doesn't work, so we use the first 4 bytes of the buffer for
345                  * that.
346                  *
347                  * Additionally, the ZSTD code seems to have a bug where it will
348                  * write just past the end of the buffer - so subtract a fudge
349                  * factor (7 bytes) from the dst buffer size to account for
350                  * that.
351                  */
352                 size_t len = zstd_compress_cctx(ctx,
353                                 dst + 4,        dst_len - 4 - 7,
354                                 src,            src_len,
355                                 &c->zstd_params);
356                 if (zstd_is_error(len))
357                         return 0;
358
359                 *((__le32 *) dst) = cpu_to_le32(len);
360                 return len + 4;
361         }
362         default:
363                 BUG();
364         }
365 }
366
367 static unsigned __bio_compress(struct bch_fs *c,
368                                struct bio *dst, size_t *dst_len,
369                                struct bio *src, size_t *src_len,
370                                enum bch_compression_type compression_type)
371 {
372         struct bbuf src_data = { NULL }, dst_data = { NULL };
373         void *workspace;
374         unsigned pad;
375         int ret = 0;
376
377         BUG_ON(compression_type >= BCH_COMPRESSION_TYPE_NR);
378         BUG_ON(!mempool_initialized(&c->compress_workspace[compression_type]));
379
380         /* If it's only one block, don't bother trying to compress: */
381         if (src->bi_iter.bi_size <= c->opts.block_size)
382                 return 0;
383
384         dst_data = bio_map_or_bounce(c, dst, WRITE);
385         src_data = bio_map_or_bounce(c, src, READ);
386
387         workspace = mempool_alloc(&c->compress_workspace[compression_type], GFP_NOIO);
388
389         *src_len = src->bi_iter.bi_size;
390         *dst_len = dst->bi_iter.bi_size;
391
392         /*
393          * XXX: this algorithm sucks when the compression code doesn't tell us
394          * how much would fit, like LZ4 does:
395          */
396         while (1) {
397                 if (*src_len <= block_bytes(c)) {
398                         ret = -1;
399                         break;
400                 }
401
402                 ret = attempt_compress(c, workspace,
403                                        dst_data.b,      *dst_len,
404                                        src_data.b,      *src_len,
405                                        compression_type);
406                 if (ret > 0) {
407                         *dst_len = ret;
408                         ret = 0;
409                         break;
410                 }
411
412                 /* Didn't fit: should we retry with a smaller amount?  */
413                 if (*src_len <= *dst_len) {
414                         ret = -1;
415                         break;
416                 }
417
418                 /*
419                  * If ret is negative, it's a hint as to how much data would fit
420                  */
421                 BUG_ON(-ret >= *src_len);
422
423                 if (ret < 0)
424                         *src_len = -ret;
425                 else
426                         *src_len -= (*src_len - *dst_len) / 2;
427                 *src_len = round_down(*src_len, block_bytes(c));
428         }
429
430         mempool_free(workspace, &c->compress_workspace[compression_type]);
431
432         if (ret)
433                 goto err;
434
435         /* Didn't get smaller: */
436         if (round_up(*dst_len, block_bytes(c)) >= *src_len)
437                 goto err;
438
439         pad = round_up(*dst_len, block_bytes(c)) - *dst_len;
440
441         memset(dst_data.b + *dst_len, 0, pad);
442         *dst_len += pad;
443
444         if (dst_data.type != BB_NONE &&
445             dst_data.type != BB_VMAP)
446                 memcpy_to_bio(dst, dst->bi_iter, dst_data.b);
447
448         BUG_ON(!*dst_len || *dst_len > dst->bi_iter.bi_size);
449         BUG_ON(!*src_len || *src_len > src->bi_iter.bi_size);
450         BUG_ON(*dst_len & (block_bytes(c) - 1));
451         BUG_ON(*src_len & (block_bytes(c) - 1));
452 out:
453         bio_unmap_or_unbounce(c, src_data);
454         bio_unmap_or_unbounce(c, dst_data);
455         return compression_type;
456 err:
457         compression_type = BCH_COMPRESSION_TYPE_incompressible;
458         goto out;
459 }
460
461 unsigned bch2_bio_compress(struct bch_fs *c,
462                            struct bio *dst, size_t *dst_len,
463                            struct bio *src, size_t *src_len,
464                            unsigned compression_type)
465 {
466         unsigned orig_dst = dst->bi_iter.bi_size;
467         unsigned orig_src = src->bi_iter.bi_size;
468
469         /* Don't consume more than BCH_ENCODED_EXTENT_MAX from @src: */
470         src->bi_iter.bi_size = min_t(unsigned, src->bi_iter.bi_size,
471                                      c->opts.encoded_extent_max);
472         /* Don't generate a bigger output than input: */
473         dst->bi_iter.bi_size = min(dst->bi_iter.bi_size, src->bi_iter.bi_size);
474
475         if (compression_type == BCH_COMPRESSION_TYPE_lz4_old)
476                 compression_type = BCH_COMPRESSION_TYPE_lz4;
477
478         compression_type =
479                 __bio_compress(c, dst, dst_len, src, src_len, compression_type);
480
481         dst->bi_iter.bi_size = orig_dst;
482         src->bi_iter.bi_size = orig_src;
483         return compression_type;
484 }
485
486 static int __bch2_fs_compress_init(struct bch_fs *, u64);
487
488 #define BCH_FEATURE_none        0
489
490 static const unsigned bch2_compression_opt_to_feature[] = {
491 #define x(t, n) [BCH_COMPRESSION_OPT_##t] = BCH_FEATURE_##t,
492         BCH_COMPRESSION_OPTS()
493 #undef x
494 };
495
496 #undef BCH_FEATURE_none
497
498 static int __bch2_check_set_has_compressed_data(struct bch_fs *c, u64 f)
499 {
500         int ret = 0;
501
502         if ((c->sb.features & f) == f)
503                 return 0;
504
505         mutex_lock(&c->sb_lock);
506
507         if ((c->sb.features & f) == f) {
508                 mutex_unlock(&c->sb_lock);
509                 return 0;
510         }
511
512         ret = __bch2_fs_compress_init(c, c->sb.features|f);
513         if (ret) {
514                 mutex_unlock(&c->sb_lock);
515                 return ret;
516         }
517
518         c->disk_sb.sb->features[0] |= cpu_to_le64(f);
519         bch2_write_super(c);
520         mutex_unlock(&c->sb_lock);
521
522         return 0;
523 }
524
525 int bch2_check_set_has_compressed_data(struct bch_fs *c,
526                                        unsigned compression_type)
527 {
528         BUG_ON(compression_type >= ARRAY_SIZE(bch2_compression_opt_to_feature));
529
530         return compression_type
531                 ? __bch2_check_set_has_compressed_data(c,
532                                 1ULL << bch2_compression_opt_to_feature[compression_type])
533                 : 0;
534 }
535
536 void bch2_fs_compress_exit(struct bch_fs *c)
537 {
538         unsigned i;
539
540         mempool_exit(&c->decompress_workspace);
541         for (i = 0; i < ARRAY_SIZE(c->compress_workspace); i++)
542                 mempool_exit(&c->compress_workspace[i]);
543         mempool_exit(&c->compression_bounce[WRITE]);
544         mempool_exit(&c->compression_bounce[READ]);
545 }
546
547 static int __bch2_fs_compress_init(struct bch_fs *c, u64 features)
548 {
549         size_t decompress_workspace_size = 0;
550         bool decompress_workspace_needed;
551         ZSTD_parameters params = zstd_get_params(0, c->opts.encoded_extent_max);
552         struct {
553                 unsigned        feature;
554                 unsigned        type;
555                 size_t          compress_workspace;
556                 size_t          decompress_workspace;
557         } compression_types[] = {
558                 { BCH_FEATURE_lz4, BCH_COMPRESSION_TYPE_lz4, LZ4_MEM_COMPRESS, 0 },
559                 { BCH_FEATURE_gzip, BCH_COMPRESSION_TYPE_gzip,
560                         zlib_deflate_workspacesize(MAX_WBITS, DEF_MEM_LEVEL),
561                         zlib_inflate_workspacesize(), },
562                 { BCH_FEATURE_zstd, BCH_COMPRESSION_TYPE_zstd,
563                         zstd_cctx_workspace_bound(&params.cParams),
564                         zstd_dctx_workspace_bound() },
565         }, *i;
566         int ret = 0;
567
568         pr_verbose_init(c->opts, "");
569
570         c->zstd_params = params;
571
572         for (i = compression_types;
573              i < compression_types + ARRAY_SIZE(compression_types);
574              i++)
575                 if (features & (1 << i->feature))
576                         goto have_compressed;
577
578         goto out;
579 have_compressed:
580
581         if (!mempool_initialized(&c->compression_bounce[READ])) {
582                 ret = mempool_init_kvpmalloc_pool(&c->compression_bounce[READ],
583                                                   1, c->opts.encoded_extent_max);
584                 if (ret)
585                         goto out;
586         }
587
588         if (!mempool_initialized(&c->compression_bounce[WRITE])) {
589                 ret = mempool_init_kvpmalloc_pool(&c->compression_bounce[WRITE],
590                                                   1, c->opts.encoded_extent_max);
591                 if (ret)
592                         goto out;
593         }
594
595         for (i = compression_types;
596              i < compression_types + ARRAY_SIZE(compression_types);
597              i++) {
598                 decompress_workspace_size =
599                         max(decompress_workspace_size, i->decompress_workspace);
600
601                 if (!(features & (1 << i->feature)))
602                         continue;
603
604                 if (i->decompress_workspace)
605                         decompress_workspace_needed = true;
606
607                 if (mempool_initialized(&c->compress_workspace[i->type]))
608                         continue;
609
610                 ret = mempool_init_kvpmalloc_pool(
611                                 &c->compress_workspace[i->type],
612                                 1, i->compress_workspace);
613                 if (ret)
614                         goto out;
615         }
616
617         if (!mempool_initialized(&c->decompress_workspace)) {
618                 ret = mempool_init_kvpmalloc_pool(
619                                 &c->decompress_workspace,
620                                 1, decompress_workspace_size);
621                 if (ret)
622                         goto out;
623         }
624 out:
625         pr_verbose_init(c->opts, "ret %i", ret);
626         return ret;
627 }
628
629 int bch2_fs_compress_init(struct bch_fs *c)
630 {
631         u64 f = c->sb.features;
632
633         if (c->opts.compression)
634                 f |= 1ULL << bch2_compression_opt_to_feature[c->opts.compression];
635
636         if (c->opts.background_compression)
637                 f |= 1ULL << bch2_compression_opt_to_feature[c->opts.background_compression];
638
639         return __bch2_fs_compress_init(c, f);
640
641 }