• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 == ZSTD_ps_enable) {
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 == ZSTD_ps_enable) {
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 == ZSTD_ps_enable) {
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 == ZSTD_ps_enable);
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 == ZSTD_ps_enable && 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 = ZSTD_ps_disable;
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 /* Don't create chunks smaller than the zstd block size.
811  * This stops us from regressing compression ratio too much,
812  * and ensures our output fits in ZSTD_compressBound().
813  *
814  * If this is shrunk < ZSTD_BLOCKSIZELOG_MIN then
815  * ZSTD_COMPRESSBOUND() will need to be updated.
816  */
817 #define RSYNC_MIN_BLOCK_LOG ZSTD_BLOCKSIZELOG_MAX
818 #define RSYNC_MIN_BLOCK_SIZE (1<<RSYNC_MIN_BLOCK_LOG)
819 
820 typedef struct {
821   U64 hash;
822   U64 hitMask;
823   U64 primePower;
824 } rsyncState_t;
825 
826 struct ZSTDMT_CCtx_s {
827     POOL_ctx* factory;
828     ZSTDMT_jobDescription* jobs;
829     ZSTDMT_bufferPool* bufPool;
830     ZSTDMT_CCtxPool* cctxPool;
831     ZSTDMT_seqPool* seqPool;
832     ZSTD_CCtx_params params;
833     size_t targetSectionSize;
834     size_t targetPrefixSize;
835     int jobReady;        /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */
836     inBuff_t inBuff;
837     roundBuff_t roundBuff;
838     serialState_t serial;
839     rsyncState_t rsync;
840     unsigned jobIDMask;
841     unsigned doneJobID;
842     unsigned nextJobID;
843     unsigned frameEnded;
844     unsigned allJobsCompleted;
845     unsigned long long frameContentSize;
846     unsigned long long consumed;
847     unsigned long long produced;
848     ZSTD_customMem cMem;
849     ZSTD_CDict* cdictLocal;
850     const ZSTD_CDict* cdict;
851     unsigned providedFactory: 1;
852 };
853 
ZSTDMT_freeJobsTable(ZSTDMT_jobDescription * jobTable,U32 nbJobs,ZSTD_customMem cMem)854 static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
855 {
856     U32 jobNb;
857     if (jobTable == NULL) return;
858     for (jobNb=0; jobNb<nbJobs; jobNb++) {
859         ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);
860         ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);
861     }
862     ZSTD_customFree(jobTable, cMem);
863 }
864 
865 /* ZSTDMT_allocJobsTable()
866  * allocate and init a job table.
867  * update *nbJobsPtr to next power of 2 value, as size of table */
ZSTDMT_createJobsTable(U32 * nbJobsPtr,ZSTD_customMem cMem)868 static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
869 {
870     U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
871     U32 const nbJobs = 1 << nbJobsLog2;
872     U32 jobNb;
873     ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
874                 ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
875     int initError = 0;
876     if (jobTable==NULL) return NULL;
877     *nbJobsPtr = nbJobs;
878     for (jobNb=0; jobNb<nbJobs; jobNb++) {
879         initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
880         initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);
881     }
882     if (initError != 0) {
883         ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
884         return NULL;
885     }
886     return jobTable;
887 }
888 
ZSTDMT_expandJobsTable(ZSTDMT_CCtx * mtctx,U32 nbWorkers)889 static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
890     U32 nbJobs = nbWorkers + 2;
891     if (nbJobs > mtctx->jobIDMask+1) {  /* need more job capacity */
892         ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
893         mtctx->jobIDMask = 0;
894         mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);
895         if (mtctx->jobs==NULL) return ERROR(memory_allocation);
896         assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0));  /* ensure nbJobs is a power of 2 */
897         mtctx->jobIDMask = nbJobs - 1;
898     }
899     return 0;
900 }
901 
902 
903 /* ZSTDMT_CCtxParam_setNbWorkers():
904  * Internal use only */
ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params * params,unsigned nbWorkers)905 static size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)
906 {
907     return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);
908 }
909 
ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers,ZSTD_customMem cMem,ZSTD_threadPool * pool)910 MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
911 {
912     ZSTDMT_CCtx* mtctx;
913     U32 nbJobs = nbWorkers + 2;
914     int initError;
915     DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
916 
917     if (nbWorkers < 1) return NULL;
918     nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
919     if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
920         /* invalid custom allocator */
921         return NULL;
922 
923     mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);
924     if (!mtctx) return NULL;
925     ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
926     mtctx->cMem = cMem;
927     mtctx->allJobsCompleted = 1;
928     if (pool != NULL) {
929       mtctx->factory = pool;
930       mtctx->providedFactory = 1;
931     }
932     else {
933       mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
934       mtctx->providedFactory = 0;
935     }
936     mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
937     assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0);  /* ensure nbJobs is a power of 2 */
938     mtctx->jobIDMask = nbJobs - 1;
939     mtctx->bufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
940     mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
941     mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
942     initError = ZSTDMT_serialState_init(&mtctx->serial);
943     mtctx->roundBuff = kNullRoundBuff;
944     if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {
945         ZSTDMT_freeCCtx(mtctx);
946         return NULL;
947     }
948     DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);
949     return mtctx;
950 }
951 
ZSTDMT_createCCtx_advanced(unsigned nbWorkers,ZSTD_customMem cMem,ZSTD_threadPool * pool)952 ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
953 {
954 #ifdef ZSTD_MULTITHREAD
955     return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);
956 #else
957     (void)nbWorkers;
958     (void)cMem;
959     (void)pool;
960     return NULL;
961 #endif
962 }
963 
964 
965 /* ZSTDMT_releaseAllJobResources() :
966  * note : ensure all workers are killed first ! */
ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx * mtctx)967 static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
968 {
969     unsigned jobID;
970     DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
971     for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
972         /* Copy the mutex/cond out */
973         ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;
974         ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;
975 
976         DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
977         ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
978 
979         /* Clear the job description, but keep the mutex/cond */
980         ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));
981         mtctx->jobs[jobID].job_mutex = mutex;
982         mtctx->jobs[jobID].job_cond = cond;
983     }
984     mtctx->inBuff.buffer = g_nullBuffer;
985     mtctx->inBuff.filled = 0;
986     mtctx->allJobsCompleted = 1;
987 }
988 
ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx * mtctx)989 static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)
990 {
991     DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
992     while (mtctx->doneJobID < mtctx->nextJobID) {
993         unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
994         ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
995         while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
996             DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID);   /* we want to block when waiting for data to flush */
997             ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
998         }
999         ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
1000         mtctx->doneJobID++;
1001     }
1002 }
1003 
ZSTDMT_freeCCtx(ZSTDMT_CCtx * mtctx)1004 size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
1005 {
1006     if (mtctx==NULL) return 0;   /* compatible with free on NULL */
1007     if (!mtctx->providedFactory)
1008         POOL_free(mtctx->factory);   /* stop and free worker threads */
1009     ZSTDMT_releaseAllJobResources(mtctx);  /* release job resources into pools first */
1010     ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
1011     ZSTDMT_freeBufferPool(mtctx->bufPool);
1012     ZSTDMT_freeCCtxPool(mtctx->cctxPool);
1013     ZSTDMT_freeSeqPool(mtctx->seqPool);
1014     ZSTDMT_serialState_free(&mtctx->serial);
1015     ZSTD_freeCDict(mtctx->cdictLocal);
1016     if (mtctx->roundBuff.buffer)
1017         ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
1018     ZSTD_customFree(mtctx, mtctx->cMem);
1019     return 0;
1020 }
1021 
ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx * mtctx)1022 size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
1023 {
1024     if (mtctx == NULL) return 0;   /* supports sizeof NULL */
1025     return sizeof(*mtctx)
1026             + POOL_sizeof(mtctx->factory)
1027             + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
1028             + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
1029             + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
1030             + ZSTDMT_sizeof_seqPool(mtctx->seqPool)
1031             + ZSTD_sizeof_CDict(mtctx->cdictLocal)
1032             + mtctx->roundBuff.capacity;
1033 }
1034 
1035 
1036 /* ZSTDMT_resize() :
1037  * @return : error code if fails, 0 on success */
ZSTDMT_resize(ZSTDMT_CCtx * mtctx,unsigned nbWorkers)1038 static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)
1039 {
1040     if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
1041     FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");
1042     mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, nbWorkers);
1043     if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
1044     mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);
1045     if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);
1046     mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);
1047     if (mtctx->seqPool == NULL) return ERROR(memory_allocation);
1048     ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
1049     return 0;
1050 }
1051 
1052 
1053 /*! ZSTDMT_updateCParams_whileCompressing() :
1054  *  Updates a selected set of compression parameters, remaining compatible with currently active frame.
1055  *  New parameters will be applied to next compression job. */
ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx * mtctx,const ZSTD_CCtx_params * cctxParams)1056 void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)
1057 {
1058     U32 const saved_wlog = mtctx->params.cParams.windowLog;   /* Do not modify windowLog while compressing */
1059     int const compressionLevel = cctxParams->compressionLevel;
1060     DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",
1061                 compressionLevel);
1062     mtctx->params.compressionLevel = compressionLevel;
1063     {   ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
1064         cParams.windowLog = saved_wlog;
1065         mtctx->params.cParams = cParams;
1066     }
1067 }
1068 
1069 /* ZSTDMT_getFrameProgression():
1070  * tells how much data has been consumed (input) and produced (output) for current frame.
1071  * able to count progression inside worker threads.
1072  * Note : mutex will be acquired during statistics collection inside workers. */
ZSTDMT_getFrameProgression(ZSTDMT_CCtx * mtctx)1073 ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
1074 {
1075     ZSTD_frameProgression fps;
1076     DEBUGLOG(5, "ZSTDMT_getFrameProgression");
1077     fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
1078     fps.consumed = mtctx->consumed;
1079     fps.produced = fps.flushed = mtctx->produced;
1080     fps.currentJobID = mtctx->nextJobID;
1081     fps.nbActiveWorkers = 0;
1082     {   unsigned jobNb;
1083         unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
1084         DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
1085                     mtctx->doneJobID, lastJobNb, mtctx->jobReady)
1086         for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
1087             unsigned const wJobID = jobNb & mtctx->jobIDMask;
1088             ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
1089             ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
1090             {   size_t const cResult = jobPtr->cSize;
1091                 size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
1092                 size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
1093                 assert(flushed <= produced);
1094                 fps.ingested += jobPtr->src.size;
1095                 fps.consumed += jobPtr->consumed;
1096                 fps.produced += produced;
1097                 fps.flushed  += flushed;
1098                 fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);
1099             }
1100             ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
1101         }
1102     }
1103     return fps;
1104 }
1105 
1106 
ZSTDMT_toFlushNow(ZSTDMT_CCtx * mtctx)1107 size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)
1108 {
1109     size_t toFlush;
1110     unsigned const jobID = mtctx->doneJobID;
1111     assert(jobID <= mtctx->nextJobID);
1112     if (jobID == mtctx->nextJobID) return 0;   /* no active job => nothing to flush */
1113 
1114     /* look into oldest non-fully-flushed job */
1115     {   unsigned const wJobID = jobID & mtctx->jobIDMask;
1116         ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
1117         ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
1118         {   size_t const cResult = jobPtr->cSize;
1119             size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
1120             size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
1121             assert(flushed <= produced);
1122             assert(jobPtr->consumed <= jobPtr->src.size);
1123             toFlush = produced - flushed;
1124             /* if toFlush==0, nothing is available to flush.
1125              * However, jobID is expected to still be active:
1126              * if jobID was already completed and fully flushed,
1127              * ZSTDMT_flushProduced() should have already moved onto next job.
1128              * Therefore, some input has not yet been consumed. */
1129             if (toFlush==0) {
1130                 assert(jobPtr->consumed < jobPtr->src.size);
1131             }
1132         }
1133         ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
1134     }
1135 
1136     return toFlush;
1137 }
1138 
1139 
1140 /* ------------------------------------------ */
1141 /* =====   Multi-threaded compression   ===== */
1142 /* ------------------------------------------ */
1143 
ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params * params)1144 static unsigned ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params* params)
1145 {
1146     unsigned jobLog;
1147     if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
1148         /* In Long Range Mode, the windowLog is typically oversized.
1149          * In which case, it's preferable to determine the jobSize
1150          * based on cycleLog instead. */
1151         jobLog = MAX(21, ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy) + 3);
1152     } else {
1153         jobLog = MAX(20, params->cParams.windowLog + 2);
1154     }
1155     return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);
1156 }
1157 
ZSTDMT_overlapLog_default(ZSTD_strategy strat)1158 static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
1159 {
1160     switch(strat)
1161     {
1162         case ZSTD_btultra2:
1163             return 9;
1164         case ZSTD_btultra:
1165         case ZSTD_btopt:
1166             return 8;
1167         case ZSTD_btlazy2:
1168         case ZSTD_lazy2:
1169             return 7;
1170         case ZSTD_lazy:
1171         case ZSTD_greedy:
1172         case ZSTD_dfast:
1173         case ZSTD_fast:
1174         default:;
1175     }
1176     return 6;
1177 }
1178 
ZSTDMT_overlapLog(int ovlog,ZSTD_strategy strat)1179 static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)
1180 {
1181     assert(0 <= ovlog && ovlog <= 9);
1182     if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
1183     return ovlog;
1184 }
1185 
ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params * params)1186 static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)
1187 {
1188     int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);
1189     int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);
1190     assert(0 <= overlapRLog && overlapRLog <= 8);
1191     if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
1192         /* In Long Range Mode, the windowLog is typically oversized.
1193          * In which case, it's preferable to determine the jobSize
1194          * based on chainLog instead.
1195          * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
1196         ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)
1197                 - overlapRLog;
1198     }
1199     assert(0 <= ovLog && ovLog <= ZSTD_WINDOWLOG_MAX);
1200     DEBUGLOG(4, "overlapLog : %i", params->overlapLog);
1201     DEBUGLOG(4, "overlap size : %i", 1 << ovLog);
1202     return (ovLog==0) ? 0 : (size_t)1 << ovLog;
1203 }
1204 
1205 /* ====================================== */
1206 /* =======      Streaming API     ======= */
1207 /* ====================================== */
1208 
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)1209 size_t ZSTDMT_initCStream_internal(
1210         ZSTDMT_CCtx* mtctx,
1211         const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
1212         const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
1213         unsigned long long pledgedSrcSize)
1214 {
1215     DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
1216                 (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
1217 
1218     /* params supposed partially fully validated at this point */
1219     assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
1220     assert(!((dict) && (cdict)));  /* either dict or cdict, not both */
1221 
1222     /* init */
1223     if (params.nbWorkers != mtctx->params.nbWorkers)
1224         FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, params.nbWorkers) , "");
1225 
1226     if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
1227     if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;
1228 
1229     DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
1230 
1231     if (mtctx->allJobsCompleted == 0) {   /* previous compression not correctly finished */
1232         ZSTDMT_waitForAllJobsCompleted(mtctx);
1233         ZSTDMT_releaseAllJobResources(mtctx);
1234         mtctx->allJobsCompleted = 1;
1235     }
1236 
1237     mtctx->params = params;
1238     mtctx->frameContentSize = pledgedSrcSize;
1239     if (dict) {
1240         ZSTD_freeCDict(mtctx->cdictLocal);
1241         mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
1242                                                     ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
1243                                                     params.cParams, mtctx->cMem);
1244         mtctx->cdict = mtctx->cdictLocal;
1245         if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
1246     } else {
1247         ZSTD_freeCDict(mtctx->cdictLocal);
1248         mtctx->cdictLocal = NULL;
1249         mtctx->cdict = cdict;
1250     }
1251 
1252     mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(&params);
1253     DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
1254     mtctx->targetSectionSize = params.jobSize;
1255     if (mtctx->targetSectionSize == 0) {
1256         mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(&params);
1257     }
1258     assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);
1259 
1260     if (params.rsyncable) {
1261         /* Aim for the targetsectionSize as the average job size. */
1262         U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);
1263         U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);
1264         /* We refuse to create jobs < RSYNC_MIN_BLOCK_SIZE bytes, so make sure our
1265          * expected job size is at least 4x larger. */
1266         assert(rsyncBits >= RSYNC_MIN_BLOCK_LOG + 2);
1267         DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
1268         mtctx->rsync.hash = 0;
1269         mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
1270         mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
1271     }
1272     if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize;  /* job size must be >= overlap size */
1273     DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
1274     DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
1275     ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
1276     {
1277         /* If ldm is enabled we need windowSize space. */
1278         size_t const windowSize = mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable ? (1U << mtctx->params.cParams.windowLog) : 0;
1279         /* Two buffers of slack, plus extra space for the overlap
1280          * This is the minimum slack that LDM works with. One extra because
1281          * flush might waste up to targetSectionSize-1 bytes. Another extra
1282          * for the overlap (if > 0), then one to fill which doesn't overlap
1283          * with the LDM window.
1284          */
1285         size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
1286         size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
1287         /* Compute the total size, and always have enough slack */
1288         size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
1289         size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
1290         size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
1291         if (mtctx->roundBuff.capacity < capacity) {
1292             if (mtctx->roundBuff.buffer)
1293                 ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
1294             mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);
1295             if (mtctx->roundBuff.buffer == NULL) {
1296                 mtctx->roundBuff.capacity = 0;
1297                 return ERROR(memory_allocation);
1298             }
1299             mtctx->roundBuff.capacity = capacity;
1300         }
1301     }
1302     DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
1303     mtctx->roundBuff.pos = 0;
1304     mtctx->inBuff.buffer = g_nullBuffer;
1305     mtctx->inBuff.filled = 0;
1306     mtctx->inBuff.prefix = kNullRange;
1307     mtctx->doneJobID = 0;
1308     mtctx->nextJobID = 0;
1309     mtctx->frameEnded = 0;
1310     mtctx->allJobsCompleted = 0;
1311     mtctx->consumed = 0;
1312     mtctx->produced = 0;
1313     if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize,
1314                                  dict, dictSize, dictContentType))
1315         return ERROR(memory_allocation);
1316     return 0;
1317 }
1318 
1319 
1320 /* ZSTDMT_writeLastEmptyBlock()
1321  * Write a single empty block with an end-of-frame to finish a frame.
1322  * Job must be created from streaming variant.
1323  * This function is always successful if expected conditions are fulfilled.
1324  */
ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription * job)1325 static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)
1326 {
1327     assert(job->lastJob == 1);
1328     assert(job->src.size == 0);   /* last job is empty -> will be simplified into a last empty block */
1329     assert(job->firstJob == 0);   /* cannot be first job, as it also needs to create frame header */
1330     assert(job->dstBuff.start == NULL);   /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
1331     job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
1332     if (job->dstBuff.start == NULL) {
1333       job->cSize = ERROR(memory_allocation);
1334       return;
1335     }
1336     assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize);   /* no buffer should ever be that small */
1337     job->src = kNullRange;
1338     job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);
1339     assert(!ZSTD_isError(job->cSize));
1340     assert(job->consumed == 0);
1341 }
1342 
ZSTDMT_createCompressionJob(ZSTDMT_CCtx * mtctx,size_t srcSize,ZSTD_EndDirective endOp)1343 static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)
1344 {
1345     unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
1346     int const endFrame = (endOp == ZSTD_e_end);
1347 
1348     if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
1349         DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
1350         assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
1351         return 0;
1352     }
1353 
1354     if (!mtctx->jobReady) {
1355         BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
1356         DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
1357                     mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
1358         mtctx->jobs[jobID].src.start = src;
1359         mtctx->jobs[jobID].src.size = srcSize;
1360         assert(mtctx->inBuff.filled >= srcSize);
1361         mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
1362         mtctx->jobs[jobID].consumed = 0;
1363         mtctx->jobs[jobID].cSize = 0;
1364         mtctx->jobs[jobID].params = mtctx->params;
1365         mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
1366         mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
1367         mtctx->jobs[jobID].dstBuff = g_nullBuffer;
1368         mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
1369         mtctx->jobs[jobID].bufPool = mtctx->bufPool;
1370         mtctx->jobs[jobID].seqPool = mtctx->seqPool;
1371         mtctx->jobs[jobID].serial = &mtctx->serial;
1372         mtctx->jobs[jobID].jobID = mtctx->nextJobID;
1373         mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
1374         mtctx->jobs[jobID].lastJob = endFrame;
1375         mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
1376         mtctx->jobs[jobID].dstFlushed = 0;
1377 
1378         /* Update the round buffer pos and clear the input buffer to be reset */
1379         mtctx->roundBuff.pos += srcSize;
1380         mtctx->inBuff.buffer = g_nullBuffer;
1381         mtctx->inBuff.filled = 0;
1382         /* Set the prefix */
1383         if (!endFrame) {
1384             size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
1385             mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
1386             mtctx->inBuff.prefix.size = newPrefixSize;
1387         } else {   /* endFrame==1 => no need for another input buffer */
1388             mtctx->inBuff.prefix = kNullRange;
1389             mtctx->frameEnded = endFrame;
1390             if (mtctx->nextJobID == 0) {
1391                 /* single job exception : checksum is already calculated directly within worker thread */
1392                 mtctx->params.fParams.checksumFlag = 0;
1393         }   }
1394 
1395         if ( (srcSize == 0)
1396           && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
1397             DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
1398             assert(endOp == ZSTD_e_end);  /* only possible case : need to end the frame with an empty last block */
1399             ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
1400             mtctx->nextJobID++;
1401             return 0;
1402         }
1403     }
1404 
1405     DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes  (end:%u, jobNb == %u (mod:%u))",
1406                 mtctx->nextJobID,
1407                 (U32)mtctx->jobs[jobID].src.size,
1408                 mtctx->jobs[jobID].lastJob,
1409                 mtctx->nextJobID,
1410                 jobID);
1411     if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
1412         mtctx->nextJobID++;
1413         mtctx->jobReady = 0;
1414     } else {
1415         DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);
1416         mtctx->jobReady = 1;
1417     }
1418     return 0;
1419 }
1420 
1421 
1422 /*! ZSTDMT_flushProduced() :
1423  *  flush whatever data has been produced but not yet flushed in current job.
1424  *  move to next job if current one is fully flushed.
1425  * `output` : `pos` will be updated with amount of data flushed .
1426  * `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .
1427  * @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)1428 static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)
1429 {
1430     unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
1431     DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
1432                 blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
1433     assert(output->size >= output->pos);
1434 
1435     ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
1436     if (  blockToFlush
1437       && (mtctx->doneJobID < mtctx->nextJobID) ) {
1438         assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
1439         while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) {  /* nothing to flush */
1440             if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
1441                 DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
1442                             mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
1443                 break;
1444             }
1445             DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
1446                         mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
1447             ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex);  /* block when nothing to flush but some to come */
1448     }   }
1449 
1450     /* try to flush something */
1451     {   size_t cSize = mtctx->jobs[wJobID].cSize;                  /* shared */
1452         size_t const srcConsumed = mtctx->jobs[wJobID].consumed;   /* shared */
1453         size_t const srcSize = mtctx->jobs[wJobID].src.size;       /* read-only, could be done after mutex lock, but no-declaration-after-statement */
1454         ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
1455         if (ZSTD_isError(cSize)) {
1456             DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
1457                         mtctx->doneJobID, ZSTD_getErrorName(cSize));
1458             ZSTDMT_waitForAllJobsCompleted(mtctx);
1459             ZSTDMT_releaseAllJobResources(mtctx);
1460             return cSize;
1461         }
1462         /* add frame checksum if necessary (can only happen once) */
1463         assert(srcConsumed <= srcSize);
1464         if ( (srcConsumed == srcSize)   /* job completed -> worker no longer active */
1465           && mtctx->jobs[wJobID].frameChecksumNeeded ) {
1466             U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
1467             DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
1468             MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
1469             cSize += 4;
1470             mtctx->jobs[wJobID].cSize += 4;  /* can write this shared value, as worker is no longer active */
1471             mtctx->jobs[wJobID].frameChecksumNeeded = 0;
1472         }
1473 
1474         if (cSize > 0) {   /* compression is ongoing or completed */
1475             size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
1476             DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
1477                         (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
1478             assert(mtctx->doneJobID < mtctx->nextJobID);
1479             assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
1480             assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
1481             if (toFlush > 0) {
1482                 ZSTD_memcpy((char*)output->dst + output->pos,
1483                     (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
1484                     toFlush);
1485             }
1486             output->pos += toFlush;
1487             mtctx->jobs[wJobID].dstFlushed += toFlush;  /* can write : this value is only used by mtctx */
1488 
1489             if ( (srcConsumed == srcSize)    /* job is completed */
1490               && (mtctx->jobs[wJobID].dstFlushed == cSize) ) {   /* output buffer fully flushed => free this job position */
1491                 DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
1492                         mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
1493                 ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
1494                 DEBUGLOG(5, "dstBuffer released");
1495                 mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
1496                 mtctx->jobs[wJobID].cSize = 0;   /* ensure this job slot is considered "not started" in future check */
1497                 mtctx->consumed += srcSize;
1498                 mtctx->produced += cSize;
1499                 mtctx->doneJobID++;
1500         }   }
1501 
1502         /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
1503         if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
1504         if (srcSize > srcConsumed) return 1;   /* current job not completely compressed */
1505     }
1506     if (mtctx->doneJobID < mtctx->nextJobID) return 1;   /* some more jobs ongoing */
1507     if (mtctx->jobReady) return 1;      /* one job is ready to push, just not yet in the list */
1508     if (mtctx->inBuff.filled > 0) return 1;   /* input is not empty, and still needs to be converted into a job */
1509     mtctx->allJobsCompleted = mtctx->frameEnded;   /* all jobs are entirely flushed => if this one is last one, frame is completed */
1510     if (end == ZSTD_e_end) return !mtctx->frameEnded;  /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */
1511     return 0;   /* internal buffers fully flushed */
1512 }
1513 
1514 /**
1515  * Returns the range of data used by the earliest job that is not yet complete.
1516  * If the data of the first job is broken up into two segments, we cover both
1517  * sections.
1518  */
ZSTDMT_getInputDataInUse(ZSTDMT_CCtx * mtctx)1519 static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)
1520 {
1521     unsigned const firstJobID = mtctx->doneJobID;
1522     unsigned const lastJobID = mtctx->nextJobID;
1523     unsigned jobID;
1524 
1525     for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
1526         unsigned const wJobID = jobID & mtctx->jobIDMask;
1527         size_t consumed;
1528 
1529         ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
1530         consumed = mtctx->jobs[wJobID].consumed;
1531         ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
1532 
1533         if (consumed < mtctx->jobs[wJobID].src.size) {
1534             range_t range = mtctx->jobs[wJobID].prefix;
1535             if (range.size == 0) {
1536                 /* Empty prefix */
1537                 range = mtctx->jobs[wJobID].src;
1538             }
1539             /* Job source in multiple segments not supported yet */
1540             assert(range.start <= mtctx->jobs[wJobID].src.start);
1541             return range;
1542         }
1543     }
1544     return kNullRange;
1545 }
1546 
1547 /**
1548  * Returns non-zero iff buffer and range overlap.
1549  */
ZSTDMT_isOverlapped(buffer_t buffer,range_t range)1550 static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
1551 {
1552     BYTE const* const bufferStart = (BYTE const*)buffer.start;
1553     BYTE const* const rangeStart = (BYTE const*)range.start;
1554 
1555     if (rangeStart == NULL || bufferStart == NULL)
1556         return 0;
1557 
1558     {
1559         BYTE const* const bufferEnd = bufferStart + buffer.capacity;
1560         BYTE const* const rangeEnd = rangeStart + range.size;
1561 
1562         /* Empty ranges cannot overlap */
1563         if (bufferStart == bufferEnd || rangeStart == rangeEnd)
1564             return 0;
1565 
1566         return bufferStart < rangeEnd && rangeStart < bufferEnd;
1567     }
1568 }
1569 
ZSTDMT_doesOverlapWindow(buffer_t buffer,ZSTD_window_t window)1570 static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)
1571 {
1572     range_t extDict;
1573     range_t prefix;
1574 
1575     DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
1576     extDict.start = window.dictBase + window.lowLimit;
1577     extDict.size = window.dictLimit - window.lowLimit;
1578 
1579     prefix.start = window.base + window.dictLimit;
1580     prefix.size = window.nextSrc - (window.base + window.dictLimit);
1581     DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
1582                 (size_t)extDict.start,
1583                 (size_t)extDict.start + extDict.size);
1584     DEBUGLOG(5, "prefix  [0x%zx, 0x%zx)",
1585                 (size_t)prefix.start,
1586                 (size_t)prefix.start + prefix.size);
1587 
1588     return ZSTDMT_isOverlapped(buffer, extDict)
1589         || ZSTDMT_isOverlapped(buffer, prefix);
1590 }
1591 
ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx * mtctx,buffer_t buffer)1592 static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)
1593 {
1594     if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) {
1595         ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
1596         DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
1597         DEBUGLOG(5, "source  [0x%zx, 0x%zx)",
1598                     (size_t)buffer.start,
1599                     (size_t)buffer.start + buffer.capacity);
1600         ZSTD_PTHREAD_MUTEX_LOCK(mutex);
1601         while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {
1602             DEBUGLOG(5, "Waiting for LDM to finish...");
1603             ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);
1604         }
1605         DEBUGLOG(6, "Done waiting for LDM to finish");
1606         ZSTD_pthread_mutex_unlock(mutex);
1607     }
1608 }
1609 
1610 /**
1611  * Attempts to set the inBuff to the next section to fill.
1612  * If any part of the new section is still in use we give up.
1613  * Returns non-zero if the buffer is filled.
1614  */
ZSTDMT_tryGetInputRange(ZSTDMT_CCtx * mtctx)1615 static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)
1616 {
1617     range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
1618     size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
1619     size_t const target = mtctx->targetSectionSize;
1620     buffer_t buffer;
1621 
1622     DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
1623     assert(mtctx->inBuff.buffer.start == NULL);
1624     assert(mtctx->roundBuff.capacity >= target);
1625 
1626     if (spaceLeft < target) {
1627         /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
1628          * Simply copy the prefix to the beginning in that case.
1629          */
1630         BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
1631         size_t const prefixSize = mtctx->inBuff.prefix.size;
1632 
1633         buffer.start = start;
1634         buffer.capacity = prefixSize;
1635         if (ZSTDMT_isOverlapped(buffer, inUse)) {
1636             DEBUGLOG(5, "Waiting for buffer...");
1637             return 0;
1638         }
1639         ZSTDMT_waitForLdmComplete(mtctx, buffer);
1640         ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);
1641         mtctx->inBuff.prefix.start = start;
1642         mtctx->roundBuff.pos = prefixSize;
1643     }
1644     buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
1645     buffer.capacity = target;
1646 
1647     if (ZSTDMT_isOverlapped(buffer, inUse)) {
1648         DEBUGLOG(5, "Waiting for buffer...");
1649         return 0;
1650     }
1651     assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
1652 
1653     ZSTDMT_waitForLdmComplete(mtctx, buffer);
1654 
1655     DEBUGLOG(5, "Using prefix range [%zx, %zx)",
1656                 (size_t)mtctx->inBuff.prefix.start,
1657                 (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
1658     DEBUGLOG(5, "Using source range [%zx, %zx)",
1659                 (size_t)buffer.start,
1660                 (size_t)buffer.start + buffer.capacity);
1661 
1662 
1663     mtctx->inBuff.buffer = buffer;
1664     mtctx->inBuff.filled = 0;
1665     assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);
1666     return 1;
1667 }
1668 
1669 typedef struct {
1670   size_t toLoad;  /* The number of bytes to load from the input. */
1671   int flush;      /* Boolean declaring if we must flush because we found a synchronization point. */
1672 } syncPoint_t;
1673 
1674 /**
1675  * Searches through the input for a synchronization point. If one is found, we
1676  * will instruct the caller to flush, and return the number of bytes to load.
1677  * Otherwise, we will load as many bytes as possible and instruct the caller
1678  * to continue as normal.
1679  */
1680 static syncPoint_t
findSynchronizationPoint(ZSTDMT_CCtx const * mtctx,ZSTD_inBuffer const input)1681 findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)
1682 {
1683     BYTE const* const istart = (BYTE const*)input.src + input.pos;
1684     U64 const primePower = mtctx->rsync.primePower;
1685     U64 const hitMask = mtctx->rsync.hitMask;
1686 
1687     syncPoint_t syncPoint;
1688     U64 hash;
1689     BYTE const* prev;
1690     size_t pos;
1691 
1692     syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
1693     syncPoint.flush = 0;
1694     if (!mtctx->params.rsyncable)
1695         /* Rsync is disabled. */
1696         return syncPoint;
1697     if (mtctx->inBuff.filled + input.size - input.pos < RSYNC_MIN_BLOCK_SIZE)
1698         /* We don't emit synchronization points if it would produce too small blocks.
1699          * We don't have enough input to find a synchronization point, so don't look.
1700          */
1701         return syncPoint;
1702     if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
1703         /* Not enough to compute the hash.
1704          * We will miss any synchronization points in this RSYNC_LENGTH byte
1705          * window. However, since it depends only in the internal buffers, if the
1706          * state is already synchronized, we will remain synchronized.
1707          * Additionally, the probability that we miss a synchronization point is
1708          * low: RSYNC_LENGTH / targetSectionSize.
1709          */
1710         return syncPoint;
1711     /* Initialize the loop variables. */
1712     if (mtctx->inBuff.filled < RSYNC_MIN_BLOCK_SIZE) {
1713         /* We don't need to scan the first RSYNC_MIN_BLOCK_SIZE positions
1714          * because they can't possibly be a sync point. So we can start
1715          * part way through the input buffer.
1716          */
1717         pos = RSYNC_MIN_BLOCK_SIZE - mtctx->inBuff.filled;
1718         if (pos >= RSYNC_LENGTH) {
1719             prev = istart + pos - RSYNC_LENGTH;
1720             hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
1721         } else {
1722             assert(mtctx->inBuff.filled >= RSYNC_LENGTH);
1723             prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
1724             hash = ZSTD_rollingHash_compute(prev + pos, (RSYNC_LENGTH - pos));
1725             hash = ZSTD_rollingHash_append(hash, istart, pos);
1726         }
1727     } else {
1728         /* We have enough bytes buffered to initialize the hash,
1729          * and are have processed enough bytes to find a sync point.
1730          * Start scanning at the beginning of the input.
1731          */
1732         assert(mtctx->inBuff.filled >= RSYNC_MIN_BLOCK_SIZE);
1733         assert(RSYNC_MIN_BLOCK_SIZE >= RSYNC_LENGTH);
1734         pos = 0;
1735         prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
1736         hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
1737         if ((hash & hitMask) == hitMask) {
1738             /* We're already at a sync point so don't load any more until
1739              * we're able to flush this sync point.
1740              * This likely happened because the job table was full so we
1741              * couldn't add our job.
1742              */
1743             syncPoint.toLoad = 0;
1744             syncPoint.flush = 1;
1745             return syncPoint;
1746         }
1747     }
1748     /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
1749      * through the input. If we hit a synchronization point, then cut the
1750      * job off, and tell the compressor to flush the job. Otherwise, load
1751      * all the bytes and continue as normal.
1752      * If we go too long without a synchronization point (targetSectionSize)
1753      * then a block will be emitted anyways, but this is okay, since if we
1754      * are already synchronized we will remain synchronized.
1755      */
1756     for (; pos < syncPoint.toLoad; ++pos) {
1757         BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
1758         assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);
1759         hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
1760         assert(mtctx->inBuff.filled + pos >= RSYNC_MIN_BLOCK_SIZE);
1761         if ((hash & hitMask) == hitMask) {
1762             syncPoint.toLoad = pos + 1;
1763             syncPoint.flush = 1;
1764             break;
1765         }
1766     }
1767     return syncPoint;
1768 }
1769 
ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx * mtctx)1770 size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)
1771 {
1772     size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;
1773     if (hintInSize==0) hintInSize = mtctx->targetSectionSize;
1774     return hintInSize;
1775 }
1776 
1777 /** ZSTDMT_compressStream_generic() :
1778  *  internal use only - exposed to be invoked from zstd_compress.c
1779  *  assumption : output and input are valid (pos <= size)
1780  * @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)1781 size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
1782                                      ZSTD_outBuffer* output,
1783                                      ZSTD_inBuffer* input,
1784                                      ZSTD_EndDirective endOp)
1785 {
1786     unsigned forwardInputProgress = 0;
1787     DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
1788                 (U32)endOp, (U32)(input->size - input->pos));
1789     assert(output->pos <= output->size);
1790     assert(input->pos  <= input->size);
1791 
1792     if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
1793         /* current frame being ended. Only flush/end are allowed */
1794         return ERROR(stage_wrong);
1795     }
1796 
1797     /* fill input buffer */
1798     if ( (!mtctx->jobReady)
1799       && (input->size > input->pos) ) {   /* support NULL input */
1800         if (mtctx->inBuff.buffer.start == NULL) {
1801             assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
1802             if (!ZSTDMT_tryGetInputRange(mtctx)) {
1803                 /* It is only possible for this operation to fail if there are
1804                  * still compression jobs ongoing.
1805                  */
1806                 DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
1807                 assert(mtctx->doneJobID != mtctx->nextJobID);
1808             } else
1809                 DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
1810         }
1811         if (mtctx->inBuff.buffer.start != NULL) {
1812             syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
1813             if (syncPoint.flush && endOp == ZSTD_e_continue) {
1814                 endOp = ZSTD_e_flush;
1815             }
1816             assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
1817             DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
1818                         (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
1819             ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
1820             input->pos += syncPoint.toLoad;
1821             mtctx->inBuff.filled += syncPoint.toLoad;
1822             forwardInputProgress = syncPoint.toLoad>0;
1823         }
1824     }
1825     if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {
1826         /* Can't end yet because the input is not fully consumed.
1827             * We are in one of these cases:
1828             * - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.
1829             * - We filled the input buffer: flush this job but don't end the frame.
1830             * - We hit a synchronization point: flush this job but don't end the frame.
1831             */
1832         assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);
1833         endOp = ZSTD_e_flush;
1834     }
1835 
1836     if ( (mtctx->jobReady)
1837       || (mtctx->inBuff.filled >= mtctx->targetSectionSize)  /* filled enough : let's compress */
1838       || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0))  /* something to flush : let's go */
1839       || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) {   /* must finish the frame with a zero-size block */
1840         size_t const jobSize = mtctx->inBuff.filled;
1841         assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
1842         FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");
1843     }
1844 
1845     /* check for potential compressed data ready to be flushed */
1846     {   size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */
1847         if (input->pos < input->size) return MAX(remainingToFlush, 1);  /* input not consumed : do not end flush yet */
1848         DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);
1849         return remainingToFlush;
1850     }
1851 }
1852