zstdmt_compress.c 79 KB

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