compr.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * fs/logfs/compr.c - compression routines
  3. *
  4. * As should be obvious for Linux kernel code, license is GPLv2
  5. *
  6. * Copyright (c) 2005-2008 Joern Engel <joern@logfs.org>
  7. */
  8. #include "logfs.h"
  9. #include <linux/vmalloc.h>
  10. #include <linux/zlib.h>
  11. #define COMPR_LEVEL 3
  12. static DEFINE_MUTEX(compr_mutex);
  13. static struct z_stream_s stream;
  14. int logfs_compress(void *in, void *out, size_t inlen, size_t outlen)
  15. {
  16. int err, ret;
  17. ret = -EIO;
  18. mutex_lock(&compr_mutex);
  19. err = zlib_deflateInit(&stream, COMPR_LEVEL);
  20. if (err != Z_OK)
  21. goto error;
  22. stream.next_in = in;
  23. stream.avail_in = inlen;
  24. stream.total_in = 0;
  25. stream.next_out = out;
  26. stream.avail_out = outlen;
  27. stream.total_out = 0;
  28. err = zlib_deflate(&stream, Z_FINISH);
  29. if (err != Z_STREAM_END)
  30. goto error;
  31. err = zlib_deflateEnd(&stream);
  32. if (err != Z_OK)
  33. goto error;
  34. if (stream.total_out >= stream.total_in)
  35. goto error;
  36. ret = stream.total_out;
  37. error:
  38. mutex_unlock(&compr_mutex);
  39. return ret;
  40. }
  41. int logfs_uncompress(void *in, void *out, size_t inlen, size_t outlen)
  42. {
  43. int err, ret;
  44. ret = -EIO;
  45. mutex_lock(&compr_mutex);
  46. err = zlib_inflateInit(&stream);
  47. if (err != Z_OK)
  48. goto error;
  49. stream.next_in = in;
  50. stream.avail_in = inlen;
  51. stream.total_in = 0;
  52. stream.next_out = out;
  53. stream.avail_out = outlen;
  54. stream.total_out = 0;
  55. err = zlib_inflate(&stream, Z_FINISH);
  56. if (err != Z_STREAM_END)
  57. goto error;
  58. err = zlib_inflateEnd(&stream);
  59. if (err != Z_OK)
  60. goto error;
  61. ret = 0;
  62. error:
  63. mutex_unlock(&compr_mutex);
  64. return ret;
  65. }
  66. int __init logfs_compr_init(void)
  67. {
  68. size_t size = max(zlib_deflate_workspacesize(MAX_WBITS, MAX_MEM_LEVEL),
  69. zlib_inflate_workspacesize());
  70. stream.workspace = vmalloc(size);
  71. if (!stream.workspace)
  72. return -ENOMEM;
  73. return 0;
  74. }
  75. void logfs_compr_exit(void)
  76. {
  77. vfree(stream.workspace);
  78. }