zstd_ldm.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. // SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause
  2. /*
  3. * Copyright (c) Meta Platforms, Inc. and affiliates.
  4. * All rights reserved.
  5. *
  6. * This source code is licensed under both the BSD-style license (found in the
  7. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  8. * in the COPYING file in the root directory of this source tree).
  9. * You may select, at your option, one of the above-listed licenses.
  10. */
  11. #include "zstd_ldm.h"
  12. #include "../common/debug.h"
  13. #include <linux/xxhash.h>
  14. #include "zstd_fast.h" /* ZSTD_fillHashTable() */
  15. #include "zstd_double_fast.h" /* ZSTD_fillDoubleHashTable() */
  16. #include "zstd_ldm_geartab.h"
  17. #define LDM_BUCKET_SIZE_LOG 4
  18. #define LDM_MIN_MATCH_LENGTH 64
  19. #define LDM_HASH_RLOG 7
  20. typedef struct {
  21. U64 rolling;
  22. U64 stopMask;
  23. } ldmRollingHashState_t;
  24. /* ZSTD_ldm_gear_init():
  25. *
  26. * Initializes the rolling hash state such that it will honor the
  27. * settings in params. */
  28. static void ZSTD_ldm_gear_init(ldmRollingHashState_t* state, ldmParams_t const* params)
  29. {
  30. unsigned maxBitsInMask = MIN(params->minMatchLength, 64);
  31. unsigned hashRateLog = params->hashRateLog;
  32. state->rolling = ~(U32)0;
  33. /* The choice of the splitting criterion is subject to two conditions:
  34. * 1. it has to trigger on average every 2^(hashRateLog) bytes;
  35. * 2. ideally, it has to depend on a window of minMatchLength bytes.
  36. *
  37. * In the gear hash algorithm, bit n depends on the last n bytes;
  38. * so in order to obtain a good quality splitting criterion it is
  39. * preferable to use bits with high weight.
  40. *
  41. * To match condition 1 we use a mask with hashRateLog bits set
  42. * and, because of the previous remark, we make sure these bits
  43. * have the highest possible weight while still respecting
  44. * condition 2.
  45. */
  46. if (hashRateLog > 0 && hashRateLog <= maxBitsInMask) {
  47. state->stopMask = (((U64)1 << hashRateLog) - 1) << (maxBitsInMask - hashRateLog);
  48. } else {
  49. /* In this degenerate case we simply honor the hash rate. */
  50. state->stopMask = ((U64)1 << hashRateLog) - 1;
  51. }
  52. }
  53. /* ZSTD_ldm_gear_reset()
  54. * Feeds [data, data + minMatchLength) into the hash without registering any
  55. * splits. This effectively resets the hash state. This is used when skipping
  56. * over data, either at the beginning of a block, or skipping sections.
  57. */
  58. static void ZSTD_ldm_gear_reset(ldmRollingHashState_t* state,
  59. BYTE const* data, size_t minMatchLength)
  60. {
  61. U64 hash = state->rolling;
  62. size_t n = 0;
  63. #define GEAR_ITER_ONCE() do { \
  64. hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
  65. n += 1; \
  66. } while (0)
  67. while (n + 3 < minMatchLength) {
  68. GEAR_ITER_ONCE();
  69. GEAR_ITER_ONCE();
  70. GEAR_ITER_ONCE();
  71. GEAR_ITER_ONCE();
  72. }
  73. while (n < minMatchLength) {
  74. GEAR_ITER_ONCE();
  75. }
  76. #undef GEAR_ITER_ONCE
  77. }
  78. /* ZSTD_ldm_gear_feed():
  79. *
  80. * Registers in the splits array all the split points found in the first
  81. * size bytes following the data pointer. This function terminates when
  82. * either all the data has been processed or LDM_BATCH_SIZE splits are
  83. * present in the splits array.
  84. *
  85. * Precondition: The splits array must not be full.
  86. * Returns: The number of bytes processed. */
  87. static size_t ZSTD_ldm_gear_feed(ldmRollingHashState_t* state,
  88. BYTE const* data, size_t size,
  89. size_t* splits, unsigned* numSplits)
  90. {
  91. size_t n;
  92. U64 hash, mask;
  93. hash = state->rolling;
  94. mask = state->stopMask;
  95. n = 0;
  96. #define GEAR_ITER_ONCE() do { \
  97. hash = (hash << 1) + ZSTD_ldm_gearTab[data[n] & 0xff]; \
  98. n += 1; \
  99. if (UNLIKELY((hash & mask) == 0)) { \
  100. splits[*numSplits] = n; \
  101. *numSplits += 1; \
  102. if (*numSplits == LDM_BATCH_SIZE) \
  103. goto done; \
  104. } \
  105. } while (0)
  106. while (n + 3 < size) {
  107. GEAR_ITER_ONCE();
  108. GEAR_ITER_ONCE();
  109. GEAR_ITER_ONCE();
  110. GEAR_ITER_ONCE();
  111. }
  112. while (n < size) {
  113. GEAR_ITER_ONCE();
  114. }
  115. #undef GEAR_ITER_ONCE
  116. done:
  117. state->rolling = hash;
  118. return n;
  119. }
  120. void ZSTD_ldm_adjustParameters(ldmParams_t* params,
  121. const ZSTD_compressionParameters* cParams)
  122. {
  123. params->windowLog = cParams->windowLog;
  124. ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
  125. DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
  126. if (params->hashRateLog == 0) {
  127. if (params->hashLog > 0) {
  128. /* if params->hashLog is set, derive hashRateLog from it */
  129. assert(params->hashLog <= ZSTD_HASHLOG_MAX);
  130. if (params->windowLog > params->hashLog) {
  131. params->hashRateLog = params->windowLog - params->hashLog;
  132. }
  133. } else {
  134. assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
  135. /* mapping from [fast, rate7] to [btultra2, rate4] */
  136. params->hashRateLog = 7 - (cParams->strategy/3);
  137. }
  138. }
  139. if (params->hashLog == 0) {
  140. params->hashLog = BOUNDED(ZSTD_HASHLOG_MIN, params->windowLog - params->hashRateLog, ZSTD_HASHLOG_MAX);
  141. }
  142. if (params->minMatchLength == 0) {
  143. params->minMatchLength = LDM_MIN_MATCH_LENGTH;
  144. if (cParams->strategy >= ZSTD_btultra)
  145. params->minMatchLength /= 2;
  146. }
  147. if (params->bucketSizeLog==0) {
  148. assert(1 <= (int)cParams->strategy && (int)cParams->strategy <= 9);
  149. params->bucketSizeLog = BOUNDED(LDM_BUCKET_SIZE_LOG, (U32)cParams->strategy, ZSTD_LDM_BUCKETSIZELOG_MAX);
  150. }
  151. params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
  152. }
  153. size_t ZSTD_ldm_getTableSize(ldmParams_t params)
  154. {
  155. size_t const ldmHSize = ((size_t)1) << params.hashLog;
  156. size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
  157. size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
  158. size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
  159. + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
  160. return params.enableLdm == ZSTD_ps_enable ? totalSize : 0;
  161. }
  162. size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
  163. {
  164. return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
  165. }
  166. /* ZSTD_ldm_getBucket() :
  167. * Returns a pointer to the start of the bucket associated with hash. */
  168. static ldmEntry_t* ZSTD_ldm_getBucket(
  169. const ldmState_t* ldmState, size_t hash, U32 const bucketSizeLog)
  170. {
  171. return ldmState->hashTable + (hash << bucketSizeLog);
  172. }
  173. /* ZSTD_ldm_insertEntry() :
  174. * Insert the entry with corresponding hash into the hash table */
  175. static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
  176. size_t const hash, const ldmEntry_t entry,
  177. U32 const bucketSizeLog)
  178. {
  179. BYTE* const pOffset = ldmState->bucketOffsets + hash;
  180. unsigned const offset = *pOffset;
  181. *(ZSTD_ldm_getBucket(ldmState, hash, bucketSizeLog) + offset) = entry;
  182. *pOffset = (BYTE)((offset + 1) & ((1u << bucketSizeLog) - 1));
  183. }
  184. /* ZSTD_ldm_countBackwardsMatch() :
  185. * Returns the number of bytes that match backwards before pIn and pMatch.
  186. *
  187. * We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
  188. static size_t ZSTD_ldm_countBackwardsMatch(
  189. const BYTE* pIn, const BYTE* pAnchor,
  190. const BYTE* pMatch, const BYTE* pMatchBase)
  191. {
  192. size_t matchLength = 0;
  193. while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
  194. pIn--;
  195. pMatch--;
  196. matchLength++;
  197. }
  198. return matchLength;
  199. }
  200. /* ZSTD_ldm_countBackwardsMatch_2segments() :
  201. * Returns the number of bytes that match backwards from pMatch,
  202. * even with the backwards match spanning 2 different segments.
  203. *
  204. * On reaching `pMatchBase`, start counting from mEnd */
  205. static size_t ZSTD_ldm_countBackwardsMatch_2segments(
  206. const BYTE* pIn, const BYTE* pAnchor,
  207. const BYTE* pMatch, const BYTE* pMatchBase,
  208. const BYTE* pExtDictStart, const BYTE* pExtDictEnd)
  209. {
  210. size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
  211. if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
  212. /* If backwards match is entirely in the extDict or prefix, immediately return */
  213. return matchLength;
  214. }
  215. DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
  216. matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
  217. DEBUGLOG(7, "final backwards match length = %zu", matchLength);
  218. return matchLength;
  219. }
  220. /* ZSTD_ldm_fillFastTables() :
  221. *
  222. * Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
  223. * This is similar to ZSTD_loadDictionaryContent.
  224. *
  225. * The tables for the other strategies are filled within their
  226. * block compressors. */
  227. static size_t ZSTD_ldm_fillFastTables(ZSTD_MatchState_t* ms,
  228. void const* end)
  229. {
  230. const BYTE* const iend = (const BYTE*)end;
  231. switch(ms->cParams.strategy)
  232. {
  233. case ZSTD_fast:
  234. ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
  235. break;
  236. case ZSTD_dfast:
  237. #ifndef ZSTD_EXCLUDE_DFAST_BLOCK_COMPRESSOR
  238. ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
  239. #else
  240. assert(0); /* shouldn't be called: cparams should've been adjusted. */
  241. #endif
  242. break;
  243. case ZSTD_greedy:
  244. case ZSTD_lazy:
  245. case ZSTD_lazy2:
  246. case ZSTD_btlazy2:
  247. case ZSTD_btopt:
  248. case ZSTD_btultra:
  249. case ZSTD_btultra2:
  250. break;
  251. default:
  252. assert(0); /* not possible : not a valid strategy id */
  253. }
  254. return 0;
  255. }
  256. void ZSTD_ldm_fillHashTable(
  257. ldmState_t* ldmState, const BYTE* ip,
  258. const BYTE* iend, ldmParams_t const* params)
  259. {
  260. U32 const minMatchLength = params->minMatchLength;
  261. U32 const bucketSizeLog = params->bucketSizeLog;
  262. U32 const hBits = params->hashLog - bucketSizeLog;
  263. BYTE const* const base = ldmState->window.base;
  264. BYTE const* const istart = ip;
  265. ldmRollingHashState_t hashState;
  266. size_t* const splits = ldmState->splitIndices;
  267. unsigned numSplits;
  268. DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
  269. ZSTD_ldm_gear_init(&hashState, params);
  270. while (ip < iend) {
  271. size_t hashed;
  272. unsigned n;
  273. numSplits = 0;
  274. hashed = ZSTD_ldm_gear_feed(&hashState, ip, (size_t)(iend - ip), splits, &numSplits);
  275. for (n = 0; n < numSplits; n++) {
  276. if (ip + splits[n] >= istart + minMatchLength) {
  277. BYTE const* const split = ip + splits[n] - minMatchLength;
  278. U64 const xxhash = xxh64(split, minMatchLength, 0);
  279. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  280. ldmEntry_t entry;
  281. entry.offset = (U32)(split - base);
  282. entry.checksum = (U32)(xxhash >> 32);
  283. ZSTD_ldm_insertEntry(ldmState, hash, entry, params->bucketSizeLog);
  284. }
  285. }
  286. ip += hashed;
  287. }
  288. }
  289. /* ZSTD_ldm_limitTableUpdate() :
  290. *
  291. * Sets cctx->nextToUpdate to a position corresponding closer to anchor
  292. * if it is far way
  293. * (after a long match, only update tables a limited amount). */
  294. static void ZSTD_ldm_limitTableUpdate(ZSTD_MatchState_t* ms, const BYTE* anchor)
  295. {
  296. U32 const curr = (U32)(anchor - ms->window.base);
  297. if (curr > ms->nextToUpdate + 1024) {
  298. ms->nextToUpdate =
  299. curr - MIN(512, curr - ms->nextToUpdate - 1024);
  300. }
  301. }
  302. static
  303. ZSTD_ALLOW_POINTER_OVERFLOW_ATTR
  304. size_t ZSTD_ldm_generateSequences_internal(
  305. ldmState_t* ldmState, RawSeqStore_t* rawSeqStore,
  306. ldmParams_t const* params, void const* src, size_t srcSize)
  307. {
  308. /* LDM parameters */
  309. int const extDict = ZSTD_window_hasExtDict(ldmState->window);
  310. U32 const minMatchLength = params->minMatchLength;
  311. U32 const entsPerBucket = 1U << params->bucketSizeLog;
  312. U32 const hBits = params->hashLog - params->bucketSizeLog;
  313. /* Prefix and extDict parameters */
  314. U32 const dictLimit = ldmState->window.dictLimit;
  315. U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
  316. BYTE const* const base = ldmState->window.base;
  317. BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
  318. BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
  319. BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
  320. BYTE const* const lowPrefixPtr = base + dictLimit;
  321. /* Input bounds */
  322. BYTE const* const istart = (BYTE const*)src;
  323. BYTE const* const iend = istart + srcSize;
  324. BYTE const* const ilimit = iend - HASH_READ_SIZE;
  325. /* Input positions */
  326. BYTE const* anchor = istart;
  327. BYTE const* ip = istart;
  328. /* Rolling hash state */
  329. ldmRollingHashState_t hashState;
  330. /* Arrays for staged-processing */
  331. size_t* const splits = ldmState->splitIndices;
  332. ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
  333. unsigned numSplits;
  334. if (srcSize < minMatchLength)
  335. return iend - anchor;
  336. /* Initialize the rolling hash state with the first minMatchLength bytes */
  337. ZSTD_ldm_gear_init(&hashState, params);
  338. ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
  339. ip += minMatchLength;
  340. while (ip < ilimit) {
  341. size_t hashed;
  342. unsigned n;
  343. numSplits = 0;
  344. hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
  345. splits, &numSplits);
  346. for (n = 0; n < numSplits; n++) {
  347. BYTE const* const split = ip + splits[n] - minMatchLength;
  348. U64 const xxhash = xxh64(split, minMatchLength, 0);
  349. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  350. candidates[n].split = split;
  351. candidates[n].hash = hash;
  352. candidates[n].checksum = (U32)(xxhash >> 32);
  353. candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, params->bucketSizeLog);
  354. PREFETCH_L1(candidates[n].bucket);
  355. }
  356. for (n = 0; n < numSplits; n++) {
  357. size_t forwardMatchLength = 0, backwardMatchLength = 0,
  358. bestMatchLength = 0, mLength;
  359. U32 offset;
  360. BYTE const* const split = candidates[n].split;
  361. U32 const checksum = candidates[n].checksum;
  362. U32 const hash = candidates[n].hash;
  363. ldmEntry_t* const bucket = candidates[n].bucket;
  364. ldmEntry_t const* cur;
  365. ldmEntry_t const* bestEntry = NULL;
  366. ldmEntry_t newEntry;
  367. newEntry.offset = (U32)(split - base);
  368. newEntry.checksum = checksum;
  369. /* If a split point would generate a sequence overlapping with
  370. * the previous one, we merely register it in the hash table and
  371. * move on */
  372. if (split < anchor) {
  373. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
  374. continue;
  375. }
  376. for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
  377. size_t curForwardMatchLength, curBackwardMatchLength,
  378. curTotalMatchLength;
  379. if (cur->checksum != checksum || cur->offset <= lowestIndex) {
  380. continue;
  381. }
  382. if (extDict) {
  383. BYTE const* const curMatchBase =
  384. cur->offset < dictLimit ? dictBase : base;
  385. BYTE const* const pMatch = curMatchBase + cur->offset;
  386. BYTE const* const matchEnd =
  387. cur->offset < dictLimit ? dictEnd : iend;
  388. BYTE const* const lowMatchPtr =
  389. cur->offset < dictLimit ? dictStart : lowPrefixPtr;
  390. curForwardMatchLength =
  391. ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
  392. if (curForwardMatchLength < minMatchLength) {
  393. continue;
  394. }
  395. curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
  396. split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
  397. } else { /* !extDict */
  398. BYTE const* const pMatch = base + cur->offset;
  399. curForwardMatchLength = ZSTD_count(split, pMatch, iend);
  400. if (curForwardMatchLength < minMatchLength) {
  401. continue;
  402. }
  403. curBackwardMatchLength =
  404. ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
  405. }
  406. curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
  407. if (curTotalMatchLength > bestMatchLength) {
  408. bestMatchLength = curTotalMatchLength;
  409. forwardMatchLength = curForwardMatchLength;
  410. backwardMatchLength = curBackwardMatchLength;
  411. bestEntry = cur;
  412. }
  413. }
  414. /* No match found -- insert an entry into the hash table
  415. * and process the next candidate match */
  416. if (bestEntry == NULL) {
  417. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
  418. continue;
  419. }
  420. /* Match found */
  421. offset = (U32)(split - base) - bestEntry->offset;
  422. mLength = forwardMatchLength + backwardMatchLength;
  423. {
  424. rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
  425. /* Out of sequence storage */
  426. if (rawSeqStore->size == rawSeqStore->capacity)
  427. return ERROR(dstSize_tooSmall);
  428. seq->litLength = (U32)(split - backwardMatchLength - anchor);
  429. seq->matchLength = (U32)mLength;
  430. seq->offset = offset;
  431. rawSeqStore->size++;
  432. }
  433. /* Insert the current entry into the hash table --- it must be
  434. * done after the previous block to avoid clobbering bestEntry */
  435. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, params->bucketSizeLog);
  436. anchor = split + forwardMatchLength;
  437. /* If we find a match that ends after the data that we've hashed
  438. * then we have a repeating, overlapping, pattern. E.g. all zeros.
  439. * If one repetition of the pattern matches our `stopMask` then all
  440. * repetitions will. We don't need to insert them all into out table,
  441. * only the first one. So skip over overlapping matches.
  442. * This is a major speed boost (20x) for compressing a single byte
  443. * repeated, when that byte ends up in the table.
  444. */
  445. if (anchor > ip + hashed) {
  446. ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
  447. /* Continue the outer loop at anchor (ip + hashed == anchor). */
  448. ip = anchor - hashed;
  449. break;
  450. }
  451. }
  452. ip += hashed;
  453. }
  454. return iend - anchor;
  455. }
  456. /*! ZSTD_ldm_reduceTable() :
  457. * reduce table indexes by `reducerValue` */
  458. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  459. U32 const reducerValue)
  460. {
  461. U32 u;
  462. for (u = 0; u < size; u++) {
  463. if (table[u].offset < reducerValue) table[u].offset = 0;
  464. else table[u].offset -= reducerValue;
  465. }
  466. }
  467. size_t ZSTD_ldm_generateSequences(
  468. ldmState_t* ldmState, RawSeqStore_t* sequences,
  469. ldmParams_t const* params, void const* src, size_t srcSize)
  470. {
  471. U32 const maxDist = 1U << params->windowLog;
  472. BYTE const* const istart = (BYTE const*)src;
  473. BYTE const* const iend = istart + srcSize;
  474. size_t const kMaxChunkSize = 1 << 20;
  475. size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
  476. size_t chunk;
  477. size_t leftoverSize = 0;
  478. assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
  479. /* Check that ZSTD_window_update() has been called for this chunk prior
  480. * to passing it to this function.
  481. */
  482. assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
  483. /* The input could be very large (in zstdmt), so it must be broken up into
  484. * chunks to enforce the maximum distance and handle overflow correction.
  485. */
  486. assert(sequences->pos <= sequences->size);
  487. assert(sequences->size <= sequences->capacity);
  488. for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
  489. BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
  490. size_t const remaining = (size_t)(iend - chunkStart);
  491. BYTE const *const chunkEnd =
  492. (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
  493. size_t const chunkSize = chunkEnd - chunkStart;
  494. size_t newLeftoverSize;
  495. size_t const prevSize = sequences->size;
  496. assert(chunkStart < iend);
  497. /* 1. Perform overflow correction if necessary. */
  498. if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
  499. U32 const ldmHSize = 1U << params->hashLog;
  500. U32 const correction = ZSTD_window_correctOverflow(
  501. &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
  502. ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
  503. /* invalidate dictionaries on overflow correction */
  504. ldmState->loadedDictEnd = 0;
  505. }
  506. /* 2. We enforce the maximum offset allowed.
  507. *
  508. * kMaxChunkSize should be small enough that we don't lose too much of
  509. * the window through early invalidation.
  510. * TODO: * Test the chunk size.
  511. * * Try invalidation after the sequence generation and test the
  512. * offset against maxDist directly.
  513. *
  514. * NOTE: Because of dictionaries + sequence splitting we MUST make sure
  515. * that any offset used is valid at the END of the sequence, since it may
  516. * be split into two sequences. This condition holds when using
  517. * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
  518. * against maxDist directly, we'll have to carefully handle that case.
  519. */
  520. ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
  521. /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
  522. newLeftoverSize = ZSTD_ldm_generateSequences_internal(
  523. ldmState, sequences, params, chunkStart, chunkSize);
  524. if (ZSTD_isError(newLeftoverSize))
  525. return newLeftoverSize;
  526. /* 4. We add the leftover literals from previous iterations to the first
  527. * newly generated sequence, or add the `newLeftoverSize` if none are
  528. * generated.
  529. */
  530. /* Prepend the leftover literals from the last call */
  531. if (prevSize < sequences->size) {
  532. sequences->seq[prevSize].litLength += (U32)leftoverSize;
  533. leftoverSize = newLeftoverSize;
  534. } else {
  535. assert(newLeftoverSize == chunkSize);
  536. leftoverSize += chunkSize;
  537. }
  538. }
  539. return 0;
  540. }
  541. void
  542. ZSTD_ldm_skipSequences(RawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch)
  543. {
  544. while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
  545. rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
  546. if (srcSize <= seq->litLength) {
  547. /* Skip past srcSize literals */
  548. seq->litLength -= (U32)srcSize;
  549. return;
  550. }
  551. srcSize -= seq->litLength;
  552. seq->litLength = 0;
  553. if (srcSize < seq->matchLength) {
  554. /* Skip past the first srcSize of the match */
  555. seq->matchLength -= (U32)srcSize;
  556. if (seq->matchLength < minMatch) {
  557. /* The match is too short, omit it */
  558. if (rawSeqStore->pos + 1 < rawSeqStore->size) {
  559. seq[1].litLength += seq[0].matchLength;
  560. }
  561. rawSeqStore->pos++;
  562. }
  563. return;
  564. }
  565. srcSize -= seq->matchLength;
  566. seq->matchLength = 0;
  567. rawSeqStore->pos++;
  568. }
  569. }
  570. /*
  571. * If the sequence length is longer than remaining then the sequence is split
  572. * between this block and the next.
  573. *
  574. * Returns the current sequence to handle, or if the rest of the block should
  575. * be literals, it returns a sequence with offset == 0.
  576. */
  577. static rawSeq maybeSplitSequence(RawSeqStore_t* rawSeqStore,
  578. U32 const remaining, U32 const minMatch)
  579. {
  580. rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
  581. assert(sequence.offset > 0);
  582. /* Likely: No partial sequence */
  583. if (remaining >= sequence.litLength + sequence.matchLength) {
  584. rawSeqStore->pos++;
  585. return sequence;
  586. }
  587. /* Cut the sequence short (offset == 0 ==> rest is literals). */
  588. if (remaining <= sequence.litLength) {
  589. sequence.offset = 0;
  590. } else if (remaining < sequence.litLength + sequence.matchLength) {
  591. sequence.matchLength = remaining - sequence.litLength;
  592. if (sequence.matchLength < minMatch) {
  593. sequence.offset = 0;
  594. }
  595. }
  596. /* Skip past `remaining` bytes for the future sequences. */
  597. ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
  598. return sequence;
  599. }
  600. void ZSTD_ldm_skipRawSeqStoreBytes(RawSeqStore_t* rawSeqStore, size_t nbBytes) {
  601. U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
  602. while (currPos && rawSeqStore->pos < rawSeqStore->size) {
  603. rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
  604. if (currPos >= currSeq.litLength + currSeq.matchLength) {
  605. currPos -= currSeq.litLength + currSeq.matchLength;
  606. rawSeqStore->pos++;
  607. } else {
  608. rawSeqStore->posInSequence = currPos;
  609. break;
  610. }
  611. }
  612. if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
  613. rawSeqStore->posInSequence = 0;
  614. }
  615. }
  616. size_t ZSTD_ldm_blockCompress(RawSeqStore_t* rawSeqStore,
  617. ZSTD_MatchState_t* ms, SeqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  618. ZSTD_ParamSwitch_e useRowMatchFinder,
  619. void const* src, size_t srcSize)
  620. {
  621. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  622. unsigned const minMatch = cParams->minMatch;
  623. ZSTD_BlockCompressor_f const blockCompressor =
  624. ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
  625. /* Input bounds */
  626. BYTE const* const istart = (BYTE const*)src;
  627. BYTE const* const iend = istart + srcSize;
  628. /* Input positions */
  629. BYTE const* ip = istart;
  630. DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
  631. /* If using opt parser, use LDMs only as candidates rather than always accepting them */
  632. if (cParams->strategy >= ZSTD_btopt) {
  633. size_t lastLLSize;
  634. ms->ldmSeqStore = rawSeqStore;
  635. lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
  636. ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
  637. return lastLLSize;
  638. }
  639. assert(rawSeqStore->pos <= rawSeqStore->size);
  640. assert(rawSeqStore->size <= rawSeqStore->capacity);
  641. /* Loop through each sequence and apply the block compressor to the literals */
  642. while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
  643. /* maybeSplitSequence updates rawSeqStore->pos */
  644. rawSeq const sequence = maybeSplitSequence(rawSeqStore,
  645. (U32)(iend - ip), minMatch);
  646. /* End signal */
  647. if (sequence.offset == 0)
  648. break;
  649. assert(ip + sequence.litLength + sequence.matchLength <= iend);
  650. /* Fill tables for block compressor */
  651. ZSTD_ldm_limitTableUpdate(ms, ip);
  652. ZSTD_ldm_fillFastTables(ms, ip);
  653. /* Run the block compressor */
  654. DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
  655. {
  656. int i;
  657. size_t const newLitLength =
  658. blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
  659. ip += sequence.litLength;
  660. /* Update the repcodes */
  661. for (i = ZSTD_REP_NUM - 1; i > 0; i--)
  662. rep[i] = rep[i-1];
  663. rep[0] = sequence.offset;
  664. /* Store the sequence */
  665. ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
  666. OFFSET_TO_OFFBASE(sequence.offset),
  667. sequence.matchLength);
  668. ip += sequence.matchLength;
  669. }
  670. }
  671. /* Fill the tables for the block compressor */
  672. ZSTD_ldm_limitTableUpdate(ms, ip);
  673. ZSTD_ldm_fillFastTables(ms, ip);
  674. /* Compress the last literals */
  675. return blockCompressor(ms, seqStore, rep, ip, iend - ip);
  676. }