zstdmt_compress.c 76 KB

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