zstdmt_compress.c 79 KB

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