You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

zstd_ldm.c 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 "debug.h"
  12. #include "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 3
  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. ZSTD_compressionParameters const* 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->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG;
  126. if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH;
  127. if (params->hashLog == 0) {
  128. params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG);
  129. assert(params->hashLog <= ZSTD_HASHLOG_MAX);
  130. }
  131. if (params->hashRateLog == 0) {
  132. params->hashRateLog = params->windowLog < params->hashLog
  133. ? 0
  134. : params->windowLog - params->hashLog;
  135. }
  136. params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
  137. }
  138. size_t ZSTD_ldm_getTableSize(ldmParams_t params)
  139. {
  140. size_t const ldmHSize = ((size_t)1) << params.hashLog;
  141. size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
  142. size_t const ldmBucketSize = ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
  143. size_t const totalSize = ZSTD_cwksp_alloc_size(ldmBucketSize)
  144. + ZSTD_cwksp_alloc_size(ldmHSize * sizeof(ldmEntry_t));
  145. return params.enableLdm == ZSTD_ps_enable ? totalSize : 0;
  146. }
  147. size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
  148. {
  149. return params.enableLdm == ZSTD_ps_enable ? (maxChunkSize / params.minMatchLength) : 0;
  150. }
  151. /** ZSTD_ldm_getBucket() :
  152. * Returns a pointer to the start of the bucket associated with hash. */
  153. static ldmEntry_t* ZSTD_ldm_getBucket(
  154. ldmState_t* ldmState, size_t hash, ldmParams_t const ldmParams)
  155. {
  156. return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
  157. }
  158. /** ZSTD_ldm_insertEntry() :
  159. * Insert the entry with corresponding hash into the hash table */
  160. static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
  161. size_t const hash, const ldmEntry_t entry,
  162. ldmParams_t const ldmParams)
  163. {
  164. BYTE* const pOffset = ldmState->bucketOffsets + hash;
  165. unsigned const offset = *pOffset;
  166. *(ZSTD_ldm_getBucket(ldmState, hash, ldmParams) + offset) = entry;
  167. *pOffset = (BYTE)((offset + 1) & ((1u << ldmParams.bucketSizeLog) - 1));
  168. }
  169. /** ZSTD_ldm_countBackwardsMatch() :
  170. * Returns the number of bytes that match backwards before pIn and pMatch.
  171. *
  172. * We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
  173. static size_t ZSTD_ldm_countBackwardsMatch(
  174. const BYTE* pIn, const BYTE* pAnchor,
  175. const BYTE* pMatch, const BYTE* pMatchBase)
  176. {
  177. size_t matchLength = 0;
  178. while (pIn > pAnchor && pMatch > pMatchBase && pIn[-1] == pMatch[-1]) {
  179. pIn--;
  180. pMatch--;
  181. matchLength++;
  182. }
  183. return matchLength;
  184. }
  185. /** ZSTD_ldm_countBackwardsMatch_2segments() :
  186. * Returns the number of bytes that match backwards from pMatch,
  187. * even with the backwards match spanning 2 different segments.
  188. *
  189. * On reaching `pMatchBase`, start counting from mEnd */
  190. static size_t ZSTD_ldm_countBackwardsMatch_2segments(
  191. const BYTE* pIn, const BYTE* pAnchor,
  192. const BYTE* pMatch, const BYTE* pMatchBase,
  193. const BYTE* pExtDictStart, const BYTE* pExtDictEnd)
  194. {
  195. size_t matchLength = ZSTD_ldm_countBackwardsMatch(pIn, pAnchor, pMatch, pMatchBase);
  196. if (pMatch - matchLength != pMatchBase || pMatchBase == pExtDictStart) {
  197. /* If backwards match is entirely in the extDict or prefix, immediately return */
  198. return matchLength;
  199. }
  200. DEBUGLOG(7, "ZSTD_ldm_countBackwardsMatch_2segments: found 2-parts backwards match (length in prefix==%zu)", matchLength);
  201. matchLength += ZSTD_ldm_countBackwardsMatch(pIn - matchLength, pAnchor, pExtDictEnd, pExtDictStart);
  202. DEBUGLOG(7, "final backwards match length = %zu", matchLength);
  203. return matchLength;
  204. }
  205. /** ZSTD_ldm_fillFastTables() :
  206. *
  207. * Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
  208. * This is similar to ZSTD_loadDictionaryContent.
  209. *
  210. * The tables for the other strategies are filled within their
  211. * block compressors. */
  212. static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms,
  213. void const* end)
  214. {
  215. const BYTE* const iend = (const BYTE*)end;
  216. switch(ms->cParams.strategy)
  217. {
  218. case ZSTD_fast:
  219. ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
  220. break;
  221. case ZSTD_dfast:
  222. ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast, ZSTD_tfp_forCCtx);
  223. break;
  224. case ZSTD_greedy:
  225. case ZSTD_lazy:
  226. case ZSTD_lazy2:
  227. case ZSTD_btlazy2:
  228. case ZSTD_btopt:
  229. case ZSTD_btultra:
  230. case ZSTD_btultra2:
  231. break;
  232. default:
  233. assert(0); /* not possible : not a valid strategy id */
  234. }
  235. return 0;
  236. }
  237. void ZSTD_ldm_fillHashTable(
  238. ldmState_t* ldmState, const BYTE* ip,
  239. const BYTE* iend, ldmParams_t const* params)
  240. {
  241. U32 const minMatchLength = params->minMatchLength;
  242. U32 const hBits = params->hashLog - params->bucketSizeLog;
  243. BYTE const* const base = ldmState->window.base;
  244. BYTE const* const istart = ip;
  245. ldmRollingHashState_t hashState;
  246. size_t* const splits = ldmState->splitIndices;
  247. unsigned numSplits;
  248. DEBUGLOG(5, "ZSTD_ldm_fillHashTable");
  249. ZSTD_ldm_gear_init(&hashState, params);
  250. while (ip < iend) {
  251. size_t hashed;
  252. unsigned n;
  253. numSplits = 0;
  254. hashed = ZSTD_ldm_gear_feed(&hashState, ip, iend - ip, splits, &numSplits);
  255. for (n = 0; n < numSplits; n++) {
  256. if (ip + splits[n] >= istart + minMatchLength) {
  257. BYTE const* const split = ip + splits[n] - minMatchLength;
  258. U64 const xxhash = XXH64(split, minMatchLength, 0);
  259. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  260. ldmEntry_t entry;
  261. entry.offset = (U32)(split - base);
  262. entry.checksum = (U32)(xxhash >> 32);
  263. ZSTD_ldm_insertEntry(ldmState, hash, entry, *params);
  264. }
  265. }
  266. ip += hashed;
  267. }
  268. }
  269. /** ZSTD_ldm_limitTableUpdate() :
  270. *
  271. * Sets cctx->nextToUpdate to a position corresponding closer to anchor
  272. * if it is far way
  273. * (after a long match, only update tables a limited amount). */
  274. static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor)
  275. {
  276. U32 const curr = (U32)(anchor - ms->window.base);
  277. if (curr > ms->nextToUpdate + 1024) {
  278. ms->nextToUpdate =
  279. curr - MIN(512, curr - ms->nextToUpdate - 1024);
  280. }
  281. }
  282. static size_t ZSTD_ldm_generateSequences_internal(
  283. ldmState_t* ldmState, rawSeqStore_t* rawSeqStore,
  284. ldmParams_t const* params, void const* src, size_t srcSize)
  285. {
  286. /* LDM parameters */
  287. int const extDict = ZSTD_window_hasExtDict(ldmState->window);
  288. U32 const minMatchLength = params->minMatchLength;
  289. U32 const entsPerBucket = 1U << params->bucketSizeLog;
  290. U32 const hBits = params->hashLog - params->bucketSizeLog;
  291. /* Prefix and extDict parameters */
  292. U32 const dictLimit = ldmState->window.dictLimit;
  293. U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
  294. BYTE const* const base = ldmState->window.base;
  295. BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
  296. BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
  297. BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
  298. BYTE const* const lowPrefixPtr = base + dictLimit;
  299. /* Input bounds */
  300. BYTE const* const istart = (BYTE const*)src;
  301. BYTE const* const iend = istart + srcSize;
  302. BYTE const* const ilimit = iend - HASH_READ_SIZE;
  303. /* Input positions */
  304. BYTE const* anchor = istart;
  305. BYTE const* ip = istart;
  306. /* Rolling hash state */
  307. ldmRollingHashState_t hashState;
  308. /* Arrays for staged-processing */
  309. size_t* const splits = ldmState->splitIndices;
  310. ldmMatchCandidate_t* const candidates = ldmState->matchCandidates;
  311. unsigned numSplits;
  312. if (srcSize < minMatchLength)
  313. return iend - anchor;
  314. /* Initialize the rolling hash state with the first minMatchLength bytes */
  315. ZSTD_ldm_gear_init(&hashState, params);
  316. ZSTD_ldm_gear_reset(&hashState, ip, minMatchLength);
  317. ip += minMatchLength;
  318. while (ip < ilimit) {
  319. size_t hashed;
  320. unsigned n;
  321. numSplits = 0;
  322. hashed = ZSTD_ldm_gear_feed(&hashState, ip, ilimit - ip,
  323. splits, &numSplits);
  324. for (n = 0; n < numSplits; n++) {
  325. BYTE const* const split = ip + splits[n] - minMatchLength;
  326. U64 const xxhash = XXH64(split, minMatchLength, 0);
  327. U32 const hash = (U32)(xxhash & (((U32)1 << hBits) - 1));
  328. candidates[n].split = split;
  329. candidates[n].hash = hash;
  330. candidates[n].checksum = (U32)(xxhash >> 32);
  331. candidates[n].bucket = ZSTD_ldm_getBucket(ldmState, hash, *params);
  332. PREFETCH_L1(candidates[n].bucket);
  333. }
  334. for (n = 0; n < numSplits; n++) {
  335. size_t forwardMatchLength = 0, backwardMatchLength = 0,
  336. bestMatchLength = 0, mLength;
  337. U32 offset;
  338. BYTE const* const split = candidates[n].split;
  339. U32 const checksum = candidates[n].checksum;
  340. U32 const hash = candidates[n].hash;
  341. ldmEntry_t* const bucket = candidates[n].bucket;
  342. ldmEntry_t const* cur;
  343. ldmEntry_t const* bestEntry = NULL;
  344. ldmEntry_t newEntry;
  345. newEntry.offset = (U32)(split - base);
  346. newEntry.checksum = checksum;
  347. /* If a split point would generate a sequence overlapping with
  348. * the previous one, we merely register it in the hash table and
  349. * move on */
  350. if (split < anchor) {
  351. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  352. continue;
  353. }
  354. for (cur = bucket; cur < bucket + entsPerBucket; cur++) {
  355. size_t curForwardMatchLength, curBackwardMatchLength,
  356. curTotalMatchLength;
  357. if (cur->checksum != checksum || cur->offset <= lowestIndex) {
  358. continue;
  359. }
  360. if (extDict) {
  361. BYTE const* const curMatchBase =
  362. cur->offset < dictLimit ? dictBase : base;
  363. BYTE const* const pMatch = curMatchBase + cur->offset;
  364. BYTE const* const matchEnd =
  365. cur->offset < dictLimit ? dictEnd : iend;
  366. BYTE const* const lowMatchPtr =
  367. cur->offset < dictLimit ? dictStart : lowPrefixPtr;
  368. curForwardMatchLength =
  369. ZSTD_count_2segments(split, pMatch, iend, matchEnd, lowPrefixPtr);
  370. if (curForwardMatchLength < minMatchLength) {
  371. continue;
  372. }
  373. curBackwardMatchLength = ZSTD_ldm_countBackwardsMatch_2segments(
  374. split, anchor, pMatch, lowMatchPtr, dictStart, dictEnd);
  375. } else { /* !extDict */
  376. BYTE const* const pMatch = base + cur->offset;
  377. curForwardMatchLength = ZSTD_count(split, pMatch, iend);
  378. if (curForwardMatchLength < minMatchLength) {
  379. continue;
  380. }
  381. curBackwardMatchLength =
  382. ZSTD_ldm_countBackwardsMatch(split, anchor, pMatch, lowPrefixPtr);
  383. }
  384. curTotalMatchLength = curForwardMatchLength + curBackwardMatchLength;
  385. if (curTotalMatchLength > bestMatchLength) {
  386. bestMatchLength = curTotalMatchLength;
  387. forwardMatchLength = curForwardMatchLength;
  388. backwardMatchLength = curBackwardMatchLength;
  389. bestEntry = cur;
  390. }
  391. }
  392. /* No match found -- insert an entry into the hash table
  393. * and process the next candidate match */
  394. if (bestEntry == NULL) {
  395. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  396. continue;
  397. }
  398. /* Match found */
  399. offset = (U32)(split - base) - bestEntry->offset;
  400. mLength = forwardMatchLength + backwardMatchLength;
  401. {
  402. rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
  403. /* Out of sequence storage */
  404. if (rawSeqStore->size == rawSeqStore->capacity)
  405. return ERROR(dstSize_tooSmall);
  406. seq->litLength = (U32)(split - backwardMatchLength - anchor);
  407. seq->matchLength = (U32)mLength;
  408. seq->offset = offset;
  409. rawSeqStore->size++;
  410. }
  411. /* Insert the current entry into the hash table --- it must be
  412. * done after the previous block to avoid clobbering bestEntry */
  413. ZSTD_ldm_insertEntry(ldmState, hash, newEntry, *params);
  414. anchor = split + forwardMatchLength;
  415. /* If we find a match that ends after the data that we've hashed
  416. * then we have a repeating, overlapping, pattern. E.g. all zeros.
  417. * If one repetition of the pattern matches our `stopMask` then all
  418. * repetitions will. We don't need to insert them all into out table,
  419. * only the first one. So skip over overlapping matches.
  420. * This is a major speed boost (20x) for compressing a single byte
  421. * repeated, when that byte ends up in the table.
  422. */
  423. if (anchor > ip + hashed) {
  424. ZSTD_ldm_gear_reset(&hashState, anchor - minMatchLength, minMatchLength);
  425. /* Continue the outer loop at anchor (ip + hashed == anchor). */
  426. ip = anchor - hashed;
  427. break;
  428. }
  429. }
  430. ip += hashed;
  431. }
  432. return iend - anchor;
  433. }
  434. /*! ZSTD_ldm_reduceTable() :
  435. * reduce table indexes by `reducerValue` */
  436. static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
  437. U32 const reducerValue)
  438. {
  439. U32 u;
  440. for (u = 0; u < size; u++) {
  441. if (table[u].offset < reducerValue) table[u].offset = 0;
  442. else table[u].offset -= reducerValue;
  443. }
  444. }
  445. size_t ZSTD_ldm_generateSequences(
  446. ldmState_t* ldmState, rawSeqStore_t* sequences,
  447. ldmParams_t const* params, void const* src, size_t srcSize)
  448. {
  449. U32 const maxDist = 1U << params->windowLog;
  450. BYTE const* const istart = (BYTE const*)src;
  451. BYTE const* const iend = istart + srcSize;
  452. size_t const kMaxChunkSize = 1 << 20;
  453. size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
  454. size_t chunk;
  455. size_t leftoverSize = 0;
  456. assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
  457. /* Check that ZSTD_window_update() has been called for this chunk prior
  458. * to passing it to this function.
  459. */
  460. assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
  461. /* The input could be very large (in zstdmt), so it must be broken up into
  462. * chunks to enforce the maximum distance and handle overflow correction.
  463. */
  464. assert(sequences->pos <= sequences->size);
  465. assert(sequences->size <= sequences->capacity);
  466. for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
  467. BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
  468. size_t const remaining = (size_t)(iend - chunkStart);
  469. BYTE const *const chunkEnd =
  470. (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
  471. size_t const chunkSize = chunkEnd - chunkStart;
  472. size_t newLeftoverSize;
  473. size_t const prevSize = sequences->size;
  474. assert(chunkStart < iend);
  475. /* 1. Perform overflow correction if necessary. */
  476. if (ZSTD_window_needOverflowCorrection(ldmState->window, 0, maxDist, ldmState->loadedDictEnd, chunkStart, chunkEnd)) {
  477. U32 const ldmHSize = 1U << params->hashLog;
  478. U32 const correction = ZSTD_window_correctOverflow(
  479. &ldmState->window, /* cycleLog */ 0, maxDist, chunkStart);
  480. ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
  481. /* invalidate dictionaries on overflow correction */
  482. ldmState->loadedDictEnd = 0;
  483. }
  484. /* 2. We enforce the maximum offset allowed.
  485. *
  486. * kMaxChunkSize should be small enough that we don't lose too much of
  487. * the window through early invalidation.
  488. * TODO: * Test the chunk size.
  489. * * Try invalidation after the sequence generation and test the
  490. * offset against maxDist directly.
  491. *
  492. * NOTE: Because of dictionaries + sequence splitting we MUST make sure
  493. * that any offset used is valid at the END of the sequence, since it may
  494. * be split into two sequences. This condition holds when using
  495. * ZSTD_window_enforceMaxDist(), but if we move to checking offsets
  496. * against maxDist directly, we'll have to carefully handle that case.
  497. */
  498. ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, &ldmState->loadedDictEnd, NULL);
  499. /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
  500. newLeftoverSize = ZSTD_ldm_generateSequences_internal(
  501. ldmState, sequences, params, chunkStart, chunkSize);
  502. if (ZSTD_isError(newLeftoverSize))
  503. return newLeftoverSize;
  504. /* 4. We add the leftover literals from previous iterations to the first
  505. * newly generated sequence, or add the `newLeftoverSize` if none are
  506. * generated.
  507. */
  508. /* Prepend the leftover literals from the last call */
  509. if (prevSize < sequences->size) {
  510. sequences->seq[prevSize].litLength += (U32)leftoverSize;
  511. leftoverSize = newLeftoverSize;
  512. } else {
  513. assert(newLeftoverSize == chunkSize);
  514. leftoverSize += chunkSize;
  515. }
  516. }
  517. return 0;
  518. }
  519. void
  520. ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch)
  521. {
  522. while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
  523. rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
  524. if (srcSize <= seq->litLength) {
  525. /* Skip past srcSize literals */
  526. seq->litLength -= (U32)srcSize;
  527. return;
  528. }
  529. srcSize -= seq->litLength;
  530. seq->litLength = 0;
  531. if (srcSize < seq->matchLength) {
  532. /* Skip past the first srcSize of the match */
  533. seq->matchLength -= (U32)srcSize;
  534. if (seq->matchLength < minMatch) {
  535. /* The match is too short, omit it */
  536. if (rawSeqStore->pos + 1 < rawSeqStore->size) {
  537. seq[1].litLength += seq[0].matchLength;
  538. }
  539. rawSeqStore->pos++;
  540. }
  541. return;
  542. }
  543. srcSize -= seq->matchLength;
  544. seq->matchLength = 0;
  545. rawSeqStore->pos++;
  546. }
  547. }
  548. /**
  549. * If the sequence length is longer than remaining then the sequence is split
  550. * between this block and the next.
  551. *
  552. * Returns the current sequence to handle, or if the rest of the block should
  553. * be literals, it returns a sequence with offset == 0.
  554. */
  555. static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore,
  556. U32 const remaining, U32 const minMatch)
  557. {
  558. rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
  559. assert(sequence.offset > 0);
  560. /* Likely: No partial sequence */
  561. if (remaining >= sequence.litLength + sequence.matchLength) {
  562. rawSeqStore->pos++;
  563. return sequence;
  564. }
  565. /* Cut the sequence short (offset == 0 ==> rest is literals). */
  566. if (remaining <= sequence.litLength) {
  567. sequence.offset = 0;
  568. } else if (remaining < sequence.litLength + sequence.matchLength) {
  569. sequence.matchLength = remaining - sequence.litLength;
  570. if (sequence.matchLength < minMatch) {
  571. sequence.offset = 0;
  572. }
  573. }
  574. /* Skip past `remaining` bytes for the future sequences. */
  575. ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
  576. return sequence;
  577. }
  578. void ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes) {
  579. U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);
  580. while (currPos && rawSeqStore->pos < rawSeqStore->size) {
  581. rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];
  582. if (currPos >= currSeq.litLength + currSeq.matchLength) {
  583. currPos -= currSeq.litLength + currSeq.matchLength;
  584. rawSeqStore->pos++;
  585. } else {
  586. rawSeqStore->posInSequence = currPos;
  587. break;
  588. }
  589. }
  590. if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {
  591. rawSeqStore->posInSequence = 0;
  592. }
  593. }
  594. size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
  595. ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
  596. ZSTD_paramSwitch_e useRowMatchFinder,
  597. void const* src, size_t srcSize)
  598. {
  599. const ZSTD_compressionParameters* const cParams = &ms->cParams;
  600. unsigned const minMatch = cParams->minMatch;
  601. ZSTD_blockCompressor const blockCompressor =
  602. ZSTD_selectBlockCompressor(cParams->strategy, useRowMatchFinder, ZSTD_matchState_dictMode(ms));
  603. /* Input bounds */
  604. BYTE const* const istart = (BYTE const*)src;
  605. BYTE const* const iend = istart + srcSize;
  606. /* Input positions */
  607. BYTE const* ip = istart;
  608. DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
  609. /* If using opt parser, use LDMs only as candidates rather than always accepting them */
  610. if (cParams->strategy >= ZSTD_btopt) {
  611. size_t lastLLSize;
  612. ms->ldmSeqStore = rawSeqStore;
  613. lastLLSize = blockCompressor(ms, seqStore, rep, src, srcSize);
  614. ZSTD_ldm_skipRawSeqStoreBytes(rawSeqStore, srcSize);
  615. return lastLLSize;
  616. }
  617. assert(rawSeqStore->pos <= rawSeqStore->size);
  618. assert(rawSeqStore->size <= rawSeqStore->capacity);
  619. /* Loop through each sequence and apply the block compressor to the literals */
  620. while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
  621. /* maybeSplitSequence updates rawSeqStore->pos */
  622. rawSeq const sequence = maybeSplitSequence(rawSeqStore,
  623. (U32)(iend - ip), minMatch);
  624. int i;
  625. /* End signal */
  626. if (sequence.offset == 0)
  627. break;
  628. assert(ip + sequence.litLength + sequence.matchLength <= iend);
  629. /* Fill tables for block compressor */
  630. ZSTD_ldm_limitTableUpdate(ms, ip);
  631. ZSTD_ldm_fillFastTables(ms, ip);
  632. /* Run the block compressor */
  633. DEBUGLOG(5, "pos %u : calling block compressor on segment of size %u", (unsigned)(ip-istart), sequence.litLength);
  634. {
  635. size_t const newLitLength =
  636. blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
  637. ip += sequence.litLength;
  638. /* Update the repcodes */
  639. for (i = ZSTD_REP_NUM - 1; i > 0; i--)
  640. rep[i] = rep[i-1];
  641. rep[0] = sequence.offset;
  642. /* Store the sequence */
  643. ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength, iend,
  644. OFFSET_TO_OFFBASE(sequence.offset),
  645. sequence.matchLength);
  646. ip += sequence.matchLength;
  647. }
  648. }
  649. /* Fill the tables for the block compressor */
  650. ZSTD_ldm_limitTableUpdate(ms, ip);
  651. ZSTD_ldm_fillFastTables(ms, ip);
  652. /* Compress the last literals */
  653. return blockCompressor(ms, seqStore, rep, ip, iend - ip);
  654. }