zstdmt_compress.c 79 KB

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