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(-ENOMEM);
20 
21 	return ctx;
22 }
23 
24 static void lz4hc_free_ctx(void *ctx)
25 {
26 	vfree(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, slen,
33 		*dlen, LZ4HC_DEFAULT_CLEVEL, 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(src, dst, slen, *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 	.alloc_ctx		= lz4hc_alloc_ctx,
70 	.free_ctx		= lz4hc_free_ctx,
71 	.compress		= lz4hc_scompress,
72 	.decompress		= lz4hc_sdecompress,
73 	.base			= {
74 		.cra_name	= "lz4hc",
75 		.cra_driver_name = "lz4hc-scomp",
76 		.cra_module	 = THIS_MODULE,
77 	}
78 };
79 
80 static int __init lz4hc_mod_init(void)
81 {
82 	return crypto_register_scomp(&scomp);
83 }
84 
85 static void __exit lz4hc_mod_fini(void)
86 {
87 	crypto_unregister_scomp(&scomp);
88 }
89 
90 module_init(lz4hc_mod_init);
91 module_exit(lz4hc_mod_fini);
92 
93 MODULE_LICENSE("GPL");
94 MODULE_DESCRIPTION("LZ4HC Compression Algorithm");
95 MODULE_ALIAS_CRYPTO("lz4hc");
96