| 1 | // SPDX-License-Identifier: GPL-2.0-only |
| 2 | /* |
| 3 | * Cryptographic API. |
| 4 | * |
| 5 | * Copyright (c) 2013 Chanho Min <chanho.min@lge.com> |
| 6 | */ |
| 7 | #include <crypto/internal/scompress.h> |
| 8 | #include <linux/init.h> |
| 9 | #include <linux/module.h> |
| 10 | #include <linux/vmalloc.h> |
| 11 | #include <linux/lz4.h> |
| 12 | |
| 13 | static void *lz4hc_alloc_ctx(void) |
| 14 | { |
| 15 | void *ctx; |
| 16 | |
| 17 | ctx = vmalloc(LZ4HC_MEM_COMPRESS); |
| 18 | if (!ctx) |
| 19 | return ERR_PTR(error: -ENOMEM); |
| 20 | |
| 21 | return ctx; |
| 22 | } |
| 23 | |
| 24 | static void lz4hc_free_ctx(void *ctx) |
| 25 | { |
| 26 | vfree(addr: ctx); |
| 27 | } |
| 28 | |
| 29 | static int __lz4hc_compress_crypto(const u8 *src, unsigned int slen, |
| 30 | u8 *dst, unsigned int *dlen, void *ctx) |
| 31 | { |
| 32 | int out_len = LZ4_compress_HC(src, dst, srcSize: slen, |
| 33 | dstCapacity: *dlen, LZ4HC_DEFAULT_CLEVEL, wrkmem: ctx); |
| 34 | |
| 35 | if (!out_len) |
| 36 | return -EINVAL; |
| 37 | |
| 38 | *dlen = out_len; |
| 39 | return 0; |
| 40 | } |
| 41 | |
| 42 | static int lz4hc_scompress(struct crypto_scomp *tfm, const u8 *src, |
| 43 | unsigned int slen, u8 *dst, unsigned int *dlen, |
| 44 | void *ctx) |
| 45 | { |
| 46 | return __lz4hc_compress_crypto(src, slen, dst, dlen, ctx); |
| 47 | } |
| 48 | |
| 49 | static int __lz4hc_decompress_crypto(const u8 *src, unsigned int slen, |
| 50 | u8 *dst, unsigned int *dlen, void *ctx) |
| 51 | { |
| 52 | int out_len = LZ4_decompress_safe(source: src, dest: dst, compressedSize: slen, maxDecompressedSize: *dlen); |
| 53 | |
| 54 | if (out_len < 0) |
| 55 | return -EINVAL; |
| 56 | |
| 57 | *dlen = out_len; |
| 58 | return 0; |
| 59 | } |
| 60 | |
| 61 | static int lz4hc_sdecompress(struct crypto_scomp *tfm, const u8 *src, |
| 62 | unsigned int slen, u8 *dst, unsigned int *dlen, |
| 63 | void *ctx) |
| 64 | { |
| 65 | return __lz4hc_decompress_crypto(src, slen, dst, dlen, NULL); |
| 66 | } |
| 67 | |
| 68 | static struct scomp_alg scomp = { |
| 69 | .streams = { |
| 70 | .alloc_ctx = lz4hc_alloc_ctx, |
| 71 | .free_ctx = lz4hc_free_ctx, |
| 72 | }, |
| 73 | .compress = lz4hc_scompress, |
| 74 | .decompress = lz4hc_sdecompress, |
| 75 | .base = { |
| 76 | .cra_name = "lz4hc" , |
| 77 | .cra_driver_name = "lz4hc-scomp" , |
| 78 | .cra_module = THIS_MODULE, |
| 79 | } |
| 80 | }; |
| 81 | |
| 82 | static int __init lz4hc_mod_init(void) |
| 83 | { |
| 84 | return crypto_register_scomp(alg: &scomp); |
| 85 | } |
| 86 | |
| 87 | static void __exit lz4hc_mod_fini(void) |
| 88 | { |
| 89 | crypto_unregister_scomp(alg: &scomp); |
| 90 | } |
| 91 | |
| 92 | module_init(lz4hc_mod_init); |
| 93 | module_exit(lz4hc_mod_fini); |
| 94 | |
| 95 | MODULE_LICENSE("GPL" ); |
| 96 | MODULE_DESCRIPTION("LZ4HC Compression Algorithm" ); |
| 97 | MODULE_ALIAS_CRYPTO("lz4hc" ); |
| 98 | |