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