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 8 #include <linux/init.h> 9 #include <linux/module.h> 10 #include <linux/crypto.h> 11 #include <linux/vmalloc.h> 12 #include <linux/lz4.h> 13 #include <crypto/internal/scompress.h> 14 15 static void *lz4_alloc_ctx(void) 16 { 17 void *ctx; 18 19 ctx = vmalloc(LZ4_MEM_COMPRESS); 20 if (!ctx) 21 return ERR_PTR(-ENOMEM); 22 23 return ctx; 24 } 25 26 static void lz4_free_ctx(void *ctx) 27 { 28 vfree(ctx); 29 } 30 31 static int __lz4_compress_crypto(const u8 *src, unsigned int slen, 32 u8 *dst, unsigned int *dlen, void *ctx) 33 { 34 int out_len = LZ4_compress_default(src, dst, 35 slen, *dlen, ctx); 36 37 if (!out_len) 38 return -EINVAL; 39 40 *dlen = out_len; 41 return 0; 42 } 43 44 static int lz4_scompress(struct crypto_scomp *tfm, const u8 *src, 45 unsigned int slen, u8 *dst, unsigned int *dlen, 46 void *ctx) 47 { 48 return __lz4_compress_crypto(src, slen, dst, dlen, ctx); 49 } 50 51 static int __lz4_decompress_crypto(const u8 *src, unsigned int slen, 52 u8 *dst, unsigned int *dlen, void *ctx) 53 { 54 int out_len = LZ4_decompress_safe(src, dst, slen, *dlen); 55 56 if (out_len < 0) 57 return -EINVAL; 58 59 *dlen = out_len; 60 return 0; 61 } 62 63 static int lz4_sdecompress(struct crypto_scomp *tfm, const u8 *src, 64 unsigned int slen, u8 *dst, unsigned int *dlen, 65 void *ctx) 66 { 67 return __lz4_decompress_crypto(src, slen, dst, dlen, NULL); 68 } 69 70 static struct scomp_alg scomp = { 71 .alloc_ctx = lz4_alloc_ctx, 72 .free_ctx = lz4_free_ctx, 73 .compress = lz4_scompress, 74 .decompress = lz4_sdecompress, 75 .base = { 76 .cra_name = "lz4", 77 .cra_driver_name = "lz4-scomp", 78 .cra_module = THIS_MODULE, 79 } 80 }; 81 82 static int __init lz4_mod_init(void) 83 { 84 return crypto_register_scomp(&scomp); 85 } 86 87 static void __exit lz4_mod_fini(void) 88 { 89 crypto_unregister_scomp(&scomp); 90 } 91 92 module_init(lz4_mod_init); 93 module_exit(lz4_mod_fini); 94 95 MODULE_LICENSE("GPL"); 96 MODULE_DESCRIPTION("LZ4 Compression Algorithm"); 97 MODULE_ALIAS_CRYPTO("lz4"); 98