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