lz4.c 1.9 KB

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