entropy_common.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /* ******************************************************************
  2. * Common functions of New Generation Entropy library
  3. * Copyright (c) Yann Collet, Facebook, Inc.
  4. *
  5. * You can contact the author at :
  6. * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
  7. * - Public forum : https://groups.google.com/forum/#!forum/lz4c
  8. *
  9. * This source code is licensed under both the BSD-style license (found in the
  10. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  11. * in the COPYING file in the root directory of this source tree).
  12. * You may select, at your option, one of the above-listed licenses.
  13. ****************************************************************** */
  14. /* *************************************
  15. * Dependencies
  16. ***************************************/
  17. #include <linux/module.h>
  18. #include "mem.h"
  19. #include "error_private.h" /* ERR_*, ERROR */
  20. #define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
  21. #include "fse.h"
  22. #define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
  23. #include "huf.h"
  24. /*=== Version ===*/
  25. unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
  26. /*=== Error Management ===*/
  27. unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  28. const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
  29. unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  30. const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
  31. /*-**************************************************************
  32. * FSE NCount encoding-decoding
  33. ****************************************************************/
  34. static U32 FSE_ctz(U32 val)
  35. {
  36. assert(val != 0);
  37. {
  38. # if (__GNUC__ >= 3) /* GCC Intrinsic */
  39. return __builtin_ctz(val);
  40. # else /* Software version */
  41. U32 count = 0;
  42. while ((val & 1) == 0) {
  43. val >>= 1;
  44. ++count;
  45. }
  46. return count;
  47. # endif
  48. }
  49. }
  50. FORCE_INLINE_TEMPLATE
  51. size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  52. const void* headerBuffer, size_t hbSize)
  53. {
  54. const BYTE* const istart = (const BYTE*) headerBuffer;
  55. const BYTE* const iend = istart + hbSize;
  56. const BYTE* ip = istart;
  57. int nbBits;
  58. int remaining;
  59. int threshold;
  60. U32 bitStream;
  61. int bitCount;
  62. unsigned charnum = 0;
  63. unsigned const maxSV1 = *maxSVPtr + 1;
  64. int previous0 = 0;
  65. if (hbSize < 8) {
  66. /* This function only works when hbSize >= 8 */
  67. char buffer[8] = {0};
  68. ZSTD_memcpy(buffer, headerBuffer, hbSize);
  69. { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
  70. buffer, sizeof(buffer));
  71. if (FSE_isError(countSize)) return countSize;
  72. if (countSize > hbSize) return ERROR(corruption_detected);
  73. return countSize;
  74. } }
  75. assert(hbSize >= 8);
  76. /* init */
  77. ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
  78. bitStream = MEM_readLE32(ip);
  79. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  80. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  81. bitStream >>= 4;
  82. bitCount = 4;
  83. *tableLogPtr = nbBits;
  84. remaining = (1<<nbBits)+1;
  85. threshold = 1<<nbBits;
  86. nbBits++;
  87. for (;;) {
  88. if (previous0) {
  89. /* Count the number of repeats. Each time the
  90. * 2-bit repeat code is 0b11 there is another
  91. * repeat.
  92. * Avoid UB by setting the high bit to 1.
  93. */
  94. int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
  95. while (repeats >= 12) {
  96. charnum += 3 * 12;
  97. if (LIKELY(ip <= iend-7)) {
  98. ip += 3;
  99. } else {
  100. bitCount -= (int)(8 * (iend - 7 - ip));
  101. bitCount &= 31;
  102. ip = iend - 4;
  103. }
  104. bitStream = MEM_readLE32(ip) >> bitCount;
  105. repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
  106. }
  107. charnum += 3 * repeats;
  108. bitStream >>= 2 * repeats;
  109. bitCount += 2 * repeats;
  110. /* Add the final repeat which isn't 0b11. */
  111. assert((bitStream & 3) < 3);
  112. charnum += bitStream & 3;
  113. bitCount += 2;
  114. /* This is an error, but break and return an error
  115. * at the end, because returning out of a loop makes
  116. * it harder for the compiler to optimize.
  117. */
  118. if (charnum >= maxSV1) break;
  119. /* We don't need to set the normalized count to 0
  120. * because we already memset the whole buffer to 0.
  121. */
  122. if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  123. assert((bitCount >> 3) <= 3); /* For first condition to work */
  124. ip += bitCount>>3;
  125. bitCount &= 7;
  126. } else {
  127. bitCount -= (int)(8 * (iend - 4 - ip));
  128. bitCount &= 31;
  129. ip = iend - 4;
  130. }
  131. bitStream = MEM_readLE32(ip) >> bitCount;
  132. }
  133. {
  134. int const max = (2*threshold-1) - remaining;
  135. int count;
  136. if ((bitStream & (threshold-1)) < (U32)max) {
  137. count = bitStream & (threshold-1);
  138. bitCount += nbBits-1;
  139. } else {
  140. count = bitStream & (2*threshold-1);
  141. if (count >= threshold) count -= max;
  142. bitCount += nbBits;
  143. }
  144. count--; /* extra accuracy */
  145. /* When it matters (small blocks), this is a
  146. * predictable branch, because we don't use -1.
  147. */
  148. if (count >= 0) {
  149. remaining -= count;
  150. } else {
  151. assert(count == -1);
  152. remaining += count;
  153. }
  154. normalizedCounter[charnum++] = (short)count;
  155. previous0 = !count;
  156. assert(threshold > 1);
  157. if (remaining < threshold) {
  158. /* This branch can be folded into the
  159. * threshold update condition because we
  160. * know that threshold > 1.
  161. */
  162. if (remaining <= 1) break;
  163. nbBits = BIT_highbit32(remaining) + 1;
  164. threshold = 1 << (nbBits - 1);
  165. }
  166. if (charnum >= maxSV1) break;
  167. if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  168. ip += bitCount>>3;
  169. bitCount &= 7;
  170. } else {
  171. bitCount -= (int)(8 * (iend - 4 - ip));
  172. bitCount &= 31;
  173. ip = iend - 4;
  174. }
  175. bitStream = MEM_readLE32(ip) >> bitCount;
  176. } }
  177. if (remaining != 1) return ERROR(corruption_detected);
  178. /* Only possible when there are too many zeros. */
  179. if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
  180. if (bitCount > 32) return ERROR(corruption_detected);
  181. *maxSVPtr = charnum-1;
  182. ip += (bitCount+7)>>3;
  183. return ip-istart;
  184. }
  185. /* Avoids the FORCE_INLINE of the _body() function. */
  186. static size_t FSE_readNCount_body_default(
  187. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  188. const void* headerBuffer, size_t hbSize)
  189. {
  190. return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  191. }
  192. #if DYNAMIC_BMI2
  193. TARGET_ATTRIBUTE("bmi2") static size_t FSE_readNCount_body_bmi2(
  194. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  195. const void* headerBuffer, size_t hbSize)
  196. {
  197. return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  198. }
  199. #endif
  200. size_t FSE_readNCount_bmi2(
  201. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  202. const void* headerBuffer, size_t hbSize, int bmi2)
  203. {
  204. #if DYNAMIC_BMI2
  205. if (bmi2) {
  206. return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  207. }
  208. #endif
  209. (void)bmi2;
  210. return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
  211. }
  212. size_t FSE_readNCount(
  213. short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  214. const void* headerBuffer, size_t hbSize)
  215. {
  216. return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
  217. }
  218. EXPORT_SYMBOL_GPL(FSE_readNCount);
  219. /*! HUF_readStats() :
  220. Read compact Huffman tree, saved by HUF_writeCTable().
  221. `huffWeight` is destination buffer.
  222. `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
  223. @return : size read from `src` , or an error Code .
  224. Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
  225. */
  226. size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  227. U32* nbSymbolsPtr, U32* tableLogPtr,
  228. const void* src, size_t srcSize)
  229. {
  230. U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
  231. return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);
  232. }
  233. EXPORT_SYMBOL_GPL(HUF_readStats);
  234. FORCE_INLINE_TEMPLATE size_t
  235. HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  236. U32* nbSymbolsPtr, U32* tableLogPtr,
  237. const void* src, size_t srcSize,
  238. void* workSpace, size_t wkspSize,
  239. int bmi2)
  240. {
  241. U32 weightTotal;
  242. const BYTE* ip = (const BYTE*) src;
  243. size_t iSize;
  244. size_t oSize;
  245. if (!srcSize) return ERROR(srcSize_wrong);
  246. iSize = ip[0];
  247. /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
  248. if (iSize >= 128) { /* special header */
  249. oSize = iSize - 127;
  250. iSize = ((oSize+1)/2);
  251. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  252. if (oSize >= hwSize) return ERROR(corruption_detected);
  253. ip += 1;
  254. { U32 n;
  255. for (n=0; n<oSize; n+=2) {
  256. huffWeight[n] = ip[n/2] >> 4;
  257. huffWeight[n+1] = ip[n/2] & 15;
  258. } } }
  259. else { /* header compressed with FSE (normal case) */
  260. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  261. /* max (hwSize-1) values decoded, as last one is implied */
  262. oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
  263. if (FSE_isError(oSize)) return oSize;
  264. }
  265. /* collect weight stats */
  266. ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
  267. weightTotal = 0;
  268. { U32 n; for (n=0; n<oSize; n++) {
  269. if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  270. rankStats[huffWeight[n]]++;
  271. weightTotal += (1 << huffWeight[n]) >> 1;
  272. } }
  273. if (weightTotal == 0) return ERROR(corruption_detected);
  274. /* get last non-null symbol weight (implied, total must be 2^n) */
  275. { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
  276. if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
  277. *tableLogPtr = tableLog;
  278. /* determine last weight */
  279. { U32 const total = 1 << tableLog;
  280. U32 const rest = total - weightTotal;
  281. U32 const verif = 1 << BIT_highbit32(rest);
  282. U32 const lastWeight = BIT_highbit32(rest) + 1;
  283. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  284. huffWeight[oSize] = (BYTE)lastWeight;
  285. rankStats[lastWeight]++;
  286. } }
  287. /* check tree construction validity */
  288. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  289. /* results */
  290. *nbSymbolsPtr = (U32)(oSize+1);
  291. return iSize+1;
  292. }
  293. /* Avoids the FORCE_INLINE of the _body() function. */
  294. static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  295. U32* nbSymbolsPtr, U32* tableLogPtr,
  296. const void* src, size_t srcSize,
  297. void* workSpace, size_t wkspSize)
  298. {
  299. return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
  300. }
  301. #if DYNAMIC_BMI2
  302. static TARGET_ATTRIBUTE("bmi2") size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  303. U32* nbSymbolsPtr, U32* tableLogPtr,
  304. const void* src, size_t srcSize,
  305. void* workSpace, size_t wkspSize)
  306. {
  307. return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
  308. }
  309. #endif
  310. size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  311. U32* nbSymbolsPtr, U32* tableLogPtr,
  312. const void* src, size_t srcSize,
  313. void* workSpace, size_t wkspSize,
  314. int bmi2)
  315. {
  316. #if DYNAMIC_BMI2
  317. if (bmi2) {
  318. return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
  319. }
  320. #endif
  321. (void)bmi2;
  322. return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
  323. }
  324. EXPORT_SYMBOL_GPL(HUF_readStats_wksp);