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