zstdmt_compress.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. /*
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /* ====== Tuning parameters ====== */
  11. #define ZSTDMT_NBTHREADS_MAX 200
  12. #define ZSTDMT_OVERLAPLOG_DEFAULT 6
  13. /* ====== Compiler specifics ====== */
  14. #if defined(_MSC_VER)
  15. # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
  16. #endif
  17. /* ====== Dependencies ====== */
  18. #include <string.h> /* memcpy, memset */
  19. #include "pool.h" /* threadpool */
  20. #include "threading.h" /* mutex */
  21. #include "zstd_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
  22. #include "zstdmt_compress.h"
  23. /* ====== Debug ====== */
  24. #if defined(ZSTD_DEBUG) && (ZSTD_DEBUG>=2)
  25. # include <stdio.h>
  26. # include <unistd.h>
  27. # include <sys/times.h>
  28. # define DEBUGLOGRAW(l, ...) if (l<=ZSTD_DEBUG) { fprintf(stderr, __VA_ARGS__); }
  29. # define DEBUG_PRINTHEX(l,p,n) { \
  30. unsigned debug_u; \
  31. for (debug_u=0; debug_u<(n); debug_u++) \
  32. DEBUGLOGRAW(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
  33. DEBUGLOGRAW(l, " \n"); \
  34. }
  35. static unsigned long long GetCurrentClockTimeMicroseconds(void)
  36. {
  37. static clock_t _ticksPerSecond = 0;
  38. if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);
  39. { struct tms junk; clock_t newTicks = (clock_t) times(&junk);
  40. return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond); }
  41. }
  42. #define MUTEX_WAIT_TIME_DLEVEL 6
  43. #define ZSTD_PTHREAD_MUTEX_LOCK(mutex) { \
  44. if (ZSTD_DEBUG >= MUTEX_WAIT_TIME_DLEVEL) { \
  45. unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \
  46. ZSTD_pthread_mutex_lock(mutex); \
  47. { unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
  48. unsigned long long const elapsedTime = (afterTime-beforeTime); \
  49. if (elapsedTime > 1000) { /* or whatever threshold you like; I'm using 1 millisecond here */ \
  50. DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \
  51. elapsedTime, #mutex); \
  52. } } \
  53. } else { \
  54. ZSTD_pthread_mutex_lock(mutex); \
  55. } \
  56. }
  57. #else
  58. # define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)
  59. # define DEBUG_PRINTHEX(l,p,n) {}
  60. #endif
  61. /* ===== Buffer Pool ===== */
  62. /* a single Buffer Pool can be invoked from multiple threads in parallel */
  63. typedef struct buffer_s {
  64. void* start;
  65. size_t size;
  66. } buffer_t;
  67. static const buffer_t g_nullBuffer = { NULL, 0 };
  68. typedef struct ZSTDMT_bufferPool_s {
  69. ZSTD_pthread_mutex_t poolMutex;
  70. size_t bufferSize;
  71. unsigned totalBuffers;
  72. unsigned nbBuffers;
  73. ZSTD_customMem cMem;
  74. buffer_t bTable[1]; /* variable size */
  75. } ZSTDMT_bufferPool;
  76. static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned nbThreads, ZSTD_customMem cMem)
  77. {
  78. unsigned const maxNbBuffers = 2*nbThreads + 3;
  79. ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_calloc(
  80. sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);
  81. if (bufPool==NULL) return NULL;
  82. if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
  83. ZSTD_free(bufPool, cMem);
  84. return NULL;
  85. }
  86. bufPool->bufferSize = 64 KB;
  87. bufPool->totalBuffers = maxNbBuffers;
  88. bufPool->nbBuffers = 0;
  89. bufPool->cMem = cMem;
  90. return bufPool;
  91. }
  92. static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
  93. {
  94. unsigned u;
  95. DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
  96. if (!bufPool) return; /* compatibility with free on NULL */
  97. for (u=0; u<bufPool->totalBuffers; u++) {
  98. DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);
  99. ZSTD_free(bufPool->bTable[u].start, bufPool->cMem);
  100. }
  101. ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
  102. ZSTD_free(bufPool, bufPool->cMem);
  103. }
  104. /* only works at initialization, not during compression */
  105. static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)
  106. {
  107. size_t const poolSize = sizeof(*bufPool)
  108. + (bufPool->totalBuffers - 1) * sizeof(buffer_t);
  109. unsigned u;
  110. size_t totalBufferSize = 0;
  111. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  112. for (u=0; u<bufPool->totalBuffers; u++)
  113. totalBufferSize += bufPool->bTable[u].size;
  114. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  115. return poolSize + totalBufferSize;
  116. }
  117. static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* bufPool, size_t bSize)
  118. {
  119. bufPool->bufferSize = bSize;
  120. }
  121. /** ZSTDMT_getBuffer() :
  122. * assumption : bufPool must be valid */
  123. static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)
  124. {
  125. size_t const bSize = bufPool->bufferSize;
  126. DEBUGLOG(5, "ZSTDMT_getBuffer");
  127. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  128. if (bufPool->nbBuffers) { /* try to use an existing buffer */
  129. buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];
  130. size_t const availBufferSize = buf.size;
  131. bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;
  132. if ((availBufferSize >= bSize) & (availBufferSize <= 10*bSize)) {
  133. /* large enough, but not too much */
  134. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  135. return buf;
  136. }
  137. /* size conditions not respected : scratch this buffer, create new one */
  138. DEBUGLOG(5, "existing buffer does not meet size conditions => freeing");
  139. ZSTD_free(buf.start, bufPool->cMem);
  140. }
  141. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  142. /* create new buffer */
  143. DEBUGLOG(5, "create a new buffer");
  144. { buffer_t buffer;
  145. void* const start = ZSTD_malloc(bSize, bufPool->cMem);
  146. buffer.start = start; /* note : start can be NULL if malloc fails ! */
  147. buffer.size = (start==NULL) ? 0 : bSize;
  148. return buffer;
  149. }
  150. }
  151. /* store buffer for later re-use, up to pool capacity */
  152. static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
  153. {
  154. if (buf.start == NULL) return; /* compatible with release on NULL */
  155. DEBUGLOG(5, "ZSTDMT_releaseBuffer");
  156. ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
  157. if (bufPool->nbBuffers < bufPool->totalBuffers) {
  158. bufPool->bTable[bufPool->nbBuffers++] = buf; /* stored for later use */
  159. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  160. return;
  161. }
  162. ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
  163. /* Reached bufferPool capacity (should not happen) */
  164. DEBUGLOG(5, "buffer pool capacity reached => freeing ");
  165. ZSTD_free(buf.start, bufPool->cMem);
  166. }
  167. /* Sets parameters relevant to the compression job, initializing others to
  168. * default values. Notably, nbThreads should probably be zero. */
  169. static ZSTD_CCtx_params ZSTDMT_makeJobCCtxParams(ZSTD_CCtx_params const params)
  170. {
  171. ZSTD_CCtx_params jobParams;
  172. memset(&jobParams, 0, sizeof(jobParams));
  173. jobParams.cParams = params.cParams;
  174. jobParams.fParams = params.fParams;
  175. jobParams.compressionLevel = params.compressionLevel;
  176. jobParams.ldmParams = params.ldmParams;
  177. return jobParams;
  178. }
  179. /* ===== CCtx Pool ===== */
  180. /* a single CCtx Pool can be invoked from multiple threads in parallel */
  181. typedef struct {
  182. ZSTD_pthread_mutex_t poolMutex;
  183. unsigned totalCCtx;
  184. unsigned availCCtx;
  185. ZSTD_customMem cMem;
  186. ZSTD_CCtx* cctx[1]; /* variable size */
  187. } ZSTDMT_CCtxPool;
  188. /* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
  189. static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
  190. {
  191. unsigned u;
  192. for (u=0; u<pool->totalCCtx; u++)
  193. ZSTD_freeCCtx(pool->cctx[u]); /* note : compatible with free on NULL */
  194. ZSTD_pthread_mutex_destroy(&pool->poolMutex);
  195. ZSTD_free(pool, pool->cMem);
  196. }
  197. /* ZSTDMT_createCCtxPool() :
  198. * implies nbThreads >= 1 , checked by caller ZSTDMT_createCCtx() */
  199. static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(unsigned nbThreads,
  200. ZSTD_customMem cMem)
  201. {
  202. ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_calloc(
  203. sizeof(ZSTDMT_CCtxPool) + (nbThreads-1)*sizeof(ZSTD_CCtx*), cMem);
  204. if (!cctxPool) return NULL;
  205. if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
  206. ZSTD_free(cctxPool, cMem);
  207. return NULL;
  208. }
  209. cctxPool->cMem = cMem;
  210. cctxPool->totalCCtx = nbThreads;
  211. cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
  212. cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
  213. if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
  214. DEBUGLOG(3, "cctxPool created, with %u threads", nbThreads);
  215. return cctxPool;
  216. }
  217. /* only works during initialization phase, not during compression */
  218. static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
  219. {
  220. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  221. { unsigned const nbThreads = cctxPool->totalCCtx;
  222. size_t const poolSize = sizeof(*cctxPool)
  223. + (nbThreads-1)*sizeof(ZSTD_CCtx*);
  224. unsigned u;
  225. size_t totalCCtxSize = 0;
  226. for (u=0; u<nbThreads; u++) {
  227. totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);
  228. }
  229. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  230. return poolSize + totalCCtxSize;
  231. }
  232. }
  233. static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
  234. {
  235. DEBUGLOG(5, "ZSTDMT_getCCtx");
  236. ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
  237. if (cctxPool->availCCtx) {
  238. cctxPool->availCCtx--;
  239. { ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
  240. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  241. return cctx;
  242. } }
  243. ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
  244. DEBUGLOG(5, "create one more CCtx");
  245. return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */
  246. }
  247. static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
  248. {
  249. if (cctx==NULL) return; /* compatibility with release on NULL */
  250. ZSTD_pthread_mutex_lock(&pool->poolMutex);
  251. if (pool->availCCtx < pool->totalCCtx)
  252. pool->cctx[pool->availCCtx++] = cctx;
  253. else {
  254. /* pool overflow : should not happen, since totalCCtx==nbThreads */
  255. DEBUGLOG(5, "CCtx pool overflow : free cctx");
  256. ZSTD_freeCCtx(cctx);
  257. }
  258. ZSTD_pthread_mutex_unlock(&pool->poolMutex);
  259. }
  260. /* ===== Thread worker ===== */
  261. typedef struct {
  262. buffer_t src;
  263. const void* srcStart;
  264. size_t dictSize;
  265. size_t srcSize;
  266. buffer_t dstBuff;
  267. size_t cSize;
  268. size_t dstFlushed;
  269. unsigned firstChunk;
  270. unsigned lastChunk;
  271. unsigned jobCompleted;
  272. unsigned jobScanned;
  273. ZSTD_pthread_mutex_t* jobCompleted_mutex;
  274. ZSTD_pthread_cond_t* jobCompleted_cond;
  275. ZSTD_CCtx_params params;
  276. const ZSTD_CDict* cdict;
  277. ZSTDMT_CCtxPool* cctxPool;
  278. ZSTDMT_bufferPool* bufPool;
  279. unsigned long long fullFrameSize;
  280. } ZSTDMT_jobDescription;
  281. /* ZSTDMT_compressChunk() : POOL_function type */
  282. void ZSTDMT_compressChunk(void* jobDescription)
  283. {
  284. ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
  285. ZSTD_CCtx* cctx = ZSTDMT_getCCtx(job->cctxPool);
  286. const void* const src = (const char*)job->srcStart + job->dictSize;
  287. buffer_t dstBuff = job->dstBuff;
  288. DEBUGLOG(5, "job (first:%u) (last:%u) : dictSize %u, srcSize %u",
  289. job->firstChunk, job->lastChunk, (U32)job->dictSize, (U32)job->srcSize);
  290. if (cctx==NULL) {
  291. job->cSize = ERROR(memory_allocation);
  292. goto _endJob;
  293. }
  294. if (dstBuff.start == NULL) {
  295. dstBuff = ZSTDMT_getBuffer(job->bufPool);
  296. if (dstBuff.start==NULL) {
  297. job->cSize = ERROR(memory_allocation);
  298. goto _endJob;
  299. }
  300. job->dstBuff = dstBuff;
  301. }
  302. if (job->cdict) { /* should only happen for first segment */
  303. size_t const initError = ZSTD_compressBegin_usingCDict_advanced(cctx, job->cdict, job->params.fParams, job->fullFrameSize);
  304. DEBUGLOG(5, "using CDict");
  305. if (ZSTD_isError(initError)) { job->cSize = initError; goto _endJob; }
  306. } else { /* srcStart points at reloaded section */
  307. if (!job->firstChunk) job->params.fParams.contentSizeFlag = 0; /* ensure no srcSize control */
  308. { ZSTD_CCtx_params jobParams = job->params;
  309. size_t const forceWindowError =
  310. ZSTD_CCtxParam_setParameter(&jobParams, ZSTD_p_forceMaxWindow, !job->firstChunk);
  311. /* Force loading dictionary in "content-only" mode (no header analysis) */
  312. size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, job->srcStart, job->dictSize, ZSTD_dm_rawContent, jobParams, job->fullFrameSize);
  313. if (ZSTD_isError(initError) || ZSTD_isError(forceWindowError)) {
  314. job->cSize = initError;
  315. goto _endJob;
  316. }
  317. } }
  318. if (!job->firstChunk) { /* flush and overwrite frame header when it's not first segment */
  319. size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.size, src, 0);
  320. if (ZSTD_isError(hSize)) { job->cSize = hSize; goto _endJob; }
  321. ZSTD_invalidateRepCodes(cctx);
  322. }
  323. DEBUGLOG(5, "Compressing : ");
  324. DEBUG_PRINTHEX(4, job->srcStart, 12);
  325. job->cSize = (job->lastChunk) ?
  326. ZSTD_compressEnd (cctx, dstBuff.start, dstBuff.size, src, job->srcSize) :
  327. ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.size, src, job->srcSize);
  328. DEBUGLOG(5, "compressed %u bytes into %u bytes (first:%u) (last:%u)",
  329. (unsigned)job->srcSize, (unsigned)job->cSize, job->firstChunk, job->lastChunk);
  330. DEBUGLOG(5, "dstBuff.size : %u ; => %s", (U32)dstBuff.size, ZSTD_getErrorName(job->cSize));
  331. _endJob:
  332. ZSTDMT_releaseCCtx(job->cctxPool, cctx);
  333. ZSTDMT_releaseBuffer(job->bufPool, job->src);
  334. job->src = g_nullBuffer; job->srcStart = NULL;
  335. ZSTD_PTHREAD_MUTEX_LOCK(job->jobCompleted_mutex);
  336. job->jobCompleted = 1;
  337. job->jobScanned = 0;
  338. ZSTD_pthread_cond_signal(job->jobCompleted_cond);
  339. ZSTD_pthread_mutex_unlock(job->jobCompleted_mutex);
  340. }
  341. /* ------------------------------------------ */
  342. /* ===== Multi-threaded compression ===== */
  343. /* ------------------------------------------ */
  344. typedef struct {
  345. buffer_t buffer;
  346. size_t filled;
  347. } inBuff_t;
  348. struct ZSTDMT_CCtx_s {
  349. POOL_ctx* factory;
  350. ZSTDMT_jobDescription* jobs;
  351. ZSTDMT_bufferPool* bufPool;
  352. ZSTDMT_CCtxPool* cctxPool;
  353. ZSTD_pthread_mutex_t jobCompleted_mutex;
  354. ZSTD_pthread_cond_t jobCompleted_cond;
  355. size_t targetSectionSize;
  356. size_t inBuffSize;
  357. size_t dictSize;
  358. size_t targetDictSize;
  359. inBuff_t inBuff;
  360. ZSTD_CCtx_params params;
  361. XXH64_state_t xxhState;
  362. unsigned jobIDMask;
  363. unsigned doneJobID;
  364. unsigned nextJobID;
  365. unsigned frameEnded;
  366. unsigned allJobsCompleted;
  367. unsigned long long frameContentSize;
  368. ZSTD_customMem cMem;
  369. ZSTD_CDict* cdictLocal;
  370. const ZSTD_CDict* cdict;
  371. };
  372. static ZSTDMT_jobDescription* ZSTDMT_allocJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
  373. {
  374. U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
  375. U32 const nbJobs = 1 << nbJobsLog2;
  376. *nbJobsPtr = nbJobs;
  377. return (ZSTDMT_jobDescription*) ZSTD_calloc(
  378. nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
  379. }
  380. /* Internal only */
  381. size_t ZSTDMT_initializeCCtxParameters(ZSTD_CCtx_params* params, unsigned nbThreads)
  382. {
  383. params->nbThreads = nbThreads;
  384. params->overlapSizeLog = ZSTDMT_OVERLAPLOG_DEFAULT;
  385. params->jobSize = 0;
  386. return 0;
  387. }
  388. ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbThreads, ZSTD_customMem cMem)
  389. {
  390. ZSTDMT_CCtx* mtctx;
  391. U32 nbJobs = nbThreads + 2;
  392. DEBUGLOG(3, "ZSTDMT_createCCtx_advanced");
  393. if (nbThreads < 1) return NULL;
  394. nbThreads = MIN(nbThreads , ZSTDMT_NBTHREADS_MAX);
  395. if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
  396. /* invalid custom allocator */
  397. return NULL;
  398. mtctx = (ZSTDMT_CCtx*) ZSTD_calloc(sizeof(ZSTDMT_CCtx), cMem);
  399. if (!mtctx) return NULL;
  400. ZSTDMT_initializeCCtxParameters(&mtctx->params, nbThreads);
  401. mtctx->cMem = cMem;
  402. mtctx->allJobsCompleted = 1;
  403. mtctx->factory = POOL_create_advanced(nbThreads, 0, cMem);
  404. mtctx->jobs = ZSTDMT_allocJobsTable(&nbJobs, cMem);
  405. mtctx->jobIDMask = nbJobs - 1;
  406. mtctx->bufPool = ZSTDMT_createBufferPool(nbThreads, cMem);
  407. mtctx->cctxPool = ZSTDMT_createCCtxPool(nbThreads, cMem);
  408. if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool) {
  409. ZSTDMT_freeCCtx(mtctx);
  410. return NULL;
  411. }
  412. if (ZSTD_pthread_mutex_init(&mtctx->jobCompleted_mutex, NULL)) {
  413. ZSTDMT_freeCCtx(mtctx);
  414. return NULL;
  415. }
  416. if (ZSTD_pthread_cond_init(&mtctx->jobCompleted_cond, NULL)) {
  417. ZSTDMT_freeCCtx(mtctx);
  418. return NULL;
  419. }
  420. DEBUGLOG(3, "mt_cctx created, for %u threads", nbThreads);
  421. return mtctx;
  422. }
  423. ZSTDMT_CCtx* ZSTDMT_createCCtx(unsigned nbThreads)
  424. {
  425. return ZSTDMT_createCCtx_advanced(nbThreads, ZSTD_defaultCMem);
  426. }
  427. /* ZSTDMT_releaseAllJobResources() :
  428. * note : ensure all workers are killed first ! */
  429. static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
  430. {
  431. unsigned jobID;
  432. DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
  433. for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
  434. DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
  435. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
  436. mtctx->jobs[jobID].dstBuff = g_nullBuffer;
  437. DEBUGLOG(4, "job%02u: release src address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].src.start);
  438. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].src);
  439. mtctx->jobs[jobID].src = g_nullBuffer;
  440. }
  441. memset(mtctx->jobs, 0, (mtctx->jobIDMask+1)*sizeof(ZSTDMT_jobDescription));
  442. DEBUGLOG(4, "input: release address %08X", (U32)(size_t)mtctx->inBuff.buffer.start);
  443. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->inBuff.buffer);
  444. mtctx->inBuff.buffer = g_nullBuffer;
  445. mtctx->allJobsCompleted = 1;
  446. }
  447. static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* zcs)
  448. {
  449. DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
  450. while (zcs->doneJobID < zcs->nextJobID) {
  451. unsigned const jobID = zcs->doneJobID & zcs->jobIDMask;
  452. ZSTD_PTHREAD_MUTEX_LOCK(&zcs->jobCompleted_mutex);
  453. while (zcs->jobs[jobID].jobCompleted==0) {
  454. DEBUGLOG(5, "waiting for jobCompleted signal from chunk %u", zcs->doneJobID); /* we want to block when waiting for data to flush */
  455. ZSTD_pthread_cond_wait(&zcs->jobCompleted_cond, &zcs->jobCompleted_mutex);
  456. }
  457. ZSTD_pthread_mutex_unlock(&zcs->jobCompleted_mutex);
  458. zcs->doneJobID++;
  459. }
  460. }
  461. size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
  462. {
  463. if (mtctx==NULL) return 0; /* compatible with free on NULL */
  464. POOL_free(mtctx->factory); /* stop and free worker threads */
  465. ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
  466. ZSTD_free(mtctx->jobs, mtctx->cMem);
  467. ZSTDMT_freeBufferPool(mtctx->bufPool);
  468. ZSTDMT_freeCCtxPool(mtctx->cctxPool);
  469. ZSTD_freeCDict(mtctx->cdictLocal);
  470. ZSTD_pthread_mutex_destroy(&mtctx->jobCompleted_mutex);
  471. ZSTD_pthread_cond_destroy(&mtctx->jobCompleted_cond);
  472. ZSTD_free(mtctx, mtctx->cMem);
  473. return 0;
  474. }
  475. size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
  476. {
  477. if (mtctx == NULL) return 0; /* supports sizeof NULL */
  478. return sizeof(*mtctx)
  479. + POOL_sizeof(mtctx->factory)
  480. + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
  481. + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
  482. + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
  483. + ZSTD_sizeof_CDict(mtctx->cdictLocal);
  484. }
  485. /* Internal only */
  486. size_t ZSTDMT_CCtxParam_setMTCtxParameter(
  487. ZSTD_CCtx_params* params, ZSTDMT_parameter parameter, unsigned value) {
  488. switch(parameter)
  489. {
  490. case ZSTDMT_p_sectionSize :
  491. params->jobSize = value;
  492. return 0;
  493. case ZSTDMT_p_overlapSectionLog :
  494. DEBUGLOG(4, "ZSTDMT_p_overlapSectionLog : %u", value);
  495. params->overlapSizeLog = (value >= 9) ? 9 : value;
  496. return 0;
  497. default :
  498. return ERROR(parameter_unsupported);
  499. }
  500. }
  501. size_t ZSTDMT_setMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, unsigned value)
  502. {
  503. switch(parameter)
  504. {
  505. case ZSTDMT_p_sectionSize :
  506. return ZSTDMT_CCtxParam_setMTCtxParameter(&mtctx->params, parameter, value);
  507. case ZSTDMT_p_overlapSectionLog :
  508. return ZSTDMT_CCtxParam_setMTCtxParameter(&mtctx->params, parameter, value);
  509. default :
  510. return ERROR(parameter_unsupported);
  511. }
  512. }
  513. /* ------------------------------------------ */
  514. /* ===== Multi-threaded compression ===== */
  515. /* ------------------------------------------ */
  516. static unsigned computeNbChunks(size_t srcSize, unsigned windowLog, unsigned nbThreads) {
  517. size_t const chunkSizeTarget = (size_t)1 << (windowLog + 2);
  518. size_t const chunkMaxSize = chunkSizeTarget << 2;
  519. size_t const passSizeMax = chunkMaxSize * nbThreads;
  520. unsigned const multiplier = (unsigned)(srcSize / passSizeMax) + 1;
  521. unsigned const nbChunksLarge = multiplier * nbThreads;
  522. unsigned const nbChunksMax = (unsigned)(srcSize / chunkSizeTarget) + 1;
  523. unsigned const nbChunksSmall = MIN(nbChunksMax, nbThreads);
  524. return (multiplier>1) ? nbChunksLarge : nbChunksSmall;
  525. }
  526. static size_t ZSTDMT_compress_advanced_internal(
  527. ZSTDMT_CCtx* mtctx,
  528. void* dst, size_t dstCapacity,
  529. const void* src, size_t srcSize,
  530. const ZSTD_CDict* cdict,
  531. ZSTD_CCtx_params const params)
  532. {
  533. ZSTD_CCtx_params const jobParams = ZSTDMT_makeJobCCtxParams(params);
  534. unsigned const overlapRLog = (params.overlapSizeLog>9) ? 0 : 9-params.overlapSizeLog;
  535. size_t const overlapSize = (overlapRLog>=9) ? 0 : (size_t)1 << (params.cParams.windowLog - overlapRLog);
  536. unsigned nbChunks = computeNbChunks(srcSize, params.cParams.windowLog, params.nbThreads);
  537. size_t const proposedChunkSize = (srcSize + (nbChunks-1)) / nbChunks;
  538. size_t const avgChunkSize = ((proposedChunkSize & 0x1FFFF) < 0x7FFF) ? proposedChunkSize + 0xFFFF : proposedChunkSize; /* avoid too small last block */
  539. const char* const srcStart = (const char*)src;
  540. size_t remainingSrcSize = srcSize;
  541. unsigned const compressWithinDst = (dstCapacity >= ZSTD_compressBound(srcSize)) ? nbChunks : (unsigned)(dstCapacity / ZSTD_compressBound(avgChunkSize)); /* presumes avgChunkSize >= 256 KB, which should be the case */
  542. size_t frameStartPos = 0, dstBufferPos = 0;
  543. XXH64_state_t xxh64;
  544. assert(jobParams.nbThreads == 0);
  545. assert(mtctx->cctxPool->totalCCtx == params.nbThreads);
  546. DEBUGLOG(4, "nbChunks : %2u (chunkSize : %u bytes) ", nbChunks, (U32)avgChunkSize);
  547. if (nbChunks==1) { /* fallback to single-thread mode */
  548. ZSTD_CCtx* const cctx = mtctx->cctxPool->cctx[0];
  549. if (cdict) return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, jobParams.fParams);
  550. return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, NULL, 0, jobParams);
  551. }
  552. assert(avgChunkSize >= 256 KB); /* condition for ZSTD_compressBound(A) + ZSTD_compressBound(B) <= ZSTD_compressBound(A+B), which is required for compressWithinDst */
  553. ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(avgChunkSize) );
  554. XXH64_reset(&xxh64, 0);
  555. if (nbChunks > mtctx->jobIDMask+1) { /* enlarge job table */
  556. U32 nbJobs = nbChunks;
  557. ZSTD_free(mtctx->jobs, mtctx->cMem);
  558. mtctx->jobIDMask = 0;
  559. mtctx->jobs = ZSTDMT_allocJobsTable(&nbJobs, mtctx->cMem);
  560. if (mtctx->jobs==NULL) return ERROR(memory_allocation);
  561. mtctx->jobIDMask = nbJobs - 1;
  562. }
  563. { unsigned u;
  564. for (u=0; u<nbChunks; u++) {
  565. size_t const chunkSize = MIN(remainingSrcSize, avgChunkSize);
  566. size_t const dstBufferCapacity = ZSTD_compressBound(chunkSize);
  567. buffer_t const dstAsBuffer = { (char*)dst + dstBufferPos, dstBufferCapacity };
  568. buffer_t const dstBuffer = u < compressWithinDst ? dstAsBuffer : g_nullBuffer;
  569. size_t dictSize = u ? overlapSize : 0;
  570. mtctx->jobs[u].src = g_nullBuffer;
  571. mtctx->jobs[u].srcStart = srcStart + frameStartPos - dictSize;
  572. mtctx->jobs[u].dictSize = dictSize;
  573. mtctx->jobs[u].srcSize = chunkSize;
  574. mtctx->jobs[u].cdict = mtctx->nextJobID==0 ? cdict : NULL;
  575. mtctx->jobs[u].fullFrameSize = srcSize;
  576. mtctx->jobs[u].params = jobParams;
  577. /* do not calculate checksum within sections, but write it in header for first section */
  578. if (u!=0) mtctx->jobs[u].params.fParams.checksumFlag = 0;
  579. mtctx->jobs[u].dstBuff = dstBuffer;
  580. mtctx->jobs[u].cctxPool = mtctx->cctxPool;
  581. mtctx->jobs[u].bufPool = mtctx->bufPool;
  582. mtctx->jobs[u].firstChunk = (u==0);
  583. mtctx->jobs[u].lastChunk = (u==nbChunks-1);
  584. mtctx->jobs[u].jobCompleted = 0;
  585. mtctx->jobs[u].jobCompleted_mutex = &mtctx->jobCompleted_mutex;
  586. mtctx->jobs[u].jobCompleted_cond = &mtctx->jobCompleted_cond;
  587. if (params.fParams.checksumFlag) {
  588. XXH64_update(&xxh64, srcStart + frameStartPos, chunkSize);
  589. }
  590. DEBUGLOG(5, "posting job %u (%u bytes)", u, (U32)chunkSize);
  591. DEBUG_PRINTHEX(6, mtctx->jobs[u].srcStart, 12);
  592. POOL_add(mtctx->factory, ZSTDMT_compressChunk, &mtctx->jobs[u]);
  593. frameStartPos += chunkSize;
  594. dstBufferPos += dstBufferCapacity;
  595. remainingSrcSize -= chunkSize;
  596. } }
  597. /* collect result */
  598. { size_t error = 0, dstPos = 0;
  599. unsigned chunkID;
  600. for (chunkID=0; chunkID<nbChunks; chunkID++) {
  601. DEBUGLOG(5, "waiting for chunk %u ", chunkID);
  602. ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobCompleted_mutex);
  603. while (mtctx->jobs[chunkID].jobCompleted==0) {
  604. DEBUGLOG(5, "waiting for jobCompleted signal from chunk %u", chunkID);
  605. ZSTD_pthread_cond_wait(&mtctx->jobCompleted_cond, &mtctx->jobCompleted_mutex);
  606. }
  607. ZSTD_pthread_mutex_unlock(&mtctx->jobCompleted_mutex);
  608. DEBUGLOG(5, "ready to write chunk %u ", chunkID);
  609. mtctx->jobs[chunkID].srcStart = NULL;
  610. { size_t const cSize = mtctx->jobs[chunkID].cSize;
  611. if (ZSTD_isError(cSize)) error = cSize;
  612. if ((!error) && (dstPos + cSize > dstCapacity)) error = ERROR(dstSize_tooSmall);
  613. if (chunkID) { /* note : chunk 0 is written directly at dst, which is correct position */
  614. if (!error)
  615. memmove((char*)dst + dstPos, mtctx->jobs[chunkID].dstBuff.start, cSize); /* may overlap when chunk compressed within dst */
  616. if (chunkID >= compressWithinDst) { /* chunk compressed into its own buffer, which must be released */
  617. DEBUGLOG(5, "releasing buffer %u>=%u", chunkID, compressWithinDst);
  618. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[chunkID].dstBuff);
  619. } }
  620. mtctx->jobs[chunkID].dstBuff = g_nullBuffer;
  621. dstPos += cSize ;
  622. }
  623. } /* for (chunkID=0; chunkID<nbChunks; chunkID++) */
  624. DEBUGLOG(4, "checksumFlag : %u ", params.fParams.checksumFlag);
  625. if (params.fParams.checksumFlag) {
  626. U32 const checksum = (U32)XXH64_digest(&xxh64);
  627. if (dstPos + 4 > dstCapacity) {
  628. error = ERROR(dstSize_tooSmall);
  629. } else {
  630. DEBUGLOG(4, "writing checksum : %08X \n", checksum);
  631. MEM_writeLE32((char*)dst + dstPos, checksum);
  632. dstPos += 4;
  633. } }
  634. if (!error) DEBUGLOG(4, "compressed size : %u ", (U32)dstPos);
  635. return error ? error : dstPos;
  636. }
  637. }
  638. size_t ZSTDMT_compress_advanced(ZSTDMT_CCtx* mtctx,
  639. void* dst, size_t dstCapacity,
  640. const void* src, size_t srcSize,
  641. const ZSTD_CDict* cdict,
  642. ZSTD_parameters const params,
  643. unsigned overlapLog)
  644. {
  645. ZSTD_CCtx_params cctxParams = mtctx->params;
  646. cctxParams.cParams = params.cParams;
  647. cctxParams.fParams = params.fParams;
  648. cctxParams.overlapSizeLog = overlapLog;
  649. return ZSTDMT_compress_advanced_internal(mtctx,
  650. dst, dstCapacity,
  651. src, srcSize,
  652. cdict, cctxParams);
  653. }
  654. size_t ZSTDMT_compressCCtx(ZSTDMT_CCtx* mtctx,
  655. void* dst, size_t dstCapacity,
  656. const void* src, size_t srcSize,
  657. int compressionLevel)
  658. {
  659. U32 const overlapLog = (compressionLevel >= ZSTD_maxCLevel()) ? 9 : ZSTDMT_OVERLAPLOG_DEFAULT;
  660. ZSTD_parameters params = ZSTD_getParams(compressionLevel, srcSize, 0);
  661. params.fParams.contentSizeFlag = 1;
  662. return ZSTDMT_compress_advanced(mtctx, dst, dstCapacity, src, srcSize, NULL, params, overlapLog);
  663. }
  664. /* ====================================== */
  665. /* ======= Streaming API ======= */
  666. /* ====================================== */
  667. size_t ZSTDMT_initCStream_internal(
  668. ZSTDMT_CCtx* zcs,
  669. const void* dict, size_t dictSize, ZSTD_dictMode_e dictMode,
  670. const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
  671. unsigned long long pledgedSrcSize)
  672. {
  673. DEBUGLOG(4, "ZSTDMT_initCStream_internal");
  674. /* params are supposed to be fully validated at this point */
  675. assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
  676. assert(!((dict) && (cdict))); /* either dict or cdict, not both */
  677. assert(zcs->cctxPool->totalCCtx == params.nbThreads);
  678. if (params.nbThreads==1) {
  679. ZSTD_CCtx_params const singleThreadParams = ZSTDMT_makeJobCCtxParams(params);
  680. DEBUGLOG(4, "single thread mode");
  681. assert(singleThreadParams.nbThreads == 0);
  682. return ZSTD_initCStream_internal(zcs->cctxPool->cctx[0],
  683. dict, dictSize, cdict,
  684. singleThreadParams, pledgedSrcSize);
  685. }
  686. if (zcs->allJobsCompleted == 0) { /* previous compression not correctly finished */
  687. ZSTDMT_waitForAllJobsCompleted(zcs);
  688. ZSTDMT_releaseAllJobResources(zcs);
  689. zcs->allJobsCompleted = 1;
  690. }
  691. zcs->params = params;
  692. zcs->frameContentSize = pledgedSrcSize;
  693. if (dict) {
  694. DEBUGLOG(4,"cdictLocal: %08X", (U32)(size_t)zcs->cdictLocal);
  695. ZSTD_freeCDict(zcs->cdictLocal);
  696. zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
  697. ZSTD_dlm_byCopy, dictMode, /* note : a loadPrefix becomes an internal CDict */
  698. params.cParams, zcs->cMem);
  699. zcs->cdict = zcs->cdictLocal;
  700. if (zcs->cdictLocal == NULL) return ERROR(memory_allocation);
  701. } else {
  702. DEBUGLOG(4,"cdictLocal: %08X", (U32)(size_t)zcs->cdictLocal);
  703. ZSTD_freeCDict(zcs->cdictLocal);
  704. zcs->cdictLocal = NULL;
  705. zcs->cdict = cdict;
  706. }
  707. zcs->targetDictSize = (params.overlapSizeLog==0) ? 0 : (size_t)1 << (params.cParams.windowLog - (9 - params.overlapSizeLog));
  708. DEBUGLOG(4, "overlapLog : %u ", params.overlapSizeLog);
  709. DEBUGLOG(4, "overlap Size : %u KB", (U32)(zcs->targetDictSize>>10));
  710. zcs->targetSectionSize = params.jobSize ? params.jobSize : (size_t)1 << (params.cParams.windowLog + 2);
  711. zcs->targetSectionSize = MAX(ZSTDMT_SECTION_SIZE_MIN, zcs->targetSectionSize);
  712. zcs->targetSectionSize = MAX(zcs->targetDictSize, zcs->targetSectionSize);
  713. DEBUGLOG(4, "Section Size : %u KB", (U32)(zcs->targetSectionSize>>10));
  714. zcs->inBuffSize = zcs->targetDictSize + zcs->targetSectionSize;
  715. ZSTDMT_setBufferSize(zcs->bufPool, MAX(zcs->inBuffSize, ZSTD_compressBound(zcs->targetSectionSize)) );
  716. zcs->inBuff.buffer = g_nullBuffer;
  717. zcs->dictSize = 0;
  718. zcs->doneJobID = 0;
  719. zcs->nextJobID = 0;
  720. zcs->frameEnded = 0;
  721. zcs->allJobsCompleted = 0;
  722. if (params.fParams.checksumFlag) XXH64_reset(&zcs->xxhState, 0);
  723. return 0;
  724. }
  725. size_t ZSTDMT_initCStream_advanced(ZSTDMT_CCtx* mtctx,
  726. const void* dict, size_t dictSize,
  727. ZSTD_parameters params,
  728. unsigned long long pledgedSrcSize)
  729. {
  730. ZSTD_CCtx_params cctxParams = mtctx->params;
  731. DEBUGLOG(5, "ZSTDMT_initCStream_advanced");
  732. cctxParams.cParams = params.cParams;
  733. cctxParams.fParams = params.fParams;
  734. return ZSTDMT_initCStream_internal(mtctx, dict, dictSize, ZSTD_dm_auto, NULL,
  735. cctxParams, pledgedSrcSize);
  736. }
  737. size_t ZSTDMT_initCStream_usingCDict(ZSTDMT_CCtx* mtctx,
  738. const ZSTD_CDict* cdict,
  739. ZSTD_frameParameters fParams,
  740. unsigned long long pledgedSrcSize)
  741. {
  742. ZSTD_CCtx_params cctxParams = mtctx->params;
  743. cctxParams.cParams = ZSTD_getCParamsFromCDict(cdict);
  744. cctxParams.fParams = fParams;
  745. if (cdict==NULL) return ERROR(dictionary_wrong); /* method incompatible with NULL cdict */
  746. return ZSTDMT_initCStream_internal(mtctx, NULL, 0 /*dictSize*/, ZSTD_dm_auto, cdict,
  747. cctxParams, pledgedSrcSize);
  748. }
  749. /* ZSTDMT_resetCStream() :
  750. * pledgedSrcSize is optional and can be zero == unknown */
  751. size_t ZSTDMT_resetCStream(ZSTDMT_CCtx* zcs, unsigned long long pledgedSrcSize)
  752. {
  753. if (zcs->params.nbThreads==1)
  754. return ZSTD_resetCStream(zcs->cctxPool->cctx[0], pledgedSrcSize);
  755. return ZSTDMT_initCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, 0, zcs->params,
  756. pledgedSrcSize);
  757. }
  758. size_t ZSTDMT_initCStream(ZSTDMT_CCtx* zcs, int compressionLevel) {
  759. ZSTD_parameters const params = ZSTD_getParams(compressionLevel, 0, 0);
  760. ZSTD_CCtx_params cctxParams = zcs->params;
  761. cctxParams.cParams = params.cParams;
  762. cctxParams.fParams = params.fParams;
  763. return ZSTDMT_initCStream_internal(zcs, NULL, 0, ZSTD_dm_auto, NULL, cctxParams, 0);
  764. }
  765. static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* zcs, size_t srcSize, unsigned endFrame)
  766. {
  767. unsigned const jobID = zcs->nextJobID & zcs->jobIDMask;
  768. DEBUGLOG(4, "preparing job %u to compress %u bytes with %u preload ",
  769. zcs->nextJobID, (U32)srcSize, (U32)zcs->dictSize);
  770. zcs->jobs[jobID].src = zcs->inBuff.buffer;
  771. zcs->jobs[jobID].srcStart = zcs->inBuff.buffer.start;
  772. zcs->jobs[jobID].srcSize = srcSize;
  773. zcs->jobs[jobID].dictSize = zcs->dictSize;
  774. assert(zcs->inBuff.filled >= srcSize + zcs->dictSize);
  775. zcs->jobs[jobID].params = zcs->params;
  776. /* do not calculate checksum within sections, but write it in header for first section */
  777. if (zcs->nextJobID) zcs->jobs[jobID].params.fParams.checksumFlag = 0;
  778. zcs->jobs[jobID].cdict = zcs->nextJobID==0 ? zcs->cdict : NULL;
  779. zcs->jobs[jobID].fullFrameSize = zcs->frameContentSize;
  780. zcs->jobs[jobID].dstBuff = g_nullBuffer;
  781. zcs->jobs[jobID].cctxPool = zcs->cctxPool;
  782. zcs->jobs[jobID].bufPool = zcs->bufPool;
  783. zcs->jobs[jobID].firstChunk = (zcs->nextJobID==0);
  784. zcs->jobs[jobID].lastChunk = endFrame;
  785. zcs->jobs[jobID].jobCompleted = 0;
  786. zcs->jobs[jobID].dstFlushed = 0;
  787. zcs->jobs[jobID].jobCompleted_mutex = &zcs->jobCompleted_mutex;
  788. zcs->jobs[jobID].jobCompleted_cond = &zcs->jobCompleted_cond;
  789. if (zcs->params.fParams.checksumFlag)
  790. XXH64_update(&zcs->xxhState, (const char*)zcs->inBuff.buffer.start + zcs->dictSize, srcSize);
  791. /* get a new buffer for next input */
  792. if (!endFrame) {
  793. size_t const newDictSize = MIN(srcSize + zcs->dictSize, zcs->targetDictSize);
  794. zcs->inBuff.buffer = ZSTDMT_getBuffer(zcs->bufPool);
  795. if (zcs->inBuff.buffer.start == NULL) { /* not enough memory to allocate next input buffer */
  796. zcs->jobs[jobID].jobCompleted = 1;
  797. zcs->nextJobID++;
  798. ZSTDMT_waitForAllJobsCompleted(zcs);
  799. ZSTDMT_releaseAllJobResources(zcs);
  800. return ERROR(memory_allocation);
  801. }
  802. zcs->inBuff.filled -= srcSize + zcs->dictSize - newDictSize;
  803. memmove(zcs->inBuff.buffer.start,
  804. (const char*)zcs->jobs[jobID].srcStart + zcs->dictSize + srcSize - newDictSize,
  805. zcs->inBuff.filled);
  806. zcs->dictSize = newDictSize;
  807. } else { /* if (endFrame==1) */
  808. zcs->inBuff.buffer = g_nullBuffer;
  809. zcs->inBuff.filled = 0;
  810. zcs->dictSize = 0;
  811. zcs->frameEnded = 1;
  812. if (zcs->nextJobID == 0) {
  813. /* single chunk exception : checksum is calculated directly within worker thread */
  814. zcs->params.fParams.checksumFlag = 0;
  815. } }
  816. DEBUGLOG(4, "posting job %u : %u bytes (end:%u) (note : doneJob = %u=>%u)",
  817. zcs->nextJobID,
  818. (U32)zcs->jobs[jobID].srcSize,
  819. zcs->jobs[jobID].lastChunk,
  820. zcs->doneJobID,
  821. zcs->doneJobID & zcs->jobIDMask);
  822. POOL_add(zcs->factory, ZSTDMT_compressChunk, &zcs->jobs[jobID]); /* this call is blocking when thread worker pool is exhausted */
  823. zcs->nextJobID++;
  824. return 0;
  825. }
  826. /* ZSTDMT_flushNextJob() :
  827. * output : will be updated with amount of data flushed .
  828. * blockToFlush : if >0, the function will block and wait if there is no data available to flush .
  829. * @return : amount of data remaining within internal buffer, 1 if unknown but > 0, 0 if no more, or an error code */
  830. static size_t ZSTDMT_flushNextJob(ZSTDMT_CCtx* zcs, ZSTD_outBuffer* output, unsigned blockToFlush)
  831. {
  832. unsigned const wJobID = zcs->doneJobID & zcs->jobIDMask;
  833. if (zcs->doneJobID == zcs->nextJobID) return 0; /* all flushed ! */
  834. ZSTD_PTHREAD_MUTEX_LOCK(&zcs->jobCompleted_mutex);
  835. while (zcs->jobs[wJobID].jobCompleted==0) {
  836. DEBUGLOG(5, "waiting for jobCompleted signal from job %u", zcs->doneJobID);
  837. if (!blockToFlush) { ZSTD_pthread_mutex_unlock(&zcs->jobCompleted_mutex); return 0; } /* nothing ready to be flushed => skip */
  838. ZSTD_pthread_cond_wait(&zcs->jobCompleted_cond, &zcs->jobCompleted_mutex); /* block when nothing available to flush */
  839. }
  840. ZSTD_pthread_mutex_unlock(&zcs->jobCompleted_mutex);
  841. /* compression job completed : output can be flushed */
  842. { ZSTDMT_jobDescription job = zcs->jobs[wJobID];
  843. if (!job.jobScanned) {
  844. if (ZSTD_isError(job.cSize)) {
  845. DEBUGLOG(5, "compression error detected ");
  846. ZSTDMT_waitForAllJobsCompleted(zcs);
  847. ZSTDMT_releaseAllJobResources(zcs);
  848. return job.cSize;
  849. }
  850. DEBUGLOG(5, "zcs->params.fParams.checksumFlag : %u ", zcs->params.fParams.checksumFlag);
  851. if (zcs->params.fParams.checksumFlag) {
  852. if (zcs->frameEnded && (zcs->doneJobID+1 == zcs->nextJobID)) { /* write checksum at end of last section */
  853. U32 const checksum = (U32)XXH64_digest(&zcs->xxhState);
  854. DEBUGLOG(5, "writing checksum : %08X \n", checksum);
  855. MEM_writeLE32((char*)job.dstBuff.start + job.cSize, checksum);
  856. job.cSize += 4;
  857. zcs->jobs[wJobID].cSize += 4;
  858. } }
  859. zcs->jobs[wJobID].jobScanned = 1;
  860. }
  861. { size_t const toWrite = MIN(job.cSize - job.dstFlushed, output->size - output->pos);
  862. DEBUGLOG(5, "Flushing %u bytes from job %u ", (U32)toWrite, zcs->doneJobID);
  863. memcpy((char*)output->dst + output->pos, (const char*)job.dstBuff.start + job.dstFlushed, toWrite);
  864. output->pos += toWrite;
  865. job.dstFlushed += toWrite;
  866. }
  867. if (job.dstFlushed == job.cSize) { /* output buffer fully flushed => move to next one */
  868. ZSTDMT_releaseBuffer(zcs->bufPool, job.dstBuff);
  869. zcs->jobs[wJobID].dstBuff = g_nullBuffer;
  870. zcs->jobs[wJobID].jobCompleted = 0;
  871. zcs->doneJobID++;
  872. } else {
  873. zcs->jobs[wJobID].dstFlushed = job.dstFlushed;
  874. }
  875. /* return value : how many bytes left in buffer ; fake it to 1 if unknown but >0 */
  876. if (job.cSize > job.dstFlushed) return (job.cSize - job.dstFlushed);
  877. if (zcs->doneJobID < zcs->nextJobID) return 1; /* still some buffer to flush */
  878. zcs->allJobsCompleted = zcs->frameEnded; /* frame completed and entirely flushed */
  879. return 0; /* everything flushed */
  880. } }
  881. /** ZSTDMT_compressStream_generic() :
  882. * internal use only - exposed to be invoked from zstd_compress.c
  883. * assumption : output and input are valid (pos <= size)
  884. * @return : minimum amount of data remaining to flush, 0 if none */
  885. size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
  886. ZSTD_outBuffer* output,
  887. ZSTD_inBuffer* input,
  888. ZSTD_EndDirective endOp)
  889. {
  890. size_t const newJobThreshold = mtctx->dictSize + mtctx->targetSectionSize;
  891. unsigned forwardInputProgress = 0;
  892. assert(output->pos <= output->size);
  893. assert(input->pos <= input->size);
  894. if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
  895. /* current frame being ended. Only flush/end are allowed */
  896. return ERROR(stage_wrong);
  897. }
  898. if (mtctx->params.nbThreads==1) { /* delegate to single-thread (synchronous) */
  899. return ZSTD_compressStream_generic(mtctx->cctxPool->cctx[0], output, input, endOp);
  900. }
  901. /* single-pass shortcut (note : synchronous-mode) */
  902. if ( (mtctx->nextJobID == 0) /* just started */
  903. && (mtctx->inBuff.filled == 0) /* nothing buffered */
  904. && (endOp == ZSTD_e_end) /* end order */
  905. && (output->size - output->pos >= ZSTD_compressBound(input->size - input->pos)) ) { /* enough room */
  906. size_t const cSize = ZSTDMT_compress_advanced_internal(mtctx,
  907. (char*)output->dst + output->pos, output->size - output->pos,
  908. (const char*)input->src + input->pos, input->size - input->pos,
  909. mtctx->cdict, mtctx->params);
  910. if (ZSTD_isError(cSize)) return cSize;
  911. input->pos = input->size;
  912. output->pos += cSize;
  913. ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->inBuff.buffer); /* was allocated in initStream */
  914. mtctx->allJobsCompleted = 1;
  915. mtctx->frameEnded = 1;
  916. return 0;
  917. }
  918. /* fill input buffer */
  919. if (input->size > input->pos) { /* support NULL input */
  920. if (mtctx->inBuff.buffer.start == NULL) {
  921. mtctx->inBuff.buffer = ZSTDMT_getBuffer(mtctx->bufPool); /* note : may fail, in which case, no forward input progress */
  922. mtctx->inBuff.filled = 0;
  923. }
  924. if (mtctx->inBuff.buffer.start) {
  925. size_t const toLoad = MIN(input->size - input->pos, mtctx->inBuffSize - mtctx->inBuff.filled);
  926. DEBUGLOG(5, "inBuff:%08X; inBuffSize=%u; ToCopy=%u", (U32)(size_t)mtctx->inBuff.buffer.start, (U32)mtctx->inBuffSize, (U32)toLoad);
  927. memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, toLoad);
  928. input->pos += toLoad;
  929. mtctx->inBuff.filled += toLoad;
  930. forwardInputProgress = toLoad>0;
  931. } }
  932. if ( (mtctx->inBuff.filled >= newJobThreshold) /* filled enough : let's compress */
  933. && (mtctx->nextJobID <= mtctx->doneJobID + mtctx->jobIDMask) ) { /* avoid overwriting job round buffer */
  934. CHECK_F( ZSTDMT_createCompressionJob(mtctx, mtctx->targetSectionSize, 0 /* endFrame */) );
  935. }
  936. /* check for potential compressed data ready to be flushed */
  937. CHECK_F( ZSTDMT_flushNextJob(mtctx, output, !forwardInputProgress /* blockToFlush */) ); /* block if there was no forward input progress */
  938. if (input->pos < input->size) /* input not consumed : do not flush yet */
  939. endOp = ZSTD_e_continue;
  940. switch(endOp)
  941. {
  942. case ZSTD_e_flush:
  943. return ZSTDMT_flushStream(mtctx, output);
  944. case ZSTD_e_end:
  945. return ZSTDMT_endStream(mtctx, output);
  946. case ZSTD_e_continue:
  947. return 1;
  948. default:
  949. return ERROR(GENERIC); /* invalid endDirective */
  950. }
  951. }
  952. size_t ZSTDMT_compressStream(ZSTDMT_CCtx* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
  953. {
  954. CHECK_F( ZSTDMT_compressStream_generic(zcs, output, input, ZSTD_e_continue) );
  955. /* recommended next input size : fill current input buffer */
  956. return zcs->inBuffSize - zcs->inBuff.filled; /* note : could be zero when input buffer is fully filled and no more availability to create new job */
  957. }
  958. static size_t ZSTDMT_flushStream_internal(ZSTDMT_CCtx* zcs, ZSTD_outBuffer* output, unsigned endFrame)
  959. {
  960. size_t const srcSize = zcs->inBuff.filled - zcs->dictSize;
  961. if ( ((srcSize > 0) || (endFrame && !zcs->frameEnded))
  962. && (zcs->nextJobID <= zcs->doneJobID + zcs->jobIDMask) ) {
  963. CHECK_F( ZSTDMT_createCompressionJob(zcs, srcSize, endFrame) );
  964. }
  965. /* check if there is any data available to flush */
  966. return ZSTDMT_flushNextJob(zcs, output, 1 /* blockToFlush */);
  967. }
  968. size_t ZSTDMT_flushStream(ZSTDMT_CCtx* zcs, ZSTD_outBuffer* output)
  969. {
  970. DEBUGLOG(5, "ZSTDMT_flushStream");
  971. if (zcs->params.nbThreads==1)
  972. return ZSTD_flushStream(zcs->cctxPool->cctx[0], output);
  973. return ZSTDMT_flushStream_internal(zcs, output, 0 /* endFrame */);
  974. }
  975. size_t ZSTDMT_endStream(ZSTDMT_CCtx* zcs, ZSTD_outBuffer* output)
  976. {
  977. DEBUGLOG(4, "ZSTDMT_endStream");
  978. if (zcs->params.nbThreads==1)
  979. return ZSTD_endStream(zcs->cctxPool->cctx[0], output);
  980. return ZSTDMT_flushStream_internal(zcs, output, 1 /* endFrame */);
  981. }