Path: blob/master/Utilities/cmzstd/lib/compress/zstdmt_compress.c
5020 views
/*1* Copyright (c) Meta Platforms, Inc. and affiliates.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/* ====== Dependencies ====== */18#include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customCalloc, ZSTD_customFree */19#include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset, INT_MAX, UINT_MAX */20#include "../common/mem.h" /* MEM_STATIC */21#include "../common/pool.h" /* threadpool */22#include "../common/threading.h" /* mutex */23#include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */24#include "zstd_ldm.h"25#include "zstdmt_compress.h"2627/* Guards code to support resizing the SeqPool.28* We will want to resize the SeqPool to save memory in the future.29* Until then, comment the code out since it is unused.30*/31#define ZSTD_RESIZE_SEQPOOL 03233/* ====== Debug ====== */34#if defined(DEBUGLEVEL) && (DEBUGLEVEL>=2) \35&& !defined(_MSC_VER) \36&& !defined(__MINGW32__)3738# include <stdio.h>39# include <unistd.h>40# include <sys/times.h>4142# define DEBUG_PRINTHEX(l,p,n) \43do { \44unsigned debug_u; \45for (debug_u=0; debug_u<(n); debug_u++) \46RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \47RAWLOG(l, " \n"); \48} while (0)4950static unsigned long long GetCurrentClockTimeMicroseconds(void)51{52static clock_t _ticksPerSecond = 0;53if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);5455{ struct tms junk; clock_t newTicks = (clock_t) times(&junk);56return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);57} }5859#define MUTEX_WAIT_TIME_DLEVEL 660#define ZSTD_PTHREAD_MUTEX_LOCK(mutex) \61do { \62if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) { \63unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \64ZSTD_pthread_mutex_lock(mutex); \65{ unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \66unsigned long long const elapsedTime = (afterTime-beforeTime); \67if (elapsedTime > 1000) { \68/* or whatever threshold you like; I'm using 1 millisecond here */ \69DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, \70"Thread took %llu microseconds to acquire mutex %s \n", \71elapsedTime, #mutex); \72} } \73} else { \74ZSTD_pthread_mutex_lock(mutex); \75} \76} while (0)7778#else7980# define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)81# define DEBUG_PRINTHEX(l,p,n) do { } while (0)8283#endif848586/* ===== Buffer Pool ===== */87/* a single Buffer Pool can be invoked from multiple threads in parallel */8889typedef struct buffer_s {90void* start;91size_t capacity;92} Buffer;9394static const Buffer g_nullBuffer = { NULL, 0 };9596typedef struct ZSTDMT_bufferPool_s {97ZSTD_pthread_mutex_t poolMutex;98size_t bufferSize;99unsigned totalBuffers;100unsigned nbBuffers;101ZSTD_customMem cMem;102Buffer* buffers;103} ZSTDMT_bufferPool;104105static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)106{107DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);108if (!bufPool) return; /* compatibility with free on NULL */109if (bufPool->buffers) {110unsigned u;111for (u=0; u<bufPool->totalBuffers; u++) {112DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->buffers[u].start);113ZSTD_customFree(bufPool->buffers[u].start, bufPool->cMem);114}115ZSTD_customFree(bufPool->buffers, bufPool->cMem);116}117ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);118ZSTD_customFree(bufPool, bufPool->cMem);119}120121static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned maxNbBuffers, ZSTD_customMem cMem)122{123ZSTDMT_bufferPool* const bufPool =124(ZSTDMT_bufferPool*)ZSTD_customCalloc(sizeof(ZSTDMT_bufferPool), cMem);125if (bufPool==NULL) return NULL;126if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {127ZSTD_customFree(bufPool, cMem);128return NULL;129}130bufPool->buffers = (Buffer*)ZSTD_customCalloc(maxNbBuffers * sizeof(Buffer), cMem);131if (bufPool->buffers==NULL) {132ZSTDMT_freeBufferPool(bufPool);133return NULL;134}135bufPool->bufferSize = 64 KB;136bufPool->totalBuffers = maxNbBuffers;137bufPool->nbBuffers = 0;138bufPool->cMem = cMem;139return bufPool;140}141142/* only works at initialization, not during compression */143static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)144{145size_t const poolSize = sizeof(*bufPool);146size_t const arraySize = bufPool->totalBuffers * sizeof(Buffer);147unsigned u;148size_t totalBufferSize = 0;149ZSTD_pthread_mutex_lock(&bufPool->poolMutex);150for (u=0; u<bufPool->totalBuffers; u++)151totalBufferSize += bufPool->buffers[u].capacity;152ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);153154return poolSize + arraySize + totalBufferSize;155}156157/* ZSTDMT_setBufferSize() :158* all future buffers provided by this buffer pool will have _at least_ this size159* note : it's better for all buffers to have same size,160* as they become freely interchangeable, reducing malloc/free usages and memory fragmentation */161static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* const bufPool, size_t const bSize)162{163ZSTD_pthread_mutex_lock(&bufPool->poolMutex);164DEBUGLOG(4, "ZSTDMT_setBufferSize: bSize = %u", (U32)bSize);165bufPool->bufferSize = bSize;166ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);167}168169170static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, unsigned maxNbBuffers)171{172if (srcBufPool==NULL) return NULL;173if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */174return srcBufPool;175/* need a larger buffer pool */176{ ZSTD_customMem const cMem = srcBufPool->cMem;177size_t const bSize = srcBufPool->bufferSize; /* forward parameters */178ZSTDMT_bufferPool* newBufPool;179ZSTDMT_freeBufferPool(srcBufPool);180newBufPool = ZSTDMT_createBufferPool(maxNbBuffers, cMem);181if (newBufPool==NULL) return newBufPool;182ZSTDMT_setBufferSize(newBufPool, bSize);183return newBufPool;184}185}186187/** ZSTDMT_getBuffer() :188* assumption : bufPool must be valid189* @return : a buffer, with start pointer and size190* note: allocation may fail, in this case, start==NULL and size==0 */191static Buffer ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)192{193size_t const bSize = bufPool->bufferSize;194DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);195ZSTD_pthread_mutex_lock(&bufPool->poolMutex);196if (bufPool->nbBuffers) { /* try to use an existing buffer */197Buffer const buf = bufPool->buffers[--(bufPool->nbBuffers)];198size_t const availBufferSize = buf.capacity;199bufPool->buffers[bufPool->nbBuffers] = g_nullBuffer;200if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {201/* large enough, but not too much */202DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",203bufPool->nbBuffers, (U32)buf.capacity);204ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);205return buf;206}207/* size conditions not respected : scratch this buffer, create new one */208DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");209ZSTD_customFree(buf.start, bufPool->cMem);210}211ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);212/* create new buffer */213DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");214{ Buffer buffer;215void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);216buffer.start = start; /* note : start can be NULL if malloc fails ! */217buffer.capacity = (start==NULL) ? 0 : bSize;218if (start==NULL) {219DEBUGLOG(5, "ZSTDMT_getBuffer: buffer allocation failure !!");220} else {221DEBUGLOG(5, "ZSTDMT_getBuffer: created buffer of size %u", (U32)bSize);222}223return buffer;224}225}226227#if ZSTD_RESIZE_SEQPOOL228/** ZSTDMT_resizeBuffer() :229* assumption : bufPool must be valid230* @return : a buffer that is at least the buffer pool buffer size.231* If a reallocation happens, the data in the input buffer is copied.232*/233static Buffer ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, Buffer buffer)234{235size_t const bSize = bufPool->bufferSize;236if (buffer.capacity < bSize) {237void* const start = ZSTD_customMalloc(bSize, bufPool->cMem);238Buffer newBuffer;239newBuffer.start = start;240newBuffer.capacity = start == NULL ? 0 : bSize;241if (start != NULL) {242assert(newBuffer.capacity >= buffer.capacity);243ZSTD_memcpy(newBuffer.start, buffer.start, buffer.capacity);244DEBUGLOG(5, "ZSTDMT_resizeBuffer: created buffer of size %u", (U32)bSize);245return newBuffer;246}247DEBUGLOG(5, "ZSTDMT_resizeBuffer: buffer allocation failure !!");248}249return buffer;250}251#endif252253/* store buffer for later re-use, up to pool capacity */254static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, Buffer buf)255{256DEBUGLOG(5, "ZSTDMT_releaseBuffer");257if (buf.start == NULL) return; /* compatible with release on NULL */258ZSTD_pthread_mutex_lock(&bufPool->poolMutex);259if (bufPool->nbBuffers < bufPool->totalBuffers) {260bufPool->buffers[bufPool->nbBuffers++] = buf; /* stored for later use */261DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",262(U32)buf.capacity, (U32)(bufPool->nbBuffers-1));263ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);264return;265}266ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);267/* Reached bufferPool capacity (note: should not happen) */268DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");269ZSTD_customFree(buf.start, bufPool->cMem);270}271272/* We need 2 output buffers per worker since each dstBuff must be flushed after it is released.273* The 3 additional buffers are as follows:274* 1 buffer for input loading275* 1 buffer for "next input" when submitting current one276* 1 buffer stuck in queue */277#define BUF_POOL_MAX_NB_BUFFERS(nbWorkers) (2*(nbWorkers) + 3)278279/* After a worker releases its rawSeqStore, it is immediately ready for reuse.280* So we only need one seq buffer per worker. */281#define SEQ_POOL_MAX_NB_BUFFERS(nbWorkers) (nbWorkers)282283/* ===== Seq Pool Wrapper ====== */284285typedef ZSTDMT_bufferPool ZSTDMT_seqPool;286287static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)288{289return ZSTDMT_sizeof_bufferPool(seqPool);290}291292static RawSeqStore_t bufferToSeq(Buffer buffer)293{294RawSeqStore_t seq = kNullRawSeqStore;295seq.seq = (rawSeq*)buffer.start;296seq.capacity = buffer.capacity / sizeof(rawSeq);297return seq;298}299300static Buffer seqToBuffer(RawSeqStore_t seq)301{302Buffer buffer;303buffer.start = seq.seq;304buffer.capacity = seq.capacity * sizeof(rawSeq);305return buffer;306}307308static RawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)309{310if (seqPool->bufferSize == 0) {311return kNullRawSeqStore;312}313return bufferToSeq(ZSTDMT_getBuffer(seqPool));314}315316#if ZSTD_RESIZE_SEQPOOL317static RawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, RawSeqStore_t seq)318{319return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));320}321#endif322323static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, RawSeqStore_t seq)324{325ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));326}327328static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)329{330ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));331}332333static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)334{335ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(SEQ_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);336if (seqPool == NULL) return NULL;337ZSTDMT_setNbSeq(seqPool, 0);338return seqPool;339}340341static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)342{343ZSTDMT_freeBufferPool(seqPool);344}345346static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)347{348return ZSTDMT_expandBufferPool(pool, SEQ_POOL_MAX_NB_BUFFERS(nbWorkers));349}350351352/* ===== CCtx Pool ===== */353/* a single CCtx Pool can be invoked from multiple threads in parallel */354355typedef struct {356ZSTD_pthread_mutex_t poolMutex;357int totalCCtx;358int availCCtx;359ZSTD_customMem cMem;360ZSTD_CCtx** cctxs;361} ZSTDMT_CCtxPool;362363/* note : all CCtx borrowed from the pool must be reverted back to the pool _before_ freeing the pool */364static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)365{366if (!pool) return;367ZSTD_pthread_mutex_destroy(&pool->poolMutex);368if (pool->cctxs) {369int cid;370for (cid=0; cid<pool->totalCCtx; cid++)371ZSTD_freeCCtx(pool->cctxs[cid]); /* free compatible with NULL */372ZSTD_customFree(pool->cctxs, pool->cMem);373}374ZSTD_customFree(pool, pool->cMem);375}376377/* ZSTDMT_createCCtxPool() :378* implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */379static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,380ZSTD_customMem cMem)381{382ZSTDMT_CCtxPool* const cctxPool =383(ZSTDMT_CCtxPool*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtxPool), cMem);384assert(nbWorkers > 0);385if (!cctxPool) return NULL;386if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {387ZSTD_customFree(cctxPool, cMem);388return NULL;389}390cctxPool->totalCCtx = nbWorkers;391cctxPool->cctxs = (ZSTD_CCtx**)ZSTD_customCalloc(nbWorkers * sizeof(ZSTD_CCtx*), cMem);392if (!cctxPool->cctxs) {393ZSTDMT_freeCCtxPool(cctxPool);394return NULL;395}396cctxPool->cMem = cMem;397cctxPool->cctxs[0] = ZSTD_createCCtx_advanced(cMem);398if (!cctxPool->cctxs[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }399cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */400DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);401return cctxPool;402}403404static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,405int nbWorkers)406{407if (srcPool==NULL) return NULL;408if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */409/* need a larger cctx pool */410{ ZSTD_customMem const cMem = srcPool->cMem;411ZSTDMT_freeCCtxPool(srcPool);412return ZSTDMT_createCCtxPool(nbWorkers, cMem);413}414}415416/* only works during initialization phase, not during compression */417static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)418{419ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);420{ unsigned const nbWorkers = cctxPool->totalCCtx;421size_t const poolSize = sizeof(*cctxPool);422size_t const arraySize = cctxPool->totalCCtx * sizeof(ZSTD_CCtx*);423size_t totalCCtxSize = 0;424unsigned u;425for (u=0; u<nbWorkers; u++) {426totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctxs[u]);427}428ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);429assert(nbWorkers > 0);430return poolSize + arraySize + totalCCtxSize;431}432}433434static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)435{436DEBUGLOG(5, "ZSTDMT_getCCtx");437ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);438if (cctxPool->availCCtx) {439cctxPool->availCCtx--;440{ ZSTD_CCtx* const cctx = cctxPool->cctxs[cctxPool->availCCtx];441ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);442return cctx;443} }444ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);445DEBUGLOG(5, "create one more CCtx");446return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */447}448449static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)450{451if (cctx==NULL) return; /* compatibility with release on NULL */452ZSTD_pthread_mutex_lock(&pool->poolMutex);453if (pool->availCCtx < pool->totalCCtx)454pool->cctxs[pool->availCCtx++] = cctx;455else {456/* pool overflow : should not happen, since totalCCtx==nbWorkers */457DEBUGLOG(4, "CCtx pool overflow : free cctx");458ZSTD_freeCCtx(cctx);459}460ZSTD_pthread_mutex_unlock(&pool->poolMutex);461}462463/* ==== Serial State ==== */464465typedef struct {466void const* start;467size_t size;468} Range;469470typedef struct {471/* All variables in the struct are protected by mutex. */472ZSTD_pthread_mutex_t mutex;473ZSTD_pthread_cond_t cond;474ZSTD_CCtx_params params;475ldmState_t ldmState;476XXH64_state_t xxhState;477unsigned nextJobID;478/* Protects ldmWindow.479* Must be acquired after the main mutex when acquiring both.480*/481ZSTD_pthread_mutex_t ldmWindowMutex;482ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is updated */483ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */484} SerialState;485486static int487ZSTDMT_serialState_reset(SerialState* serialState,488ZSTDMT_seqPool* seqPool,489ZSTD_CCtx_params params,490size_t jobSize,491const void* dict, size_t const dictSize,492ZSTD_dictContentType_e dictContentType)493{494/* Adjust parameters */495if (params.ldmParams.enableLdm == ZSTD_ps_enable) {496DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);497ZSTD_ldm_adjustParameters(¶ms.ldmParams, ¶ms.cParams);498assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);499assert(params.ldmParams.hashRateLog < 32);500} else {501ZSTD_memset(¶ms.ldmParams, 0, sizeof(params.ldmParams));502}503serialState->nextJobID = 0;504if (params.fParams.checksumFlag)505XXH64_reset(&serialState->xxhState, 0);506if (params.ldmParams.enableLdm == ZSTD_ps_enable) {507ZSTD_customMem cMem = params.customMem;508unsigned const hashLog = params.ldmParams.hashLog;509size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);510unsigned const bucketLog =511params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;512unsigned const prevBucketLog =513serialState->params.ldmParams.hashLog -514serialState->params.ldmParams.bucketSizeLog;515size_t const numBuckets = (size_t)1 << bucketLog;516/* Size the seq pool tables */517ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));518/* Reset the window */519ZSTD_window_init(&serialState->ldmState.window);520/* Resize tables and output space if necessary. */521if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {522ZSTD_customFree(serialState->ldmState.hashTable, cMem);523serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_customMalloc(hashSize, cMem);524}525if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {526ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);527serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_customMalloc(numBuckets, cMem);528}529if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)530return 1;531/* Zero the tables */532ZSTD_memset(serialState->ldmState.hashTable, 0, hashSize);533ZSTD_memset(serialState->ldmState.bucketOffsets, 0, numBuckets);534535/* Update window state and fill hash table with dict */536serialState->ldmState.loadedDictEnd = 0;537if (dictSize > 0) {538if (dictContentType == ZSTD_dct_rawContent) {539BYTE const* const dictEnd = (const BYTE*)dict + dictSize;540ZSTD_window_update(&serialState->ldmState.window, dict, dictSize, /* forceNonContiguous */ 0);541ZSTD_ldm_fillHashTable(&serialState->ldmState, (const BYTE*)dict, dictEnd, ¶ms.ldmParams);542serialState->ldmState.loadedDictEnd = params.forceWindow ? 0 : (U32)(dictEnd - serialState->ldmState.window.base);543} else {544/* don't even load anything */545}546}547548/* Initialize serialState's copy of ldmWindow. */549serialState->ldmWindow = serialState->ldmState.window;550}551552serialState->params = params;553serialState->params.jobSize = (U32)jobSize;554return 0;555}556557static int ZSTDMT_serialState_init(SerialState* serialState)558{559int initError = 0;560ZSTD_memset(serialState, 0, sizeof(*serialState));561initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);562initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);563initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);564initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);565return initError;566}567568static void ZSTDMT_serialState_free(SerialState* serialState)569{570ZSTD_customMem cMem = serialState->params.customMem;571ZSTD_pthread_mutex_destroy(&serialState->mutex);572ZSTD_pthread_cond_destroy(&serialState->cond);573ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);574ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);575ZSTD_customFree(serialState->ldmState.hashTable, cMem);576ZSTD_customFree(serialState->ldmState.bucketOffsets, cMem);577}578579static void580ZSTDMT_serialState_genSequences(SerialState* serialState,581RawSeqStore_t* seqStore,582Range src, unsigned jobID)583{584/* Wait for our turn */585ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);586while (serialState->nextJobID < jobID) {587DEBUGLOG(5, "wait for serialState->cond");588ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);589}590/* A future job may error and skip our job */591if (serialState->nextJobID == jobID) {592/* It is now our turn, do any processing necessary */593if (serialState->params.ldmParams.enableLdm == ZSTD_ps_enable) {594size_t error;595DEBUGLOG(6, "ZSTDMT_serialState_genSequences: LDM update");596assert(seqStore->seq != NULL && seqStore->pos == 0 &&597seqStore->size == 0 && seqStore->capacity > 0);598assert(src.size <= serialState->params.jobSize);599ZSTD_window_update(&serialState->ldmState.window, src.start, src.size, /* forceNonContiguous */ 0);600error = ZSTD_ldm_generateSequences(601&serialState->ldmState, seqStore,602&serialState->params.ldmParams, src.start, src.size);603/* We provide a large enough buffer to never fail. */604assert(!ZSTD_isError(error)); (void)error;605/* Update ldmWindow to match the ldmState.window and signal the main606* thread if it is waiting for a buffer.607*/608ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);609serialState->ldmWindow = serialState->ldmState.window;610ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);611ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);612}613if (serialState->params.fParams.checksumFlag && src.size > 0)614XXH64_update(&serialState->xxhState, src.start, src.size);615}616/* Now it is the next jobs turn */617serialState->nextJobID++;618ZSTD_pthread_cond_broadcast(&serialState->cond);619ZSTD_pthread_mutex_unlock(&serialState->mutex);620}621622static void623ZSTDMT_serialState_applySequences(const SerialState* serialState, /* just for an assert() check */624ZSTD_CCtx* jobCCtx,625const RawSeqStore_t* seqStore)626{627if (seqStore->size > 0) {628DEBUGLOG(5, "ZSTDMT_serialState_applySequences: uploading %u external sequences", (unsigned)seqStore->size);629assert(serialState->params.ldmParams.enableLdm == ZSTD_ps_enable); (void)serialState;630assert(jobCCtx);631ZSTD_referenceExternalSequences(jobCCtx, seqStore->seq, seqStore->size);632}633}634635static void ZSTDMT_serialState_ensureFinished(SerialState* serialState,636unsigned jobID, size_t cSize)637{638ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);639if (serialState->nextJobID <= jobID) {640assert(ZSTD_isError(cSize)); (void)cSize;641DEBUGLOG(5, "Skipping past job %u because of error", jobID);642serialState->nextJobID = jobID + 1;643ZSTD_pthread_cond_broadcast(&serialState->cond);644645ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);646ZSTD_window_clear(&serialState->ldmWindow);647ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);648ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);649}650ZSTD_pthread_mutex_unlock(&serialState->mutex);651652}653654655/* ------------------------------------------ */656/* ===== Worker thread ===== */657/* ------------------------------------------ */658659static const Range kNullRange = { NULL, 0 };660661typedef struct {662size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */663size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */664ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */665ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */666ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */667ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */668ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */669SerialState* serial; /* Thread-safe - used by mtctx and (all) workers */670Buffer dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */671Range prefix; /* set by mtctx, then read by worker & mtctx => no barrier */672Range src; /* set by mtctx, then read by worker & mtctx => no barrier */673unsigned jobID; /* set by mtctx, then read by worker => no barrier */674unsigned firstJob; /* set by mtctx, then read by worker => no barrier */675unsigned lastJob; /* set by mtctx, then read by worker => no barrier */676ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */677const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */678unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */679size_t dstFlushed; /* used only by mtctx */680unsigned frameChecksumNeeded; /* used only by mtctx */681} ZSTDMT_jobDescription;682683#define JOB_ERROR(e) \684do { \685ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \686job->cSize = e; \687ZSTD_pthread_mutex_unlock(&job->job_mutex); \688goto _endJob; \689} while (0)690691/* ZSTDMT_compressionJob() is a POOL_function type */692static void ZSTDMT_compressionJob(void* jobDescription)693{694ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;695ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */696ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);697RawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);698Buffer dstBuff = job->dstBuff;699size_t lastCBlockSize = 0;700701DEBUGLOG(5, "ZSTDMT_compressionJob: job %u", job->jobID);702/* resources */703if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));704if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */705dstBuff = ZSTDMT_getBuffer(job->bufPool);706if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));707job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */708}709if (jobParams.ldmParams.enableLdm == ZSTD_ps_enable && rawSeqStore.seq == NULL)710JOB_ERROR(ERROR(memory_allocation));711712/* Don't compute the checksum for chunks, since we compute it externally,713* but write it in the header.714*/715if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;716/* Don't run LDM for the chunks, since we handle it externally */717jobParams.ldmParams.enableLdm = ZSTD_ps_disable;718/* Correct nbWorkers to 0. */719jobParams.nbWorkers = 0;720721722/* init */723724/* Perform serial step as early as possible */725ZSTDMT_serialState_genSequences(job->serial, &rawSeqStore, job->src, job->jobID);726727if (job->cdict) {728size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, &jobParams, job->fullFrameSize);729assert(job->firstJob); /* only allowed for first job */730if (ZSTD_isError(initError)) JOB_ERROR(initError);731} else {732U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;733{ size_t const forceWindowError = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);734if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);735}736if (!job->firstJob) {737size_t const err = ZSTD_CCtxParams_setParameter(&jobParams, ZSTD_c_deterministicRefPrefix, 0);738if (ZSTD_isError(err)) JOB_ERROR(err);739}740DEBUGLOG(6, "ZSTDMT_compressionJob: job %u: loading prefix of size %zu", job->jobID, job->prefix.size);741{ size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,742job->prefix.start, job->prefix.size, ZSTD_dct_rawContent,743ZSTD_dtlm_fast,744NULL, /*cdict*/745&jobParams, pledgedSrcSize);746if (ZSTD_isError(initError)) JOB_ERROR(initError);747} }748749/* External Sequences can only be applied after CCtx initialization */750ZSTDMT_serialState_applySequences(job->serial, cctx, &rawSeqStore);751752if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */753size_t const hSize = ZSTD_compressContinue_public(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);754if (ZSTD_isError(hSize)) JOB_ERROR(hSize);755DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);756ZSTD_invalidateRepCodes(cctx);757}758759/* compress the entire job by smaller chunks, for better granularity */760{ size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;761int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);762const BYTE* ip = (const BYTE*) job->src.start;763BYTE* const ostart = (BYTE*)dstBuff.start;764BYTE* op = ostart;765BYTE* oend = op + dstBuff.capacity;766int chunkNb;767if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */768DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);769assert(job->cSize == 0);770for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {771size_t const cSize = ZSTD_compressContinue_public(cctx, op, oend-op, ip, chunkSize);772if (ZSTD_isError(cSize)) JOB_ERROR(cSize);773ip += chunkSize;774op += cSize; assert(op < oend);775/* stats */776ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);777job->cSize += cSize;778job->consumed = chunkSize * chunkNb;779DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",780(U32)cSize, (U32)job->cSize);781ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */782ZSTD_pthread_mutex_unlock(&job->job_mutex);783}784/* last block */785assert(chunkSize > 0);786assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */787if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {788size_t const lastBlockSize1 = job->src.size & (chunkSize-1);789size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;790size_t const cSize = (job->lastJob) ?791ZSTD_compressEnd_public(cctx, op, oend-op, ip, lastBlockSize) :792ZSTD_compressContinue_public(cctx, op, oend-op, ip, lastBlockSize);793if (ZSTD_isError(cSize)) JOB_ERROR(cSize);794lastCBlockSize = cSize;795} }796if (!job->firstJob) {797/* Double check that we don't have an ext-dict, because then our798* repcode invalidation doesn't work.799*/800assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));801}802ZSTD_CCtx_trace(cctx, 0);803804_endJob:805ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);806if (job->prefix.size > 0)807DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);808DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);809/* release resources */810ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);811ZSTDMT_releaseCCtx(job->cctxPool, cctx);812/* report */813ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);814if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);815job->cSize += lastCBlockSize;816job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */817ZSTD_pthread_cond_signal(&job->job_cond);818ZSTD_pthread_mutex_unlock(&job->job_mutex);819}820821822/* ------------------------------------------ */823/* ===== Multi-threaded compression ===== */824/* ------------------------------------------ */825826typedef struct {827Range prefix; /* read-only non-owned prefix buffer */828Buffer buffer;829size_t filled;830} InBuff_t;831832typedef struct {833BYTE* buffer; /* The round input buffer. All jobs get references834* to pieces of the buffer. ZSTDMT_tryGetInputRange()835* handles handing out job input buffers, and makes836* sure it doesn't overlap with any pieces still in use.837*/838size_t capacity; /* The capacity of buffer. */839size_t pos; /* The position of the current inBuff in the round840* buffer. Updated past the end if the inBuff once841* the inBuff is sent to the worker thread.842* pos <= capacity.843*/844} RoundBuff_t;845846static const RoundBuff_t kNullRoundBuff = {NULL, 0, 0};847848#define RSYNC_LENGTH 32849/* 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 then854* ZSTD_COMPRESSBOUND() will need to be updated.855*/856#define RSYNC_MIN_BLOCK_LOG ZSTD_BLOCKSIZELOG_MAX857#define RSYNC_MIN_BLOCK_SIZE (1<<RSYNC_MIN_BLOCK_LOG)858859typedef struct {860U64 hash;861U64 hitMask;862U64 primePower;863} RSyncState_t;864865struct ZSTDMT_CCtx_s {866POOL_ctx* factory;867ZSTDMT_jobDescription* jobs;868ZSTDMT_bufferPool* bufPool;869ZSTDMT_CCtxPool* cctxPool;870ZSTDMT_seqPool* seqPool;871ZSTD_CCtx_params params;872size_t targetSectionSize;873size_t targetPrefixSize;874int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */875InBuff_t inBuff;876RoundBuff_t roundBuff;877SerialState serial;878RSyncState_t rsync;879unsigned jobIDMask;880unsigned doneJobID;881unsigned nextJobID;882unsigned frameEnded;883unsigned allJobsCompleted;884unsigned long long frameContentSize;885unsigned long long consumed;886unsigned long long produced;887ZSTD_customMem cMem;888ZSTD_CDict* cdictLocal;889const ZSTD_CDict* cdict;890unsigned providedFactory: 1;891};892893static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)894{895U32 jobNb;896if (jobTable == NULL) return;897for (jobNb=0; jobNb<nbJobs; jobNb++) {898ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);899ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);900}901ZSTD_customFree(jobTable, cMem);902}903904/* ZSTDMT_allocJobsTable()905* allocate and init a job table.906* update *nbJobsPtr to next power of 2 value, as size of table */907static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)908{909U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;910U32 const nbJobs = 1 << nbJobsLog2;911U32 jobNb;912ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)913ZSTD_customCalloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);914int initError = 0;915if (jobTable==NULL) return NULL;916*nbJobsPtr = nbJobs;917for (jobNb=0; jobNb<nbJobs; jobNb++) {918initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);919initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);920}921if (initError != 0) {922ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);923return NULL;924}925return jobTable;926}927928static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {929U32 nbJobs = nbWorkers + 2;930if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */931ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);932mtctx->jobIDMask = 0;933mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);934if (mtctx->jobs==NULL) return ERROR(memory_allocation);935assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */936mtctx->jobIDMask = nbJobs - 1;937}938return 0;939}940941942/* ZSTDMT_CCtxParam_setNbWorkers():943* Internal use only */944static size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)945{946return ZSTD_CCtxParams_setParameter(params, ZSTD_c_nbWorkers, (int)nbWorkers);947}948949MEM_STATIC ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced_internal(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)950{951ZSTDMT_CCtx* mtctx;952U32 nbJobs = nbWorkers + 2;953int initError;954DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);955956if (nbWorkers < 1) return NULL;957nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);958if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))959/* invalid custom allocator */960return NULL;961962mtctx = (ZSTDMT_CCtx*) ZSTD_customCalloc(sizeof(ZSTDMT_CCtx), cMem);963if (!mtctx) return NULL;964ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);965mtctx->cMem = cMem;966mtctx->allJobsCompleted = 1;967if (pool != NULL) {968mtctx->factory = pool;969mtctx->providedFactory = 1;970}971else {972mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);973mtctx->providedFactory = 0;974}975mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);976assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */977mtctx->jobIDMask = nbJobs - 1;978mtctx->bufPool = ZSTDMT_createBufferPool(BUF_POOL_MAX_NB_BUFFERS(nbWorkers), cMem);979mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);980mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);981initError = ZSTDMT_serialState_init(&mtctx->serial);982mtctx->roundBuff = kNullRoundBuff;983if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {984ZSTDMT_freeCCtx(mtctx);985return NULL;986}987DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);988return mtctx;989}990991ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem, ZSTD_threadPool* pool)992{993#ifdef ZSTD_MULTITHREAD994return ZSTDMT_createCCtx_advanced_internal(nbWorkers, cMem, pool);995#else996(void)nbWorkers;997(void)cMem;998(void)pool;999return NULL;1000#endif1001}100210031004/* ZSTDMT_releaseAllJobResources() :1005* note : ensure all workers are killed first ! */1006static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)1007{1008unsigned jobID;1009DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");1010for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {1011/* Copy the mutex/cond out */1012ZSTD_pthread_mutex_t const mutex = mtctx->jobs[jobID].job_mutex;1013ZSTD_pthread_cond_t const cond = mtctx->jobs[jobID].job_cond;10141015DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);1016ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);10171018/* Clear the job description, but keep the mutex/cond */1019ZSTD_memset(&mtctx->jobs[jobID], 0, sizeof(mtctx->jobs[jobID]));1020mtctx->jobs[jobID].job_mutex = mutex;1021mtctx->jobs[jobID].job_cond = cond;1022}1023mtctx->inBuff.buffer = g_nullBuffer;1024mtctx->inBuff.filled = 0;1025mtctx->allJobsCompleted = 1;1026}10271028static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)1029{1030DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");1031while (mtctx->doneJobID < mtctx->nextJobID) {1032unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;1033ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);1034while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {1035DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */1036ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);1037}1038ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);1039mtctx->doneJobID++;1040}1041}10421043size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)1044{1045if (mtctx==NULL) return 0; /* compatible with free on NULL */1046if (!mtctx->providedFactory)1047POOL_free(mtctx->factory); /* stop and free worker threads */1048ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */1049ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);1050ZSTDMT_freeBufferPool(mtctx->bufPool);1051ZSTDMT_freeCCtxPool(mtctx->cctxPool);1052ZSTDMT_freeSeqPool(mtctx->seqPool);1053ZSTDMT_serialState_free(&mtctx->serial);1054ZSTD_freeCDict(mtctx->cdictLocal);1055if (mtctx->roundBuff.buffer)1056ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);1057ZSTD_customFree(mtctx, mtctx->cMem);1058return 0;1059}10601061size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)1062{1063if (mtctx == NULL) return 0; /* supports sizeof NULL */1064return sizeof(*mtctx)1065+ POOL_sizeof(mtctx->factory)1066+ ZSTDMT_sizeof_bufferPool(mtctx->bufPool)1067+ (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)1068+ ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)1069+ ZSTDMT_sizeof_seqPool(mtctx->seqPool)1070+ ZSTD_sizeof_CDict(mtctx->cdictLocal)1071+ mtctx->roundBuff.capacity;1072}107310741075/* ZSTDMT_resize() :1076* @return : error code if fails, 0 on success */1077static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)1078{1079if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);1080FORWARD_IF_ERROR( ZSTDMT_expandJobsTable(mtctx, nbWorkers) , "");1081mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, BUF_POOL_MAX_NB_BUFFERS(nbWorkers));1082if (mtctx->bufPool == NULL) return ERROR(memory_allocation);1083mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);1084if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);1085mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);1086if (mtctx->seqPool == NULL) return ERROR(memory_allocation);1087ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);1088return 0;1089}109010911092/*! ZSTDMT_updateCParams_whileCompressing() :1093* Updates a selected set of compression parameters, remaining compatible with currently active frame.1094* New parameters will be applied to next compression job. */1095void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)1096{1097U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */1098int const compressionLevel = cctxParams->compressionLevel;1099DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",1100compressionLevel);1101mtctx->params.compressionLevel = compressionLevel;1102{ ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, 0, ZSTD_cpm_noAttachDict);1103cParams.windowLog = saved_wlog;1104mtctx->params.cParams = cParams;1105}1106}11071108/* ZSTDMT_getFrameProgression():1109* tells how much data has been consumed (input) and produced (output) for current frame.1110* able to count progression inside worker threads.1111* Note : mutex will be acquired during statistics collection inside workers. */1112ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)1113{1114ZSTD_frameProgression fps;1115DEBUGLOG(5, "ZSTDMT_getFrameProgression");1116fps.ingested = mtctx->consumed + mtctx->inBuff.filled;1117fps.consumed = mtctx->consumed;1118fps.produced = fps.flushed = mtctx->produced;1119fps.currentJobID = mtctx->nextJobID;1120fps.nbActiveWorkers = 0;1121{ unsigned jobNb;1122unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);1123DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",1124mtctx->doneJobID, lastJobNb, mtctx->jobReady);1125for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {1126unsigned const wJobID = jobNb & mtctx->jobIDMask;1127ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];1128ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);1129{ size_t const cResult = jobPtr->cSize;1130size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;1131size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;1132assert(flushed <= produced);1133fps.ingested += jobPtr->src.size;1134fps.consumed += jobPtr->consumed;1135fps.produced += produced;1136fps.flushed += flushed;1137fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);1138}1139ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1140}1141}1142return fps;1143}114411451146size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)1147{1148size_t toFlush;1149unsigned const jobID = mtctx->doneJobID;1150assert(jobID <= mtctx->nextJobID);1151if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */11521153/* look into oldest non-fully-flushed job */1154{ unsigned const wJobID = jobID & mtctx->jobIDMask;1155ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];1156ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);1157{ size_t const cResult = jobPtr->cSize;1158size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;1159size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;1160assert(flushed <= produced);1161assert(jobPtr->consumed <= jobPtr->src.size);1162toFlush = produced - flushed;1163/* if toFlush==0, nothing is available to flush.1164* However, jobID is expected to still be active:1165* if jobID was already completed and fully flushed,1166* ZSTDMT_flushProduced() should have already moved onto next job.1167* Therefore, some input has not yet been consumed. */1168if (toFlush==0) {1169assert(jobPtr->consumed < jobPtr->src.size);1170}1171}1172ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1173}11741175return toFlush;1176}117711781179/* ------------------------------------------ */1180/* ===== Multi-threaded compression ===== */1181/* ------------------------------------------ */11821183static unsigned ZSTDMT_computeTargetJobLog(const ZSTD_CCtx_params* params)1184{1185unsigned jobLog;1186if (params->ldmParams.enableLdm == ZSTD_ps_enable) {1187/* In Long Range Mode, the windowLog is typically oversized.1188* In which case, it's preferable to determine the jobSize1189* based on cycleLog instead. */1190jobLog = MAX(21, ZSTD_cycleLog(params->cParams.chainLog, params->cParams.strategy) + 3);1191} else {1192jobLog = MAX(20, params->cParams.windowLog + 2);1193}1194return MIN(jobLog, (unsigned)ZSTDMT_JOBLOG_MAX);1195}11961197static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)1198{1199switch(strat)1200{1201case ZSTD_btultra2:1202return 9;1203case ZSTD_btultra:1204case ZSTD_btopt:1205return 8;1206case ZSTD_btlazy2:1207case ZSTD_lazy2:1208return 7;1209case ZSTD_lazy:1210case ZSTD_greedy:1211case ZSTD_dfast:1212case ZSTD_fast:1213default:;1214}1215return 6;1216}12171218static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)1219{1220assert(0 <= ovlog && ovlog <= 9);1221if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);1222return ovlog;1223}12241225static size_t ZSTDMT_computeOverlapSize(const ZSTD_CCtx_params* params)1226{1227int const overlapRLog = 9 - ZSTDMT_overlapLog(params->overlapLog, params->cParams.strategy);1228int ovLog = (overlapRLog >= 8) ? 0 : (params->cParams.windowLog - overlapRLog);1229assert(0 <= overlapRLog && overlapRLog <= 8);1230if (params->ldmParams.enableLdm == ZSTD_ps_enable) {1231/* In Long Range Mode, the windowLog is typically oversized.1232* In which case, it's preferable to determine the jobSize1233* based on chainLog instead.1234* Then, ovLog becomes a fraction of the jobSize, rather than windowSize */1235ovLog = MIN(params->cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)1236- overlapRLog;1237}1238assert(0 <= ovLog && ovLog <= ZSTD_WINDOWLOG_MAX);1239DEBUGLOG(4, "overlapLog : %i", params->overlapLog);1240DEBUGLOG(4, "overlap size : %i", 1 << ovLog);1241return (ovLog==0) ? 0 : (size_t)1 << ovLog;1242}12431244/* ====================================== */1245/* ======= Streaming API ======= */1246/* ====================================== */12471248size_t ZSTDMT_initCStream_internal(1249ZSTDMT_CCtx* mtctx,1250const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,1251const ZSTD_CDict* cdict, ZSTD_CCtx_params params,1252unsigned long long pledgedSrcSize)1253{1254DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",1255(U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);12561257/* params supposed partially fully validated at this point */1258assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));1259assert(!((dict) && (cdict))); /* either dict or cdict, not both */12601261/* init */1262if (params.nbWorkers != mtctx->params.nbWorkers)1263FORWARD_IF_ERROR( ZSTDMT_resize(mtctx, (unsigned)params.nbWorkers) , "");12641265if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;1266if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = (size_t)ZSTDMT_JOBSIZE_MAX;12671268if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */1269ZSTDMT_waitForAllJobsCompleted(mtctx);1270ZSTDMT_releaseAllJobResources(mtctx);1271mtctx->allJobsCompleted = 1;1272}12731274mtctx->params = params;1275mtctx->frameContentSize = pledgedSrcSize;1276ZSTD_freeCDict(mtctx->cdictLocal);1277if (dict) {1278mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,1279ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */1280params.cParams, mtctx->cMem);1281mtctx->cdict = mtctx->cdictLocal;1282if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);1283} else {1284mtctx->cdictLocal = NULL;1285mtctx->cdict = cdict;1286}12871288mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(¶ms);1289DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));1290mtctx->targetSectionSize = params.jobSize;1291if (mtctx->targetSectionSize == 0) {1292mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(¶ms);1293}1294assert(mtctx->targetSectionSize <= (size_t)ZSTDMT_JOBSIZE_MAX);12951296if (params.rsyncable) {1297/* Aim for the targetsectionSize as the average job size. */1298U32 const jobSizeKB = (U32)(mtctx->targetSectionSize >> 10);1299U32 const rsyncBits = (assert(jobSizeKB >= 1), ZSTD_highbit32(jobSizeKB) + 10);1300/* We refuse to create jobs < RSYNC_MIN_BLOCK_SIZE bytes, so make sure our1301* expected job size is at least 4x larger. */1302assert(rsyncBits >= RSYNC_MIN_BLOCK_LOG + 2);1303DEBUGLOG(4, "rsyncLog = %u", rsyncBits);1304mtctx->rsync.hash = 0;1305mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;1306mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);1307}1308if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */1309DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);1310DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));1311ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));1312{1313/* If ldm is enabled we need windowSize space. */1314size_t const windowSize = mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable ? (1U << mtctx->params.cParams.windowLog) : 0;1315/* Two buffers of slack, plus extra space for the overlap1316* This is the minimum slack that LDM works with. One extra because1317* flush might waste up to targetSectionSize-1 bytes. Another extra1318* for the overlap (if > 0), then one to fill which doesn't overlap1319* with the LDM window.1320*/1321size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);1322size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;1323/* Compute the total size, and always have enough slack */1324size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);1325size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;1326size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;1327if (mtctx->roundBuff.capacity < capacity) {1328if (mtctx->roundBuff.buffer)1329ZSTD_customFree(mtctx->roundBuff.buffer, mtctx->cMem);1330mtctx->roundBuff.buffer = (BYTE*)ZSTD_customMalloc(capacity, mtctx->cMem);1331if (mtctx->roundBuff.buffer == NULL) {1332mtctx->roundBuff.capacity = 0;1333return ERROR(memory_allocation);1334}1335mtctx->roundBuff.capacity = capacity;1336}1337}1338DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));1339mtctx->roundBuff.pos = 0;1340mtctx->inBuff.buffer = g_nullBuffer;1341mtctx->inBuff.filled = 0;1342mtctx->inBuff.prefix = kNullRange;1343mtctx->doneJobID = 0;1344mtctx->nextJobID = 0;1345mtctx->frameEnded = 0;1346mtctx->allJobsCompleted = 0;1347mtctx->consumed = 0;1348mtctx->produced = 0;13491350/* update dictionary */1351ZSTD_freeCDict(mtctx->cdictLocal);1352mtctx->cdictLocal = NULL;1353mtctx->cdict = NULL;1354if (dict) {1355if (dictContentType == ZSTD_dct_rawContent) {1356mtctx->inBuff.prefix.start = (const BYTE*)dict;1357mtctx->inBuff.prefix.size = dictSize;1358} else {1359/* note : a loadPrefix becomes an internal CDict */1360mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,1361ZSTD_dlm_byRef, dictContentType,1362params.cParams, mtctx->cMem);1363mtctx->cdict = mtctx->cdictLocal;1364if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);1365}1366} else {1367mtctx->cdict = cdict;1368}13691370if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize,1371dict, dictSize, dictContentType))1372return ERROR(memory_allocation);137313741375return 0;1376}137713781379/* ZSTDMT_writeLastEmptyBlock()1380* Write a single empty block with an end-of-frame to finish a frame.1381* Job must be created from streaming variant.1382* This function is always successful if expected conditions are fulfilled.1383*/1384static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)1385{1386assert(job->lastJob == 1);1387assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */1388assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */1389assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */1390job->dstBuff = ZSTDMT_getBuffer(job->bufPool);1391if (job->dstBuff.start == NULL) {1392job->cSize = ERROR(memory_allocation);1393return;1394}1395assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */1396job->src = kNullRange;1397job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);1398assert(!ZSTD_isError(job->cSize));1399assert(job->consumed == 0);1400}14011402static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)1403{1404unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;1405int const endFrame = (endOp == ZSTD_e_end);14061407if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {1408DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");1409assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));1410return 0;1411}14121413if (!mtctx->jobReady) {1414BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;1415DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",1416mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);1417mtctx->jobs[jobID].src.start = src;1418mtctx->jobs[jobID].src.size = srcSize;1419assert(mtctx->inBuff.filled >= srcSize);1420mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;1421mtctx->jobs[jobID].consumed = 0;1422mtctx->jobs[jobID].cSize = 0;1423mtctx->jobs[jobID].params = mtctx->params;1424mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;1425mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;1426mtctx->jobs[jobID].dstBuff = g_nullBuffer;1427mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;1428mtctx->jobs[jobID].bufPool = mtctx->bufPool;1429mtctx->jobs[jobID].seqPool = mtctx->seqPool;1430mtctx->jobs[jobID].serial = &mtctx->serial;1431mtctx->jobs[jobID].jobID = mtctx->nextJobID;1432mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);1433mtctx->jobs[jobID].lastJob = endFrame;1434mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);1435mtctx->jobs[jobID].dstFlushed = 0;14361437/* Update the round buffer pos and clear the input buffer to be reset */1438mtctx->roundBuff.pos += srcSize;1439mtctx->inBuff.buffer = g_nullBuffer;1440mtctx->inBuff.filled = 0;1441/* Set the prefix for next job */1442if (!endFrame) {1443size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);1444mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;1445mtctx->inBuff.prefix.size = newPrefixSize;1446} else { /* endFrame==1 => no need for another input buffer */1447mtctx->inBuff.prefix = kNullRange;1448mtctx->frameEnded = endFrame;1449if (mtctx->nextJobID == 0) {1450/* single job exception : checksum is already calculated directly within worker thread */1451mtctx->params.fParams.checksumFlag = 0;1452} }14531454if ( (srcSize == 0)1455&& (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {1456DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");1457assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */1458ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);1459mtctx->nextJobID++;1460return 0;1461}1462}14631464DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",1465mtctx->nextJobID,1466(U32)mtctx->jobs[jobID].src.size,1467mtctx->jobs[jobID].lastJob,1468mtctx->nextJobID,1469jobID);1470if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {1471mtctx->nextJobID++;1472mtctx->jobReady = 0;1473} else {1474DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);1475mtctx->jobReady = 1;1476}1477return 0;1478}147914801481/*! ZSTDMT_flushProduced() :1482* flush whatever data has been produced but not yet flushed in current job.1483* move to next job if current one is fully flushed.1484* `output` : `pos` will be updated with amount of data flushed .1485* `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .1486* @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */1487static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)1488{1489unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;1490DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",1491blockToFlush, mtctx->doneJobID, mtctx->nextJobID);1492assert(output->size >= output->pos);14931494ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);1495if ( blockToFlush1496&& (mtctx->doneJobID < mtctx->nextJobID) ) {1497assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);1498while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */1499if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {1500DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",1501mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);1502break;1503}1504DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",1505mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);1506ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */1507} }15081509/* try to flush something */1510{ size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */1511size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */1512size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */1513ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);1514if (ZSTD_isError(cSize)) {1515DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",1516mtctx->doneJobID, ZSTD_getErrorName(cSize));1517ZSTDMT_waitForAllJobsCompleted(mtctx);1518ZSTDMT_releaseAllJobResources(mtctx);1519return cSize;1520}1521/* add frame checksum if necessary (can only happen once) */1522assert(srcConsumed <= srcSize);1523if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */1524&& mtctx->jobs[wJobID].frameChecksumNeeded ) {1525U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);1526DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);1527MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);1528cSize += 4;1529mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */1530mtctx->jobs[wJobID].frameChecksumNeeded = 0;1531}15321533if (cSize > 0) { /* compression is ongoing or completed */1534size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);1535DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",1536(U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);1537assert(mtctx->doneJobID < mtctx->nextJobID);1538assert(cSize >= mtctx->jobs[wJobID].dstFlushed);1539assert(mtctx->jobs[wJobID].dstBuff.start != NULL);1540if (toFlush > 0) {1541ZSTD_memcpy((char*)output->dst + output->pos,1542(const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,1543toFlush);1544}1545output->pos += toFlush;1546mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */15471548if ( (srcConsumed == srcSize) /* job is completed */1549&& (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */1550DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",1551mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);1552ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);1553DEBUGLOG(5, "dstBuffer released");1554mtctx->jobs[wJobID].dstBuff = g_nullBuffer;1555mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */1556mtctx->consumed += srcSize;1557mtctx->produced += cSize;1558mtctx->doneJobID++;1559} }15601561/* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */1562if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);1563if (srcSize > srcConsumed) return 1; /* current job not completely compressed */1564}1565if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */1566if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */1567if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */1568mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */1569if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */1570return 0; /* internal buffers fully flushed */1571}15721573/**1574* Returns the range of data used by the earliest job that is not yet complete.1575* If the data of the first job is broken up into two segments, we cover both1576* sections.1577*/1578static Range ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)1579{1580unsigned const firstJobID = mtctx->doneJobID;1581unsigned const lastJobID = mtctx->nextJobID;1582unsigned jobID;15831584/* no need to check during first round */1585size_t roundBuffCapacity = mtctx->roundBuff.capacity;1586size_t nbJobs1stRoundMin = roundBuffCapacity / mtctx->targetSectionSize;1587if (lastJobID < nbJobs1stRoundMin) return kNullRange;15881589for (jobID = firstJobID; jobID < lastJobID; ++jobID) {1590unsigned const wJobID = jobID & mtctx->jobIDMask;1591size_t consumed;15921593ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);1594consumed = mtctx->jobs[wJobID].consumed;1595ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);15961597if (consumed < mtctx->jobs[wJobID].src.size) {1598Range range = mtctx->jobs[wJobID].prefix;1599if (range.size == 0) {1600/* Empty prefix */1601range = mtctx->jobs[wJobID].src;1602}1603/* Job source in multiple segments not supported yet */1604assert(range.start <= mtctx->jobs[wJobID].src.start);1605return range;1606}1607}1608return kNullRange;1609}16101611/**1612* Returns non-zero iff buffer and range overlap.1613*/1614static int ZSTDMT_isOverlapped(Buffer buffer, Range range)1615{1616BYTE const* const bufferStart = (BYTE const*)buffer.start;1617BYTE const* const rangeStart = (BYTE const*)range.start;16181619if (rangeStart == NULL || bufferStart == NULL)1620return 0;16211622{1623BYTE const* const bufferEnd = bufferStart + buffer.capacity;1624BYTE const* const rangeEnd = rangeStart + range.size;16251626/* Empty ranges cannot overlap */1627if (bufferStart == bufferEnd || rangeStart == rangeEnd)1628return 0;16291630return bufferStart < rangeEnd && rangeStart < bufferEnd;1631}1632}16331634static int ZSTDMT_doesOverlapWindow(Buffer buffer, ZSTD_window_t window)1635{1636Range extDict;1637Range prefix;16381639DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");1640extDict.start = window.dictBase + window.lowLimit;1641extDict.size = window.dictLimit - window.lowLimit;16421643prefix.start = window.base + window.dictLimit;1644prefix.size = window.nextSrc - (window.base + window.dictLimit);1645DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",1646(size_t)extDict.start,1647(size_t)extDict.start + extDict.size);1648DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",1649(size_t)prefix.start,1650(size_t)prefix.start + prefix.size);16511652return ZSTDMT_isOverlapped(buffer, extDict)1653|| ZSTDMT_isOverlapped(buffer, prefix);1654}16551656static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, Buffer buffer)1657{1658if (mtctx->params.ldmParams.enableLdm == ZSTD_ps_enable) {1659ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;1660DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");1661DEBUGLOG(5, "source [0x%zx, 0x%zx)",1662(size_t)buffer.start,1663(size_t)buffer.start + buffer.capacity);1664ZSTD_PTHREAD_MUTEX_LOCK(mutex);1665while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {1666DEBUGLOG(5, "Waiting for LDM to finish...");1667ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);1668}1669DEBUGLOG(6, "Done waiting for LDM to finish");1670ZSTD_pthread_mutex_unlock(mutex);1671}1672}16731674/**1675* Attempts to set the inBuff to the next section to fill.1676* If any part of the new section is still in use we give up.1677* Returns non-zero if the buffer is filled.1678*/1679static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)1680{1681Range const inUse = ZSTDMT_getInputDataInUse(mtctx);1682size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;1683size_t const spaceNeeded = mtctx->targetSectionSize;1684Buffer buffer;16851686DEBUGLOG(5, "ZSTDMT_tryGetInputRange");1687assert(mtctx->inBuff.buffer.start == NULL);1688assert(mtctx->roundBuff.capacity >= spaceNeeded);16891690if (spaceLeft < spaceNeeded) {1691/* ZSTD_invalidateRepCodes() doesn't work for extDict variants.1692* Simply copy the prefix to the beginning in that case.1693*/1694BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;1695size_t const prefixSize = mtctx->inBuff.prefix.size;16961697buffer.start = start;1698buffer.capacity = prefixSize;1699if (ZSTDMT_isOverlapped(buffer, inUse)) {1700DEBUGLOG(5, "Waiting for buffer...");1701return 0;1702}1703ZSTDMT_waitForLdmComplete(mtctx, buffer);1704ZSTD_memmove(start, mtctx->inBuff.prefix.start, prefixSize);1705mtctx->inBuff.prefix.start = start;1706mtctx->roundBuff.pos = prefixSize;1707}1708buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;1709buffer.capacity = spaceNeeded;17101711if (ZSTDMT_isOverlapped(buffer, inUse)) {1712DEBUGLOG(5, "Waiting for buffer...");1713return 0;1714}1715assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));17161717ZSTDMT_waitForLdmComplete(mtctx, buffer);17181719DEBUGLOG(5, "Using prefix range [%zx, %zx)",1720(size_t)mtctx->inBuff.prefix.start,1721(size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);1722DEBUGLOG(5, "Using source range [%zx, %zx)",1723(size_t)buffer.start,1724(size_t)buffer.start + buffer.capacity);172517261727mtctx->inBuff.buffer = buffer;1728mtctx->inBuff.filled = 0;1729assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);1730return 1;1731}17321733typedef struct {1734size_t toLoad; /* The number of bytes to load from the input. */1735int flush; /* Boolean declaring if we must flush because we found a synchronization point. */1736} SyncPoint;17371738/**1739* Searches through the input for a synchronization point. If one is found, we1740* will instruct the caller to flush, and return the number of bytes to load.1741* Otherwise, we will load as many bytes as possible and instruct the caller1742* to continue as normal.1743*/1744static SyncPoint1745findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)1746{1747BYTE const* const istart = (BYTE const*)input.src + input.pos;1748U64 const primePower = mtctx->rsync.primePower;1749U64 const hitMask = mtctx->rsync.hitMask;17501751SyncPoint syncPoint;1752U64 hash;1753BYTE const* prev;1754size_t pos;17551756syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);1757syncPoint.flush = 0;1758if (!mtctx->params.rsyncable)1759/* Rsync is disabled. */1760return syncPoint;1761if (mtctx->inBuff.filled + input.size - input.pos < RSYNC_MIN_BLOCK_SIZE)1762/* We don't emit synchronization points if it would produce too small blocks.1763* We don't have enough input to find a synchronization point, so don't look.1764*/1765return syncPoint;1766if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)1767/* Not enough to compute the hash.1768* We will miss any synchronization points in this RSYNC_LENGTH byte1769* window. However, since it depends only in the internal buffers, if the1770* state is already synchronized, we will remain synchronized.1771* Additionally, the probability that we miss a synchronization point is1772* low: RSYNC_LENGTH / targetSectionSize.1773*/1774return syncPoint;1775/* Initialize the loop variables. */1776if (mtctx->inBuff.filled < RSYNC_MIN_BLOCK_SIZE) {1777/* We don't need to scan the first RSYNC_MIN_BLOCK_SIZE positions1778* because they can't possibly be a sync point. So we can start1779* part way through the input buffer.1780*/1781pos = RSYNC_MIN_BLOCK_SIZE - mtctx->inBuff.filled;1782if (pos >= RSYNC_LENGTH) {1783prev = istart + pos - RSYNC_LENGTH;1784hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);1785} else {1786assert(mtctx->inBuff.filled >= RSYNC_LENGTH);1787prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;1788hash = ZSTD_rollingHash_compute(prev + pos, (RSYNC_LENGTH - pos));1789hash = ZSTD_rollingHash_append(hash, istart, pos);1790}1791} else {1792/* We have enough bytes buffered to initialize the hash,1793* and have processed enough bytes to find a sync point.1794* Start scanning at the beginning of the input.1795*/1796assert(mtctx->inBuff.filled >= RSYNC_MIN_BLOCK_SIZE);1797assert(RSYNC_MIN_BLOCK_SIZE >= RSYNC_LENGTH);1798pos = 0;1799prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;1800hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);1801if ((hash & hitMask) == hitMask) {1802/* We're already at a sync point so don't load any more until1803* we're able to flush this sync point.1804* This likely happened because the job table was full so we1805* couldn't add our job.1806*/1807syncPoint.toLoad = 0;1808syncPoint.flush = 1;1809return syncPoint;1810}1811}1812/* Starting with the hash of the previous RSYNC_LENGTH bytes, roll1813* through the input. If we hit a synchronization point, then cut the1814* job off, and tell the compressor to flush the job. Otherwise, load1815* all the bytes and continue as normal.1816* If we go too long without a synchronization point (targetSectionSize)1817* then a block will be emitted anyways, but this is okay, since if we1818* are already synchronized we will remain synchronized.1819*/1820assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);1821for (; pos < syncPoint.toLoad; ++pos) {1822BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];1823/* This assert is very expensive, and Debian compiles with asserts enabled.1824* So disable it for now. We can get similar coverage by checking it at the1825* beginning & end of the loop.1826* assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);1827*/1828hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);1829assert(mtctx->inBuff.filled + pos >= RSYNC_MIN_BLOCK_SIZE);1830if ((hash & hitMask) == hitMask) {1831syncPoint.toLoad = pos + 1;1832syncPoint.flush = 1;1833++pos; /* for assert */1834break;1835}1836}1837assert(pos < RSYNC_LENGTH || ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash);1838return syncPoint;1839}18401841size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)1842{1843size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;1844if (hintInSize==0) hintInSize = mtctx->targetSectionSize;1845return hintInSize;1846}18471848/** ZSTDMT_compressStream_generic() :1849* internal use only - exposed to be invoked from zstd_compress.c1850* assumption : output and input are valid (pos <= size)1851* @return : minimum amount of data remaining to flush, 0 if none */1852size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,1853ZSTD_outBuffer* output,1854ZSTD_inBuffer* input,1855ZSTD_EndDirective endOp)1856{1857unsigned forwardInputProgress = 0;1858DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",1859(U32)endOp, (U32)(input->size - input->pos));1860assert(output->pos <= output->size);1861assert(input->pos <= input->size);18621863if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {1864/* current frame being ended. Only flush/end are allowed */1865return ERROR(stage_wrong);1866}18671868/* fill input buffer */1869if ( (!mtctx->jobReady)1870&& (input->size > input->pos) ) { /* support NULL input */1871if (mtctx->inBuff.buffer.start == NULL) {1872assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */1873if (!ZSTDMT_tryGetInputRange(mtctx)) {1874/* It is only possible for this operation to fail if there are1875* still compression jobs ongoing.1876*/1877DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");1878assert(mtctx->doneJobID != mtctx->nextJobID);1879} else1880DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);1881}1882if (mtctx->inBuff.buffer.start != NULL) {1883SyncPoint const syncPoint = findSynchronizationPoint(mtctx, *input);1884if (syncPoint.flush && endOp == ZSTD_e_continue) {1885endOp = ZSTD_e_flush;1886}1887assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);1888DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",1889(U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);1890ZSTD_memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);1891input->pos += syncPoint.toLoad;1892mtctx->inBuff.filled += syncPoint.toLoad;1893forwardInputProgress = syncPoint.toLoad>0;1894}1895}1896if ((input->pos < input->size) && (endOp == ZSTD_e_end)) {1897/* Can't end yet because the input is not fully consumed.1898* We are in one of these cases:1899* - mtctx->inBuff is NULL & empty: we couldn't get an input buffer so don't create a new job.1900* - We filled the input buffer: flush this job but don't end the frame.1901* - We hit a synchronization point: flush this job but don't end the frame.1902*/1903assert(mtctx->inBuff.filled == 0 || mtctx->inBuff.filled == mtctx->targetSectionSize || mtctx->params.rsyncable);1904endOp = ZSTD_e_flush;1905}19061907if ( (mtctx->jobReady)1908|| (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */1909|| ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */1910|| ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */1911size_t const jobSize = mtctx->inBuff.filled;1912assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);1913FORWARD_IF_ERROR( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) , "");1914}19151916/* check for potential compressed data ready to be flushed */1917{ size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */1918if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */1919DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);1920return remainingToFlush;1921}1922}192319241925