Path: blob/main/sys/contrib/openzfs/module/zstd/lib/common/zstd_internal.h
48774 views
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only1/*2* Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.3* All rights reserved.4*5* This source code is licensed under both the BSD-style license (found in the6* LICENSE file in the root directory of this source tree) and the GPLv2 (found7* in the COPYING file in the root directory of this source tree).8* You may select, at your option, one of the above-listed licenses.9*/1011#ifndef ZSTD_CCOMMON_H_MODULE12#define ZSTD_CCOMMON_H_MODULE1314/* this module contains definitions which must be identical15* across compression, decompression and dictBuilder.16* It also contains a few functions useful to at least 2 of them17* and which benefit from being inlined */1819/*-*************************************20* Dependencies21***************************************/22#if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)23#include <arm_neon.h>24#endif25#include "compiler.h"26#include "mem.h"27#include "debug.h" /* assert, DEBUGLOG, RAWLOG, g_debuglevel */28#include "error_private.h"29#define ZSTD_STATIC_LINKING_ONLY30#include "../zstd.h"31#define FSE_STATIC_LINKING_ONLY32#include "fse.h"33#define HUF_STATIC_LINKING_ONLY34#include "huf.h"35#ifndef XXH_STATIC_LINKING_ONLY36# define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */37#endif38#include "xxhash.h" /* XXH_reset, update, digest */3940#if defined (__cplusplus)41extern "C" {42#endif4344/* ---- static assert (debug) --- */45#define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)46#define FSE_isError ERR_isError47#define HUF_isError ERR_isError484950/*-*************************************51* shared macros52***************************************/53#undef MIN54#undef MAX55#define MIN(a,b) ((a)<(b) ? (a) : (b))56#define MAX(a,b) ((a)>(b) ? (a) : (b))5758/**59* Ignore: this is an internal helper.60*61* This is a helper function to help force C99-correctness during compilation.62* Under strict compilation modes, variadic macro arguments can't be empty.63* However, variadic function arguments can be. Using a function therefore lets64* us statically check that at least one (string) argument was passed,65* independent of the compilation flags.66*/67static INLINE_KEYWORD UNUSED_ATTR68void _force_has_format_string(const char *format, ...) {69(void)format;70}7172/**73* Ignore: this is an internal helper.74*75* We want to force this function invocation to be syntactically correct, but76* we don't want to force runtime evaluation of its arguments.77*/78#define _FORCE_HAS_FORMAT_STRING(...) \79if (0) { \80_force_has_format_string(__VA_ARGS__); \81}8283/**84* Return the specified error if the condition evaluates to true.85*86* In debug modes, prints additional information.87* In order to do that (particularly, printing the conditional that failed),88* this can't just wrap RETURN_ERROR().89*/90#define RETURN_ERROR_IF(cond, err, ...) \91if (cond) { \92RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \93__FILE__, __LINE__, ZSTD_QUOTE(cond), ZSTD_QUOTE(ERROR(err))); \94_FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \95RAWLOG(3, ": " __VA_ARGS__); \96RAWLOG(3, "\n"); \97return ERROR(err); \98}99100/**101* Unconditionally return the specified error.102*103* In debug modes, prints additional information.104*/105#define RETURN_ERROR(err, ...) \106do { \107RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \108__FILE__, __LINE__, ZSTD_QUOTE(ERROR(err))); \109_FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \110RAWLOG(3, ": " __VA_ARGS__); \111RAWLOG(3, "\n"); \112return ERROR(err); \113} while(0);114115/**116* If the provided expression evaluates to an error code, returns that error code.117*118* In debug modes, prints additional information.119*/120#define FORWARD_IF_ERROR(err, ...) \121do { \122size_t const err_code = (err); \123if (ERR_isError(err_code)) { \124RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \125__FILE__, __LINE__, ZSTD_QUOTE(err), ERR_getErrorName(err_code)); \126_FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \127RAWLOG(3, ": " __VA_ARGS__); \128RAWLOG(3, "\n"); \129return err_code; \130} \131} while(0);132133134/*-*************************************135* Common constants136***************************************/137#define ZSTD_OPT_NUM (1<<12)138139#define ZSTD_REP_NUM 3 /* number of repcodes */140#define ZSTD_REP_MOVE (ZSTD_REP_NUM-1)141static const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 };142143#define KB *(1 <<10)144#define MB *(1 <<20)145#define GB *(1U<<30)146147#define BIT7 128148#define BIT6 64149#define BIT5 32150#define BIT4 16151#define BIT1 2152#define BIT0 1153154#define ZSTD_WINDOWLOG_ABSOLUTEMIN 10155static const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };156static const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 };157158#define ZSTD_FRAMEIDSIZE 4 /* magic number size */159160#define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */161static const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE;162typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e;163164#define ZSTD_FRAMECHECKSUMSIZE 4165166#define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */167#define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */168169#define HufLog 12170typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e;171172#define LONGNBSEQ 0x7F00173174#define MINMATCH 3175176#define Litbits 8177#define MaxLit ((1<<Litbits) - 1)178#define MaxML 52179#define MaxLL 35180#define DefaultMaxOff 28181#define MaxOff 31182#define MaxSeq MAX(MaxLL, MaxML) /* Assumption : MaxOff < MaxLL,MaxML */183#define MLFSELog 9184#define LLFSELog 9185#define OffFSELog 8186#define MaxFSELog MAX(MAX(MLFSELog, LLFSELog), OffFSELog)187188static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0,1890, 0, 0, 0, 0, 0, 0, 0,1901, 1, 1, 1, 2, 2, 3, 3,1914, 6, 7, 8, 9,10,11,12,19213,14,15,16 };193static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2,1942, 2, 2, 2, 2, 1, 1, 1,1952, 2, 2, 2, 2, 2, 2, 2,1962, 3, 2, 1, 1, 1, 1, 1,197-1,-1,-1,-1 };198#define LL_DEFAULTNORMLOG 6 /* for static allocation */199static const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;200201static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0,2020, 0, 0, 0, 0, 0, 0, 0,2030, 0, 0, 0, 0, 0, 0, 0,2040, 0, 0, 0, 0, 0, 0, 0,2051, 1, 1, 1, 2, 2, 3, 3,2064, 4, 5, 7, 8, 9,10,11,20712,13,14,15,16 };208static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2,2092, 1, 1, 1, 1, 1, 1, 1,2101, 1, 1, 1, 1, 1, 1, 1,2111, 1, 1, 1, 1, 1, 1, 1,2121, 1, 1, 1, 1, 1, 1, 1,2131, 1, 1, 1, 1, 1,-1,-1,214-1,-1,-1,-1,-1 };215#define ML_DEFAULTNORMLOG 6 /* for static allocation */216static const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;217218static const S16 OF_defaultNorm[DefaultMaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2,2192, 1, 1, 1, 1, 1, 1, 1,2201, 1, 1, 1, 1, 1, 1, 1,221-1,-1,-1,-1,-1 };222#define OF_DEFAULTNORMLOG 5 /* for static allocation */223static const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;224225226/*-*******************************************227* Shared functions to include for inlining228*********************************************/229static void ZSTD_copy8(void* dst, const void* src) {230#if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)231vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src));232#else233memcpy(dst, src, 8);234#endif235}236237#define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }238static void ZSTD_copy16(void* dst, const void* src) {239#if !defined(ZSTD_NO_INTRINSICS) && defined(__ARM_NEON)240vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));241#else242memcpy(dst, src, 16);243#endif244}245#define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }246247#define WILDCOPY_OVERLENGTH 32248#define WILDCOPY_VECLEN 16249250typedef enum {251ZSTD_no_overlap,252ZSTD_overlap_src_before_dst253/* ZSTD_overlap_dst_before_src, */254} ZSTD_overlap_e;255256/*! ZSTD_wildcopy() :257* Custom version of memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)258* @param ovtype controls the overlap detection259* - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.260* - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart.261* The src buffer must be before the dst buffer.262*/263MEM_STATIC FORCE_INLINE_ATTR264void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype)265{266ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src;267const BYTE* ip = (const BYTE*)src;268BYTE* op = (BYTE*)dst;269BYTE* const oend = op + length;270271assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN));272273if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {274/* Handle short offset copies. */275do {276COPY8(op, ip)277} while (op < oend);278} else {279assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);280/* Separate out the first COPY16() call because the copy length is281* almost certain to be short, so the branches have different282* probabilities. Since it is almost certain to be short, only do283* one COPY16() in the first call. Then, do two calls per loop since284* at that point it is more likely to have a high trip count.285*/286#ifndef __aarch64__287do {288COPY16(op, ip);289}290while (op < oend);291#else292COPY16(op, ip);293if (op >= oend) return;294do {295COPY16(op, ip);296COPY16(op, ip);297}298while (op < oend);299#endif300}301}302303MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)304{305size_t const length = MIN(dstCapacity, srcSize);306if (length > 0) {307memcpy(dst, src, length);308}309return length;310}311312/* define "workspace is too large" as this number of times larger than needed */313#define ZSTD_WORKSPACETOOLARGE_FACTOR 3314315/* when workspace is continuously too large316* during at least this number of times,317* context's memory usage is considered wasteful,318* because it's sized to handle a worst case scenario which rarely happens.319* In which case, resize it down to free some memory */320#define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128321322323/*-*******************************************324* Private declarations325*********************************************/326typedef struct seqDef_s {327U32 offset;328U16 litLength;329U16 matchLength;330} seqDef;331332typedef struct {333seqDef* sequencesStart;334seqDef* sequences;335BYTE* litStart;336BYTE* lit;337BYTE* llCode;338BYTE* mlCode;339BYTE* ofCode;340size_t maxNbSeq;341size_t maxNbLit;342U32 longLengthID; /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */343U32 longLengthPos;344} seqStore_t;345346typedef struct {347U32 litLength;348U32 matchLength;349} ZSTD_sequenceLength;350351/**352* Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences353* indicated by longLengthPos and longLengthID, and adds MINMATCH back to matchLength.354*/355MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq)356{357ZSTD_sequenceLength seqLen;358seqLen.litLength = seq->litLength;359seqLen.matchLength = seq->matchLength + MINMATCH;360if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {361if (seqStore->longLengthID == 1) {362seqLen.litLength += 0xFFFF;363}364if (seqStore->longLengthID == 2) {365seqLen.matchLength += 0xFFFF;366}367}368return seqLen;369}370371/**372* Contains the compressed frame size and an upper-bound for the decompressed frame size.373* Note: before using `compressedSize`, check for errors using ZSTD_isError().374* similarly, before using `decompressedBound`, check for errors using:375* `decompressedBound != ZSTD_CONTENTSIZE_ERROR`376*/377typedef struct {378size_t compressedSize;379unsigned long long decompressedBound;380} ZSTD_frameSizeInfo; /* decompress & legacy */381382const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */383void ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */384385/* custom memory allocation functions */386void* ZSTD_malloc(size_t size, ZSTD_customMem customMem);387void* ZSTD_calloc(size_t size, ZSTD_customMem customMem);388void ZSTD_free(void* ptr, ZSTD_customMem customMem);389390391MEM_STATIC U32 ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */392{393assert(val != 0);394{395# if defined(_MSC_VER) /* Visual */396unsigned long r=0;397return _BitScanReverse(&r, val) ? (unsigned)r : 0;398# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */399return __builtin_clz (val) ^ 31;400# elif defined(__ICCARM__) /* IAR Intrinsic */401return 31 - __CLZ(val);402# else /* Software version */403static const U32 DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };404U32 v = val;405v |= v >> 1;406v |= v >> 2;407v |= v >> 4;408v |= v >> 8;409v |= v >> 16;410return DeBruijnClz[(v * 0x07C4ACDDU) >> 27];411# endif412}413}414415416/* ZSTD_invalidateRepCodes() :417* ensures next compression will not use repcodes from previous block.418* Note : only works with regular variant;419* do not use with extDict variant ! */420void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */421422423typedef struct {424blockType_e blockType;425U32 lastBlock;426U32 origSize;427} blockProperties_t; /* declared here for decompress and fullbench */428429/*! ZSTD_getcBlockSize() :430* Provides the size of compressed block from block header `src` */431/* Used by: decompress, fullbench (does not get its definition from here) */432size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,433blockProperties_t* bpPtr);434435/*! ZSTD_decodeSeqHeaders() :436* decode sequence header from src */437/* Used by: decompress, fullbench (does not get its definition from here) */438size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,439const void* src, size_t srcSize);440441442#if defined (__cplusplus)443}444#endif445446#endif /* ZSTD_CCOMMON_H_MODULE */447448449