Coverage Report

Created: 2026-12-01 06:39

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