zstdmt_compress.c 92 KB

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