zstdmt_compress.c 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  1. /*
  2. * Copyright (c) Yann Collet, Facebook, Inc.
  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. /* ====== Compiler specifics ====== */
  11. #if defined(_MSC_VER)
  12. # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
  13. #endif
  14. /* ====== Constants ====== */
  15. #define ZSTDMT_OVERLAPLOG_DEFAULT 0
  16. /* ====== Dependencies ====== */
  17. #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset, INT_MAX, UINT_MAX */
  18. #include "../common/mem.h" /* MEM_STATIC */
  19. #include "../common/pool.h" /* threadpool */
  20. #include "../common/threading.h" /* mutex */
  21. #include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
  22. #include "zstd_ldm.h"
  23. #include "zstdmt_compress.h"
  24. /* Guards code to support resizing the SeqPool.
  25. * We will want to resize the SeqPool to save memory in the future.
  26. * Until then, comment the code out since it is unused.
  27. */
  28. #define ZSTD_RESIZE_SEQPOOL 0
  29. /* ====== Debug ====== */
  30. #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=2) \
  31. && !defined(_MSC_VER) \
  32. && !defined(__MINGW32__)
  33. # include <stdio.h>
  34. # include <unistd.h>
  35. # include <sys/times.h>
  36. # define DEBUG_PRINTHEX(l,p,n) { \
  37. unsigned debug_u; \
  38. for (debug_u=0; debug_u<(n); debug_u++) \
  39. RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
  40. RAWLOG(l, " \n"); \
  41. }
  42. static unsigned long long GetCurrentClockTimeMicroseconds(void)
  43. {
  44. static clock_t _ticksPerSecond = 0;
  45. if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);
  46. { struct tms junk; clock_t newTicks = (clock_t) times(&junk);
  47. return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);
  48. } }
  49. #define MUTEX_WAIT_TIME_DLEVEL 6
  50. #define ZSTD_PTHREAD_MUTEX_LOCK(mutex) { \
  51. if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) { \
  52. unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \
  53. ZSTD_pthread_mutex_lock(mutex); \
  54. { unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
  55. unsigned long long const elapsedTime = (afterTime-beforeTime); \
  56. if (elapsedTime > 1000) { /* or whatever threshold you like; I'm using 1 millisecond here */ \
  57. DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \
  58. elapsedTime, #mutex); \
  59. } } \
  60. } else { \
  61. ZSTD_pthread_mutex_lock(mutex); \
  62. } \
  63. }
  64. #else
  65. # define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)
  66. # define DEBUG_PRINTHEX(l,p,n) {}
  67. #endif
  68. /* ===== Buffer Pool ===== */
  69. /* a single Buffer Pool can be invoked from multiple threads in parallel */
  70. typedef struct buffer_s {
  71. void* start;
  72. size_t capacity;
  73. } buffer_t;
  74. static const buffer_t g_nullBuffer = { NULL, 0 };
  75. typedef struct ZSTDMT_bufferPool_s {
  76. ZSTD_pthread_mutex_t poolMutex;
  77. size_t bufferSize;
  78. unsigned totalBuffers;
  79. unsigned nbBuffers;
  80. ZSTD_customMem cMem;
  81. buffer_t bTable[1]; /* variable size */
  82. } ZSTDMT_bufferPool;
  83. static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned nbWorkers, ZSTD_customMem cMem)
  84. {
  85. unsigned const maxNbBuffers = 2*nbWorkers + 3;
  86. ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_customCalloc(
  87. sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);
  88. if (bufPool==NULL) return NULL;
  89. if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
  90. ZSTD_customFree(bufPool, cMem);
  91. return NULL;
  92. }
  93. bufPool->bufferSize = 64 KB;
  94. bufPool->totalBuffers = maxNbBuffers;
  95. bufPool->nbBuffers = 0;
  96. bufPool->cMem = cMem;
  97. return bufPool;
  98. }
  99. static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
  100. {
  101. unsigned u;
  102. DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
  103. if (!bufPool) return; /* compatibility with free on NULL */
  104. for (u=0; u<bufPool->totalBuffers; u++) {
  105. DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);
  106. ZSTD_customFree(bufPool->bTable[u].start, bufPool->cMem);
  107. }
  108. ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
  109. ZSTD_customFree(bufPool, bufPool->cMem);
  110. }
  111. /* only works at initialization, not during compression */
  112. static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)
  113. {
  114. size_t const poolSize = sizeof(*bufPool)
  115. + (bufPool->totalBuffers - 1) * sizeof(buffer_t);
  116. unsigned u;
  117. size_t totalBufferSize = 0;
  118. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  119. for (u=0; u<bufPool->totalBuffers; u++)
  120. totalBufferSize += bufPool->bTable[u].capacity;
  121. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  122. return poolSize + totalBufferSize;
  123. }
  124. /* ZSTDMT_setBufferSize() :
  125. * all future buffers provided by this buffer pool will have _at least_ this size
  126. * note : it's better for all buffers to have same size,
  127. * as they become freely interchangeable, reducing malloc/free usages and memory fragmentation */
  128. static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* const bufPool, size_t const bSize)
  129. {
  130. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  131. DEBUGLOG(4, "ZSTDMT_setBufferSize: bSize = %u", (U32)bSize);
  132. bufPool->bufferSize = bSize;
  133. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  134. }
  135. static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, U32 nbWorkers)
  136. {
  137. unsigned const maxNbBuffers = 2*nbWorkers + 3;
  138. if (srcBufPool==NULL) return NULL;
  139. if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */
  140. return srcBufPool;
  141. /* need a larger buffer pool */
  142. { ZSTD_customMem const cMem = srcBufPool->cMem;
  143. size_t const bSize = srcBufPool->bufferSize; /* forward parameters */
  144. ZSTDMT_bufferPool* newBufPool;
  145. ZSTDMT_freeBufferPool(srcBufPool);
  146. newBufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
  147. if (newBufPool==NULL) return newBufPool;
  148. ZSTDMT_setBufferSize(newBufPool, bSize);
  149. return newBufPool;
  150. }
  151. }
  152. /** ZSTDMT_getBuffer() :
  153. * assumption : bufPool must be valid
  154. * @return : a buffer, with start pointer and size
  155. * note: allocation may fail, in this case, start==NULL and size==0 */
  156. static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)
  157. {
  158. size_t const bSize = bufPool->bufferSize;
  159. DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);
  160. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  161. if (bufPool->nbBuffers) { /* try to use an existing buffer */
  162. buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];
  163. size_t const availBufferSize = buf.capacity;
  164. bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;
  165. if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {
  166. /* large enough, but not too much */
  167. DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",
  168. bufPool->nbBuffers, (U32)buf.capacity);
  169. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  170. return buf;
  171. }
  172. /* size conditions not respected : scratch this buffer, create new one */
  173. DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");
  174. ZSTD_customFree(buf.start, bufPool->cMem);
  175. }
  176. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  177. /* create new buffer */
  178. DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");
  179. { buffer_t buffer;
  180. void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);
  181. buffer.start = start; /* note : start can be NULL if malloc fails ! */
  182. buffer.capacity = (start==NULL) ? 0 : bSize;
  183. if (start==NULL) {
  184. DEBUGLOG(5, "ZSTDMT_getBuffer: buffer allocation failure !!");
  185. } else {
  186. DEBUGLOG(5, "ZSTDMT_getBuffer: created buffer of size %u", (U32)bSize);
  187. }
  188. return buffer;
  189. }
  190. }
  191. #if ZSTD_RESIZE_SEQPOOL
  192. /** ZSTDMT_resizeBuffer() :
  193. * assumption : bufPool must be valid
  194. * @return : a buffer that is at least the buffer pool buffer size.
  195. * If a reallocation happens, the data in the input buffer is copied.
  196. */
  197. static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer)
  198. {
  199. size_t const bSize = bufPool->bufferSize;
  200. if (buffer.capacity < bSize) {
  201. void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);
  202. buffer_t newBuffer;
  203. newBuffer.start = start;
  204. newBuffer.capacity = start == NULL ? 0 : bSize;
  205. if (start != NULL) {
  206. assert(newBuffer.capacity >= buffer.capacity);
  207. ZSTD_memcpy(newBuffer.start, buffer.start, buffer.capacity);
  208. DEBUGLOG(5, "ZSTDMT_resizeBuffer: created buffer of size %u", (U32)bSize);
  209. return newBuffer;
  210. }
  211. DEBUGLOG(5, "ZSTDMT_resizeBuffer: buffer allocation failure !!");
  212. }
  213. return buffer;
  214. }
  215. #endif
  216. /* store buffer for later re-use, up to pool capacity */
  217. static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
  218. {
  219. DEBUGLOG(5, "ZSTDMT_releaseBuffer");
  220. if (buf.start == NULL) return; /* compatible with release on NULL */
  221. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  222. if (bufPool->nbBuffers < bufPool->totalBuffers) {
  223. bufPool->bTable[bufPool->nbBuffers++] = buf; /* stored for later use */
  224. DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",
  225. (U32)buf.capacity, (U32)(bufPool->nbBuffers-1));
  226. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  227. return;
  228. }
  229. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  230. /* Reached bufferPool capacity (should not happen) */
  231. DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");
  232. ZSTD_customFree(buf.start, bufPool->cMem);
  233. }
  234. /* ===== Seq Pool Wrapper ====== */
  235. typedef ZSTDMT_bufferPool ZSTDMT_seqPool;
  236. static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)
  237. {
  238. return ZSTDMT_sizeof_bufferPool(seqPool);
  239. }
  240. static rawSeqStore_t bufferToSeq(buffer_t buffer)
  241. {
  242. rawSeqStore_t seq = kNullRawSeqStore;
  243. seq.seq = (rawSeq*)buffer.start;
  244. seq.capacity = buffer.capacity / sizeof(rawSeq);
  245. return seq;
  246. }
  247. static buffer_t seqToBuffer(rawSeqStore_t seq)
  248. {
  249. buffer_t buffer;
  250. buffer.start = seq.seq;
  251. buffer.capacity = seq.capacity * sizeof(rawSeq);
  252. return buffer;
  253. }
  254. static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)
  255. {
  256. if (seqPool->bufferSize == 0) {
  257. return kNullRawSeqStore;
  258. }
  259. return bufferToSeq(ZSTDMT_getBuffer(seqPool));
  260. }
  261. #if ZSTD_RESIZE_SEQPOOL
  262. static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
  263. {
  264. return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));
  265. }
  266. #endif
  267. static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
  268. {
  269. ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));
  270. }
  271. static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)
  272. {
  273. ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));
  274. }
  275. static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)
  276. {
  277. ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
  278. if (seqPool == NULL) return NULL;
  279. ZSTDMT_setNbSeq(seqPool, 0);
  280. return seqPool;
  281. }
  282. static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)
  283. {
  284. ZSTDMT_freeBufferPool(seqPool);
  285. }
  286. static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)
  287. {
  288. return ZSTDMT_expandBufferPool(pool, nbWorkers);
  289. }
  290. /* ===== CCtx Pool ===== */
  291. /* a single CCtx Pool can be invoked from multiple threads in parallel */
  292. typedef struct {
  293. ZSTD_pthread_mutex_t poolMutex;
  294. int totalCCtx;
  295. int availCCtx;
  296. ZSTD_customMem cMem;
  297. ZSTD_CCtx* cctx[1]; /* variable size */
  298. } ZSTDMT_CCtxPool;
  299. /* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
  300. static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
  301. {
  302. int cid;
  303. for (cid=0; cid<pool->totalCCtx; cid++)
  304. ZSTD_freeCCtx(pool->cctx[cid]); /* note : compatible with free on NULL */
  305. ZSTD_pthread_mutex_destroy(&pool->poolMutex);
  306. ZSTD_customFree(pool, pool->cMem);
  307. }
  308. /* ZSTDMT_createCCtxPool() :
  309. * implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */
  310. static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
  311. ZSTD_customMem cMem)
  312. {
  313. ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_customCalloc(
  314. sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);
  315. assert(nbWorkers > 0);
  316. if (!cctxPool) return NULL;
  317. if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
  318. ZSTD_customFree(cctxPool, cMem);
  319. return NULL;
  320. }
  321. cctxPool->cMem = cMem;
  322. cctxPool->totalCCtx = nbWorkers;
  323. cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
  324. cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
  325. if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
  326. DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
  327. return cctxPool;
  328. }
  329. static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,
  330. int nbWorkers)
  331. {
  332. if (srcPool==NULL) return NULL;
  333. if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */
  334. /* need a larger cctx pool */
  335. { ZSTD_customMem const cMem = srcPool->cMem;
  336. ZSTDMT_freeCCtxPool(srcPool);
  337. return ZSTDMT_createCCtxPool(nbWorkers, cMem);
  338. }
  339. }
  340. /* only works during initialization phase, not during compression */
  341. static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
  342. {
  343. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  344. { unsigned const nbWorkers = cctxPool->totalCCtx;
  345. size_t const poolSize = sizeof(*cctxPool)
  346. + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
  347. unsigned u;
  348. size_t totalCCtxSize = 0;
  349. for (u=0; u<nbWorkers; u++) {
  350. totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);
  351. }
  352. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  353. assert(nbWorkers > 0);
  354. return poolSize + totalCCtxSize;
  355. }
  356. }
  357. static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
  358. {
  359. DEBUGLOG(5, "ZSTDMT_getCCtx");
  360. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  361. if (cctxPool->availCCtx) {
  362. cctxPool->availCCtx--;
  363. { ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
  364. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  365. return cctx;
  366. } }
  367. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  368. DEBUGLOG(5, "create one more CCtx");
  369. return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */
  370. }
  371. static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
  372. {
  373. if (cctx==NULL) return; /* compatibility with release on NULL */
  374. ZSTD_pthread_mutex_lock(&pool->poolMutex);
  375. if (pool->availCCtx < pool->totalCCtx)
  376. pool->cctx[pool->availCCtx++] = cctx;
  377. else {
  378. /* pool overflow : should not happen, since totalCCtx==nbWorkers */
  379. DEBUGLOG(4, "CCtx pool overflow : free cctx");
  380. ZSTD_freeCCtx(cctx);
  381. }
  382. ZSTD_pthread_mutex_unlock(&pool->poolMutex);
  383. }
  384. /* ==== Serial State ==== */
  385. typedef struct {
  386. void const* start;
  387. size_t size;
  388. } range_t;
  389. typedef struct {
  390. /* All variables in the struct are protected by mutex. */
  391. ZSTD_pthread_mutex_t mutex;
  392. ZSTD_pthread_cond_t cond;
  393. ZSTD_CCtx_params params;
  394. ldmState_t ldmState;
  395. XXH64_state_t xxhState;
  396. unsigned nextJobID;
  397. /* Protects ldmWindow.
  398. * Must be acquired after the main mutex when acquiring both.
  399. */
  400. ZSTD_pthread_mutex_t ldmWindowMutex;
  401. ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is updated */
  402. ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */
  403. } serialState_t;
  404. static int
  405. ZSTDMT_serialState_reset(serialState_t* serialState,
  406. ZSTDMT_seqPool* seqPool,
  407. ZSTD_CCtx_params params,
  408. size_t jobSize,
  409. const void* dict, size_t const dictSize,
  410. ZSTD_dictContentType_e dictContentType)
  411. {
  412. /* Adjust parameters */
  413. if (params.ldmParams.enableLdm) {
  414. DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);
  415. ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
  416. assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
  417. assert(params.ldmParams.hashRateLog < 32);
  418. } else {
  419. ZSTD_memset(&params.ldmParams, 0, sizeof(params.ldmParams));
  420. }
  421. serialState->nextJobID = 0;
  422. if (params.fParams.checksumFlag)
  423. XXH64_reset(&serialState->xxhState, 0);
  424. if (params.ldmParams.enableLdm) {
  425. ZSTD_customMem cMem = params.customMem;
  426. unsigned const hashLog = params.ldmParams.hashLog;
  427. size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);
  428. unsigned const bucketLog =
  429. params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;
  430. unsigned const prevBucketLog =
  431. serialState->params.ldmParams.hashLog -
  432. serialState->params.ldmParams.bucketSizeLog;
  433. size_t const numBuckets = (size_t)1 << bucketLog;
  434. /* Size the seq pool tables */
  435. ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));
  436. /* Reset the window */
  437. ZSTD_window_init(&serialState->ldmState.window);
  438. /* Resize tables and output space if necessary. */
  439. if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {
  440. ZSTD_customFree(serialState->ldmState.hashTable, cMem);
  441. serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_customMalloc(hashSize, cMem);
  442. }
  443. if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {
  444. ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);
  445. serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_customMalloc(numBuckets, cMem);
  446. }
  447. if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)
  448. return 1;
  449. /* Zero the tables */
  450. ZSTD_memset(serialState->ldmState.hashTable, 0, hashSize);
  451. ZSTD_memset(serialState->ldmState.bucketOffsets, 0, numBuckets);
  452. /* Update window state and fill hash table with dict */
  453. serialState->ldmState.loadedDictEnd = 0;
  454. if (dictSize > 0) {
  455. if (dictContentType == ZSTD_dct_rawContent) {
  456. BYTE const* const dictEnd = (const BYTE*)dict + dictSize;
  457. ZSTD_window_update(&serialState->ldmState.window, dict, dictSize, /* forceNonContiguous */ 0);
  458. ZSTD_ldm_fillHashTable(&serialState->ldmState, (const BYTE*)dict, dictEnd, &params.ldmParams);
  459. serialState->ldmState.loadedDictEnd = params.forceWindow ? 0 : (U32)(dictEnd - serialState->ldmState.window.base);
  460. } else {
  461. /* don't even load anything */
  462. }
  463. }
  464. /* Initialize serialState's copy of ldmWindow. */
  465. serialState->ldmWindow = serialState->ldmState.window;
  466. }
  467. serialState->params = params;
  468. serialState->params.jobSize = (U32)jobSize;
  469. return 0;
  470. }
  471. static int ZSTDMT_serialState_init(serialState_t* serialState)
  472. {
  473. int initError = 0;
  474. ZSTD_memset(serialState, 0, sizeof(*serialState));
  475. initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);
  476. initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);
  477. initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);
  478. initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);
  479. return initError;
  480. }
  481. static void ZSTDMT_serialState_free(serialState_t* serialState)
  482. {
  483. ZSTD_customMem cMem = serialState->params.customMem;
  484. ZSTD_pthread_mutex_destroy(&serialState->mutex);
  485. ZSTD_pthread_cond_destroy(&serialState->cond);
  486. ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);
  487. ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);
  488. ZSTD_customFree(serialState->ldmState.hashTable, cMem);
  489. ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);
  490. }
  491. static void ZSTDMT_serialState_update(serialState_t* serialState,
  492. ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore,
  493. range_t src, unsigned jobID)
  494. {
  495. /* Wait for our turn */
  496. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
  497. while (serialState->nextJobID < jobID) {
  498. DEBUGLOG(5, "wait for serialState->cond");
  499. ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);
  500. }
  501. /* A future job may error and skip our job */
  502. if (serialState->nextJobID == jobID) {
  503. /* It is now our turn, do any processing necessary */
  504. if (serialState->params.ldmParams.enableLdm) {
  505. size_t error;
  506. assert(seqStore.seq != NULL && seqStore.pos == 0 &&
  507. seqStore.size == 0 && seqStore.capacity > 0);
  508. assert(src.size <= serialState->params.jobSize);
  509. ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0);
  510. error = ZSTD_ldm_generateSequences(
  511. &serialState->ldmState, &seqStore,
  512. &serialState->params.ldmParams, src.start, src.size);
  513. /* We provide a large enough buffer to never fail. */
  514. assert(!ZSTD_isError(error)); (void)error;
  515. /* Update ldmWindow to match the ldmState.window and signal the main
  516. * thread if it is waiting for a buffer.
  517. */
  518. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
  519. serialState->ldmWindow = serialState->ldmState.window;
  520. ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
  521. ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
  522. }
  523. if (serialState->params.fParams.checksumFlag && src.size > 0)
  524. XXH64_update(&serialState->xxhState, src.start, src.size);
  525. }
  526. /* Now it is the next jobs turn */
  527. serialState->nextJobID++;
  528. ZSTD_pthread_cond_broadcast(&serialState->cond);
  529. ZSTD_pthread_mutex_unlock(&serialState->mutex);
  530. if (seqStore.size > 0) {
  531. size_t const err = ZSTD_referenceExternalSequences(
  532. jobCCtx, seqStore.seq, seqStore.size);
  533. assert(serialState->params.ldmParams.enableLdm);
  534. assert(!ZSTD_isError(err));
  535. (void)err;
  536. }
  537. }
  538. static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,
  539. unsigned jobID, size_t cSize)
  540. {
  541. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
  542. if (serialState->nextJobID <= jobID) {
  543. assert(ZSTD_isError(cSize)); (void)cSize;
  544. DEBUGLOG(5, "Skipping past job %u because of error", jobID);
  545. serialState->nextJobID = jobID + 1;
  546. ZSTD_pthread_cond_broadcast(&serialState->cond);
  547. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
  548. ZSTD_window_clear(&serialState->ldmWindow);
  549. ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
  550. ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
  551. }
  552. ZSTD_pthread_mutex_unlock(&serialState->mutex);
  553. }
  554. /* ------------------------------------------ */
  555. /* ===== Worker thread ===== */
  556. /* ------------------------------------------ */
  557. static const range_t kNullRange = { NULL, 0 };
  558. typedef struct {
  559. size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */
  560. size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */
  561. ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */
  562. ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */
  563. ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */
  564. ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */
  565. ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */
  566. serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */
  567. buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */
  568. range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */
  569. range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */
  570. unsigned jobID; /* set by mtctx, then read by worker => no barrier */
  571. unsigned firstJob; /* set by mtctx, then read by worker => no barrier */
  572. unsigned lastJob; /* set by mtctx, then read by worker => no barrier */
  573. ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */
  574. const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */
  575. unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */
  576. size_t dstFlushed; /* used only by mtctx */
  577. unsigned frameChecksumNeeded; /* used only by mtctx */
  578. } ZSTDMT_jobDescription;
  579. #define JOB_ERROR(e) { \
  580. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \
  581. job->cSize = e; \
  582. ZSTD_pthread_mutex_unlock(&job->job_mutex); \
  583. goto _endJob; \
  584. }
  585. /* ZSTDMT_compressionJob() is a POOL_function type */
  586. static void ZSTDMT_compressionJob(void* jobDescription)
  587. {
  588. ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
  589. ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */
  590. ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);
  591. rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);
  592. buffer_t dstBuff = job->dstBuff;
  593. size_t lastCBlockSize = 0;
  594. /* resources */
  595. if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));
  596. if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */
  597. dstBuff = ZSTDMT_getBuffer(job->bufPool);
  598. if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));
  599. job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */
  600. }
  601. if (jobParams.ldmParams.enableLdm && rawSeqStore.seq == NULL)
  602. JOB_ERROR(ERROR(memory_allocation));
  603. /* Don't compute the checksum for chunks, since we compute it externally,
  604. * but write it in the header.
  605. */
  606. if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;
  607. /* Don't run LDM for the chunks, since we handle it externally */
  608. jobParams.ldmParams.enableLdm = 0;
  609. /* Correct nbWorkers to 0. */
  610. jobParams.nbWorkers = 0;
  611. /* init */
  612. if (job->cdict) {
  613. size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize);
  614. assert(job->firstJob); /* only allowed for first job */
  615. if (ZSTD_isError(initError)) JOB_ERROR(initError);
  616. } else { /* srcStart points at reloaded section */
  617. U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;
  618. { size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);
  619. if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);
  620. }
  621. if (!job->firstJob) {
  622. size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0);
  623. if (ZSTD_isError(err)) JOB_ERROR(err);
  624. }
  625. { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,
  626. job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */
  627. ZSTD_dtlm_fast,
  628. NULL, /*cdict*/
  629. &jobParams, pledgedSrcSize);
  630. if (ZSTD_isError(initError)) JOB_ERROR(initError);
  631. } }
  632. /* Perform serial step as early as possible, but after CCtx initialization */
  633. ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);
  634. if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */
  635. size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);
  636. if (ZSTD_isError(hSize)) JOB_ERROR(hSize);
  637. DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);
  638. ZSTD_invalidateRepCodes(cctx);
  639. }
  640. /* compress */
  641. { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;
  642. int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);
  643. const BYTE* ip = (const BYTE*) job->src.start;
  644. BYTE* const ostart = (BYTE*)dstBuff.start;
  645. BYTE* op = ostart;
  646. BYTE* oend = op + dstBuff.capacity;
  647. int chunkNb;
  648. if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */
  649. DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);
  650. assert(job->cSize == 0);
  651. for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {
  652. size_t const cSize = ZSTD_compressContinue(cctx, op, oend-op, ip, chunkSize);
  653. if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
  654. ip += chunkSize;
  655. op += cSize; assert(op < oend);
  656. /* stats */
  657. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
  658. job->cSize += cSize;
  659. job->consumed = chunkSize * chunkNb;
  660. DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",
  661. (U32)cSize, (U32)job->cSize);
  662. ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */
  663. ZSTD_pthread_mutex_unlock(&job->job_mutex);
  664. }
  665. /* last block */
  666. assert(chunkSize > 0);
  667. assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */
  668. if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {
  669. size_t const lastBlockSize1 = job->src.size & (chunkSize-1);
  670. size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;
  671. size_t const cSize = (job->lastJob) ?
  672. ZSTD_compressEnd (cctx, op, oend-op, ip, lastBlockSize) :
  673. ZSTD_compressContinue(cctx, op, oend-op, ip, lastBlockSize);
  674. if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
  675. lastCBlockSize = cSize;
  676. } }
  677. if (!job->firstJob) {
  678. /* Double check that we don't have an ext-dict, because then our
  679. * repcode invalidation doesn't work.
  680. */
  681. assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
  682. }
  683. ZSTD_CCtx_trace(cctx, 0);
  684. _endJob:
  685. ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);
  686. if (job->prefix.size > 0)
  687. DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);
  688. DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);
  689. /* release resources */
  690. ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);
  691. ZSTDMT_releaseCCtx(job->cctxPool, cctx);
  692. /* report */
  693. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
  694. if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);
  695. job->cSize += lastCBlockSize;
  696. job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */
  697. ZSTD_pthread_cond_signal(&job->job_cond);
  698. ZSTD_pthread_mutex_unlock(&job->job_mutex);
  699. }
  700. /* ------------------------------------------ */
  701. /* ===== Multi-threaded compression ===== */
  702. /* ------------------------------------------ */
  703. typedef struct {
  704. range_t prefix; /* read-only non-owned prefix buffer */
  705. buffer_t buffer;
  706. size_t filled;
  707. } inBuff_t;
  708. typedef struct {
  709. BYTE* buffer; /* The round input buffer. All jobs get references
  710. * to pieces of the buffer. ZSTDMT_tryGetInputRange()
  711. * handles handing out job input buffers, and makes
  712. * sure it doesn't overlap with any pieces still in use.
  713. */
  714. size_t capacity; /* The capacity of buffer. */
  715. size_t pos; /* The position of the current inBuff in the round
  716. * buffer. Updated past the end if the inBuff once
  717. * the inBuff is sent to the worker thread.
  718. * pos <= capacity.
  719. */
  720. } roundBuff_t;
  721. static const roundBuff_t kNullRoundBuff = {NULL, 0, 0};
  722. #define RSYNC_LENGTH 32
  723. typedef struct {
  724. U64 hash;
  725. U64 hitMask;
  726. U64 primePower;
  727. } rsyncState_t;
  728. struct ZSTDMT_CCtx_s {
  729. POOL_ctx* factory;
  730. ZSTDMT_jobDescription* jobs;
  731. ZSTDMT_bufferPool* bufPool;
  732. ZSTDMT_CCtxPool* cctxPool;
  733. ZSTDMT_seqPool* seqPool;
  734. ZSTD_CCtx_params params;
  735. size_t targetSectionSize;
  736. size_t targetPrefixSize;
  737. int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */
  738. inBuff_t inBuff;
  739. roundBuff_t roundBuff;
  740. serialState_t serial;
  741. rsyncState_t rsync;
  742. unsigned jobIDMask;
  743. unsigned doneJobID;
  744. unsigned nextJobID;
  745. unsigned frameEnded;
  746. unsigned allJobsCompleted;
  747. unsigned long long frameContentSize;
  748. unsigned long long consumed;
  749. unsigned long long produced;
  750. ZSTD_customMem cMem;
  751. ZSTD_CDict* cdictLocal;
  752. const ZSTD_CDict* cdict;
  753. unsigned providedFactory: 1;
  754. };
  755. static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
  756. {
  757. U32 jobNb;
  758. if (jobTable == NULL) return;
  759. for (jobNb=0; jobNb<nbJobs; jobNb++) {
  760. ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);
  761. ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);
  762. }
  763. ZSTD_customFree(jobTable, cMem);
  764. }
  765. /* ZSTDMT_allocJobsTable()
  766. * allocate and init a job table.
  767. * update *nbJobsPtr to next power of 2 value, as size of table */
  768. static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
  769. {
  770. U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
  771. U32 const nbJobs = 1 << nbJobsLog2;
  772. U32 jobNb;
  773. ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
  774. ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
  775. int initError = 0;
  776. if (jobTable==NULL) return NULL;
  777. *nbJobsPtr = nbJobs;
  778. for (jobNb=0; jobNb<nbJobs; jobNb++) {
  779. initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
  780. initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);
  781. }
  782. if (initError != 0) {
  783. ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
  784. return NULL;
  785. }
  786. return jobTable;
  787. }
  788. static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
  789. U32 nbJobs = nbWorkers + 2;
  790. if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */
  791. ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
  792. mtctx->jobIDMask = 0;
  793. mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);
  794. if (mtctx->jobs==NULL) return ERROR(memory_allocation);
  795. assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */
  796. mtctx->jobIDMask = nbJobs - 1;
  797. }
  798. return 0;
  799. }
  800. /* ZSTDMT_CCtxParam_setNbWorkers():
  801. * Internal use only */
  802. static size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)
  803. {
  804. return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);
  805. }
  806. MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
  807. {
  808. ZSTDMT_CCtx* mtctx;
  809. U32 nbJobs = nbWorkers + 2;
  810. int initError;
  811. DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
  812. if (nbWorkers < 1) return NULL;
  813. nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
  814. if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
  815. /* invalid custom allocator */
  816. return NULL;
  817. mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);
  818. if (!mtctx) return NULL;
  819. ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
  820. mtctx->cMem = cMem;
  821. mtctx->allJobsCompleted = 1;
  822. if (pool != NULL) {
  823. mtctx->factory = pool;
  824. mtctx->providedFactory = 1;
  825. }
  826. else {
  827. mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
  828. mtctx->providedFactory = 0;
  829. }
  830. mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
  831. assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */
  832. mtctx->jobIDMask = nbJobs - 1;
  833. mtctx->bufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
  834. mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
  835. mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
  836. initError = ZSTDMT_serialState_init(&mtctx->serial);
  837. mtctx->roundBuff = kNullRoundBuff;
  838. if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {
  839. ZSTDMT_freeCCtx(mtctx);
  840. return NULL;
  841. }
  842. DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);
  843. return mtctx;
  844. }
  845. ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
  846. {
  847. #ifdef ZSTD_MULTITHREAD
  848. return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);
  849. #else
  850. (void)nbWorkers;
  851. (void)cMem;
  852. (void)pool;
  853. return NULL;
  854. #endif
  855. }
  856. /* ZSTDMT_releaseAllJobResources() :
  857. * note : ensure all workers are killed first ! */
  858. static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
  859. {
  860. unsigned jobID;
  861. DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
  862. for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
  863. /* Copy the mutex/cond out */
  864. ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;
  865. ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;
  866. DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
  867. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
  868. /* Clear the job description, but keep the mutex/cond */
  869. ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));
  870. mtctx->jobs[jobID].job_mutex = mutex;
  871. mtctx->jobs[jobID].job_cond = cond;
  872. }
  873. mtctx->inBuff.buffer = g_nullBuffer;
  874. mtctx->inBuff.filled = 0;
  875. mtctx->allJobsCompleted = 1;
  876. }
  877. static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)
  878. {
  879. DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
  880. while (mtctx->doneJobID < mtctx->nextJobID) {
  881. unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
  882. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
  883. while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
  884. DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */
  885. ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
  886. }
  887. ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
  888. mtctx->doneJobID++;
  889. }
  890. }
  891. size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
  892. {
  893. if (mtctx==NULL) return 0; /* compatible with free on NULL */
  894. if (!mtctx->providedFactory)
  895. POOL_free(mtctx->factory); /* stop and free worker threads */
  896. ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
  897. ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
  898. ZSTDMT_freeBufferPool(mtctx->bufPool);
  899. ZSTDMT_freeCCtxPool(mtctx->cctxPool);
  900. ZSTDMT_freeSeqPool(mtctx->seqPool);
  901. ZSTDMT_serialState_free(&mtctx->serial);
  902. ZSTD_freeCDict(mtctx->cdictLocal);
  903. if (mtctx->roundBuff.buffer)
  904. ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
  905. ZSTD_customFree(mtctx, mtctx->cMem);
  906. return 0;
  907. }
  908. size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
  909. {
  910. if (mtctx == NULL) return 0; /* supports sizeof NULL */
  911. return sizeof(*mtctx)
  912. + POOL_sizeof(mtctx->factory)
  913. + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
  914. + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
  915. + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
  916. + ZSTDMT_sizeof_seqPool(mtctx->seqPool)
  917. + ZSTD_sizeof_CDict(mtctx->cdictLocal)
  918. + mtctx->roundBuff.capacity;
  919. }
  920. /* ZSTDMT_resize() :
  921. * @return : error code if fails, 0 on success */
  922. static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)
  923. {
  924. if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
  925. FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");
  926. mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, nbWorkers);
  927. if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
  928. mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);
  929. if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);
  930. mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);
  931. if (mtctx->seqPool == NULL) return ERROR(memory_allocation);
  932. ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
  933. return 0;
  934. }
  935. /*! ZSTDMT_updateCParams_whileCompressing() :
  936. * Updates a selected set of compression parameters, remaining compatible with currently active frame.
  937. * New parameters will be applied to next compression job. */
  938. void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)
  939. {
  940. U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */
  941. int const compressionLevel = cctxParams->compressionLevel;
  942. DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",
  943. compressionLevel);
  944. mtctx->params.compressionLevel = compressionLevel;
  945. { ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
  946. cParams.windowLog = saved_wlog;
  947. mtctx->params.cParams = cParams;
  948. }
  949. }
  950. /* ZSTDMT_getFrameProgression():
  951. * tells how much data has been consumed (input) and produced (output) for current frame.
  952. * able to count progression inside worker threads.
  953. * Note : mutex will be acquired during statistics collection inside workers. */
  954. ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
  955. {
  956. ZSTD_frameProgression fps;
  957. DEBUGLOG(5, "ZSTDMT_getFrameProgression");
  958. fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
  959. fps.consumed = mtctx->consumed;
  960. fps.produced = fps.flushed = mtctx->produced;
  961. fps.currentJobID = mtctx->nextJobID;
  962. fps.nbActiveWorkers = 0;
  963. { unsigned jobNb;
  964. unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
  965. DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
  966. mtctx->doneJobID, lastJobNb, mtctx->jobReady)
  967. for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
  968. unsigned const wJobID = jobNb & mtctx->jobIDMask;
  969. ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
  970. ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
  971. { size_t const cResult = jobPtr->cSize;
  972. size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
  973. size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
  974. assert(flushed <= produced);
  975. fps.ingested += jobPtr->src.size;
  976. fps.consumed += jobPtr->consumed;
  977. fps.produced += produced;
  978. fps.flushed += flushed;
  979. fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);
  980. }
  981. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  982. }
  983. }
  984. return fps;
  985. }
  986. size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)
  987. {
  988. size_t toFlush;
  989. unsigned const jobID = mtctx->doneJobID;
  990. assert(jobID <= mtctx->nextJobID);
  991. if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */
  992. /* look into oldest non-fully-flushed job */
  993. { unsigned const wJobID = jobID & mtctx->jobIDMask;
  994. ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
  995. ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
  996. { size_t const cResult = jobPtr->cSize;
  997. size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
  998. size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
  999. assert(flushed <= produced);
  1000. assert(jobPtr->consumed <= jobPtr->src.size);
  1001. toFlush = produced - flushed;
  1002. /* if toFlush==0, nothing is available to flush.
  1003. * However, jobID is expected to still be active:
  1004. * if jobID was already completed and fully flushed,
  1005. * ZSTDMT_flushProduced() should have already moved onto next job.
  1006. * Therefore, some input has not yet been consumed. */
  1007. if (toFlush==0) {
  1008. assert(jobPtr->consumed < jobPtr->src.size);
  1009. }
  1010. }
  1011. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1012. }
  1013. return toFlush;
  1014. }
  1015. /* ------------------------------------------ */
  1016. /* ===== Multi-threaded compression ===== */
  1017. /* ------------------------------------------ */
  1018. static unsigned ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params* params)
  1019. {
  1020. unsigned jobLog;
  1021. if (params->ldmParams.enableLdm) {
  1022. /* In Long Range Mode, the windowLog is typically oversized.
  1023. * In which case, it's preferable to determine the jobSize
  1024. * based on cycleLog instead. */
  1025. jobLog = MAX(21, ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy) + 3);
  1026. } else {
  1027. jobLog = MAX(20, params->cParams.windowLog + 2);
  1028. }
  1029. return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);
  1030. }
  1031. static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
  1032. {
  1033. switch(strat)
  1034. {
  1035. case ZSTD_btultra2:
  1036. return 9;
  1037. case ZSTD_btultra:
  1038. case ZSTD_btopt:
  1039. return 8;
  1040. case ZSTD_btlazy2:
  1041. case ZSTD_lazy2:
  1042. return 7;
  1043. case ZSTD_lazy:
  1044. case ZSTD_greedy:
  1045. case ZSTD_dfast:
  1046. case ZSTD_fast:
  1047. default:;
  1048. }
  1049. return 6;
  1050. }
  1051. static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)
  1052. {
  1053. assert(0 <= ovlog && ovlog <= 9);
  1054. if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
  1055. return ovlog;
  1056. }
  1057. static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)
  1058. {
  1059. int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);
  1060. int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);
  1061. assert(0 <= overlapRLog && overlapRLog <= 8);
  1062. if (params->ldmParams.enableLdm) {
  1063. /* In Long Range Mode, the windowLog is typically oversized.
  1064. * In which case, it's preferable to determine the jobSize
  1065. * based on chainLog instead.
  1066. * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
  1067. ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)
  1068. - overlapRLog;
  1069. }
  1070. assert(0 <= ovLog && ovLog <= ZSTD_WINDOWLOG_MAX);
  1071. DEBUGLOG(4, "overlapLog : %i", params->overlapLog);
  1072. DEBUGLOG(4, "overlap size : %i", 1 << ovLog);
  1073. return (ovLog==0) ? 0 : (size_t)1 << ovLog;
  1074. }
  1075. /* ====================================== */
  1076. /* ======= Streaming API ======= */
  1077. /* ====================================== */
  1078. size_t ZSTDMT_initCStream_internal(
  1079. ZSTDMT_CCtx* mtctx,
  1080. const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
  1081. const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
  1082. unsigned long long pledgedSrcSize)
  1083. {
  1084. DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
  1085. (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
  1086. /* params supposed partially fully validated at this point */
  1087. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  1088. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  1089. /* init */
  1090. if (params.nbWorkers != mtctx->params.nbWorkers)
  1091. FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, params.nbWorkers) , "");
  1092. if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
  1093. if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;
  1094. DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
  1095. if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */
  1096. ZSTDMT_waitForAllJobsCompleted(mtctx);
  1097. ZSTDMT_releaseAllJobResources(mtctx);
  1098. mtctx->allJobsCompleted = 1;
  1099. }
  1100. mtctx->params = params;
  1101. mtctx->frameContentSize = pledgedSrcSize;
  1102. if (dict) {
  1103. ZSTD_freeCDict(mtctx->cdictLocal);
  1104. mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  1105. ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
  1106. params.cParams, mtctx->cMem);
  1107. mtctx->cdict = mtctx->cdictLocal;
  1108. if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
  1109. } else {
  1110. ZSTD_freeCDict(mtctx->cdictLocal);
  1111. mtctx->cdictLocal = NULL;
  1112. mtctx->cdict = cdict;
  1113. }
  1114. mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(&params);
  1115. DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
  1116. mtctx->targetSectionSize = params.jobSize;
  1117. if (mtctx->targetSectionSize == 0) {
  1118. mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(&params);
  1119. }
  1120. assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);
  1121. if (params.rsyncable) {
  1122. /* Aim for the targetsectionSize as the average job size. */
  1123. U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);
  1124. U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);
  1125. DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
  1126. mtctx->rsync.hash = 0;
  1127. mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
  1128. mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
  1129. }
  1130. if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */
  1131. DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
  1132. DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
  1133. ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
  1134. {
  1135. /* If ldm is enabled we need windowSize space. */
  1136. size_t const windowSize = mtctx->params.ldmParams.enableLdm ? (1U << mtctx->params.cParams.windowLog) : 0;
  1137. /* Two buffers of slack, plus extra space for the overlap
  1138. * This is the minimum slack that LDM works with. One extra because
  1139. * flush might waste up to targetSectionSize-1 bytes. Another extra
  1140. * for the overlap (if > 0), then one to fill which doesn't overlap
  1141. * with the LDM window.
  1142. */
  1143. size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
  1144. size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
  1145. /* Compute the total size, and always have enough slack */
  1146. size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
  1147. size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
  1148. size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
  1149. if (mtctx->roundBuff.capacity < capacity) {
  1150. if (mtctx->roundBuff.buffer)
  1151. ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
  1152. mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);
  1153. if (mtctx->roundBuff.buffer == NULL) {
  1154. mtctx->roundBuff.capacity = 0;
  1155. return ERROR(memory_allocation);
  1156. }
  1157. mtctx->roundBuff.capacity = capacity;
  1158. }
  1159. }
  1160. DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
  1161. mtctx->roundBuff.pos = 0;
  1162. mtctx->inBuff.buffer = g_nullBuffer;
  1163. mtctx->inBuff.filled = 0;
  1164. mtctx->inBuff.prefix = kNullRange;
  1165. mtctx->doneJobID = 0;
  1166. mtctx->nextJobID = 0;
  1167. mtctx->frameEnded = 0;
  1168. mtctx->allJobsCompleted = 0;
  1169. mtctx->consumed = 0;
  1170. mtctx->produced = 0;
  1171. if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize,
  1172. dict, dictSize, dictContentType))
  1173. return ERROR(memory_allocation);
  1174. return 0;
  1175. }
  1176. /* ZSTDMT_writeLastEmptyBlock()
  1177. * Write a single empty block with an end-of-frame to finish a frame.
  1178. * Job must be created from streaming variant.
  1179. * This function is always successful if expected conditions are fulfilled.
  1180. */
  1181. static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)
  1182. {
  1183. assert(job->lastJob == 1);
  1184. assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */
  1185. assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */
  1186. assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
  1187. job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
  1188. if (job->dstBuff.start == NULL) {
  1189. job->cSize = ERROR(memory_allocation);
  1190. return;
  1191. }
  1192. assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */
  1193. job->src = kNullRange;
  1194. job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);
  1195. assert(!ZSTD_isError(job->cSize));
  1196. assert(job->consumed == 0);
  1197. }
  1198. static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)
  1199. {
  1200. unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
  1201. int const endFrame = (endOp == ZSTD_e_end);
  1202. if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
  1203. DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
  1204. assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
  1205. return 0;
  1206. }
  1207. if (!mtctx->jobReady) {
  1208. BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
  1209. DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
  1210. mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
  1211. mtctx->jobs[jobID].src.start = src;
  1212. mtctx->jobs[jobID].src.size = srcSize;
  1213. assert(mtctx->inBuff.filled >= srcSize);
  1214. mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
  1215. mtctx->jobs[jobID].consumed = 0;
  1216. mtctx->jobs[jobID].cSize = 0;
  1217. mtctx->jobs[jobID].params = mtctx->params;
  1218. mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
  1219. mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
  1220. mtctx->jobs[jobID].dstBuff = g_nullBuffer;
  1221. mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
  1222. mtctx->jobs[jobID].bufPool = mtctx->bufPool;
  1223. mtctx->jobs[jobID].seqPool = mtctx->seqPool;
  1224. mtctx->jobs[jobID].serial = &mtctx->serial;
  1225. mtctx->jobs[jobID].jobID = mtctx->nextJobID;
  1226. mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
  1227. mtctx->jobs[jobID].lastJob = endFrame;
  1228. mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
  1229. mtctx->jobs[jobID].dstFlushed = 0;
  1230. /* Update the round buffer pos and clear the input buffer to be reset */
  1231. mtctx->roundBuff.pos += srcSize;
  1232. mtctx->inBuff.buffer = g_nullBuffer;
  1233. mtctx->inBuff.filled = 0;
  1234. /* Set the prefix */
  1235. if (!endFrame) {
  1236. size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
  1237. mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
  1238. mtctx->inBuff.prefix.size = newPrefixSize;
  1239. } else { /* endFrame==1 => no need for another input buffer */
  1240. mtctx->inBuff.prefix = kNullRange;
  1241. mtctx->frameEnded = endFrame;
  1242. if (mtctx->nextJobID == 0) {
  1243. /* single job exception : checksum is already calculated directly within worker thread */
  1244. mtctx->params.fParams.checksumFlag = 0;
  1245. } }
  1246. if ( (srcSize == 0)
  1247. && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
  1248. DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
  1249. assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */
  1250. ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
  1251. mtctx->nextJobID++;
  1252. return 0;
  1253. }
  1254. }
  1255. DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",
  1256. mtctx->nextJobID,
  1257. (U32)mtctx->jobs[jobID].src.size,
  1258. mtctx->jobs[jobID].lastJob,
  1259. mtctx->nextJobID,
  1260. jobID);
  1261. if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
  1262. mtctx->nextJobID++;
  1263. mtctx->jobReady = 0;
  1264. } else {
  1265. DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);
  1266. mtctx->jobReady = 1;
  1267. }
  1268. return 0;
  1269. }
  1270. /*! ZSTDMT_flushProduced() :
  1271. * flush whatever data has been produced but not yet flushed in current job.
  1272. * move to next job if current one is fully flushed.
  1273. * `output` : `pos` will be updated with amount of data flushed .
  1274. * `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .
  1275. * @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */
  1276. static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)
  1277. {
  1278. unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
  1279. DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
  1280. blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
  1281. assert(output->size >= output->pos);
  1282. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
  1283. if ( blockToFlush
  1284. && (mtctx->doneJobID < mtctx->nextJobID) ) {
  1285. assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
  1286. while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */
  1287. if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
  1288. DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
  1289. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
  1290. break;
  1291. }
  1292. DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
  1293. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
  1294. ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */
  1295. } }
  1296. /* try to flush something */
  1297. { size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */
  1298. size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */
  1299. size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */
  1300. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1301. if (ZSTD_isError(cSize)) {
  1302. DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
  1303. mtctx->doneJobID, ZSTD_getErrorName(cSize));
  1304. ZSTDMT_waitForAllJobsCompleted(mtctx);
  1305. ZSTDMT_releaseAllJobResources(mtctx);
  1306. return cSize;
  1307. }
  1308. /* add frame checksum if necessary (can only happen once) */
  1309. assert(srcConsumed <= srcSize);
  1310. if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */
  1311. && mtctx->jobs[wJobID].frameChecksumNeeded ) {
  1312. U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
  1313. DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
  1314. MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
  1315. cSize += 4;
  1316. mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */
  1317. mtctx->jobs[wJobID].frameChecksumNeeded = 0;
  1318. }
  1319. if (cSize > 0) { /* compression is ongoing or completed */
  1320. size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
  1321. DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
  1322. (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
  1323. assert(mtctx->doneJobID < mtctx->nextJobID);
  1324. assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
  1325. assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
  1326. if (toFlush > 0) {
  1327. ZSTD_memcpy((char*)output->dst + output->pos,
  1328. (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
  1329. toFlush);
  1330. }
  1331. output->pos += toFlush;
  1332. mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */
  1333. if ( (srcConsumed == srcSize) /* job is completed */
  1334. && (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */
  1335. DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
  1336. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
  1337. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
  1338. DEBUGLOG(5, "dstBuffer released");
  1339. mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
  1340. mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */
  1341. mtctx->consumed += srcSize;
  1342. mtctx->produced += cSize;
  1343. mtctx->doneJobID++;
  1344. } }
  1345. /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
  1346. if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
  1347. if (srcSize > srcConsumed) return 1; /* current job not completely compressed */
  1348. }
  1349. if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */
  1350. if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */
  1351. if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */
  1352. mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */
  1353. if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */
  1354. return 0; /* internal buffers fully flushed */
  1355. }
  1356. /**
  1357. * Returns the range of data used by the earliest job that is not yet complete.
  1358. * If the data of the first job is broken up into two segments, we cover both
  1359. * sections.
  1360. */
  1361. static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)
  1362. {
  1363. unsigned const firstJobID = mtctx->doneJobID;
  1364. unsigned const lastJobID = mtctx->nextJobID;
  1365. unsigned jobID;
  1366. for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
  1367. unsigned const wJobID = jobID & mtctx->jobIDMask;
  1368. size_t consumed;
  1369. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
  1370. consumed = mtctx->jobs[wJobID].consumed;
  1371. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1372. if (consumed < mtctx->jobs[wJobID].src.size) {
  1373. range_t range = mtctx->jobs[wJobID].prefix;
  1374. if (range.size == 0) {
  1375. /* Empty prefix */
  1376. range = mtctx->jobs[wJobID].src;
  1377. }
  1378. /* Job source in multiple segments not supported yet */
  1379. assert(range.start <= mtctx->jobs[wJobID].src.start);
  1380. return range;
  1381. }
  1382. }
  1383. return kNullRange;
  1384. }
  1385. /**
  1386. * Returns non-zero iff buffer and range overlap.
  1387. */
  1388. static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
  1389. {
  1390. BYTE const* const bufferStart = (BYTE const*)buffer.start;
  1391. BYTE const* const bufferEnd = bufferStart + buffer.capacity;
  1392. BYTE const* const rangeStart = (BYTE const*)range.start;
  1393. BYTE const* const rangeEnd = range.size != 0 ? rangeStart + range.size : rangeStart;
  1394. if (rangeStart == NULL || bufferStart == NULL)
  1395. return 0;
  1396. /* Empty ranges cannot overlap */
  1397. if (bufferStart == bufferEnd || rangeStart == rangeEnd)
  1398. return 0;
  1399. return bufferStart < rangeEnd && rangeStart < bufferEnd;
  1400. }
  1401. static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)
  1402. {
  1403. range_t extDict;
  1404. range_t prefix;
  1405. DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
  1406. extDict.start = window.dictBase + window.lowLimit;
  1407. extDict.size = window.dictLimit - window.lowLimit;
  1408. prefix.start = window.base + window.dictLimit;
  1409. prefix.size = window.nextSrc - (window.base + window.dictLimit);
  1410. DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
  1411. (size_t)extDict.start,
  1412. (size_t)extDict.start + extDict.size);
  1413. DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",
  1414. (size_t)prefix.start,
  1415. (size_t)prefix.start + prefix.size);
  1416. return ZSTDMT_isOverlapped(buffer, extDict)
  1417. || ZSTDMT_isOverlapped(buffer, prefix);
  1418. }
  1419. static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)
  1420. {
  1421. if (mtctx->params.ldmParams.enableLdm) {
  1422. ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
  1423. DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
  1424. DEBUGLOG(5, "source [0x%zx, 0x%zx)",
  1425. (size_t)buffer.start,
  1426. (size_t)buffer.start + buffer.capacity);
  1427. ZSTD_PTHREAD_MUTEX_LOCK(mutex);
  1428. while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {
  1429. DEBUGLOG(5, "Waiting for LDM to finish...");
  1430. ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);
  1431. }
  1432. DEBUGLOG(6, "Done waiting for LDM to finish");
  1433. ZSTD_pthread_mutex_unlock(mutex);
  1434. }
  1435. }
  1436. /**
  1437. * Attempts to set the inBuff to the next section to fill.
  1438. * If any part of the new section is still in use we give up.
  1439. * Returns non-zero if the buffer is filled.
  1440. */
  1441. static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)
  1442. {
  1443. range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
  1444. size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
  1445. size_t const target = mtctx->targetSectionSize;
  1446. buffer_t buffer;
  1447. DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
  1448. assert(mtctx->inBuff.buffer.start == NULL);
  1449. assert(mtctx->roundBuff.capacity >= target);
  1450. if (spaceLeft < target) {
  1451. /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
  1452. * Simply copy the prefix to the beginning in that case.
  1453. */
  1454. BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
  1455. size_t const prefixSize = mtctx->inBuff.prefix.size;
  1456. buffer.start = start;
  1457. buffer.capacity = prefixSize;
  1458. if (ZSTDMT_isOverlapped(buffer, inUse)) {
  1459. DEBUGLOG(5, "Waiting for buffer...");
  1460. return 0;
  1461. }
  1462. ZSTDMT_waitForLdmComplete(mtctx, buffer);
  1463. ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);
  1464. mtctx->inBuff.prefix.start = start;
  1465. mtctx->roundBuff.pos = prefixSize;
  1466. }
  1467. buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
  1468. buffer.capacity = target;
  1469. if (ZSTDMT_isOverlapped(buffer, inUse)) {
  1470. DEBUGLOG(5, "Waiting for buffer...");
  1471. return 0;
  1472. }
  1473. assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
  1474. ZSTDMT_waitForLdmComplete(mtctx, buffer);
  1475. DEBUGLOG(5, "Using prefix range [%zx, %zx)",
  1476. (size_t)mtctx->inBuff.prefix.start,
  1477. (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
  1478. DEBUGLOG(5, "Using source range [%zx, %zx)",
  1479. (size_t)buffer.start,
  1480. (size_t)buffer.start + buffer.capacity);
  1481. mtctx->inBuff.buffer = buffer;
  1482. mtctx->inBuff.filled = 0;
  1483. assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);
  1484. return 1;
  1485. }
  1486. typedef struct {
  1487. size_t toLoad; /* The number of bytes to load from the input. */
  1488. int flush; /* Boolean declaring if we must flush because we found a synchronization point. */
  1489. } syncPoint_t;
  1490. /**
  1491. * Searches through the input for a synchronization point. If one is found, we
  1492. * will instruct the caller to flush, and return the number of bytes to load.
  1493. * Otherwise, we will load as many bytes as possible and instruct the caller
  1494. * to continue as normal.
  1495. */
  1496. static syncPoint_t
  1497. findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)
  1498. {
  1499. BYTE const* const istart = (BYTE const*)input.src + input.pos;
  1500. U64 const primePower = mtctx->rsync.primePower;
  1501. U64 const hitMask = mtctx->rsync.hitMask;
  1502. syncPoint_t syncPoint;
  1503. U64 hash;
  1504. BYTE const* prev;
  1505. size_t pos;
  1506. syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
  1507. syncPoint.flush = 0;
  1508. if (!mtctx->params.rsyncable)
  1509. /* Rsync is disabled. */
  1510. return syncPoint;
  1511. if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
  1512. /* Not enough to compute the hash.
  1513. * We will miss any synchronization points in this RSYNC_LENGTH byte
  1514. * window. However, since it depends only in the internal buffers, if the
  1515. * state is already synchronized, we will remain synchronized.
  1516. * Additionally, the probability that we miss a synchronization point is
  1517. * low: RSYNC_LENGTH / targetSectionSize.
  1518. */
  1519. return syncPoint;
  1520. /* Initialize the loop variables. */
  1521. if (mtctx->inBuff.filled >= RSYNC_LENGTH) {
  1522. /* We have enough bytes buffered to initialize the hash.
  1523. * Start scanning at the beginning of the input.
  1524. */
  1525. pos = 0;
  1526. prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
  1527. hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
  1528. if ((hash & hitMask) == hitMask) {
  1529. /* We're already at a sync point so don't load any more until
  1530. * we're able to flush this sync point.
  1531. * This likely happened because the job table was full so we
  1532. * couldn't add our job.
  1533. */
  1534. syncPoint.toLoad = 0;
  1535. syncPoint.flush = 1;
  1536. return syncPoint;
  1537. }
  1538. } else {
  1539. /* We don't have enough bytes buffered to initialize the hash, but
  1540. * we know we have at least RSYNC_LENGTH bytes total.
  1541. * Start scanning after the first RSYNC_LENGTH bytes less the bytes
  1542. * already buffered.
  1543. */
  1544. pos = RSYNC_LENGTH - mtctx->inBuff.filled;
  1545. prev = (BYTE const*)mtctx->inBuff.buffer.start - pos;
  1546. hash = ZSTD_rollingHash_compute(mtctx->inBuff.buffer.start, mtctx->inBuff.filled);
  1547. hash = ZSTD_rollingHash_append(hash, istart, pos);
  1548. }
  1549. /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
  1550. * through the input. If we hit a synchronization point, then cut the
  1551. * job off, and tell the compressor to flush the job. Otherwise, load
  1552. * all the bytes and continue as normal.
  1553. * If we go too long without a synchronization point (targetSectionSize)
  1554. * then a block will be emitted anyways, but this is okay, since if we
  1555. * are already synchronized we will remain synchronized.
  1556. */
  1557. for (; pos < syncPoint.toLoad; ++pos) {
  1558. BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
  1559. /* if (pos >= RSYNC_LENGTH) assert(ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash); */
  1560. hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
  1561. if ((hash & hitMask) == hitMask) {
  1562. syncPoint.toLoad = pos + 1;
  1563. syncPoint.flush = 1;
  1564. break;
  1565. }
  1566. }
  1567. return syncPoint;
  1568. }
  1569. size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)
  1570. {
  1571. size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;
  1572. if (hintInSize==0) hintInSize = mtctx->targetSectionSize;
  1573. return hintInSize;
  1574. }
  1575. /** ZSTDMT_compressStream_generic() :
  1576. * internal use only - exposed to be invoked from zstd_compress.c
  1577. * assumption : output and input are valid (pos <= size)
  1578. * @return : minimum amount of data remaining to flush, 0 if none */
  1579. size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
  1580. ZSTD_outBuffer* output,
  1581. ZSTD_inBuffer* input,
  1582. ZSTD_EndDirective endOp)
  1583. {
  1584. unsigned forwardInputProgress = 0;
  1585. DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
  1586. (U32)endOp, (U32)(input->size - input->pos));
  1587. assert(output->pos <= output->size);
  1588. assert(input->pos <= input->size);
  1589. if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
  1590. /* current frame being ended. Only flush/end are allowed */
  1591. return ERROR(stage_wrong);
  1592. }
  1593. /* fill input buffer */
  1594. if ( (!mtctx->jobReady)
  1595. && (input->size > input->pos) ) { /* support NULL input */
  1596. if (mtctx->inBuff.buffer.start == NULL) {
  1597. assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
  1598. if (!ZSTDMT_tryGetInputRange(mtctx)) {
  1599. /* It is only possible for this operation to fail if there are
  1600. * still compression jobs ongoing.
  1601. */
  1602. DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
  1603. assert(mtctx->doneJobID != mtctx->nextJobID);
  1604. } else
  1605. DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
  1606. }
  1607. if (mtctx->inBuff.buffer.start != NULL) {
  1608. syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
  1609. if (syncPoint.flush && endOp == ZSTD_e_continue) {
  1610. endOp = ZSTD_e_flush;
  1611. }
  1612. assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
  1613. DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
  1614. (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
  1615. ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
  1616. input->pos += syncPoint.toLoad;
  1617. mtctx->inBuff.filled += syncPoint.toLoad;
  1618. forwardInputProgress = syncPoint.toLoad>0;
  1619. }
  1620. }
  1621. if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {
  1622. /* Can't end yet because the input is not fully consumed.
  1623. * We are in one of these cases:
  1624. * - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.
  1625. * - We filled the input buffer: flush this job but don't end the frame.
  1626. * - We hit a synchronization point: flush this job but don't end the frame.
  1627. */
  1628. assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);
  1629. endOp = ZSTD_e_flush;
  1630. }
  1631. if ( (mtctx->jobReady)
  1632. || (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */
  1633. || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */
  1634. || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */
  1635. size_t const jobSize = mtctx->inBuff.filled;
  1636. assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
  1637. FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");
  1638. }
  1639. /* check for potential compressed data ready to be flushed */
  1640. { size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */
  1641. if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */
  1642. DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);
  1643. return remainingToFlush;
  1644. }
  1645. }