zstdmt_compress.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  1. /*
  2. * Copyright (c) 2016-present, 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 <string.h> /* memcpy, memset */
  18. #include <limits.h> /* INT_MAX, UINT_MAX */
  19. #include "pool.h" /* threadpool */
  20. #include "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_calloc(
  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_free(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_free(bufPool->bTable[u].start, bufPool->cMem);
  107. }
  108. ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
  109. ZSTD_free(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_free(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_malloc(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_malloc(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. 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_free(buf.start, bufPool->cMem);
  233. }
  234. /* ===== Seq Pool Wrapper ====== */
  235. static rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0};
  236. typedef ZSTDMT_bufferPool ZSTDMT_seqPool;
  237. static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)
  238. {
  239. return ZSTDMT_sizeof_bufferPool(seqPool);
  240. }
  241. static rawSeqStore_t bufferToSeq(buffer_t buffer)
  242. {
  243. rawSeqStore_t seq = {NULL, 0, 0, 0};
  244. seq.seq = (rawSeq*)buffer.start;
  245. seq.capacity = buffer.capacity / sizeof(rawSeq);
  246. return seq;
  247. }
  248. static buffer_t seqToBuffer(rawSeqStore_t seq)
  249. {
  250. buffer_t buffer;
  251. buffer.start = seq.seq;
  252. buffer.capacity = seq.capacity * sizeof(rawSeq);
  253. return buffer;
  254. }
  255. static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)
  256. {
  257. if (seqPool->bufferSize == 0) {
  258. return kNullRawSeqStore;
  259. }
  260. return bufferToSeq(ZSTDMT_getBuffer(seqPool));
  261. }
  262. #if ZSTD_RESIZE_SEQPOOL
  263. static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
  264. {
  265. return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));
  266. }
  267. #endif
  268. static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
  269. {
  270. ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));
  271. }
  272. static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)
  273. {
  274. ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));
  275. }
  276. static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)
  277. {
  278. ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
  279. if (seqPool == NULL) return NULL;
  280. ZSTDMT_setNbSeq(seqPool, 0);
  281. return seqPool;
  282. }
  283. static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)
  284. {
  285. ZSTDMT_freeBufferPool(seqPool);
  286. }
  287. static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)
  288. {
  289. return ZSTDMT_expandBufferPool(pool, nbWorkers);
  290. }
  291. /* ===== CCtx Pool ===== */
  292. /* a single CCtx Pool can be invoked from multiple threads in parallel */
  293. typedef struct {
  294. ZSTD_pthread_mutex_t poolMutex;
  295. int totalCCtx;
  296. int availCCtx;
  297. ZSTD_customMem cMem;
  298. ZSTD_CCtx* cctx[1]; /* variable size */
  299. } ZSTDMT_CCtxPool;
  300. /* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
  301. static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
  302. {
  303. int cid;
  304. for (cid=0; cid<pool->totalCCtx; cid++)
  305. ZSTD_freeCCtx(pool->cctx[cid]); /* note : compatible with free on NULL */
  306. ZSTD_pthread_mutex_destroy(&pool->poolMutex);
  307. ZSTD_free(pool, pool->cMem);
  308. }
  309. /* ZSTDMT_createCCtxPool() :
  310. * implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */
  311. static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
  312. ZSTD_customMem cMem)
  313. {
  314. ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_calloc(
  315. sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);
  316. assert(nbWorkers > 0);
  317. if (!cctxPool) return NULL;
  318. if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
  319. ZSTD_free(cctxPool, cMem);
  320. return NULL;
  321. }
  322. cctxPool->cMem = cMem;
  323. cctxPool->totalCCtx = nbWorkers;
  324. cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
  325. cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
  326. if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
  327. DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
  328. return cctxPool;
  329. }
  330. static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,
  331. int nbWorkers)
  332. {
  333. if (srcPool==NULL) return NULL;
  334. if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */
  335. /* need a larger cctx pool */
  336. { ZSTD_customMem const cMem = srcPool->cMem;
  337. ZSTDMT_freeCCtxPool(srcPool);
  338. return ZSTDMT_createCCtxPool(nbWorkers, cMem);
  339. }
  340. }
  341. /* only works during initialization phase, not during compression */
  342. static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
  343. {
  344. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  345. { unsigned const nbWorkers = cctxPool->totalCCtx;
  346. size_t const poolSize = sizeof(*cctxPool)
  347. + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
  348. unsigned u;
  349. size_t totalCCtxSize = 0;
  350. for (u=0; u<nbWorkers; u++) {
  351. totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);
  352. }
  353. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  354. assert(nbWorkers > 0);
  355. return poolSize + totalCCtxSize;
  356. }
  357. }
  358. static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
  359. {
  360. DEBUGLOG(5, "ZSTDMT_getCCtx");
  361. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  362. if (cctxPool->availCCtx) {
  363. cctxPool->availCCtx--;
  364. { ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
  365. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  366. return cctx;
  367. } }
  368. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  369. DEBUGLOG(5, "create one more CCtx");
  370. return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */
  371. }
  372. static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
  373. {
  374. if (cctx==NULL) return; /* compatibility with release on NULL */
  375. ZSTD_pthread_mutex_lock(&pool->poolMutex);
  376. if (pool->availCCtx < pool->totalCCtx)
  377. pool->cctx[pool->availCCtx++] = cctx;
  378. else {
  379. /* pool overflow : should not happen, since totalCCtx==nbWorkers */
  380. DEBUGLOG(4, "CCtx pool overflow : free cctx");
  381. ZSTD_freeCCtx(cctx);
  382. }
  383. ZSTD_pthread_mutex_unlock(&pool->poolMutex);
  384. }
  385. /* ==== Serial State ==== */
  386. typedef struct {
  387. void const* start;
  388. size_t size;
  389. } range_t;
  390. typedef struct {
  391. /* All variables in the struct are protected by mutex. */
  392. ZSTD_pthread_mutex_t mutex;
  393. ZSTD_pthread_cond_t cond;
  394. ZSTD_CCtx_params params;
  395. ldmState_t ldmState;
  396. XXH64_state_t xxhState;
  397. unsigned nextJobID;
  398. /* Protects ldmWindow.
  399. * Must be acquired after the main mutex when acquiring both.
  400. */
  401. ZSTD_pthread_mutex_t ldmWindowMutex;
  402. ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is udpated */
  403. ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */
  404. } serialState_t;
  405. static int ZSTDMT_serialState_reset(serialState_t* serialState, ZSTDMT_seqPool* seqPool, ZSTD_CCtx_params params, size_t jobSize)
  406. {
  407. /* Adjust parameters */
  408. if (params.ldmParams.enableLdm) {
  409. DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);
  410. ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
  411. assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
  412. assert(params.ldmParams.hashRateLog < 32);
  413. serialState->ldmState.hashPower =
  414. ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength);
  415. } else {
  416. memset(&params.ldmParams, 0, sizeof(params.ldmParams));
  417. }
  418. serialState->nextJobID = 0;
  419. if (params.fParams.checksumFlag)
  420. XXH64_reset(&serialState->xxhState, 0);
  421. if (params.ldmParams.enableLdm) {
  422. ZSTD_customMem cMem = params.customMem;
  423. unsigned const hashLog = params.ldmParams.hashLog;
  424. size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);
  425. unsigned const bucketLog =
  426. params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;
  427. size_t const bucketSize = (size_t)1 << bucketLog;
  428. unsigned const prevBucketLog =
  429. serialState->params.ldmParams.hashLog -
  430. serialState->params.ldmParams.bucketSizeLog;
  431. /* Size the seq pool tables */
  432. ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));
  433. /* Reset the window */
  434. ZSTD_window_clear(&serialState->ldmState.window);
  435. serialState->ldmWindow = serialState->ldmState.window;
  436. /* Resize tables and output space if necessary. */
  437. if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {
  438. ZSTD_free(serialState->ldmState.hashTable, cMem);
  439. serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_malloc(hashSize, cMem);
  440. }
  441. if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {
  442. ZSTD_free(serialState->ldmState.bucketOffsets, cMem);
  443. serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_malloc(bucketSize, cMem);
  444. }
  445. if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)
  446. return 1;
  447. /* Zero the tables */
  448. memset(serialState->ldmState.hashTable, 0, hashSize);
  449. memset(serialState->ldmState.bucketOffsets, 0, bucketSize);
  450. }
  451. serialState->params = params;
  452. serialState->params.jobSize = (U32)jobSize;
  453. return 0;
  454. }
  455. static int ZSTDMT_serialState_init(serialState_t* serialState)
  456. {
  457. int initError = 0;
  458. memset(serialState, 0, sizeof(*serialState));
  459. initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);
  460. initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);
  461. initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);
  462. initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);
  463. return initError;
  464. }
  465. static void ZSTDMT_serialState_free(serialState_t* serialState)
  466. {
  467. ZSTD_customMem cMem = serialState->params.customMem;
  468. ZSTD_pthread_mutex_destroy(&serialState->mutex);
  469. ZSTD_pthread_cond_destroy(&serialState->cond);
  470. ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);
  471. ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);
  472. ZSTD_free(serialState->ldmState.hashTable, cMem);
  473. ZSTD_free(serialState->ldmState.bucketOffsets, cMem);
  474. }
  475. static void ZSTDMT_serialState_update(serialState_t* serialState,
  476. ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore,
  477. range_t src, unsigned jobID)
  478. {
  479. /* Wait for our turn */
  480. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
  481. while (serialState->nextJobID < jobID) {
  482. DEBUGLOG(5, "wait for serialState->cond");
  483. ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);
  484. }
  485. /* A future job may error and skip our job */
  486. if (serialState->nextJobID == jobID) {
  487. /* It is now our turn, do any processing necessary */
  488. if (serialState->params.ldmParams.enableLdm) {
  489. size_t error;
  490. assert(seqStore.seq != NULL && seqStore.pos == 0 &&
  491. seqStore.size == 0 && seqStore.capacity > 0);
  492. assert(src.size <= serialState->params.jobSize);
  493. ZSTD_window_update(&serialState->ldmState.window, src.start, src.size);
  494. error = ZSTD_ldm_generateSequences(
  495. &serialState->ldmState, &seqStore,
  496. &serialState->params.ldmParams, src.start, src.size);
  497. /* We provide a large enough buffer to never fail. */
  498. assert(!ZSTD_isError(error)); (void)error;
  499. /* Update ldmWindow to match the ldmState.window and signal the main
  500. * thread if it is waiting for a buffer.
  501. */
  502. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
  503. serialState->ldmWindow = serialState->ldmState.window;
  504. ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
  505. ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
  506. }
  507. if (serialState->params.fParams.checksumFlag && src.size > 0)
  508. XXH64_update(&serialState->xxhState, src.start, src.size);
  509. }
  510. /* Now it is the next jobs turn */
  511. serialState->nextJobID++;
  512. ZSTD_pthread_cond_broadcast(&serialState->cond);
  513. ZSTD_pthread_mutex_unlock(&serialState->mutex);
  514. if (seqStore.size > 0) {
  515. size_t const err = ZSTD_referenceExternalSequences(
  516. jobCCtx, seqStore.seq, seqStore.size);
  517. assert(serialState->params.ldmParams.enableLdm);
  518. assert(!ZSTD_isError(err));
  519. (void)err;
  520. }
  521. }
  522. static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,
  523. unsigned jobID, size_t cSize)
  524. {
  525. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
  526. if (serialState->nextJobID <= jobID) {
  527. assert(ZSTD_isError(cSize)); (void)cSize;
  528. DEBUGLOG(5, "Skipping past job %u because of error", jobID);
  529. serialState->nextJobID = jobID + 1;
  530. ZSTD_pthread_cond_broadcast(&serialState->cond);
  531. ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
  532. ZSTD_window_clear(&serialState->ldmWindow);
  533. ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
  534. ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
  535. }
  536. ZSTD_pthread_mutex_unlock(&serialState->mutex);
  537. }
  538. /* ------------------------------------------ */
  539. /* ===== Worker thread ===== */
  540. /* ------------------------------------------ */
  541. static const range_t kNullRange = { NULL, 0 };
  542. typedef struct {
  543. size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */
  544. size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */
  545. ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */
  546. ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */
  547. ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */
  548. ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */
  549. ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */
  550. serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */
  551. buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */
  552. range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */
  553. range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */
  554. unsigned jobID; /* set by mtctx, then read by worker => no barrier */
  555. unsigned firstJob; /* set by mtctx, then read by worker => no barrier */
  556. unsigned lastJob; /* set by mtctx, then read by worker => no barrier */
  557. ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */
  558. const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */
  559. unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */
  560. size_t dstFlushed; /* used only by mtctx */
  561. unsigned frameChecksumNeeded; /* used only by mtctx */
  562. } ZSTDMT_jobDescription;
  563. #define JOB_ERROR(e) { \
  564. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \
  565. job->cSize = e; \
  566. ZSTD_pthread_mutex_unlock(&job->job_mutex); \
  567. goto _endJob; \
  568. }
  569. /* ZSTDMT_compressionJob() is a POOL_function type */
  570. static void ZSTDMT_compressionJob(void* jobDescription)
  571. {
  572. ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
  573. ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */
  574. ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);
  575. rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);
  576. buffer_t dstBuff = job->dstBuff;
  577. size_t lastCBlockSize = 0;
  578. /* ressources */
  579. if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));
  580. if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */
  581. dstBuff = ZSTDMT_getBuffer(job->bufPool);
  582. if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));
  583. job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */
  584. }
  585. if (jobParams.ldmParams.enableLdm && rawSeqStore.seq == NULL)
  586. JOB_ERROR(ERROR(memory_allocation));
  587. /* Don't compute the checksum for chunks, since we compute it externally,
  588. * but write it in the header.
  589. */
  590. if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;
  591. /* Don't run LDM for the chunks, since we handle it externally */
  592. jobParams.ldmParams.enableLdm = 0;
  593. /* init */
  594. if (job->cdict) {
  595. size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, jobParams, job->fullFrameSize);
  596. assert(job->firstJob); /* only allowed for first job */
  597. if (ZSTD_isError(initError)) JOB_ERROR(initError);
  598. } else { /* srcStart points at reloaded section */
  599. U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;
  600. { size_t const forceWindowError = ZSTD_CCtxParam_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);
  601. if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);
  602. }
  603. { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,
  604. job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */
  605. ZSTD_dtlm_fast,
  606. NULL, /*cdict*/
  607. jobParams, pledgedSrcSize);
  608. if (ZSTD_isError(initError)) JOB_ERROR(initError);
  609. } }
  610. /* Perform serial step as early as possible, but after CCtx initialization */
  611. ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);
  612. if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */
  613. size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);
  614. if (ZSTD_isError(hSize)) JOB_ERROR(hSize);
  615. DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);
  616. ZSTD_invalidateRepCodes(cctx);
  617. }
  618. /* compress */
  619. { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;
  620. int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);
  621. const BYTE* ip = (const BYTE*) job->src.start;
  622. BYTE* const ostart = (BYTE*)dstBuff.start;
  623. BYTE* op = ostart;
  624. BYTE* oend = op + dstBuff.capacity;
  625. int chunkNb;
  626. if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */
  627. DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);
  628. assert(job->cSize == 0);
  629. for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {
  630. size_t const cSize = ZSTD_compressContinue(cctx, op, oend-op, ip, chunkSize);
  631. if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
  632. ip += chunkSize;
  633. op += cSize; assert(op < oend);
  634. /* stats */
  635. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
  636. job->cSize += cSize;
  637. job->consumed = chunkSize * chunkNb;
  638. DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",
  639. (U32)cSize, (U32)job->cSize);
  640. ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */
  641. ZSTD_pthread_mutex_unlock(&job->job_mutex);
  642. }
  643. /* last block */
  644. assert(chunkSize > 0);
  645. assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */
  646. if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {
  647. size_t const lastBlockSize1 = job->src.size & (chunkSize-1);
  648. size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;
  649. size_t const cSize = (job->lastJob) ?
  650. ZSTD_compressEnd (cctx, op, oend-op, ip, lastBlockSize) :
  651. ZSTD_compressContinue(cctx, op, oend-op, ip, lastBlockSize);
  652. if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
  653. lastCBlockSize = cSize;
  654. } }
  655. _endJob:
  656. ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);
  657. if (job->prefix.size > 0)
  658. DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);
  659. DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);
  660. /* release resources */
  661. ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);
  662. ZSTDMT_releaseCCtx(job->cctxPool, cctx);
  663. /* report */
  664. ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
  665. if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);
  666. job->cSize += lastCBlockSize;
  667. job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */
  668. ZSTD_pthread_cond_signal(&job->job_cond);
  669. ZSTD_pthread_mutex_unlock(&job->job_mutex);
  670. }
  671. /* ------------------------------------------ */
  672. /* ===== Multi-threaded compression ===== */
  673. /* ------------------------------------------ */
  674. typedef struct {
  675. range_t prefix; /* read-only non-owned prefix buffer */
  676. buffer_t buffer;
  677. size_t filled;
  678. } inBuff_t;
  679. typedef struct {
  680. BYTE* buffer; /* The round input buffer. All jobs get references
  681. * to pieces of the buffer. ZSTDMT_tryGetInputRange()
  682. * handles handing out job input buffers, and makes
  683. * sure it doesn't overlap with any pieces still in use.
  684. */
  685. size_t capacity; /* The capacity of buffer. */
  686. size_t pos; /* The position of the current inBuff in the round
  687. * buffer. Updated past the end if the inBuff once
  688. * the inBuff is sent to the worker thread.
  689. * pos <= capacity.
  690. */
  691. } roundBuff_t;
  692. static const roundBuff_t kNullRoundBuff = {NULL, 0, 0};
  693. #define RSYNC_LENGTH 32
  694. typedef struct {
  695. U64 hash;
  696. U64 hitMask;
  697. U64 primePower;
  698. } rsyncState_t;
  699. struct ZSTDMT_CCtx_s {
  700. POOL_ctx* factory;
  701. ZSTDMT_jobDescription* jobs;
  702. ZSTDMT_bufferPool* bufPool;
  703. ZSTDMT_CCtxPool* cctxPool;
  704. ZSTDMT_seqPool* seqPool;
  705. ZSTD_CCtx_params params;
  706. size_t targetSectionSize;
  707. size_t targetPrefixSize;
  708. int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */
  709. inBuff_t inBuff;
  710. roundBuff_t roundBuff;
  711. serialState_t serial;
  712. rsyncState_t rsync;
  713. unsigned singleBlockingThread;
  714. unsigned jobIDMask;
  715. unsigned doneJobID;
  716. unsigned nextJobID;
  717. unsigned frameEnded;
  718. unsigned allJobsCompleted;
  719. unsigned long long frameContentSize;
  720. unsigned long long consumed;
  721. unsigned long long produced;
  722. ZSTD_customMem cMem;
  723. ZSTD_CDict* cdictLocal;
  724. const ZSTD_CDict* cdict;
  725. };
  726. static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
  727. {
  728. U32 jobNb;
  729. if (jobTable == NULL) return;
  730. for (jobNb=0; jobNb<nbJobs; jobNb++) {
  731. ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);
  732. ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);
  733. }
  734. ZSTD_free(jobTable, cMem);
  735. }
  736. /* ZSTDMT_allocJobsTable()
  737. * allocate and init a job table.
  738. * update *nbJobsPtr to next power of 2 value, as size of table */
  739. static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
  740. {
  741. U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
  742. U32 const nbJobs = 1 << nbJobsLog2;
  743. U32 jobNb;
  744. ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
  745. ZSTD_calloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
  746. int initError = 0;
  747. if (jobTable==NULL) return NULL;
  748. *nbJobsPtr = nbJobs;
  749. for (jobNb=0; jobNb<nbJobs; jobNb++) {
  750. initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
  751. initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);
  752. }
  753. if (initError != 0) {
  754. ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
  755. return NULL;
  756. }
  757. return jobTable;
  758. }
  759. static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
  760. U32 nbJobs = nbWorkers + 2;
  761. if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */
  762. ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
  763. mtctx->jobIDMask = 0;
  764. mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);
  765. if (mtctx->jobs==NULL) return ERROR(memory_allocation);
  766. assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */
  767. mtctx->jobIDMask = nbJobs - 1;
  768. }
  769. return 0;
  770. }
  771. /* ZSTDMT_CCtxParam_setNbWorkers():
  772. * Internal use only */
  773. size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)
  774. {
  775. if (nbWorkers > ZSTDMT_NBWORKERS_MAX) nbWorkers = ZSTDMT_NBWORKERS_MAX;
  776. params->nbWorkers = nbWorkers;
  777. params->overlapLog = ZSTDMT_OVERLAPLOG_DEFAULT;
  778. params->jobSize = 0;
  779. return nbWorkers;
  780. }
  781. ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem)
  782. {
  783. ZSTDMT_CCtx* mtctx;
  784. U32 nbJobs = nbWorkers + 2;
  785. int initError;
  786. DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
  787. if (nbWorkers < 1) return NULL;
  788. nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
  789. if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
  790. /* invalid custom allocator */
  791. return NULL;
  792. mtctx = (ZSTDMT_CCtx*) ZSTD_calloc(sizeof(ZSTDMT_CCtx), cMem);
  793. if (!mtctx) return NULL;
  794. ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
  795. mtctx->cMem = cMem;
  796. mtctx->allJobsCompleted = 1;
  797. mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
  798. mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
  799. assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */
  800. mtctx->jobIDMask = nbJobs - 1;
  801. mtctx->bufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
  802. mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
  803. mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
  804. initError = ZSTDMT_serialState_init(&mtctx->serial);
  805. mtctx->roundBuff = kNullRoundBuff;
  806. if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {
  807. ZSTDMT_freeCCtx(mtctx);
  808. return NULL;
  809. }
  810. DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);
  811. return mtctx;
  812. }
  813. ZSTDMT_CCtx* ZSTDMT_createCCtx(unsigned nbWorkers)
  814. {
  815. return ZSTDMT_createCCtx_advanced(nbWorkers, ZSTD_defaultCMem);
  816. }
  817. /* ZSTDMT_releaseAllJobResources() :
  818. * note : ensure all workers are killed first ! */
  819. static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
  820. {
  821. unsigned jobID;
  822. DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
  823. for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
  824. DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
  825. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
  826. mtctx->jobs[jobID].dstBuff = g_nullBuffer;
  827. mtctx->jobs[jobID].cSize = 0;
  828. }
  829. memset(mtctx->jobs, 0, (mtctx->jobIDMask+1)*sizeof(ZSTDMT_jobDescription));
  830. mtctx->inBuff.buffer = g_nullBuffer;
  831. mtctx->inBuff.filled = 0;
  832. mtctx->allJobsCompleted = 1;
  833. }
  834. static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)
  835. {
  836. DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
  837. while (mtctx->doneJobID < mtctx->nextJobID) {
  838. unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
  839. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
  840. while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
  841. DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */
  842. ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
  843. }
  844. ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
  845. mtctx->doneJobID++;
  846. }
  847. }
  848. size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
  849. {
  850. if (mtctx==NULL) return 0; /* compatible with free on NULL */
  851. POOL_free(mtctx->factory); /* stop and free worker threads */
  852. ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
  853. ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
  854. ZSTDMT_freeBufferPool(mtctx->bufPool);
  855. ZSTDMT_freeCCtxPool(mtctx->cctxPool);
  856. ZSTDMT_freeSeqPool(mtctx->seqPool);
  857. ZSTDMT_serialState_free(&mtctx->serial);
  858. ZSTD_freeCDict(mtctx->cdictLocal);
  859. if (mtctx->roundBuff.buffer)
  860. ZSTD_free(mtctx->roundBuff.buffer, mtctx->cMem);
  861. ZSTD_free(mtctx, mtctx->cMem);
  862. return 0;
  863. }
  864. size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
  865. {
  866. if (mtctx == NULL) return 0; /* supports sizeof NULL */
  867. return sizeof(*mtctx)
  868. + POOL_sizeof(mtctx->factory)
  869. + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
  870. + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
  871. + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
  872. + ZSTDMT_sizeof_seqPool(mtctx->seqPool)
  873. + ZSTD_sizeof_CDict(mtctx->cdictLocal)
  874. + mtctx->roundBuff.capacity;
  875. }
  876. /* Internal only */
  877. size_t
  878. ZSTDMT_CCtxParam_setMTCtxParameter(ZSTD_CCtx_params* params,
  879. ZSTDMT_parameter parameter,
  880. int value)
  881. {
  882. DEBUGLOG(4, "ZSTDMT_CCtxParam_setMTCtxParameter");
  883. switch(parameter)
  884. {
  885. case ZSTDMT_p_jobSize :
  886. DEBUGLOG(4, "ZSTDMT_CCtxParam_setMTCtxParameter : set jobSize to %i", value);
  887. if ( value != 0 /* default */
  888. && value < ZSTDMT_JOBSIZE_MIN)
  889. value = ZSTDMT_JOBSIZE_MIN;
  890. assert(value >= 0);
  891. if (value > ZSTDMT_JOBSIZE_MAX) value = ZSTDMT_JOBSIZE_MAX;
  892. params->jobSize = value;
  893. return value;
  894. case ZSTDMT_p_overlapLog :
  895. DEBUGLOG(4, "ZSTDMT_p_overlapLog : %i", value);
  896. if (value < ZSTD_OVERLAPLOG_MIN) value = ZSTD_OVERLAPLOG_MIN;
  897. if (value > ZSTD_OVERLAPLOG_MAX) value = ZSTD_OVERLAPLOG_MAX;
  898. params->overlapLog = value;
  899. return value;
  900. case ZSTDMT_p_rsyncable :
  901. value = (value != 0);
  902. params->rsyncable = value;
  903. return value;
  904. default :
  905. return ERROR(parameter_unsupported);
  906. }
  907. }
  908. size_t ZSTDMT_setMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int value)
  909. {
  910. DEBUGLOG(4, "ZSTDMT_setMTCtxParameter");
  911. return ZSTDMT_CCtxParam_setMTCtxParameter(&mtctx->params, parameter, value);
  912. }
  913. size_t ZSTDMT_getMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int* value)
  914. {
  915. switch (parameter) {
  916. case ZSTDMT_p_jobSize:
  917. assert(mtctx->params.jobSize <= INT_MAX);
  918. *value = (int)(mtctx->params.jobSize);
  919. break;
  920. case ZSTDMT_p_overlapLog:
  921. *value = mtctx->params.overlapLog;
  922. break;
  923. case ZSTDMT_p_rsyncable:
  924. *value = mtctx->params.rsyncable;
  925. break;
  926. default:
  927. return ERROR(parameter_unsupported);
  928. }
  929. return 0;
  930. }
  931. /* Sets parameters relevant to the compression job,
  932. * initializing others to default values. */
  933. static ZSTD_CCtx_params ZSTDMT_initJobCCtxParams(ZSTD_CCtx_params const params)
  934. {
  935. ZSTD_CCtx_params jobParams;
  936. memset(&jobParams, 0, sizeof(jobParams));
  937. jobParams.cParams = params.cParams;
  938. jobParams.fParams = params.fParams;
  939. jobParams.compressionLevel = params.compressionLevel;
  940. return jobParams;
  941. }
  942. /* ZSTDMT_resize() :
  943. * @return : error code if fails, 0 on success */
  944. static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)
  945. {
  946. if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
  947. CHECK_F( ZSTDMT_expandJobsTable(mtctx, nbWorkers) );
  948. mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, nbWorkers);
  949. if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
  950. mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);
  951. if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);
  952. mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);
  953. if (mtctx->seqPool == NULL) return ERROR(memory_allocation);
  954. ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
  955. return 0;
  956. }
  957. /*! ZSTDMT_updateCParams_whileCompressing() :
  958. * Updates a selected set of compression parameters, remaining compatible with currently active frame.
  959. * New parameters will be applied to next compression job. */
  960. void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)
  961. {
  962. U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */
  963. int const compressionLevel = cctxParams->compressionLevel;
  964. DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",
  965. compressionLevel);
  966. mtctx->params.compressionLevel = compressionLevel;
  967. { ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, 0, 0);
  968. cParams.windowLog = saved_wlog;
  969. mtctx->params.cParams = cParams;
  970. }
  971. }
  972. /* ZSTDMT_getFrameProgression():
  973. * tells how much data has been consumed (input) and produced (output) for current frame.
  974. * able to count progression inside worker threads.
  975. * Note : mutex will be acquired during statistics collection inside workers. */
  976. ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
  977. {
  978. ZSTD_frameProgression fps;
  979. DEBUGLOG(5, "ZSTDMT_getFrameProgression");
  980. fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
  981. fps.consumed = mtctx->consumed;
  982. fps.produced = fps.flushed = mtctx->produced;
  983. fps.currentJobID = mtctx->nextJobID;
  984. fps.nbActiveWorkers = 0;
  985. { unsigned jobNb;
  986. unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
  987. DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
  988. mtctx->doneJobID, lastJobNb, mtctx->jobReady)
  989. for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
  990. unsigned const wJobID = jobNb & mtctx->jobIDMask;
  991. ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
  992. ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
  993. { size_t const cResult = jobPtr->cSize;
  994. size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
  995. size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
  996. assert(flushed <= produced);
  997. fps.ingested += jobPtr->src.size;
  998. fps.consumed += jobPtr->consumed;
  999. fps.produced += produced;
  1000. fps.flushed += flushed;
  1001. fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);
  1002. }
  1003. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1004. }
  1005. }
  1006. return fps;
  1007. }
  1008. size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)
  1009. {
  1010. size_t toFlush;
  1011. unsigned const jobID = mtctx->doneJobID;
  1012. assert(jobID <= mtctx->nextJobID);
  1013. if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */
  1014. /* look into oldest non-fully-flushed job */
  1015. { unsigned const wJobID = jobID & mtctx->jobIDMask;
  1016. ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
  1017. ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
  1018. { size_t const cResult = jobPtr->cSize;
  1019. size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
  1020. size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
  1021. assert(flushed <= produced);
  1022. toFlush = produced - flushed;
  1023. if (toFlush==0 && (jobPtr->consumed >= jobPtr->src.size)) {
  1024. /* doneJobID is not-fully-flushed, but toFlush==0 : doneJobID should be compressing some more data */
  1025. assert(jobPtr->consumed < jobPtr->src.size);
  1026. }
  1027. }
  1028. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1029. }
  1030. return toFlush;
  1031. }
  1032. /* ------------------------------------------ */
  1033. /* ===== Multi-threaded compression ===== */
  1034. /* ------------------------------------------ */
  1035. static unsigned ZSTDMT_computeTargetJobLog(ZSTD_CCtx_params const params)
  1036. {
  1037. if (params.ldmParams.enableLdm)
  1038. /* In Long Range Mode, the windowLog is typically oversized.
  1039. * In which case, it's preferable to determine the jobSize
  1040. * based on chainLog instead. */
  1041. return MAX(21, params.cParams.chainLog + 4);
  1042. return MAX(20, params.cParams.windowLog + 2);
  1043. }
  1044. static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
  1045. {
  1046. switch(strat)
  1047. {
  1048. case ZSTD_btultra2:
  1049. return 9;
  1050. case ZSTD_btultra:
  1051. case ZSTD_btopt:
  1052. return 8;
  1053. case ZSTD_btlazy2:
  1054. case ZSTD_lazy2:
  1055. return 7;
  1056. case ZSTD_lazy:
  1057. case ZSTD_greedy:
  1058. case ZSTD_dfast:
  1059. case ZSTD_fast:
  1060. default:;
  1061. }
  1062. return 6;
  1063. }
  1064. static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)
  1065. {
  1066. assert(0 <= ovlog && ovlog <= 9);
  1067. if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
  1068. return ovlog;
  1069. }
  1070. static size_t ZSTDMT_computeOverlapSize(ZSTD_CCtx_params const params)
  1071. {
  1072. int const overlapRLog = 9 - ZSTDMT_overlapLog(params.overlapLog, params.cParams.strategy);
  1073. int ovLog = (overlapRLog >= 8) ? 0 : (params.cParams.windowLog - overlapRLog);
  1074. assert(0 <= overlapRLog && overlapRLog <= 8);
  1075. if (params.ldmParams.enableLdm) {
  1076. /* In Long Range Mode, the windowLog is typically oversized.
  1077. * In which case, it's preferable to determine the jobSize
  1078. * based on chainLog instead.
  1079. * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
  1080. ovLog = MIN(params.cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)
  1081. - overlapRLog;
  1082. }
  1083. assert(0 <= ovLog && ovLog <= 30);
  1084. DEBUGLOG(4, "overlapLog : %i", params.overlapLog);
  1085. DEBUGLOG(4, "overlap size : %i", 1 << ovLog);
  1086. return (ovLog==0) ? 0 : (size_t)1 << ovLog;
  1087. }
  1088. static unsigned
  1089. ZSTDMT_computeNbJobs(ZSTD_CCtx_params params, size_t srcSize, unsigned nbWorkers)
  1090. {
  1091. assert(nbWorkers>0);
  1092. { size_t const jobSizeTarget = (size_t)1 << ZSTDMT_computeTargetJobLog(params);
  1093. size_t const jobMaxSize = jobSizeTarget << 2;
  1094. size_t const passSizeMax = jobMaxSize * nbWorkers;
  1095. unsigned const multiplier = (unsigned)(srcSize / passSizeMax) + 1;
  1096. unsigned const nbJobsLarge = multiplier * nbWorkers;
  1097. unsigned const nbJobsMax = (unsigned)(srcSize / jobSizeTarget) + 1;
  1098. unsigned const nbJobsSmall = MIN(nbJobsMax, nbWorkers);
  1099. return (multiplier>1) ? nbJobsLarge : nbJobsSmall;
  1100. } }
  1101. /* ZSTDMT_compress_advanced_internal() :
  1102. * This is a blocking function : it will only give back control to caller after finishing its compression job.
  1103. */
  1104. static size_t ZSTDMT_compress_advanced_internal(
  1105. ZSTDMT_CCtx* mtctx,
  1106. void* dst, size_t dstCapacity,
  1107. const void* src, size_t srcSize,
  1108. const ZSTD_CDict* cdict,
  1109. ZSTD_CCtx_params params)
  1110. {
  1111. ZSTD_CCtx_params const jobParams = ZSTDMT_initJobCCtxParams(params);
  1112. size_t const overlapSize = ZSTDMT_computeOverlapSize(params);
  1113. unsigned const nbJobs = ZSTDMT_computeNbJobs(params, srcSize, params.nbWorkers);
  1114. size_t const proposedJobSize = (srcSize + (nbJobs-1)) / nbJobs;
  1115. size_t const avgJobSize = (((proposedJobSize-1) & 0x1FFFF) < 0x7FFF) ? proposedJobSize + 0xFFFF : proposedJobSize; /* avoid too small last block */
  1116. const char* const srcStart = (const char*)src;
  1117. size_t remainingSrcSize = srcSize;
  1118. unsigned const compressWithinDst = (dstCapacity >= ZSTD_compressBound(srcSize)) ? nbJobs : (unsigned)(dstCapacity / ZSTD_compressBound(avgJobSize)); /* presumes avgJobSize >= 256 KB, which should be the case */
  1119. size_t frameStartPos = 0, dstBufferPos = 0;
  1120. assert(jobParams.nbWorkers == 0);
  1121. assert(mtctx->cctxPool->totalCCtx == params.nbWorkers);
  1122. params.jobSize = (U32)avgJobSize;
  1123. DEBUGLOG(4, "ZSTDMT_compress_advanced_internal: nbJobs=%2u (rawSize=%u bytes; fixedSize=%u) ",
  1124. nbJobs, (U32)proposedJobSize, (U32)avgJobSize);
  1125. if ((nbJobs==1) | (params.nbWorkers<=1)) { /* fallback to single-thread mode : this is a blocking invocation anyway */
  1126. ZSTD_CCtx* const cctx = mtctx->cctxPool->cctx[0];
  1127. DEBUGLOG(4, "ZSTDMT_compress_advanced_internal: fallback to single-thread mode");
  1128. if (cdict) return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, jobParams.fParams);
  1129. return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, NULL, 0, jobParams);
  1130. }
  1131. assert(avgJobSize >= 256 KB); /* condition for ZSTD_compressBound(A) + ZSTD_compressBound(B) <= ZSTD_compressBound(A+B), required to compress directly into Dst (no additional buffer) */
  1132. ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(avgJobSize) );
  1133. if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, avgJobSize))
  1134. return ERROR(memory_allocation);
  1135. CHECK_F( ZSTDMT_expandJobsTable(mtctx, nbJobs) ); /* only expands if necessary */
  1136. { unsigned u;
  1137. for (u=0; u<nbJobs; u++) {
  1138. size_t const jobSize = MIN(remainingSrcSize, avgJobSize);
  1139. size_t const dstBufferCapacity = ZSTD_compressBound(jobSize);
  1140. buffer_t const dstAsBuffer = { (char*)dst + dstBufferPos, dstBufferCapacity };
  1141. buffer_t const dstBuffer = u < compressWithinDst ? dstAsBuffer : g_nullBuffer;
  1142. size_t dictSize = u ? overlapSize : 0;
  1143. mtctx->jobs[u].prefix.start = srcStart + frameStartPos - dictSize;
  1144. mtctx->jobs[u].prefix.size = dictSize;
  1145. mtctx->jobs[u].src.start = srcStart + frameStartPos;
  1146. mtctx->jobs[u].src.size = jobSize; assert(jobSize > 0); /* avoid job.src.size == 0 */
  1147. mtctx->jobs[u].consumed = 0;
  1148. mtctx->jobs[u].cSize = 0;
  1149. mtctx->jobs[u].cdict = (u==0) ? cdict : NULL;
  1150. mtctx->jobs[u].fullFrameSize = srcSize;
  1151. mtctx->jobs[u].params = jobParams;
  1152. /* do not calculate checksum within sections, but write it in header for first section */
  1153. mtctx->jobs[u].dstBuff = dstBuffer;
  1154. mtctx->jobs[u].cctxPool = mtctx->cctxPool;
  1155. mtctx->jobs[u].bufPool = mtctx->bufPool;
  1156. mtctx->jobs[u].seqPool = mtctx->seqPool;
  1157. mtctx->jobs[u].serial = &mtctx->serial;
  1158. mtctx->jobs[u].jobID = u;
  1159. mtctx->jobs[u].firstJob = (u==0);
  1160. mtctx->jobs[u].lastJob = (u==nbJobs-1);
  1161. DEBUGLOG(5, "ZSTDMT_compress_advanced_internal: posting job %u (%u bytes)", u, (U32)jobSize);
  1162. DEBUG_PRINTHEX(6, mtctx->jobs[u].prefix.start, 12);
  1163. POOL_add(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[u]);
  1164. frameStartPos += jobSize;
  1165. dstBufferPos += dstBufferCapacity;
  1166. remainingSrcSize -= jobSize;
  1167. } }
  1168. /* collect result */
  1169. { size_t error = 0, dstPos = 0;
  1170. unsigned jobID;
  1171. for (jobID=0; jobID<nbJobs; jobID++) {
  1172. DEBUGLOG(5, "waiting for job %u ", jobID);
  1173. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
  1174. while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
  1175. DEBUGLOG(5, "waiting for jobCompleted signal from job %u", jobID);
  1176. ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
  1177. }
  1178. ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
  1179. DEBUGLOG(5, "ready to write job %u ", jobID);
  1180. { size_t const cSize = mtctx->jobs[jobID].cSize;
  1181. if (ZSTD_isError(cSize)) error = cSize;
  1182. if ((!error) && (dstPos + cSize > dstCapacity)) error = ERROR(dstSize_tooSmall);
  1183. if (jobID) { /* note : job 0 is written directly at dst, which is correct position */
  1184. if (!error)
  1185. memmove((char*)dst + dstPos, mtctx->jobs[jobID].dstBuff.start, cSize); /* may overlap when job compressed within dst */
  1186. if (jobID >= compressWithinDst) { /* job compressed into its own buffer, which must be released */
  1187. DEBUGLOG(5, "releasing buffer %u>=%u", jobID, compressWithinDst);
  1188. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
  1189. } }
  1190. mtctx->jobs[jobID].dstBuff = g_nullBuffer;
  1191. mtctx->jobs[jobID].cSize = 0;
  1192. dstPos += cSize ;
  1193. }
  1194. } /* for (jobID=0; jobID<nbJobs; jobID++) */
  1195. DEBUGLOG(4, "checksumFlag : %u ", params.fParams.checksumFlag);
  1196. if (params.fParams.checksumFlag) {
  1197. U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
  1198. if (dstPos + 4 > dstCapacity) {
  1199. error = ERROR(dstSize_tooSmall);
  1200. } else {
  1201. DEBUGLOG(4, "writing checksum : %08X \n", checksum);
  1202. MEM_writeLE32((char*)dst + dstPos, checksum);
  1203. dstPos += 4;
  1204. } }
  1205. if (!error) DEBUGLOG(4, "compressed size : %u ", (U32)dstPos);
  1206. return error ? error : dstPos;
  1207. }
  1208. }
  1209. size_t ZSTDMT_compress_advanced(ZSTDMT_CCtx* mtctx,
  1210. void* dst, size_t dstCapacity,
  1211. const void* src, size_t srcSize,
  1212. const ZSTD_CDict* cdict,
  1213. ZSTD_parameters params,
  1214. int overlapLog)
  1215. {
  1216. ZSTD_CCtx_params cctxParams = mtctx->params;
  1217. cctxParams.cParams = params.cParams;
  1218. cctxParams.fParams = params.fParams;
  1219. assert(ZSTD_OVERLAPLOG_MIN <= overlapLog && overlapLog <= ZSTD_OVERLAPLOG_MAX);
  1220. cctxParams.overlapLog = overlapLog;
  1221. return ZSTDMT_compress_advanced_internal(mtctx,
  1222. dst, dstCapacity,
  1223. src, srcSize,
  1224. cdict, cctxParams);
  1225. }
  1226. size_t ZSTDMT_compressCCtx(ZSTDMT_CCtx* mtctx,
  1227. void* dst, size_t dstCapacity,
  1228. const void* src, size_t srcSize,
  1229. int compressionLevel)
  1230. {
  1231. ZSTD_parameters params = ZSTD_getParams(compressionLevel, srcSize, 0);
  1232. int const overlapLog = ZSTDMT_overlapLog_default(params.cParams.strategy);
  1233. params.fParams.contentSizeFlag = 1;
  1234. return ZSTDMT_compress_advanced(mtctx, dst, dstCapacity, src, srcSize, NULL, params, overlapLog);
  1235. }
  1236. /* ====================================== */
  1237. /* ======= Streaming API ======= */
  1238. /* ====================================== */
  1239. size_t ZSTDMT_initCStream_internal(
  1240. ZSTDMT_CCtx* mtctx,
  1241. const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
  1242. const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
  1243. unsigned long long pledgedSrcSize)
  1244. {
  1245. DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
  1246. (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
  1247. /* params supposed partially fully validated at this point */
  1248. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  1249. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  1250. /* init */
  1251. if (params.nbWorkers != mtctx->params.nbWorkers)
  1252. CHECK_F( ZSTDMT_resize(mtctx, params.nbWorkers) );
  1253. if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
  1254. if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = ZSTDMT_JOBSIZE_MAX;
  1255. mtctx->singleBlockingThread = (pledgedSrcSize <= ZSTDMT_JOBSIZE_MIN); /* do not trigger multi-threading when srcSize is too small */
  1256. if (mtctx->singleBlockingThread) {
  1257. ZSTD_CCtx_params const singleThreadParams = ZSTDMT_initJobCCtxParams(params);
  1258. DEBUGLOG(5, "ZSTDMT_initCStream_internal: switch to single blocking thread mode");
  1259. assert(singleThreadParams.nbWorkers == 0);
  1260. return ZSTD_initCStream_internal(mtctx->cctxPool->cctx[0],
  1261. dict, dictSize, cdict,
  1262. singleThreadParams, pledgedSrcSize);
  1263. }
  1264. DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
  1265. if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */
  1266. ZSTDMT_waitForAllJobsCompleted(mtctx);
  1267. ZSTDMT_releaseAllJobResources(mtctx);
  1268. mtctx->allJobsCompleted = 1;
  1269. }
  1270. mtctx->params = params;
  1271. mtctx->frameContentSize = pledgedSrcSize;
  1272. if (dict) {
  1273. ZSTD_freeCDict(mtctx->cdictLocal);
  1274. mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  1275. ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
  1276. params.cParams, mtctx->cMem);
  1277. mtctx->cdict = mtctx->cdictLocal;
  1278. if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
  1279. } else {
  1280. ZSTD_freeCDict(mtctx->cdictLocal);
  1281. mtctx->cdictLocal = NULL;
  1282. mtctx->cdict = cdict;
  1283. }
  1284. mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(params);
  1285. DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
  1286. mtctx->targetSectionSize = params.jobSize;
  1287. if (mtctx->targetSectionSize == 0) {
  1288. mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(params);
  1289. }
  1290. if (params.rsyncable) {
  1291. /* Aim for the targetsectionSize as the average job size. */
  1292. U32 const jobSizeMB = (U32)(mtctx->targetSectionSize >> 20);
  1293. U32 const rsyncBits = ZSTD_highbit32(jobSizeMB) + 20;
  1294. assert(jobSizeMB >= 1);
  1295. DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
  1296. mtctx->rsync.hash = 0;
  1297. mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
  1298. mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
  1299. }
  1300. if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */
  1301. DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
  1302. DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
  1303. ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
  1304. {
  1305. /* If ldm is enabled we need windowSize space. */
  1306. size_t const windowSize = mtctx->params.ldmParams.enableLdm ? (1U << mtctx->params.cParams.windowLog) : 0;
  1307. /* Two buffers of slack, plus extra space for the overlap
  1308. * This is the minimum slack that LDM works with. One extra because
  1309. * flush might waste up to targetSectionSize-1 bytes. Another extra
  1310. * for the overlap (if > 0), then one to fill which doesn't overlap
  1311. * with the LDM window.
  1312. */
  1313. size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
  1314. size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
  1315. /* Compute the total size, and always have enough slack */
  1316. size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
  1317. size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
  1318. size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
  1319. if (mtctx->roundBuff.capacity < capacity) {
  1320. if (mtctx->roundBuff.buffer)
  1321. ZSTD_free(mtctx->roundBuff.buffer, mtctx->cMem);
  1322. mtctx->roundBuff.buffer = (BYTE*)ZSTD_malloc(capacity, mtctx->cMem);
  1323. if (mtctx->roundBuff.buffer == NULL) {
  1324. mtctx->roundBuff.capacity = 0;
  1325. return ERROR(memory_allocation);
  1326. }
  1327. mtctx->roundBuff.capacity = capacity;
  1328. }
  1329. }
  1330. DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
  1331. mtctx->roundBuff.pos = 0;
  1332. mtctx->inBuff.buffer = g_nullBuffer;
  1333. mtctx->inBuff.filled = 0;
  1334. mtctx->inBuff.prefix = kNullRange;
  1335. mtctx->doneJobID = 0;
  1336. mtctx->nextJobID = 0;
  1337. mtctx->frameEnded = 0;
  1338. mtctx->allJobsCompleted = 0;
  1339. mtctx->consumed = 0;
  1340. mtctx->produced = 0;
  1341. if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize))
  1342. return ERROR(memory_allocation);
  1343. return 0;
  1344. }
  1345. size_t ZSTDMT_initCStream_advanced(ZSTDMT_CCtx* mtctx,
  1346. const void* dict, size_t dictSize,
  1347. ZSTD_parameters params,
  1348. unsigned long long pledgedSrcSize)
  1349. {
  1350. ZSTD_CCtx_params cctxParams = mtctx->params; /* retrieve sticky params */
  1351. DEBUGLOG(4, "ZSTDMT_initCStream_advanced (pledgedSrcSize=%u)", (U32)pledgedSrcSize);
  1352. cctxParams.cParams = params.cParams;
  1353. cctxParams.fParams = params.fParams;
  1354. return ZSTDMT_initCStream_internal(mtctx, dict, dictSize, ZSTD_dct_auto, NULL,
  1355. cctxParams, pledgedSrcSize);
  1356. }
  1357. size_t ZSTDMT_initCStream_usingCDict(ZSTDMT_CCtx* mtctx,
  1358. const ZSTD_CDict* cdict,
  1359. ZSTD_frameParameters fParams,
  1360. unsigned long long pledgedSrcSize)
  1361. {
  1362. ZSTD_CCtx_params cctxParams = mtctx->params;
  1363. if (cdict==NULL) return ERROR(dictionary_wrong); /* method incompatible with NULL cdict */
  1364. cctxParams.cParams = ZSTD_getCParamsFromCDict(cdict);
  1365. cctxParams.fParams = fParams;
  1366. return ZSTDMT_initCStream_internal(mtctx, NULL, 0 /*dictSize*/, ZSTD_dct_auto, cdict,
  1367. cctxParams, pledgedSrcSize);
  1368. }
  1369. /* ZSTDMT_resetCStream() :
  1370. * pledgedSrcSize can be zero == unknown (for the time being)
  1371. * prefer using ZSTD_CONTENTSIZE_UNKNOWN,
  1372. * as `0` might mean "empty" in the future */
  1373. size_t ZSTDMT_resetCStream(ZSTDMT_CCtx* mtctx, unsigned long long pledgedSrcSize)
  1374. {
  1375. if (!pledgedSrcSize) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
  1376. return ZSTDMT_initCStream_internal(mtctx, NULL, 0, ZSTD_dct_auto, 0, mtctx->params,
  1377. pledgedSrcSize);
  1378. }
  1379. size_t ZSTDMT_initCStream(ZSTDMT_CCtx* mtctx, int compressionLevel) {
  1380. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0);
  1381. ZSTD_CCtx_params cctxParams = mtctx->params; /* retrieve sticky params */
  1382. DEBUGLOG(4, "ZSTDMT_initCStream (cLevel=%i)", compressionLevel);
  1383. cctxParams.cParams = params.cParams;
  1384. cctxParams.fParams = params.fParams;
  1385. return ZSTDMT_initCStream_internal(mtctx, NULL, 0, ZSTD_dct_auto, NULL, cctxParams, ZSTD_CONTENTSIZE_UNKNOWN);
  1386. }
  1387. /* ZSTDMT_writeLastEmptyBlock()
  1388. * Write a single empty block with an end-of-frame to finish a frame.
  1389. * Job must be created from streaming variant.
  1390. * This function is always successfull if expected conditions are fulfilled.
  1391. */
  1392. static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)
  1393. {
  1394. assert(job->lastJob == 1);
  1395. assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */
  1396. assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */
  1397. assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
  1398. job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
  1399. if (job->dstBuff.start == NULL) {
  1400. job->cSize = ERROR(memory_allocation);
  1401. return;
  1402. }
  1403. assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */
  1404. job->src = kNullRange;
  1405. job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);
  1406. assert(!ZSTD_isError(job->cSize));
  1407. assert(job->consumed == 0);
  1408. }
  1409. static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)
  1410. {
  1411. unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
  1412. int const endFrame = (endOp == ZSTD_e_end);
  1413. if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
  1414. DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
  1415. assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
  1416. return 0;
  1417. }
  1418. if (!mtctx->jobReady) {
  1419. BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
  1420. DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
  1421. mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
  1422. mtctx->jobs[jobID].src.start = src;
  1423. mtctx->jobs[jobID].src.size = srcSize;
  1424. assert(mtctx->inBuff.filled >= srcSize);
  1425. mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
  1426. mtctx->jobs[jobID].consumed = 0;
  1427. mtctx->jobs[jobID].cSize = 0;
  1428. mtctx->jobs[jobID].params = mtctx->params;
  1429. mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
  1430. mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
  1431. mtctx->jobs[jobID].dstBuff = g_nullBuffer;
  1432. mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
  1433. mtctx->jobs[jobID].bufPool = mtctx->bufPool;
  1434. mtctx->jobs[jobID].seqPool = mtctx->seqPool;
  1435. mtctx->jobs[jobID].serial = &mtctx->serial;
  1436. mtctx->jobs[jobID].jobID = mtctx->nextJobID;
  1437. mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
  1438. mtctx->jobs[jobID].lastJob = endFrame;
  1439. mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
  1440. mtctx->jobs[jobID].dstFlushed = 0;
  1441. /* Update the round buffer pos and clear the input buffer to be reset */
  1442. mtctx->roundBuff.pos += srcSize;
  1443. mtctx->inBuff.buffer = g_nullBuffer;
  1444. mtctx->inBuff.filled = 0;
  1445. /* Set the prefix */
  1446. if (!endFrame) {
  1447. size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
  1448. mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
  1449. mtctx->inBuff.prefix.size = newPrefixSize;
  1450. } else { /* endFrame==1 => no need for another input buffer */
  1451. mtctx->inBuff.prefix = kNullRange;
  1452. mtctx->frameEnded = endFrame;
  1453. if (mtctx->nextJobID == 0) {
  1454. /* single job exception : checksum is already calculated directly within worker thread */
  1455. mtctx->params.fParams.checksumFlag = 0;
  1456. } }
  1457. if ( (srcSize == 0)
  1458. && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
  1459. DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
  1460. assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */
  1461. ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
  1462. mtctx->nextJobID++;
  1463. return 0;
  1464. }
  1465. }
  1466. DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",
  1467. mtctx->nextJobID,
  1468. (U32)mtctx->jobs[jobID].src.size,
  1469. mtctx->jobs[jobID].lastJob,
  1470. mtctx->nextJobID,
  1471. jobID);
  1472. if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
  1473. mtctx->nextJobID++;
  1474. mtctx->jobReady = 0;
  1475. } else {
  1476. DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);
  1477. mtctx->jobReady = 1;
  1478. }
  1479. return 0;
  1480. }
  1481. /*! ZSTDMT_flushProduced() :
  1482. * flush whatever data has been produced but not yet flushed in current job.
  1483. * move to next job if current one is fully flushed.
  1484. * `output` : `pos` will be updated with amount of data flushed .
  1485. * `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .
  1486. * @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */
  1487. static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)
  1488. {
  1489. unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
  1490. DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
  1491. blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
  1492. assert(output->size >= output->pos);
  1493. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
  1494. if ( blockToFlush
  1495. && (mtctx->doneJobID < mtctx->nextJobID) ) {
  1496. assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
  1497. while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */
  1498. if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
  1499. DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
  1500. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
  1501. break;
  1502. }
  1503. DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
  1504. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
  1505. ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */
  1506. } }
  1507. /* try to flush something */
  1508. { size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */
  1509. size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */
  1510. size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */
  1511. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1512. if (ZSTD_isError(cSize)) {
  1513. DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
  1514. mtctx->doneJobID, ZSTD_getErrorName(cSize));
  1515. ZSTDMT_waitForAllJobsCompleted(mtctx);
  1516. ZSTDMT_releaseAllJobResources(mtctx);
  1517. return cSize;
  1518. }
  1519. /* add frame checksum if necessary (can only happen once) */
  1520. assert(srcConsumed <= srcSize);
  1521. if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */
  1522. && mtctx->jobs[wJobID].frameChecksumNeeded ) {
  1523. U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
  1524. DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
  1525. MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
  1526. cSize += 4;
  1527. mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */
  1528. mtctx->jobs[wJobID].frameChecksumNeeded = 0;
  1529. }
  1530. if (cSize > 0) { /* compression is ongoing or completed */
  1531. size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
  1532. DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
  1533. (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
  1534. assert(mtctx->doneJobID < mtctx->nextJobID);
  1535. assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
  1536. assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
  1537. memcpy((char*)output->dst + output->pos,
  1538. (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
  1539. toFlush);
  1540. output->pos += toFlush;
  1541. mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */
  1542. if ( (srcConsumed == srcSize) /* job is completed */
  1543. && (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */
  1544. DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
  1545. mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
  1546. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
  1547. DEBUGLOG(5, "dstBuffer released");
  1548. mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
  1549. mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */
  1550. mtctx->consumed += srcSize;
  1551. mtctx->produced += cSize;
  1552. mtctx->doneJobID++;
  1553. } }
  1554. /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
  1555. if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
  1556. if (srcSize > srcConsumed) return 1; /* current job not completely compressed */
  1557. }
  1558. if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */
  1559. if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */
  1560. if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */
  1561. mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */
  1562. if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */
  1563. return 0; /* internal buffers fully flushed */
  1564. }
  1565. /**
  1566. * Returns the range of data used by the earliest job that is not yet complete.
  1567. * If the data of the first job is broken up into two segments, we cover both
  1568. * sections.
  1569. */
  1570. static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)
  1571. {
  1572. unsigned const firstJobID = mtctx->doneJobID;
  1573. unsigned const lastJobID = mtctx->nextJobID;
  1574. unsigned jobID;
  1575. for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
  1576. unsigned const wJobID = jobID & mtctx->jobIDMask;
  1577. size_t consumed;
  1578. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
  1579. consumed = mtctx->jobs[wJobID].consumed;
  1580. ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
  1581. if (consumed < mtctx->jobs[wJobID].src.size) {
  1582. range_t range = mtctx->jobs[wJobID].prefix;
  1583. if (range.size == 0) {
  1584. /* Empty prefix */
  1585. range = mtctx->jobs[wJobID].src;
  1586. }
  1587. /* Job source in multiple segments not supported yet */
  1588. assert(range.start <= mtctx->jobs[wJobID].src.start);
  1589. return range;
  1590. }
  1591. }
  1592. return kNullRange;
  1593. }
  1594. /**
  1595. * Returns non-zero iff buffer and range overlap.
  1596. */
  1597. static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
  1598. {
  1599. BYTE const* const bufferStart = (BYTE const*)buffer.start;
  1600. BYTE const* const bufferEnd = bufferStart + buffer.capacity;
  1601. BYTE const* const rangeStart = (BYTE const*)range.start;
  1602. BYTE const* const rangeEnd = rangeStart + range.size;
  1603. if (rangeStart == NULL || bufferStart == NULL)
  1604. return 0;
  1605. /* Empty ranges cannot overlap */
  1606. if (bufferStart == bufferEnd || rangeStart == rangeEnd)
  1607. return 0;
  1608. return bufferStart < rangeEnd && rangeStart < bufferEnd;
  1609. }
  1610. static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)
  1611. {
  1612. range_t extDict;
  1613. range_t prefix;
  1614. DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
  1615. extDict.start = window.dictBase + window.lowLimit;
  1616. extDict.size = window.dictLimit - window.lowLimit;
  1617. prefix.start = window.base + window.dictLimit;
  1618. prefix.size = window.nextSrc - (window.base + window.dictLimit);
  1619. DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
  1620. (size_t)extDict.start,
  1621. (size_t)extDict.start + extDict.size);
  1622. DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",
  1623. (size_t)prefix.start,
  1624. (size_t)prefix.start + prefix.size);
  1625. return ZSTDMT_isOverlapped(buffer, extDict)
  1626. || ZSTDMT_isOverlapped(buffer, prefix);
  1627. }
  1628. static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)
  1629. {
  1630. if (mtctx->params.ldmParams.enableLdm) {
  1631. ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
  1632. DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
  1633. DEBUGLOG(5, "source [0x%zx, 0x%zx)",
  1634. (size_t)buffer.start,
  1635. (size_t)buffer.start + buffer.capacity);
  1636. ZSTD_PTHREAD_MUTEX_LOCK(mutex);
  1637. while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {
  1638. DEBUGLOG(5, "Waiting for LDM to finish...");
  1639. ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);
  1640. }
  1641. DEBUGLOG(6, "Done waiting for LDM to finish");
  1642. ZSTD_pthread_mutex_unlock(mutex);
  1643. }
  1644. }
  1645. /**
  1646. * Attempts to set the inBuff to the next section to fill.
  1647. * If any part of the new section is still in use we give up.
  1648. * Returns non-zero if the buffer is filled.
  1649. */
  1650. static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)
  1651. {
  1652. range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
  1653. size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
  1654. size_t const target = mtctx->targetSectionSize;
  1655. buffer_t buffer;
  1656. DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
  1657. assert(mtctx->inBuff.buffer.start == NULL);
  1658. assert(mtctx->roundBuff.capacity >= target);
  1659. if (spaceLeft < target) {
  1660. /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
  1661. * Simply copy the prefix to the beginning in that case.
  1662. */
  1663. BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
  1664. size_t const prefixSize = mtctx->inBuff.prefix.size;
  1665. buffer.start = start;
  1666. buffer.capacity = prefixSize;
  1667. if (ZSTDMT_isOverlapped(buffer, inUse)) {
  1668. DEBUGLOG(5, "Waiting for buffer...");
  1669. return 0;
  1670. }
  1671. ZSTDMT_waitForLdmComplete(mtctx, buffer);
  1672. memmove(start, mtctx->inBuff.prefix.start, prefixSize);
  1673. mtctx->inBuff.prefix.start = start;
  1674. mtctx->roundBuff.pos = prefixSize;
  1675. }
  1676. buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
  1677. buffer.capacity = target;
  1678. if (ZSTDMT_isOverlapped(buffer, inUse)) {
  1679. DEBUGLOG(5, "Waiting for buffer...");
  1680. return 0;
  1681. }
  1682. assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
  1683. ZSTDMT_waitForLdmComplete(mtctx, buffer);
  1684. DEBUGLOG(5, "Using prefix range [%zx, %zx)",
  1685. (size_t)mtctx->inBuff.prefix.start,
  1686. (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
  1687. DEBUGLOG(5, "Using source range [%zx, %zx)",
  1688. (size_t)buffer.start,
  1689. (size_t)buffer.start + buffer.capacity);
  1690. mtctx->inBuff.buffer = buffer;
  1691. mtctx->inBuff.filled = 0;
  1692. assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);
  1693. return 1;
  1694. }
  1695. typedef struct {
  1696. size_t toLoad; /* The number of bytes to load from the input. */
  1697. int flush; /* Boolean declaring if we must flush because we found a synchronization point. */
  1698. } syncPoint_t;
  1699. /**
  1700. * Searches through the input for a synchronization point. If one is found, we
  1701. * will instruct the caller to flush, and return the number of bytes to load.
  1702. * Otherwise, we will load as many bytes as possible and instruct the caller
  1703. * to continue as normal.
  1704. */
  1705. static syncPoint_t
  1706. findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)
  1707. {
  1708. BYTE const* const istart = (BYTE const*)input.src + input.pos;
  1709. U64 const primePower = mtctx->rsync.primePower;
  1710. U64 const hitMask = mtctx->rsync.hitMask;
  1711. syncPoint_t syncPoint;
  1712. U64 hash;
  1713. BYTE const* prev;
  1714. size_t pos;
  1715. syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
  1716. syncPoint.flush = 0;
  1717. if (!mtctx->params.rsyncable)
  1718. /* Rsync is disabled. */
  1719. return syncPoint;
  1720. if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
  1721. /* Not enough to compute the hash.
  1722. * We will miss any synchronization points in this RSYNC_LENGTH byte
  1723. * window. However, since it depends only in the internal buffers, if the
  1724. * state is already synchronized, we will remain synchronized.
  1725. * Additionally, the probability that we miss a synchronization point is
  1726. * low: RSYNC_LENGTH / targetSectionSize.
  1727. */
  1728. return syncPoint;
  1729. /* Initialize the loop variables. */
  1730. if (mtctx->inBuff.filled >= RSYNC_LENGTH) {
  1731. /* We have enough bytes buffered to initialize the hash.
  1732. * Start scanning at the beginning of the input.
  1733. */
  1734. pos = 0;
  1735. prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
  1736. hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
  1737. } else {
  1738. /* We don't have enough bytes buffered to initialize the hash, but
  1739. * we know we have at least RSYNC_LENGTH bytes total.
  1740. * Start scanning after the first RSYNC_LENGTH bytes less the bytes
  1741. * already buffered.
  1742. */
  1743. pos = RSYNC_LENGTH - mtctx->inBuff.filled;
  1744. prev = (BYTE const*)mtctx->inBuff.buffer.start - pos;
  1745. hash = ZSTD_rollingHash_compute(mtctx->inBuff.buffer.start, mtctx->inBuff.filled);
  1746. hash = ZSTD_rollingHash_append(hash, istart, pos);
  1747. }
  1748. /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
  1749. * through the input. If we hit a synchronization point, then cut the
  1750. * job off, and tell the compressor to flush the job. Otherwise, load
  1751. * all the bytes and continue as normal.
  1752. * If we go too long without a synchronization point (targetSectionSize)
  1753. * then a block will be emitted anyways, but this is okay, since if we
  1754. * are already synchronized we will remain synchronized.
  1755. */
  1756. for (; pos < syncPoint.toLoad; ++pos) {
  1757. BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
  1758. /* if (pos >= RSYNC_LENGTH) assert(ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash); */
  1759. hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
  1760. if ((hash & hitMask) == hitMask) {
  1761. syncPoint.toLoad = pos + 1;
  1762. syncPoint.flush = 1;
  1763. break;
  1764. }
  1765. }
  1766. return syncPoint;
  1767. }
  1768. size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)
  1769. {
  1770. size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;
  1771. if (hintInSize==0) hintInSize = mtctx->targetSectionSize;
  1772. return hintInSize;
  1773. }
  1774. /** ZSTDMT_compressStream_generic() :
  1775. * internal use only - exposed to be invoked from zstd_compress.c
  1776. * assumption : output and input are valid (pos <= size)
  1777. * @return : minimum amount of data remaining to flush, 0 if none */
  1778. size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
  1779. ZSTD_outBuffer* output,
  1780. ZSTD_inBuffer* input,
  1781. ZSTD_EndDirective endOp)
  1782. {
  1783. unsigned forwardInputProgress = 0;
  1784. DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
  1785. (U32)endOp, (U32)(input->size - input->pos));
  1786. assert(output->pos <= output->size);
  1787. assert(input->pos <= input->size);
  1788. if (mtctx->singleBlockingThread) { /* delegate to single-thread (synchronous) */
  1789. return ZSTD_compressStream_generic(mtctx->cctxPool->cctx[0], output, input, endOp);
  1790. }
  1791. if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
  1792. /* current frame being ended. Only flush/end are allowed */
  1793. return ERROR(stage_wrong);
  1794. }
  1795. /* single-pass shortcut (note : synchronous-mode) */
  1796. if ( (!mtctx->params.rsyncable) /* rsyncable mode is disabled */
  1797. && (mtctx->nextJobID == 0) /* just started */
  1798. && (mtctx->inBuff.filled == 0) /* nothing buffered */
  1799. && (!mtctx->jobReady) /* no job already created */
  1800. && (endOp == ZSTD_e_end) /* end order */
  1801. && (output->size - output->pos >= ZSTD_compressBound(input->size - input->pos)) ) { /* enough space in dst */
  1802. size_t const cSize = ZSTDMT_compress_advanced_internal(mtctx,
  1803. (char*)output->dst + output->pos, output->size - output->pos,
  1804. (const char*)input->src + input->pos, input->size - input->pos,
  1805. mtctx->cdict, mtctx->params);
  1806. if (ZSTD_isError(cSize)) return cSize;
  1807. input->pos = input->size;
  1808. output->pos += cSize;
  1809. mtctx->allJobsCompleted = 1;
  1810. mtctx->frameEnded = 1;
  1811. return 0;
  1812. }
  1813. /* fill input buffer */
  1814. if ( (!mtctx->jobReady)
  1815. && (input->size > input->pos) ) { /* support NULL input */
  1816. if (mtctx->inBuff.buffer.start == NULL) {
  1817. assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
  1818. if (!ZSTDMT_tryGetInputRange(mtctx)) {
  1819. /* It is only possible for this operation to fail if there are
  1820. * still compression jobs ongoing.
  1821. */
  1822. DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
  1823. assert(mtctx->doneJobID != mtctx->nextJobID);
  1824. } else
  1825. DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
  1826. }
  1827. if (mtctx->inBuff.buffer.start != NULL) {
  1828. syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
  1829. if (syncPoint.flush && endOp == ZSTD_e_continue) {
  1830. endOp = ZSTD_e_flush;
  1831. }
  1832. assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
  1833. DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
  1834. (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
  1835. memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
  1836. input->pos += syncPoint.toLoad;
  1837. mtctx->inBuff.filled += syncPoint.toLoad;
  1838. forwardInputProgress = syncPoint.toLoad>0;
  1839. }
  1840. if ((input->pos < input->size) && (endOp == ZSTD_e_end))
  1841. endOp = ZSTD_e_flush; /* can't end now : not all input consumed */
  1842. }
  1843. if ( (mtctx->jobReady)
  1844. || (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */
  1845. || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */
  1846. || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */
  1847. size_t const jobSize = mtctx->inBuff.filled;
  1848. assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
  1849. CHECK_F( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) );
  1850. }
  1851. /* check for potential compressed data ready to be flushed */
  1852. { size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */
  1853. if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */
  1854. DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);
  1855. return remainingToFlush;
  1856. }
  1857. }
  1858. size_t ZSTDMT_compressStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  1859. {
  1860. CHECK_F( ZSTDMT_compressStream_generic(mtctx, output, input, ZSTD_e_continue) );
  1861. /* recommended next input size : fill current input buffer */
  1862. return mtctx->targetSectionSize - mtctx->inBuff.filled; /* note : could be zero when input buffer is fully filled and no more availability to create new job */
  1863. }
  1864. static size_t ZSTDMT_flushStream_internal(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, ZSTD_EndDirective endFrame)
  1865. {
  1866. size_t const srcSize = mtctx->inBuff.filled;
  1867. DEBUGLOG(5, "ZSTDMT_flushStream_internal");
  1868. if ( mtctx->jobReady /* one job ready for a worker to pick up */
  1869. || (srcSize > 0) /* still some data within input buffer */
  1870. || ((endFrame==ZSTD_e_end) && !mtctx->frameEnded)) { /* need a last 0-size block to end frame */
  1871. DEBUGLOG(5, "ZSTDMT_flushStream_internal : create a new job (%u bytes, end:%u)",
  1872. (U32)srcSize, (U32)endFrame);
  1873. CHECK_F( ZSTDMT_createCompressionJob(mtctx, srcSize, endFrame) );
  1874. }
  1875. /* check if there is any data available to flush */
  1876. return ZSTDMT_flushProduced(mtctx, output, 1 /* blockToFlush */, endFrame);
  1877. }
  1878. size_t ZSTDMT_flushStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output)
  1879. {
  1880. DEBUGLOG(5, "ZSTDMT_flushStream");
  1881. if (mtctx->singleBlockingThread)
  1882. return ZSTD_flushStream(mtctx->cctxPool->cctx[0], output);
  1883. return ZSTDMT_flushStream_internal(mtctx, output, ZSTD_e_flush);
  1884. }
  1885. size_t ZSTDMT_endStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output)
  1886. {
  1887. DEBUGLOG(4, "ZSTDMT_endStream");
  1888. if (mtctx->singleBlockingThread)
  1889. return ZSTD_endStream(mtctx->cctxPool->cctx[0], output);
  1890. return ZSTDMT_flushStream_internal(mtctx, output, ZSTD_e_end);
  1891. }