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