zstd_ldm.c 28 KB

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