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