zstd_ldm.c 29 KB

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