zstdmt_compress.c 90 KB

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