zstdmt_compress.c 81 KB

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