Path: blob/main/sys/contrib/zstd/lib/compress/zstdmt_compress.c
48378 views
/*1* Copyright (c) Yann Collet, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/91011/* ====== Compiler specifics ====== */12#if defined(_MSC_VER)13# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */14#endif151617/* ====== Constants ====== */18#define ZSTDMT_OVERLAPLOG_DEFAULT 0192021/* ====== Dependencies ====== */22#include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset, INT_MAX, UINT_MAX */23#include "../common/mem.h" /* MEM_STATIC */24#include "../common/pool.h" /* threadpool */25#include "../common/threading.h" /* mutex */26#include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */27#include "zstd_ldm.h"28#include "zstdmt_compress.h"2930/* Guards code to support resizing the SeqPool.31* We will want to resize the SeqPool to save memory in the future.32* Until then, comment the code out since it is unused.33*/34#define ZSTD_RESIZE_SEQPOOL 03536/* ====== Debug ====== */37#if defined(DEBUGLEVEL) && (DEBUGLEVEL>=2) \38&& !defined(_MSC_VER) \39&& !defined(__MINGW32__)4041# include <stdio.h>42# include <unistd.h>43# include <sys/times.h>4445# define DEBUG_PRINTHEX(l,p,n) { \46unsigned debug_u; \47for (debug_u=0; debug_u<(n); debug_u++) \48RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \49RAWLOG(l, " \n"); \50}5152static unsigned long long GetCurrentClockTimeMicroseconds(void)53{54static clock_t _ticksPerSecond = 0;55if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);5657{ struct tms junk; clock_t newTicks = (clock_t) times(&junk);58return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);59} }6061#define MUTEX_WAIT_TIME_DLEVEL 662#define ZSTD_PTHREAD_MUTEX_LOCK(mutex) { \63if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) { \64unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \65ZSTD_pthread_mutex_lock(mutex); \66{ unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \67unsigned long long const elapsedTime = (afterTime-beforeTime); \68if (elapsedTime > 1000) { /* or whatever threshold you like; I'm using 1 millisecond here */ \69DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \70elapsedTime, #mutex); \71} } \72} else { \73ZSTD_pthread_mutex_lock(mutex); \74} \75}7677#else7879# define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)80# define DEBUG_PRINTHEX(l,p,n) {}8182#endif838485/* ===== Buffer Pool ===== */86/* a single Buffer Pool can be invoked from multiple threads in parallel */8788typedef struct buffer_s {89void* start;90size_t capacity;91} buffer_t;9293static const buffer_t g_nullBuffer = { NULL, 0 };9495typedef struct ZSTDMT_bufferPool_s {96ZSTD_pthread_mutex_t poolMutex;97size_t bufferSize;98unsigned totalBuffers;99unsigned nbBuffers;100ZSTD_customMem cMem;101buffer_t bTable[1]; /* variable size */102} ZSTDMT_bufferPool;103104static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_customMem cMem)105{106ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_customCalloc(107sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);108if (bufPool==NULL) return NULL;109if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {110ZSTD_customFree(bufPool, cMem);111return NULL;112}113bufPool->bufferSize = 64 KB;114bufPool->totalBuffers = maxNbBuffers;115bufPool->nbBuffers = 0;116bufPool->cMem = cMem;117return bufPool;118}119120static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)121{122unsigned u;123DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);124if (!bufPool) return; /* compatibility with free on NULL */125for (u=0; u<bufPool->totalBuffers; u++) {126DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);127ZSTD_customFree(bufPool->bTable[u].start, bufPool->cMem);128}129ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);130ZSTD_customFree(bufPool, bufPool->cMem);131}132133/* only works at initialization, not during compression */134static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)135{136size_t const poolSize = sizeof(*bufPool)137+ (bufPool->totalBuffers - 1) * sizeof(buffer_t);138unsigned u;139size_t totalBufferSize = 0;140ZSTD_pthread_mutex_lock(&bufPool->poolMutex);141for (u=0; u<bufPool->totalBuffers; u++)142totalBufferSize += bufPool->bTable[u].capacity;143ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);144145return poolSize + totalBufferSize;146}147148/* ZSTDMT_setBufferSize() :149* all future buffers provided by this buffer pool will have _at least_ this size150* note : it's better for all buffers to have same size,151* as they become freely interchangeable, reducing malloc/free usages and memory fragmentation */152static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* const bufPool, size_t const bSize)153{154ZSTD_pthread_mutex_lock(&bufPool->poolMutex);155DEBUGLOG(4, "ZSTDMT_setBufferSize: bSize = %u", (U32)bSize);156bufPool->bufferSize = bSize;157ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);158}159160161static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, unsigned maxNbBuffers)162{163if (srcBufPool==NULL) return NULL;164if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */165return srcBufPool;166/* need a larger buffer pool */167{ ZSTD_customMem const cMem = srcBufPool->cMem;168size_t const bSize = srcBufPool->bufferSize; /* forward parameters */169ZSTDMT_bufferPool* newBufPool;170ZSTDMT_freeBufferPool(srcBufPool);171newBufPool = ZSTDMT_createBufferPool(maxNbBuffers, cMem);172if (newBufPool==NULL) return newBufPool;173ZSTDMT_setBufferSize(newBufPool, bSize);174return newBufPool;175}176}177178/** ZSTDMT_getBuffer() :179* assumption : bufPool must be valid180* @return : a buffer, with start pointer and size181* note: allocation may fail, in this case, start==NULL and size==0 */182static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)183{184size_t const bSize = bufPool->bufferSize;185DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);186ZSTD_pthread_mutex_lock(&bufPool->poolMutex);187if (bufPool->nbBuffers) { /* try to use an existing buffer */188buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];189size_t const availBufferSize = buf.capacity;190bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;191if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {192/* large enough, but not too much */193DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",194bufPool->nbBuffers, (U32)buf.capacity);195ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);196return buf;197}198/* size conditions not respected : scratch this buffer, create new one */199DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");200ZSTD_customFree(buf.start, bufPool->cMem);201}202ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);203/* create new buffer */204DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");205{ buffer_t buffer;206void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);207buffer.start = start; /* note : start can be NULL if malloc fails ! */208buffer.capacity = (start==NULL) ? 0 : bSize;209if (start==NULL) {210DEBUGLOG(5, "ZSTDMT_getBuffer: buffer allocation failure !!");211} else {212DEBUGLOG(5, "ZSTDMT_getBuffer: created buffer of size %u", (U32)bSize);213}214return buffer;215}216}217218#if ZSTD_RESIZE_SEQPOOL219/** ZSTDMT_resizeBuffer() :220* assumption : bufPool must be valid221* @return : a buffer that is at least the buffer pool buffer size.222* If a reallocation happens, the data in the input buffer is copied.223*/224static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer)225{226size_t const bSize = bufPool->bufferSize;227if (buffer.capacity < bSize) {228void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);229buffer_t newBuffer;230newBuffer.start = start;231newBuffer.capacity = start == NULL ? 0 : bSize;232if (start != NULL) {233assert(newBuffer.capacity >= buffer.capacity);234ZSTD_memcpy(newBuffer.start, buffer.start, buffer.capacity);235DEBUGLOG(5, "ZSTDMT_resizeBuffer: created buffer of size %u", (U32)bSize);236return newBuffer;237}238DEBUGLOG(5, "ZSTDMT_resizeBuffer: buffer allocation failure !!");239}240return buffer;241}242#endif243244/* store buffer for later re-use, up to pool capacity */245static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)246{247DEBUGLOG(5, "ZSTDMT_releaseBuffer");248if (buf.start == NULL) return; /* compatible with release on NULL */249ZSTD_pthread_mutex_lock(&bufPool->poolMutex);250if (bufPool->nbBuffers < bufPool->totalBuffers) {251bufPool->bTable[bufPool->nbBuffers++] = buf; /* stored for later use */252DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",253(U32)buf.capacity, (U32)(bufPool->nbBuffers-1));254ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);255return;256}257ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);258/* Reached bufferPool capacity (should not happen) */259DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");260ZSTD_customFree(buf.start, bufPool->cMem);261}262263/* We need 2 output buffers per worker since each dstBuff must be flushed after it is released.264* The 3 additional buffers are as follows:265* 1 buffer for input loading266* 1 buffer for "next input" when submitting current one267* 1 buffer stuck in queue */268#define BUF_POOL_MAX_NB_BUFFERS(nbWorkers) 2*nbWorkers + 3269270/* After a worker releases its rawSeqStore, it is immediately ready for reuse.271* So we only need one seq buffer per worker. */272#define SEQ_POOL_MAX_NB_BUFFERS(nbWorkers) nbWorkers273274/* ===== Seq Pool Wrapper ====== */275276typedef ZSTDMT_bufferPool ZSTDMT_seqPool;277278static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)279{280return ZSTDMT_sizeof_bufferPool(seqPool);281}282283static rawSeqStore_t bufferToSeq(buffer_t buffer)284{285rawSeqStore_t seq = kNullRawSeqStore;286seq.seq = (rawSeq*)buffer.start;287seq.capacity = buffer.capacity / sizeof(rawSeq);288return seq;289}290291static buffer_t seqToBuffer(rawSeqStore_t seq)292{293buffer_t buffer;294buffer.start = seq.seq;295buffer.capacity = seq.capacity * sizeof(rawSeq);296return buffer;297}298299static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)300{301if (seqPool->bufferSize == 0) {302return kNullRawSeqStore;303}304return bufferToSeq(ZSTDMT_getBuffer(seqPool));305}306307#if ZSTD_RESIZE_SEQPOOL308static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)309{310return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));311}312#endif313314static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)315{316ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));317}318319static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)320{321ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));322}323324static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)325{326ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(SEQ_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);327if (seqPool == NULL) return NULL;328ZSTDMT_setNbSeq(seqPool, 0);329return seqPool;330}331332static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)333{334ZSTDMT_freeBufferPool(seqPool);335}336337static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)338{339return ZSTDMT_expandBufferPool(pool, SEQ_POOL_MAX_NB_BUFFERS(nbWorkers));340}341342343/* ===== CCtx Pool ===== */344/* a single CCtx Pool can be invoked from multiple threads in parallel */345346typedef struct {347ZSTD_pthread_mutex_t poolMutex;348int totalCCtx;349int availCCtx;350ZSTD_customMem cMem;351ZSTD_CCtx* cctx[1]; /* variable size */352} ZSTDMT_CCtxPool;353354/* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */355static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)356{357int cid;358for (cid=0; cid<pool->totalCCtx; cid++)359ZSTD_freeCCtx(pool->cctx[cid]); /* note : compatible with free on NULL */360ZSTD_pthread_mutex_destroy(&pool->poolMutex);361ZSTD_customFree(pool, pool->cMem);362}363364/* ZSTDMT_createCCtxPool() :365* implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */366static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,367ZSTD_customMem cMem)368{369ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_customCalloc(370sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);371assert(nbWorkers > 0);372if (!cctxPool) return NULL;373if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {374ZSTD_customFree(cctxPool, cMem);375return NULL;376}377cctxPool->cMem = cMem;378cctxPool->totalCCtx = nbWorkers;379cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */380cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);381if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }382DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);383return cctxPool;384}385386static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,387int nbWorkers)388{389if (srcPool==NULL) return NULL;390if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */391/* need a larger cctx pool */392{ ZSTD_customMem const cMem = srcPool->cMem;393ZSTDMT_freeCCtxPool(srcPool);394return ZSTDMT_createCCtxPool(nbWorkers, cMem);395}396}397398/* only works during initialization phase, not during compression */399static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)400{401ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);402{ unsigned const nbWorkers = cctxPool->totalCCtx;403size_t const poolSize = sizeof(*cctxPool)404+ (nbWorkers-1) * sizeof(ZSTD_CCtx*);405unsigned u;406size_t totalCCtxSize = 0;407for (u=0; u<nbWorkers; u++) {408totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);409}410ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);411assert(nbWorkers > 0);412return poolSize + totalCCtxSize;413}414}415416static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)417{418DEBUGLOG(5, "ZSTDMT_getCCtx");419ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);420if (cctxPool->availCCtx) {421cctxPool->availCCtx--;422{ ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];423ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);424return cctx;425} }426ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);427DEBUGLOG(5, "create one more CCtx");428return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */429}430431static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)432{433if (cctx==NULL) return; /* compatibility with release on NULL */434ZSTD_pthread_mutex_lock(&pool->poolMutex);435if (pool->availCCtx < pool->totalCCtx)436pool->cctx[pool->availCCtx++] = cctx;437else {438/* pool overflow : should not happen, since totalCCtx==nbWorkers */439DEBUGLOG(4, "CCtx pool overflow : free cctx");440ZSTD_freeCCtx(cctx);441}442ZSTD_pthread_mutex_unlock(&pool->poolMutex);443}444445/* ==== Serial State ==== */446447typedef struct {448void const* start;449size_t size;450} range_t;451452typedef struct {453/* All variables in the struct are protected by mutex. */454ZSTD_pthread_mutex_t mutex;455ZSTD_pthread_cond_t cond;456ZSTD_CCtx_params params;457ldmState_t ldmState;458XXH64_state_t xxhState;459unsigned nextJobID;460/* Protects ldmWindow.461* Must be acquired after the main mutex when acquiring both.462*/463ZSTD_pthread_mutex_t ldmWindowMutex;464ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is updated */465ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */466} serialState_t;467468static int469ZSTDMT_serialState_reset(serialState_t* serialState,470ZSTDMT_seqPool* seqPool,471ZSTD_CCtx_params params,472size_t jobSize,473const void* dict, size_t const dictSize,474ZSTD_dictContentType_e dictContentType)475{476/* Adjust parameters */477if (params.ldmParams.enableLdm == ZSTD_ps_enable) {478DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);479ZSTD_ldm_adjustParameters(¶ms.ldmParams, ¶ms.cParams);480assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);481assert(params.ldmParams.hashRateLog < 32);482} else {483ZSTD_memset(¶ms.ldmParams, 0, sizeof(params.ldmParams));484}485serialState->nextJobID = 0;486if (params.fParams.checksumFlag)487XXH64_reset(&serialState->xxhState, 0);488if (params.ldmParams.enableLdm == ZSTD_ps_enable) {489ZSTD_customMem cMem = params.customMem;490unsigned const hashLog = params.ldmParams.hashLog;491size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);492unsigned const bucketLog =493params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;494unsigned const prevBucketLog =495serialState->params.ldmParams.hashLog -496serialState->params.ldmParams.bucketSizeLog;497size_t const numBuckets = (size_t)1 << bucketLog;498/* Size the seq pool tables */499ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));500/* Reset the window */501ZSTD_window_init(&serialState->ldmState.window);502/* Resize tables and output space if necessary. */503if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {504ZSTD_customFree(serialState->ldmState.hashTable, cMem);505serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_customMalloc(hashSize, cMem);506}507if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {508ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);509serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_customMalloc(numBuckets, cMem);510}511if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)512return 1;513/* Zero the tables */514ZSTD_memset(serialState->ldmState.hashTable, 0, hashSize);515ZSTD_memset(serialState->ldmState.bucketOffsets, 0, numBuckets);516517/* Update window state and fill hash table with dict */518serialState->ldmState.loadedDictEnd = 0;519if (dictSize > 0) {520if (dictContentType == ZSTD_dct_rawContent) {521BYTE const* const dictEnd = (const BYTE*)dict + dictSize;522ZSTD_window_update(&serialState->ldmState.window, dict, dictSize, /* forceNonContiguous */ 0);523ZSTD_ldm_fillHashTable(&serialState->ldmState, (const BYTE*)dict, dictEnd, ¶ms.ldmParams);524serialState->ldmState.loadedDictEnd = params.forceWindow ? 0 : (U32)(dictEnd - serialState->ldmState.window.base);525} else {526/* don't even load anything */527}528}529530/* Initialize serialState's copy of ldmWindow. */531serialState->ldmWindow = serialState->ldmState.window;532}533534serialState->params = params;535serialState->params.jobSize = (U32)jobSize;536return 0;537}538539static int ZSTDMT_serialState_init(serialState_t* serialState)540{541int initError = 0;542ZSTD_memset(serialState, 0, sizeof(*serialState));543initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);544initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);545initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);546initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);547return initError;548}549550static void ZSTDMT_serialState_free(serialState_t* serialState)551{552ZSTD_customMem cMem = serialState->params.customMem;553ZSTD_pthread_mutex_destroy(&serialState->mutex);554ZSTD_pthread_cond_destroy(&serialState->cond);555ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);556ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);557ZSTD_customFree(serialState->ldmState.hashTable, cMem);558ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);559}560561static void ZSTDMT_serialState_update(serialState_t* serialState,562ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore,563range_t src, unsigned jobID)564{565/* Wait for our turn */566ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);567while (serialState->nextJobID < jobID) {568DEBUGLOG(5, "wait for serialState->cond");569ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);570}571/* A future job may error and skip our job */572if (serialState->nextJobID == jobID) {573/* It is now our turn, do any processing necessary */574if (serialState->params.ldmParams.enableLdm == ZSTD_ps_enable) {575size_t error;576assert(seqStore.seq != NULL && seqStore.pos == 0 &&577seqStore.size == 0 && seqStore.capacity > 0);578assert(src.size <= serialState->params.jobSize);579ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0);580error = ZSTD_ldm_generateSequences(581&serialState->ldmState, &seqStore,582&serialState->params.ldmParams, src.start, src.size);583/* We provide a large enough buffer to never fail. */584assert(!ZSTD_isError(error)); (void)error;585/* Update ldmWindow to match the ldmState.window and signal the main586* thread if it is waiting for a buffer.587*/588ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);589serialState->ldmWindow = serialState->ldmState.window;590ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);591ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);592}593if (serialState->params.fParams.checksumFlag && src.size > 0)594XXH64_update(&serialState->xxhState, src.start, src.size);595}596/* Now it is the next jobs turn */597serialState->nextJobID++;598ZSTD_pthread_cond_broadcast(&serialState->cond);599ZSTD_pthread_mutex_unlock(&serialState->mutex);600601if (seqStore.size > 0) {602size_t const err = ZSTD_referenceExternalSequences(603jobCCtx, seqStore.seq, seqStore.size);604assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable);605assert(!ZSTD_isError(err));606(void)err;607}608}609610static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,611unsigned jobID, size_t cSize)612{613ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);614if (serialState->nextJobID <= jobID) {615assert(ZSTD_isError(cSize)); (void)cSize;616DEBUGLOG(5, "Skipping past job %u because of error", jobID);617serialState->nextJobID = jobID + 1;618ZSTD_pthread_cond_broadcast(&serialState->cond);619620ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);621ZSTD_window_clear(&serialState->ldmWindow);622ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);623ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);624}625ZSTD_pthread_mutex_unlock(&serialState->mutex);626627}628629630/* ------------------------------------------ */631/* ===== Worker thread ===== */632/* ------------------------------------------ */633634static const range_t kNullRange = { NULL, 0 };635636typedef struct {637size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */638size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */639ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */640ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */641ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */642ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */643ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */644serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */645buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */646range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */647range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */648unsigned jobID; /* set by mtctx, then read by worker => no barrier */649unsigned firstJob; /* set by mtctx, then read by worker => no barrier */650unsigned lastJob; /* set by mtctx, then read by worker => no barrier */651ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */652const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */653unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */654size_t dstFlushed; /* used only by mtctx */655unsigned frameChecksumNeeded; /* used only by mtctx */656} ZSTDMT_jobDescription;657658#define JOB_ERROR(e) { \659ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \660job->cSize = e; \661ZSTD_pthread_mutex_unlock(&job->job_mutex); \662goto _endJob; \663}664665/* ZSTDMT_compressionJob() is a POOL_function type */666static void ZSTDMT_compressionJob(void* jobDescription)667{668ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;669ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */670ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);671rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);672buffer_t dstBuff = job->dstBuff;673size_t lastCBlockSize = 0;674675/* resources */676if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));677if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */678dstBuff = ZSTDMT_getBuffer(job->bufPool);679if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));680job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */681}682if (jobParams.ldmParams.enableLdm == ZSTD_ps_enable && rawSeqStore.seq == NULL)683JOB_ERROR(ERROR(memory_allocation));684685/* Don't compute the checksum for chunks, since we compute it externally,686* but write it in the header.687*/688if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;689/* Don't run LDM for the chunks, since we handle it externally */690jobParams.ldmParams.enableLdm = ZSTD_ps_disable;691/* Correct nbWorkers to 0. */692jobParams.nbWorkers = 0;693694695/* init */696if (job->cdict) {697size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize);698assert(job->firstJob); /* only allowed for first job */699if (ZSTD_isError(initError)) JOB_ERROR(initError);700} else { /* srcStart points at reloaded section */701U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;702{ size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);703if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);704}705if (!job->firstJob) {706size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0);707if (ZSTD_isError(err)) JOB_ERROR(err);708}709{ size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,710job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */711ZSTD_dtlm_fast,712NULL, /*cdict*/713&jobParams, pledgedSrcSize);714if (ZSTD_isError(initError)) JOB_ERROR(initError);715} }716717/* Perform serial step as early as possible, but after CCtx initialization */718ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);719720if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */721size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);722if (ZSTD_isError(hSize)) JOB_ERROR(hSize);723DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);724ZSTD_invalidateRepCodes(cctx);725}726727/* compress */728{ size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;729int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);730const BYTE* ip = (const BYTE*) job->src.start;731BYTE* const ostart = (BYTE*)dstBuff.start;732BYTE* op = ostart;733BYTE* oend = op + dstBuff.capacity;734int chunkNb;735if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */736DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);737assert(job->cSize == 0);738for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {739size_t const cSize = ZSTD_compressContinue(cctx, op, oend-op, ip, chunkSize);740if (ZSTD_isError(cSize)) JOB_ERROR(cSize);741ip += chunkSize;742op += cSize; assert(op < oend);743/* stats */744ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);745job->cSize += cSize;746job->consumed = chunkSize * chunkNb;747DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",748(U32)cSize, (U32)job->cSize);749ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */750ZSTD_pthread_mutex_unlock(&job->job_mutex);751}752/* last block */753assert(chunkSize > 0);754assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */755if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {756size_t const lastBlockSize1 = job->src.size & (chunkSize-1);757size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;758size_t const cSize = (job->lastJob) ?759ZSTD_compressEnd (cctx, op, oend-op, ip, lastBlockSize) :760ZSTD_compressContinue(cctx, op, oend-op, ip, lastBlockSize);761if (ZSTD_isError(cSize)) JOB_ERROR(cSize);762lastCBlockSize = cSize;763} }764if (!job->firstJob) {765/* Double check that we don't have an ext-dict, because then our766* repcode invalidation doesn't work.767*/768assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));769}770ZSTD_CCtx_trace(cctx, 0);771772_endJob:773ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);774if (job->prefix.size > 0)775DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);776DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);777/* release resources */778ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);779ZSTDMT_releaseCCtx(job->cctxPool, cctx);780/* report */781ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);782if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);783job->cSize += lastCBlockSize;784job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */785ZSTD_pthread_cond_signal(&job->job_cond);786ZSTD_pthread_mutex_unlock(&job->job_mutex);787}788789790/* ------------------------------------------ */791/* ===== Multi-threaded compression ===== */792/* ------------------------------------------ */793794typedef struct {795range_t prefix; /* read-only non-owned prefix buffer */796buffer_t buffer;797size_t filled;798} inBuff_t;799800typedef struct {801BYTE* buffer; /* The round input buffer. All jobs get references802* to pieces of the buffer. ZSTDMT_tryGetInputRange()803* handles handing out job input buffers, and makes804* sure it doesn't overlap with any pieces still in use.805*/806size_t capacity; /* The capacity of buffer. */807size_t pos; /* The position of the current inBuff in the round808* buffer. Updated past the end if the inBuff once809* the inBuff is sent to the worker thread.810* pos <= capacity.811*/812} roundBuff_t;813814static const roundBuff_t kNullRoundBuff = {NULL, 0, 0};815816#define RSYNC_LENGTH 32817/* Don't create chunks smaller than the zstd block size.818* This stops us from regressing compression ratio too much,819* and ensures our output fits in ZSTD_compressBound().820*821* If this is shrunk < ZSTD_BLOCKSIZELOG_MIN then822* ZSTD_COMPRESSBOUND() will need to be updated.823*/824#define RSYNC_MIN_BLOCK_LOG ZSTD_BLOCKSIZELOG_MAX825#define RSYNC_MIN_BLOCK_SIZE (1<<RSYNC_MIN_BLOCK_LOG)826827typedef struct {828U64 hash;829U64 hitMask;830U64 primePower;831} rsyncState_t;832833struct ZSTDMT_CCtx_s {834POOL_ctx* factory;835ZSTDMT_jobDescription* jobs;836ZSTDMT_bufferPool* bufPool;837ZSTDMT_CCtxPool* cctxPool;838ZSTDMT_seqPool* seqPool;839ZSTD_CCtx_params params;840size_t targetSectionSize;841size_t targetPrefixSize;842int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */843inBuff_t inBuff;844roundBuff_t roundBuff;845serialState_t serial;846rsyncState_t rsync;847unsigned jobIDMask;848unsigned doneJobID;849unsigned nextJobID;850unsigned frameEnded;851unsigned allJobsCompleted;852unsigned long long frameContentSize;853unsigned long long consumed;854unsigned long long produced;855ZSTD_customMem cMem;856ZSTD_CDict* cdictLocal;857const ZSTD_CDict* cdict;858unsigned providedFactory: 1;859};860861static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)862{863U32 jobNb;864if (jobTable == NULL) return;865for (jobNb=0; jobNb<nbJobs; jobNb++) {866ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);867ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);868}869ZSTD_customFree(jobTable, cMem);870}871872/* ZSTDMT_allocJobsTable()873* allocate and init a job table.874* update *nbJobsPtr to next power of 2 value, as size of table */875static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)876{877U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;878U32 const nbJobs = 1 << nbJobsLog2;879U32 jobNb;880ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)881ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);882int initError = 0;883if (jobTable==NULL) return NULL;884*nbJobsPtr = nbJobs;885for (jobNb=0; jobNb<nbJobs; jobNb++) {886initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);887initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);888}889if (initError != 0) {890ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);891return NULL;892}893return jobTable;894}895896static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {897U32 nbJobs = nbWorkers + 2;898if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */899ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);900mtctx->jobIDMask = 0;901mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);902if (mtctx->jobs==NULL) return ERROR(memory_allocation);903assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */904mtctx->jobIDMask = nbJobs - 1;905}906return 0;907}908909910/* ZSTDMT_CCtxParam_setNbWorkers():911* Internal use only */912static size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)913{914return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);915}916917MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)918{919ZSTDMT_CCtx* mtctx;920U32 nbJobs = nbWorkers + 2;921int initError;922DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);923924if (nbWorkers < 1) return NULL;925nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);926if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))927/* invalid custom allocator */928return NULL;929930mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);931if (!mtctx) return NULL;932ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);933mtctx->cMem = cMem;934mtctx->allJobsCompleted = 1;935if (pool != NULL) {936mtctx->factory = pool;937mtctx->providedFactory = 1;938}939else {940mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);941mtctx->providedFactory = 0;942}943mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);944assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */945mtctx->jobIDMask = nbJobs - 1;946mtctx->bufPool = ZSTDMT_createBufferPool(BUF_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);947mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);948mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);949initError = ZSTDMT_serialState_init(&mtctx->serial);950mtctx->roundBuff = kNullRoundBuff;951if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {952ZSTDMT_freeCCtx(mtctx);953return NULL;954}955DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);956return mtctx;957}958959ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)960{961#ifdef ZSTD_MULTITHREAD962return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);963#else964(void)nbWorkers;965(void)cMem;966(void)pool;967return NULL;968#endif969}970971972/* ZSTDMT_releaseAllJobResources() :973* note : ensure all workers are killed first ! */974static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)975{976unsigned jobID;977DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");978for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {979/* Copy the mutex/cond out */980ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;981ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;982983DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);984ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);985986/* Clear the job description, but keep the mutex/cond */987ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));988mtctx->jobs[jobID].job_mutex = mutex;989mtctx->jobs[jobID].job_cond = cond;990}991mtctx->inBuff.buffer = g_nullBuffer;992mtctx->inBuff.filled = 0;993mtctx->allJobsCompleted = 1;994}995996static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)997{998DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");999while (mtctx->doneJobID < mtctx->nextJobID) {1000unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;1001ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);1002while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {1003DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */1004ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);1005}1006ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);1007mtctx->doneJobID++;1008}1009}10101011size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)1012{1013if (mtctx==NULL) return 0; /* compatible with free on NULL */1014if (!mtctx->providedFactory)1015POOL_free(mtctx->factory); /* stop and free worker threads */1016ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */1017ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);1018ZSTDMT_freeBufferPool(mtctx->bufPool);1019ZSTDMT_freeCCtxPool(mtctx->cctxPool);1020ZSTDMT_freeSeqPool(mtctx->seqPool);1021ZSTDMT_serialState_free(&mtctx->serial);1022ZSTD_freeCDict(mtctx->cdictLocal);1023if (mtctx->roundBuff.buffer)1024ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);1025ZSTD_customFree(mtctx, mtctx->cMem);1026return 0;1027}10281029size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)1030{1031if (mtctx == NULL) return 0; /* supports sizeof NULL */1032return sizeof(*mtctx)1033+ POOL_sizeof(mtctx->factory)1034+ ZSTDMT_sizeof_bufferPool(mtctx->bufPool)1035+ (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)1036+ ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)1037+ ZSTDMT_sizeof_seqPool(mtctx->seqPool)1038+ ZSTD_sizeof_CDict(mtctx->cdictLocal)1039+ mtctx->roundBuff.capacity;1040}104110421043/* ZSTDMT_resize() :1044* @return : error code if fails, 0 on success */1045static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)1046{1047if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);1048FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");1049mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, BUF_POOL_MAX_NB_BUFFERS(nbWorkers));1050if (mtctx->bufPool == NULL) return ERROR(memory_allocation);1051mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);1052if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);1053mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);1054if (mtctx->seqPool == NULL) return ERROR(memory_allocation);1055ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);1056return 0;1057}105810591060/*! ZSTDMT_updateCParams_whileCompressing() :1061* Updates a selected set of compression parameters, remaining compatible with currently active frame.1062* New parameters will be applied to next compression job. */1063void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)1064{1065U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */1066int const compressionLevel = cctxParams->compressionLevel;1067DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",1068compressionLevel);1069mtctx->params.compressionLevel = compressionLevel;1070{ ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);1071cParams.windowLog = saved_wlog;1072mtctx->params.cParams = cParams;1073}1074}10751076/* ZSTDMT_getFrameProgression():1077* tells how much data has been consumed (input) and produced (output) for current frame.1078* able to count progression inside worker threads.1079* Note : mutex will be acquired during statistics collection inside workers. */1080ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)1081{1082ZSTD_frameProgression fps;1083DEBUGLOG(5, "ZSTDMT_getFrameProgression");1084fps.ingested = mtctx->consumed + mtctx->inBuff.filled;1085fps.consumed = mtctx->consumed;1086fps.produced = fps.flushed = mtctx->produced;1087fps.currentJobID = mtctx->nextJobID;1088fps.nbActiveWorkers = 0;1089{ unsigned jobNb;1090unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);1091DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",1092mtctx->doneJobID, lastJobNb, mtctx->jobReady)1093for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {1094unsigned const wJobID = jobNb & mtctx->jobIDMask;1095ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];1096ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);1097{ size_t const cResult = jobPtr->cSize;1098size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;1099size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;1100assert(flushed <= produced);1101fps.ingested += jobPtr->src.size;1102fps.consumed += jobPtr->consumed;1103fps.produced += produced;1104fps.flushed += flushed;1105fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);1106}1107ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1108}1109}1110return fps;1111}111211131114size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)1115{1116size_t toFlush;1117unsigned const jobID = mtctx->doneJobID;1118assert(jobID <= mtctx->nextJobID);1119if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */11201121/* look into oldest non-fully-flushed job */1122{ unsigned const wJobID = jobID & mtctx->jobIDMask;1123ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];1124ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);1125{ size_t const cResult = jobPtr->cSize;1126size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;1127size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;1128assert(flushed <= produced);1129assert(jobPtr->consumed <= jobPtr->src.size);1130toFlush = produced - flushed;1131/* if toFlush==0, nothing is available to flush.1132* However, jobID is expected to still be active:1133* if jobID was already completed and fully flushed,1134* ZSTDMT_flushProduced() should have already moved onto next job.1135* Therefore, some input has not yet been consumed. */1136if (toFlush==0) {1137assert(jobPtr->consumed < jobPtr->src.size);1138}1139}1140ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1141}11421143return toFlush;1144}114511461147/* ------------------------------------------ */1148/* ===== Multi-threaded compression ===== */1149/* ------------------------------------------ */11501151static unsigned ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params* params)1152{1153unsigned jobLog;1154if (params->ldmParams.enableLdm == ZSTD_ps_enable) {1155/* In Long Range Mode, the windowLog is typically oversized.1156* In which case, it's preferable to determine the jobSize1157* based on cycleLog instead. */1158jobLog = MAX(21, ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy) + 3);1159} else {1160jobLog = MAX(20, params->cParams.windowLog + 2);1161}1162return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);1163}11641165static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)1166{1167switch(strat)1168{1169case ZSTD_btultra2:1170return 9;1171case ZSTD_btultra:1172case ZSTD_btopt:1173return 8;1174case ZSTD_btlazy2:1175case ZSTD_lazy2:1176return 7;1177case ZSTD_lazy:1178case ZSTD_greedy:1179case ZSTD_dfast:1180case ZSTD_fast:1181default:;1182}1183return 6;1184}11851186static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)1187{1188assert(0 <= ovlog && ovlog <= 9);1189if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);1190return ovlog;1191}11921193static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)1194{1195int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);1196int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);1197assert(0 <= overlapRLog && overlapRLog <= 8);1198if (params->ldmParams.enableLdm == ZSTD_ps_enable) {1199/* In Long Range Mode, the windowLog is typically oversized.1200* In which case, it's preferable to determine the jobSize1201* based on chainLog instead.1202* Then, ovLog becomes a fraction of the jobSize, rather than windowSize */1203ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)1204- overlapRLog;1205}1206assert(0 <= ovLog && ovLog <= ZSTD_WINDOWLOG_MAX);1207DEBUGLOG(4, "overlapLog : %i", params->overlapLog);1208DEBUGLOG(4, "overlap size : %i", 1 << ovLog);1209return (ovLog==0) ? 0 : (size_t)1 << ovLog;1210}12111212/* ====================================== */1213/* ======= Streaming API ======= */1214/* ====================================== */12151216size_t ZSTDMT_initCStream_internal(1217ZSTDMT_CCtx* mtctx,1218const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,1219const ZSTD_CDict* cdict, ZSTD_CCtx_params params,1220unsigned long long pledgedSrcSize)1221{1222DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",1223(U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);12241225/* params supposed partially fully validated at this point */1226assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));1227assert(!((dict) && (cdict))); /* either dict or cdict, not both */12281229/* init */1230if (params.nbWorkers != mtctx->params.nbWorkers)1231FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, params.nbWorkers) , "");12321233if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;1234if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;12351236DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);12371238if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */1239ZSTDMT_waitForAllJobsCompleted(mtctx);1240ZSTDMT_releaseAllJobResources(mtctx);1241mtctx->allJobsCompleted = 1;1242}12431244mtctx->params = params;1245mtctx->frameContentSize = pledgedSrcSize;1246if (dict) {1247ZSTD_freeCDict(mtctx->cdictLocal);1248mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,1249ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */1250params.cParams, mtctx->cMem);1251mtctx->cdict = mtctx->cdictLocal;1252if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);1253} else {1254ZSTD_freeCDict(mtctx->cdictLocal);1255mtctx->cdictLocal = NULL;1256mtctx->cdict = cdict;1257}12581259mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(¶ms);1260DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));1261mtctx->targetSectionSize = params.jobSize;1262if (mtctx->targetSectionSize == 0) {1263mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(¶ms);1264}1265assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);12661267if (params.rsyncable) {1268/* Aim for the targetsectionSize as the average job size. */1269U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);1270U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);1271/* We refuse to create jobs < RSYNC_MIN_BLOCK_SIZE bytes, so make sure our1272* expected job size is at least 4x larger. */1273assert(rsyncBits >= RSYNC_MIN_BLOCK_LOG + 2);1274DEBUGLOG(4, "rsyncLog = %u", rsyncBits);1275mtctx->rsync.hash = 0;1276mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;1277mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);1278}1279if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */1280DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);1281DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));1282ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));1283{1284/* If ldm is enabled we need windowSize space. */1285size_t const windowSize = mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable ? (1U << mtctx->params.cParams.windowLog) : 0;1286/* Two buffers of slack, plus extra space for the overlap1287* This is the minimum slack that LDM works with. One extra because1288* flush might waste up to targetSectionSize-1 bytes. Another extra1289* for the overlap (if > 0), then one to fill which doesn't overlap1290* with the LDM window.1291*/1292size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);1293size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;1294/* Compute the total size, and always have enough slack */1295size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);1296size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;1297size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;1298if (mtctx->roundBuff.capacity < capacity) {1299if (mtctx->roundBuff.buffer)1300ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);1301mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);1302if (mtctx->roundBuff.buffer == NULL) {1303mtctx->roundBuff.capacity = 0;1304return ERROR(memory_allocation);1305}1306mtctx->roundBuff.capacity = capacity;1307}1308}1309DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));1310mtctx->roundBuff.pos = 0;1311mtctx->inBuff.buffer = g_nullBuffer;1312mtctx->inBuff.filled = 0;1313mtctx->inBuff.prefix = kNullRange;1314mtctx->doneJobID = 0;1315mtctx->nextJobID = 0;1316mtctx->frameEnded = 0;1317mtctx->allJobsCompleted = 0;1318mtctx->consumed = 0;1319mtctx->produced = 0;1320if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize,1321dict, dictSize, dictContentType))1322return ERROR(memory_allocation);1323return 0;1324}132513261327/* ZSTDMT_writeLastEmptyBlock()1328* Write a single empty block with an end-of-frame to finish a frame.1329* Job must be created from streaming variant.1330* This function is always successful if expected conditions are fulfilled.1331*/1332static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)1333{1334assert(job->lastJob == 1);1335assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */1336assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */1337assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */1338job->dstBuff = ZSTDMT_getBuffer(job->bufPool);1339if (job->dstBuff.start == NULL) {1340job->cSize = ERROR(memory_allocation);1341return;1342}1343assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */1344job->src = kNullRange;1345job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);1346assert(!ZSTD_isError(job->cSize));1347assert(job->consumed == 0);1348}13491350static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)1351{1352unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;1353int const endFrame = (endOp == ZSTD_e_end);13541355if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {1356DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");1357assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));1358return 0;1359}13601361if (!mtctx->jobReady) {1362BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;1363DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",1364mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);1365mtctx->jobs[jobID].src.start = src;1366mtctx->jobs[jobID].src.size = srcSize;1367assert(mtctx->inBuff.filled >= srcSize);1368mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;1369mtctx->jobs[jobID].consumed = 0;1370mtctx->jobs[jobID].cSize = 0;1371mtctx->jobs[jobID].params = mtctx->params;1372mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;1373mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;1374mtctx->jobs[jobID].dstBuff = g_nullBuffer;1375mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;1376mtctx->jobs[jobID].bufPool = mtctx->bufPool;1377mtctx->jobs[jobID].seqPool = mtctx->seqPool;1378mtctx->jobs[jobID].serial = &mtctx->serial;1379mtctx->jobs[jobID].jobID = mtctx->nextJobID;1380mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);1381mtctx->jobs[jobID].lastJob = endFrame;1382mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);1383mtctx->jobs[jobID].dstFlushed = 0;13841385/* Update the round buffer pos and clear the input buffer to be reset */1386mtctx->roundBuff.pos += srcSize;1387mtctx->inBuff.buffer = g_nullBuffer;1388mtctx->inBuff.filled = 0;1389/* Set the prefix */1390if (!endFrame) {1391size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);1392mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;1393mtctx->inBuff.prefix.size = newPrefixSize;1394} else { /* endFrame==1 => no need for another input buffer */1395mtctx->inBuff.prefix = kNullRange;1396mtctx->frameEnded = endFrame;1397if (mtctx->nextJobID == 0) {1398/* single job exception : checksum is already calculated directly within worker thread */1399mtctx->params.fParams.checksumFlag = 0;1400} }14011402if ( (srcSize == 0)1403&& (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {1404DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");1405assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */1406ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);1407mtctx->nextJobID++;1408return 0;1409}1410}14111412DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",1413mtctx->nextJobID,1414(U32)mtctx->jobs[jobID].src.size,1415mtctx->jobs[jobID].lastJob,1416mtctx->nextJobID,1417jobID);1418if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {1419mtctx->nextJobID++;1420mtctx->jobReady = 0;1421} else {1422DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);1423mtctx->jobReady = 1;1424}1425return 0;1426}142714281429/*! ZSTDMT_flushProduced() :1430* flush whatever data has been produced but not yet flushed in current job.1431* move to next job if current one is fully flushed.1432* `output` : `pos` will be updated with amount of data flushed .1433* `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .1434* @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */1435static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)1436{1437unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;1438DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",1439blockToFlush, mtctx->doneJobID, mtctx->nextJobID);1440assert(output->size >= output->pos);14411442ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);1443if ( blockToFlush1444&& (mtctx->doneJobID < mtctx->nextJobID) ) {1445assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);1446while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */1447if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {1448DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",1449mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);1450break;1451}1452DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",1453mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);1454ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */1455} }14561457/* try to flush something */1458{ size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */1459size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */1460size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */1461ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1462if (ZSTD_isError(cSize)) {1463DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",1464mtctx->doneJobID, ZSTD_getErrorName(cSize));1465ZSTDMT_waitForAllJobsCompleted(mtctx);1466ZSTDMT_releaseAllJobResources(mtctx);1467return cSize;1468}1469/* add frame checksum if necessary (can only happen once) */1470assert(srcConsumed <= srcSize);1471if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */1472&& mtctx->jobs[wJobID].frameChecksumNeeded ) {1473U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);1474DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);1475MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);1476cSize += 4;1477mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */1478mtctx->jobs[wJobID].frameChecksumNeeded = 0;1479}14801481if (cSize > 0) { /* compression is ongoing or completed */1482size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);1483DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",1484(U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);1485assert(mtctx->doneJobID < mtctx->nextJobID);1486assert(cSize >= mtctx->jobs[wJobID].dstFlushed);1487assert(mtctx->jobs[wJobID].dstBuff.start != NULL);1488if (toFlush > 0) {1489ZSTD_memcpy((char*)output->dst + output->pos,1490(const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,1491toFlush);1492}1493output->pos += toFlush;1494mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */14951496if ( (srcConsumed == srcSize) /* job is completed */1497&& (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */1498DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",1499mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);1500ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);1501DEBUGLOG(5, "dstBuffer released");1502mtctx->jobs[wJobID].dstBuff = g_nullBuffer;1503mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */1504mtctx->consumed += srcSize;1505mtctx->produced += cSize;1506mtctx->doneJobID++;1507} }15081509/* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */1510if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);1511if (srcSize > srcConsumed) return 1; /* current job not completely compressed */1512}1513if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */1514if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */1515if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */1516mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */1517if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */1518return 0; /* internal buffers fully flushed */1519}15201521/**1522* Returns the range of data used by the earliest job that is not yet complete.1523* If the data of the first job is broken up into two segments, we cover both1524* sections.1525*/1526static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)1527{1528unsigned const firstJobID = mtctx->doneJobID;1529unsigned const lastJobID = mtctx->nextJobID;1530unsigned jobID;15311532for (jobID = firstJobID; jobID < lastJobID; ++jobID) {1533unsigned const wJobID = jobID & mtctx->jobIDMask;1534size_t consumed;15351536ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);1537consumed = mtctx->jobs[wJobID].consumed;1538ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);15391540if (consumed < mtctx->jobs[wJobID].src.size) {1541range_t range = mtctx->jobs[wJobID].prefix;1542if (range.size == 0) {1543/* Empty prefix */1544range = mtctx->jobs[wJobID].src;1545}1546/* Job source in multiple segments not supported yet */1547assert(range.start <= mtctx->jobs[wJobID].src.start);1548return range;1549}1550}1551return kNullRange;1552}15531554/**1555* Returns non-zero iff buffer and range overlap.1556*/1557static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)1558{1559BYTE const* const bufferStart = (BYTE const*)buffer.start;1560BYTE const* const rangeStart = (BYTE const*)range.start;15611562if (rangeStart == NULL || bufferStart == NULL)1563return 0;15641565{1566BYTE const* const bufferEnd = bufferStart + buffer.capacity;1567BYTE const* const rangeEnd = rangeStart + range.size;15681569/* Empty ranges cannot overlap */1570if (bufferStart == bufferEnd || rangeStart == rangeEnd)1571return 0;15721573return bufferStart < rangeEnd && rangeStart < bufferEnd;1574}1575}15761577static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)1578{1579range_t extDict;1580range_t prefix;15811582DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");1583extDict.start = window.dictBase + window.lowLimit;1584extDict.size = window.dictLimit - window.lowLimit;15851586prefix.start = window.base + window.dictLimit;1587prefix.size = window.nextSrc - (window.base + window.dictLimit);1588DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",1589(size_t)extDict.start,1590(size_t)extDict.start + extDict.size);1591DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",1592(size_t)prefix.start,1593(size_t)prefix.start + prefix.size);15941595return ZSTDMT_isOverlapped(buffer, extDict)1596|| ZSTDMT_isOverlapped(buffer, prefix);1597}15981599static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)1600{1601if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) {1602ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;1603DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");1604DEBUGLOG(5, "source [0x%zx, 0x%zx)",1605(size_t)buffer.start,1606(size_t)buffer.start + buffer.capacity);1607ZSTD_PTHREAD_MUTEX_LOCK(mutex);1608while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {1609DEBUGLOG(5, "Waiting for LDM to finish...");1610ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);1611}1612DEBUGLOG(6, "Done waiting for LDM to finish");1613ZSTD_pthread_mutex_unlock(mutex);1614}1615}16161617/**1618* Attempts to set the inBuff to the next section to fill.1619* If any part of the new section is still in use we give up.1620* Returns non-zero if the buffer is filled.1621*/1622static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)1623{1624range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);1625size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;1626size_t const target = mtctx->targetSectionSize;1627buffer_t buffer;16281629DEBUGLOG(5, "ZSTDMT_tryGetInputRange");1630assert(mtctx->inBuff.buffer.start == NULL);1631assert(mtctx->roundBuff.capacity >= target);16321633if (spaceLeft < target) {1634/* ZSTD_invalidateRepCodes() doesn't work for extDict variants.1635* Simply copy the prefix to the beginning in that case.1636*/1637BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;1638size_t const prefixSize = mtctx->inBuff.prefix.size;16391640buffer.start = start;1641buffer.capacity = prefixSize;1642if (ZSTDMT_isOverlapped(buffer, inUse)) {1643DEBUGLOG(5, "Waiting for buffer...");1644return 0;1645}1646ZSTDMT_waitForLdmComplete(mtctx, buffer);1647ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);1648mtctx->inBuff.prefix.start = start;1649mtctx->roundBuff.pos = prefixSize;1650}1651buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;1652buffer.capacity = target;16531654if (ZSTDMT_isOverlapped(buffer, inUse)) {1655DEBUGLOG(5, "Waiting for buffer...");1656return 0;1657}1658assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));16591660ZSTDMT_waitForLdmComplete(mtctx, buffer);16611662DEBUGLOG(5, "Using prefix range [%zx, %zx)",1663(size_t)mtctx->inBuff.prefix.start,1664(size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);1665DEBUGLOG(5, "Using source range [%zx, %zx)",1666(size_t)buffer.start,1667(size_t)buffer.start + buffer.capacity);166816691670mtctx->inBuff.buffer = buffer;1671mtctx->inBuff.filled = 0;1672assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);1673return 1;1674}16751676typedef struct {1677size_t toLoad; /* The number of bytes to load from the input. */1678int flush; /* Boolean declaring if we must flush because we found a synchronization point. */1679} syncPoint_t;16801681/**1682* Searches through the input for a synchronization point. If one is found, we1683* will instruct the caller to flush, and return the number of bytes to load.1684* Otherwise, we will load as many bytes as possible and instruct the caller1685* to continue as normal.1686*/1687static syncPoint_t1688findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)1689{1690BYTE const* const istart = (BYTE const*)input.src + input.pos;1691U64 const primePower = mtctx->rsync.primePower;1692U64 const hitMask = mtctx->rsync.hitMask;16931694syncPoint_t syncPoint;1695U64 hash;1696BYTE const* prev;1697size_t pos;16981699syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);1700syncPoint.flush = 0;1701if (!mtctx->params.rsyncable)1702/* Rsync is disabled. */1703return syncPoint;1704if (mtctx->inBuff.filled + input.size - input.pos < RSYNC_MIN_BLOCK_SIZE)1705/* We don't emit synchronization points if it would produce too small blocks.1706* We don't have enough input to find a synchronization point, so don't look.1707*/1708return syncPoint;1709if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)1710/* Not enough to compute the hash.1711* We will miss any synchronization points in this RSYNC_LENGTH byte1712* window. However, since it depends only in the internal buffers, if the1713* state is already synchronized, we will remain synchronized.1714* Additionally, the probability that we miss a synchronization point is1715* low: RSYNC_LENGTH / targetSectionSize.1716*/1717return syncPoint;1718/* Initialize the loop variables. */1719if (mtctx->inBuff.filled < RSYNC_MIN_BLOCK_SIZE) {1720/* We don't need to scan the first RSYNC_MIN_BLOCK_SIZE positions1721* because they can't possibly be a sync point. So we can start1722* part way through the input buffer.1723*/1724pos = RSYNC_MIN_BLOCK_SIZE - mtctx->inBuff.filled;1725if (pos >= RSYNC_LENGTH) {1726prev = istart + pos - RSYNC_LENGTH;1727hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);1728} else {1729assert(mtctx->inBuff.filled >= RSYNC_LENGTH);1730prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;1731hash = ZSTD_rollingHash_compute(prev + pos, (RSYNC_LENGTH - pos));1732hash = ZSTD_rollingHash_append(hash, istart, pos);1733}1734} else {1735/* We have enough bytes buffered to initialize the hash,1736* and are have processed enough bytes to find a sync point.1737* Start scanning at the beginning of the input.1738*/1739assert(mtctx->inBuff.filled >= RSYNC_MIN_BLOCK_SIZE);1740assert(RSYNC_MIN_BLOCK_SIZE >= RSYNC_LENGTH);1741pos = 0;1742prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;1743hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);1744if ((hash & hitMask) == hitMask) {1745/* We're already at a sync point so don't load any more until1746* we're able to flush this sync point.1747* This likely happened because the job table was full so we1748* couldn't add our job.1749*/1750syncPoint.toLoad = 0;1751syncPoint.flush = 1;1752return syncPoint;1753}1754}1755/* Starting with the hash of the previous RSYNC_LENGTH bytes, roll1756* through the input. If we hit a synchronization point, then cut the1757* job off, and tell the compressor to flush the job. Otherwise, load1758* all the bytes and continue as normal.1759* If we go too long without a synchronization point (targetSectionSize)1760* then a block will be emitted anyways, but this is okay, since if we1761* are already synchronized we will remain synchronized.1762*/1763for (; pos < syncPoint.toLoad; ++pos) {1764BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];1765assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);1766hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);1767assert(mtctx->inBuff.filled + pos >= RSYNC_MIN_BLOCK_SIZE);1768if ((hash & hitMask) == hitMask) {1769syncPoint.toLoad = pos + 1;1770syncPoint.flush = 1;1771break;1772}1773}1774return syncPoint;1775}17761777size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)1778{1779size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;1780if (hintInSize==0) hintInSize = mtctx->targetSectionSize;1781return hintInSize;1782}17831784/** ZSTDMT_compressStream_generic() :1785* internal use only - exposed to be invoked from zstd_compress.c1786* assumption : output and input are valid (pos <= size)1787* @return : minimum amount of data remaining to flush, 0 if none */1788size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,1789ZSTD_outBuffer* output,1790ZSTD_inBuffer* input,1791ZSTD_EndDirective endOp)1792{1793unsigned forwardInputProgress = 0;1794DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",1795(U32)endOp, (U32)(input->size - input->pos));1796assert(output->pos <= output->size);1797assert(input->pos <= input->size);17981799if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {1800/* current frame being ended. Only flush/end are allowed */1801return ERROR(stage_wrong);1802}18031804/* fill input buffer */1805if ( (!mtctx->jobReady)1806&& (input->size > input->pos) ) { /* support NULL input */1807if (mtctx->inBuff.buffer.start == NULL) {1808assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */1809if (!ZSTDMT_tryGetInputRange(mtctx)) {1810/* It is only possible for this operation to fail if there are1811* still compression jobs ongoing.1812*/1813DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");1814assert(mtctx->doneJobID != mtctx->nextJobID);1815} else1816DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);1817}1818if (mtctx->inBuff.buffer.start != NULL) {1819syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);1820if (syncPoint.flush && endOp == ZSTD_e_continue) {1821endOp = ZSTD_e_flush;1822}1823assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);1824DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",1825(U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);1826ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);1827input->pos += syncPoint.toLoad;1828mtctx->inBuff.filled += syncPoint.toLoad;1829forwardInputProgress = syncPoint.toLoad>0;1830}1831}1832if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {1833/* Can't end yet because the input is not fully consumed.1834* We are in one of these cases:1835* - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.1836* - We filled the input buffer: flush this job but don't end the frame.1837* - We hit a synchronization point: flush this job but don't end the frame.1838*/1839assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);1840endOp = ZSTD_e_flush;1841}18421843if ( (mtctx->jobReady)1844|| (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */1845|| ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */1846|| ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */1847size_t const jobSize = mtctx->inBuff.filled;1848assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);1849FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");1850}18511852/* check for potential compressed data ready to be flushed */1853{ size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */1854if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */1855DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);1856return remainingToFlush;1857}1858}185918601861