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 struct lz4hc_ctx {
14 void *lz4hc_comp_mem;
15 };
16
lz4hc_alloc_ctx(void)17 static void *lz4hc_alloc_ctx(void)
18 {
19 void *ctx;
20
21 ctx = vmalloc(LZ4HC_MEM_COMPRESS);
22 if (!ctx)
23 return ERR_PTR(-ENOMEM);
24
25 return ctx;
26 }
27
lz4hc_free_ctx(void * ctx)28 static void lz4hc_free_ctx(void *ctx)
29 {
30 vfree(ctx);
31 }
32
__lz4hc_compress_crypto(const u8 * src,unsigned int slen,u8 * dst,unsigned int * dlen,void * ctx)33 static int __lz4hc_compress_crypto(const u8 *src, unsigned int slen,
34 u8 *dst, unsigned int *dlen, void *ctx)
35 {
36 int out_len = LZ4_compress_HC(src, dst, slen,
37 *dlen, LZ4HC_DEFAULT_CLEVEL, ctx);
38
39 if (!out_len)
40 return -EINVAL;
41
42 *dlen = out_len;
43 return 0;
44 }
45
lz4hc_scompress(struct crypto_scomp * tfm,const u8 * src,unsigned int slen,u8 * dst,unsigned int * dlen,void * ctx)46 static int lz4hc_scompress(struct crypto_scomp *tfm, const u8 *src,
47 unsigned int slen, u8 *dst, unsigned int *dlen,
48 void *ctx)
49 {
50 return __lz4hc_compress_crypto(src, slen, dst, dlen, ctx);
51 }
52
__lz4hc_decompress_crypto(const u8 * src,unsigned int slen,u8 * dst,unsigned int * dlen,void * ctx)53 static int __lz4hc_decompress_crypto(const u8 *src, unsigned int slen,
54 u8 *dst, unsigned int *dlen, void *ctx)
55 {
56 int out_len = LZ4_decompress_safe(src, dst, slen, *dlen);
57
58 if (out_len < 0)
59 return -EINVAL;
60
61 *dlen = out_len;
62 return 0;
63 }
64
lz4hc_sdecompress(struct crypto_scomp * tfm,const u8 * src,unsigned int slen,u8 * dst,unsigned int * dlen,void * ctx)65 static int lz4hc_sdecompress(struct crypto_scomp *tfm, const u8 *src,
66 unsigned int slen, u8 *dst, unsigned int *dlen,
67 void *ctx)
68 {
69 return __lz4hc_decompress_crypto(src, slen, dst, dlen, NULL);
70 }
71
72 static struct scomp_alg scomp = {
73 .alloc_ctx = lz4hc_alloc_ctx,
74 .free_ctx = lz4hc_free_ctx,
75 .compress = lz4hc_scompress,
76 .decompress = lz4hc_sdecompress,
77 .base = {
78 .cra_name = "lz4hc",
79 .cra_driver_name = "lz4hc-scomp",
80 .cra_module = THIS_MODULE,
81 }
82 };
83
lz4hc_mod_init(void)84 static int __init lz4hc_mod_init(void)
85 {
86 return crypto_register_scomp(&scomp);
87 }
88
lz4hc_mod_fini(void)89 static void __exit lz4hc_mod_fini(void)
90 {
91 crypto_unregister_scomp(&scomp);
92 }
93
94 subsys_initcall(lz4hc_mod_init);
95 module_exit(lz4hc_mod_fini);
96
97 MODULE_LICENSE("GPL");
98 MODULE_DESCRIPTION("LZ4HC Compression Algorithm");
99 MODULE_ALIAS_CRYPTO("lz4hc");
100