10c16b537SWarner Losh /*
2*5ff13fbcSAllan Jude * Copyright (c) Yann Collet, Facebook, Inc.
30c16b537SWarner Losh * All rights reserved.
40c16b537SWarner Losh *
50c16b537SWarner Losh * This source code is licensed under both the BSD-style license (found in the
60c16b537SWarner Losh * LICENSE file in the root directory of this source tree) and the GPLv2 (found
70c16b537SWarner Losh * in the COPYING file in the root directory of this source tree).
80c16b537SWarner Losh * You may select, at your option, one of the above-listed licenses.
90c16b537SWarner Losh */
100c16b537SWarner Losh
110c16b537SWarner Losh
120c16b537SWarner Losh /* ====== Compiler specifics ====== */
130c16b537SWarner Losh #if defined(_MSC_VER)
140c16b537SWarner Losh # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
150c16b537SWarner Losh #endif
160c16b537SWarner Losh
170c16b537SWarner Losh
18a0483764SConrad Meyer /* ====== Constants ====== */
19a0483764SConrad Meyer #define ZSTDMT_OVERLAPLOG_DEFAULT 0
20a0483764SConrad Meyer
21a0483764SConrad Meyer
220c16b537SWarner Losh /* ====== Dependencies ====== */
23f7cd7fe5SConrad Meyer #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset, INT_MAX, UINT_MAX */
2437f1f268SConrad Meyer #include "../common/mem.h" /* MEM_STATIC */
2537f1f268SConrad Meyer #include "../common/pool.h" /* threadpool */
2637f1f268SConrad Meyer #include "../common/threading.h" /* mutex */
27052d3c12SConrad Meyer #include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
2819fcbaf1SConrad Meyer #include "zstd_ldm.h"
290c16b537SWarner Losh #include "zstdmt_compress.h"
300c16b537SWarner Losh
3119fcbaf1SConrad Meyer /* Guards code to support resizing the SeqPool.
3219fcbaf1SConrad Meyer * We will want to resize the SeqPool to save memory in the future.
3319fcbaf1SConrad Meyer * Until then, comment the code out since it is unused.
3419fcbaf1SConrad Meyer */
3519fcbaf1SConrad Meyer #define ZSTD_RESIZE_SEQPOOL 0
360c16b537SWarner Losh
370c16b537SWarner Losh /* ====== Debug ====== */
380f743729SConrad Meyer #if defined(DEBUGLEVEL) && (DEBUGLEVEL>=2) \
390f743729SConrad Meyer && !defined(_MSC_VER) \
400f743729SConrad Meyer && !defined(__MINGW32__)
410c16b537SWarner Losh
420c16b537SWarner Losh # include <stdio.h>
430c16b537SWarner Losh # include <unistd.h>
440c16b537SWarner Losh # include <sys/times.h>
450c16b537SWarner Losh
460c16b537SWarner Losh # define DEBUG_PRINTHEX(l,p,n) { \
470c16b537SWarner Losh unsigned debug_u; \
480c16b537SWarner Losh for (debug_u=0; debug_u<(n); debug_u++) \
490f743729SConrad Meyer RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
500f743729SConrad Meyer RAWLOG(l, " \n"); \
510c16b537SWarner Losh }
520c16b537SWarner Losh
GetCurrentClockTimeMicroseconds(void)530c16b537SWarner Losh static unsigned long long GetCurrentClockTimeMicroseconds(void)
540c16b537SWarner Losh {
550c16b537SWarner Losh static clock_t _ticksPerSecond = 0;
560c16b537SWarner Losh if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);
570c16b537SWarner Losh
580c16b537SWarner Losh { struct tms junk; clock_t newTicks = (clock_t) times(&junk);
59a0483764SConrad Meyer return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);
60a0483764SConrad Meyer } }
610c16b537SWarner Losh
620c16b537SWarner Losh #define MUTEX_WAIT_TIME_DLEVEL 6
630c16b537SWarner Losh #define ZSTD_PTHREAD_MUTEX_LOCK(mutex) { \
640f743729SConrad Meyer if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) { \
650c16b537SWarner Losh unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \
660c16b537SWarner Losh ZSTD_pthread_mutex_lock(mutex); \
670c16b537SWarner Losh { unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
680c16b537SWarner Losh unsigned long long const elapsedTime = (afterTime-beforeTime); \
690c16b537SWarner Losh if (elapsedTime > 1000) { /* or whatever threshold you like; I'm using 1 millisecond here */ \
700c16b537SWarner Losh DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \
710c16b537SWarner Losh elapsedTime, #mutex); \
720c16b537SWarner Losh } } \
730c16b537SWarner Losh } else { \
740c16b537SWarner Losh ZSTD_pthread_mutex_lock(mutex); \
750c16b537SWarner Losh } \
760c16b537SWarner Losh }
770c16b537SWarner Losh
780c16b537SWarner Losh #else
790c16b537SWarner Losh
800c16b537SWarner Losh # define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)
810c16b537SWarner Losh # define DEBUG_PRINTHEX(l,p,n) {}
820c16b537SWarner Losh
830c16b537SWarner Losh #endif
840c16b537SWarner Losh
850c16b537SWarner Losh
860c16b537SWarner Losh /* ===== Buffer Pool ===== */
870c16b537SWarner Losh /* a single Buffer Pool can be invoked from multiple threads in parallel */
880c16b537SWarner Losh
890c16b537SWarner Losh typedef struct buffer_s {
900c16b537SWarner Losh void* start;
9119fcbaf1SConrad Meyer size_t capacity;
920c16b537SWarner Losh } buffer_t;
930c16b537SWarner Losh
940c16b537SWarner Losh static const buffer_t g_nullBuffer = { NULL, 0 };
950c16b537SWarner Losh
960c16b537SWarner Losh typedef struct ZSTDMT_bufferPool_s {
970c16b537SWarner Losh ZSTD_pthread_mutex_t poolMutex;
980c16b537SWarner Losh size_t bufferSize;
990c16b537SWarner Losh unsigned totalBuffers;
1000c16b537SWarner Losh unsigned nbBuffers;
1010c16b537SWarner Losh ZSTD_customMem cMem;
1020c16b537SWarner Losh buffer_t bTable[1]; /* variable size */
1030c16b537SWarner Losh } ZSTDMT_bufferPool;
1040c16b537SWarner Losh
ZSTDMT_createBufferPool(unsigned maxNbBuffers,ZSTD_customMem cMem)105*5ff13fbcSAllan Jude static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_customMem cMem)
1060c16b537SWarner Losh {
107f7cd7fe5SConrad Meyer ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_customCalloc(
1080c16b537SWarner Losh sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);
1090c16b537SWarner Losh if (bufPool==NULL) return NULL;
1100c16b537SWarner Losh if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
111f7cd7fe5SConrad Meyer ZSTD_customFree(bufPool, cMem);
1120c16b537SWarner Losh return NULL;
1130c16b537SWarner Losh }
1140c16b537SWarner Losh bufPool->bufferSize = 64 KB;
1150c16b537SWarner Losh bufPool->totalBuffers = maxNbBuffers;
1160c16b537SWarner Losh bufPool->nbBuffers = 0;
1170c16b537SWarner Losh bufPool->cMem = cMem;
1180c16b537SWarner Losh return bufPool;
1190c16b537SWarner Losh }
1200c16b537SWarner Losh
ZSTDMT_freeBufferPool(ZSTDMT_bufferPool * bufPool)1210c16b537SWarner Losh static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
1220c16b537SWarner Losh {
1230c16b537SWarner Losh unsigned u;
1240c16b537SWarner Losh DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
1250c16b537SWarner Losh if (!bufPool) return; /* compatibility with free on NULL */
1260c16b537SWarner Losh for (u=0; u<bufPool->totalBuffers; u++) {
1270c16b537SWarner Losh DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);
128f7cd7fe5SConrad Meyer ZSTD_customFree(bufPool->bTable[u].start, bufPool->cMem);
1290c16b537SWarner Losh }
1300c16b537SWarner Losh ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
131f7cd7fe5SConrad Meyer ZSTD_customFree(bufPool, bufPool->cMem);
1320c16b537SWarner Losh }
1330c16b537SWarner Losh
1340c16b537SWarner Losh /* only works at initialization, not during compression */
ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool * bufPool)1350c16b537SWarner Losh static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)
1360c16b537SWarner Losh {
1370c16b537SWarner Losh size_t const poolSize = sizeof(*bufPool)
1380c16b537SWarner Losh + (bufPool->totalBuffers - 1) * sizeof(buffer_t);
1390c16b537SWarner Losh unsigned u;
1400c16b537SWarner Losh size_t totalBufferSize = 0;
1410c16b537SWarner Losh ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
1420c16b537SWarner Losh for (u=0; u<bufPool->totalBuffers; u++)
14319fcbaf1SConrad Meyer totalBufferSize += bufPool->bTable[u].capacity;
1440c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
1450c16b537SWarner Losh
1460c16b537SWarner Losh return poolSize + totalBufferSize;
1470c16b537SWarner Losh }
1480c16b537SWarner Losh
14919fcbaf1SConrad Meyer /* ZSTDMT_setBufferSize() :
15019fcbaf1SConrad Meyer * all future buffers provided by this buffer pool will have _at least_ this size
15119fcbaf1SConrad Meyer * note : it's better for all buffers to have same size,
15219fcbaf1SConrad Meyer * as they become freely interchangeable, reducing malloc/free usages and memory fragmentation */
ZSTDMT_setBufferSize(ZSTDMT_bufferPool * const bufPool,size_t const bSize)153052d3c12SConrad Meyer static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* const bufPool, size_t const bSize)
1540c16b537SWarner Losh {
155052d3c12SConrad Meyer ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
156052d3c12SConrad Meyer DEBUGLOG(4, "ZSTDMT_setBufferSize: bSize = %u", (U32)bSize);
1570c16b537SWarner Losh bufPool->bufferSize = bSize;
158052d3c12SConrad Meyer ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
1590c16b537SWarner Losh }
1600c16b537SWarner Losh
1610f743729SConrad Meyer
ZSTDMT_expandBufferPool(ZSTDMT_bufferPool * srcBufPool,unsigned maxNbBuffers)162*5ff13fbcSAllan Jude static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, unsigned maxNbBuffers)
1630f743729SConrad Meyer {
1640f743729SConrad Meyer if (srcBufPool==NULL) return NULL;
1650f743729SConrad Meyer if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */
1660f743729SConrad Meyer return srcBufPool;
1670f743729SConrad Meyer /* need a larger buffer pool */
1680f743729SConrad Meyer { ZSTD_customMem const cMem = srcBufPool->cMem;
1690f743729SConrad Meyer size_t const bSize = srcBufPool->bufferSize; /* forward parameters */
1700f743729SConrad Meyer ZSTDMT_bufferPool* newBufPool;
1710f743729SConrad Meyer ZSTDMT_freeBufferPool(srcBufPool);
172*5ff13fbcSAllan Jude newBufPool = ZSTDMT_createBufferPool(maxNbBuffers, cMem);
1730f743729SConrad Meyer if (newBufPool==NULL) return newBufPool;
1740f743729SConrad Meyer ZSTDMT_setBufferSize(newBufPool, bSize);
1750f743729SConrad Meyer return newBufPool;
1760f743729SConrad Meyer }
1770f743729SConrad Meyer }
1780f743729SConrad Meyer
1790c16b537SWarner Losh /** ZSTDMT_getBuffer() :
18019fcbaf1SConrad Meyer * assumption : bufPool must be valid
18119fcbaf1SConrad Meyer * @return : a buffer, with start pointer and size
18219fcbaf1SConrad Meyer * note: allocation may fail, in this case, start==NULL and size==0 */
ZSTDMT_getBuffer(ZSTDMT_bufferPool * bufPool)1830c16b537SWarner Losh static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)
1840c16b537SWarner Losh {
1850c16b537SWarner Losh size_t const bSize = bufPool->bufferSize;
186052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);
1870c16b537SWarner Losh ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
1880c16b537SWarner Losh if (bufPool->nbBuffers) { /* try to use an existing buffer */
1890c16b537SWarner Losh buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];
19019fcbaf1SConrad Meyer size_t const availBufferSize = buf.capacity;
1910c16b537SWarner Losh bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;
192052d3c12SConrad Meyer if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {
1930c16b537SWarner Losh /* large enough, but not too much */
194052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",
19519fcbaf1SConrad Meyer bufPool->nbBuffers, (U32)buf.capacity);
1960c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
1970c16b537SWarner Losh return buf;
1980c16b537SWarner Losh }
1990c16b537SWarner Losh /* size conditions not respected : scratch this buffer, create new one */
200052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");
201f7cd7fe5SConrad Meyer ZSTD_customFree(buf.start, bufPool->cMem);
2020c16b537SWarner Losh }
2030c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
2040c16b537SWarner Losh /* create new buffer */
205052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");
2060c16b537SWarner Losh { buffer_t buffer;
207f7cd7fe5SConrad Meyer void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);
2080c16b537SWarner Losh buffer.start = start; /* note : start can be NULL if malloc fails ! */
20919fcbaf1SConrad Meyer buffer.capacity = (start==NULL) ? 0 : bSize;
21019fcbaf1SConrad Meyer if (start==NULL) {
21119fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: buffer allocation failure !!");
21219fcbaf1SConrad Meyer } else {
213052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_getBuffer: created buffer of size %u", (U32)bSize);
21419fcbaf1SConrad Meyer }
2150c16b537SWarner Losh return buffer;
2160c16b537SWarner Losh }
2170c16b537SWarner Losh }
2180c16b537SWarner Losh
21919fcbaf1SConrad Meyer #if ZSTD_RESIZE_SEQPOOL
22019fcbaf1SConrad Meyer /** ZSTDMT_resizeBuffer() :
22119fcbaf1SConrad Meyer * assumption : bufPool must be valid
22219fcbaf1SConrad Meyer * @return : a buffer that is at least the buffer pool buffer size.
22319fcbaf1SConrad Meyer * If a reallocation happens, the data in the input buffer is copied.
22419fcbaf1SConrad Meyer */
ZSTDMT_resizeBuffer(ZSTDMT_bufferPool * bufPool,buffer_t buffer)22519fcbaf1SConrad Meyer static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer)
22619fcbaf1SConrad Meyer {
22719fcbaf1SConrad Meyer size_t const bSize = bufPool->bufferSize;
22819fcbaf1SConrad Meyer if (buffer.capacity < bSize) {
229f7cd7fe5SConrad Meyer void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);
23019fcbaf1SConrad Meyer buffer_t newBuffer;
23119fcbaf1SConrad Meyer newBuffer.start = start;
23219fcbaf1SConrad Meyer newBuffer.capacity = start == NULL ? 0 : bSize;
23319fcbaf1SConrad Meyer if (start != NULL) {
23419fcbaf1SConrad Meyer assert(newBuffer.capacity >= buffer.capacity);
235f7cd7fe5SConrad Meyer ZSTD_memcpy(newBuffer.start, buffer.start, buffer.capacity);
23619fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_resizeBuffer: created buffer of size %u", (U32)bSize);
23719fcbaf1SConrad Meyer return newBuffer;
23819fcbaf1SConrad Meyer }
23919fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_resizeBuffer: buffer allocation failure !!");
24019fcbaf1SConrad Meyer }
24119fcbaf1SConrad Meyer return buffer;
24219fcbaf1SConrad Meyer }
24319fcbaf1SConrad Meyer #endif
24419fcbaf1SConrad Meyer
2450c16b537SWarner Losh /* store buffer for later re-use, up to pool capacity */
ZSTDMT_releaseBuffer(ZSTDMT_bufferPool * bufPool,buffer_t buf)2460c16b537SWarner Losh static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
2470c16b537SWarner Losh {
2480c16b537SWarner Losh DEBUGLOG(5, "ZSTDMT_releaseBuffer");
2490f743729SConrad Meyer if (buf.start == NULL) return; /* compatible with release on NULL */
2500c16b537SWarner Losh ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
2510c16b537SWarner Losh if (bufPool->nbBuffers < bufPool->totalBuffers) {
2520c16b537SWarner Losh bufPool->bTable[bufPool->nbBuffers++] = buf; /* stored for later use */
253052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",
25419fcbaf1SConrad Meyer (U32)buf.capacity, (U32)(bufPool->nbBuffers-1));
2550c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
2560c16b537SWarner Losh return;
2570c16b537SWarner Losh }
2580c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
2590c16b537SWarner Losh /* Reached bufferPool capacity (should not happen) */
260052d3c12SConrad Meyer DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");
261f7cd7fe5SConrad Meyer ZSTD_customFree(buf.start, bufPool->cMem);
2620c16b537SWarner Losh }
2630c16b537SWarner Losh
264*5ff13fbcSAllan Jude /* We need 2 output buffers per worker since each dstBuff must be flushed after it is released.
265*5ff13fbcSAllan Jude * The 3 additional buffers are as follows:
266*5ff13fbcSAllan Jude * 1 buffer for input loading
267*5ff13fbcSAllan Jude * 1 buffer for "next input" when submitting current one
268*5ff13fbcSAllan Jude * 1 buffer stuck in queue */
269*5ff13fbcSAllan Jude #define BUF_POOL_MAX_NB_BUFFERS(nbWorkers) 2*nbWorkers + 3
270*5ff13fbcSAllan Jude
271*5ff13fbcSAllan Jude /* After a worker releases its rawSeqStore, it is immediately ready for reuse.
272*5ff13fbcSAllan Jude * So we only need one seq buffer per worker. */
273*5ff13fbcSAllan Jude #define SEQ_POOL_MAX_NB_BUFFERS(nbWorkers) nbWorkers
27419fcbaf1SConrad Meyer
27519fcbaf1SConrad Meyer /* ===== Seq Pool Wrapper ====== */
27619fcbaf1SConrad Meyer
27719fcbaf1SConrad Meyer typedef ZSTDMT_bufferPool ZSTDMT_seqPool;
27819fcbaf1SConrad Meyer
ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool * seqPool)27919fcbaf1SConrad Meyer static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)
2800c16b537SWarner Losh {
28119fcbaf1SConrad Meyer return ZSTDMT_sizeof_bufferPool(seqPool);
2820c16b537SWarner Losh }
2830c16b537SWarner Losh
bufferToSeq(buffer_t buffer)28419fcbaf1SConrad Meyer static rawSeqStore_t bufferToSeq(buffer_t buffer)
28519fcbaf1SConrad Meyer {
286f7cd7fe5SConrad Meyer rawSeqStore_t seq = kNullRawSeqStore;
28719fcbaf1SConrad Meyer seq.seq = (rawSeq*)buffer.start;
28819fcbaf1SConrad Meyer seq.capacity = buffer.capacity / sizeof(rawSeq);
28919fcbaf1SConrad Meyer return seq;
29019fcbaf1SConrad Meyer }
29119fcbaf1SConrad Meyer
seqToBuffer(rawSeqStore_t seq)29219fcbaf1SConrad Meyer static buffer_t seqToBuffer(rawSeqStore_t seq)
29319fcbaf1SConrad Meyer {
29419fcbaf1SConrad Meyer buffer_t buffer;
29519fcbaf1SConrad Meyer buffer.start = seq.seq;
29619fcbaf1SConrad Meyer buffer.capacity = seq.capacity * sizeof(rawSeq);
29719fcbaf1SConrad Meyer return buffer;
29819fcbaf1SConrad Meyer }
29919fcbaf1SConrad Meyer
ZSTDMT_getSeq(ZSTDMT_seqPool * seqPool)30019fcbaf1SConrad Meyer static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)
30119fcbaf1SConrad Meyer {
30219fcbaf1SConrad Meyer if (seqPool->bufferSize == 0) {
30319fcbaf1SConrad Meyer return kNullRawSeqStore;
30419fcbaf1SConrad Meyer }
30519fcbaf1SConrad Meyer return bufferToSeq(ZSTDMT_getBuffer(seqPool));
30619fcbaf1SConrad Meyer }
30719fcbaf1SConrad Meyer
30819fcbaf1SConrad Meyer #if ZSTD_RESIZE_SEQPOOL
ZSTDMT_resizeSeq(ZSTDMT_seqPool * seqPool,rawSeqStore_t seq)30919fcbaf1SConrad Meyer static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
31019fcbaf1SConrad Meyer {
31119fcbaf1SConrad Meyer return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));
31219fcbaf1SConrad Meyer }
31319fcbaf1SConrad Meyer #endif
31419fcbaf1SConrad Meyer
ZSTDMT_releaseSeq(ZSTDMT_seqPool * seqPool,rawSeqStore_t seq)31519fcbaf1SConrad Meyer static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
31619fcbaf1SConrad Meyer {
31719fcbaf1SConrad Meyer ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));
31819fcbaf1SConrad Meyer }
31919fcbaf1SConrad Meyer
ZSTDMT_setNbSeq(ZSTDMT_seqPool * const seqPool,size_t const nbSeq)32019fcbaf1SConrad Meyer static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)
32119fcbaf1SConrad Meyer {
32219fcbaf1SConrad Meyer ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));
32319fcbaf1SConrad Meyer }
32419fcbaf1SConrad Meyer
ZSTDMT_createSeqPool(unsigned nbWorkers,ZSTD_customMem cMem)32519fcbaf1SConrad Meyer static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)
32619fcbaf1SConrad Meyer {
327*5ff13fbcSAllan Jude ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(SEQ_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);
3280f743729SConrad Meyer if (seqPool == NULL) return NULL;
32919fcbaf1SConrad Meyer ZSTDMT_setNbSeq(seqPool, 0);
33019fcbaf1SConrad Meyer return seqPool;
33119fcbaf1SConrad Meyer }
33219fcbaf1SConrad Meyer
ZSTDMT_freeSeqPool(ZSTDMT_seqPool * seqPool)33319fcbaf1SConrad Meyer static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)
33419fcbaf1SConrad Meyer {
33519fcbaf1SConrad Meyer ZSTDMT_freeBufferPool(seqPool);
33619fcbaf1SConrad Meyer }
33719fcbaf1SConrad Meyer
ZSTDMT_expandSeqPool(ZSTDMT_seqPool * pool,U32 nbWorkers)3380f743729SConrad Meyer static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)
3390f743729SConrad Meyer {
340*5ff13fbcSAllan Jude return ZSTDMT_expandBufferPool(pool, SEQ_POOL_MAX_NB_BUFFERS(nbWorkers));
3410f743729SConrad Meyer }
34219fcbaf1SConrad Meyer
34319fcbaf1SConrad Meyer
3440c16b537SWarner Losh /* ===== CCtx Pool ===== */
3450c16b537SWarner Losh /* a single CCtx Pool can be invoked from multiple threads in parallel */
3460c16b537SWarner Losh
3470c16b537SWarner Losh typedef struct {
3480c16b537SWarner Losh ZSTD_pthread_mutex_t poolMutex;
349a0483764SConrad Meyer int totalCCtx;
350a0483764SConrad Meyer int availCCtx;
3510c16b537SWarner Losh ZSTD_customMem cMem;
3520c16b537SWarner Losh ZSTD_CCtx* cctx[1]; /* variable size */
3530c16b537SWarner Losh } ZSTDMT_CCtxPool;
3540c16b537SWarner Losh
3550c16b537SWarner Losh /* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool * pool)3560c16b537SWarner Losh static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
3570c16b537SWarner Losh {
358a0483764SConrad Meyer int cid;
359a0483764SConrad Meyer for (cid=0; cid<pool->totalCCtx; cid++)
360a0483764SConrad Meyer ZSTD_freeCCtx(pool->cctx[cid]); /* note : compatible with free on NULL */
3610c16b537SWarner Losh ZSTD_pthread_mutex_destroy(&pool->poolMutex);
362f7cd7fe5SConrad Meyer ZSTD_customFree(pool, pool->cMem);
3630c16b537SWarner Losh }
3640c16b537SWarner Losh
3650c16b537SWarner Losh /* ZSTDMT_createCCtxPool() :
36619fcbaf1SConrad Meyer * implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */
ZSTDMT_createCCtxPool(int nbWorkers,ZSTD_customMem cMem)367a0483764SConrad Meyer static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
3680c16b537SWarner Losh ZSTD_customMem cMem)
3690c16b537SWarner Losh {
370f7cd7fe5SConrad Meyer ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_customCalloc(
37119fcbaf1SConrad Meyer sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);
37219fcbaf1SConrad Meyer assert(nbWorkers > 0);
3730c16b537SWarner Losh if (!cctxPool) return NULL;
3740c16b537SWarner Losh if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
375f7cd7fe5SConrad Meyer ZSTD_customFree(cctxPool, cMem);
3760c16b537SWarner Losh return NULL;
3770c16b537SWarner Losh }
3780c16b537SWarner Losh cctxPool->cMem = cMem;
37919fcbaf1SConrad Meyer cctxPool->totalCCtx = nbWorkers;
3800c16b537SWarner Losh cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
3810c16b537SWarner Losh cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
3820c16b537SWarner Losh if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
38319fcbaf1SConrad Meyer DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
3840c16b537SWarner Losh return cctxPool;
3850c16b537SWarner Losh }
3860c16b537SWarner Losh
ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool * srcPool,int nbWorkers)3870f743729SConrad Meyer static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,
388a0483764SConrad Meyer int nbWorkers)
3890f743729SConrad Meyer {
3900f743729SConrad Meyer if (srcPool==NULL) return NULL;
3910f743729SConrad Meyer if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */
3920f743729SConrad Meyer /* need a larger cctx pool */
3930f743729SConrad Meyer { ZSTD_customMem const cMem = srcPool->cMem;
3940f743729SConrad Meyer ZSTDMT_freeCCtxPool(srcPool);
3950f743729SConrad Meyer return ZSTDMT_createCCtxPool(nbWorkers, cMem);
3960f743729SConrad Meyer }
3970f743729SConrad Meyer }
3980f743729SConrad Meyer
3990c16b537SWarner Losh /* only works during initialization phase, not during compression */
ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool * cctxPool)4000c16b537SWarner Losh static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
4010c16b537SWarner Losh {
4020c16b537SWarner Losh ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
40319fcbaf1SConrad Meyer { unsigned const nbWorkers = cctxPool->totalCCtx;
4040c16b537SWarner Losh size_t const poolSize = sizeof(*cctxPool)
40519fcbaf1SConrad Meyer + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
4060c16b537SWarner Losh unsigned u;
4070c16b537SWarner Losh size_t totalCCtxSize = 0;
40819fcbaf1SConrad Meyer for (u=0; u<nbWorkers; u++) {
4090c16b537SWarner Losh totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);
4100c16b537SWarner Losh }
4110c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
41219fcbaf1SConrad Meyer assert(nbWorkers > 0);
4130c16b537SWarner Losh return poolSize + totalCCtxSize;
4140c16b537SWarner Losh }
4150c16b537SWarner Losh }
4160c16b537SWarner Losh
ZSTDMT_getCCtx(ZSTDMT_CCtxPool * cctxPool)4170c16b537SWarner Losh static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
4180c16b537SWarner Losh {
4190c16b537SWarner Losh DEBUGLOG(5, "ZSTDMT_getCCtx");
4200c16b537SWarner Losh ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
4210c16b537SWarner Losh if (cctxPool->availCCtx) {
4220c16b537SWarner Losh cctxPool->availCCtx--;
4230c16b537SWarner Losh { ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
4240c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
4250c16b537SWarner Losh return cctx;
4260c16b537SWarner Losh } }
4270c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
4280c16b537SWarner Losh DEBUGLOG(5, "create one more CCtx");
4290c16b537SWarner Losh return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */
4300c16b537SWarner Losh }
4310c16b537SWarner Losh
ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool * pool,ZSTD_CCtx * cctx)4320c16b537SWarner Losh static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
4330c16b537SWarner Losh {
4340c16b537SWarner Losh if (cctx==NULL) return; /* compatibility with release on NULL */
4350c16b537SWarner Losh ZSTD_pthread_mutex_lock(&pool->poolMutex);
4360c16b537SWarner Losh if (pool->availCCtx < pool->totalCCtx)
4370c16b537SWarner Losh pool->cctx[pool->availCCtx++] = cctx;
4380c16b537SWarner Losh else {
43919fcbaf1SConrad Meyer /* pool overflow : should not happen, since totalCCtx==nbWorkers */
44019fcbaf1SConrad Meyer DEBUGLOG(4, "CCtx pool overflow : free cctx");
4410c16b537SWarner Losh ZSTD_freeCCtx(cctx);
4420c16b537SWarner Losh }
4430c16b537SWarner Losh ZSTD_pthread_mutex_unlock(&pool->poolMutex);
4440c16b537SWarner Losh }
4450c16b537SWarner Losh
44619fcbaf1SConrad Meyer /* ==== Serial State ==== */
4470c16b537SWarner Losh
4480c16b537SWarner Losh typedef struct {
44919fcbaf1SConrad Meyer void const* start;
45019fcbaf1SConrad Meyer size_t size;
45119fcbaf1SConrad Meyer } range_t;
45219fcbaf1SConrad Meyer
45319fcbaf1SConrad Meyer typedef struct {
45419fcbaf1SConrad Meyer /* All variables in the struct are protected by mutex. */
45519fcbaf1SConrad Meyer ZSTD_pthread_mutex_t mutex;
45619fcbaf1SConrad Meyer ZSTD_pthread_cond_t cond;
4570c16b537SWarner Losh ZSTD_CCtx_params params;
45819fcbaf1SConrad Meyer ldmState_t ldmState;
45919fcbaf1SConrad Meyer XXH64_state_t xxhState;
46019fcbaf1SConrad Meyer unsigned nextJobID;
46119fcbaf1SConrad Meyer /* Protects ldmWindow.
46219fcbaf1SConrad Meyer * Must be acquired after the main mutex when acquiring both.
46319fcbaf1SConrad Meyer */
46419fcbaf1SConrad Meyer ZSTD_pthread_mutex_t ldmWindowMutex;
4652b9c00cbSConrad Meyer ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is updated */
46619fcbaf1SConrad Meyer ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */
46719fcbaf1SConrad Meyer } serialState_t;
46819fcbaf1SConrad Meyer
46937f1f268SConrad Meyer static int
ZSTDMT_serialState_reset(serialState_t * serialState,ZSTDMT_seqPool * seqPool,ZSTD_CCtx_params params,size_t jobSize,const void * dict,size_t const dictSize,ZSTD_dictContentType_e dictContentType)47037f1f268SConrad Meyer ZSTDMT_serialState_reset(serialState_t* serialState,
47137f1f268SConrad Meyer ZSTDMT_seqPool* seqPool,
47237f1f268SConrad Meyer ZSTD_CCtx_params params,
47337f1f268SConrad Meyer size_t jobSize,
47437f1f268SConrad Meyer const void* dict, size_t const dictSize,
47537f1f268SConrad Meyer ZSTD_dictContentType_e dictContentType)
47619fcbaf1SConrad Meyer {
47719fcbaf1SConrad Meyer /* Adjust parameters */
478*5ff13fbcSAllan Jude if (params.ldmParams.enableLdm == ZSTD_ps_enable) {
47919fcbaf1SConrad Meyer DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);
48019fcbaf1SConrad Meyer ZSTD_ldm_adjustParameters(¶ms.ldmParams, ¶ms.cParams);
48119fcbaf1SConrad Meyer assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
482a0483764SConrad Meyer assert(params.ldmParams.hashRateLog < 32);
48319fcbaf1SConrad Meyer } else {
484f7cd7fe5SConrad Meyer ZSTD_memset(¶ms.ldmParams, 0, sizeof(params.ldmParams));
48519fcbaf1SConrad Meyer }
48619fcbaf1SConrad Meyer serialState->nextJobID = 0;
48719fcbaf1SConrad Meyer if (params.fParams.checksumFlag)
48819fcbaf1SConrad Meyer XXH64_reset(&serialState->xxhState, 0);
489*5ff13fbcSAllan Jude if (params.ldmParams.enableLdm == ZSTD_ps_enable) {
49019fcbaf1SConrad Meyer ZSTD_customMem cMem = params.customMem;
49119fcbaf1SConrad Meyer unsigned const hashLog = params.ldmParams.hashLog;
49219fcbaf1SConrad Meyer size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);
49319fcbaf1SConrad Meyer unsigned const bucketLog =
49419fcbaf1SConrad Meyer params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;
49519fcbaf1SConrad Meyer unsigned const prevBucketLog =
49619fcbaf1SConrad Meyer serialState->params.ldmParams.hashLog -
49719fcbaf1SConrad Meyer serialState->params.ldmParams.bucketSizeLog;
498*5ff13fbcSAllan Jude size_t const numBuckets = (size_t)1 << bucketLog;
49919fcbaf1SConrad Meyer /* Size the seq pool tables */
5000f743729SConrad Meyer ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));
50119fcbaf1SConrad Meyer /* Reset the window */
50237f1f268SConrad Meyer ZSTD_window_init(&serialState->ldmState.window);
50319fcbaf1SConrad Meyer /* Resize tables and output space if necessary. */
50419fcbaf1SConrad Meyer if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {
505f7cd7fe5SConrad Meyer ZSTD_customFree(serialState->ldmState.hashTable, cMem);
506f7cd7fe5SConrad Meyer serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_customMalloc(hashSize, cMem);
50719fcbaf1SConrad Meyer }
50819fcbaf1SConrad Meyer if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {
509f7cd7fe5SConrad Meyer ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);
510*5ff13fbcSAllan Jude serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_customMalloc(numBuckets, cMem);
51119fcbaf1SConrad Meyer }
51219fcbaf1SConrad Meyer if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)
51319fcbaf1SConrad Meyer return 1;
51419fcbaf1SConrad Meyer /* Zero the tables */
515f7cd7fe5SConrad Meyer ZSTD_memset(serialState->ldmState.hashTable, 0, hashSize);
516*5ff13fbcSAllan Jude ZSTD_memset(serialState->ldmState.bucketOffsets, 0, numBuckets);
51737f1f268SConrad Meyer
51837f1f268SConrad Meyer /* Update window state and fill hash table with dict */
51937f1f268SConrad Meyer serialState->ldmState.loadedDictEnd = 0;
52037f1f268SConrad Meyer if (dictSize > 0) {
52137f1f268SConrad Meyer if (dictContentType == ZSTD_dct_rawContent) {
52237f1f268SConrad Meyer BYTE const* const dictEnd = (const BYTE*)dict + dictSize;
523*5ff13fbcSAllan Jude ZSTD_window_update(&serialState->ldmState.window, dict, dictSize, /* forceNonContiguous */ 0);
52437f1f268SConrad Meyer ZSTD_ldm_fillHashTable(&serialState->ldmState, (const BYTE*)dict, dictEnd, ¶ms.ldmParams);
52537f1f268SConrad Meyer serialState->ldmState.loadedDictEnd = params.forceWindow ? 0 : (U32)(dictEnd - serialState->ldmState.window.base);
52637f1f268SConrad Meyer } else {
52737f1f268SConrad Meyer /* don't even load anything */
52819fcbaf1SConrad Meyer }
52937f1f268SConrad Meyer }
53037f1f268SConrad Meyer
53137f1f268SConrad Meyer /* Initialize serialState's copy of ldmWindow. */
53237f1f268SConrad Meyer serialState->ldmWindow = serialState->ldmState.window;
53337f1f268SConrad Meyer }
53437f1f268SConrad Meyer
53519fcbaf1SConrad Meyer serialState->params = params;
5360f743729SConrad Meyer serialState->params.jobSize = (U32)jobSize;
53719fcbaf1SConrad Meyer return 0;
53819fcbaf1SConrad Meyer }
53919fcbaf1SConrad Meyer
ZSTDMT_serialState_init(serialState_t * serialState)54019fcbaf1SConrad Meyer static int ZSTDMT_serialState_init(serialState_t* serialState)
54119fcbaf1SConrad Meyer {
54219fcbaf1SConrad Meyer int initError = 0;
543f7cd7fe5SConrad Meyer ZSTD_memset(serialState, 0, sizeof(*serialState));
54419fcbaf1SConrad Meyer initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);
54519fcbaf1SConrad Meyer initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);
54619fcbaf1SConrad Meyer initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);
54719fcbaf1SConrad Meyer initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);
54819fcbaf1SConrad Meyer return initError;
54919fcbaf1SConrad Meyer }
55019fcbaf1SConrad Meyer
ZSTDMT_serialState_free(serialState_t * serialState)55119fcbaf1SConrad Meyer static void ZSTDMT_serialState_free(serialState_t* serialState)
55219fcbaf1SConrad Meyer {
55319fcbaf1SConrad Meyer ZSTD_customMem cMem = serialState->params.customMem;
55419fcbaf1SConrad Meyer ZSTD_pthread_mutex_destroy(&serialState->mutex);
55519fcbaf1SConrad Meyer ZSTD_pthread_cond_destroy(&serialState->cond);
55619fcbaf1SConrad Meyer ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);
55719fcbaf1SConrad Meyer ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);
558f7cd7fe5SConrad Meyer ZSTD_customFree(serialState->ldmState.hashTable, cMem);
559f7cd7fe5SConrad Meyer ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);
56019fcbaf1SConrad Meyer }
56119fcbaf1SConrad Meyer
ZSTDMT_serialState_update(serialState_t * serialState,ZSTD_CCtx * jobCCtx,rawSeqStore_t seqStore,range_t src,unsigned jobID)56219fcbaf1SConrad Meyer static void ZSTDMT_serialState_update(serialState_t* serialState,
56319fcbaf1SConrad Meyer ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore,
56419fcbaf1SConrad Meyer range_t src, unsigned jobID)
56519fcbaf1SConrad Meyer {
56619fcbaf1SConrad Meyer /* Wait for our turn */
56719fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
56819fcbaf1SConrad Meyer while (serialState->nextJobID < jobID) {
5690f743729SConrad Meyer DEBUGLOG(5, "wait for serialState->cond");
57019fcbaf1SConrad Meyer ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);
57119fcbaf1SConrad Meyer }
57219fcbaf1SConrad Meyer /* A future job may error and skip our job */
57319fcbaf1SConrad Meyer if (serialState->nextJobID == jobID) {
57419fcbaf1SConrad Meyer /* It is now our turn, do any processing necessary */
575*5ff13fbcSAllan Jude if (serialState->params.ldmParams.enableLdm == ZSTD_ps_enable) {
57619fcbaf1SConrad Meyer size_t error;
57719fcbaf1SConrad Meyer assert(seqStore.seq != NULL && seqStore.pos == 0 &&
57819fcbaf1SConrad Meyer seqStore.size == 0 && seqStore.capacity > 0);
5790f743729SConrad Meyer assert(src.size <= serialState->params.jobSize);
580*5ff13fbcSAllan Jude ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0);
58119fcbaf1SConrad Meyer error = ZSTD_ldm_generateSequences(
58219fcbaf1SConrad Meyer &serialState->ldmState, &seqStore,
58319fcbaf1SConrad Meyer &serialState->params.ldmParams, src.start, src.size);
58419fcbaf1SConrad Meyer /* We provide a large enough buffer to never fail. */
58519fcbaf1SConrad Meyer assert(!ZSTD_isError(error)); (void)error;
58619fcbaf1SConrad Meyer /* Update ldmWindow to match the ldmState.window and signal the main
58719fcbaf1SConrad Meyer * thread if it is waiting for a buffer.
58819fcbaf1SConrad Meyer */
58919fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
59019fcbaf1SConrad Meyer serialState->ldmWindow = serialState->ldmState.window;
59119fcbaf1SConrad Meyer ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
59219fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
59319fcbaf1SConrad Meyer }
59419fcbaf1SConrad Meyer if (serialState->params.fParams.checksumFlag && src.size > 0)
59519fcbaf1SConrad Meyer XXH64_update(&serialState->xxhState, src.start, src.size);
59619fcbaf1SConrad Meyer }
59719fcbaf1SConrad Meyer /* Now it is the next jobs turn */
59819fcbaf1SConrad Meyer serialState->nextJobID++;
59919fcbaf1SConrad Meyer ZSTD_pthread_cond_broadcast(&serialState->cond);
60019fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&serialState->mutex);
60119fcbaf1SConrad Meyer
60219fcbaf1SConrad Meyer if (seqStore.size > 0) {
60319fcbaf1SConrad Meyer size_t const err = ZSTD_referenceExternalSequences(
60419fcbaf1SConrad Meyer jobCCtx, seqStore.seq, seqStore.size);
605*5ff13fbcSAllan Jude assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable);
60619fcbaf1SConrad Meyer assert(!ZSTD_isError(err));
60719fcbaf1SConrad Meyer (void)err;
60819fcbaf1SConrad Meyer }
60919fcbaf1SConrad Meyer }
61019fcbaf1SConrad Meyer
ZSTDMT_serialState_ensureFinished(serialState_t * serialState,unsigned jobID,size_t cSize)61119fcbaf1SConrad Meyer static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,
61219fcbaf1SConrad Meyer unsigned jobID, size_t cSize)
61319fcbaf1SConrad Meyer {
61419fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
61519fcbaf1SConrad Meyer if (serialState->nextJobID <= jobID) {
61619fcbaf1SConrad Meyer assert(ZSTD_isError(cSize)); (void)cSize;
61719fcbaf1SConrad Meyer DEBUGLOG(5, "Skipping past job %u because of error", jobID);
61819fcbaf1SConrad Meyer serialState->nextJobID = jobID + 1;
61919fcbaf1SConrad Meyer ZSTD_pthread_cond_broadcast(&serialState->cond);
62019fcbaf1SConrad Meyer
62119fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
62219fcbaf1SConrad Meyer ZSTD_window_clear(&serialState->ldmWindow);
62319fcbaf1SConrad Meyer ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
62419fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
62519fcbaf1SConrad Meyer }
62619fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&serialState->mutex);
62719fcbaf1SConrad Meyer
62819fcbaf1SConrad Meyer }
62919fcbaf1SConrad Meyer
63019fcbaf1SConrad Meyer
63119fcbaf1SConrad Meyer /* ------------------------------------------ */
63219fcbaf1SConrad Meyer /* ===== Worker thread ===== */
63319fcbaf1SConrad Meyer /* ------------------------------------------ */
63419fcbaf1SConrad Meyer
63519fcbaf1SConrad Meyer static const range_t kNullRange = { NULL, 0 };
63619fcbaf1SConrad Meyer
63719fcbaf1SConrad Meyer typedef struct {
63819fcbaf1SConrad Meyer size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */
63919fcbaf1SConrad Meyer size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */
64019fcbaf1SConrad Meyer ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */
64119fcbaf1SConrad Meyer ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */
64219fcbaf1SConrad Meyer ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */
64319fcbaf1SConrad Meyer ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */
64419fcbaf1SConrad Meyer ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */
64519fcbaf1SConrad Meyer serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */
64619fcbaf1SConrad Meyer buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */
64719fcbaf1SConrad Meyer range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */
64819fcbaf1SConrad Meyer range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */
64919fcbaf1SConrad Meyer unsigned jobID; /* set by mtctx, then read by worker => no barrier */
65019fcbaf1SConrad Meyer unsigned firstJob; /* set by mtctx, then read by worker => no barrier */
65119fcbaf1SConrad Meyer unsigned lastJob; /* set by mtctx, then read by worker => no barrier */
65219fcbaf1SConrad Meyer ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */
65319fcbaf1SConrad Meyer const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */
65419fcbaf1SConrad Meyer unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */
65519fcbaf1SConrad Meyer size_t dstFlushed; /* used only by mtctx */
65619fcbaf1SConrad Meyer unsigned frameChecksumNeeded; /* used only by mtctx */
6570c16b537SWarner Losh } ZSTDMT_jobDescription;
6580c16b537SWarner Losh
6590f743729SConrad Meyer #define JOB_ERROR(e) { \
6600f743729SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \
6610f743729SConrad Meyer job->cSize = e; \
6620f743729SConrad Meyer ZSTD_pthread_mutex_unlock(&job->job_mutex); \
6630f743729SConrad Meyer goto _endJob; \
6640f743729SConrad Meyer }
6650f743729SConrad Meyer
66619fcbaf1SConrad Meyer /* ZSTDMT_compressionJob() is a POOL_function type */
ZSTDMT_compressionJob(void * jobDescription)6670f743729SConrad Meyer static void ZSTDMT_compressionJob(void* jobDescription)
6680c16b537SWarner Losh {
6690c16b537SWarner Losh ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
67019fcbaf1SConrad Meyer ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */
671052d3c12SConrad Meyer ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);
67219fcbaf1SConrad Meyer rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);
6730c16b537SWarner Losh buffer_t dstBuff = job->dstBuff;
6740f743729SConrad Meyer size_t lastCBlockSize = 0;
6750f743729SConrad Meyer
6762b9c00cbSConrad Meyer /* resources */
6770f743729SConrad Meyer if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));
6780f743729SConrad Meyer if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */
6790f743729SConrad Meyer dstBuff = ZSTDMT_getBuffer(job->bufPool);
6800f743729SConrad Meyer if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));
6810f743729SConrad Meyer job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */
6820f743729SConrad Meyer }
683*5ff13fbcSAllan Jude if (jobParams.ldmParams.enableLdm == ZSTD_ps_enable && rawSeqStore.seq == NULL)
6840f743729SConrad Meyer JOB_ERROR(ERROR(memory_allocation));
6850c16b537SWarner Losh
68619fcbaf1SConrad Meyer /* Don't compute the checksum for chunks, since we compute it externally,
68719fcbaf1SConrad Meyer * but write it in the header.
68819fcbaf1SConrad Meyer */
68919fcbaf1SConrad Meyer if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;
69019fcbaf1SConrad Meyer /* Don't run LDM for the chunks, since we handle it externally */
691*5ff13fbcSAllan Jude jobParams.ldmParams.enableLdm = ZSTD_ps_disable;
692*5ff13fbcSAllan Jude /* Correct nbWorkers to 0. */
693*5ff13fbcSAllan Jude jobParams.nbWorkers = 0;
69419fcbaf1SConrad Meyer
6950c16b537SWarner Losh
69619fcbaf1SConrad Meyer /* init */
697052d3c12SConrad Meyer if (job->cdict) {
6989cbefe25SConrad Meyer size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize);
69919fcbaf1SConrad Meyer assert(job->firstJob); /* only allowed for first job */
7000f743729SConrad Meyer if (ZSTD_isError(initError)) JOB_ERROR(initError);
7010c16b537SWarner Losh } else { /* srcStart points at reloaded section */
70219fcbaf1SConrad Meyer U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;
7032b9c00cbSConrad Meyer { size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);
7040f743729SConrad Meyer if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);
7050f743729SConrad Meyer }
706*5ff13fbcSAllan Jude if (!job->firstJob) {
707*5ff13fbcSAllan Jude size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0);
708*5ff13fbcSAllan Jude if (ZSTD_isError(err)) JOB_ERROR(err);
709*5ff13fbcSAllan Jude }
710052d3c12SConrad Meyer { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,
71119fcbaf1SConrad Meyer job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */
7120f743729SConrad Meyer ZSTD_dtlm_fast,
71319fcbaf1SConrad Meyer NULL, /*cdict*/
7149cbefe25SConrad Meyer &jobParams, pledgedSrcSize);
7150f743729SConrad Meyer if (ZSTD_isError(initError)) JOB_ERROR(initError);
7160f743729SConrad Meyer } }
71719fcbaf1SConrad Meyer
71819fcbaf1SConrad Meyer /* Perform serial step as early as possible, but after CCtx initialization */
71919fcbaf1SConrad Meyer ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);
72019fcbaf1SConrad Meyer
72119fcbaf1SConrad Meyer if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */
72219fcbaf1SConrad Meyer size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);
7230f743729SConrad Meyer if (ZSTD_isError(hSize)) JOB_ERROR(hSize);
72419fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);
7250c16b537SWarner Losh ZSTD_invalidateRepCodes(cctx);
7260c16b537SWarner Losh }
7270c16b537SWarner Losh
72819fcbaf1SConrad Meyer /* compress */
72919fcbaf1SConrad Meyer { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;
73019fcbaf1SConrad Meyer int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);
73119fcbaf1SConrad Meyer const BYTE* ip = (const BYTE*) job->src.start;
73219fcbaf1SConrad Meyer BYTE* const ostart = (BYTE*)dstBuff.start;
73319fcbaf1SConrad Meyer BYTE* op = ostart;
73419fcbaf1SConrad Meyer BYTE* oend = op + dstBuff.capacity;
73519fcbaf1SConrad Meyer int chunkNb;
73619fcbaf1SConrad Meyer if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */
73719fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);
73819fcbaf1SConrad Meyer assert(job->cSize == 0);
73919fcbaf1SConrad Meyer for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {
74019fcbaf1SConrad Meyer size_t const cSize = ZSTD_compressContinue(cctx, op, oend-op, ip, chunkSize);
7410f743729SConrad Meyer if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
74219fcbaf1SConrad Meyer ip += chunkSize;
74319fcbaf1SConrad Meyer op += cSize; assert(op < oend);
74419fcbaf1SConrad Meyer /* stats */
74519fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
74619fcbaf1SConrad Meyer job->cSize += cSize;
74719fcbaf1SConrad Meyer job->consumed = chunkSize * chunkNb;
74819fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",
74919fcbaf1SConrad Meyer (U32)cSize, (U32)job->cSize);
75019fcbaf1SConrad Meyer ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */
75119fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&job->job_mutex);
75219fcbaf1SConrad Meyer }
75319fcbaf1SConrad Meyer /* last block */
7540f743729SConrad Meyer assert(chunkSize > 0);
7550f743729SConrad Meyer assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */
75619fcbaf1SConrad Meyer if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {
75719fcbaf1SConrad Meyer size_t const lastBlockSize1 = job->src.size & (chunkSize-1);
75819fcbaf1SConrad Meyer size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;
75919fcbaf1SConrad Meyer size_t const cSize = (job->lastJob) ?
76019fcbaf1SConrad Meyer ZSTD_compressEnd (cctx, op, oend-op, ip, lastBlockSize) :
76119fcbaf1SConrad Meyer ZSTD_compressContinue(cctx, op, oend-op, ip, lastBlockSize);
7620f743729SConrad Meyer if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
7630f743729SConrad Meyer lastCBlockSize = cSize;
76419fcbaf1SConrad Meyer } }
765*5ff13fbcSAllan Jude if (!job->firstJob) {
766*5ff13fbcSAllan Jude /* Double check that we don't have an ext-dict, because then our
767*5ff13fbcSAllan Jude * repcode invalidation doesn't work.
768*5ff13fbcSAllan Jude */
769*5ff13fbcSAllan Jude assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
770*5ff13fbcSAllan Jude }
771*5ff13fbcSAllan Jude ZSTD_CCtx_trace(cctx, 0);
7720c16b537SWarner Losh
7730c16b537SWarner Losh _endJob:
77419fcbaf1SConrad Meyer ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);
77519fcbaf1SConrad Meyer if (job->prefix.size > 0)
77619fcbaf1SConrad Meyer DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);
77719fcbaf1SConrad Meyer DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);
77819fcbaf1SConrad Meyer /* release resources */
77919fcbaf1SConrad Meyer ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);
7800c16b537SWarner Losh ZSTDMT_releaseCCtx(job->cctxPool, cctx);
78119fcbaf1SConrad Meyer /* report */
78219fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
7830f743729SConrad Meyer if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);
7840f743729SConrad Meyer job->cSize += lastCBlockSize;
7850f743729SConrad Meyer job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */
78619fcbaf1SConrad Meyer ZSTD_pthread_cond_signal(&job->job_cond);
78719fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&job->job_mutex);
7880c16b537SWarner Losh }
7890c16b537SWarner Losh
7900c16b537SWarner Losh
7910c16b537SWarner Losh /* ------------------------------------------ */
7920c16b537SWarner Losh /* ===== Multi-threaded compression ===== */
7930c16b537SWarner Losh /* ------------------------------------------ */
7940c16b537SWarner Losh
7950c16b537SWarner Losh typedef struct {
79619fcbaf1SConrad Meyer range_t prefix; /* read-only non-owned prefix buffer */
7970c16b537SWarner Losh buffer_t buffer;
7980c16b537SWarner Losh size_t filled;
7990c16b537SWarner Losh } inBuff_t;
8000c16b537SWarner Losh
80119fcbaf1SConrad Meyer typedef struct {
80219fcbaf1SConrad Meyer BYTE* buffer; /* The round input buffer. All jobs get references
80319fcbaf1SConrad Meyer * to pieces of the buffer. ZSTDMT_tryGetInputRange()
80419fcbaf1SConrad Meyer * handles handing out job input buffers, and makes
80519fcbaf1SConrad Meyer * sure it doesn't overlap with any pieces still in use.
80619fcbaf1SConrad Meyer */
80719fcbaf1SConrad Meyer size_t capacity; /* The capacity of buffer. */
80819fcbaf1SConrad Meyer size_t pos; /* The position of the current inBuff in the round
80919fcbaf1SConrad Meyer * buffer. Updated past the end if the inBuff once
81019fcbaf1SConrad Meyer * the inBuff is sent to the worker thread.
81119fcbaf1SConrad Meyer * pos <= capacity.
81219fcbaf1SConrad Meyer */
81319fcbaf1SConrad Meyer } roundBuff_t;
81419fcbaf1SConrad Meyer
81519fcbaf1SConrad Meyer static const roundBuff_t kNullRoundBuff = {NULL, 0, 0};
81619fcbaf1SConrad Meyer
817a0483764SConrad Meyer #define RSYNC_LENGTH 32
818*5ff13fbcSAllan Jude /* Don't create chunks smaller than the zstd block size.
819*5ff13fbcSAllan Jude * This stops us from regressing compression ratio too much,
820*5ff13fbcSAllan Jude * and ensures our output fits in ZSTD_compressBound().
821*5ff13fbcSAllan Jude *
822*5ff13fbcSAllan Jude * If this is shrunk < ZSTD_BLOCKSIZELOG_MIN then
823*5ff13fbcSAllan Jude * ZSTD_COMPRESSBOUND() will need to be updated.
824*5ff13fbcSAllan Jude */
825*5ff13fbcSAllan Jude #define RSYNC_MIN_BLOCK_LOG ZSTD_BLOCKSIZELOG_MAX
826*5ff13fbcSAllan Jude #define RSYNC_MIN_BLOCK_SIZE (1<<RSYNC_MIN_BLOCK_LOG)
827a0483764SConrad Meyer
828a0483764SConrad Meyer typedef struct {
829a0483764SConrad Meyer U64 hash;
830a0483764SConrad Meyer U64 hitMask;
831a0483764SConrad Meyer U64 primePower;
832a0483764SConrad Meyer } rsyncState_t;
833a0483764SConrad Meyer
8340c16b537SWarner Losh struct ZSTDMT_CCtx_s {
8350c16b537SWarner Losh POOL_ctx* factory;
8360c16b537SWarner Losh ZSTDMT_jobDescription* jobs;
8370c16b537SWarner Losh ZSTDMT_bufferPool* bufPool;
8380c16b537SWarner Losh ZSTDMT_CCtxPool* cctxPool;
83919fcbaf1SConrad Meyer ZSTDMT_seqPool* seqPool;
840052d3c12SConrad Meyer ZSTD_CCtx_params params;
8410c16b537SWarner Losh size_t targetSectionSize;
84219fcbaf1SConrad Meyer size_t targetPrefixSize;
8430f743729SConrad Meyer int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */
8440c16b537SWarner Losh inBuff_t inBuff;
8450f743729SConrad Meyer roundBuff_t roundBuff;
84619fcbaf1SConrad Meyer serialState_t serial;
847a0483764SConrad Meyer rsyncState_t rsync;
8480c16b537SWarner Losh unsigned jobIDMask;
8490c16b537SWarner Losh unsigned doneJobID;
8500c16b537SWarner Losh unsigned nextJobID;
8510c16b537SWarner Losh unsigned frameEnded;
8520c16b537SWarner Losh unsigned allJobsCompleted;
8530c16b537SWarner Losh unsigned long long frameContentSize;
85419fcbaf1SConrad Meyer unsigned long long consumed;
85519fcbaf1SConrad Meyer unsigned long long produced;
8560c16b537SWarner Losh ZSTD_customMem cMem;
8570c16b537SWarner Losh ZSTD_CDict* cdictLocal;
8580c16b537SWarner Losh const ZSTD_CDict* cdict;
859f7cd7fe5SConrad Meyer unsigned providedFactory: 1;
8600c16b537SWarner Losh };
8610c16b537SWarner Losh
ZSTDMT_freeJobsTable(ZSTDMT_jobDescription * jobTable,U32 nbJobs,ZSTD_customMem cMem)86219fcbaf1SConrad Meyer static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
86319fcbaf1SConrad Meyer {
86419fcbaf1SConrad Meyer U32 jobNb;
86519fcbaf1SConrad Meyer if (jobTable == NULL) return;
86619fcbaf1SConrad Meyer for (jobNb=0; jobNb<nbJobs; jobNb++) {
86719fcbaf1SConrad Meyer ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);
86819fcbaf1SConrad Meyer ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);
86919fcbaf1SConrad Meyer }
870f7cd7fe5SConrad Meyer ZSTD_customFree(jobTable, cMem);
87119fcbaf1SConrad Meyer }
87219fcbaf1SConrad Meyer
87319fcbaf1SConrad Meyer /* ZSTDMT_allocJobsTable()
87419fcbaf1SConrad Meyer * allocate and init a job table.
87519fcbaf1SConrad Meyer * update *nbJobsPtr to next power of 2 value, as size of table */
ZSTDMT_createJobsTable(U32 * nbJobsPtr,ZSTD_customMem cMem)87619fcbaf1SConrad Meyer static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
8770c16b537SWarner Losh {
8780c16b537SWarner Losh U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
8790c16b537SWarner Losh U32 const nbJobs = 1 << nbJobsLog2;
88019fcbaf1SConrad Meyer U32 jobNb;
88119fcbaf1SConrad Meyer ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
882f7cd7fe5SConrad Meyer ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
88319fcbaf1SConrad Meyer int initError = 0;
88419fcbaf1SConrad Meyer if (jobTable==NULL) return NULL;
8850c16b537SWarner Losh *nbJobsPtr = nbJobs;
88619fcbaf1SConrad Meyer for (jobNb=0; jobNb<nbJobs; jobNb++) {
88719fcbaf1SConrad Meyer initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
88819fcbaf1SConrad Meyer initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);
88919fcbaf1SConrad Meyer }
89019fcbaf1SConrad Meyer if (initError != 0) {
89119fcbaf1SConrad Meyer ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
89219fcbaf1SConrad Meyer return NULL;
89319fcbaf1SConrad Meyer }
89419fcbaf1SConrad Meyer return jobTable;
8950c16b537SWarner Losh }
8960c16b537SWarner Losh
ZSTDMT_expandJobsTable(ZSTDMT_CCtx * mtctx,U32 nbWorkers)8970f743729SConrad Meyer static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
8980f743729SConrad Meyer U32 nbJobs = nbWorkers + 2;
8990f743729SConrad Meyer if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */
9000f743729SConrad Meyer ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
9010f743729SConrad Meyer mtctx->jobIDMask = 0;
9020f743729SConrad Meyer mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);
9030f743729SConrad Meyer if (mtctx->jobs==NULL) return ERROR(memory_allocation);
9040f743729SConrad Meyer assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */
9050f743729SConrad Meyer mtctx->jobIDMask = nbJobs - 1;
9060f743729SConrad Meyer }
9070f743729SConrad Meyer return 0;
9080f743729SConrad Meyer }
9090f743729SConrad Meyer
9100f743729SConrad Meyer
91119fcbaf1SConrad Meyer /* ZSTDMT_CCtxParam_setNbWorkers():
912052d3c12SConrad Meyer * Internal use only */
ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params * params,unsigned nbWorkers)913f7cd7fe5SConrad Meyer static size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)
9140c16b537SWarner Losh {
9152b9c00cbSConrad Meyer return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);
916052d3c12SConrad Meyer }
917052d3c12SConrad Meyer
ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers,ZSTD_customMem cMem,ZSTD_threadPool * pool)918f7cd7fe5SConrad Meyer MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
9190c16b537SWarner Losh {
9200c16b537SWarner Losh ZSTDMT_CCtx* mtctx;
92119fcbaf1SConrad Meyer U32 nbJobs = nbWorkers + 2;
92219fcbaf1SConrad Meyer int initError;
92319fcbaf1SConrad Meyer DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
9240c16b537SWarner Losh
92519fcbaf1SConrad Meyer if (nbWorkers < 1) return NULL;
92619fcbaf1SConrad Meyer nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
9270c16b537SWarner Losh if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
9280c16b537SWarner Losh /* invalid custom allocator */
9290c16b537SWarner Losh return NULL;
9300c16b537SWarner Losh
931f7cd7fe5SConrad Meyer mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);
9320c16b537SWarner Losh if (!mtctx) return NULL;
93319fcbaf1SConrad Meyer ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
9340c16b537SWarner Losh mtctx->cMem = cMem;
9350c16b537SWarner Losh mtctx->allJobsCompleted = 1;
936f7cd7fe5SConrad Meyer if (pool != NULL) {
937f7cd7fe5SConrad Meyer mtctx->factory = pool;
938f7cd7fe5SConrad Meyer mtctx->providedFactory = 1;
939f7cd7fe5SConrad Meyer }
940f7cd7fe5SConrad Meyer else {
94119fcbaf1SConrad Meyer mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
942f7cd7fe5SConrad Meyer mtctx->providedFactory = 0;
943f7cd7fe5SConrad Meyer }
94419fcbaf1SConrad Meyer mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
94519fcbaf1SConrad Meyer assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */
9460c16b537SWarner Losh mtctx->jobIDMask = nbJobs - 1;
947*5ff13fbcSAllan Jude mtctx->bufPool = ZSTDMT_createBufferPool(BUF_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);
94819fcbaf1SConrad Meyer mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
94919fcbaf1SConrad Meyer mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
95019fcbaf1SConrad Meyer initError = ZSTDMT_serialState_init(&mtctx->serial);
95119fcbaf1SConrad Meyer mtctx->roundBuff = kNullRoundBuff;
95219fcbaf1SConrad Meyer if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {
9530c16b537SWarner Losh ZSTDMT_freeCCtx(mtctx);
9540c16b537SWarner Losh return NULL;
9550c16b537SWarner Losh }
95619fcbaf1SConrad Meyer DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);
9570c16b537SWarner Losh return mtctx;
9580c16b537SWarner Losh }
9590c16b537SWarner Losh
ZSTDMT_createCCtx_advanced(unsigned nbWorkers,ZSTD_customMem cMem,ZSTD_threadPool * pool)960f7cd7fe5SConrad Meyer ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)
9612b9c00cbSConrad Meyer {
9622b9c00cbSConrad Meyer #ifdef ZSTD_MULTITHREAD
963f7cd7fe5SConrad Meyer return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);
9642b9c00cbSConrad Meyer #else
9652b9c00cbSConrad Meyer (void)nbWorkers;
9662b9c00cbSConrad Meyer (void)cMem;
967f7cd7fe5SConrad Meyer (void)pool;
9682b9c00cbSConrad Meyer return NULL;
9692b9c00cbSConrad Meyer #endif
9702b9c00cbSConrad Meyer }
9712b9c00cbSConrad Meyer
97219fcbaf1SConrad Meyer
9730c16b537SWarner Losh /* ZSTDMT_releaseAllJobResources() :
9740c16b537SWarner Losh * note : ensure all workers are killed first ! */
ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx * mtctx)9750c16b537SWarner Losh static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
9760c16b537SWarner Losh {
9770c16b537SWarner Losh unsigned jobID;
9780c16b537SWarner Losh DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
9790c16b537SWarner Losh for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
9809cbefe25SConrad Meyer /* Copy the mutex/cond out */
9819cbefe25SConrad Meyer ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;
9829cbefe25SConrad Meyer ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;
9839cbefe25SConrad Meyer
9840c16b537SWarner Losh DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
9850c16b537SWarner Losh ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
9869cbefe25SConrad Meyer
9879cbefe25SConrad Meyer /* Clear the job description, but keep the mutex/cond */
988f7cd7fe5SConrad Meyer ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));
9899cbefe25SConrad Meyer mtctx->jobs[jobID].job_mutex = mutex;
9909cbefe25SConrad Meyer mtctx->jobs[jobID].job_cond = cond;
9910c16b537SWarner Losh }
9920c16b537SWarner Losh mtctx->inBuff.buffer = g_nullBuffer;
99319fcbaf1SConrad Meyer mtctx->inBuff.filled = 0;
9940c16b537SWarner Losh mtctx->allJobsCompleted = 1;
9950c16b537SWarner Losh }
9960c16b537SWarner Losh
ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx * mtctx)99719fcbaf1SConrad Meyer static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)
9980c16b537SWarner Losh {
9990c16b537SWarner Losh DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
100019fcbaf1SConrad Meyer while (mtctx->doneJobID < mtctx->nextJobID) {
100119fcbaf1SConrad Meyer unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
100219fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
100319fcbaf1SConrad Meyer while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
10040f743729SConrad Meyer DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */
100519fcbaf1SConrad Meyer ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
10060c16b537SWarner Losh }
100719fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
100819fcbaf1SConrad Meyer mtctx->doneJobID++;
10090c16b537SWarner Losh }
10100c16b537SWarner Losh }
10110c16b537SWarner Losh
ZSTDMT_freeCCtx(ZSTDMT_CCtx * mtctx)10120c16b537SWarner Losh size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
10130c16b537SWarner Losh {
10140c16b537SWarner Losh if (mtctx==NULL) return 0; /* compatible with free on NULL */
1015f7cd7fe5SConrad Meyer if (!mtctx->providedFactory)
10160c16b537SWarner Losh POOL_free(mtctx->factory); /* stop and free worker threads */
10170c16b537SWarner Losh ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
101819fcbaf1SConrad Meyer ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
10190c16b537SWarner Losh ZSTDMT_freeBufferPool(mtctx->bufPool);
10200c16b537SWarner Losh ZSTDMT_freeCCtxPool(mtctx->cctxPool);
102119fcbaf1SConrad Meyer ZSTDMT_freeSeqPool(mtctx->seqPool);
102219fcbaf1SConrad Meyer ZSTDMT_serialState_free(&mtctx->serial);
10230c16b537SWarner Losh ZSTD_freeCDict(mtctx->cdictLocal);
102419fcbaf1SConrad Meyer if (mtctx->roundBuff.buffer)
1025f7cd7fe5SConrad Meyer ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
1026f7cd7fe5SConrad Meyer ZSTD_customFree(mtctx, mtctx->cMem);
10270c16b537SWarner Losh return 0;
10280c16b537SWarner Losh }
10290c16b537SWarner Losh
ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx * mtctx)10300c16b537SWarner Losh size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
10310c16b537SWarner Losh {
10320c16b537SWarner Losh if (mtctx == NULL) return 0; /* supports sizeof NULL */
10330c16b537SWarner Losh return sizeof(*mtctx)
10340c16b537SWarner Losh + POOL_sizeof(mtctx->factory)
10350c16b537SWarner Losh + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
10360c16b537SWarner Losh + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
10370c16b537SWarner Losh + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
103819fcbaf1SConrad Meyer + ZSTDMT_sizeof_seqPool(mtctx->seqPool)
103919fcbaf1SConrad Meyer + ZSTD_sizeof_CDict(mtctx->cdictLocal)
104019fcbaf1SConrad Meyer + mtctx->roundBuff.capacity;
10410c16b537SWarner Losh }
10420c16b537SWarner Losh
10430f743729SConrad Meyer
10440f743729SConrad Meyer /* ZSTDMT_resize() :
10450f743729SConrad Meyer * @return : error code if fails, 0 on success */
ZSTDMT_resize(ZSTDMT_CCtx * mtctx,unsigned nbWorkers)10460f743729SConrad Meyer static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)
10470f743729SConrad Meyer {
10480f743729SConrad Meyer if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
104937f1f268SConrad Meyer FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");
1050*5ff13fbcSAllan Jude mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, BUF_POOL_MAX_NB_BUFFERS(nbWorkers));
10510f743729SConrad Meyer if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
10520f743729SConrad Meyer mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);
10530f743729SConrad Meyer if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);
10540f743729SConrad Meyer mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);
10550f743729SConrad Meyer if (mtctx->seqPool == NULL) return ERROR(memory_allocation);
10560f743729SConrad Meyer ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
10570f743729SConrad Meyer return 0;
10580f743729SConrad Meyer }
10590f743729SConrad Meyer
10600f743729SConrad Meyer
106119fcbaf1SConrad Meyer /*! ZSTDMT_updateCParams_whileCompressing() :
10620f743729SConrad Meyer * Updates a selected set of compression parameters, remaining compatible with currently active frame.
106319fcbaf1SConrad Meyer * New parameters will be applied to next compression job. */
ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx * mtctx,const ZSTD_CCtx_params * cctxParams)106419fcbaf1SConrad Meyer void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)
106519fcbaf1SConrad Meyer {
106619fcbaf1SConrad Meyer U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */
106719fcbaf1SConrad Meyer int const compressionLevel = cctxParams->compressionLevel;
106819fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",
106919fcbaf1SConrad Meyer compressionLevel);
107019fcbaf1SConrad Meyer mtctx->params.compressionLevel = compressionLevel;
1071f7cd7fe5SConrad Meyer { ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);
107219fcbaf1SConrad Meyer cParams.windowLog = saved_wlog;
107319fcbaf1SConrad Meyer mtctx->params.cParams = cParams;
107419fcbaf1SConrad Meyer }
107519fcbaf1SConrad Meyer }
107619fcbaf1SConrad Meyer
107719fcbaf1SConrad Meyer /* ZSTDMT_getFrameProgression():
107819fcbaf1SConrad Meyer * tells how much data has been consumed (input) and produced (output) for current frame.
107919fcbaf1SConrad Meyer * able to count progression inside worker threads.
10800f743729SConrad Meyer * Note : mutex will be acquired during statistics collection inside workers. */
ZSTDMT_getFrameProgression(ZSTDMT_CCtx * mtctx)108119fcbaf1SConrad Meyer ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
108219fcbaf1SConrad Meyer {
108319fcbaf1SConrad Meyer ZSTD_frameProgression fps;
10840f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_getFrameProgression");
108519fcbaf1SConrad Meyer fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
10860f743729SConrad Meyer fps.consumed = mtctx->consumed;
10870f743729SConrad Meyer fps.produced = fps.flushed = mtctx->produced;
10880f743729SConrad Meyer fps.currentJobID = mtctx->nextJobID;
10890f743729SConrad Meyer fps.nbActiveWorkers = 0;
109019fcbaf1SConrad Meyer { unsigned jobNb;
109119fcbaf1SConrad Meyer unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
109219fcbaf1SConrad Meyer DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
109319fcbaf1SConrad Meyer mtctx->doneJobID, lastJobNb, mtctx->jobReady)
109419fcbaf1SConrad Meyer for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
109519fcbaf1SConrad Meyer unsigned const wJobID = jobNb & mtctx->jobIDMask;
10960f743729SConrad Meyer ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
10970f743729SConrad Meyer ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
10980f743729SConrad Meyer { size_t const cResult = jobPtr->cSize;
109919fcbaf1SConrad Meyer size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
11000f743729SConrad Meyer size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
11010f743729SConrad Meyer assert(flushed <= produced);
11020f743729SConrad Meyer fps.ingested += jobPtr->src.size;
11030f743729SConrad Meyer fps.consumed += jobPtr->consumed;
110419fcbaf1SConrad Meyer fps.produced += produced;
11050f743729SConrad Meyer fps.flushed += flushed;
11060f743729SConrad Meyer fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);
110719fcbaf1SConrad Meyer }
110819fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
110919fcbaf1SConrad Meyer }
111019fcbaf1SConrad Meyer }
111119fcbaf1SConrad Meyer return fps;
111219fcbaf1SConrad Meyer }
111319fcbaf1SConrad Meyer
111419fcbaf1SConrad Meyer
ZSTDMT_toFlushNow(ZSTDMT_CCtx * mtctx)11150f743729SConrad Meyer size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)
11160f743729SConrad Meyer {
11170f743729SConrad Meyer size_t toFlush;
11180f743729SConrad Meyer unsigned const jobID = mtctx->doneJobID;
11190f743729SConrad Meyer assert(jobID <= mtctx->nextJobID);
11200f743729SConrad Meyer if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */
11210f743729SConrad Meyer
11220f743729SConrad Meyer /* look into oldest non-fully-flushed job */
11230f743729SConrad Meyer { unsigned const wJobID = jobID & mtctx->jobIDMask;
11240f743729SConrad Meyer ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
11250f743729SConrad Meyer ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
11260f743729SConrad Meyer { size_t const cResult = jobPtr->cSize;
11270f743729SConrad Meyer size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
11280f743729SConrad Meyer size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
11290f743729SConrad Meyer assert(flushed <= produced);
11304d3f1eafSConrad Meyer assert(jobPtr->consumed <= jobPtr->src.size);
11310f743729SConrad Meyer toFlush = produced - flushed;
11324d3f1eafSConrad Meyer /* if toFlush==0, nothing is available to flush.
11334d3f1eafSConrad Meyer * However, jobID is expected to still be active:
11344d3f1eafSConrad Meyer * if jobID was already completed and fully flushed,
11354d3f1eafSConrad Meyer * ZSTDMT_flushProduced() should have already moved onto next job.
11364d3f1eafSConrad Meyer * Therefore, some input has not yet been consumed. */
11374d3f1eafSConrad Meyer if (toFlush==0) {
11380f743729SConrad Meyer assert(jobPtr->consumed < jobPtr->src.size);
11390f743729SConrad Meyer }
11400f743729SConrad Meyer }
11410f743729SConrad Meyer ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
11420f743729SConrad Meyer }
11430f743729SConrad Meyer
11440f743729SConrad Meyer return toFlush;
11450f743729SConrad Meyer }
11460f743729SConrad Meyer
11470f743729SConrad Meyer
11480c16b537SWarner Losh /* ------------------------------------------ */
11490c16b537SWarner Losh /* ===== Multi-threaded compression ===== */
11500c16b537SWarner Losh /* ------------------------------------------ */
11510c16b537SWarner Losh
ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params * params)11529cbefe25SConrad Meyer static unsigned ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params* params)
115319fcbaf1SConrad Meyer {
11544d3f1eafSConrad Meyer unsigned jobLog;
1155*5ff13fbcSAllan Jude if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
1156a0483764SConrad Meyer /* In Long Range Mode, the windowLog is typically oversized.
1157a0483764SConrad Meyer * In which case, it's preferable to determine the jobSize
1158f7cd7fe5SConrad Meyer * based on cycleLog instead. */
1159f7cd7fe5SConrad Meyer jobLog = MAX(21, ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy) + 3);
11604d3f1eafSConrad Meyer } else {
11619cbefe25SConrad Meyer jobLog = MAX(20, params->cParams.windowLog + 2);
11624d3f1eafSConrad Meyer }
11634d3f1eafSConrad Meyer return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);
11640c16b537SWarner Losh }
11650c16b537SWarner Losh
ZSTDMT_overlapLog_default(ZSTD_strategy strat)1166a0483764SConrad Meyer static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
116719fcbaf1SConrad Meyer {
1168a0483764SConrad Meyer switch(strat)
1169a0483764SConrad Meyer {
1170a0483764SConrad Meyer case ZSTD_btultra2:
1171a0483764SConrad Meyer return 9;
1172a0483764SConrad Meyer case ZSTD_btultra:
1173a0483764SConrad Meyer case ZSTD_btopt:
1174a0483764SConrad Meyer return 8;
1175a0483764SConrad Meyer case ZSTD_btlazy2:
1176a0483764SConrad Meyer case ZSTD_lazy2:
1177a0483764SConrad Meyer return 7;
1178a0483764SConrad Meyer case ZSTD_lazy:
1179a0483764SConrad Meyer case ZSTD_greedy:
1180a0483764SConrad Meyer case ZSTD_dfast:
1181a0483764SConrad Meyer case ZSTD_fast:
1182a0483764SConrad Meyer default:;
1183a0483764SConrad Meyer }
1184a0483764SConrad Meyer return 6;
118519fcbaf1SConrad Meyer }
118619fcbaf1SConrad Meyer
ZSTDMT_overlapLog(int ovlog,ZSTD_strategy strat)1187a0483764SConrad Meyer static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)
1188a0483764SConrad Meyer {
1189a0483764SConrad Meyer assert(0 <= ovlog && ovlog <= 9);
1190a0483764SConrad Meyer if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
1191a0483764SConrad Meyer return ovlog;
1192a0483764SConrad Meyer }
1193a0483764SConrad Meyer
ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params * params)11949cbefe25SConrad Meyer static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)
1195a0483764SConrad Meyer {
11969cbefe25SConrad Meyer int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);
11979cbefe25SConrad Meyer int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);
1198a0483764SConrad Meyer assert(0 <= overlapRLog && overlapRLog <= 8);
1199*5ff13fbcSAllan Jude if (params->ldmParams.enableLdm == ZSTD_ps_enable) {
1200a0483764SConrad Meyer /* In Long Range Mode, the windowLog is typically oversized.
1201a0483764SConrad Meyer * In which case, it's preferable to determine the jobSize
1202a0483764SConrad Meyer * based on chainLog instead.
1203a0483764SConrad Meyer * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
12049cbefe25SConrad Meyer ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)
1205a0483764SConrad Meyer - overlapRLog;
1206a0483764SConrad Meyer }
12074d3f1eafSConrad Meyer assert(0 <= ovLog && ovLog <= ZSTD_WINDOWLOG_MAX);
12089cbefe25SConrad Meyer DEBUGLOG(4, "overlapLog : %i", params->overlapLog);
1209a0483764SConrad Meyer DEBUGLOG(4, "overlap size : %i", 1 << ovLog);
1210a0483764SConrad Meyer return (ovLog==0) ? 0 : (size_t)1 << ovLog;
1211a0483764SConrad Meyer }
1212a0483764SConrad Meyer
12130c16b537SWarner Losh /* ====================================== */
12140c16b537SWarner Losh /* ======= Streaming API ======= */
12150c16b537SWarner Losh /* ====================================== */
12160c16b537SWarner Losh
ZSTDMT_initCStream_internal(ZSTDMT_CCtx * mtctx,const void * dict,size_t dictSize,ZSTD_dictContentType_e dictContentType,const ZSTD_CDict * cdict,ZSTD_CCtx_params params,unsigned long long pledgedSrcSize)12170c16b537SWarner Losh size_t ZSTDMT_initCStream_internal(
121819fcbaf1SConrad Meyer ZSTDMT_CCtx* mtctx,
121919fcbaf1SConrad Meyer const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
12200c16b537SWarner Losh const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
12210c16b537SWarner Losh unsigned long long pledgedSrcSize)
12220c16b537SWarner Losh {
12230f743729SConrad Meyer DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
12240f743729SConrad Meyer (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
12250f743729SConrad Meyer
12260f743729SConrad Meyer /* params supposed partially fully validated at this point */
12270c16b537SWarner Losh assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
12280c16b537SWarner Losh assert(!((dict) && (cdict))); /* either dict or cdict, not both */
12290c16b537SWarner Losh
123019fcbaf1SConrad Meyer /* init */
12310f743729SConrad Meyer if (params.nbWorkers != mtctx->params.nbWorkers)
123237f1f268SConrad Meyer FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, params.nbWorkers) , "");
12330f743729SConrad Meyer
1234a0483764SConrad Meyer if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
12354d3f1eafSConrad Meyer if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;
123619fcbaf1SConrad Meyer
123719fcbaf1SConrad Meyer DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
123819fcbaf1SConrad Meyer
123919fcbaf1SConrad Meyer if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */
124019fcbaf1SConrad Meyer ZSTDMT_waitForAllJobsCompleted(mtctx);
124119fcbaf1SConrad Meyer ZSTDMT_releaseAllJobResources(mtctx);
124219fcbaf1SConrad Meyer mtctx->allJobsCompleted = 1;
12430c16b537SWarner Losh }
12440c16b537SWarner Losh
124519fcbaf1SConrad Meyer mtctx->params = params;
124619fcbaf1SConrad Meyer mtctx->frameContentSize = pledgedSrcSize;
12470c16b537SWarner Losh if (dict) {
124819fcbaf1SConrad Meyer ZSTD_freeCDict(mtctx->cdictLocal);
124919fcbaf1SConrad Meyer mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
125019fcbaf1SConrad Meyer ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
125119fcbaf1SConrad Meyer params.cParams, mtctx->cMem);
125219fcbaf1SConrad Meyer mtctx->cdict = mtctx->cdictLocal;
125319fcbaf1SConrad Meyer if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
12540c16b537SWarner Losh } else {
125519fcbaf1SConrad Meyer ZSTD_freeCDict(mtctx->cdictLocal);
125619fcbaf1SConrad Meyer mtctx->cdictLocal = NULL;
125719fcbaf1SConrad Meyer mtctx->cdict = cdict;
12580c16b537SWarner Losh }
12590c16b537SWarner Losh
12609cbefe25SConrad Meyer mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(¶ms);
1261a0483764SConrad Meyer DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
126219fcbaf1SConrad Meyer mtctx->targetSectionSize = params.jobSize;
12630f743729SConrad Meyer if (mtctx->targetSectionSize == 0) {
12649cbefe25SConrad Meyer mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(¶ms);
12650f743729SConrad Meyer }
12664d3f1eafSConrad Meyer assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);
12674d3f1eafSConrad Meyer
1268a0483764SConrad Meyer if (params.rsyncable) {
1269a0483764SConrad Meyer /* Aim for the targetsectionSize as the average job size. */
1270*5ff13fbcSAllan Jude U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);
1271*5ff13fbcSAllan Jude U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);
1272*5ff13fbcSAllan Jude /* We refuse to create jobs < RSYNC_MIN_BLOCK_SIZE bytes, so make sure our
1273*5ff13fbcSAllan Jude * expected job size is at least 4x larger. */
1274*5ff13fbcSAllan Jude assert(rsyncBits >= RSYNC_MIN_BLOCK_LOG + 2);
1275a0483764SConrad Meyer DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
1276a0483764SConrad Meyer mtctx->rsync.hash = 0;
1277a0483764SConrad Meyer mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
1278a0483764SConrad Meyer mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
1279a0483764SConrad Meyer }
128019fcbaf1SConrad Meyer if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */
1281a0483764SConrad Meyer DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
128219fcbaf1SConrad Meyer DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
128319fcbaf1SConrad Meyer ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
128419fcbaf1SConrad Meyer {
128519fcbaf1SConrad Meyer /* If ldm is enabled we need windowSize space. */
1286*5ff13fbcSAllan Jude size_t const windowSize = mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable ? (1U << mtctx->params.cParams.windowLog) : 0;
128719fcbaf1SConrad Meyer /* Two buffers of slack, plus extra space for the overlap
128819fcbaf1SConrad Meyer * This is the minimum slack that LDM works with. One extra because
128919fcbaf1SConrad Meyer * flush might waste up to targetSectionSize-1 bytes. Another extra
129019fcbaf1SConrad Meyer * for the overlap (if > 0), then one to fill which doesn't overlap
129119fcbaf1SConrad Meyer * with the LDM window.
129219fcbaf1SConrad Meyer */
129319fcbaf1SConrad Meyer size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
129419fcbaf1SConrad Meyer size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
129519fcbaf1SConrad Meyer /* Compute the total size, and always have enough slack */
129619fcbaf1SConrad Meyer size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
129719fcbaf1SConrad Meyer size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
129819fcbaf1SConrad Meyer size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
129919fcbaf1SConrad Meyer if (mtctx->roundBuff.capacity < capacity) {
130019fcbaf1SConrad Meyer if (mtctx->roundBuff.buffer)
1301f7cd7fe5SConrad Meyer ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);
1302f7cd7fe5SConrad Meyer mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);
130319fcbaf1SConrad Meyer if (mtctx->roundBuff.buffer == NULL) {
130419fcbaf1SConrad Meyer mtctx->roundBuff.capacity = 0;
130519fcbaf1SConrad Meyer return ERROR(memory_allocation);
130619fcbaf1SConrad Meyer }
130719fcbaf1SConrad Meyer mtctx->roundBuff.capacity = capacity;
130819fcbaf1SConrad Meyer }
130919fcbaf1SConrad Meyer }
131019fcbaf1SConrad Meyer DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
131119fcbaf1SConrad Meyer mtctx->roundBuff.pos = 0;
131219fcbaf1SConrad Meyer mtctx->inBuff.buffer = g_nullBuffer;
131319fcbaf1SConrad Meyer mtctx->inBuff.filled = 0;
131419fcbaf1SConrad Meyer mtctx->inBuff.prefix = kNullRange;
131519fcbaf1SConrad Meyer mtctx->doneJobID = 0;
131619fcbaf1SConrad Meyer mtctx->nextJobID = 0;
131719fcbaf1SConrad Meyer mtctx->frameEnded = 0;
131819fcbaf1SConrad Meyer mtctx->allJobsCompleted = 0;
131919fcbaf1SConrad Meyer mtctx->consumed = 0;
132019fcbaf1SConrad Meyer mtctx->produced = 0;
132137f1f268SConrad Meyer if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize,
132237f1f268SConrad Meyer dict, dictSize, dictContentType))
132319fcbaf1SConrad Meyer return ERROR(memory_allocation);
13240c16b537SWarner Losh return 0;
13250c16b537SWarner Losh }
13260c16b537SWarner Losh
13270c16b537SWarner Losh
132819fcbaf1SConrad Meyer /* ZSTDMT_writeLastEmptyBlock()
132919fcbaf1SConrad Meyer * Write a single empty block with an end-of-frame to finish a frame.
133019fcbaf1SConrad Meyer * Job must be created from streaming variant.
13312b9c00cbSConrad Meyer * This function is always successful if expected conditions are fulfilled.
133219fcbaf1SConrad Meyer */
ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription * job)133319fcbaf1SConrad Meyer static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)
13340c16b537SWarner Losh {
133519fcbaf1SConrad Meyer assert(job->lastJob == 1);
133619fcbaf1SConrad Meyer assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */
133719fcbaf1SConrad Meyer assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */
133819fcbaf1SConrad Meyer assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
133919fcbaf1SConrad Meyer job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
134019fcbaf1SConrad Meyer if (job->dstBuff.start == NULL) {
134119fcbaf1SConrad Meyer job->cSize = ERROR(memory_allocation);
134219fcbaf1SConrad Meyer return;
13430c16b537SWarner Losh }
134419fcbaf1SConrad Meyer assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */
134519fcbaf1SConrad Meyer job->src = kNullRange;
134619fcbaf1SConrad Meyer job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);
134719fcbaf1SConrad Meyer assert(!ZSTD_isError(job->cSize));
134819fcbaf1SConrad Meyer assert(job->consumed == 0);
134919fcbaf1SConrad Meyer }
135019fcbaf1SConrad Meyer
ZSTDMT_createCompressionJob(ZSTDMT_CCtx * mtctx,size_t srcSize,ZSTD_EndDirective endOp)135119fcbaf1SConrad Meyer static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)
135219fcbaf1SConrad Meyer {
135319fcbaf1SConrad Meyer unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
135419fcbaf1SConrad Meyer int const endFrame = (endOp == ZSTD_e_end);
135519fcbaf1SConrad Meyer
135619fcbaf1SConrad Meyer if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
135719fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
135819fcbaf1SConrad Meyer assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
135919fcbaf1SConrad Meyer return 0;
136019fcbaf1SConrad Meyer }
136119fcbaf1SConrad Meyer
136219fcbaf1SConrad Meyer if (!mtctx->jobReady) {
136319fcbaf1SConrad Meyer BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
136419fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
136519fcbaf1SConrad Meyer mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
136619fcbaf1SConrad Meyer mtctx->jobs[jobID].src.start = src;
136719fcbaf1SConrad Meyer mtctx->jobs[jobID].src.size = srcSize;
136819fcbaf1SConrad Meyer assert(mtctx->inBuff.filled >= srcSize);
136919fcbaf1SConrad Meyer mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
137019fcbaf1SConrad Meyer mtctx->jobs[jobID].consumed = 0;
137119fcbaf1SConrad Meyer mtctx->jobs[jobID].cSize = 0;
137219fcbaf1SConrad Meyer mtctx->jobs[jobID].params = mtctx->params;
137319fcbaf1SConrad Meyer mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
137419fcbaf1SConrad Meyer mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
137519fcbaf1SConrad Meyer mtctx->jobs[jobID].dstBuff = g_nullBuffer;
137619fcbaf1SConrad Meyer mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
137719fcbaf1SConrad Meyer mtctx->jobs[jobID].bufPool = mtctx->bufPool;
137819fcbaf1SConrad Meyer mtctx->jobs[jobID].seqPool = mtctx->seqPool;
137919fcbaf1SConrad Meyer mtctx->jobs[jobID].serial = &mtctx->serial;
138019fcbaf1SConrad Meyer mtctx->jobs[jobID].jobID = mtctx->nextJobID;
138119fcbaf1SConrad Meyer mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
138219fcbaf1SConrad Meyer mtctx->jobs[jobID].lastJob = endFrame;
13830f743729SConrad Meyer mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
138419fcbaf1SConrad Meyer mtctx->jobs[jobID].dstFlushed = 0;
138519fcbaf1SConrad Meyer
138619fcbaf1SConrad Meyer /* Update the round buffer pos and clear the input buffer to be reset */
138719fcbaf1SConrad Meyer mtctx->roundBuff.pos += srcSize;
138819fcbaf1SConrad Meyer mtctx->inBuff.buffer = g_nullBuffer;
138919fcbaf1SConrad Meyer mtctx->inBuff.filled = 0;
139019fcbaf1SConrad Meyer /* Set the prefix */
139119fcbaf1SConrad Meyer if (!endFrame) {
139219fcbaf1SConrad Meyer size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
139319fcbaf1SConrad Meyer mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
139419fcbaf1SConrad Meyer mtctx->inBuff.prefix.size = newPrefixSize;
139519fcbaf1SConrad Meyer } else { /* endFrame==1 => no need for another input buffer */
139619fcbaf1SConrad Meyer mtctx->inBuff.prefix = kNullRange;
139719fcbaf1SConrad Meyer mtctx->frameEnded = endFrame;
139819fcbaf1SConrad Meyer if (mtctx->nextJobID == 0) {
139919fcbaf1SConrad Meyer /* single job exception : checksum is already calculated directly within worker thread */
140019fcbaf1SConrad Meyer mtctx->params.fParams.checksumFlag = 0;
14010c16b537SWarner Losh } }
14020c16b537SWarner Losh
140319fcbaf1SConrad Meyer if ( (srcSize == 0)
140419fcbaf1SConrad Meyer && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
140519fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
140619fcbaf1SConrad Meyer assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */
140719fcbaf1SConrad Meyer ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
140819fcbaf1SConrad Meyer mtctx->nextJobID++;
140919fcbaf1SConrad Meyer return 0;
141019fcbaf1SConrad Meyer }
141119fcbaf1SConrad Meyer }
141219fcbaf1SConrad Meyer
141319fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",
141419fcbaf1SConrad Meyer mtctx->nextJobID,
141519fcbaf1SConrad Meyer (U32)mtctx->jobs[jobID].src.size,
141619fcbaf1SConrad Meyer mtctx->jobs[jobID].lastJob,
141719fcbaf1SConrad Meyer mtctx->nextJobID,
141819fcbaf1SConrad Meyer jobID);
141919fcbaf1SConrad Meyer if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
142019fcbaf1SConrad Meyer mtctx->nextJobID++;
142119fcbaf1SConrad Meyer mtctx->jobReady = 0;
142219fcbaf1SConrad Meyer } else {
142319fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);
142419fcbaf1SConrad Meyer mtctx->jobReady = 1;
142519fcbaf1SConrad Meyer }
14260c16b537SWarner Losh return 0;
14270c16b537SWarner Losh }
14280c16b537SWarner Losh
14290c16b537SWarner Losh
143019fcbaf1SConrad Meyer /*! ZSTDMT_flushProduced() :
14310f743729SConrad Meyer * flush whatever data has been produced but not yet flushed in current job.
14320f743729SConrad Meyer * move to next job if current one is fully flushed.
143319fcbaf1SConrad Meyer * `output` : `pos` will be updated with amount of data flushed .
143419fcbaf1SConrad Meyer * `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .
143519fcbaf1SConrad Meyer * @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */
ZSTDMT_flushProduced(ZSTDMT_CCtx * mtctx,ZSTD_outBuffer * output,unsigned blockToFlush,ZSTD_EndDirective end)143619fcbaf1SConrad Meyer static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)
14370c16b537SWarner Losh {
143819fcbaf1SConrad Meyer unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
143919fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
144019fcbaf1SConrad Meyer blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
144119fcbaf1SConrad Meyer assert(output->size >= output->pos);
144219fcbaf1SConrad Meyer
144319fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
144419fcbaf1SConrad Meyer if ( blockToFlush
144519fcbaf1SConrad Meyer && (mtctx->doneJobID < mtctx->nextJobID) ) {
144619fcbaf1SConrad Meyer assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
144719fcbaf1SConrad Meyer while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */
144819fcbaf1SConrad Meyer if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
144919fcbaf1SConrad Meyer DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
145019fcbaf1SConrad Meyer mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
145119fcbaf1SConrad Meyer break;
14520c16b537SWarner Losh }
145319fcbaf1SConrad Meyer DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
145419fcbaf1SConrad Meyer mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
145519fcbaf1SConrad Meyer ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */
14560c16b537SWarner Losh } }
145719fcbaf1SConrad Meyer
145819fcbaf1SConrad Meyer /* try to flush something */
145919fcbaf1SConrad Meyer { size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */
146019fcbaf1SConrad Meyer size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */
146119fcbaf1SConrad Meyer size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */
146219fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
146319fcbaf1SConrad Meyer if (ZSTD_isError(cSize)) {
146419fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
146519fcbaf1SConrad Meyer mtctx->doneJobID, ZSTD_getErrorName(cSize));
146619fcbaf1SConrad Meyer ZSTDMT_waitForAllJobsCompleted(mtctx);
146719fcbaf1SConrad Meyer ZSTDMT_releaseAllJobResources(mtctx);
146819fcbaf1SConrad Meyer return cSize;
14690c16b537SWarner Losh }
147019fcbaf1SConrad Meyer /* add frame checksum if necessary (can only happen once) */
147119fcbaf1SConrad Meyer assert(srcConsumed <= srcSize);
147219fcbaf1SConrad Meyer if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */
147319fcbaf1SConrad Meyer && mtctx->jobs[wJobID].frameChecksumNeeded ) {
147419fcbaf1SConrad Meyer U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
147519fcbaf1SConrad Meyer DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
147619fcbaf1SConrad Meyer MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
147719fcbaf1SConrad Meyer cSize += 4;
147819fcbaf1SConrad Meyer mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */
147919fcbaf1SConrad Meyer mtctx->jobs[wJobID].frameChecksumNeeded = 0;
14800c16b537SWarner Losh }
14810f743729SConrad Meyer
148219fcbaf1SConrad Meyer if (cSize > 0) { /* compression is ongoing or completed */
148319fcbaf1SConrad Meyer size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
148419fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
148519fcbaf1SConrad Meyer (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
148619fcbaf1SConrad Meyer assert(mtctx->doneJobID < mtctx->nextJobID);
148719fcbaf1SConrad Meyer assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
148819fcbaf1SConrad Meyer assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
148937f1f268SConrad Meyer if (toFlush > 0) {
1490f7cd7fe5SConrad Meyer ZSTD_memcpy((char*)output->dst + output->pos,
149119fcbaf1SConrad Meyer (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
149219fcbaf1SConrad Meyer toFlush);
149337f1f268SConrad Meyer }
149419fcbaf1SConrad Meyer output->pos += toFlush;
149519fcbaf1SConrad Meyer mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */
149619fcbaf1SConrad Meyer
14970f743729SConrad Meyer if ( (srcConsumed == srcSize) /* job is completed */
149819fcbaf1SConrad Meyer && (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */
149919fcbaf1SConrad Meyer DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
150019fcbaf1SConrad Meyer mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
150119fcbaf1SConrad Meyer ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
15020f743729SConrad Meyer DEBUGLOG(5, "dstBuffer released");
150319fcbaf1SConrad Meyer mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
150419fcbaf1SConrad Meyer mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */
150519fcbaf1SConrad Meyer mtctx->consumed += srcSize;
150619fcbaf1SConrad Meyer mtctx->produced += cSize;
150719fcbaf1SConrad Meyer mtctx->doneJobID++;
15080c16b537SWarner Losh } }
15090c16b537SWarner Losh
151019fcbaf1SConrad Meyer /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
151119fcbaf1SConrad Meyer if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
151219fcbaf1SConrad Meyer if (srcSize > srcConsumed) return 1; /* current job not completely compressed */
151319fcbaf1SConrad Meyer }
151419fcbaf1SConrad Meyer if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */
151519fcbaf1SConrad Meyer if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */
151619fcbaf1SConrad Meyer if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */
151719fcbaf1SConrad Meyer mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */
151819fcbaf1SConrad Meyer if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */
151919fcbaf1SConrad Meyer return 0; /* internal buffers fully flushed */
152019fcbaf1SConrad Meyer }
152119fcbaf1SConrad Meyer
152219fcbaf1SConrad Meyer /**
152319fcbaf1SConrad Meyer * Returns the range of data used by the earliest job that is not yet complete.
152419fcbaf1SConrad Meyer * If the data of the first job is broken up into two segments, we cover both
152519fcbaf1SConrad Meyer * sections.
152619fcbaf1SConrad Meyer */
ZSTDMT_getInputDataInUse(ZSTDMT_CCtx * mtctx)152719fcbaf1SConrad Meyer static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)
152819fcbaf1SConrad Meyer {
152919fcbaf1SConrad Meyer unsigned const firstJobID = mtctx->doneJobID;
153019fcbaf1SConrad Meyer unsigned const lastJobID = mtctx->nextJobID;
153119fcbaf1SConrad Meyer unsigned jobID;
153219fcbaf1SConrad Meyer
153319fcbaf1SConrad Meyer for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
153419fcbaf1SConrad Meyer unsigned const wJobID = jobID & mtctx->jobIDMask;
153519fcbaf1SConrad Meyer size_t consumed;
153619fcbaf1SConrad Meyer
153719fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
153819fcbaf1SConrad Meyer consumed = mtctx->jobs[wJobID].consumed;
153919fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
154019fcbaf1SConrad Meyer
154119fcbaf1SConrad Meyer if (consumed < mtctx->jobs[wJobID].src.size) {
154219fcbaf1SConrad Meyer range_t range = mtctx->jobs[wJobID].prefix;
154319fcbaf1SConrad Meyer if (range.size == 0) {
154419fcbaf1SConrad Meyer /* Empty prefix */
154519fcbaf1SConrad Meyer range = mtctx->jobs[wJobID].src;
154619fcbaf1SConrad Meyer }
154719fcbaf1SConrad Meyer /* Job source in multiple segments not supported yet */
154819fcbaf1SConrad Meyer assert(range.start <= mtctx->jobs[wJobID].src.start);
154919fcbaf1SConrad Meyer return range;
155019fcbaf1SConrad Meyer }
155119fcbaf1SConrad Meyer }
155219fcbaf1SConrad Meyer return kNullRange;
155319fcbaf1SConrad Meyer }
155419fcbaf1SConrad Meyer
155519fcbaf1SConrad Meyer /**
155619fcbaf1SConrad Meyer * Returns non-zero iff buffer and range overlap.
155719fcbaf1SConrad Meyer */
ZSTDMT_isOverlapped(buffer_t buffer,range_t range)155819fcbaf1SConrad Meyer static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
155919fcbaf1SConrad Meyer {
156019fcbaf1SConrad Meyer BYTE const* const bufferStart = (BYTE const*)buffer.start;
156119fcbaf1SConrad Meyer BYTE const* const rangeStart = (BYTE const*)range.start;
156219fcbaf1SConrad Meyer
156319fcbaf1SConrad Meyer if (rangeStart == NULL || bufferStart == NULL)
156419fcbaf1SConrad Meyer return 0;
1565*5ff13fbcSAllan Jude
1566*5ff13fbcSAllan Jude {
1567*5ff13fbcSAllan Jude BYTE const* const bufferEnd = bufferStart + buffer.capacity;
1568*5ff13fbcSAllan Jude BYTE const* const rangeEnd = rangeStart + range.size;
1569*5ff13fbcSAllan Jude
157019fcbaf1SConrad Meyer /* Empty ranges cannot overlap */
157119fcbaf1SConrad Meyer if (bufferStart == bufferEnd || rangeStart == rangeEnd)
157219fcbaf1SConrad Meyer return 0;
157319fcbaf1SConrad Meyer
157419fcbaf1SConrad Meyer return bufferStart < rangeEnd && rangeStart < bufferEnd;
157519fcbaf1SConrad Meyer }
1576*5ff13fbcSAllan Jude }
157719fcbaf1SConrad Meyer
ZSTDMT_doesOverlapWindow(buffer_t buffer,ZSTD_window_t window)157819fcbaf1SConrad Meyer static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)
157919fcbaf1SConrad Meyer {
158019fcbaf1SConrad Meyer range_t extDict;
158119fcbaf1SConrad Meyer range_t prefix;
158219fcbaf1SConrad Meyer
15830f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
158419fcbaf1SConrad Meyer extDict.start = window.dictBase + window.lowLimit;
158519fcbaf1SConrad Meyer extDict.size = window.dictLimit - window.lowLimit;
158619fcbaf1SConrad Meyer
158719fcbaf1SConrad Meyer prefix.start = window.base + window.dictLimit;
158819fcbaf1SConrad Meyer prefix.size = window.nextSrc - (window.base + window.dictLimit);
158919fcbaf1SConrad Meyer DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
159019fcbaf1SConrad Meyer (size_t)extDict.start,
159119fcbaf1SConrad Meyer (size_t)extDict.start + extDict.size);
159219fcbaf1SConrad Meyer DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",
159319fcbaf1SConrad Meyer (size_t)prefix.start,
159419fcbaf1SConrad Meyer (size_t)prefix.start + prefix.size);
159519fcbaf1SConrad Meyer
159619fcbaf1SConrad Meyer return ZSTDMT_isOverlapped(buffer, extDict)
159719fcbaf1SConrad Meyer || ZSTDMT_isOverlapped(buffer, prefix);
159819fcbaf1SConrad Meyer }
159919fcbaf1SConrad Meyer
ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx * mtctx,buffer_t buffer)160019fcbaf1SConrad Meyer static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)
160119fcbaf1SConrad Meyer {
1602*5ff13fbcSAllan Jude if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) {
160319fcbaf1SConrad Meyer ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
16040f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
160519fcbaf1SConrad Meyer DEBUGLOG(5, "source [0x%zx, 0x%zx)",
160619fcbaf1SConrad Meyer (size_t)buffer.start,
160719fcbaf1SConrad Meyer (size_t)buffer.start + buffer.capacity);
160819fcbaf1SConrad Meyer ZSTD_PTHREAD_MUTEX_LOCK(mutex);
160919fcbaf1SConrad Meyer while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {
16100f743729SConrad Meyer DEBUGLOG(5, "Waiting for LDM to finish...");
161119fcbaf1SConrad Meyer ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);
161219fcbaf1SConrad Meyer }
161319fcbaf1SConrad Meyer DEBUGLOG(6, "Done waiting for LDM to finish");
161419fcbaf1SConrad Meyer ZSTD_pthread_mutex_unlock(mutex);
161519fcbaf1SConrad Meyer }
161619fcbaf1SConrad Meyer }
161719fcbaf1SConrad Meyer
161819fcbaf1SConrad Meyer /**
161919fcbaf1SConrad Meyer * Attempts to set the inBuff to the next section to fill.
162019fcbaf1SConrad Meyer * If any part of the new section is still in use we give up.
162119fcbaf1SConrad Meyer * Returns non-zero if the buffer is filled.
162219fcbaf1SConrad Meyer */
ZSTDMT_tryGetInputRange(ZSTDMT_CCtx * mtctx)162319fcbaf1SConrad Meyer static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)
162419fcbaf1SConrad Meyer {
162519fcbaf1SConrad Meyer range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
162619fcbaf1SConrad Meyer size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
162719fcbaf1SConrad Meyer size_t const target = mtctx->targetSectionSize;
162819fcbaf1SConrad Meyer buffer_t buffer;
162919fcbaf1SConrad Meyer
16300f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
163119fcbaf1SConrad Meyer assert(mtctx->inBuff.buffer.start == NULL);
163219fcbaf1SConrad Meyer assert(mtctx->roundBuff.capacity >= target);
163319fcbaf1SConrad Meyer
163419fcbaf1SConrad Meyer if (spaceLeft < target) {
163519fcbaf1SConrad Meyer /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
163619fcbaf1SConrad Meyer * Simply copy the prefix to the beginning in that case.
163719fcbaf1SConrad Meyer */
163819fcbaf1SConrad Meyer BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
163919fcbaf1SConrad Meyer size_t const prefixSize = mtctx->inBuff.prefix.size;
164019fcbaf1SConrad Meyer
164119fcbaf1SConrad Meyer buffer.start = start;
164219fcbaf1SConrad Meyer buffer.capacity = prefixSize;
164319fcbaf1SConrad Meyer if (ZSTDMT_isOverlapped(buffer, inUse)) {
16440f743729SConrad Meyer DEBUGLOG(5, "Waiting for buffer...");
164519fcbaf1SConrad Meyer return 0;
164619fcbaf1SConrad Meyer }
164719fcbaf1SConrad Meyer ZSTDMT_waitForLdmComplete(mtctx, buffer);
1648f7cd7fe5SConrad Meyer ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);
164919fcbaf1SConrad Meyer mtctx->inBuff.prefix.start = start;
165019fcbaf1SConrad Meyer mtctx->roundBuff.pos = prefixSize;
165119fcbaf1SConrad Meyer }
165219fcbaf1SConrad Meyer buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
165319fcbaf1SConrad Meyer buffer.capacity = target;
165419fcbaf1SConrad Meyer
165519fcbaf1SConrad Meyer if (ZSTDMT_isOverlapped(buffer, inUse)) {
16560f743729SConrad Meyer DEBUGLOG(5, "Waiting for buffer...");
165719fcbaf1SConrad Meyer return 0;
165819fcbaf1SConrad Meyer }
165919fcbaf1SConrad Meyer assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
166019fcbaf1SConrad Meyer
166119fcbaf1SConrad Meyer ZSTDMT_waitForLdmComplete(mtctx, buffer);
166219fcbaf1SConrad Meyer
166319fcbaf1SConrad Meyer DEBUGLOG(5, "Using prefix range [%zx, %zx)",
166419fcbaf1SConrad Meyer (size_t)mtctx->inBuff.prefix.start,
166519fcbaf1SConrad Meyer (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
166619fcbaf1SConrad Meyer DEBUGLOG(5, "Using source range [%zx, %zx)",
166719fcbaf1SConrad Meyer (size_t)buffer.start,
166819fcbaf1SConrad Meyer (size_t)buffer.start + buffer.capacity);
166919fcbaf1SConrad Meyer
167019fcbaf1SConrad Meyer
167119fcbaf1SConrad Meyer mtctx->inBuff.buffer = buffer;
167219fcbaf1SConrad Meyer mtctx->inBuff.filled = 0;
167319fcbaf1SConrad Meyer assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);
167419fcbaf1SConrad Meyer return 1;
167519fcbaf1SConrad Meyer }
167619fcbaf1SConrad Meyer
1677a0483764SConrad Meyer typedef struct {
1678a0483764SConrad Meyer size_t toLoad; /* The number of bytes to load from the input. */
1679a0483764SConrad Meyer int flush; /* Boolean declaring if we must flush because we found a synchronization point. */
1680a0483764SConrad Meyer } syncPoint_t;
1681a0483764SConrad Meyer
1682a0483764SConrad Meyer /**
1683a0483764SConrad Meyer * Searches through the input for a synchronization point. If one is found, we
1684a0483764SConrad Meyer * will instruct the caller to flush, and return the number of bytes to load.
1685a0483764SConrad Meyer * Otherwise, we will load as many bytes as possible and instruct the caller
1686a0483764SConrad Meyer * to continue as normal.
1687a0483764SConrad Meyer */
1688a0483764SConrad Meyer static syncPoint_t
findSynchronizationPoint(ZSTDMT_CCtx const * mtctx,ZSTD_inBuffer const input)1689a0483764SConrad Meyer findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)
1690a0483764SConrad Meyer {
1691a0483764SConrad Meyer BYTE const* const istart = (BYTE const*)input.src + input.pos;
1692a0483764SConrad Meyer U64 const primePower = mtctx->rsync.primePower;
1693a0483764SConrad Meyer U64 const hitMask = mtctx->rsync.hitMask;
1694a0483764SConrad Meyer
1695a0483764SConrad Meyer syncPoint_t syncPoint;
1696a0483764SConrad Meyer U64 hash;
1697a0483764SConrad Meyer BYTE const* prev;
1698a0483764SConrad Meyer size_t pos;
1699a0483764SConrad Meyer
1700a0483764SConrad Meyer syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
1701a0483764SConrad Meyer syncPoint.flush = 0;
1702a0483764SConrad Meyer if (!mtctx->params.rsyncable)
1703a0483764SConrad Meyer /* Rsync is disabled. */
1704a0483764SConrad Meyer return syncPoint;
1705*5ff13fbcSAllan Jude if (mtctx->inBuff.filled + input.size - input.pos < RSYNC_MIN_BLOCK_SIZE)
1706*5ff13fbcSAllan Jude /* We don't emit synchronization points if it would produce too small blocks.
1707*5ff13fbcSAllan Jude * We don't have enough input to find a synchronization point, so don't look.
1708*5ff13fbcSAllan Jude */
1709*5ff13fbcSAllan Jude return syncPoint;
1710a0483764SConrad Meyer if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
1711a0483764SConrad Meyer /* Not enough to compute the hash.
1712a0483764SConrad Meyer * We will miss any synchronization points in this RSYNC_LENGTH byte
1713a0483764SConrad Meyer * window. However, since it depends only in the internal buffers, if the
1714a0483764SConrad Meyer * state is already synchronized, we will remain synchronized.
1715a0483764SConrad Meyer * Additionally, the probability that we miss a synchronization point is
1716a0483764SConrad Meyer * low: RSYNC_LENGTH / targetSectionSize.
1717a0483764SConrad Meyer */
1718a0483764SConrad Meyer return syncPoint;
1719a0483764SConrad Meyer /* Initialize the loop variables. */
1720*5ff13fbcSAllan Jude if (mtctx->inBuff.filled < RSYNC_MIN_BLOCK_SIZE) {
1721*5ff13fbcSAllan Jude /* We don't need to scan the first RSYNC_MIN_BLOCK_SIZE positions
1722*5ff13fbcSAllan Jude * because they can't possibly be a sync point. So we can start
1723*5ff13fbcSAllan Jude * part way through the input buffer.
1724*5ff13fbcSAllan Jude */
1725*5ff13fbcSAllan Jude pos = RSYNC_MIN_BLOCK_SIZE - mtctx->inBuff.filled;
1726*5ff13fbcSAllan Jude if (pos >= RSYNC_LENGTH) {
1727*5ff13fbcSAllan Jude prev = istart + pos - RSYNC_LENGTH;
1728*5ff13fbcSAllan Jude hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
1729*5ff13fbcSAllan Jude } else {
1730*5ff13fbcSAllan Jude assert(mtctx->inBuff.filled >= RSYNC_LENGTH);
1731*5ff13fbcSAllan Jude prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
1732*5ff13fbcSAllan Jude hash = ZSTD_rollingHash_compute(prev + pos, (RSYNC_LENGTH - pos));
1733*5ff13fbcSAllan Jude hash = ZSTD_rollingHash_append(hash, istart, pos);
1734*5ff13fbcSAllan Jude }
1735*5ff13fbcSAllan Jude } else {
1736*5ff13fbcSAllan Jude /* We have enough bytes buffered to initialize the hash,
1737*5ff13fbcSAllan Jude * and are have processed enough bytes to find a sync point.
1738a0483764SConrad Meyer * Start scanning at the beginning of the input.
1739a0483764SConrad Meyer */
1740*5ff13fbcSAllan Jude assert(mtctx->inBuff.filled >= RSYNC_MIN_BLOCK_SIZE);
1741*5ff13fbcSAllan Jude assert(RSYNC_MIN_BLOCK_SIZE >= RSYNC_LENGTH);
1742a0483764SConrad Meyer pos = 0;
1743a0483764SConrad Meyer prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
1744a0483764SConrad Meyer hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
1745f7cd7fe5SConrad Meyer if ((hash & hitMask) == hitMask) {
1746f7cd7fe5SConrad Meyer /* We're already at a sync point so don't load any more until
1747f7cd7fe5SConrad Meyer * we're able to flush this sync point.
1748f7cd7fe5SConrad Meyer * This likely happened because the job table was full so we
1749f7cd7fe5SConrad Meyer * couldn't add our job.
1750f7cd7fe5SConrad Meyer */
1751f7cd7fe5SConrad Meyer syncPoint.toLoad = 0;
1752f7cd7fe5SConrad Meyer syncPoint.flush = 1;
1753f7cd7fe5SConrad Meyer return syncPoint;
1754f7cd7fe5SConrad Meyer }
1755a0483764SConrad Meyer }
1756a0483764SConrad Meyer /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
1757a0483764SConrad Meyer * through the input. If we hit a synchronization point, then cut the
1758a0483764SConrad Meyer * job off, and tell the compressor to flush the job. Otherwise, load
1759a0483764SConrad Meyer * all the bytes and continue as normal.
1760a0483764SConrad Meyer * If we go too long without a synchronization point (targetSectionSize)
1761a0483764SConrad Meyer * then a block will be emitted anyways, but this is okay, since if we
1762a0483764SConrad Meyer * are already synchronized we will remain synchronized.
1763a0483764SConrad Meyer */
1764a0483764SConrad Meyer for (; pos < syncPoint.toLoad; ++pos) {
1765a0483764SConrad Meyer BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
1766*5ff13fbcSAllan Jude assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);
1767a0483764SConrad Meyer hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
1768*5ff13fbcSAllan Jude assert(mtctx->inBuff.filled + pos >= RSYNC_MIN_BLOCK_SIZE);
1769a0483764SConrad Meyer if ((hash & hitMask) == hitMask) {
1770a0483764SConrad Meyer syncPoint.toLoad = pos + 1;
1771a0483764SConrad Meyer syncPoint.flush = 1;
1772a0483764SConrad Meyer break;
1773a0483764SConrad Meyer }
1774a0483764SConrad Meyer }
1775a0483764SConrad Meyer return syncPoint;
1776a0483764SConrad Meyer }
1777a0483764SConrad Meyer
ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx * mtctx)1778a0483764SConrad Meyer size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)
1779a0483764SConrad Meyer {
1780a0483764SConrad Meyer size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;
1781a0483764SConrad Meyer if (hintInSize==0) hintInSize = mtctx->targetSectionSize;
1782a0483764SConrad Meyer return hintInSize;
1783a0483764SConrad Meyer }
17840c16b537SWarner Losh
17850c16b537SWarner Losh /** ZSTDMT_compressStream_generic() :
17860c16b537SWarner Losh * internal use only - exposed to be invoked from zstd_compress.c
17870c16b537SWarner Losh * assumption : output and input are valid (pos <= size)
17880c16b537SWarner Losh * @return : minimum amount of data remaining to flush, 0 if none */
ZSTDMT_compressStream_generic(ZSTDMT_CCtx * mtctx,ZSTD_outBuffer * output,ZSTD_inBuffer * input,ZSTD_EndDirective endOp)17890c16b537SWarner Losh size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
17900c16b537SWarner Losh ZSTD_outBuffer* output,
17910c16b537SWarner Losh ZSTD_inBuffer* input,
17920c16b537SWarner Losh ZSTD_EndDirective endOp)
17930c16b537SWarner Losh {
17940c16b537SWarner Losh unsigned forwardInputProgress = 0;
179519fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
179619fcbaf1SConrad Meyer (U32)endOp, (U32)(input->size - input->pos));
17970c16b537SWarner Losh assert(output->pos <= output->size);
17980c16b537SWarner Losh assert(input->pos <= input->size);
1799052d3c12SConrad Meyer
18000c16b537SWarner Losh if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
18010c16b537SWarner Losh /* current frame being ended. Only flush/end are allowed */
18020c16b537SWarner Losh return ERROR(stage_wrong);
18030c16b537SWarner Losh }
18040c16b537SWarner Losh
18050c16b537SWarner Losh /* fill input buffer */
180619fcbaf1SConrad Meyer if ( (!mtctx->jobReady)
180719fcbaf1SConrad Meyer && (input->size > input->pos) ) { /* support NULL input */
18080c16b537SWarner Losh if (mtctx->inBuff.buffer.start == NULL) {
180919fcbaf1SConrad Meyer assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
181019fcbaf1SConrad Meyer if (!ZSTDMT_tryGetInputRange(mtctx)) {
181119fcbaf1SConrad Meyer /* It is only possible for this operation to fail if there are
181219fcbaf1SConrad Meyer * still compression jobs ongoing.
181319fcbaf1SConrad Meyer */
18140f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
181519fcbaf1SConrad Meyer assert(mtctx->doneJobID != mtctx->nextJobID);
18160f743729SConrad Meyer } else
18170f743729SConrad Meyer DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
181819fcbaf1SConrad Meyer }
181919fcbaf1SConrad Meyer if (mtctx->inBuff.buffer.start != NULL) {
1820a0483764SConrad Meyer syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
1821a0483764SConrad Meyer if (syncPoint.flush && endOp == ZSTD_e_continue) {
1822a0483764SConrad Meyer endOp = ZSTD_e_flush;
1823a0483764SConrad Meyer }
182419fcbaf1SConrad Meyer assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
182519fcbaf1SConrad Meyer DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
1826a0483764SConrad Meyer (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
1827f7cd7fe5SConrad Meyer ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
1828a0483764SConrad Meyer input->pos += syncPoint.toLoad;
1829a0483764SConrad Meyer mtctx->inBuff.filled += syncPoint.toLoad;
1830a0483764SConrad Meyer forwardInputProgress = syncPoint.toLoad>0;
183119fcbaf1SConrad Meyer }
1832f7cd7fe5SConrad Meyer }
1833f7cd7fe5SConrad Meyer if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {
1834f7cd7fe5SConrad Meyer /* Can't end yet because the input is not fully consumed.
1835f7cd7fe5SConrad Meyer * We are in one of these cases:
1836f7cd7fe5SConrad Meyer * - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.
1837f7cd7fe5SConrad Meyer * - We filled the input buffer: flush this job but don't end the frame.
1838f7cd7fe5SConrad Meyer * - We hit a synchronization point: flush this job but don't end the frame.
1839f7cd7fe5SConrad Meyer */
1840f7cd7fe5SConrad Meyer assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);
1841f7cd7fe5SConrad Meyer endOp = ZSTD_e_flush;
184219fcbaf1SConrad Meyer }
18430c16b537SWarner Losh
184419fcbaf1SConrad Meyer if ( (mtctx->jobReady)
184519fcbaf1SConrad Meyer || (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */
184619fcbaf1SConrad Meyer || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */
184719fcbaf1SConrad Meyer || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */
184819fcbaf1SConrad Meyer size_t const jobSize = mtctx->inBuff.filled;
184919fcbaf1SConrad Meyer assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
185037f1f268SConrad Meyer FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");
18510c16b537SWarner Losh }
18520c16b537SWarner Losh
18530c16b537SWarner Losh /* check for potential compressed data ready to be flushed */
185419fcbaf1SConrad Meyer { size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */
185519fcbaf1SConrad Meyer if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */
18560f743729SConrad Meyer DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);
185719fcbaf1SConrad Meyer return remainingToFlush;
18580c16b537SWarner Losh }
18590c16b537SWarner Losh }
1860