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