From 447861cb12efeb00861635f206d381486fb3fe11 Mon Sep 17 00:00:00 2001 From: hxsyzl Date: Mon, 10 Feb 2025 09:21:18 +0800 Subject: [PATCH 01/29] Revert "qcacld-3.0: Do not necessarily compile Host Device Driver trace file" This reverts commit d2327fe9ab86926c6caf83e5d0fb34e8ce6352af. --- drivers/staging/qcacld-3.0/Kbuild | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/staging/qcacld-3.0/Kbuild b/drivers/staging/qcacld-3.0/Kbuild index f6d8a660b244..1d9bf3d119eb 100644 --- a/drivers/staging/qcacld-3.0/Kbuild +++ b/drivers/staging/qcacld-3.0/Kbuild @@ -63,6 +63,7 @@ HDD_OBJS := $(HDD_SRC_DIR)/wlan_hdd_assoc.o \ $(HDD_SRC_DIR)/wlan_hdd_scan.o \ $(HDD_SRC_DIR)/wlan_hdd_softap_tx_rx.o \ $(HDD_SRC_DIR)/wlan_hdd_stats.o \ + $(HDD_SRC_DIR)/wlan_hdd_trace.o \ $(HDD_SRC_DIR)/wlan_hdd_tx_rx.o \ $(HDD_SRC_DIR)/wlan_hdd_wext.o \ $(HDD_SRC_DIR)/wlan_hdd_wmm.o \ From 344e758794e4c765add1c789109a720a327d05af Mon Sep 17 00:00:00 2001 From: Helium_Studio <67852324+Helium-Studio@users.noreply.github.com> Date: Sun, 9 Feb 2025 21:19:25 +0800 Subject: [PATCH 02/29] f2fs/dir: Fix mismerge The identifier is missing when using Unicode --- fs/f2fs/dir.c | 1 + 1 file changed, 1 insertion(+) diff --git a/fs/f2fs/dir.c b/fs/f2fs/dir.c index 5ca0eb3ba4a1..e1a7b5ab5960 100644 --- a/fs/f2fs/dir.c +++ b/fs/f2fs/dir.c @@ -80,6 +80,7 @@ int f2fs_init_casefolded_name(const struct inode *dir, struct f2fs_filename *fname) { #ifdef CONFIG_UNICODE + struct super_block *sb = dir->i_sb; if (IS_CASEFOLDED(dir)) { fname->cf_name.name = f2fs_kmem_cache_alloc(f2fs_cf_name_slab, From 504cbacd388bc8b32d4c155a3c73444ac4382a98 Mon Sep 17 00:00:00 2001 From: Helium_Studio <67852324+Helium-Studio@users.noreply.github.com> Date: Sun, 9 Feb 2025 21:24:00 +0800 Subject: [PATCH 03/29] f2fs/dir: Fix mismerge * Remove non-exist sbi identifier --- fs/f2fs/dir.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs/f2fs/dir.c b/fs/f2fs/dir.c index e1a7b5ab5960..37538d120cb3 100644 --- a/fs/f2fs/dir.c +++ b/fs/f2fs/dir.c @@ -87,7 +87,7 @@ int f2fs_init_casefolded_name(const struct inode *dir, GFP_NOFS, false, F2FS_SB(sb)); if (!fname->cf_name.name) return -ENOMEM; - fname->cf_name.len = utf8_casefold(sbi->sb->s_encoding, + fname->cf_name.len = utf8_casefold(sb->s_encoding, fname->usr_fname, fname->cf_name.name, F2FS_NAME_LEN); From 809a7d647414ce09f4b7c1edeb6489696b49c37a Mon Sep 17 00:00:00 2001 From: John Galt Date: Tue, 13 Sep 2022 15:43:53 -0400 Subject: [PATCH 04/29] lz4: slight reset Drop backported single patches in favor of full update to latest v1.9.4 --- lib/lz4/lz4_compress.c | 4 +- lib/lz4/lz4_decompress.c | 413 +++++++-------------------------------- lib/lz4/lz4defs.h | 61 +----- lib/lz4/lz4hc_compress.c | 2 +- 4 files changed, 73 insertions(+), 407 deletions(-) diff --git a/lib/lz4/lz4_compress.c b/lib/lz4/lz4_compress.c index 9d72635d930a..6642c8681c64 100644 --- a/lib/lz4/lz4_compress.c +++ b/lib/lz4/lz4_compress.c @@ -322,7 +322,7 @@ static FORCE_INLINE int LZ4_compress_generic( *token = (BYTE)(litLength << ML_BITS); /* Copy Literals */ - LZ4_wildCopy8(op, anchor, op + litLength); + LZ4_wildCopy(op, anchor, op + litLength); op += litLength; } @@ -628,7 +628,7 @@ static int LZ4_compress_destSize_generic( *token = (BYTE)(litLength << ML_BITS); /* Copy Literals */ - LZ4_wildCopy8(op, anchor, op + litLength); + LZ4_wildCopy(op, anchor, op + litLength); op += litLength; } diff --git a/lib/lz4/lz4_decompress.c b/lib/lz4/lz4_decompress.c index 6be1067b955d..d732cfca46f5 100644 --- a/lib/lz4/lz4_decompress.c +++ b/lib/lz4/lz4_decompress.c @@ -50,96 +50,6 @@ #define assert(condition) ((void)0) #endif -#ifndef LZ4_FAST_DEC_LOOP -#if defined(__i386__) || defined(__x86_64__) -#define LZ4_FAST_DEC_LOOP 1 -#elif defined(__aarch64__) - /* On aarch64, we disable this optimization for clang because on certain - * mobile chipsets and clang, it reduces performance. For more information - * refer to https://github.com/lz4/lz4/pull/707. */ -#define LZ4_FAST_DEC_LOOP 1 -#else -#define LZ4_FAST_DEC_LOOP 0 -#endif -#endif - -#if LZ4_FAST_DEC_LOOP -#define FASTLOOP_SAFE_DISTANCE 64 -FORCE_O2_INLINE_GCC_PPC64LE void -LZ4_memcpy_using_offset_base(BYTE * dstPtr, const BYTE * srcPtr, BYTE * dstEnd, - const size_t offset) -{ - if (offset < 8) { - dstPtr[0] = srcPtr[0]; - - dstPtr[1] = srcPtr[1]; - dstPtr[2] = srcPtr[2]; - dstPtr[3] = srcPtr[3]; - srcPtr += inc32table[offset]; - memcpy(dstPtr + 4, srcPtr, 4); - srcPtr -= dec64table[offset]; - dstPtr += 8; - } else { - memcpy(dstPtr, srcPtr, 8); - dstPtr += 8; - srcPtr += 8; - } - - LZ4_wildCopy8(dstPtr, srcPtr, dstEnd); -} - -/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd - * this version copies two times 16 bytes (instead of one time 32 bytes) - * because it must be compatible with offsets >= 16. */ -FORCE_O2_INLINE_GCC_PPC64LE void -LZ4_wildCopy32(void *dstPtr, const void *srcPtr, void *dstEnd) -{ - BYTE *d = (BYTE *) dstPtr; - const BYTE *s = (const BYTE *)srcPtr; - BYTE *const e = (BYTE *) dstEnd; - - do { - memcpy(d, s, 16); - memcpy(d + 16, s + 16, 16); - d += 32; - s += 32; - } while (d < e); -} - -FORCE_O2_INLINE_GCC_PPC64LE void -LZ4_memcpy_using_offset(BYTE *dstPtr, const BYTE *srcPtr, BYTE *dstEnd, - const size_t offset) -{ - BYTE v[8]; - switch (offset) { - - case 1: - memset(v, *srcPtr, 8); - goto copy_loop; - case 2: - memcpy(v, srcPtr, 2); - memcpy(&v[2], srcPtr, 2); - memcpy(&v[4], &v[0], 4); - goto copy_loop; - case 4: - memcpy(v, srcPtr, 4); - memcpy(&v[4], srcPtr, 4); - goto copy_loop; - default: - LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); - return; - } - - copy_loop: - memcpy(dstPtr, v, 8); - dstPtr += 8; - while (dstPtr < dstEnd) { - memcpy(dstPtr, v, 8); - dstPtr += 8; - } -} -#endif - /* * LZ4_decompress_generic() : * This generic decompression function covers all use cases. @@ -170,28 +80,25 @@ static FORCE_INLINE int LZ4_decompress_generic( const size_t dictSize ) { - const BYTE *ip = (const BYTE *)src; - const BYTE *const iend = ip + srcSize; + const BYTE *ip = (const BYTE *) src; + const BYTE * const iend = ip + srcSize; BYTE *op = (BYTE *) dst; - BYTE *const oend = op + outputSize; + BYTE * const oend = op + outputSize; BYTE *cpy; const BYTE * const dictEnd = (const BYTE *)dictStart + dictSize; + static const unsigned int inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; + static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; const int safeDecode = (endOnInput == endOnInputSize); const int checkOffset = ((safeDecode) && (dictSize < (int)(64 * KB))); /* Set up the "end" pointers for the shortcut. */ const BYTE *const shortiend = iend - - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; const BYTE *const shortoend = oend - - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; - - const BYTE *match; - size_t offset; - unsigned int token; - size_t length; + (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; DEBUGLOG(5, "%s (srcSize:%i, dstSize:%i)", __func__, srcSize, outputSize); @@ -210,196 +117,15 @@ static FORCE_INLINE int LZ4_decompress_generic( if ((endOnInput) && unlikely(srcSize == 0)) return -1; -#if LZ4_FAST_DEC_LOOP - if ((oend - op) < FASTLOOP_SAFE_DISTANCE) { - DEBUGLOG(6, "skip fast decode loop"); - goto safe_decode; - } - - /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ - while (1) { - /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ - assert(oend - op >= FASTLOOP_SAFE_DISTANCE); - if (endOnInput) { - assert(ip < iend); - } - token = *ip++; - length = token >> ML_BITS; /* literal length */ - - assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ - - /* decode literal length */ - if (length == RUN_MASK) { - variable_length_error error = ok; - length += - read_variable_length(&ip, iend - RUN_MASK, - endOnInput, endOnInput, - &error); - if (error == initial_error) { - goto _output_error; - } - if ((safeDecode) - && unlikely((uptrval) (op) + length < - (uptrval) (op))) { - goto _output_error; - } /* overflow detection */ - if ((safeDecode) - && unlikely((uptrval) (ip) + length < - (uptrval) (ip))) { - goto _output_error; - } - - /* overflow detection */ - /* copy literals */ - cpy = op + length; - LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); - if (endOnInput) { /* LZ4_decompress_safe() */ - if ((cpy > oend - 32) - || (ip + length > iend - 32)) { - goto safe_literal_copy; - } - LZ4_wildCopy32(op, ip, cpy); - } else { /* LZ4_decompress_fast() */ - if (cpy > oend - 8) { - goto safe_literal_copy; - } - LZ4_wildCopy8(op, ip, cpy); - /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time */ - /* it doesn't know input length, and only relies on end-of-block */ - /* properties */ - } - ip += length; - op = cpy; - } else { - cpy = op + length; - if (endOnInput) { /* LZ4_decompress_safe() */ - DEBUGLOG(7, - "copy %u bytes in a 16-bytes stripe", - (unsigned)length); - /* We don't need to check oend */ - /* since we check it once for each loop below */ - if (ip > iend - (16 + 1)) { /*max lit + offset + nextToken */ - goto safe_literal_copy; - } - /* Literals can only be 14, but hope compilers optimize */ - /*if we copy by a register size */ - memcpy(op, ip, 16); - } else { - /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time */ - /* it doesn't know input length, and relies on end-of-block */ - /* properties */ - memcpy(op, ip, 8); - if (length > 8) { - memcpy(op + 8, ip + 8, 8); - } - } - ip += length; - op = cpy; - } - - /* get offset */ - offset = LZ4_readLE16(ip); - ip += 2; /* end-of-block condition violated */ - match = op - offset; - - /* get matchlength */ - length = token & ML_MASK; - - if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { - goto _output_error; - } - /* Error : offset outside buffers */ - if (length == ML_MASK) { - variable_length_error error = ok; - length += - read_variable_length(&ip, iend - LASTLITERALS + 1, - endOnInput, 0, &error); - if (error != ok) { - goto _output_error; - } - if ((safeDecode) - && unlikely((uptrval) (op) + length < (uptrval) op)) { - goto _output_error; - } /* overflow detection */ - length += MINMATCH; - if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { - goto safe_match_copy; - } - } else { - length += MINMATCH; - if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { - goto safe_match_copy; - } - - /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ - if (!(dict == usingExtDict) || (match >= lowPrefix)) { - if (offset >= 8) { - memcpy(op, match, 8); - memcpy(op + 8, match + 8, 8); - memcpy(op + 16, match + 16, 2); - op += length; - continue; - } - } - } - - /* match starting within external dictionary */ - if ((dict == usingExtDict) && (match < lowPrefix)) { - if (unlikely(op + length > oend - LASTLITERALS)) { - if (partialDecoding) { - /* reach end of buffer */ - length = - min(length, (size_t) (oend - op)); - } else { - /* end-of-block condition violated */ - goto _output_error; - } - } - - if (length <= (size_t) (lowPrefix - match)) { - /* match fits entirely within external dictionary : just copy */ - memmove(op, dictEnd - (lowPrefix - match), - length); - op += length; - } else { - /* match stretches into both external dict and current block */ - size_t const copySize = - (size_t) (lowPrefix - match); - size_t const restSize = length - copySize; - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - if (restSize > (size_t) (op - lowPrefix)) { /* overlap copy */ - BYTE *const endOfMatch = op + restSize; - const BYTE *copyFrom = lowPrefix; - while (op < endOfMatch) { - *op++ = *copyFrom++; - } - } else { - memcpy(op, lowPrefix, restSize); - op += restSize; - } - } - continue; - } - - /* copy match within block */ - cpy = op + length; - - assert((op <= oend) && (oend - op >= 32)); - if (unlikely(offset < 16)) { - LZ4_memcpy_using_offset(op, match, cpy, offset); - } else { - LZ4_wildCopy32(op, match, cpy); - } - - op = cpy; /* wildcopy correction */ - } - safe_decode: -#endif /* Main Loop : decode sequences */ while (1) { - token = *ip++; - length = token >> ML_BITS; + size_t length; + const BYTE *match; + size_t offset; + + /* get literal length */ + unsigned int const token = *ip++; + length = token>>ML_BITS; /* ip < iend before the increment */ assert(!endOnInput || ip <= iend); @@ -415,32 +141,28 @@ static FORCE_INLINE int LZ4_decompress_generic( * space in the output for those 18 bytes earlier, upon * entering the shortcut (in other words, there is a * combined check for both stages). - * - * The & in the likely() below is intentionally not && so that - * some compilers can produce better parallelized runtime code */ if ((endOnInput ? length != RUN_MASK : length <= 8) - /* - * strictly "less than" on input, to re-enter - * the loop with at least one byte - */ - && likely((endOnInput ? ip < shortiend : 1) & - (op <= shortoend))) { + /* + * strictly "less than" on input, to re-enter + * the loop with at least one byte + */ + && likely((endOnInput ? ip < shortiend : 1) & + (op <= shortoend))) { /* Copy the literals */ LZ4_memcpy(op, ip, endOnInput ? 16 : 8); - op += length; - ip += length; + op += length; ip += length; /* * The second stage: * prepare for match copying, decode full info. * If it doesn't work out, the info won't be wasted. */ - length = token & ML_MASK; /* match length */ + length = token & ML_MASK; /* match length */ offset = LZ4_readLE16(ip); ip += 2; match = op - offset; - assert(match <= op); /* check overflow */ + assert(match <= op); /* check overflow */ /* Do not deal with overlapping matches. */ if ((length != ML_MASK) && @@ -465,24 +187,28 @@ static FORCE_INLINE int LZ4_decompress_generic( /* decode literal length */ if (length == RUN_MASK) { + unsigned int s; - variable_length_error error = ok; - length += - read_variable_length(&ip, iend - RUN_MASK, - endOnInput, endOnInput, - &error); - if (error == initial_error) + if (unlikely(endOnInput ? ip >= iend - RUN_MASK : 0)) { + /* overflow detection */ goto _output_error; + } + do { + s = *ip++; + length += s; + } while (likely(endOnInput + ? ip < iend - RUN_MASK + : 1) & (s == 255)); if ((safeDecode) - && unlikely((uptrval) (op) + - length < (uptrval) (op))) { + && unlikely((uptrval)(op) + + length < (uptrval)(op))) { /* overflow detection */ goto _output_error; } if ((safeDecode) - && unlikely((uptrval) (ip) + - length < (uptrval) (ip))) { + && unlikely((uptrval)(ip) + + length < (uptrval)(ip))) { /* overflow detection */ goto _output_error; } @@ -490,15 +216,11 @@ static FORCE_INLINE int LZ4_decompress_generic( /* copy literals */ cpy = op + length; -#if LZ4_FAST_DEC_LOOP - safe_literal_copy: -#endif LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); if (((endOnInput) && ((cpy > oend - MFLIMIT) - || (ip + length > - iend - (2 + 1 + LASTLITERALS)))) - || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { + || (ip + length > iend - (2 + 1 + LASTLITERALS)))) + || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { if (partialDecoding) { if (cpy > oend) { /* @@ -509,7 +231,7 @@ static FORCE_INLINE int LZ4_decompress_generic( length = oend - op; } if ((endOnInput) - && (ip + length > iend)) { + && (ip + length > iend)) { /* * Error : * read attempt beyond @@ -519,7 +241,7 @@ static FORCE_INLINE int LZ4_decompress_generic( } } else { if ((!endOnInput) - && (cpy != oend)) { + && (cpy != oend)) { /* * Error : * block decoding must @@ -528,7 +250,7 @@ static FORCE_INLINE int LZ4_decompress_generic( goto _output_error; } if ((endOnInput) - && ((ip + length != iend) + && ((ip + length != iend) || (cpy > oend))) { /* * Error : @@ -538,24 +260,16 @@ static FORCE_INLINE int LZ4_decompress_generic( } } - /* - * supports overlapping memory regions; only matters - * for in-place decompression scenarios - */ - LZ4_memmove(op, ip, length); + LZ4_memcpy(op, ip, length); ip += length; op += length; - /* Necessarily EOF when !partialDecoding. - * When partialDecoding, it is EOF if we've either - * filled the output buffer or - * can't proceed with reading an offset for following match. - */ - if (!partialDecoding || (cpy == oend) || (ip >= (iend - 2))) + /* Necessarily EOF, due to parsing restrictions */ + if (!partialDecoding || (cpy == oend)) break; } else { /* may overwrite up to WILDCOPYLENGTH beyond cpy */ - LZ4_wildCopy8(op, ip, cpy); + LZ4_wildCopy(op, ip, cpy); ip += length; op = cpy; } @@ -574,14 +288,29 @@ static FORCE_INLINE int LZ4_decompress_generic( goto _output_error; } + /* costs ~1%; silence an msan warning when offset == 0 */ + /* + * note : when partialDecoding, there is no guarantee that + * at least 4 bytes remain available in output buffer + */ + if (!partialDecoding) { + assert(oend > op); + assert(oend - op >= 4); + + LZ4_write32(op, (U32)offset); + } + if (length == ML_MASK) { + unsigned int s; - variable_length_error error = ok; - length += - read_variable_length(&ip, iend - LASTLITERALS + 1, - endOnInput, 0, &error); - if (error != ok) - goto _output_error; + do { + s = *ip++; + + if ((endOnInput) && (ip > iend - LASTLITERALS)) + goto _output_error; + + length += s; + } while (s == 255); if ((safeDecode) && unlikely( @@ -593,10 +322,6 @@ static FORCE_INLINE int LZ4_decompress_generic( length += MINMATCH; -#if LZ4_FAST_DEC_LOOP -safe_match_copy: -#endif - /* match starting within external dictionary */ if ((dict == usingExtDict) && (match < lowPrefix)) { if (unlikely(op + length > oend - LASTLITERALS)) { @@ -693,7 +418,7 @@ static FORCE_INLINE int LZ4_decompress_generic( } if (op < oCopyLimit) { - LZ4_wildCopy8(op, match, oCopyLimit); + LZ4_wildCopy(op, match, oCopyLimit); match += oCopyLimit - op; op = oCopyLimit; } @@ -702,7 +427,7 @@ static FORCE_INLINE int LZ4_decompress_generic( } else { LZ4_copy8(op, match); if (length > 16) - LZ4_wildCopy8(op + 8, match + 8, cpy); + LZ4_wildCopy(op + 8, match + 8, cpy); } op = cpy; /* wildcopy correction */ } diff --git a/lib/lz4/lz4defs.h b/lib/lz4/lz4defs.h index 7015a2c9ccb8..c91dd96ef629 100644 --- a/lib/lz4/lz4defs.h +++ b/lib/lz4/lz4defs.h @@ -40,28 +40,6 @@ #define FORCE_INLINE __always_inline -/* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE - * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8, - * together with a simple 8-byte copy loop as a fall-back path. - * However, this optimization hurts the decompression speed by >30%, - * because the execution does not go to the optimized loop - * for typical compressible data, and all of the preamble checks - * before going to the fall-back path become useless overhead. - * This optimization happens only with the -O3 flag, and -O2 generates - * a simple 8-byte copy loop. - * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8 - * functions are annotated with __attribute__((optimize("O2"))), - * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute - * of LZ4_wildCopy8 does not affect the compression speed. - */ -#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__) -# define FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2"))) -# define FORCE_O2_INLINE_GCC_PPC64LE (__attribute__((optimize("O2"))) FORCE_INLINE) -#else -# define FORCE_O2_GCC_PPC64LE FORCE_INLINE -# define FORCE_O2_INLINE_GCC_PPC64LE FORCE_INLINE -#endif - /*-************************************ * Basic Types **************************************/ @@ -121,9 +99,6 @@ typedef uintptr_t uptrval; #define RUN_BITS (8 - ML_BITS) #define RUN_MASK ((1U << RUN_BITS) - 1) -static const unsigned inc32table[8] = { 0, 1, 2, 1, 0, 4, 4, 4 }; -static const int dec64table[8] = { 0, 0, 0, -1, -4, 1, 2, 3 }; - /*-************************************ * Reading and writing into memory **************************************/ @@ -171,7 +146,6 @@ static FORCE_INLINE void LZ4_writeLE16(void *memPtr, U16 value) * environments. This is needed when decompressing the Linux Kernel, for example. */ #define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) -#define LZ4_memmove(dst, src, size) __builtin_memmove(dst, src, size) static FORCE_INLINE void LZ4_copy8(void *dst, const void *src) { @@ -192,7 +166,7 @@ static FORCE_INLINE void LZ4_copy8(void *dst, const void *src) * customized variant of memcpy, * which can overwrite up to 7 bytes beyond dstEnd */ -static FORCE_O2_INLINE_GCC_PPC64LE void LZ4_wildCopy8(void *dstPtr, +static FORCE_INLINE void LZ4_wildCopy(void *dstPtr, const void *srcPtr, void *dstEnd) { BYTE *d = (BYTE *)dstPtr; @@ -256,39 +230,6 @@ static FORCE_INLINE unsigned int LZ4_count( return (unsigned int)(pIn - pStart); } -/* Read the variable-length literal or match length. - * - * ip - pointer to use as input. - * lencheck - end ip. Return an error if ip advances >= lencheck. - * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so. - * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so. - * error (output) - error code. Should be set to 0 before call. - */ -typedef enum { loop_error = -2, initial_error = -1, ok = 0} variable_length_error; -static FORCE_INLINE unsigned read_variable_length(const BYTE **ip, - const BYTE *lencheck, - int loop_check, int initial_check, - variable_length_error *error) -{ - unsigned length = 0; - unsigned s; - if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ - *error = initial_error; - return length; - } - do { - s = **ip; - (*ip)++; - length += s; - if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ - *error = loop_error; - return length; - } - } while (s == 255); - - return length; -} - typedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive; typedef enum { byPtr, byU32, byU16 } tableType_t; diff --git a/lib/lz4/lz4hc_compress.c b/lib/lz4/lz4hc_compress.c index 0fa1bdc6832e..e7ac8694b797 100644 --- a/lib/lz4/lz4hc_compress.c +++ b/lib/lz4/lz4hc_compress.c @@ -293,7 +293,7 @@ static FORCE_INLINE int LZ4HC_encodeSequence( *token = (BYTE)(length< Date: Wed, 29 Jun 2022 19:16:02 +0200 Subject: [PATCH 05/29] lib: Update LZ4 module to v1.9.3+ Update lz4 module using official repository from revision [1]. Keep in mind lz4hc wasn't updated thus it is not used. It may not compile anymore. [1]: https://github.com/lz4/lz4/tree/4ebe313e00aa52c837ee029ede39a0503a8a39c9 --- include/linux/lz4.h | 159 +++-- lib/lz4/lz4_compress.c | 1395 ++++++++++++++++++++++---------------- lib/lz4/lz4_decompress.c | 1199 ++++++++++++++++++++------------ lib/lz4/lz4defs.h | 129 ++-- 4 files changed, 1749 insertions(+), 1133 deletions(-) diff --git a/include/linux/lz4.h b/include/linux/lz4.h index 3ca5fbae0840..edd32c93718d 100644 --- a/include/linux/lz4.h +++ b/include/linux/lz4.h @@ -42,7 +42,7 @@ #define __LZ4_H__ #include -#include /* memset, memcpy */ +#include /* memset, memcpy */ /*-************************************************************************ * CONSTANTS @@ -57,23 +57,24 @@ */ #define LZ4_MEMORY_USAGE 16 -#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ -#define LZ4_COMPRESSBOUND(isize) (\ - (unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE \ - ? 0 \ - : (isize) + ((isize)/255) + 16) +#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ +#define LZ4_COMPRESSBOUND(isize) \ + ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? \ + 0 : \ + (isize) + ((isize) / 255) + 16) #define LZ4_ACCELERATION_DEFAULT 1 -#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) +#define LZ4_ACCELERATION_MAX 65537 +#define LZ4_HASHLOG (LZ4_MEMORY_USAGE - 2) #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) -#define LZ4HC_MIN_CLEVEL 3 -#define LZ4HC_DEFAULT_CLEVEL 9 -#define LZ4HC_MAX_CLEVEL 16 +#define LZ4HC_MIN_CLEVEL 3 +#define LZ4HC_DEFAULT_CLEVEL 9 +#define LZ4HC_MAX_CLEVEL 16 #define LZ4HC_DICTIONARY_LOGSIZE 16 -#define LZ4HC_MAXD (1< compression run slower on incompressible data */ +static const U32 LZ4_skipTrigger = 6; + +LZ4_stream_t *LZ4_initStream(void *buffer, size_t size); /*-****************************** * Compression functions ********************************/ -static FORCE_INLINE U32 LZ4_hash4( - U32 sequence, - tableType_t const tableType) +static FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType) { if (tableType == byU16) - return ((sequence * 2654435761U) - >> ((MINMATCH * 8) - (LZ4_HASHLOG + 1))); + return ((sequence * 2654435761U) >> + ((MINMATCH * 8) - (LZ4_HASHLOG + 1))); else - return ((sequence * 2654435761U) - >> ((MINMATCH * 8) - LZ4_HASHLOG)); + return ((sequence * 2654435761U) >> + ((MINMATCH * 8) - LZ4_HASHLOG)); } -static FORCE_INLINE U32 LZ4_hash5( - U64 sequence, - tableType_t const tableType) +static FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType) { - const U32 hashLog = (tableType == byU16) - ? LZ4_HASHLOG + 1 - : LZ4_HASHLOG; + const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG + 1 : + LZ4_HASHLOG; #if LZ4_LITTLE_ENDIAN static const U64 prime5bytes = 889523592379ULL; @@ -76,245 +75,454 @@ static FORCE_INLINE U32 LZ4_hash5( #endif } -static FORCE_INLINE U32 LZ4_hashPosition( - const void *p, - tableType_t const tableType) +static FORCE_INLINE U32 LZ4_hashPosition(const void *p, + tableType_t const tableType) { #if LZ4_ARCH64 - if (tableType == byU32) + if (tableType != byU16) return LZ4_hash5(LZ4_read_ARCH(p), tableType); #endif return LZ4_hash4(LZ4_read32(p), tableType); } -static void LZ4_putPositionOnHash( - const BYTE *p, - U32 h, - void *tableBase, - tableType_t const tableType, - const BYTE *srcBase) +static FORCE_INLINE void LZ4_clearHash(U32 h, void *tableBase, + tableType_t const tableType) { switch (tableType) { - case byPtr: - { + default: /* fallthrough */ + case clearedTable: { /* illegal! */ + assert(0); + return; + } + case byPtr: { + const BYTE **hashTable = (const BYTE **)tableBase; + hashTable[h] = NULL; + return; + } + case byU32: { + U32 *hashTable = (U32 *)tableBase; + hashTable[h] = 0; + return; + } + case byU16: { + U16 *hashTable = (U16 *)tableBase; + hashTable[h] = 0; + return; + } + } +} + +static FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void *tableBase, + tableType_t const tableType) +{ + switch (tableType) { + default: /* fallthrough */ + case clearedTable: /* fallthrough */ + case byPtr: { /* illegal! */ + assert(0); + return; + } + case byU32: { + U32 *hashTable = (U32 *)tableBase; + hashTable[h] = idx; + return; + } + case byU16: { + U16 *hashTable = (U16 *)tableBase; + assert(idx < 65536); + hashTable[h] = (U16)idx; + return; + } + } +} + +static void LZ4_putPositionOnHash(const BYTE *p, U32 h, void *tableBase, + tableType_t const tableType, + const BYTE *srcBase) +{ + switch (tableType) { + case byPtr: { const BYTE **hashTable = (const BYTE **)tableBase; hashTable[h] = p; return; } - case byU32: - { - U32 *hashTable = (U32 *) tableBase; + case byU32: { + U32 *hashTable = (U32 *)tableBase; hashTable[h] = (U32)(p - srcBase); return; } - case byU16: - { - U16 *hashTable = (U16 *) tableBase; + case byU16: { + U16 *hashTable = (U16 *)tableBase; hashTable[h] = (U16)(p - srcBase); return; } + case clearedTable: { /* fallthrough */ + } } } -static FORCE_INLINE void LZ4_putPosition( - const BYTE *p, - void *tableBase, - tableType_t tableType, - const BYTE *srcBase) +static FORCE_INLINE void LZ4_putPosition(const BYTE *p, void *tableBase, + tableType_t tableType, + const BYTE *srcBase) { U32 const h = LZ4_hashPosition(p, tableType); LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); } -static const BYTE *LZ4_getPositionOnHash( - U32 h, - void *tableBase, - tableType_t tableType, - const BYTE *srcBase) +/* LZ4_getIndexOnHash() : + * Index of match position registered in hash table. + * hash position must be calculated by using base+index, or dictBase+index. + * Assumption 1 : only valid if tableType == byU32 or byU16. + * Assumption 2 : h is presumed valid (within limits of hash table) + */ +static FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void *tableBase, + tableType_t tableType) +{ + LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); + if (tableType == byU32) { + const U32 *const hashTable = (const U32 *)tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE - 2))); + return hashTable[h]; + } + if (tableType == byU16) { + const U16 *const hashTable = (const U16 *)tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE - 1))); + return hashTable[h]; + } + assert(0); + return 0; /* forbidden case */ +} + +static const BYTE *LZ4_getPositionOnHash(U32 h, void *tableBase, + tableType_t tableType, + const BYTE *srcBase) { if (tableType == byPtr) { - const BYTE **hashTable = (const BYTE **) tableBase; + const BYTE **hashTable = (const BYTE **)tableBase; return hashTable[h]; } if (tableType == byU32) { - const U32 * const hashTable = (U32 *) tableBase; + const U32 *const hashTable = (U32 *)tableBase; return hashTable[h] + srcBase; } { /* default, to ensure a return */ - const U16 * const hashTable = (U16 *) tableBase; + const U16 *const hashTable = (U16 *)tableBase; return hashTable[h] + srcBase; } } -static FORCE_INLINE const BYTE *LZ4_getPosition( - const BYTE *p, - void *tableBase, - tableType_t tableType, - const BYTE *srcBase) +static FORCE_INLINE const BYTE *LZ4_getPosition(const BYTE *p, void *tableBase, + tableType_t tableType, + const BYTE *srcBase) { U32 const h = LZ4_hashPosition(p, tableType); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); } +static FORCE_INLINE void LZ4_prepareTable(LZ4_stream_t_internal *const cctx, + const int inputSize, + const tableType_t tableType) +{ + /* If the table hasn't been used, it's guaranteed to be zeroed out, and is + * therefore safe to use no matter what mode we're in. Otherwise, we figure + * out if it's safe to leave as is or whether it needs to be reset. + */ + if ((tableType_t)cctx->tableType != clearedTable) { + assert(inputSize >= 0); + if ((tableType_t)cctx->tableType != tableType || + ((tableType == byU16) && + cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU) || + ((tableType == byU32) && cctx->currentOffset > 1 * GB) || + tableType == byPtr || inputSize >= 4 * KB) { + DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", + cctx); + memset(cctx->hashTable, 0, LZ4_HASHTABLESIZE); + cctx->currentOffset = 0; + cctx->tableType = (U32)clearedTable; + } else { + DEBUGLOG( + 4, + "LZ4_prepareTable: Re-use hash table (no reset)"); + } + } + + /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, + * is faster than compressing without a gap. + * However, compressing with currentOffset == 0 is faster still, + * so we preserve that case. + */ + if (cctx->currentOffset != 0 && tableType == byU32) { + DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); + cctx->currentOffset += 64 * KB; + } -/* - * LZ4_compress_generic() : - * inlined, to ensure branches are decided at compilation time + /* Finally, clear history */ + cctx->dictCtx = NULL; + cctx->dictionary = NULL; + cctx->dictSize = 0; +} + +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time. + * Presumed already validated at this stage: + * - source != NULL + * - inputSize > 0 */ -static FORCE_INLINE int LZ4_compress_generic( - LZ4_stream_t_internal * const dictPtr, - const char * const source, - char * const dest, - const int inputSize, - const int maxOutputSize, - const limitedOutput_directive outputLimited, - const tableType_t tableType, - const dict_directive dict, - const dictIssue_directive dictIssue, - const U32 acceleration) +static FORCE_INLINE int LZ4_compress_generic_validated( + LZ4_stream_t_internal *const cctx, const char *const source, + char *const dest, const int inputSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ + const int maxOutputSize, const limitedOutput_directive outputDirective, + const tableType_t tableType, const dict_directive dictDirective, + const dictIssue_directive dictIssue, const int acceleration) { - const BYTE *ip = (const BYTE *) source; - const BYTE *base; + int result; + const BYTE *ip = (const BYTE *)source; + + U32 const startIndex = cctx->currentOffset; + const BYTE *base = (const BYTE *)source - startIndex; const BYTE *lowLimit; - const BYTE * const lowRefLimit = ip - dictPtr->dictSize; - const BYTE * const dictionary = dictPtr->dictionary; - const BYTE * const dictEnd = dictionary + dictPtr->dictSize; - const size_t dictDelta = dictEnd - (const BYTE *)source; - const BYTE *anchor = (const BYTE *) source; - const BYTE * const iend = ip + inputSize; - const BYTE * const mflimit = iend - MFLIMIT; - const BYTE * const matchlimit = iend - LASTLITERALS; - - BYTE *op = (BYTE *) dest; - BYTE * const olimit = op + maxOutputSize; + const LZ4_stream_t_internal *dictCtx = + (const LZ4_stream_t_internal *)cctx->dictCtx; + const BYTE *const dictionary = dictDirective == usingDictCtx ? + dictCtx->dictionary : + cctx->dictionary; + const U32 dictSize = dictDirective == usingDictCtx ? dictCtx->dictSize : + cctx->dictSize; + const U32 dictDelta = + (dictDirective == usingDictCtx) ? + startIndex - dictCtx->currentOffset : + 0; /* make indexes in dictCtx comparable with index in current context */ + + int const maybe_extMem = (dictDirective == usingExtDict) || + (dictDirective == usingDictCtx); + U32 const prefixIdxLimit = + startIndex - + dictSize; /* used when dictDirective == dictSmall */ + const BYTE *const dictEnd = dictionary ? dictionary + dictSize : + dictionary; + const BYTE *anchor = (const BYTE *)source; + const BYTE *const iend = ip + inputSize; + const BYTE *const mflimitPlusOne = iend - MFLIMIT + 1; + const BYTE *const matchlimit = iend - LASTLITERALS; + + /* the dictCtx currentOffset is indexed on the start of the dictionary, + * while a dictionary in the current context precedes the currentOffset */ + const BYTE *dictBase = + (dictionary == NULL) ? + NULL : + (dictDirective == usingDictCtx) ? + dictionary + dictSize - dictCtx->currentOffset : + dictionary + dictSize - startIndex; + + BYTE *op = (BYTE *)dest; + BYTE *const olimit = op + maxOutputSize; + + U32 offset = 0; U32 forwardH; - size_t refDelta = 0; - /* Init conditions */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) { - /* Unsupported inputSize, too large (or negative) */ + DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", + inputSize, tableType); + assert(ip != NULL); + /* If init conditions are not met, we don't have to mark stream + * as having dirty context, since no action was taken yet */ + if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; - } - - switch (dict) { - case noDict: - default: - base = (const BYTE *)source; - lowLimit = (const BYTE *)source; - break; - case withPrefix64k: - base = (const BYTE *)source - dictPtr->currentOffset; - lowLimit = (const BYTE *)source - dictPtr->dictSize; - break; - case usingExtDict: - base = (const BYTE *)source - dictPtr->currentOffset; - lowLimit = (const BYTE *)source; - break; - } - - if ((tableType == byU16) - && (inputSize >= LZ4_64Klimit)) { - /* Size too large (not within 64K limit) */ + } /* Impossible to store anything */ + if ((tableType == byU16) && (inputSize >= LZ4_64Klimit)) { return 0; + } /* Size too large (not within 64K limit) */ + if (tableType == byPtr) + assert(dictDirective == + noDict); /* only supported use case with byPtr */ + assert(acceleration >= 1); + + lowLimit = (const BYTE *)source - + (dictDirective == withPrefix64k ? dictSize : 0); + + /* Update context state */ + if (dictDirective == usingDictCtx) { + /* Subsequent linked blocks can't use the dictionary. */ + /* Instead, they use the block we just compressed. */ + cctx->dictCtx = NULL; + cctx->dictSize = (U32)inputSize; + } else { + cctx->dictSize += (U32)inputSize; } + cctx->currentOffset += (U32)inputSize; + cctx->tableType = (U32)tableType; - if (inputSize < LZ4_minLength) { - /* Input too small, no compression (all literals) */ - goto _last_literals; - } + if (inputSize < LZ4_minLength) + goto _last_literals; /* Input too small, no compression (all literals) */ /* First Byte */ - LZ4_putPosition(ip, dictPtr->hashTable, tableType, base); + LZ4_putPosition(ip, cctx->hashTable, tableType, base); ip++; forwardH = LZ4_hashPosition(ip, tableType); /* Main Loop */ - for ( ; ; ) { + for (;;) { const BYTE *match; BYTE *token; + const BYTE *filledIp; /* Find a match */ - { + if (tableType == byPtr) { const BYTE *forwardIp = ip; - unsigned int step = 1; - unsigned int searchMatchNb = acceleration << LZ4_SKIPTRIGGER; - + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; do { U32 const h = forwardH; - ip = forwardIp; forwardIp += step; - step = (searchMatchNb++ >> LZ4_SKIPTRIGGER); + step = (searchMatchNb++ >> LZ4_skipTrigger); - if (unlikely(forwardIp > mflimit)) + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); + + match = LZ4_getPositionOnHash( + h, cctx->hashTable, tableType, base); + forwardH = + LZ4_hashPosition(forwardIp, tableType); + LZ4_putPositionOnHash(ip, h, cctx->hashTable, + tableType, base); - match = LZ4_getPositionOnHash(h, - dictPtr->hashTable, - tableType, base); + } while ((match + LZ4_DISTANCE_MAX < ip) || + (LZ4_read32(match) != LZ4_read32(ip))); - if (dict == usingExtDict) { - if (match < (const BYTE *)source) { - refDelta = dictDelta; + } else { /* byU32, byU16 */ + + const BYTE *forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + U32 const cur = (U32)(forwardIp - base); + U32 matchIndex = LZ4_getIndexOnHash( + h, cctx->hashTable, tableType); + assert(matchIndex <= cur); + assert(forwardIp - base < + (ptrdiff_t)(2 * GB - 1)); + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) + goto _last_literals; + assert(ip < mflimitPlusOne); + + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + assert(tableType == byU32); + matchIndex = LZ4_getIndexOnHash( + h, dictCtx->hashTable, + byU32); + match = dictBase + matchIndex; + matchIndex += + dictDelta; /* make dictCtx index comparable with current context */ + lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE *)source; + } + } else if (dictDirective == usingExtDict) { + if (matchIndex < startIndex) { + DEBUGLOG( + 7, + "extDict candidate: matchIndex=%5u < startIndex=%5u", + matchIndex, startIndex); + assert(startIndex - + matchIndex >= + MINMATCH); + assert(dictBase); + match = dictBase + matchIndex; lowLimit = dictionary; } else { - refDelta = 0; + match = base + matchIndex; lowLimit = (const BYTE *)source; - } } - - forwardH = LZ4_hashPosition(forwardIp, - tableType); - - LZ4_putPositionOnHash(ip, h, dictPtr->hashTable, - tableType, base); - } while (((dictIssue == dictSmall) - ? (match < lowRefLimit) - : 0) - || ((tableType == byU16) - ? 0 - : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match + refDelta) - != LZ4_read32(ip))); + } + } else { /* single continuous memory segment */ + match = base + matchIndex; + } + forwardH = + LZ4_hashPosition(forwardIp, tableType); + LZ4_putIndexOnHash(cur, h, cctx->hashTable, + tableType); + + DEBUGLOG(7, + "candidate at pos=%u (offset=%u \n", + matchIndex, cur - matchIndex); + if ((dictIssue == dictSmall) && + (matchIndex < prefixIdxLimit)) { + continue; + } /* match outside of valid area */ + assert(matchIndex < cur); + if (((tableType != byU16) || + (LZ4_DISTANCE_MAX < + LZ4_DISTANCE_ABSOLUTE_MAX)) && + (matchIndex + LZ4_DISTANCE_MAX < cur)) { + continue; + } /* too far */ + assert((cur - matchIndex) <= + LZ4_DISTANCE_MAX); /* match now expected within distance */ + + if (LZ4_read32(match) == LZ4_read32(ip)) { + if (maybe_extMem) + offset = cur - matchIndex; + break; /* match found */ + } + + } while (1); } /* Catch up */ - while (((ip > anchor) & (match + refDelta > lowLimit)) - && (unlikely(ip[-1] == match[refDelta - 1]))) { + filledIp = ip; + while (((ip > anchor) & (match > lowLimit)) && + (unlikely(ip[-1] == match[-1]))) { ip--; match--; } /* Encode Literals */ { - unsigned const int litLength = (unsigned int)(ip - anchor); - + unsigned const litLength = (unsigned)(ip - anchor); token = op++; - - if ((outputLimited) && - /* Check output buffer overflow */ - (unlikely(op + litLength + - (2 + 1 + LASTLITERALS) + - (litLength / 255) > olimit))) - return 0; - + if ((outputDirective == + limitedOutput) && /* Check output buffer overflow */ + (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + + (litLength / 255) > + olimit))) { + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + if ((outputDirective == fillOutput) && + (unlikely( + op + (litLength + 240) / 255 /* litlen */ + + litLength /* literals */ + + 2 /* offset */ + 1 /* token */ + + MFLIMIT - + MINMATCH /* min last literals so last match is <= end - MFLIMIT */ + > olimit))) { + op--; + goto _last_literals; + } if (litLength >= RUN_MASK) { - int len = (int)litLength - RUN_MASK; - + int len = (int)(litLength - RUN_MASK); *token = (RUN_MASK << ML_BITS); - for (; len >= 255; len -= 255) *op++ = 255; *op++ = (BYTE)len; @@ -322,103 +530,222 @@ static FORCE_INLINE int LZ4_compress_generic( *token = (BYTE)(litLength << ML_BITS); /* Copy Literals */ - LZ4_wildCopy(op, anchor, op + litLength); + LZ4_wildCopy8(op, anchor, op + litLength); op += litLength; + DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor - (const BYTE *)source), + litLength, (int)(ip - (const BYTE *)source)); } _next_match: + /* at this stage, the following variables must be correctly set : + * - ip : at start of LZ operation + * - match : at start of previous pattern occurrence; can be within current prefix, or within extDict + * - offset : if maybe_ext_memSegment==1 (constant) + * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise + * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written + */ + + if ((outputDirective == fillOutput) && + (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - + MINMATCH /* min last literals so last match is <= end - MFLIMIT */ + > olimit)) { + /* the match was too close to the end, rewind and go to last literals */ + op = token; + goto _last_literals; + } + /* Encode Offset */ - LZ4_writeLE16(op, (U16)(ip - match)); - op += 2; + if (maybe_extMem) { /* static test */ + DEBUGLOG(6, + " with offset=%u (ext if > %i)", + offset, (int)(ip - (const BYTE *)source)); + assert(offset <= LZ4_DISTANCE_MAX && offset > 0); + LZ4_writeLE16(op, (U16)offset); + op += 2; + } else { + DEBUGLOG(6, + " with offset=%u (same segment)", + (U32)(ip - match)); + assert(ip - match <= LZ4_DISTANCE_MAX); + LZ4_writeLE16(op, (U16)(ip - match)); + op += 2; + } /* Encode MatchLength */ { - unsigned int matchCode; - - if ((dict == usingExtDict) - && (lowLimit == dictionary)) { - const BYTE *limit; - - match += refDelta; - limit = ip + (dictEnd - match); - + unsigned matchCode; + + if ((dictDirective == usingExtDict || + dictDirective == usingDictCtx) && + (lowLimit == + dictionary) /* match within extDict */) { + const BYTE *limit = ip + (dictEnd - match); + assert(dictEnd > match); if (limit > matchlimit) limit = matchlimit; - matchCode = LZ4_count(ip + MINMATCH, - match + MINMATCH, limit); - - ip += MINMATCH + matchCode; - + match + MINMATCH, limit); + ip += (size_t)matchCode + MINMATCH; if (ip == limit) { - unsigned const int more = LZ4_count(ip, - (const BYTE *)source, + unsigned const more = LZ4_count( + limit, (const BYTE *)source, matchlimit); - matchCode += more; ip += more; } + DEBUGLOG( + 6, + " with matchLength=%u starting in extDict", + matchCode + MINMATCH); } else { matchCode = LZ4_count(ip + MINMATCH, - match + MINMATCH, matchlimit); - ip += MINMATCH + matchCode; + match + MINMATCH, + matchlimit); + ip += (size_t)matchCode + MINMATCH; + DEBUGLOG(6, " with matchLength=%u", + matchCode + MINMATCH); } - if (outputLimited && - /* Check output buffer overflow */ - (unlikely(op + - (1 + LASTLITERALS) + - (matchCode >> 8) > olimit))) - return 0; - + if ((outputDirective) && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + + (matchCode + 240) / 255 > + olimit))) { + if (outputDirective == fillOutput) { + /* Match description too long : reduce it */ + U32 newMatchCode = + 15 /* in token */ - + 1 /* to avoid needing a zero byte */ + + ((U32)(olimit - op) - 1 - + LASTLITERALS) * + 255; + ip -= matchCode - newMatchCode; + assert(newMatchCode < matchCode); + matchCode = newMatchCode; + if (unlikely(ip <= filledIp)) { + /* We have already filled up to filledIp so if ip ends up less than filledIp + * we have positions in the hash table beyond the current position. This is + * a problem if we reuse the hash table. So we have to remove these positions + * from the hash table. + */ + const BYTE *ptr; + DEBUGLOG( + 5, + "Clearing %u positions", + (U32)(filledIp - ip)); + for (ptr = ip; ptr <= filledIp; + ++ptr) { + U32 const h = + LZ4_hashPosition( + ptr, + tableType); + LZ4_clearHash( + h, + cctx->hashTable, + tableType); + } + } + } else { + assert(outputDirective == + limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } if (matchCode >= ML_MASK) { *token += ML_MASK; matchCode -= ML_MASK; LZ4_write32(op, 0xFFFFFFFF); - while (matchCode >= 4 * 255) { op += 4; LZ4_write32(op, 0xFFFFFFFF); matchCode -= 4 * 255; } - op += matchCode / 255; *op++ = (BYTE)(matchCode % 255); } else *token += (BYTE)(matchCode); } + /* Ensure we have enough space for the last literals. */ + assert(!(outputDirective == fillOutput && + op + 1 + LASTLITERALS > olimit)); anchor = ip; /* Test end of chunk */ - if (ip > mflimit) + if (ip >= mflimitPlusOne) break; /* Fill table */ - LZ4_putPosition(ip - 2, dictPtr->hashTable, tableType, base); + LZ4_putPosition(ip - 2, cctx->hashTable, tableType, base); /* Test next position */ - match = LZ4_getPosition(ip, dictPtr->hashTable, - tableType, base); - - if (dict == usingExtDict) { - if (match < (const BYTE *)source) { - refDelta = dictDelta; - lowLimit = dictionary; - } else { - refDelta = 0; - lowLimit = (const BYTE *)source; + if (tableType == byPtr) { + match = LZ4_getPosition(ip, cctx->hashTable, tableType, + base); + LZ4_putPosition(ip, cctx->hashTable, tableType, base); + if ((match + LZ4_DISTANCE_MAX >= ip) && + (LZ4_read32(match) == LZ4_read32(ip))) { + token = op++; + *token = 0; + goto _next_match; } - } - - LZ4_putPosition(ip, dictPtr->hashTable, tableType, base); - if (((dictIssue == dictSmall) ? (match >= lowRefLimit) : 1) - && (match + MAX_DISTANCE >= ip) - && (LZ4_read32(match + refDelta) == LZ4_read32(ip))) { - token = op++; - *token = 0; - goto _next_match; + } else { /* byU32, byU16 */ + + U32 const h = LZ4_hashPosition(ip, tableType); + U32 const cur = (U32)(ip - base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, + tableType); + assert(matchIndex < cur); + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + matchIndex = LZ4_getIndexOnHash( + h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + lowLimit = + dictionary; /* required for match length counter */ + matchIndex += dictDelta; + } else { + match = base + matchIndex; + lowLimit = (const BYTE *) + source; /* required for match length counter */ + } + } else if (dictDirective == usingExtDict) { + if (matchIndex < startIndex) { + assert(dictBase); + match = dictBase + matchIndex; + lowLimit = + dictionary; /* required for match length counter */ + } else { + match = base + matchIndex; + lowLimit = (const BYTE *) + source; /* required for match length counter */ + } + } else { /* single memory segment */ + match = base + matchIndex; + } + LZ4_putIndexOnHash(cur, h, cctx->hashTable, tableType); + assert(matchIndex < cur); + if (((dictIssue == dictSmall) ? + (matchIndex >= prefixIdxLimit) : + 1) && + (((tableType == byU16) && + (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? + 1 : + (matchIndex + LZ4_DISTANCE_MAX >= cur)) && + (LZ4_read32(match) == LZ4_read32(ip))) { + token = op++; + *token = 0; + if (maybe_extMem) + offset = cur - matchIndex; + DEBUGLOG( + 6, + "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor - (const BYTE *)source), 0, + (int)(ip - (const BYTE *)source)); + goto _next_match; + } } /* Prepare next loop */ @@ -428,398 +755,286 @@ static FORCE_INLINE int LZ4_compress_generic( _last_literals: /* Encode Last Literals */ { - size_t const lastRun = (size_t)(iend - anchor); - - if ((outputLimited) && - /* Check output buffer overflow */ - ((op - (BYTE *)dest) + lastRun + 1 + - ((lastRun + 255 - RUN_MASK) / 255) > (U32)maxOutputSize)) - return 0; - + size_t lastRun = (size_t)(iend - anchor); + if ((outputDirective) && /* Check output buffer overflow */ + (op + lastRun + 1 + ((lastRun + 255 - RUN_MASK) / 255) > + olimit)) { + if (outputDirective == fillOutput) { + /* adapt lastRun to fill 'dst' */ + assert(olimit >= op); + lastRun = (size_t)(olimit - op) - 1 /*token*/; + lastRun -= (lastRun + 256 - RUN_MASK) / + 256; /*additional length tokens*/ + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun); if (lastRun >= RUN_MASK) { size_t accumulator = lastRun - RUN_MASK; *op++ = RUN_MASK << ML_BITS; for (; accumulator >= 255; accumulator -= 255) *op++ = 255; - *op++ = (BYTE) accumulator; + *op++ = (BYTE)accumulator; } else { *op++ = (BYTE)(lastRun << ML_BITS); } - LZ4_memcpy(op, anchor, lastRun); - + ip = anchor + lastRun; op += lastRun; } - /* End */ - return (int) (((char *)op) - dest); + if (outputDirective == fillOutput) { + *inputConsumed = (int)(((const char *)ip) - source); + } + result = (int)(((char *)op) - dest); + assert(result > 0); + DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", + inputSize, result); + return result; } -static int LZ4_compress_fast_extState( - void *state, - const char *source, - char *dest, - int inputSize, - int maxOutputSize, - int acceleration) +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time; + * takes care of src == (NULL, 0) + * and forward the rest to LZ4_compress_generic_validated */ +static FORCE_INLINE int LZ4_compress_generic( + LZ4_stream_t_internal *const cctx, const char *const src, + char *const dst, const int srcSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ + const int dstCapacity, const limitedOutput_directive outputDirective, + const tableType_t tableType, const dict_directive dictDirective, + const dictIssue_directive dictIssue, const int acceleration) { - LZ4_stream_t_internal *ctx = &((LZ4_stream_t *)state)->internal_donotuse; -#if LZ4_ARCH64 - const tableType_t tableType = byU32; -#else - const tableType_t tableType = byPtr; -#endif + DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i", srcSize, + dstCapacity); - LZ4_resetStream((LZ4_stream_t *)state); + if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { + return 0; + } /* Unsupported srcSize, too large (or negative) */ + if (srcSize == 0) { /* src == NULL supported if srcSize == 0 */ + if (outputDirective != notLimited && dstCapacity <= 0) + return 0; /* no output, can't write anything */ + DEBUGLOG(5, "Generating an empty block"); + assert(outputDirective == notLimited || dstCapacity >= 1); + assert(dst != NULL); + dst[0] = 0; + if (outputDirective == fillOutput) { + assert(inputConsumed != NULL); + *inputConsumed = 0; + } + return 1; + } + assert(src != NULL); + + return LZ4_compress_generic_validated( + cctx, src, dst, srcSize, + inputConsumed, /* only written into if outputDirective == fillOutput */ + dstCapacity, outputDirective, tableType, dictDirective, + dictIssue, acceleration); +} +int LZ4_compress_fast_extState(void *state, const char *source, char *dest, + int inputSize, int maxOutputSize, + int acceleration) +{ + LZ4_stream_t_internal *const ctx = + &LZ4_initStream(state, sizeof(LZ4_stream_t))->internal_donotuse; + assert(ctx != NULL); if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; - - if (maxOutputSize >= LZ4_COMPRESSBOUND(inputSize)) { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, - dest, inputSize, 0, - noLimit, byU16, noDict, - noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, - dest, inputSize, 0, - noLimit, tableType, noDict, - noDictIssue, acceleration); + if (acceleration > LZ4_ACCELERATION_MAX) + acceleration = LZ4_ACCELERATION_MAX; + if (maxOutputSize >= LZ4_compressBound(inputSize)) { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, + inputSize, NULL, 0, + notLimited, byU16, noDict, + noDictIssue, acceleration); + } else { + const tableType_t tableType = + ((sizeof(void *) == 4) && + ((uptrval)source > LZ4_DISTANCE_MAX)) ? + byPtr : + byU32; + return LZ4_compress_generic(ctx, source, dest, + inputSize, NULL, 0, + notLimited, tableType, + noDict, noDictIssue, + acceleration); + } } else { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, - dest, inputSize, + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic( + ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, - dest, inputSize, + } else { + const tableType_t tableType = + ((sizeof(void *) == 4) && + ((uptrval)source > LZ4_DISTANCE_MAX)) ? + byPtr : + byU32; + return LZ4_compress_generic( + ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } } } int LZ4_compress_fast(const char *source, char *dest, int inputSize, - int maxOutputSize, int acceleration, void *wrkmem) + int maxOutputSize, int acceleration, void *wrkmem) { return LZ4_compress_fast_extState(wrkmem, source, dest, inputSize, - maxOutputSize, acceleration); + maxOutputSize, acceleration); } EXPORT_SYMBOL(LZ4_compress_fast); int LZ4_compress_default(const char *source, char *dest, int inputSize, - int maxOutputSize, void *wrkmem) + int maxOutputSize, void *wrkmem) { - return LZ4_compress_fast(source, dest, inputSize, - maxOutputSize, LZ4_ACCELERATION_DEFAULT, wrkmem); + return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, + LZ4_ACCELERATION_DEFAULT, wrkmem); } EXPORT_SYMBOL(LZ4_compress_default); -/*-****************************** - * *_destSize() variant - ********************************/ -static int LZ4_compress_destSize_generic( - LZ4_stream_t_internal * const ctx, - const char * const src, - char * const dst, - int * const srcSizePtr, - const int targetDstSize, - const tableType_t tableType) +static int LZ4_compress_destSize_extState(LZ4_stream_t *state, const char *src, + char *dst, int *srcSizePtr, + int targetDstSize) { - const BYTE *ip = (const BYTE *) src; - const BYTE *base = (const BYTE *) src; - const BYTE *lowLimit = (const BYTE *) src; - const BYTE *anchor = ip; - const BYTE * const iend = ip + *srcSizePtr; - const BYTE * const mflimit = iend - MFLIMIT; - const BYTE * const matchlimit = iend - LASTLITERALS; - - BYTE *op = (BYTE *) dst; - BYTE * const oend = op + targetDstSize; - BYTE * const oMaxLit = op + targetDstSize - 2 /* offset */ - - 8 /* because 8 + MINMATCH == MFLIMIT */ - 1 /* token */; - BYTE * const oMaxMatch = op + targetDstSize - - (LASTLITERALS + 1 /* token */); - BYTE * const oMaxSeq = oMaxLit - 1 /* token */; - - U32 forwardH; - - /* Init conditions */ - /* Impossible to store anything */ - if (targetDstSize < 1) - return 0; - /* Unsupported input size, too large (or negative) */ - if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) - return 0; - /* Size too large (not within 64K limit) */ - if ((tableType == byU16) && (*srcSizePtr >= LZ4_64Klimit)) - return 0; - /* Input too small, no compression (all literals) */ - if (*srcSizePtr < LZ4_minLength) - goto _last_literals; - - /* First Byte */ - *srcSizePtr = 0; - LZ4_putPosition(ip, ctx->hashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); - - /* Main Loop */ - for ( ; ; ) { - const BYTE *match; - BYTE *token; - - /* Find a match */ - { - const BYTE *forwardIp = ip; - unsigned int step = 1; - unsigned int searchMatchNb = 1 << LZ4_SKIPTRIGGER; - - do { - U32 h = forwardH; - - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_SKIPTRIGGER); - - if (unlikely(forwardIp > mflimit)) - goto _last_literals; - - match = LZ4_getPositionOnHash(h, ctx->hashTable, - tableType, base); - forwardH = LZ4_hashPosition(forwardIp, - tableType); - LZ4_putPositionOnHash(ip, h, - ctx->hashTable, tableType, - base); - - } while (((tableType == byU16) - ? 0 - : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match) != LZ4_read32(ip))); - } - - /* Catch up */ - while ((ip > anchor) - && (match > lowLimit) - && (unlikely(ip[-1] == match[-1]))) { - ip--; - match--; - } - - /* Encode Literal length */ - { - unsigned int litLength = (unsigned int)(ip - anchor); - - token = op++; - if (op + ((litLength + 240) / 255) - + litLength > oMaxLit) { - /* Not enough space for a last match */ - op--; - goto _last_literals; - } - if (litLength >= RUN_MASK) { - unsigned int len = litLength - RUN_MASK; - *token = (RUN_MASK<= 255; len -= 255) - *op++ = 255; - *op++ = (BYTE)len; - } else - *token = (BYTE)(litLength << ML_BITS); - - /* Copy Literals */ - LZ4_wildCopy(op, anchor, op + litLength); - op += litLength; - } - -_next_match: - /* Encode Offset */ - LZ4_writeLE16(op, (U16)(ip - match)); op += 2; - - /* Encode MatchLength */ - { - size_t matchLength = LZ4_count(ip + MINMATCH, - match + MINMATCH, matchlimit); - - if (op + ((matchLength + 240)/255) > oMaxMatch) { - /* Match description too long : reduce it */ - matchLength = (15 - 1) + (oMaxMatch - op) * 255; - } - ip += MINMATCH + matchLength; - - if (matchLength >= ML_MASK) { - *token += ML_MASK; - matchLength -= ML_MASK; - while (matchLength >= 255) { - matchLength -= 255; - *op++ = 255; - } - *op++ = (BYTE)matchLength; - } else - *token += (BYTE)(matchLength); - } - - anchor = ip; - - /* Test end of block */ - if (ip > mflimit) - break; - if (op > oMaxSeq) - break; - - /* Fill table */ - LZ4_putPosition(ip - 2, ctx->hashTable, tableType, base); - - /* Test next position */ - match = LZ4_getPosition(ip, ctx->hashTable, tableType, base); - LZ4_putPosition(ip, ctx->hashTable, tableType, base); - - if ((match + MAX_DISTANCE >= ip) - && (LZ4_read32(match) == LZ4_read32(ip))) { - token = op++; *token = 0; - goto _next_match; - } - - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - } - -_last_literals: - /* Encode Last Literals */ - { - size_t lastRunSize = (size_t)(iend - anchor); - - if (op + 1 /* token */ - + ((lastRunSize + 240) / 255) /* litLength */ - + lastRunSize /* literals */ > oend) { - /* adapt lastRunSize to fill 'dst' */ - lastRunSize = (oend - op) - 1; - lastRunSize -= (lastRunSize + 240) / 255; - } - ip = anchor + lastRunSize; - - if (lastRunSize >= RUN_MASK) { - size_t accumulator = lastRunSize - RUN_MASK; - - *op++ = RUN_MASK << ML_BITS; - for (; accumulator >= 255; accumulator -= 255) - *op++ = 255; - *op++ = (BYTE) accumulator; + void *const s = LZ4_initStream(state, sizeof(*state)); + assert(s != NULL); + (void)s; + + if (targetDstSize >= + LZ4_compressBound( + *srcSizePtr)) { /* compression success is guaranteed */ + return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, + targetDstSize, 1); + } else { + if (*srcSizePtr < LZ4_64Klimit) { + return LZ4_compress_generic(&state->internal_donotuse, + src, dst, *srcSizePtr, + srcSizePtr, targetDstSize, + fillOutput, byU16, noDict, + noDictIssue, 1); } else { - *op++ = (BYTE)(lastRunSize< LZ4_DISTANCE_MAX)) ? + byPtr : + byU32; + return LZ4_compress_generic(&state->internal_donotuse, + src, dst, *srcSizePtr, + srcSizePtr, targetDstSize, + fillOutput, addrMode, + noDict, noDictIssue, 1); } - memcpy(op, anchor, lastRunSize); - op += lastRunSize; } - - /* End */ - *srcSizePtr = (int) (((const char *)ip) - src); - return (int) (((char *)op) - dst); } -static int LZ4_compress_destSize_extState( - LZ4_stream_t *state, - const char *src, - char *dst, - int *srcSizePtr, - int targetDstSize) -{ -#if LZ4_ARCH64 - const tableType_t tableType = byU32; -#else - const tableType_t tableType = byPtr; -#endif - - LZ4_resetStream(state); - - if (targetDstSize >= LZ4_COMPRESSBOUND(*srcSizePtr)) { - /* compression success is guaranteed */ - return LZ4_compress_fast_extState( - state, src, dst, *srcSizePtr, - targetDstSize, 1); - } else { - if (*srcSizePtr < LZ4_64Klimit) - return LZ4_compress_destSize_generic( - &state->internal_donotuse, - src, dst, srcSizePtr, - targetDstSize, byU16); - else - return LZ4_compress_destSize_generic( - &state->internal_donotuse, - src, dst, srcSizePtr, - targetDstSize, tableType); - } -} - - -int LZ4_compress_destSize( - const char *src, - char *dst, - int *srcSizePtr, - int targetDstSize, - void *wrkmem) +int LZ4_compress_destSize(const char *src, char *dst, int *srcSizePtr, + int targetDstSize, void *wrkmem) { return LZ4_compress_destSize_extState(wrkmem, src, dst, srcSizePtr, - targetDstSize); + targetDstSize); } EXPORT_SYMBOL(LZ4_compress_destSize); /*-****************************** * Streaming functions ********************************/ +static size_t LZ4_stream_t_alignment(void) +{ + typedef struct { + char c; + LZ4_stream_t t; + } t_a; + return sizeof(t_a) - sizeof(LZ4_stream_t); +} + +static int LZ4_isAligned(const void *ptr, size_t alignment) +{ + return ((size_t)ptr & (alignment - 1)) == 0; +} + +LZ4_stream_t *LZ4_initStream(void *buffer, size_t size) +{ + DEBUGLOG(5, "LZ4_initStream"); + if (buffer == NULL) { + return NULL; + } + if (size < sizeof(LZ4_stream_t)) { + return NULL; + } + if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) + return NULL; + memset(buffer, 0, sizeof(LZ4_stream_t_internal)); + return (LZ4_stream_t *)buffer; +} + void LZ4_resetStream(LZ4_stream_t *LZ4_stream) { - memset(LZ4_stream, 0, sizeof(LZ4_stream_t)); + memset(LZ4_stream, 0, sizeof(LZ4_stream_t_internal)); } -int LZ4_loadDict(LZ4_stream_t *LZ4_dict, - const char *dictionary, int dictSize) +int LZ4_loadDict(LZ4_stream_t *LZ4_dict, const char *dictionary, int dictSize) { LZ4_stream_t_internal *dict = &LZ4_dict->internal_donotuse; + const tableType_t tableType = byU32; const BYTE *p = (const BYTE *)dictionary; - const BYTE * const dictEnd = p + dictSize; + const BYTE *const dictEnd = p + dictSize; const BYTE *base; - if ((dict->initCheck) - || (dict->currentOffset > 1 * GB)) { - /* Uninitialized structure, or reuse overflow */ - LZ4_resetStream(LZ4_dict); - } + DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, + dictionary, LZ4_dict); + + /* It's necessary to reset the context, + * and not just continue it with prepareTable() + * to avoid any risk of generating overflowing matchIndex + * when compressing using this dictionary */ + LZ4_resetStream(LZ4_dict); + + /* We always increment the offset by 64 KB, since, if the dict is longer, + * we truncate it to the last 64k, and if it's shorter, we still want to + * advance by a whole window length so we can provide the guarantee that + * there are only valid offsets in the window, which allows an optimization + * in LZ4_compress_fast_continue() where it uses noDictIssue even when the + * dictionary isn't a full 64k. */ + dict->currentOffset += 64 * KB; if (dictSize < (int)HASH_UNIT) { - dict->dictionary = NULL; - dict->dictSize = 0; return 0; } if ((dictEnd - p) > 64 * KB) p = dictEnd - 64 * KB; - dict->currentOffset += 64 * KB; - base = p - dict->currentOffset; + base = dictEnd - dict->currentOffset; dict->dictionary = p; dict->dictSize = (U32)(dictEnd - p); - dict->currentOffset += dict->dictSize; + dict->tableType = (U32)tableType; while (p <= dictEnd - HASH_UNIT) { - LZ4_putPosition(p, dict->hashTable, byU32, base); + LZ4_putPosition(p, dict->hashTable, tableType, base); p += 3; } - return dict->dictSize; + return (int)dict->dictSize; } EXPORT_SYMBOL(LZ4_loadDict); -static void LZ4_renormDictT(LZ4_stream_t_internal *LZ4_dict, - const BYTE *src) +static void LZ4_renormDictT(LZ4_stream_t_internal *LZ4_dict, int nextSize) { - if ((LZ4_dict->currentOffset > 0x80000000) || - ((uptrval)LZ4_dict->currentOffset > (uptrval)src)) { - /* address space overflow */ + assert(nextSize >= 0); + if (LZ4_dict->currentOffset + (unsigned)nextSize > + 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ /* rescale hash table */ U32 const delta = LZ4_dict->currentOffset - 64 * KB; const BYTE *dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; int i; - + DEBUGLOG(4, "LZ4_renormDictT"); for (i = 0; i < LZ4_HASH_SIZE_U32; i++) { if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i] = 0; @@ -835,17 +1050,26 @@ static void LZ4_renormDictT(LZ4_stream_t_internal *LZ4_dict, int LZ4_saveDict(LZ4_stream_t *LZ4_dict, char *safeBuffer, int dictSize) { - LZ4_stream_t_internal * const dict = &LZ4_dict->internal_donotuse; - const BYTE * const previousDictEnd = dict->dictionary + dict->dictSize; + LZ4_stream_t_internal *const dict = &LZ4_dict->internal_donotuse; + + DEBUGLOG(5, "LZ4_saveDict : dictSize=%i, safeBuffer=%p", dictSize, + safeBuffer); if ((U32)dictSize > 64 * KB) { - /* useless to define a dictionary > 64 * KB */ dictSize = 64 * KB; + } /* useless to define a dictionary > 64 KB */ + if ((U32)dictSize > dict->dictSize) { + dictSize = (int)dict->dictSize; } - if ((U32)dictSize > dict->dictSize) - dictSize = dict->dictSize; - memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + if (safeBuffer == NULL) + assert(dictSize == 0); + if (dictSize > 0) { + const BYTE *const previousDictEnd = + dict->dictionary + dict->dictSize; + assert(dict->dictionary); + LZ4_memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + } dict->dictionary = (const BYTE *)safeBuffer; dict->dictSize = (U32)dictSize; @@ -855,82 +1079,121 @@ int LZ4_saveDict(LZ4_stream_t *LZ4_dict, char *safeBuffer, int dictSize) EXPORT_SYMBOL(LZ4_saveDict); int LZ4_compress_fast_continue(LZ4_stream_t *LZ4_stream, const char *source, - char *dest, int inputSize, int maxOutputSize, int acceleration) + char *dest, int inputSize, int maxOutputSize, + int acceleration) { - LZ4_stream_t_internal *streamPtr = &LZ4_stream->internal_donotuse; - const BYTE * const dictEnd = streamPtr->dictionary - + streamPtr->dictSize; - - const BYTE *smallest = (const BYTE *) source; - - if (streamPtr->initCheck) { - /* Uninitialized structure detected */ - return 0; - } - - if ((streamPtr->dictSize > 0) && (smallest > dictEnd)) - smallest = dictEnd; + const tableType_t tableType = byU32; + LZ4_stream_t_internal *const streamPtr = &LZ4_stream->internal_donotuse; + const char *dictEnd = streamPtr->dictSize ? + (const char *)streamPtr->dictionary + + streamPtr->dictSize : + NULL; - LZ4_renormDictT(streamPtr, smallest); + DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i, dictSize=%u)", + inputSize, streamPtr->dictSize); + LZ4_renormDictT(streamPtr, inputSize); /* fix index overflow */ if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) + acceleration = LZ4_ACCELERATION_MAX; + + /* invalidate tiny dictionaries */ + if ((streamPtr->dictSize < + 4) /* tiny dictionary : not enough for a hash */ + && (dictEnd != source) /* prefix mode */ + && + (inputSize > + 0) /* tolerance : don't lose history, in case next invocation would use prefix mode */ + && (streamPtr->dictCtx == NULL) /* usingDictCtx */ + ) { + DEBUGLOG( + 5, + "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", + streamPtr->dictSize, streamPtr->dictionary); + /* remove dictionary existence from history, to employ faster prefix mode */ + streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE *)source; + dictEnd = source; + } /* Check overlapping input/dictionary space */ { - const BYTE *sourceEnd = (const BYTE *) source + inputSize; - - if ((sourceEnd > streamPtr->dictionary) - && (sourceEnd < dictEnd)) { + const char *const sourceEnd = source + inputSize; + if ((sourceEnd > (const char *)streamPtr->dictionary) && + (sourceEnd < dictEnd)) { streamPtr->dictSize = (U32)(dictEnd - sourceEnd); if (streamPtr->dictSize > 64 * KB) streamPtr->dictSize = 64 * KB; if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; - streamPtr->dictionary = dictEnd - streamPtr->dictSize; + streamPtr->dictionary = + (const BYTE *)dictEnd - streamPtr->dictSize; } } /* prefix mode : source data follows dictionary */ - if (dictEnd == (const BYTE *)source) { - int result; - + if (dictEnd == source) { if ((streamPtr->dictSize < 64 * KB) && - (streamPtr->dictSize < streamPtr->currentOffset)) { - result = LZ4_compress_generic( - streamPtr, source, dest, inputSize, - maxOutputSize, limitedOutput, byU32, + (streamPtr->dictSize < streamPtr->currentOffset)) + return LZ4_compress_generic( + streamPtr, source, dest, inputSize, NULL, + maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); - } else { - result = LZ4_compress_generic( - streamPtr, source, dest, inputSize, - maxOutputSize, limitedOutput, byU32, + else + return LZ4_compress_generic( + streamPtr, source, dest, inputSize, NULL, + maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); - } - streamPtr->dictSize += (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - return result; } /* external dictionary mode */ { int result; - - if ((streamPtr->dictSize < 64 * KB) && - (streamPtr->dictSize < streamPtr->currentOffset)) { - result = LZ4_compress_generic( - streamPtr, source, dest, inputSize, - maxOutputSize, limitedOutput, byU32, - usingExtDict, dictSmall, acceleration); - } else { - result = LZ4_compress_generic( - streamPtr, source, dest, inputSize, - maxOutputSize, limitedOutput, byU32, - usingExtDict, noDictIssue, acceleration); + if (streamPtr->dictCtx) { + /* We depend here on the fact that dictCtx'es (produced by + * LZ4_loadDict) guarantee that their tables contain no references + * to offsets between dictCtx->currentOffset - 64 KB and + * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe + * to use noDictIssue even when the dict isn't a full 64 KB. + */ + if (inputSize > 4 * KB) { + /* For compressing large blobs, it is faster to pay the setup + * cost to copy the dictionary's tables into the active context, + * so that the compression loop is only looking into one table. + */ + LZ4_memcpy(streamPtr, streamPtr->dictCtx, + sizeof(*streamPtr)); + result = LZ4_compress_generic( + streamPtr, source, dest, inputSize, + NULL, maxOutputSize, limitedOutput, + tableType, usingExtDict, noDictIssue, + acceleration); + } else { + result = LZ4_compress_generic( + streamPtr, source, dest, inputSize, + NULL, maxOutputSize, limitedOutput, + tableType, usingDictCtx, noDictIssue, + acceleration); + } + } else { /* small data <= 4 KB */ + if ((streamPtr->dictSize < 64 * KB) && + (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic( + streamPtr, source, dest, inputSize, + NULL, maxOutputSize, limitedOutput, + tableType, usingExtDict, dictSmall, + acceleration); + } else { + result = LZ4_compress_generic( + streamPtr, source, dest, inputSize, + NULL, maxOutputSize, limitedOutput, + tableType, usingExtDict, noDictIssue, + acceleration); + } } streamPtr->dictionary = (const BYTE *)source; streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; return result; } } diff --git a/lib/lz4/lz4_decompress.c b/lib/lz4/lz4_decompress.c index d732cfca46f5..5e0ff76e55e0 100644 --- a/lib/lz4/lz4_decompress.c +++ b/lib/lz4/lz4_decompress.c @@ -44,12 +44,134 @@ * Decompression functions *******************************/ -#define DEBUGLOG(l, ...) {} /* disabled */ +#define LZ4_FAST_DEC_LOOP 1 -#ifndef assert -#define assert(condition) ((void)0) +static const unsigned inc32table[8] = { 0, 1, 2, 1, 0, 4, 4, 4 }; +static const int dec64table[8] = { 0, 0, 0, -1, -4, 1, 2, 3 }; + +#if LZ4_FAST_DEC_LOOP + +static FORCE_INLINE void LZ4_memcpy_using_offset_base(BYTE *dstPtr, + const BYTE *srcPtr, + BYTE *dstEnd, + const size_t offset) +{ + assert(srcPtr + offset == dstPtr); + if (offset < 8) { + LZ4_write32(dstPtr, + 0); /* silence an msan warning when offset==0 */ + dstPtr[0] = srcPtr[0]; + dstPtr[1] = srcPtr[1]; + dstPtr[2] = srcPtr[2]; + dstPtr[3] = srcPtr[3]; + srcPtr += inc32table[offset]; + LZ4_memcpy(dstPtr + 4, srcPtr, 4); + srcPtr -= dec64table[offset]; + dstPtr += 8; + } else { + LZ4_memcpy(dstPtr, srcPtr, 8); + dstPtr += 8; + srcPtr += 8; + } + + LZ4_wildCopy8(dstPtr, srcPtr, dstEnd); +} + +/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd + * this version copies two times 16 bytes (instead of one time 32 bytes) + * because it must be compatible with offsets >= 16. */ +static FORCE_INLINE void LZ4_wildCopy32(void *dstPtr, const void *srcPtr, + void *dstEnd) +{ + BYTE *d = (BYTE *)dstPtr; + const BYTE *s = (const BYTE *)srcPtr; + BYTE *const e = (BYTE *)dstEnd; + + do { + LZ4_memcpy(d, s, 16); + LZ4_memcpy(d + 16, s + 16, 16); + d += 32; + s += 32; + } while (d < e); +} + +/* LZ4_memcpy_using_offset() presumes : + * - dstEnd >= dstPtr + MINMATCH + * - there is at least 8 bytes available to write after dstEnd */ +static FORCE_INLINE void LZ4_memcpy_using_offset(BYTE *dstPtr, + const BYTE *srcPtr, + BYTE *dstEnd, + const size_t offset) +{ + BYTE v[8]; + + assert(dstEnd >= dstPtr + MINMATCH); + + switch (offset) { + case 1: + memset(v, *srcPtr, 8); + break; + case 2: + LZ4_memcpy(v, srcPtr, 2); + LZ4_memcpy(&v[2], srcPtr, 2); + LZ4_memcpy(&v[4], v, 4); + break; + case 4: + LZ4_memcpy(v, srcPtr, 4); + LZ4_memcpy(&v[4], srcPtr, 4); + break; + default: + LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); + return; + } + + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + while (dstPtr < dstEnd) { + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + } +} #endif +/* Read the variable-length literal or match length. + * + * ip - pointer to use as input. + * lencheck - end ip. Return an error if ip advances >= lencheck. + * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so. + * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so. + * error (output) - error code. Should be set to 0 before call. + */ +typedef enum { + loop_error = -2, + initial_error = -1, + ok = 0 +} variable_length_error; +static FORCE_INLINE unsigned +read_variable_length(const BYTE **ip, const BYTE *lencheck, int loop_check, + int initial_check, variable_length_error *error) +{ + U32 length = 0; + U32 s; + if (initial_check && + unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = initial_error; + return length; + } + do { + s = **ip; + (*ip)++; + length += s; + if (loop_check && + unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = loop_error; + return length; + } + } while (s == 255); + + return length; +} + /* * LZ4_decompress_generic() : * This generic decompression function covers all use cases. @@ -57,419 +179,643 @@ * Note that it is important for performance that this function really get inlined, * in order to remove useless branches during compilation optimization. */ -static FORCE_INLINE int LZ4_decompress_generic( - const char * const src, - char * const dst, - int srcSize, - /* +static FORCE_INLINE int +LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, + /* * If endOnInput == endOnInputSize, * this value is `dstCapacity` */ - int outputSize, - /* endOnOutputSize, endOnInputSize */ - endCondition_directive endOnInput, - /* full, partial */ - earlyEnd_directive partialDecoding, - /* noDict, withPrefix64k, usingExtDict */ - dict_directive dict, - /* always <= dst, == dst when no prefix */ - const BYTE * const lowPrefix, - /* only if dict == usingExtDict */ - const BYTE * const dictStart, - /* note : = 0 if noDict */ - const size_t dictSize - ) + int outputSize, + /* endOnOutputSize, endOnInputSize */ + endCondition_directive endOnInput, + /* full, partial */ + earlyEnd_directive partialDecoding, + /* noDict, withPrefix64k, usingExtDict */ + dict_directive dict, + /* always <= dst, == dst when no prefix */ + const BYTE *const lowPrefix, + /* only if dict == usingExtDict */ + const BYTE *const dictStart, + /* note : = 0 if noDict */ + const size_t dictSize) { - const BYTE *ip = (const BYTE *) src; - const BYTE * const iend = ip + srcSize; - - BYTE *op = (BYTE *) dst; - BYTE * const oend = op + outputSize; - BYTE *cpy; - - const BYTE * const dictEnd = (const BYTE *)dictStart + dictSize; - static const unsigned int inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; - static const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; - - const int safeDecode = (endOnInput == endOnInputSize); - const int checkOffset = ((safeDecode) && (dictSize < (int)(64 * KB))); - - /* Set up the "end" pointers for the shortcut. */ - const BYTE *const shortiend = iend - - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; - const BYTE *const shortoend = oend - - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; + if ((src == NULL) || (outputSize < 0)) { + return -1; + } - DEBUGLOG(5, "%s (srcSize:%i, dstSize:%i)", __func__, - srcSize, outputSize); + { + const BYTE *ip = (const BYTE *)src; + const BYTE *const iend = ip + srcSize; - /* Special cases */ - assert(lowPrefix <= op); - assert(src != NULL); + BYTE *op = (BYTE *)dst; + BYTE *const oend = op + outputSize; + BYTE *cpy; - /* Empty output buffer */ - if ((endOnInput) && (unlikely(outputSize == 0))) - return ((srcSize == 1) && (*ip == 0)) ? 0 : -1; + const BYTE *const dictEnd = + (dictStart == NULL) ? NULL : dictStart + dictSize; - if ((!endOnInput) && (unlikely(outputSize == 0))) - return (*ip == 0 ? 1 : -1); + const int safeDecode = (endOnInput == endOnInputSize); + const int checkOffset = + ((safeDecode) && (dictSize < (int)(64 * KB))); - if ((endOnInput) && unlikely(srcSize == 0)) - return -1; + /* Set up the "end" pointers for the shortcut. */ + const BYTE *const shortiend = + iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + const BYTE *const shortoend = + oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; - /* Main Loop : decode sequences */ - while (1) { - size_t length; const BYTE *match; size_t offset; + unsigned token; + size_t length; - /* get literal length */ - unsigned int const token = *ip++; - length = token>>ML_BITS; - - /* ip < iend before the increment */ - assert(!endOnInput || ip <= iend); - - /* - * A two-stage shortcut for the most common case: - * 1) If the literal length is 0..14, and there is enough - * space, enter the shortcut and copy 16 bytes on behalf - * of the literals (in the fast mode, only 8 bytes can be - * safely copied this way). - * 2) Further if the match length is 4..18, copy 18 bytes - * in a similar manner; but we ensure that there's enough - * space in the output for those 18 bytes earlier, upon - * entering the shortcut (in other words, there is a - * combined check for both stages). - */ - if ((endOnInput ? length != RUN_MASK : length <= 8) - /* - * strictly "less than" on input, to re-enter - * the loop with at least one byte - */ - && likely((endOnInput ? ip < shortiend : 1) & - (op <= shortoend))) { - /* Copy the literals */ - LZ4_memcpy(op, ip, endOnInput ? 16 : 8); - op += length; ip += length; - - /* - * The second stage: - * prepare for match copying, decode full info. - * If it doesn't work out, the info won't be wasted. - */ - length = token & ML_MASK; /* match length */ - offset = LZ4_readLE16(ip); - ip += 2; - match = op - offset; - assert(match <= op); /* check overflow */ - - /* Do not deal with overlapping matches. */ - if ((length != ML_MASK) && - (offset >= 8) && - (dict == withPrefix64k || match >= lowPrefix)) { - /* Copy the match. */ - LZ4_memcpy(op + 0, match + 0, 8); - LZ4_memcpy(op + 8, match + 8, 8); - LZ4_memcpy(op + 16, match + 16, 2); - op += length + MINMATCH; - /* Both stages worked, load the next token. */ - continue; - } + DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", + srcSize, outputSize); - /* - * The second stage didn't work out, but the info - * is ready. Propel it right to the point of match - * copying. - */ - goto _copy_match; + /* Special cases */ + assert(lowPrefix <= op); + if ((endOnInput) && (unlikely(outputSize == 0))) { + /* Empty output buffer */ + if (partialDecoding) + return 0; + return ((srcSize == 1) && (*ip == 0)) ? 0 : -1; + } + if ((!endOnInput) && (unlikely(outputSize == 0))) { + return (*ip == 0 ? 1 : -1); + } + if ((endOnInput) && unlikely(srcSize == 0)) { + return -1; } - /* decode literal length */ - if (length == RUN_MASK) { - unsigned int s; - - if (unlikely(endOnInput ? ip >= iend - RUN_MASK : 0)) { - /* overflow detection */ - goto _output_error; - } - do { - s = *ip++; - length += s; - } while (likely(endOnInput - ? ip < iend - RUN_MASK - : 1) & (s == 255)); - - if ((safeDecode) - && unlikely((uptrval)(op) + - length < (uptrval)(op))) { - /* overflow detection */ - goto _output_error; - } - if ((safeDecode) - && unlikely((uptrval)(ip) + - length < (uptrval)(ip))) { - /* overflow detection */ - goto _output_error; - } + /* Currently the fast loop shows a regression on qualcomm arm chips. */ +#if LZ4_FAST_DEC_LOOP + if ((oend - op) < FASTLOOP_SAFE_DISTANCE) { + DEBUGLOG(6, "skip fast decode loop"); + goto safe_decode; } - /* copy literals */ - cpy = op + length; - LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); - - if (((endOnInput) && ((cpy > oend - MFLIMIT) - || (ip + length > iend - (2 + 1 + LASTLITERALS)))) - || ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { - if (partialDecoding) { - if (cpy > oend) { - /* - * Partial decoding : - * stop in the middle of literal segment - */ - cpy = oend; - length = oend - op; + /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ + while (1) { + /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ + assert(oend - op >= FASTLOOP_SAFE_DISTANCE); + if (endOnInput) { + assert(ip < iend); + } + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || + ip <= iend); /* ip < iend before the increment */ + + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length( + &ip, iend - RUN_MASK, (int)endOnInput, + (int)endOnInput, &error); + if (error == initial_error) { + goto _output_error; } - if ((endOnInput) - && (ip + length > iend)) { - /* - * Error : - * read attempt beyond - * end of input buffer - */ + if ((safeDecode) && + unlikely((uptrval)(op) + length < + (uptrval)(op))) { goto _output_error; + } /* overflow detection */ + if ((safeDecode) && + unlikely((uptrval)(ip) + length < + (uptrval)(ip))) { + goto _output_error; + } /* overflow detection */ + + /* copy literals */ + cpy = op + length; + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if (endOnInput) { /* LZ4_decompress_safe() */ + if ((cpy > oend - 32) || + (ip + length > iend - 32)) { + goto safe_literal_copy; + } + LZ4_wildCopy32(op, ip, cpy); + } else { /* LZ4_decompress_fast() */ + if (cpy > oend - 8) { + goto safe_literal_copy; + } + LZ4_wildCopy8( + op, ip, + cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and only relies on end-of-block properties */ } + ip += length; + op = cpy; } else { - if ((!endOnInput) - && (cpy != oend)) { - /* - * Error : - * block decoding must - * stop exactly there - */ + cpy = op + length; + if (endOnInput) { /* LZ4_decompress_safe() */ + DEBUGLOG( + 7, + "copy %u bytes in a 16-bytes stripe", + (unsigned)length); + /* We don't need to check oend, since we check it once for each loop below */ + if (ip > + iend - (16 + + 1 /*max lit + offset + nextToken*/)) { + goto safe_literal_copy; + } + /* Literals can only be 14, but hope compilers optimize if we copy by a register size */ + LZ4_memcpy(op, ip, 16); + } else { /* LZ4_decompress_fast() */ + /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and relies on end-of-block properties */ + LZ4_memcpy(op, ip, 8); + if (length > 8) { + LZ4_memcpy(op + 8, ip + 8, 8); + } + } + ip += length; + op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); + ip += 2; + match = op - offset; + assert(match <= op); + + /* get matchlength */ + length = token & ML_MASK; + + if (length == ML_MASK) { + variable_length_error error = ok; + if ((checkOffset) && + (unlikely(match + dictSize < lowPrefix))) { + goto _output_error; + } /* Error : offset outside buffers */ + length += read_variable_length( + &ip, iend - LASTLITERALS + 1, + (int)endOnInput, 0, &error); + if (error != ok) { goto _output_error; } - if ((endOnInput) - && ((ip + length != iend) - || (cpy > oend))) { - /* - * Error : - * input must be consumed - */ + if ((safeDecode) && + unlikely((uptrval)(op) + length < + (uptrval)op)) { goto _output_error; + } /* overflow detection */ + length += MINMATCH; + if (op + length >= + oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + } else { + length += MINMATCH; + if (op + length >= + oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; } - } - LZ4_memcpy(op, ip, length); - ip += length; - op += length; + /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ + if ((dict == withPrefix64k) || + (match >= lowPrefix)) { + if (offset >= 8) { + assert(match >= lowPrefix); + assert(match <= op); + assert(op + 18 <= oend); + + LZ4_memcpy(op, match, 8); + LZ4_memcpy(op + 8, match + 8, + 8); + LZ4_memcpy(op + 16, match + 16, + 2); + op += length; + continue; + } + } + } - /* Necessarily EOF, due to parsing restrictions */ - if (!partialDecoding || (cpy == oend)) - break; - } else { - /* may overwrite up to WILDCOPYLENGTH beyond cpy */ - LZ4_wildCopy(op, ip, cpy); - ip += length; - op = cpy; - } + if (checkOffset && + (unlikely(match + dictSize < lowPrefix))) { + goto _output_error; + } /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict == usingExtDict) && (match < lowPrefix)) { + if (unlikely(op + length > + oend - LASTLITERALS)) { + if (partialDecoding) { + DEBUGLOG( + 7, + "partialDecoding: dictionary match, close to dstEnd"); + length = min( + length, + (size_t)(oend - op)); + } else { + goto _output_error; /* end-of-block condition violated */ + } + } - /* get offset */ - offset = LZ4_readLE16(ip); - ip += 2; - match = op - offset; + if (length <= (size_t)(lowPrefix - match)) { + /* match fits entirely within external dictionary : just copy */ + LZ4_memmove(op, + dictEnd - + (lowPrefix - match), + length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = + (size_t)(lowPrefix - match); + size_t const restSize = + length - copySize; + LZ4_memcpy(op, dictEnd - copySize, + copySize); + op += copySize; + if (restSize > + (size_t)(op - + lowPrefix)) { /* overlap copy */ + BYTE *const endOfMatch = + op + restSize; + const BYTE *copyFrom = + lowPrefix; + while (op < endOfMatch) { + *op++ = *copyFrom++; + } + } else { + LZ4_memcpy(op, lowPrefix, + restSize); + op += restSize; + } + } + continue; + } - /* get matchlength */ - length = token & ML_MASK; + /* copy match within block */ + cpy = op + length; -_copy_match: - if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { - /* Error : offset outside buffers */ - goto _output_error; - } - - /* costs ~1%; silence an msan warning when offset == 0 */ - /* - * note : when partialDecoding, there is no guarantee that - * at least 4 bytes remain available in output buffer - */ - if (!partialDecoding) { - assert(oend > op); - assert(oend - op >= 4); + assert((op <= oend) && (oend - op >= 32)); + if (unlikely(offset < 16)) { + LZ4_memcpy_using_offset(op, match, cpy, offset); + } else { + LZ4_wildCopy32(op, match, cpy); + } - LZ4_write32(op, (U32)offset); + op = cpy; /* wildcopy correction */ } +safe_decode: +#endif - if (length == ML_MASK) { - unsigned int s; + /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ + while (1) { + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || + ip <= iend); /* ip < iend before the increment */ + + /* A two-stage shortcut for the most common case: + * 1) If the literal length is 0..14, and there is enough space, + * enter the shortcut and copy 16 bytes on behalf of the literals + * (in the fast mode, only 8 bytes can be safely copied this way). + * 2) Further if the match length is 4..18, copy 18 bytes in a similar + * manner; but we ensure that there's enough space in the output for + * those 18 bytes earlier, upon entering the shortcut (in other words, + * there is a combined check for both stages). + */ + if ((endOnInput ? length != RUN_MASK : length <= 8) + /* strictly "less than" on input, to re-enter the loop with at least one byte */ + && likely((endOnInput ? ip < shortiend : 1) & + (op <= shortoend))) { + /* Copy the literals */ + LZ4_memcpy(op, ip, endOnInput ? 16 : 8); + op += length; + ip += length; + + /* The second stage: prepare for match copying, decode full info. + * If it doesn't work out, the info won't be wasted. */ + length = token & ML_MASK; /* match length */ + offset = LZ4_readLE16(ip); + ip += 2; + match = op - offset; + assert(match <= op); /* check overflow */ + + /* Do not deal with overlapping matches. */ + if ((length != ML_MASK) && (offset >= 8) && + (dict == withPrefix64k || + match >= lowPrefix)) { + /* Copy the match. */ + LZ4_memcpy(op + 0, match + 0, 8); + LZ4_memcpy(op + 8, match + 8, 8); + LZ4_memcpy(op + 16, match + 16, 2); + op += length + MINMATCH; + /* Both stages worked, load the next token. */ + continue; + } - do { - s = *ip++; + /* The second stage didn't work out, but the info is ready. + * Propel it right to the point of match copying. */ + goto _copy_match; + } - if ((endOnInput) && (ip > iend - LASTLITERALS)) + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length( + &ip, iend - RUN_MASK, (int)endOnInput, + (int)endOnInput, &error); + if (error == initial_error) { goto _output_error; + } + if ((safeDecode) && + unlikely((uptrval)(op) + length < + (uptrval)(op))) { + goto _output_error; + } /* overflow detection */ + if ((safeDecode) && + unlikely((uptrval)(ip) + length < + (uptrval)(ip))) { + goto _output_error; + } /* overflow detection */ + } - length += s; - } while (s == 255); - - if ((safeDecode) - && unlikely( - (uptrval)(op) + length < (uptrval)op)) { - /* overflow detection */ - goto _output_error; + /* copy literals */ + cpy = op + length; +#if LZ4_FAST_DEC_LOOP +safe_literal_copy: +#endif + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if (((endOnInput) && + ((cpy > oend - MFLIMIT) || + (ip + length > iend - (2 + 1 + LASTLITERALS)))) || + ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { + /* We've either hit the input parsing restriction or the output parsing restriction. + * In the normal scenario, decoding a full block, it must be the last sequence, + * otherwise it's an error (invalid input or dimensions). + * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow. + */ + if (partialDecoding) { + /* Since we are partial decoding we may be in this block because of the output parsing + * restriction, which is not valid since the output buffer is allowed to be undersized. + */ + assert(endOnInput); + DEBUGLOG( + 7, + "partialDecoding: copying literals, close to input or output end") + DEBUGLOG( + 7, + "partialDecoding: literal length = %u", + (unsigned)length); + DEBUGLOG( + 7, + "partialDecoding: remaining space in dstBuffer : %i", + (int)(oend - op)); + DEBUGLOG( + 7, + "partialDecoding: remaining space in srcBuffer : %i", + (int)(iend - ip)); + /* Finishing in the middle of a literals segment, + * due to lack of input. + */ + if (ip + length > iend) { + length = (size_t)(iend - ip); + cpy = op + length; + } + /* Finishing in the middle of a literals segment, + * due to lack of output space. + */ + if (cpy > oend) { + cpy = oend; + assert(op <= oend); + length = (size_t)(oend - op); + } + } else { + /* We must be on the last sequence because of the parsing limitations so check + * that we exactly regenerate the original size (must be exact when !endOnInput). + */ + if ((!endOnInput) && (cpy != oend)) { + goto _output_error; + } + /* We must be on the last sequence (or invalid) because of the parsing limitations + * so check that we exactly consume the input and don't overrun the output buffer. + */ + if ((endOnInput) && + ((ip + length != iend) || + (cpy > oend))) { + DEBUGLOG( + 6, + "should have been last run of literals") + DEBUGLOG( + 6, + "ip(%p) + length(%i) = %p != iend (%p)", + ip, (int)length, + ip + length, iend); + DEBUGLOG( + 6, + "or cpy(%p) > oend(%p)", + cpy, oend); + goto _output_error; + } + } + LZ4_memmove( + op, ip, + length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */ + ip += length; + op += length; + /* Necessarily EOF when !partialDecoding. + * When partialDecoding, it is EOF if we've either + * filled the output buffer or + * can't proceed with reading an offset for following match. + */ + if (!partialDecoding || (cpy == oend) || + (ip >= (iend - 2))) { + break; + } + } else { + LZ4_wildCopy8( + op, ip, + cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ + ip += length; + op = cpy; } - } - length += MINMATCH; + /* get offset */ + offset = LZ4_readLE16(ip); + ip += 2; + match = op - offset; + + /* get matchlength */ + length = token & ML_MASK; - /* match starting within external dictionary */ - if ((dict == usingExtDict) && (match < lowPrefix)) { - if (unlikely(op + length > oend - LASTLITERALS)) { - /* doesn't respect parsing restriction */ - if (!partialDecoding) +_copy_match: + if (length == ML_MASK) { + variable_length_error error = ok; + length += read_variable_length( + &ip, iend - LASTLITERALS + 1, + (int)endOnInput, 0, &error); + if (error != ok) goto _output_error; - length = min(length, (size_t)(oend - op)); + if ((safeDecode) && + unlikely((uptrval)(op) + length < + (uptrval)op)) + goto _output_error; /* overflow detection */ } + length += MINMATCH; - if (length <= (size_t)(lowPrefix - match)) { - /* - * match fits entirely within external - * dictionary : just copy - */ - memmove(op, dictEnd - (lowPrefix - match), - length); - op += length; - } else { - /* - * match stretches into both external - * dictionary and current block - */ - size_t const copySize = (size_t)(lowPrefix - match); - size_t const restSize = length - copySize; - - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - if (restSize > (size_t)(op - lowPrefix)) { - /* overlap copy */ - BYTE * const endOfMatch = op + restSize; - const BYTE *copyFrom = lowPrefix; - - while (op < endOfMatch) - *op++ = *copyFrom++; +#if LZ4_FAST_DEC_LOOP +safe_match_copy: +#endif + if ((checkOffset) && + (unlikely(match + dictSize < lowPrefix))) + goto _output_error; /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict == usingExtDict) && (match < lowPrefix)) { + if (unlikely(op + length > + oend - LASTLITERALS)) { + if (partialDecoding) + length = min( + length, + (size_t)(oend - op)); + else + goto _output_error; /* doesn't respect parsing restriction */ + } + + if (length <= (size_t)(lowPrefix - match)) { + /* match fits entirely within external dictionary : just copy */ + LZ4_memmove(op, + dictEnd - + (lowPrefix - match), + length); + op += length; } else { - memcpy(op, lowPrefix, restSize); - op += restSize; + /* match stretches into both external dictionary and current block */ + size_t const copySize = + (size_t)(lowPrefix - match); + size_t const restSize = + length - copySize; + LZ4_memcpy(op, dictEnd - copySize, + copySize); + op += copySize; + if (restSize > + (size_t)(op - + lowPrefix)) { /* overlap copy */ + BYTE *const endOfMatch = + op + restSize; + const BYTE *copyFrom = + lowPrefix; + while (op < endOfMatch) + *op++ = *copyFrom++; + } else { + LZ4_memcpy(op, lowPrefix, + restSize); + op += restSize; + } } + continue; + } + assert(match >= lowPrefix); + + /* copy match within block */ + cpy = op + length; + + /* partialDecoding : may end anywhere within the block */ + assert(op <= oend); + if (partialDecoding && + (cpy > oend - MATCH_SAFEGUARD_DISTANCE)) { + size_t const mlen = + min(length, (size_t)(oend - op)); + const BYTE *const matchEnd = match + mlen; + BYTE *const copyEnd = op + mlen; + if (matchEnd > op) { /* overlap copy */ + while (op < copyEnd) { + *op++ = *match++; + } + } else { + LZ4_memcpy(op, match, mlen); + } + op = copyEnd; + if (op == oend) { + break; + } + continue; } - continue; - } - /* copy match within block */ - cpy = op + length; + if (unlikely(offset < 8)) { + LZ4_write32( + op, + 0); /* silence msan warning when offset==0 */ + op[0] = match[0]; + op[1] = match[1]; + op[2] = match[2]; + op[3] = match[3]; + match += inc32table[offset]; + LZ4_memcpy(op + 4, match, 4); + match -= dec64table[offset]; + } else { + LZ4_memcpy(op, match, 8); + match += 8; + } + op += 8; - /* - * partialDecoding : - * may not respect endBlock parsing restrictions - */ - assert(op <= oend); - if (partialDecoding && - (cpy > oend - MATCH_SAFEGUARD_DISTANCE)) { - size_t const mlen = min(length, (size_t)(oend - op)); - const BYTE * const matchEnd = match + mlen; - BYTE * const copyEnd = op + mlen; - - if (matchEnd > op) { - /* overlap copy */ - while (op < copyEnd) + if (unlikely(cpy > oend - MATCH_SAFEGUARD_DISTANCE)) { + BYTE *const oCopyLimit = + oend - (WILDCOPYLENGTH - 1); + if (cpy > oend - LASTLITERALS) { + goto _output_error; + } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ + if (op < oCopyLimit) { + LZ4_wildCopy8(op, match, oCopyLimit); + match += oCopyLimit - op; + op = oCopyLimit; + } + while (op < cpy) { *op++ = *match++; + } } else { - LZ4_memcpy(op, match, mlen); + LZ4_memcpy(op, match, 8); + if (length > 16) { + LZ4_wildCopy8(op + 8, match + 8, cpy); + } } - op = copyEnd; - if (op == oend) - break; - continue; + op = cpy; /* wildcopy correction */ } - if (unlikely(offset < 8)) { - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += inc32table[offset]; - LZ4_memcpy(op + 4, match, 4); - match -= dec64table[offset]; - } else { - LZ4_copy8(op, match); - match += 8; - } - - op += 8; - - if (unlikely(cpy > oend - MATCH_SAFEGUARD_DISTANCE)) { - BYTE * const oCopyLimit = oend - (WILDCOPYLENGTH - 1); - - if (cpy > oend - LASTLITERALS) { - /* - * Error : last LASTLITERALS bytes - * must be literals (uncompressed) - */ - goto _output_error; - } - - if (op < oCopyLimit) { - LZ4_wildCopy(op, match, oCopyLimit); - match += oCopyLimit - op; - op = oCopyLimit; - } - while (op < cpy) - *op++ = *match++; + /* end of decoding */ + if (endOnInput) { + DEBUGLOG(5, "decoded %i bytes", + (int)(((char *)op) - dst)); + return (int)(((char *)op) - + dst); /* Nb of output bytes decoded */ } else { - LZ4_copy8(op, match); - if (length > 16) - LZ4_wildCopy(op + 8, match + 8, cpy); + return (int)(((const char *)ip) - + src); /* Nb of input bytes read */ } - op = cpy; /* wildcopy correction */ - } - /* end of decoding */ - if (endOnInput) { - /* Nb of output bytes decoded */ - return (int) (((char *)op) - dst); - } else { - /* Nb of input bytes read */ - return (int) (((const char *)ip) - src); - } - - /* Overflow error detected */ + /* Overflow error detected */ _output_error: - return (int) (-(((const char *)ip) - src)) - 1; + return (int)(-(((const char *)ip) - src)) - 1; + } } -int LZ4_decompress_safe(const char *source, char *dest, - int compressedSize, int maxDecompressedSize) +int LZ4_decompress_safe(const char *source, char *dest, int compressedSize, + int maxDecompressedSize) { - return LZ4_decompress_generic(source, dest, - compressedSize, maxDecompressedSize, - endOnInputSize, decode_full_block, - noDict, (BYTE *)dest, NULL, 0); + return LZ4_decompress_generic(source, dest, compressedSize, + maxDecompressedSize, endOnInputSize, + decode_full_block, noDict, (BYTE *)dest, + NULL, 0); } -int LZ4_decompress_safe_partial(const char *src, char *dst, - int compressedSize, int targetOutputSize, int dstCapacity) +int LZ4_decompress_safe_partial(const char *src, char *dst, int compressedSize, + int targetOutputSize, int dstCapacity) { dstCapacity = min(targetOutputSize, dstCapacity); return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity, - endOnInputSize, partial_decode, - noDict, (BYTE *)dst, NULL, 0); + endOnInputSize, partial_decode, noDict, + (BYTE *)dst, NULL, 0); } int LZ4_decompress_fast(const char *source, char *dest, int originalSize) { return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, - withPrefix64k, - (BYTE *)dest - 64 * KB, NULL, 0); + withPrefix64k, (BYTE *)dest - 64 * KB, + NULL, 0); } /* ===== Instantiate a few more decoding cases, used more than once. ===== */ @@ -477,10 +823,9 @@ int LZ4_decompress_fast(const char *source, char *dest, int originalSize) int LZ4_decompress_safe_withPrefix64k(const char *source, char *dest, int compressedSize, int maxOutputSize) { - return LZ4_decompress_generic(source, dest, - compressedSize, maxOutputSize, - endOnInputSize, decode_full_block, - withPrefix64k, + return LZ4_decompress_generic(source, dest, compressedSize, + maxOutputSize, endOnInputSize, + decode_full_block, withPrefix64k, (BYTE *)dest - 64 * KB, NULL, 0); } @@ -489,10 +834,9 @@ static int LZ4_decompress_safe_withSmallPrefix(const char *source, char *dest, int maxOutputSize, size_t prefixSize) { - return LZ4_decompress_generic(source, dest, - compressedSize, maxOutputSize, - endOnInputSize, decode_full_block, - noDict, + return LZ4_decompress_generic(source, dest, compressedSize, + maxOutputSize, endOnInputSize, + decode_full_block, noDict, (BYTE *)dest - prefixSize, NULL, 0); } @@ -500,19 +844,18 @@ int LZ4_decompress_safe_forceExtDict(const char *source, char *dest, int compressedSize, int maxOutputSize, const void *dictStart, size_t dictSize) { - return LZ4_decompress_generic(source, dest, - compressedSize, maxOutputSize, - endOnInputSize, decode_full_block, - usingExtDict, (BYTE *)dest, - (const BYTE *)dictStart, dictSize); + return LZ4_decompress_generic(source, dest, compressedSize, + maxOutputSize, endOnInputSize, + decode_full_block, usingExtDict, + (BYTE *)dest, (const BYTE *)dictStart, + dictSize); } static int LZ4_decompress_fast_extDict(const char *source, char *dest, - int originalSize, - const void *dictStart, size_t dictSize) + int originalSize, const void *dictStart, + size_t dictSize) { - return LZ4_decompress_generic(source, dest, - 0, originalSize, + return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, usingExtDict, (BYTE *)dest, (const BYTE *)dictStart, dictSize); @@ -523,26 +866,23 @@ static int LZ4_decompress_fast_extDict(const char *source, char *dest, * of the dictionary is passed as prefix, and the second via dictStart + dictSize. * These routines are used only once, in LZ4_decompress_*_continue(). */ -static FORCE_INLINE -int LZ4_decompress_safe_doubleDict(const char *source, char *dest, - int compressedSize, int maxOutputSize, - size_t prefixSize, - const void *dictStart, size_t dictSize) +static FORCE_INLINE int LZ4_decompress_safe_doubleDict( + const char *source, char *dest, int compressedSize, int maxOutputSize, + size_t prefixSize, const void *dictStart, size_t dictSize) { - return LZ4_decompress_generic(source, dest, - compressedSize, maxOutputSize, - endOnInputSize, decode_full_block, - usingExtDict, (BYTE *)dest - prefixSize, + return LZ4_decompress_generic(source, dest, compressedSize, + maxOutputSize, endOnInputSize, + decode_full_block, usingExtDict, + (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize); } -static FORCE_INLINE -int LZ4_decompress_fast_doubleDict(const char *source, char *dest, - int originalSize, size_t prefixSize, - const void *dictStart, size_t dictSize) +static FORCE_INLINE int +LZ4_decompress_fast_doubleDict(const char *source, char *dest, int originalSize, + size_t prefixSize, const void *dictStart, + size_t dictSize) { - return LZ4_decompress_generic(source, dest, - 0, originalSize, + return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, usingExtDict, (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize); @@ -551,15 +891,15 @@ int LZ4_decompress_fast_doubleDict(const char *source, char *dest, /* ===== streaming decompression functions ===== */ int LZ4_setStreamDecode(LZ4_streamDecode_t *LZ4_streamDecode, - const char *dictionary, int dictSize) + const char *dictionary, int dictSize) { LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse; - lz4sd->prefixSize = (size_t) dictSize; - lz4sd->prefixEnd = (const BYTE *) dictionary + dictSize; + lz4sd->prefixSize = (size_t)dictSize; + lz4sd->prefixEnd = (const BYTE *)dictionary + dictSize; lz4sd->externalDict = NULL; - lz4sd->extDictSize = 0; + lz4sd->extDictSize = 0; return 1; } @@ -574,7 +914,8 @@ int LZ4_setStreamDecode(LZ4_streamDecode_t *LZ4_streamDecode, * and indicate where it stands using LZ4_setStreamDecode() */ int LZ4_decompress_safe_continue(LZ4_streamDecode_t *LZ4_streamDecode, - const char *source, char *dest, int compressedSize, int maxOutputSize) + const char *source, char *dest, + int compressedSize, int maxOutputSize) { LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse; @@ -583,85 +924,86 @@ int LZ4_decompress_safe_continue(LZ4_streamDecode_t *LZ4_streamDecode, if (lz4sd->prefixSize == 0) { /* The first call, no dictionary yet. */ assert(lz4sd->extDictSize == 0); - result = LZ4_decompress_safe(source, dest, - compressedSize, maxOutputSize); + result = LZ4_decompress_safe(source, dest, compressedSize, + maxOutputSize); if (result <= 0) return result; - lz4sd->prefixSize = result; + lz4sd->prefixSize = (size_t)result; lz4sd->prefixEnd = (BYTE *)dest + result; } else if (lz4sd->prefixEnd == (BYTE *)dest) { /* They're rolling the current segment. */ if (lz4sd->prefixSize >= 64 * KB - 1) - result = LZ4_decompress_safe_withPrefix64k(source, dest, - compressedSize, maxOutputSize); + result = LZ4_decompress_safe_withPrefix64k( + source, dest, compressedSize, maxOutputSize); else if (lz4sd->extDictSize == 0) - result = LZ4_decompress_safe_withSmallPrefix(source, - dest, compressedSize, maxOutputSize, + result = LZ4_decompress_safe_withSmallPrefix( + source, dest, compressedSize, maxOutputSize, lz4sd->prefixSize); else - result = LZ4_decompress_safe_doubleDict(source, dest, - compressedSize, maxOutputSize, - lz4sd->prefixSize, - lz4sd->externalDict, lz4sd->extDictSize); + result = LZ4_decompress_safe_doubleDict( + source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize, lz4sd->externalDict, + lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize += result; - lz4sd->prefixEnd += result; + lz4sd->prefixSize += (size_t)result; + lz4sd->prefixEnd += result; } else { - /* - * The buffer wraps around, or they're - * switching to another buffer. - */ + /* The buffer wraps around, or they're switching to another buffer. */ lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_safe_forceExtDict(source, dest, - compressedSize, maxOutputSize, + result = LZ4_decompress_safe_forceExtDict( + source, dest, compressedSize, maxOutputSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = result; - lz4sd->prefixEnd = (BYTE *)dest + result; + lz4sd->prefixSize = (size_t)result; + lz4sd->prefixEnd = (BYTE *)dest + result; } return result; } int LZ4_decompress_fast_continue(LZ4_streamDecode_t *LZ4_streamDecode, - const char *source, char *dest, int originalSize) + const char *source, char *dest, + int originalSize) { - LZ4_streamDecode_t_internal *lz4sd = &LZ4_streamDecode->internal_donotuse; + LZ4_streamDecode_t_internal *lz4sd = + &LZ4_streamDecode->internal_donotuse; int result; + assert(originalSize >= 0); if (lz4sd->prefixSize == 0) { assert(lz4sd->extDictSize == 0); result = LZ4_decompress_fast(source, dest, originalSize); if (result <= 0) return result; - lz4sd->prefixSize = originalSize; + lz4sd->prefixSize = (size_t)originalSize; lz4sd->prefixEnd = (BYTE *)dest + originalSize; } else if (lz4sd->prefixEnd == (BYTE *)dest) { - if (lz4sd->prefixSize >= 64 * KB - 1 || - lz4sd->extDictSize == 0) - result = LZ4_decompress_fast(source, dest, - originalSize); + if (lz4sd->prefixSize >= 64 * KB - 1 || lz4sd->extDictSize == 0) + result = + LZ4_decompress_fast(source, dest, originalSize); else - result = LZ4_decompress_fast_doubleDict(source, dest, - originalSize, lz4sd->prefixSize, + result = LZ4_decompress_fast_doubleDict( + source, dest, originalSize, lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize += originalSize; - lz4sd->prefixEnd += originalSize; + lz4sd->prefixSize += (size_t)originalSize; + lz4sd->prefixEnd += originalSize; } else { lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_fast_extDict(source, dest, - originalSize, lz4sd->externalDict, lz4sd->extDictSize); + result = LZ4_decompress_fast_extDict(source, dest, originalSize, + lz4sd->externalDict, + lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = originalSize; + lz4sd->prefixSize = (size_t)originalSize; lz4sd->prefixEnd = (BYTE *)dest + originalSize; } + return result; } @@ -670,28 +1012,29 @@ int LZ4_decompress_safe_usingDict(const char *source, char *dest, const char *dictStart, int dictSize) { if (dictSize == 0) - return LZ4_decompress_safe(source, dest, - compressedSize, maxOutputSize); - if (dictStart+dictSize == dest) { + return LZ4_decompress_safe(source, dest, compressedSize, + maxOutputSize); + if (dictStart + dictSize == dest) { if (dictSize >= 64 * KB - 1) - return LZ4_decompress_safe_withPrefix64k(source, dest, - compressedSize, maxOutputSize); - return LZ4_decompress_safe_withSmallPrefix(source, dest, - compressedSize, maxOutputSize, dictSize); + return LZ4_decompress_safe_withPrefix64k( + source, dest, compressedSize, maxOutputSize); + return LZ4_decompress_safe_withSmallPrefix( + source, dest, compressedSize, maxOutputSize, dictSize); } - return LZ4_decompress_safe_forceExtDict(source, dest, - compressedSize, maxOutputSize, dictStart, dictSize); + return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, + maxOutputSize, dictStart, + dictSize); } int LZ4_decompress_fast_usingDict(const char *source, char *dest, - int originalSize, - const char *dictStart, int dictSize) + int originalSize, const char *dictStart, + int dictSize) { if (dictSize == 0 || dictStart + dictSize == dest) return LZ4_decompress_fast(source, dest, originalSize); return LZ4_decompress_fast_extDict(source, dest, originalSize, - dictStart, dictSize); + dictStart, dictSize); } #ifndef STATIC diff --git a/lib/lz4/lz4defs.h b/lib/lz4/lz4defs.h index c91dd96ef629..f7fa464d9958 100644 --- a/lib/lz4/lz4defs.h +++ b/lib/lz4/lz4defs.h @@ -36,7 +36,7 @@ */ #include -#include /* memset, memcpy */ +#include /* memset, memcpy */ #define FORCE_INLINE __always_inline @@ -45,10 +45,10 @@ **************************************/ #include -typedef uint8_t BYTE; +typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; -typedef int32_t S32; +typedef int32_t S32; typedef uint64_t U64; typedef uintptr_t uptrval; @@ -67,22 +67,28 @@ typedef uintptr_t uptrval; #define LZ4_LITTLE_ENDIAN 0 #endif +#define DEBUGLOG(l, ...) \ + { \ + } /* disabled */ + +#ifndef assert +#define assert(condition) ((void)0) +#endif + /*-************************************ * Constants **************************************/ +#define LZ4_DISTANCE_ABSOLUTE_MAX 65535 +#define LZ4_DISTANCE_MAX 65535 #define MINMATCH 4 #define WILDCOPYLENGTH 8 -#define LASTLITERALS 5 -#define MFLIMIT (WILDCOPYLENGTH + MINMATCH) -/* - * ensure it's possible to write 2 x wildcopyLength - * without overflowing output buffer - */ -#define MATCH_SAFEGUARD_DISTANCE ((2 * WILDCOPYLENGTH) - MINMATCH) - -/* Increase this value ==> compression run slower on incompressible data */ -#define LZ4_SKIPTRIGGER 6 +#define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MATCH_SAFEGUARD_DISTANCE \ + ((2 * WILDCOPYLENGTH) - \ + MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ +#define FASTLOOP_SAFE_DISTANCE 64 #define HASH_UNIT sizeof(size_t) @@ -90,12 +96,16 @@ typedef uintptr_t uptrval; #define MB (1 << 20) #define GB (1U << 30) -#define MAXD_LOG 16 -#define MAX_DISTANCE ((1 << MAXD_LOG) - 1) +#if defined(__x86_64__) +typedef U64 reg_t; /* 64-bits in x32 mode */ +#else +typedef size_t reg_t; /* 32-bits in x32 mode */ +#endif + #define STEPSIZE sizeof(size_t) -#define ML_BITS 4 -#define ML_MASK ((1U << ML_BITS) - 1) +#define ML_BITS 4 +#define ML_MASK ((1U << ML_BITS) - 1) #define RUN_BITS (8 - ML_BITS) #define RUN_MASK ((1U << RUN_BITS) - 1) @@ -146,41 +156,24 @@ static FORCE_INLINE void LZ4_writeLE16(void *memPtr, U16 value) * environments. This is needed when decompressing the Linux Kernel, for example. */ #define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) +#define LZ4_memmove(dst, src, size) __builtin_memmove(dst, src, size) -static FORCE_INLINE void LZ4_copy8(void *dst, const void *src) -{ -#if LZ4_ARCH64 - U64 a = get_unaligned((const U64 *)src); - - put_unaligned(a, (U64 *)dst); -#else - U32 a = get_unaligned((const U32 *)src); - U32 b = get_unaligned((const U32 *)src + 1); - - put_unaligned(a, (U32 *)dst); - put_unaligned(b, (U32 *)dst + 1); -#endif -} - -/* - * customized variant of memcpy, - * which can overwrite up to 7 bytes beyond dstEnd - */ -static FORCE_INLINE void LZ4_wildCopy(void *dstPtr, - const void *srcPtr, void *dstEnd) +/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ +static FORCE_INLINE void LZ4_wildCopy8(void *dstPtr, const void *srcPtr, + void *dstEnd) { BYTE *d = (BYTE *)dstPtr; const BYTE *s = (const BYTE *)srcPtr; BYTE *const e = (BYTE *)dstEnd; do { - LZ4_copy8(d, s); + LZ4_memcpy(d, s, 8); d += 8; s += 8; } while (d < e); } -static FORCE_INLINE unsigned int LZ4_NbCommonBytes(register size_t val) +static FORCE_INLINE unsigned int LZ4_NbCommonBytes(reg_t val) { #if LZ4_LITTLE_ENDIAN return __ffs(val) >> 3; @@ -189,56 +182,64 @@ static FORCE_INLINE unsigned int LZ4_NbCommonBytes(register size_t val) #endif } -static FORCE_INLINE unsigned int LZ4_count( - const BYTE *pIn, - const BYTE *pMatch, - const BYTE *pInLimit) +static FORCE_INLINE unsigned int LZ4_count(const BYTE *pIn, const BYTE *pMatch, + const BYTE *pInLimit) { const BYTE *const pStart = pIn; - while (likely(pIn < pInLimit - (STEPSIZE - 1))) { - size_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (likely(pIn < pInLimit - (STEPSIZE - 1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); + if (!diff) { + pIn += STEPSIZE; + pMatch += STEPSIZE; + } else { + return LZ4_NbCommonBytes(diff); + } + } + while (likely(pIn < pInLimit - (STEPSIZE - 1))) { + reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); if (!diff) { pIn += STEPSIZE; pMatch += STEPSIZE; continue; } - pIn += LZ4_NbCommonBytes(diff); - - return (unsigned int)(pIn - pStart); + return (unsigned)(pIn - pStart); } -#if LZ4_ARCH64 - if ((pIn < (pInLimit - 3)) - && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { + if ((STEPSIZE == 8) && (pIn < (pInLimit - 3)) && + (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn += 4; pMatch += 4; } -#endif - - if ((pIn < (pInLimit - 1)) - && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { + if ((pIn < (pInLimit - 1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn += 2; pMatch += 2; } - if ((pIn < pInLimit) && (*pMatch == *pIn)) pIn++; - - return (unsigned int)(pIn - pStart); + return (unsigned)(pIn - pStart); } -typedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive; -typedef enum { byPtr, byU32, byU16 } tableType_t; - -typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; +typedef enum { + notLimited = 0, + limitedOutput = 1, + fillOutput = 2 +} limitedOutput_directive; +typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; + +typedef enum { + noDict = 0, + withPrefix64k, + usingExtDict, + usingDictCtx +} dict_directive; typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; -#define LZ4_STATIC_ASSERT(c) BUILD_BUG_ON(!(c)) +#define LZ4_STATIC_ASSERT(c) BUILD_BUG_ON(!(c)) #endif From 804fc9e235449e159d34a29ed9eab617c392894e Mon Sep 17 00:00:00 2001 From: Andrzej Perczak Date: Sun, 28 Aug 2022 22:21:28 +0200 Subject: [PATCH 06/29] lz4: Update to version 1.9.4 Signed-off-by: Andrzej Perczak --- include/linux/lz4.h | 41 ++-- lib/lz4/lz4_compress.c | 3 +- lib/lz4/lz4_decompress.c | 461 +++++++++++++++++++++++---------------- 3 files changed, 302 insertions(+), 203 deletions(-) diff --git a/include/linux/lz4.h b/include/linux/lz4.h index edd32c93718d..266b6c462b4f 100644 --- a/include/linux/lz4.h +++ b/include/linux/lz4.h @@ -58,9 +58,9 @@ #define LZ4_MEMORY_USAGE 16 #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ -#define LZ4_COMPRESSBOUND(isize) \ - ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? \ - 0 : \ +#define LZ4_COMPRESSBOUND(isize) \ + ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? \ + 0 : \ (isize) + ((isize) / 255) + 16) #define LZ4_ACCELERATION_DEFAULT 1 @@ -83,32 +83,33 @@ /*-************************************************************************ * STREAMING CONSTANTS AND STRUCTURES **************************************************************************/ -#define LZ4_STREAMSIZE \ - ((1UL << LZ4_MEMORY_USAGE) + \ +#define LZ4_STREAM_MINSIZE \ + ((1UL << LZ4_MEMORY_USAGE) + \ 32) /* static size, for inter-version compatibility */ -#define LZ4_STREAMSIZE_VOIDP (LZ4_STREAMSIZE / sizeof(void *)) - -#define LZ4_STREAMDECODESIZE_U64 \ - (4 + ((sizeof(void *) == 16) ? 2 : 0) /*AS-400*/) -#define LZ4_STREAMDECODESIZE \ - (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) #define LZ4_STREAMHCSIZE_SIZET (262192 / sizeof(size_t)) +/*! LZ4_stream_t : + * Never ever use below internal definitions directly ! + * These definitions are not API/ABI safe, and may change in future versions. + * If you need static allocation, declare or allocate an LZ4_stream_t object. +**/ + /* * LZ4_stream_t - information structure to track an LZ4 stream. */ typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; struct LZ4_stream_t_internal { uint32_t hashTable[LZ4_HASH_SIZE_U32]; - uint32_t currentOffset; - uint32_t tableType; const uint8_t *dictionary; const LZ4_stream_t_internal *dictCtx; + uint32_t currentOffset; + uint32_t tableType; uint32_t dictSize; + /* Implicit padding to ensure structure is aligned */ }; typedef union { - void *table[LZ4_STREAMSIZE_VOIDP]; + char minStateSize[LZ4_STREAM_MINSIZE]; LZ4_stream_t_internal internal_donotuse; } LZ4_stream_t; @@ -143,21 +144,27 @@ typedef union { * * init this structure using LZ4_setStreamDecode (or memset()) before first use */ +/*! LZ4_streamDecode_t : + * Never ever use below internal definitions directly ! + * These definitions are not API/ABI safe, and may change in future versions. + * If you need static allocation, declare or allocate an LZ4_streamDecode_t object. +**/ typedef struct { const uint8_t *externalDict; - size_t extDictSize; const uint8_t *prefixEnd; + size_t extDictSize; size_t prefixSize; } LZ4_streamDecode_t_internal; +#define LZ4_STREAMDECODE_MINSIZE 32 typedef union { - unsigned long long table[LZ4_STREAMDECODESIZE_U64]; + char minStateSize[LZ4_STREAMDECODE_MINSIZE]; LZ4_streamDecode_t_internal internal_donotuse; } LZ4_streamDecode_t; /*-************************************************************************ * SIZE OF STATE **************************************************************************/ -#define LZ4_MEM_COMPRESS LZ4_STREAMSIZE +#define LZ4_MEM_COMPRESS sizeof(LZ4_stream_t) #define LZ4HC_MEM_COMPRESS LZ4_STREAMHCSIZE /*-************************************************************************ diff --git a/lib/lz4/lz4_compress.c b/lib/lz4/lz4_compress.c index 2ade91cf2298..15be304a1b91 100644 --- a/lib/lz4/lz4_compress.c +++ b/lib/lz4/lz4_compress.c @@ -1068,7 +1068,8 @@ int LZ4_saveDict(LZ4_stream_t *LZ4_dict, char *safeBuffer, int dictSize) const BYTE *const previousDictEnd = dict->dictionary + dict->dictSize; assert(dict->dictionary); - LZ4_memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + LZ4_memmove(safeBuffer, previousDictEnd - dictSize, + (size_t)dictSize); } dict->dictionary = (const BYTE *)safeBuffer; diff --git a/lib/lz4/lz4_decompress.c b/lib/lz4/lz4_decompress.c index 5e0ff76e55e0..b212338e5f4a 100644 --- a/lib/lz4/lz4_decompress.c +++ b/lib/lz4/lz4_decompress.c @@ -134,38 +134,185 @@ static FORCE_INLINE void LZ4_memcpy_using_offset(BYTE *dstPtr, } #endif +/* variant for decompress_unsafe() + * does not know end of input + * presumes input is well formed + * note : will consume at least one byte */ +size_t read_long_length_no_check(const BYTE **pp) +{ + size_t b, l = 0; + do { + b = **pp; + (*pp)++; + l += b; + } while (b == 255); + DEBUGLOG(6, + "read_long_length_no_check: +length=%zu using %zu input bytes", + l, l / 255 + 1) + return l; +} + +/* core decoder variant for LZ4_decompress_fast*() + * for legacy support only : these entry points are deprecated. + * - Presumes input is correctly formed (no defense vs malformed inputs) + * - Does not know input size (presume input buffer is "large enough") + * - Decompress a full block (only) + * @return : nb of bytes read from input. + * Note : this variant is not optimized for speed, just for maintenance. + * the goal is to remove support of decompress_fast*() variants by v2.0 +**/ +FORCE_INLINE int LZ4_decompress_unsafe_generic( + const BYTE *const istart, BYTE *const ostart, int decompressedSize, + size_t prefixSize, + const BYTE *const dictStart, /* only if dict==usingExtDict */ + const size_t dictSize /* note: =0 if dictStart==NULL */ +) +{ + const BYTE *ip = istart; + BYTE *op = (BYTE *)ostart; + BYTE *const oend = ostart + decompressedSize; + const BYTE *const prefixStart = ostart - prefixSize; + + DEBUGLOG(5, "LZ4_decompress_unsafe_generic"); + if (dictStart == NULL) + assert(dictSize == 0); + + while (1) { + /* start new sequence */ + unsigned token = *ip++; + + /* literals */ + { + size_t ll = token >> ML_BITS; + if (ll == 15) { + /* long literal length */ + ll += read_long_length_no_check(&ip); + } + if ((size_t)(oend - op) < ll) + return -1; /* output buffer overflow */ + LZ4_memmove(op, ip, + ll); /* support in-place decompression */ + op += ll; + ip += ll; + if ((size_t)(oend - op) < MFLIMIT) { + if (op == oend) + break; /* end of block */ + DEBUGLOG( + 5, + "invalid: literals end at distance %zi from end of block", + oend - op); + /* incorrect end of block : + * last match must start at least MFLIMIT==12 bytes before end of output block */ + return -1; + } + } + + /* match */ + { + size_t ml = token & 15; + size_t const offset = LZ4_readLE16(ip); + ip += 2; + + if (ml == 15) { + /* long literal length */ + ml += read_long_length_no_check(&ip); + } + ml += MINMATCH; + + if ((size_t)(oend - op) < ml) + return -1; /* output buffer overflow */ + + { + const BYTE *match = op - offset; + + /* out of range */ + if (offset > + (size_t)(op - prefixStart) + dictSize) { + DEBUGLOG(6, "offset out of range"); + return -1; + } + + /* check special case : extDict */ + if (offset > (size_t)(op - prefixStart)) { + /* extDict scenario */ + const BYTE *const dictEnd = + dictStart + dictSize; + const BYTE *extMatch = + dictEnd - + (offset - + (size_t)(op - prefixStart)); + size_t const extml = + (size_t)(dictEnd - extMatch); + if (extml > ml) { + /* match entirely within extDict */ + LZ4_memmove(op, extMatch, ml); + op += ml; + ml = 0; + } else { + /* match split between extDict & prefix */ + LZ4_memmove(op, extMatch, + extml); + op += extml; + ml -= extml; + } + match = prefixStart; + } + + /* match copy - slow variant, supporting overlap copy */ + { + size_t u; + for (u = 0; u < ml; u++) { + op[u] = match[u]; + } + } + } + op += ml; + if ((size_t)(oend - op) < LASTLITERALS) { + DEBUGLOG( + 5, + "invalid: match ends at distance %zi from end of block", + oend - op); + /* incorrect end of block : + * last match must stop at least LASTLITERALS==5 bytes before end of output block */ + return -1; + } + } /* match */ + } /* main loop */ + return (int)(ip - istart); +} + /* Read the variable-length literal or match length. * - * ip - pointer to use as input. - * lencheck - end ip. Return an error if ip advances >= lencheck. - * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so. - * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so. - * error (output) - error code. Should be set to 0 before call. - */ -typedef enum { - loop_error = -2, - initial_error = -1, - ok = 0 -} variable_length_error; -static FORCE_INLINE unsigned -read_variable_length(const BYTE **ip, const BYTE *lencheck, int loop_check, - int initial_check, variable_length_error *error) + * @ip : input pointer + * @ilimit : position after which if length is not decoded, the input is necessarily corrupted. + * @initial_check - check ip >= ipmax before start of loop. Returns initial_error if so. + * @error (output) - error code. Must be set to 0 before call. +**/ +typedef size_t Rvl_t; +static const Rvl_t rvl_error = (Rvl_t)(-1); +static FORCE_INLINE Rvl_t read_variable_length(const BYTE **ip, + const BYTE *ilimit, + int initial_check) { - U32 length = 0; - U32 s; + Rvl_t s, length = 0; + assert(ip != NULL); + assert(*ip != NULL); + assert(ilimit != NULL); if (initial_check && - unlikely((*ip) >= lencheck)) { /* overflow detection */ - *error = initial_error; - return length; + unlikely((*ip) >= ilimit)) { /* read limit reached */ + return rvl_error; } do { s = **ip; (*ip)++; length += s; - if (loop_check && - unlikely((*ip) >= lencheck)) { /* overflow detection */ - *error = loop_error; - return length; + if (unlikely((*ip) > ilimit)) { /* read limit reached */ + return rvl_error; + } + /* accumulator overflow detection (32-bit mode only) */ + if ((sizeof(length) < 8) && + unlikely(length > ((Rvl_t)(-1) / 2))) { + return rvl_error; } } while (s == 255); @@ -187,8 +334,6 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, */ int outputSize, /* endOnOutputSize, endOnInputSize */ - endCondition_directive endOnInput, - /* full, partial */ earlyEnd_directive partialDecoding, /* noDict, withPrefix64k, usingExtDict */ dict_directive dict, @@ -214,15 +359,13 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, const BYTE *const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; - const int safeDecode = (endOnInput == endOnInputSize); - const int checkOffset = - ((safeDecode) && (dictSize < (int)(64 * KB))); + const int checkOffset = (dictSize < (int)(64 * KB)); /* Set up the "end" pointers for the shortcut. */ const BYTE *const shortiend = - iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + iend - 14 /*maxLL*/ - 2 /*offset*/; const BYTE *const shortoend = - oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; + oend - 14 /*maxLL*/ - 18 /*maxML*/; const BYTE *match; size_t offset; @@ -234,55 +377,47 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, /* Special cases */ assert(lowPrefix <= op); - if ((endOnInput) && (unlikely(outputSize == 0))) { + if (unlikely(outputSize == 0)) { /* Empty output buffer */ if (partialDecoding) return 0; return ((srcSize == 1) && (*ip == 0)) ? 0 : -1; } - if ((!endOnInput) && (unlikely(outputSize == 0))) { - return (*ip == 0 ? 1 : -1); - } - if ((endOnInput) && unlikely(srcSize == 0)) { + if (unlikely(srcSize == 0)) { return -1; } - /* Currently the fast loop shows a regression on qualcomm arm chips. */ + /* LZ4_FAST_DEC_LOOP: + * designed for modern OoO performance cpus, + * where copying reliably 32-bytes is preferable to an unpredictable branch. + * note : fast loop may show a regression for some client arm chips. */ #if LZ4_FAST_DEC_LOOP if ((oend - op) < FASTLOOP_SAFE_DISTANCE) { DEBUGLOG(6, "skip fast decode loop"); goto safe_decode; } - /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ + /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */ while (1) { /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ assert(oend - op >= FASTLOOP_SAFE_DISTANCE); - if (endOnInput) { - assert(ip < iend); - } + assert(ip < iend); token = *ip++; length = token >> ML_BITS; /* literal length */ - assert(!endOnInput || - ip <= iend); /* ip < iend before the increment */ - /* decode literal length */ if (length == RUN_MASK) { - variable_length_error error = ok; - length += read_variable_length( - &ip, iend - RUN_MASK, (int)endOnInput, - (int)endOnInput, &error); - if (error == initial_error) { + size_t const addl = read_variable_length( + &ip, iend - RUN_MASK, 1); + if (addl == rvl_error) { goto _output_error; } - if ((safeDecode) && - unlikely((uptrval)(op) + length < + length += addl; + if (unlikely((uptrval)(op) + length < (uptrval)(op))) { goto _output_error; } /* overflow detection */ - if ((safeDecode) && - unlikely((uptrval)(ip) + length < + if (unlikely((uptrval)(ip) + length < (uptrval)(ip))) { goto _output_error; } /* overflow detection */ @@ -290,46 +425,26 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, /* copy literals */ cpy = op + length; LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); - if (endOnInput) { /* LZ4_decompress_safe() */ - if ((cpy > oend - 32) || - (ip + length > iend - 32)) { - goto safe_literal_copy; - } - LZ4_wildCopy32(op, ip, cpy); - } else { /* LZ4_decompress_fast() */ - if (cpy > oend - 8) { - goto safe_literal_copy; - } - LZ4_wildCopy8( - op, ip, - cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : - * it doesn't know input length, and only relies on end-of-block properties */ + if ((cpy > oend - 32) || + (ip + length > iend - 32)) { + goto safe_literal_copy; } + LZ4_wildCopy32(op, ip, cpy); ip += length; op = cpy; } else { cpy = op + length; - if (endOnInput) { /* LZ4_decompress_safe() */ - DEBUGLOG( - 7, - "copy %u bytes in a 16-bytes stripe", - (unsigned)length); - /* We don't need to check oend, since we check it once for each loop below */ - if (ip > - iend - (16 + - 1 /*max lit + offset + nextToken*/)) { - goto safe_literal_copy; - } - /* Literals can only be 14, but hope compilers optimize if we copy by a register size */ - LZ4_memcpy(op, ip, 16); - } else { /* LZ4_decompress_fast() */ - /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : - * it doesn't know input length, and relies on end-of-block properties */ - LZ4_memcpy(op, ip, 8); - if (length > 8) { - LZ4_memcpy(op + 8, ip + 8, 8); - } + DEBUGLOG(7, + "copy %u bytes in a 16-bytes stripe", + (unsigned)length); + /* We don't need to check oend, since we check it once for each loop below */ + if (ip > + iend - (16 + + 1 /*max lit + offset + nextToken*/)) { + goto safe_literal_copy; } + /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */ + LZ4_memcpy(op, ip, 16); ip += length; op = cpy; } @@ -338,29 +453,27 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, offset = LZ4_readLE16(ip); ip += 2; match = op - offset; - assert(match <= op); + assert(match <= op); /* overflow check */ /* get matchlength */ length = token & ML_MASK; if (length == ML_MASK) { - variable_length_error error = ok; - if ((checkOffset) && - (unlikely(match + dictSize < lowPrefix))) { - goto _output_error; - } /* Error : offset outside buffers */ - length += read_variable_length( - &ip, iend - LASTLITERALS + 1, - (int)endOnInput, 0, &error); - if (error != ok) { + size_t const addl = read_variable_length( + &ip, iend - LASTLITERALS + 1, 0); + if (addl == rvl_error) { goto _output_error; } - if ((safeDecode) && - unlikely((uptrval)(op) + length < + length += addl; + length += MINMATCH; + if (unlikely((uptrval)(op) + length < (uptrval)op)) { goto _output_error; } /* overflow detection */ - length += MINMATCH; + if ((checkOffset) && + (unlikely(match + dictSize < lowPrefix))) { + goto _output_error; + } /* Error : offset outside buffers */ if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { goto safe_match_copy; @@ -372,7 +485,7 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, goto safe_match_copy; } - /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ + /* Fastpath check: skip LZ4_wildCopy32 when true */ if ((dict == withPrefix64k) || (match >= lowPrefix)) { if (offset >= 8) { @@ -397,6 +510,7 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, } /* Error : offset outside buffers */ /* match starting within external dictionary */ if ((dict == usingExtDict) && (match < lowPrefix)) { + assert(dictEnd != NULL); if (unlikely(op + length > oend - LASTLITERALS)) { if (partialDecoding) { @@ -463,12 +577,10 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ while (1) { + assert(ip < iend); token = *ip++; length = token >> ML_BITS; /* literal length */ - assert(!endOnInput || - ip <= iend); /* ip < iend before the increment */ - /* A two-stage shortcut for the most common case: * 1) If the literal length is 0..14, and there is enough space, * enter the shortcut and copy 16 bytes on behalf of the literals @@ -478,12 +590,11 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, * those 18 bytes earlier, upon entering the shortcut (in other words, * there is a combined check for both stages). */ - if ((endOnInput ? length != RUN_MASK : length <= 8) + if ((length != RUN_MASK) /* strictly "less than" on input, to re-enter the loop with at least one byte */ - && likely((endOnInput ? ip < shortiend : 1) & - (op <= shortoend))) { + && likely((ip < shortiend) & (op <= shortoend))) { /* Copy the literals */ - LZ4_memcpy(op, ip, endOnInput ? 16 : 8); + LZ4_memcpy(op, ip, 16); op += length; ip += length; @@ -515,20 +626,17 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, /* decode literal length */ if (length == RUN_MASK) { - variable_length_error error = ok; - length += read_variable_length( - &ip, iend - RUN_MASK, (int)endOnInput, - (int)endOnInput, &error); - if (error == initial_error) { + size_t const addl = read_variable_length( + &ip, iend - RUN_MASK, 1); + if (addl == rvl_error) { goto _output_error; } - if ((safeDecode) && - unlikely((uptrval)(op) + length < + length += addl; + if (unlikely((uptrval)(op) + length < (uptrval)(op))) { goto _output_error; } /* overflow detection */ - if ((safeDecode) && - unlikely((uptrval)(ip) + length < + if (unlikely((uptrval)(ip) + length < (uptrval)(ip))) { goto _output_error; } /* overflow detection */ @@ -540,10 +648,8 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, safe_literal_copy: #endif LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); - if (((endOnInput) && - ((cpy > oend - MFLIMIT) || - (ip + length > iend - (2 + 1 + LASTLITERALS)))) || - ((!endOnInput) && (cpy > oend - WILDCOPYLENGTH))) { + if ((cpy > oend - MFLIMIT) || + (ip + length > iend - (2 + 1 + LASTLITERALS))) { /* We've either hit the input parsing restriction or the output parsing restriction. * In the normal scenario, decoding a full block, it must be the last sequence, * otherwise it's an error (invalid input or dimensions). @@ -553,7 +659,6 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, /* Since we are partial decoding we may be in this block because of the output parsing * restriction, which is not valid since the output buffer is allowed to be undersized. */ - assert(endOnInput); DEBUGLOG( 7, "partialDecoding: copying literals, close to input or output end") @@ -585,18 +690,11 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, length = (size_t)(oend - op); } } else { - /* We must be on the last sequence because of the parsing limitations so check - * that we exactly regenerate the original size (must be exact when !endOnInput). - */ - if ((!endOnInput) && (cpy != oend)) { - goto _output_error; - } /* We must be on the last sequence (or invalid) because of the parsing limitations * so check that we exactly consume the input and don't overrun the output buffer. */ - if ((endOnInput) && - ((ip + length != iend) || - (cpy > oend))) { + if ((ip + length != iend) || + (cpy > oend)) { DEBUGLOG( 6, "should have been last run of literals") @@ -614,7 +712,7 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, } LZ4_memmove( op, ip, - length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */ + length); /* supports overlapping memory regions, for in-place decompression scenarios */ ip += length; op += length; /* Necessarily EOF when !partialDecoding. @@ -629,7 +727,7 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, } else { LZ4_wildCopy8( op, ip, - cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ + cpy); /* can overwrite up to 8 bytes beyond cpy */ ip += length; op = cpy; } @@ -644,14 +742,13 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, _copy_match: if (length == ML_MASK) { - variable_length_error error = ok; - length += read_variable_length( - &ip, iend - LASTLITERALS + 1, - (int)endOnInput, 0, &error); - if (error != ok) + size_t const addl = read_variable_length( + &ip, iend - LASTLITERALS + 1, 0); + if (addl == rvl_error) { goto _output_error; - if ((safeDecode) && - unlikely((uptrval)(op) + length < + } + length += addl; + if (unlikely((uptrval)(op) + length < (uptrval)op)) goto _output_error; /* overflow detection */ } @@ -665,6 +762,7 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, goto _output_error; /* Error : offset outside buffers */ /* match starting within external dictionary */ if ((dict == usingExtDict) && (match < lowPrefix)) { + assert(dictEnd != NULL); if (unlikely(op + length > oend - LASTLITERALS)) { if (partialDecoding) @@ -776,15 +874,9 @@ LZ4_decompress_generic(const char *const src, char *const dst, int srcSize, } /* end of decoding */ - if (endOnInput) { - DEBUGLOG(5, "decoded %i bytes", - (int)(((char *)op) - dst)); - return (int)(((char *)op) - - dst); /* Nb of output bytes decoded */ - } else { - return (int)(((const char *)ip) - - src); /* Nb of input bytes read */ - } + DEBUGLOG(5, "decoded %i bytes", (int)(((char *)op) - dst)); + return (int)(((char *)op) - + dst); /* Nb of output bytes decoded */ /* Overflow error detected */ _output_error: @@ -796,9 +888,8 @@ int LZ4_decompress_safe(const char *source, char *dest, int compressedSize, int maxDecompressedSize) { return LZ4_decompress_generic(source, dest, compressedSize, - maxDecompressedSize, endOnInputSize, - decode_full_block, noDict, (BYTE *)dest, - NULL, 0); + maxDecompressedSize, decode_full_block, + noDict, (BYTE *)dest, NULL, 0); } int LZ4_decompress_safe_partial(const char *src, char *dst, int compressedSize, @@ -806,16 +897,14 @@ int LZ4_decompress_safe_partial(const char *src, char *dst, int compressedSize, { dstCapacity = min(targetOutputSize, dstCapacity); return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity, - endOnInputSize, partial_decode, noDict, - (BYTE *)dst, NULL, 0); + partial_decode, noDict, (BYTE *)dst, NULL, + 0); } int LZ4_decompress_fast(const char *source, char *dest, int originalSize) { - return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, decode_full_block, - withPrefix64k, (BYTE *)dest - 64 * KB, - NULL, 0); + return LZ4_decompress_unsafe_generic((const BYTE *)source, (BYTE *)dest, + originalSize, 0, NULL, 0); } /* ===== Instantiate a few more decoding cases, used more than once. ===== */ @@ -824,9 +913,9 @@ int LZ4_decompress_safe_withPrefix64k(const char *source, char *dest, int compressedSize, int maxOutputSize) { return LZ4_decompress_generic(source, dest, compressedSize, - maxOutputSize, endOnInputSize, - decode_full_block, withPrefix64k, - (BYTE *)dest - 64 * KB, NULL, 0); + maxOutputSize, decode_full_block, + withPrefix64k, (BYTE *)dest - 64 * KB, + NULL, 0); } static int LZ4_decompress_safe_withSmallPrefix(const char *source, char *dest, @@ -835,8 +924,7 @@ static int LZ4_decompress_safe_withSmallPrefix(const char *source, char *dest, size_t prefixSize) { return LZ4_decompress_generic(source, dest, compressedSize, - maxOutputSize, endOnInputSize, - decode_full_block, noDict, + maxOutputSize, decode_full_block, noDict, (BYTE *)dest - prefixSize, NULL, 0); } @@ -845,20 +933,18 @@ int LZ4_decompress_safe_forceExtDict(const char *source, char *dest, const void *dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, compressedSize, - maxOutputSize, endOnInputSize, - decode_full_block, usingExtDict, - (BYTE *)dest, (const BYTE *)dictStart, - dictSize); + maxOutputSize, decode_full_block, + usingExtDict, (BYTE *)dest, + (const BYTE *)dictStart, dictSize); } static int LZ4_decompress_fast_extDict(const char *source, char *dest, int originalSize, const void *dictStart, size_t dictSize) { - return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, decode_full_block, - usingExtDict, (BYTE *)dest, - (const BYTE *)dictStart, dictSize); + return LZ4_decompress_unsafe_generic((const BYTE *)source, (BYTE *)dest, + originalSize, 0, + (const BYTE *)dictStart, dictSize); } /* @@ -871,9 +957,8 @@ static FORCE_INLINE int LZ4_decompress_safe_doubleDict( size_t prefixSize, const void *dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, compressedSize, - maxOutputSize, endOnInputSize, - decode_full_block, usingExtDict, - (BYTE *)dest - prefixSize, + maxOutputSize, decode_full_block, + usingExtDict, (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize); } @@ -883,8 +968,8 @@ LZ4_decompress_fast_doubleDict(const char *source, char *dest, int originalSize, size_t dictSize) { return LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, decode_full_block, - usingExtDict, (BYTE *)dest - prefixSize, + decode_full_block, usingExtDict, + (BYTE *)dest - prefixSize, (const BYTE *)dictStart, dictSize); } @@ -968,12 +1053,17 @@ int LZ4_decompress_fast_continue(LZ4_streamDecode_t *LZ4_streamDecode, const char *source, char *dest, int originalSize) { - LZ4_streamDecode_t_internal *lz4sd = - &LZ4_streamDecode->internal_donotuse; + LZ4_streamDecode_t_internal *const lz4sd = + (assert(LZ4_streamDecode != NULL), + &LZ4_streamDecode->internal_donotuse); int result; + + DEBUGLOG(5, "LZ4_decompress_fast_continue (toDecodeSize=%i)", + originalSize); assert(originalSize >= 0); if (lz4sd->prefixSize == 0) { + DEBUGLOG(5, "first invocation : no prefix nor extDict"); assert(lz4sd->extDictSize == 0); result = LZ4_decompress_fast(source, dest, originalSize); if (result <= 0) @@ -981,18 +1071,17 @@ int LZ4_decompress_fast_continue(LZ4_streamDecode_t *LZ4_streamDecode, lz4sd->prefixSize = (size_t)originalSize; lz4sd->prefixEnd = (BYTE *)dest + originalSize; } else if (lz4sd->prefixEnd == (BYTE *)dest) { - if (lz4sd->prefixSize >= 64 * KB - 1 || lz4sd->extDictSize == 0) - result = - LZ4_decompress_fast(source, dest, originalSize); - else - result = LZ4_decompress_fast_doubleDict( - source, dest, originalSize, lz4sd->prefixSize, - lz4sd->externalDict, lz4sd->extDictSize); + DEBUGLOG(5, "continue using existing prefix"); + result = LZ4_decompress_unsafe_generic( + (const BYTE *)source, (BYTE *)dest, originalSize, + lz4sd->prefixSize, lz4sd->externalDict, + lz4sd->extDictSize); if (result <= 0) return result; lz4sd->prefixSize += (size_t)originalSize; lz4sd->prefixEnd += originalSize; } else { + DEBUGLOG(5, "prefix becomes extDict"); lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; result = LZ4_decompress_fast_extDict(source, dest, originalSize, @@ -1031,7 +1120,9 @@ int LZ4_decompress_fast_usingDict(const char *source, char *dest, int dictSize) { if (dictSize == 0 || dictStart + dictSize == dest) - return LZ4_decompress_fast(source, dest, originalSize); + return LZ4_decompress_unsafe_generic((const BYTE *)source, + (BYTE *)dest, originalSize, + (size_t)dictSize, NULL, 0); return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize); From 939a9f2ad840e114f92ee14305743dab3f0c8b01 Mon Sep 17 00:00:00 2001 From: Christoph Hellwig Date: Tue, 28 Jun 2022 20:20:47 +0200 Subject: [PATCH 07/29] zram: stop using ->queuedata Instead of setting up the queuedata as well just use one private data field. Signed-off-by: Christoph Hellwig Signed-off-by: Jens Axboe Signed-off-by: Andrzej Perczak --- drivers/block/zram/zram_drv.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c index 7f78f1460f79..d0c9bbf92696 100644 --- a/drivers/block/zram/zram_drv.c +++ b/drivers/block/zram/zram_drv.c @@ -1847,7 +1847,7 @@ static void __zram_make_request(struct zram *zram, struct bio *bio) */ static blk_qc_t zram_make_request(struct request_queue *queue, struct bio *bio) { - struct zram *zram = queue->queuedata; + struct zram *zram = bio->bi_disk->private_data; if (!valid_io_request(zram, bio->bi_iter.bi_sector, bio->bi_iter.bi_size)) { @@ -2175,7 +2175,6 @@ static int zram_add(void) zram->disk->first_minor = device_id; zram->disk->fops = &zram_devops; zram->disk->queue = queue; - zram->disk->queue->queuedata = zram; zram->disk->private_data = zram; snprintf(zram->disk->disk_name, 16, "zram%d", device_id); From 370a088f8ec405a0cdbfc89d9f5bfb0140110471 Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Tue, 28 Jun 2022 20:22:55 +0200 Subject: [PATCH 08/29] zram: off by one in read_block_state() [ Upstream commit a88e03cf3d190cf46bc4063a9b7efe87590de5f4 ] snprintf() returns the number of bytes it would have printed if there were space. But it does not count the NUL terminator. So that means that if "count == copied" then this has already overflowed by one character. This bug likely isn't super harmful in real life. Link: https://lkml.kernel.org/r/20210916130404.GA25094@kili Fixes: c0265342bff4 ("zram: introduce zram memory tracking") Signed-off-by: Dan Carpenter Cc: Minchan Kim Cc: Sergey Senozhatsky Signed-off-by: Andrew Morton Signed-off-by: Linus Torvalds Signed-off-by: Sasha Levin Signed-off-by: Andrzej Perczak --- drivers/block/zram/zram_drv.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c index d0c9bbf92696..4316154180f9 100644 --- a/drivers/block/zram/zram_drv.c +++ b/drivers/block/zram/zram_drv.c @@ -847,7 +847,7 @@ static ssize_t read_block_state(struct file *file, char __user *buf, zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', zram_test_flag(zram, index, ZRAM_DEDUPED) ? 'd' : '.'); - if (count < copied) { + if (count <= copied) { zram_slot_unlock(zram, index); break; } From 5a591f9ff4512f391bf695e0c9ac3329e29029ef Mon Sep 17 00:00:00 2001 From: Ming Lei Date: Fri, 1 Jul 2022 17:35:47 +0200 Subject: [PATCH 09/29] zram: fix race between zram_reset_device() and disksize_store() When the ->init_lock is released in zram_reset_device(), disksize_store() can come in and try to allocate meta, but zram_reset_device() is freeing free meta, so cause races. Link: https://lore.kernel.org/linux-block/20210927163805.808907-1-mcgrof@kernel.org/T/#mc617f865a3fa2778e40f317ddf48f6447c20c073 Reported-by: Luis Chamberlain Reviewed-by: Luis Chamberlain Signed-off-by: Ming Lei Acked-by: Minchan Kim Link: https://lore.kernel.org/r/20211025025426.2815424-2-ming.lei@redhat.com Signed-off-by: Jens Axboe Signed-off-by: Andrzej Perczak --- drivers/block/zram/zram_drv.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c index 4316154180f9..d1a09a503d3e 100644 --- a/drivers/block/zram/zram_drv.c +++ b/drivers/block/zram/zram_drv.c @@ -1952,12 +1952,13 @@ static void zram_reset_device(struct zram *zram) set_capacity(zram->disk, 0); part_stat_set_all(&zram->disk->part0, 0); - up_write(&zram->init_lock); /* I/O operation under all of CPU are done so let's free */ zram_meta_free(zram, disksize); memset(&zram->stats, 0, sizeof(zram->stats)); zcomp_destroy(comp); reset_bdev(zram); + + up_write(&zram->init_lock); } static ssize_t disksize_store(struct device *dev, From 49ddaa3756e3da1b0cde2141049542357e1b5d92 Mon Sep 17 00:00:00 2001 From: Yu Zhao Date: Thu, 21 Jul 2022 01:18:57 -0600 Subject: [PATCH 10/29] mglru: fixes Signed-off-by: Yu Zhao Change-Id: I09999793fd6481bcf2acefb29c57d5d40c0b1427 --- mm/swap.c | 3 ++- mm/vmscan.c | 58 ++++++++++++++++++++++++++++++----------------------- 2 files changed, 35 insertions(+), 26 deletions(-) diff --git a/mm/swap.c b/mm/swap.c index 295dc57b9cf7..aa308b27f5d2 100644 --- a/mm/swap.c +++ b/mm/swap.c @@ -556,7 +556,8 @@ void __lru_cache_add_active_or_unevictable(struct page *page, VM_BUG_ON_PAGE(PageLRU(page), page); if (likely((vma_flags & (VM_LOCKED | VM_SPECIAL)) != VM_LOCKED)) { - SetPageActive(page); + if (!lru_gen_enabled()) + SetPageActive(page); lru_cache_add(page); return; } diff --git a/mm/vmscan.c b/mm/vmscan.c index 9d56e1a2b2ff..4f9c96c49324 100644 --- a/mm/vmscan.c +++ b/mm/vmscan.c @@ -3802,9 +3802,9 @@ static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq, * from the producer's POV, the aging only cares about the upper bound * of hot pages, i.e., 1/MIN_NR_GENS. */ - if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq) + if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) *need_aging = true; - else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq) + else if (min_seq[!can_swap] + MIN_NR_GENS < max_seq) *need_aging = false; else if (young * MIN_NR_GENS > total) *need_aging = true; @@ -3895,10 +3895,9 @@ static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc) * younger than min_ttl. However, another theoretical possibility is all * memcgs are either below min or empty. */ - if (!success && mutex_trylock(&oom_lock)) { + if (!success && !sc->order && mutex_trylock(&oom_lock)) { struct oom_control oc = { .gfp_mask = sc->gfp_mask, - .order = sc->order, }; out_of_memory(&oc); @@ -3938,7 +3937,7 @@ void lru_gen_look_around(struct page_vma_mapped_walk *pvmw) return; start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start); - end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end); + end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1; if (end - start > MIN_LRU_BATCH * PAGE_SIZE) { if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2) @@ -4313,7 +4312,7 @@ static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swapp if (try_to_inc_min_seq(lruvec, swappiness)) scanned++; - if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS) + if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS) scanned = 0; spin_unlock_irq(&pgdat->lru_lock); @@ -4364,33 +4363,38 @@ static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swapp } static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap, - unsigned long *evictable) + unsigned long reclaimed, unsigned long *evictable, bool *need_aging) { - bool need_aging; + int priority; long nr_to_scan; struct mem_cgroup *memcg = lruvec_memcg(lruvec); DEFINE_MAX_SEQ(lruvec); DEFINE_MIN_SEQ(lruvec); - nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging); + nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, need_aging); if (!nr_to_scan) return 0; *evictable = nr_to_scan; - /* reset the priority if the target has been met */ - nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY; - + /* adjust priority if memcg is offline or the target is met */ if (!mem_cgroup_online(memcg)) - nr_to_scan++; + priority = 0; + else if (sc->nr_reclaimed - reclaimed >= sc->nr_to_reclaim) + priority = DEF_PRIORITY; + else + priority = sc->priority; + nr_to_scan >>= priority; if (!nr_to_scan) return 0; - if (!need_aging) { - sc->memcgs_need_aging = false; + if (!*need_aging) return nr_to_scan; - } + + /* skip the aging path at the default priority */ + if (priority == DEF_PRIORITY) + goto done; /* leave the work to lru_gen_age_node() */ if (current_is_kswapd()) @@ -4398,14 +4402,15 @@ static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false)) return nr_to_scan; - - return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0; +done: + return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0; } static unsigned long lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc) { struct blk_plug plug; long scanned = 0; + bool need_aging = false; bool swapped = false; unsigned long evictable = 0; unsigned long reclaimed = sc->nr_reclaimed; @@ -4430,27 +4435,30 @@ static unsigned long lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_co else swappiness = 0; - nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &evictable); + nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, reclaimed, + &evictable, &need_aging); if (!nr_to_scan) - break; + goto done; delta = evict_pages(lruvec, sc, swappiness, &swapped); if (!delta) - break; + goto done; if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped) break; scanned += delta; - if (scanned >= nr_to_scan) { - if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH) - sc->memcgs_need_swapping = false; + if (scanned >= nr_to_scan) break; - } cond_resched(); } + if (!need_aging) + sc->memcgs_need_aging = false; + if (!swapped) + sc->memcgs_need_swapping = false; +done: if (current_is_kswapd()) current->reclaim_state->mm_walk = NULL; From 099b49507a7e62ee7dd666df5059f0cddbd4e4d0 Mon Sep 17 00:00:00 2001 From: "Angelo G. Del Regno" Date: Wed, 27 Feb 2019 11:22:25 +0100 Subject: [PATCH 11/29] thermal: Increase thermal trip points to 16 Some DT devices, mainly smartphones, do need more trip points to allow more fine grained thermal mitigations, hence allowing a better user experience (and overall performance), for example, by lowering the CPU clocks just a little for each temperature step. Signed-off-by: Henrique Pereira Signed-off-by: Panchajanya1999 Signed-off-by: Cyber Knight --- include/linux/thermal.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/linux/thermal.h b/include/linux/thermal.h index a6985901871b..3e58e571a789 100644 --- a/include/linux/thermal.h +++ b/include/linux/thermal.h @@ -33,7 +33,7 @@ #include #define THERMAL_TRIPS_NONE -1 -#define THERMAL_MAX_TRIPS 12 +#define THERMAL_MAX_TRIPS 16 /* invalid cooling state */ #define THERMAL_CSTATE_INVALID -1UL From 7da8a639998fc6919d97f9e7f6a1d6fd0780798f Mon Sep 17 00:00:00 2001 From: pwnrazr <1644943+pwnrazr@users.noreply.github.com> Date: Thu, 18 Aug 2022 14:36:46 +0800 Subject: [PATCH 12/29] mm: cma: include linux/sched/signal.h I get this error when I compile with IPC_LOGGING disabled. I have no clue how to fix seeing as https://github.com/RealJohnGalt/GaltsGulch-sm8150 has exact same cma.c as I do and that kernel can be compiled as far as I can tell without IPC_LOGGING. So just include where it is declared? Anyone please advise if you know where it went wrong ../mm/cma.c:497:9: error: implicit declaration of function 'fatal_signal_pending' [-Werror,-Wimplicit-function-declaration] if (fatal_signal_pending(current)) ^ 1 error generated. --- mm/cma.c | 1 + 1 file changed, 1 insertion(+) diff --git a/mm/cma.c b/mm/cma.c index 25421889b6f8..398ed6dae78c 100644 --- a/mm/cma.c +++ b/mm/cma.c @@ -38,6 +38,7 @@ #include #include #include +#include #include "cma.h" From eb2f537ce49b16050f91b8f04f8ee8edbbb91160 Mon Sep 17 00:00:00 2001 From: Park Ju Hyung Date: Mon, 8 Jul 2019 02:43:37 +0900 Subject: [PATCH 13/29] adreno: hardcode for a640 Signed-off-by: Park Ju Hyung Signed-off-by: celtare21 --- drivers/gpu/msm/adreno.h | 67 +++++++++++++++------------------------- 1 file changed, 25 insertions(+), 42 deletions(-) diff --git a/drivers/gpu/msm/adreno.h b/drivers/gpu/msm/adreno.h index 62a7e1fac5d1..7bf1e68e20de 100644 --- a/drivers/gpu/msm/adreno.h +++ b/drivers/gpu/msm/adreno.h @@ -1220,13 +1220,12 @@ u32 adreno_get_ucode_version(const u32 *data); #define ADRENO_TARGET(_name, _id) \ static inline int adreno_is_##_name(struct adreno_device *adreno_dev) \ { \ - return (ADRENO_GPUREV(adreno_dev) == (_id)); \ + return 0; \ } static inline int adreno_is_a3xx(struct adreno_device *adreno_dev) { - return ((ADRENO_GPUREV(adreno_dev) >= 300) && - (ADRENO_GPUREV(adreno_dev) < 400)); + return 0; } ADRENO_TARGET(a304, ADRENO_REV_A304) @@ -1241,28 +1240,24 @@ ADRENO_TARGET(a330, ADRENO_REV_A330) static inline int adreno_is_a330v2(struct adreno_device *adreno_dev) { - return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A330) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) > 0)); + return 0; } static inline int adreno_is_a330v21(struct adreno_device *adreno_dev) { - return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A330) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) > 0xF)); + return 0; } static inline int adreno_is_a4xx(struct adreno_device *adreno_dev) { - return ADRENO_GPUREV(adreno_dev) >= 400 && - ADRENO_GPUREV(adreno_dev) < 500; + return 0; } ADRENO_TARGET(a405, ADRENO_REV_A405); static inline int adreno_is_a405v2(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A405) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 0x10); + return 0; } ADRENO_TARGET(a418, ADRENO_REV_A418) @@ -1271,14 +1266,12 @@ ADRENO_TARGET(a430, ADRENO_REV_A430) static inline int adreno_is_a430v2(struct adreno_device *adreno_dev) { - return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A430) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1)); + return 0; } static inline int adreno_is_a5xx(struct adreno_device *adreno_dev) { - return ADRENO_GPUREV(adreno_dev) >= 500 && - ADRENO_GPUREV(adreno_dev) < 600; + return 0; } ADRENO_TARGET(a504, ADRENO_REV_A504) @@ -1292,51 +1285,48 @@ ADRENO_TARGET(a540, ADRENO_REV_A540) static inline int adreno_is_a530v1(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A530) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 0); + return 0; } static inline int adreno_is_a530v2(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A530) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1); + return 0; } static inline int adreno_is_a530v3(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A530) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 2); + return 0; } static inline int adreno_is_a504_to_a506(struct adreno_device *adreno_dev) { - return ADRENO_GPUREV(adreno_dev) >= 504 && - ADRENO_GPUREV(adreno_dev) <= 506; + return 0; } static inline int adreno_is_a540v1(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A540) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 0); + return 0; } static inline int adreno_is_a540v2(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A540) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1); + return 0; } static inline int adreno_is_a6xx(struct adreno_device *adreno_dev) { - return ADRENO_GPUREV(adreno_dev) >= 600 && - ADRENO_GPUREV(adreno_dev) < 700; + return 1; +} + +static inline int adreno_is_a640(struct adreno_device *adreno_dev) +{ + return 1; } ADRENO_TARGET(a610, ADRENO_REV_A610) ADRENO_TARGET(a612, ADRENO_REV_A612) ADRENO_TARGET(a618, ADRENO_REV_A618) ADRENO_TARGET(a630, ADRENO_REV_A630) -ADRENO_TARGET(a640, ADRENO_REV_A640) ADRENO_TARGET(a680, ADRENO_REV_A680) /* @@ -1345,22 +1335,17 @@ ADRENO_TARGET(a680, ADRENO_REV_A680) */ static inline int adreno_is_a615_family(struct adreno_device *adreno_dev) { - unsigned int rev = ADRENO_GPUREV(adreno_dev); - - return (rev == ADRENO_REV_A615 || rev == ADRENO_REV_A616 || - rev == ADRENO_REV_A618); + return 0; } static inline int adreno_is_a630v1(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A630) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 0); + return 0; } static inline int adreno_is_a630v2(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A630) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1); + return 0; } static inline int adreno_is_a640v1(struct adreno_device *adreno_dev) @@ -1377,14 +1362,12 @@ static inline int adreno_is_a640v2(struct adreno_device *adreno_dev) static inline int adreno_is_a680v1(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A680) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 0); + return 0; } static inline int adreno_is_a680v2(struct adreno_device *adreno_dev) { - return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A680) && - (ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1); + return 0; } /* From 07d0a47dd8c193b48babbed1d0f9a82697767edf Mon Sep 17 00:00:00 2001 From: Park Ju Hyung Date: Tue, 16 Jul 2019 03:07:37 +0900 Subject: [PATCH 14/29] adreno: leave only /sys/kernel/debug/kgsl/proc/%d/mem for debugfs Others are unused Signed-off-by: Park Ju Hyung Signed-off-by: celtare21 --- drivers/gpu/msm/Makefile | 1 - drivers/gpu/msm/adreno.h | 6 -- drivers/gpu/msm/adreno_profile.h | 11 -- drivers/gpu/msm/kgsl.c | 5 - drivers/gpu/msm/kgsl_debugfs.c | 179 ------------------------------- drivers/gpu/msm/kgsl_debugfs.h | 5 - 6 files changed, 207 deletions(-) diff --git a/drivers/gpu/msm/Makefile b/drivers/gpu/msm/Makefile index 19af028c1da8..dab939205127 100644 --- a/drivers/gpu/msm/Makefile +++ b/drivers/gpu/msm/Makefile @@ -35,7 +35,6 @@ msm_adreno-y += \ adreno_perfcounter.o msm_adreno-$(CONFIG_QCOM_KGSL_IOMMU) += adreno_iommu.o -msm_adreno-$(CONFIG_DEBUG_FS) += adreno_debugfs.o adreno_profile.o msm_adreno-$(CONFIG_COMPAT) += adreno_compat.o msm_kgsl_core-objs = $(msm_kgsl_core-y) diff --git a/drivers/gpu/msm/adreno.h b/drivers/gpu/msm/adreno.h index 7bf1e68e20de..83762912d0bc 100644 --- a/drivers/gpu/msm/adreno.h +++ b/drivers/gpu/msm/adreno.h @@ -1674,16 +1674,10 @@ static inline void adreno_set_protected_registers( *index = *index + 1; } -#ifdef CONFIG_DEBUG_FS -void adreno_debugfs_init(struct adreno_device *adreno_dev); -void adreno_context_debugfs_init(struct adreno_device *adreno_dev, - struct adreno_context *ctx); -#else static inline void adreno_debugfs_init(struct adreno_device *adreno_dev) { } static inline void adreno_context_debugfs_init(struct adreno_device *device, struct adreno_context *context) { } -#endif /** * adreno_compare_pm4_version() - Compare the PM4 microcode version diff --git a/drivers/gpu/msm/adreno_profile.h b/drivers/gpu/msm/adreno_profile.h index 4d81abd14837..9fa059ff0c96 100644 --- a/drivers/gpu/msm/adreno_profile.h +++ b/drivers/gpu/msm/adreno_profile.h @@ -62,16 +62,6 @@ struct adreno_profile { #define ADRENO_PROFILE_LOG_BUF_SIZE_DWORDS (ADRENO_PROFILE_LOG_BUF_SIZE / \ sizeof(unsigned int)) -#ifdef CONFIG_DEBUG_FS -void adreno_profile_init(struct adreno_device *adreno_dev); -void adreno_profile_close(struct adreno_device *adreno_dev); -int adreno_profile_process_results(struct adreno_device *adreno_dev); -void adreno_profile_preib_processing(struct adreno_device *adreno_dev, - struct adreno_context *drawctxt, unsigned int *cmd_flags, - unsigned int **rbptr); -void adreno_profile_postib_processing(struct adreno_device *adreno_dev, - unsigned int *cmd_flags, unsigned int **rbptr); -#else static inline void adreno_profile_init(struct adreno_device *adreno_dev) { } static inline void adreno_profile_close(struct adreno_device *adreno_dev) { } static inline int adreno_profile_process_results( @@ -88,7 +78,6 @@ static inline void adreno_profile_preib_processing( static inline void adreno_profile_postib_processing( struct adreno_device *adreno_dev, unsigned int *cmd_flags, unsigned int **rbptr) { } -#endif static inline bool adreno_profile_enabled(struct adreno_profile *profile) { diff --git a/drivers/gpu/msm/kgsl.c b/drivers/gpu/msm/kgsl.c index b5fd1afda407..6faf21d7cc78 100644 --- a/drivers/gpu/msm/kgsl.c +++ b/drivers/gpu/msm/kgsl.c @@ -4949,9 +4949,6 @@ int kgsl_device_platform_probe(struct kgsl_device *device) if (status) return status; - /* Initialize logging first, so that failures below actually print. */ - kgsl_device_debugfs_init(device); - /* Disable the sparse ioctl invocation as they are not used */ device->flags &= ~KGSL_FLAG_SPARSE; @@ -5094,7 +5091,6 @@ int kgsl_device_platform_probe(struct kgsl_device *device) error_pwrctrl_close: kgsl_pwrctrl_close(device); error: - kgsl_device_debugfs_close(device); _unregister_device(device); return status; } @@ -5123,7 +5119,6 @@ void kgsl_device_platform_remove(struct kgsl_device *device) kgsl_pwrctrl_close(device); - kgsl_device_debugfs_close(device); _unregister_device(device); } EXPORT_SYMBOL(kgsl_device_platform_remove); diff --git a/drivers/gpu/msm/kgsl_debugfs.c b/drivers/gpu/msm/kgsl_debugfs.c index 1b393b8560fa..2fb05cec6430 100644 --- a/drivers/gpu/msm/kgsl_debugfs.c +++ b/drivers/gpu/msm/kgsl_debugfs.c @@ -19,79 +19,9 @@ #include "kgsl_sharedmem.h" #include "kgsl_debugfs.h" -/*default log levels is error for everything*/ -#define KGSL_LOG_LEVEL_MAX 7 - struct dentry *kgsl_debugfs_dir; static struct dentry *proc_d_debugfs; -static inline int kgsl_log_set(unsigned int *log_val, void *data, u64 val) -{ - *log_val = min_t(unsigned int, val, KGSL_LOG_LEVEL_MAX); - return 0; -} - -#define KGSL_DEBUGFS_LOG(__log) \ -static int __log ## _set(void *data, u64 val) \ -{ \ - struct kgsl_device *device = data; \ - return kgsl_log_set(&device->__log, data, val); \ -} \ -static int __log ## _get(void *data, u64 *val) \ -{ \ - struct kgsl_device *device = data; \ - *val = device->__log; \ - return 0; \ -} \ -DEFINE_SIMPLE_ATTRIBUTE(__log ## _fops, \ -__log ## _get, __log ## _set, "%llu\n") \ - -KGSL_DEBUGFS_LOG(drv_log); -KGSL_DEBUGFS_LOG(cmd_log); -KGSL_DEBUGFS_LOG(ctxt_log); -KGSL_DEBUGFS_LOG(mem_log); -KGSL_DEBUGFS_LOG(pwr_log); - -static int _strict_set(void *data, u64 val) -{ - kgsl_sharedmem_set_noretry(val ? true : false); - return 0; -} - -static int _strict_get(void *data, u64 *val) -{ - *val = kgsl_sharedmem_get_noretry(); - return 0; -} - -DEFINE_SIMPLE_ATTRIBUTE(_strict_fops, _strict_get, _strict_set, "%llu\n"); - -void kgsl_device_debugfs_init(struct kgsl_device *device) -{ - if (kgsl_debugfs_dir && !IS_ERR(kgsl_debugfs_dir)) - device->d_debugfs = debugfs_create_dir(device->name, - kgsl_debugfs_dir); - - if (!device->d_debugfs || IS_ERR(device->d_debugfs)) - return; - - debugfs_create_file("log_level_cmd", 0644, device->d_debugfs, device, - &cmd_log_fops); - debugfs_create_file("log_level_ctxt", 0644, device->d_debugfs, device, - &ctxt_log_fops); - debugfs_create_file("log_level_drv", 0644, device->d_debugfs, device, - &drv_log_fops); - debugfs_create_file("log_level_mem", 0644, device->d_debugfs, device, - &mem_log_fops); - debugfs_create_file("log_level_pwr", 0644, device->d_debugfs, device, - &pwr_log_fops); -} - -void kgsl_device_debugfs_close(struct kgsl_device *device) -{ - debugfs_remove_recursive(device->d_debugfs); -} - struct type_entry { int type; const char *str; @@ -301,96 +231,6 @@ static const struct file_operations process_mem_fops = { .release = process_mem_release, }; -static int print_sparse_mem_entry(int id, void *ptr, void *data) -{ - struct seq_file *s = data; - struct kgsl_mem_entry *entry = ptr; - struct kgsl_memdesc *m = &entry->memdesc; - struct rb_node *node; - - if (!(m->flags & KGSL_MEMFLAGS_SPARSE_VIRT)) - return 0; - - spin_lock(&entry->bind_lock); - node = rb_first(&entry->bind_tree); - - while (node != NULL) { - struct sparse_bind_object *obj = rb_entry(node, - struct sparse_bind_object, node); - seq_printf(s, "%5d %16llx %16llx %16llx %16llx\n", - entry->id, entry->memdesc.gpuaddr, - obj->v_off, obj->size, obj->p_off); - node = rb_next(node); - } - spin_unlock(&entry->bind_lock); - - seq_putc(s, '\n'); - - return 0; -} - -static int process_sparse_mem_print(struct seq_file *s, void *unused) -{ - struct kgsl_process_private *private = s->private; - - seq_printf(s, "%5s %16s %16s %16s %16s\n", - "v_id", "gpuaddr", "v_offset", "v_size", "p_offset"); - - spin_lock(&private->mem_lock); - idr_for_each(&private->mem_idr, print_sparse_mem_entry, s); - spin_unlock(&private->mem_lock); - - return 0; -} - -static int process_sparse_mem_open(struct inode *inode, struct file *file) -{ - int ret; - pid_t pid = (pid_t) (unsigned long) inode->i_private; - struct kgsl_process_private *private = NULL; - - private = kgsl_process_private_find(pid); - - if (!private) - return -ENODEV; - - ret = single_open(file, process_sparse_mem_print, private); - if (ret) - kgsl_process_private_put(private); - - return ret; -} - -static const struct file_operations process_sparse_mem_fops = { - .open = process_sparse_mem_open, - .read = seq_read, - .llseek = seq_lseek, - .release = process_mem_release, -}; - -static int globals_print(struct seq_file *s, void *unused) -{ - kgsl_print_global_pt_entries(s); - return 0; -} - -static int globals_open(struct inode *inode, struct file *file) -{ - return single_open(file, globals_print, NULL); -} - -static int globals_release(struct inode *inode, struct file *file) -{ - return single_release(inode, file); -} - -static const struct file_operations global_fops = { - .open = globals_open, - .read = seq_read, - .llseek = seq_lseek, - .release = globals_release, -}; - /** * kgsl_process_init_debugfs() - Initialize debugfs for a process * @private: Pointer to process private structure created for the process @@ -431,31 +271,12 @@ void kgsl_process_init_debugfs(struct kgsl_process_private *private) if (IS_ERR_OR_NULL(dentry)) WARN((dentry == NULL), "Unable to create 'mem' file for %s\n", name); - - dentry = debugfs_create_file("sparse_mem", 0444, private->debug_root, - (void *) ((unsigned long) pid_nr(private->pid)), - &process_sparse_mem_fops); - - if (IS_ERR_OR_NULL(dentry)) - WARN((dentry == NULL), - "Unable to create 'sparse_mem' file for %s\n", name); - } void kgsl_core_debugfs_init(void) { - struct dentry *debug_dir; - kgsl_debugfs_dir = debugfs_create_dir("kgsl", NULL); - debugfs_create_file("globals", 0444, kgsl_debugfs_dir, NULL, - &global_fops); - - debug_dir = debugfs_create_dir("debug", kgsl_debugfs_dir); - - debugfs_create_file("strict_memory", 0644, debug_dir, NULL, - &_strict_fops); - proc_d_debugfs = debugfs_create_dir("proc", kgsl_debugfs_dir); } diff --git a/drivers/gpu/msm/kgsl_debugfs.h b/drivers/gpu/msm/kgsl_debugfs.h index 7c9ab8f925a2..3774dfa30889 100644 --- a/drivers/gpu/msm/kgsl_debugfs.h +++ b/drivers/gpu/msm/kgsl_debugfs.h @@ -22,9 +22,6 @@ struct kgsl_process_private; void kgsl_core_debugfs_init(void); void kgsl_core_debugfs_close(void); -void kgsl_device_debugfs_init(struct kgsl_device *device); -void kgsl_device_debugfs_close(struct kgsl_device *device); - extern struct dentry *kgsl_debugfs_dir; static inline struct dentry *kgsl_get_debugfs_dir(void) { @@ -34,8 +31,6 @@ static inline struct dentry *kgsl_get_debugfs_dir(void) void kgsl_process_init_debugfs(struct kgsl_process_private *priv); #else static inline void kgsl_core_debugfs_init(void) { } -static inline void kgsl_device_debugfs_init(struct kgsl_device *device) { } -static inline void kgsl_device_debugfs_close(struct kgsl_device *device) { } static inline void kgsl_core_debugfs_close(void) { } static inline struct dentry *kgsl_get_debugfs_dir(void) { return NULL; } static inline void kgsl_process_init_debugfs(struct kgsl_process_private *priv) From 4309d369e6ee93b2ee342fd0a5c08ede4bf1260b Mon Sep 17 00:00:00 2001 From: celtare21 Date: Thu, 20 Feb 2020 09:12:03 +0000 Subject: [PATCH 15/29] gpu: msm: Remove tracing Signed-off-by: celtare21 Change-Id: I530538ac90d4e1e2e7e1835b2124a2d541f938f0 --- drivers/gpu/msm/kgsl_pwrctrl.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/drivers/gpu/msm/kgsl_pwrctrl.c b/drivers/gpu/msm/kgsl_pwrctrl.c index a78a8aaafa77..546749293288 100644 --- a/drivers/gpu/msm/kgsl_pwrctrl.c +++ b/drivers/gpu/msm/kgsl_pwrctrl.c @@ -481,11 +481,6 @@ void kgsl_pwrctrl_pwrlevel_change(struct kgsl_device *device, kgsl_clk_set_rate(device, pwr->active_pwrlevel); _isense_clk_set_rate(pwr, pwr->active_pwrlevel); - trace_kgsl_pwrlevel(device, - pwr->active_pwrlevel, pwrlevel->gpu_freq, - pwr->previous_pwrlevel, - pwr->pwrlevels[old_level].gpu_freq); - /* * Some targets do not support the bandwidth requirement of * GPU at TURBO, for such targets we need to set GPU-BIMC From 013b140a21fed482de3c974d4a733ad47d3ec98c Mon Sep 17 00:00:00 2001 From: Sami Tolvanen Date: Fri, 19 Jan 2018 11:19:11 -0800 Subject: [PATCH 16/29] msm: ipa3: fix callback function type for ndo_start_xmit Bug: 67506682 Change-Id: Iad7ed493bd29e2da85e2d6bc0f1dc0fbdac8a41d Signed-off-by: Sami Tolvanen (cherry picked from commit f4dbb3c698af0bcf83df4f6b55ac714295c572d3) (cherry picked from commit 6b4c6da82352590f93ab25951e415142cb66ea61) (cherry picked from commit a853bd62173442182dcc7520186095b1da2989c3) (cherry picked from commit 09b9474be7b961c95ba107b91bccbaab92939b2d) Signed-off-by: Panchajanya1999 --- drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c b/drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c index 8ed317e07a00..2f92e2de73a0 100644 --- a/drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c +++ b/drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c @@ -1235,9 +1235,9 @@ static int ipa3_wwan_change_mtu(struct net_device *dev, int new_mtu) * later * -EFAULT: Error while transmitting the skb */ -static int ipa3_wwan_xmit(struct sk_buff *skb, struct net_device *dev) +static netdev_tx_t ipa3_wwan_xmit(struct sk_buff *skb, struct net_device *dev) { - int ret = 0; + netdev_tx_t ret = NETDEV_TX_OK; bool qmap_check; struct ipa3_wwan_private *wwan_ptr = netdev_priv(dev); unsigned long flags; From a8e0ee3880b1addcc48e7fc323f046ffae926341 Mon Sep 17 00:00:00 2001 From: Danny Lin Date: Mon, 23 Sep 2019 19:29:26 -0700 Subject: [PATCH 17/29] drm/msm/dsi-staging: Fix CFI violation in DSI clock control path Signed-off-by: Danny Lin [@0ctobot: Adapted for 4.14] Signed-off-by: Adam W. Willis Signed-off-by: azrim --- drivers/gpu/drm/msm/dsi-staging/dsi_clk.h | 3 +-- drivers/gpu/drm/msm/dsi-staging/dsi_display.c | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/msm/dsi-staging/dsi_clk.h b/drivers/gpu/drm/msm/dsi-staging/dsi_clk.h index 94cd7d82c6a0..f90d773a1c55 100644 --- a/drivers/gpu/drm/msm/dsi-staging/dsi_clk.h +++ b/drivers/gpu/drm/msm/dsi-staging/dsi_clk.h @@ -279,8 +279,7 @@ int dsi_display_link_clk_force_update(void *handle); * * return: error code in case of failure or 0 for success. */ -int dsi_display_clk_ctrl(void *handle, - enum dsi_clk_type clk_type, enum dsi_clk_state clk_state); +int dsi_display_clk_ctrl(void *handle, u32 clk_type, u32 clk_state); /** * dsi_clk_set_link_frequencies() - set frequencies for link clks diff --git a/drivers/gpu/drm/msm/dsi-staging/dsi_display.c b/drivers/gpu/drm/msm/dsi-staging/dsi_display.c index 28e99f05f1cc..84242ae42409 100644 --- a/drivers/gpu/drm/msm/dsi-staging/dsi_display.c +++ b/drivers/gpu/drm/msm/dsi-staging/dsi_display.c @@ -5067,8 +5067,7 @@ static int dsi_display_link_clk_force_update_ctrl(void *handle) return rc; } -int dsi_display_clk_ctrl(void *handle, - enum dsi_clk_type clk_type, enum dsi_clk_state clk_state) +int dsi_display_clk_ctrl(void *handle, u32 clk_type, u32 clk_state) { int rc = 0; From f3959073a44e48cd57dd0e157e3e04f2edf2da3d Mon Sep 17 00:00:00 2001 From: "Angelo G. Del Regno" Date: Thu, 6 Jun 2019 10:34:58 +0200 Subject: [PATCH 18/29] platform: msm: ipa: Correctly allocate memory for copy_from_user Copying from user to a global variable inside the driver is unsafe and insecure: allocate and free the memory used for copying from userspace in the functions doing it. This also has the good side effect of solving a build failure when the kernel is built with GCC >=4.9 Change-Id: I04bfb0cd0ffb6870481f639818cf8c51191d927d --- drivers/char/rdbg.c | 2 +- drivers/platform/msm/ipa/ipa_api.c | 26 +++++++++++++ .../platform/msm/ipa/ipa_clients/odu_bridge.c | 12 ++++-- drivers/platform/msm/ipa/ipa_common_i.h | 3 ++ drivers/platform/msm/ipa/ipa_v3/ipa.c | 30 +++++++++------ drivers/platform/msm/ipa/ipa_v3/ipa_debugfs.c | 38 ++++++++++++------- drivers/platform/msm/ipa/ipa_v3/ipa_dma.c | 12 ++++-- .../platform/msm/ipa/ipa_v3/ipa_hw_stats.c | 28 +++++++++----- drivers/platform/msm/ipa/ipa_v3/ipa_i.h | 2 + 9 files changed, 112 insertions(+), 41 deletions(-) diff --git a/drivers/char/rdbg.c b/drivers/char/rdbg.c index 0c623221bd1c..400efb134c55 100644 --- a/drivers/char/rdbg.c +++ b/drivers/char/rdbg.c @@ -136,7 +136,7 @@ struct rdbg_device { int registers[32] = {0}; static struct rdbg_device g_rdbg_instance = { - { {0} }, + {}, NULL, 0, SMP2P_NUM_PROCS, diff --git a/drivers/platform/msm/ipa/ipa_api.c b/drivers/platform/msm/ipa/ipa_api.c index 4f3be33dd6bd..e685581d278d 100644 --- a/drivers/platform/msm/ipa/ipa_api.c +++ b/drivers/platform/msm/ipa/ipa_api.c @@ -111,6 +111,32 @@ static bool running_emulation; static enum ipa_hw_type ipa_api_hw_type; static struct ipa_api_controller *ipa_api_ctrl; +#define MAX_CPY_BUFF_SZ 4096 +unsigned long +ipa_safe_copy_from_user(char *dst, const char __user *buf, size_t count) +{ + unsigned long missing = 0; + char *from_user = NULL; + int sz; + + if (MAX_CPY_BUFF_SZ < count + 1) + return ULONG_MAX; + + sz = count * sizeof(char); + from_user = kmalloc(sz + 1, GFP_KERNEL); + if (!from_user) + return ULONG_MAX; + + missing = copy_from_user(from_user, buf, count); + if (missing) + goto end; + + memcpy(dst, from_user, sz); +end: + kfree(from_user); + return missing; +} + const char *ipa_clients_strings[IPA_CLIENT_MAX] = { __stringify(IPA_CLIENT_HSIC1_PROD), __stringify(IPA_CLIENT_HSIC1_CONS), diff --git a/drivers/platform/msm/ipa/ipa_clients/odu_bridge.c b/drivers/platform/msm/ipa/ipa_clients/odu_bridge.c index 2e82040cc10a..184c0a1dd8aa 100644 --- a/drivers/platform/msm/ipa/ipa_clients/odu_bridge.c +++ b/drivers/platform/msm/ipa/ipa_clients/odu_bridge.c @@ -159,7 +159,7 @@ static struct odu_bridge_ctx *odu_bridge_ctx; #ifdef CONFIG_DEBUG_FS #define ODU_MAX_MSG_LEN 512 -static char dbg_buff[ODU_MAX_MSG_LEN]; +static char *dbg_buff; #endif static void odu_bridge_emb_cons_cb(void *priv, enum ipa_dp_evt_type evt, @@ -710,10 +710,10 @@ static ssize_t odu_debugfs_hw_bridge_mode_write(struct file *file, unsigned long missing; enum odu_bridge_mode mode; - if (sizeof(dbg_buff) < count + 1) + if (ODU_MAX_MSG_LEN < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) return -EFAULT; @@ -783,6 +783,10 @@ static void odu_debugfs_init(void) return; } + dbg_buff = kmalloc(ODU_MAX_MSG_LEN * sizeof(char), GFP_KERNEL); + if (!dbg_buff) + return; + dfile_stats = debugfs_create_file("stats", read_only_mode, dent, 0, &odu_stats_ops); @@ -802,12 +806,14 @@ static void odu_debugfs_init(void) return; fail: + kfree(dbg_buff); debugfs_remove_recursive(dent); } static void odu_debugfs_destroy(void) { debugfs_remove_recursive(dent); + kfree(dbg_buff); } #else diff --git a/drivers/platform/msm/ipa/ipa_common_i.h b/drivers/platform/msm/ipa/ipa_common_i.h index c956533495e8..840785f17a02 100644 --- a/drivers/platform/msm/ipa/ipa_common_i.h +++ b/drivers/platform/msm/ipa/ipa_common_i.h @@ -353,6 +353,9 @@ extern const char *ipa_clients_strings[]; ## args); \ } while (0) +unsigned long +ipa_safe_copy_from_user(char *dst, const char __user *buf, size_t count); + void ipa_inc_client_enable_clks(struct ipa_active_client_logging_info *id); void ipa_dec_client_disable_clks(struct ipa_active_client_logging_info *id); int ipa_inc_client_enable_clks_no_block( diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa.c b/drivers/platform/msm/ipa/ipa_v3/ipa.c index 13c4efeb69aa..6e12711f9027 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa.c +++ b/drivers/platform/msm/ipa/ipa_v3/ipa.c @@ -6691,19 +6691,24 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { unsigned long missing; - - char dbg_buff[32] = { 0 }; + char *dbg_buff = NULL; + int ret = 0; int i = 0; - if (sizeof(dbg_buff) < count + 1) + if (count < 2) return -EFAULT; - missing = copy_from_user(dbg_buff, buf, min(sizeof(dbg_buff), count)); + dbg_buff = kmalloc((count + 1) * sizeof(char), GFP_KERNEL); + if (!dbg_buff) + return -ENOMEM; + + missing = copy_from_user(dbg_buff, buf, count); if (missing) { IPAERR("Unable to copy data from user\n"); - return -EFAULT; + ret = -EFAULT; + goto end; } if (count > 0) @@ -6720,7 +6725,7 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, if (i == count) { IPADBG("Empty ipa_config file\n"); - return count; + goto end_msg; } /* Check MHI configuration on MDM devices */ @@ -6751,7 +6756,7 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, ipa3_ctx->vlan_mode_iface[IPA_VLAN_IF_RNDIS]); IPAERR("ecm vlan(%d)\n", ipa3_ctx->vlan_mode_iface[IPA_VLAN_IF_ECM]); - return count; + goto end_msg; } /* trim ending newline character if any */ @@ -6768,7 +6773,7 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, } else if (strcmp(dbg_buff, "1")) { IPAERR("got invalid string %s not loading FW\n", dbg_buff); - return count; + goto end_msg; } pr_info("IPA is loading with %sMHI configuration\n", ipa3_ctx->ipa_config_is_mhi ? "" : "non "); @@ -6776,12 +6781,12 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, /* Prevent consequent calls from trying to load the FW again. */ if (ipa3_is_ready()) - return count; + goto end_msg; /* Prevent multiple calls from trying to load the FW again. */ if (ipa3_ctx->fw_loaded) { IPAERR("not load FW again\n"); - return count; + goto end_msg; } /* Schedule WQ to load ipa-fws */ @@ -6790,8 +6795,11 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, queue_work(ipa3_ctx->transport_power_mgmt_wq, &ipa3_fw_loading_work); +end_msg: IPADBG("Scheduled a work to load IPA FW\n"); - return count; +end: + kfree(dbg_buff); + return ret < 0 ? ret : count; } /** diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa_debugfs.c b/drivers/platform/msm/ipa/ipa_v3/ipa_debugfs.c index e95465b11699..a8544b9dd3f2 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa_debugfs.c +++ b/drivers/platform/msm/ipa/ipa_v3/ipa_debugfs.c @@ -113,14 +113,16 @@ const char *ipa3_hdr_proc_type_name[] = { __stringify(IPA_HDR_PROC_SET_DSCP), }; +#define MAX_DBG_BUFF_SZ 4096 + static struct dentry *dent; -static char dbg_buff[IPA_MAX_MSG_LEN + 1]; +static struct dentry *dent_eth; +static char *dbg_buff; static char *active_clients_buf; static s8 ep_reg_idx; static void *ipa_ipc_low_buff; - static ssize_t ipa3_read_gen_reg(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) { @@ -165,10 +167,10 @@ static ssize_t ipa3_write_ep_holb(struct file *file, unsigned long missing; char *sptr, *token; - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, buf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, buf, count); if (missing) return -EFAULT; @@ -208,10 +210,10 @@ static ssize_t ipa3_write_ep_reg(struct file *file, const char __user *buf, unsigned long missing; s8 option = 0; - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, buf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, buf, count); if (missing) return -EFAULT; @@ -346,10 +348,10 @@ static ssize_t ipa3_write_keep_awake(struct file *file, const char __user *buf, unsigned long missing; s8 option = 0; - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, buf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, buf, count); if (missing) return -EFAULT; @@ -1600,10 +1602,10 @@ static ssize_t ipa3_write_dbg_cnt(struct file *file, const char __user *buf, return -EPERM; } - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, buf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, buf, count); if (missing) return -EFAULT; @@ -2602,10 +2604,10 @@ static ssize_t ipa3_clear_active_clients_log(struct file *file, unsigned long missing; s8 option = 0; - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) return -EFAULT; @@ -2624,10 +2626,10 @@ static ssize_t ipa3_enable_ipc_low(struct file *file, unsigned long missing; s8 option = 0; - if (sizeof(dbg_buff) < count + 1) + if (MAX_DBG_BUFF_SZ < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) return -EFAULT; @@ -2965,6 +2967,10 @@ void ipa3_debugfs_post_init(void) return; } + dbg_buff = kmalloc(MAX_DBG_BUFF_SZ * sizeof(char), GFP_KERNEL); + if (!dbg_buff) + return; + file = debugfs_create_u32("hw_type", IPA_READ_ONLY_MODE, dent, &ipa3_ctx->ipa_hw_type); if (!file) { @@ -3033,6 +3039,7 @@ void ipa3_debugfs_post_init(void) return; fail: + kfree(dbg_buff); debugfs_remove_recursive(dent); } @@ -3047,6 +3054,9 @@ void ipa3_debugfs_remove(void) active_clients_buf = NULL; } debugfs_remove_recursive(dent); + kfree(dbg_buff); + + ipa_debugfs_remove_stats(); } struct dentry *ipa_debugfs_get_root(void) diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa_dma.c b/drivers/platform/msm/ipa/ipa_v3/ipa_dma.c index 35ddc6fac361..19bfe6392e1d 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa_dma.c +++ b/drivers/platform/msm/ipa/ipa_v3/ipa_dma.c @@ -67,7 +67,7 @@ #ifdef CONFIG_DEBUG_FS #define IPADMA_MAX_MSG_LEN 1024 -static char dbg_buff[IPADMA_MAX_MSG_LEN]; +static char *dbg_buff; static void ipa3_dma_debugfs_init(void); static void ipa3_dma_debugfs_destroy(void); #else @@ -1196,10 +1196,10 @@ static ssize_t ipa3_dma_debugfs_reset_statistics(struct file *file, unsigned long missing; s8 in_num = 0; - if (sizeof(dbg_buff) < count + 1) + if (IPADMA_MAX_MSG_LEN < count + 1) return -EFAULT; - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) return -EFAULT; @@ -1236,6 +1236,10 @@ static void ipa3_dma_debugfs_init(void) return; } + dbg_buff = kmalloc(IPADMA_MAX_MSG_LEN * sizeof(char), GFP_KERNEL); + if (!dbg_buff) + return; + dfile_info = debugfs_create_file("info", read_write_mode, dent, 0, &ipa3_ipadma_stats_ops); @@ -1245,12 +1249,14 @@ static void ipa3_dma_debugfs_init(void) } return; fail: + kfree(dbg_buff); debugfs_remove_recursive(dent); } static void ipa3_dma_debugfs_destroy(void) { debugfs_remove_recursive(dent); + kfree(dbg_buff); } #endif /* !CONFIG_DEBUG_FS */ diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa_hw_stats.c b/drivers/platform/msm/ipa/ipa_v3/ipa_hw_stats.c index 0cf0e60617b9..ad7ceff6cab0 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa_hw_stats.c +++ b/drivers/platform/msm/ipa/ipa_v3/ipa_hw_stats.c @@ -1618,7 +1618,7 @@ int ipa_reset_all_drop_stats(void) int ipa_debugfs_init_stats(struct dentry *parent) { return 0; } #else #define IPA_MAX_MSG_LEN 4096 -static char dbg_buff[IPA_MAX_MSG_LEN]; +static char *dbg_buff; static ssize_t ipa_debugfs_reset_quota_stats(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos) @@ -1628,12 +1628,12 @@ static ssize_t ipa_debugfs_reset_quota_stats(struct file *file, int ret; mutex_lock(&ipa3_ctx->lock); - if (sizeof(dbg_buff) < count + 1) { + if (IPA_MAX_MSG_LEN < count + 1) { ret = -EFAULT; goto bail; } - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) { ret = -EFAULT; goto bail; @@ -1727,12 +1727,12 @@ static ssize_t ipa_debugfs_reset_tethering_stats(struct file *file, int ret; mutex_lock(&ipa3_ctx->lock); - if (sizeof(dbg_buff) < count + 1) { + if (IPA_MAX_MSG_LEN < count + 1) { ret = -EFAULT; goto bail; } - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) { ret = -EFAULT; goto bail; @@ -1861,12 +1861,12 @@ static ssize_t ipa_debugfs_control_flt_rt_stats(struct file *file, } mutex_lock(&ipa3_ctx->lock); - if (sizeof(dbg_buff) < count + 1) { + if (IPA_MAX_MSG_LEN < count + 1) { ret = -EFAULT; goto bail; } - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) { ret = -EFAULT; goto bail; @@ -1962,12 +1962,12 @@ static ssize_t ipa_debugfs_reset_drop_stats(struct file *file, int ret; mutex_lock(&ipa3_ctx->lock); - if (sizeof(dbg_buff) < count + 1) { + if (IPA_MAX_MSG_LEN < count + 1) { ret = -EFAULT; goto bail; } - missing = copy_from_user(dbg_buff, ubuf, min(sizeof(dbg_buff), count)); + missing = ipa_safe_copy_from_user(dbg_buff, ubuf, count); if (missing) { ret = -EFAULT; goto bail; @@ -2166,6 +2166,10 @@ int ipa_debugfs_init_stats(struct dentry *parent) return -EFAULT; } + dbg_buff = kmalloc(IPA_MAX_MSG_LEN * sizeof(char), GFP_KERNEL); + if (!dbg_buff) + return -ENOMEM; + file = debugfs_create_file("quota", read_write_mode, dent, NULL, &ipa3_quota_ops); if (IS_ERR_OR_NULL(file)) { @@ -2204,6 +2208,12 @@ int ipa_debugfs_init_stats(struct dentry *parent) return 0; fail: debugfs_remove_recursive(dent); + kfree(dbg_buff); return -EFAULT; } + +void ipa_debugfs_remove_stats(void) +{ + kfree(dbg_buff); +} #endif diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa_i.h b/drivers/platform/msm/ipa/ipa_v3/ipa_i.h index a74214584e9e..0afed2d9d330 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa_i.h +++ b/drivers/platform/msm/ipa/ipa_v3/ipa_i.h @@ -3039,6 +3039,8 @@ int ipa_hw_stats_init(void); int ipa_init_flt_rt_stats(void); int ipa_debugfs_init_stats(struct dentry *parent); +void ipa_debugfs_remove_stats(void); +#endif int ipa_init_quota_stats(u32 pipe_bitmask); From 575c697778971aec3bd45554865ad7b7afd75528 Mon Sep 17 00:00:00 2001 From: MarijnS95 Date: Sat, 8 Jun 2019 12:20:27 +0200 Subject: [PATCH 19/29] platform: msm: ipav3: Correct smallest ipa3_write string to 1. The smallest string that this function deals with is "1", which is of size 1. Correct the if to allow this case. Change-Id: Iaa68bcc452a3428d4752e5c34c98d0bd2e926c5a Signed-off-by: MarijnS95 --- drivers/platform/msm/ipa/ipa_v3/ipa.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/platform/msm/ipa/ipa_v3/ipa.c b/drivers/platform/msm/ipa/ipa_v3/ipa.c index 6e12711f9027..38a3436dda8d 100644 --- a/drivers/platform/msm/ipa/ipa_v3/ipa.c +++ b/drivers/platform/msm/ipa/ipa_v3/ipa.c @@ -6696,8 +6696,8 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, int i = 0; - if (count < 2) - return -EFAULT; + if (count < 1) + return -EINVAL; dbg_buff = kmalloc((count + 1) * sizeof(char), GFP_KERNEL); if (!dbg_buff) @@ -6773,7 +6773,7 @@ static ssize_t ipa3_write(struct file *file, const char __user *buf, } else if (strcmp(dbg_buff, "1")) { IPAERR("got invalid string %s not loading FW\n", dbg_buff); - goto end_msg; + goto end; } pr_info("IPA is loading with %sMHI configuration\n", ipa3_ctx->ipa_config_is_mhi ? "" : "non "); From 2e20f994c06e7adf61f66718a6cb85a5e43b624b Mon Sep 17 00:00:00 2001 From: atndko Date: Sun, 20 Dec 2020 14:58:19 +0800 Subject: [PATCH 20/29] icnss: Fix log spam caused by wrong paired PM operation for ICNSS Becauase of using wrong pair of PM operation device was not resuming if suspend fails. Also device gives errors in dmesg like below: [ 2420.308491] dpm_run_callback(): icnss_pm_suspend_noirq+0x0/0xc0 returns -11 [ 2420.308510] PM: Device 18800000.qcom,icnss failed to suspend async: error -11 [ 2420.312069] PM: noirq suspend of devices failed [ 2423.384002] dpm_run_callback(): icnss_pm_suspend_noirq+0x0/0xc0 returns -11 [ 2423.384020] PM: Device 18800000.qcom,icnss failed to suspend async: error -11 [ 2423.317523] PM: noirq suspend of devices failed [ 2426.444164] dpm_run_callback(): icnss_pm_suspend_noirq+0x0/0xc0 returns -11 [ 2426.444181] PM: Device 18800000.qcom,icnss failed to suspend async: error -11 [ 2426.447813] PM: noirq suspend of devices failed [ 2428.915643] dpm_run_callback(): icnss_pm_suspend_noirq+0x0/0xc0 returns -11 [ 2428.915659] PM: Device 18800000.qcom,icnss failed to suspend async: error -11 [ 2428.919208] PM: noirq suspend of devices failed [ 2429.529067] dpm_run_callback(): icnss_pm_suspend_noirq+0x0/0xc0 returns -11 [ 2429.529086] PM: Device 18800000.qcom,icnss failed to suspend async: error -11 [ 2423.532786] PM: noirq suspend of devices failed Adding changes to use correct set of PM operations and fix log spam. Signed-off-by: atndko --- drivers/soc/qcom/icnss.c | 48 ++++++++++++++++---------------- drivers/soc/qcom/icnss_private.h | 10 +++---- include/soc/qcom/icnss.h | 2 ++ 3 files changed, 31 insertions(+), 29 deletions(-) diff --git a/drivers/soc/qcom/icnss.c b/drivers/soc/qcom/icnss.c index 80eb4d3e51af..ee9385fee2e6 100644 --- a/drivers/soc/qcom/icnss.c +++ b/drivers/soc/qcom/icnss.c @@ -3122,8 +3122,8 @@ static int icnss_stats_show_state(struct seq_file *s, struct icnss_priv *priv) case ICNSS_PM_SUSPEND: seq_puts(s, "PM SUSPEND"); continue; - case ICNSS_PM_SUSPEND_NOIRQ: - seq_puts(s, "PM SUSPEND NOIRQ"); + case ICNSS_PM_SUSPEND_LATE: + seq_puts(s, "PM SUSPEND LATE"); continue; case ICNSS_SSR_REGISTERED: seq_puts(s, "SSR REGISTERED"); @@ -3301,10 +3301,10 @@ static int icnss_stats_show(struct seq_file *s, void *data) ICNSS_STATS_DUMP(s, priv, pm_suspend_err); ICNSS_STATS_DUMP(s, priv, pm_resume); ICNSS_STATS_DUMP(s, priv, pm_resume_err); - ICNSS_STATS_DUMP(s, priv, pm_suspend_noirq); - ICNSS_STATS_DUMP(s, priv, pm_suspend_noirq_err); - ICNSS_STATS_DUMP(s, priv, pm_resume_noirq); - ICNSS_STATS_DUMP(s, priv, pm_resume_noirq_err); + ICNSS_STATS_DUMP(s, priv, pm_suspend_late); + ICNSS_STATS_DUMP(s, priv, pm_suspend_late_err); + ICNSS_STATS_DUMP(s, priv, pm_resume_early); + ICNSS_STATS_DUMP(s, priv, pm_resume_early_err); ICNSS_STATS_DUMP(s, priv, pm_stay_awake); ICNSS_STATS_DUMP(s, priv, pm_relax); @@ -4009,60 +4009,60 @@ static int icnss_pm_resume(struct device *dev) return ret; } -static int icnss_pm_suspend_noirq(struct device *dev) +static int icnss_pm_suspend_late(struct device *dev) { struct icnss_priv *priv = dev_get_drvdata(dev); int ret = 0; if (priv->magic != ICNSS_MAGIC) { - icnss_pr_err("Invalid drvdata for pm suspend_noirq: dev %pK, data %pK, magic 0x%x\n", + icnss_pr_err("Invalid drvdata for pm suspend_late: dev %pK, data %pK, magic 0x%x\n", dev, priv, priv->magic); return -EINVAL; } - icnss_pr_vdbg("PM suspend_noirq, state: 0x%lx\n", priv->state); + icnss_pr_vdbg("PM suspend_late, state: 0x%lx\n", priv->state); - if (!priv->ops || !priv->ops->suspend_noirq || + if (!priv->ops || !priv->ops->suspend_late || !test_bit(ICNSS_DRIVER_PROBED, &priv->state)) goto out; - ret = priv->ops->suspend_noirq(dev); + ret = priv->ops->suspend_late(dev); out: if (ret == 0) { - priv->stats.pm_suspend_noirq++; - set_bit(ICNSS_PM_SUSPEND_NOIRQ, &priv->state); + priv->stats.pm_suspend_late++; + set_bit(ICNSS_PM_SUSPEND_LATE, &priv->state); } else { - priv->stats.pm_suspend_noirq_err++; + priv->stats.pm_suspend_late_err++; } return ret; } -static int icnss_pm_resume_noirq(struct device *dev) +static int icnss_pm_resume_early(struct device *dev) { struct icnss_priv *priv = dev_get_drvdata(dev); int ret = 0; if (priv->magic != ICNSS_MAGIC) { - icnss_pr_err("Invalid drvdata for pm resume_noirq: dev %pK, data %pK, magic 0x%x\n", + icnss_pr_err("Invalid drvdata for pm resume_early: dev %pK, data %pK, magic 0x%x\n", dev, priv, priv->magic); return -EINVAL; } - icnss_pr_vdbg("PM resume_noirq, state: 0x%lx\n", priv->state); + icnss_pr_vdbg("PM resume_early, state: 0x%lx\n", priv->state); - if (!priv->ops || !priv->ops->resume_noirq || + if (!priv->ops || !priv->ops->resume_early || !test_bit(ICNSS_DRIVER_PROBED, &priv->state)) goto out; - ret = priv->ops->resume_noirq(dev); + ret = priv->ops->resume_early(dev); out: if (ret == 0) { - priv->stats.pm_resume_noirq++; - clear_bit(ICNSS_PM_SUSPEND_NOIRQ, &priv->state); + priv->stats.pm_resume_early++; + clear_bit(ICNSS_PM_SUSPEND_LATE, &priv->state); } else { - priv->stats.pm_resume_noirq_err++; + priv->stats.pm_resume_early_err++; } return ret; } @@ -4071,8 +4071,8 @@ static int icnss_pm_resume_noirq(struct device *dev) static const struct dev_pm_ops icnss_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(icnss_pm_suspend, icnss_pm_resume) - SET_NOIRQ_SYSTEM_SLEEP_PM_OPS(icnss_pm_suspend_noirq, - icnss_pm_resume_noirq) + SET_LATE_SYSTEM_SLEEP_PM_OPS(icnss_pm_suspend_late, + icnss_pm_resume_early) }; static const struct of_device_id icnss_dt_match[] = { diff --git a/drivers/soc/qcom/icnss_private.h b/drivers/soc/qcom/icnss_private.h index 2aacf3bb1f21..ae2f1320581f 100644 --- a/drivers/soc/qcom/icnss_private.h +++ b/drivers/soc/qcom/icnss_private.h @@ -151,7 +151,7 @@ enum icnss_driver_state { ICNSS_DRIVER_PROBED, ICNSS_FW_TEST_MODE, ICNSS_PM_SUSPEND, - ICNSS_PM_SUSPEND_NOIRQ, + ICNSS_PM_SUSPEND_LATE, ICNSS_SSR_REGISTERED, ICNSS_PDR_REGISTERED, ICNSS_PD_RESTART, @@ -217,10 +217,10 @@ struct icnss_stats { uint32_t pm_suspend_err; uint32_t pm_resume; uint32_t pm_resume_err; - uint32_t pm_suspend_noirq; - uint32_t pm_suspend_noirq_err; - uint32_t pm_resume_noirq; - uint32_t pm_resume_noirq_err; + uint32_t pm_suspend_late; + uint32_t pm_suspend_late_err; + uint32_t pm_resume_early; + uint32_t pm_resume_early_err; uint32_t pm_stay_awake; uint32_t pm_relax; diff --git a/include/soc/qcom/icnss.h b/include/soc/qcom/icnss.h index 54f2a51123e6..ea9936edbff6 100644 --- a/include/soc/qcom/icnss.h +++ b/include/soc/qcom/icnss.h @@ -49,6 +49,8 @@ struct icnss_driver_ops { int (*pm_resume)(struct device *dev); int (*suspend_noirq)(struct device *dev); int (*resume_noirq)(struct device *dev); + int (*suspend_late)(struct device *dev); + int (*resume_early)(struct device *dev); int (*uevent)(struct device *dev, struct icnss_uevent_data *uevent); int (*idle_shutdown)(struct device *dev); int (*idle_restart)(struct device *dev); From ca0a7ceafe7c625d503e48f8d009a39f7271dfc5 Mon Sep 17 00:00:00 2001 From: msdx321 Date: Mon, 25 Mar 2019 17:40:22 -0400 Subject: [PATCH 21/29] clk: qcom: clk-cpu-osm: Set min freq to 576MHz Signed-off-by: msdx321 --- drivers/clk/qcom/clk-cpu-osm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/clk/qcom/clk-cpu-osm.c b/drivers/clk/qcom/clk-cpu-osm.c index 10f97caa77e6..ef3b54069f3b 100644 --- a/drivers/clk/qcom/clk-cpu-osm.c +++ b/drivers/clk/qcom/clk-cpu-osm.c @@ -725,7 +725,7 @@ static int osm_cpufreq_cpu_init(struct cpufreq_policy *policy) if (!osm_dt_find_freq(of_table, of_len, table[i].frequency)) table[i].frequency = CPUFREQ_ENTRY_INVALID; - if (core_count == SINGLE_CORE_COUNT) + if (core_count == SINGLE_CORE_COUNT || table[i].frequency < 576000) table[i].frequency = CPUFREQ_ENTRY_INVALID; /* Two of the same frequencies means end of table */ From 965da4b74918143722f5d541a261ff881770e85c Mon Sep 17 00:00:00 2001 From: Andrzej Perczak Date: Wed, 24 Aug 2022 19:28:11 +0200 Subject: [PATCH 22/29] fs: f2fs: Remove android tracing and align with upstream For easier upstream merges. Signed-off-by: Andrzej Perczak --- fs/f2fs/data.c | 57 +++++------------------------------------------- fs/f2fs/file.c | 11 ---------- fs/f2fs/inline.c | 17 --------------- fs/f2fs/inode.c | 1 + fs/f2fs/node.c | 9 ++++++++ 5 files changed, 15 insertions(+), 80 deletions(-) diff --git a/fs/f2fs/data.c b/fs/f2fs/data.c index 0921320303eb..a2c83cff78f3 100644 --- a/fs/f2fs/data.c +++ b/fs/f2fs/data.c @@ -25,7 +25,6 @@ #include "segment.h" #include "iostat.h" #include -#include #define NUM_PREALLOC_POST_READ_CTXS 128 @@ -508,32 +507,6 @@ static inline void __submit_bio(struct f2fs_sb_info *sbi, submit_bio(bio); } -static void __f2fs_submit_read_bio(struct f2fs_sb_info *sbi, - struct bio *bio, enum page_type type) -{ - if (trace_android_fs_dataread_start_enabled() && (type == DATA)) { - struct page *first_page = bio->bi_io_vec[0].bv_page; - - if (first_page != NULL && - __read_io_type(first_page) == F2FS_RD_DATA) { - char *path, pathbuf[MAX_TRACE_PATHBUF_LEN]; - - path = android_fstrace_get_pathname(pathbuf, - MAX_TRACE_PATHBUF_LEN, - first_page->mapping->host); - - trace_android_fs_dataread_start( - first_page->mapping->host, - page_offset(first_page), - bio->bi_iter.bi_size, - current->pid, - path, - current->comm); - } - } - __submit_bio(sbi, bio, type); -} - void f2fs_submit_bio(struct f2fs_sb_info *sbi, struct bio *bio, enum page_type type) { @@ -725,10 +698,7 @@ int f2fs_submit_page_bio(struct f2fs_io_info *fio) inc_page_count(fio->sbi, is_read_io(fio->op) ? __read_io_type(page): WB_DATA_TYPE(fio->page)); - if (is_read_io(fio->op)) - __f2fs_submit_read_bio(fio->sbi, bio, fio->type); - else - __submit_bio(fio->sbi, bio, fio->type); + __submit_bio(fio->sbi, bio, fio->type); return 0; } @@ -1083,7 +1053,7 @@ static int f2fs_submit_page_read(struct inode *inode, struct page *page, ClearPageError(page); inc_page_count(sbi, F2FS_RD_DATA); f2fs_update_iostat(sbi, FS_DATA_READ_IO, F2FS_BLKSIZE); - __f2fs_submit_read_bio(sbi, bio, DATA); + __submit_bio(sbi, bio, DATA); return 0; } @@ -2155,7 +2125,7 @@ static int f2fs_read_single_page(struct inode *inode, struct page *page, *last_block_in_bio, block_nr) || !f2fs_crypt_mergeable_bio(bio, inode, page->index, NULL))) { submit_and_realloc: - __f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA); + __submit_bio(F2FS_I_SB(inode), bio, DATA); bio = NULL; } @@ -2185,7 +2155,7 @@ static int f2fs_read_single_page(struct inode *inode, struct page *page, goto out; confused: if (bio) { - __f2fs_submit_read_bio(F2FS_I_SB(inode), bio, DATA); + __submit_bio(F2FS_I_SB(inode), bio, DATA); bio = NULL; } unlock_page(page); @@ -3461,16 +3431,6 @@ static int f2fs_write_begin(struct file *file, struct address_space *mapping, block_t blkaddr = NULL_ADDR; int err = 0; - if (trace_android_fs_datawrite_start_enabled()) { - char *path, pathbuf[MAX_TRACE_PATHBUF_LEN]; - - path = android_fstrace_get_pathname(pathbuf, - MAX_TRACE_PATHBUF_LEN, - inode); - trace_android_fs_datawrite_start(inode, pos, len, - current->pid, path, - current->comm); - } trace_f2fs_write_begin(inode, pos, len, flags); if (!f2fs_is_checkpoint_ready(sbi)) { @@ -3601,7 +3561,6 @@ static int f2fs_write_end(struct file *file, { struct inode *inode = page->mapping->host; - trace_android_fs_datawrite_end(inode, pos, len); trace_f2fs_write_end(inode, pos, len, copied); /* @@ -3810,14 +3769,8 @@ static ssize_t f2fs_direct_IO(struct kiocb *iocb, struct iov_iter *iter) f2fs_update_iostat(F2FS_I_SB(inode), APP_DIRECT_READ_IO, count - iov_iter_count(iter)); } -out: - if (trace_android_fs_dataread_start_enabled() && - (rw == READ)) - trace_android_fs_dataread_end(inode, offset, count); - if (trace_android_fs_datawrite_start_enabled() && - (rw == WRITE)) - trace_android_fs_datawrite_end(inode, offset, count); +out: trace_f2fs_direct_IO_exit(inode, offset, count, rw, err); return err; diff --git a/fs/f2fs/file.c b/fs/f2fs/file.c index d6b01e03b275..378188c49607 100644 --- a/fs/f2fs/file.c +++ b/fs/f2fs/file.c @@ -30,7 +30,6 @@ #include "gc.h" #include "iostat.h" #include -#include #include static int f2fs_filemap_fault(struct vm_fault *vmf) @@ -266,15 +265,6 @@ static int f2fs_do_sync_file(struct file *file, loff_t start, loff_t end, trace_f2fs_sync_file_enter(inode); - if (trace_android_fs_fsync_start_enabled()) { - char *path, pathbuf[MAX_TRACE_PATHBUF_LEN]; - - path = android_fstrace_get_pathname(pathbuf, - MAX_TRACE_PATHBUF_LEN, inode); - trace_android_fs_fsync_start(inode, - current->pid, path, current->comm); - } - if (S_ISDIR(inode->i_mode)) goto go_write; @@ -391,7 +381,6 @@ static int f2fs_do_sync_file(struct file *file, loff_t start, loff_t end, f2fs_update_time(sbi, REQ_TIME); out: trace_f2fs_sync_file_exit(inode, cp_reason, datasync, ret); - trace_android_fs_fsync_end(inode, start, end - start); return ret; } diff --git a/fs/f2fs/inline.c b/fs/f2fs/inline.c index 1721f74bc587..8745629fa39a 100644 --- a/fs/f2fs/inline.c +++ b/fs/f2fs/inline.c @@ -86,29 +86,14 @@ int f2fs_read_inline_data(struct inode *inode, struct page *page) { struct page *ipage; - if (trace_android_fs_dataread_start_enabled()) { - char *path, pathbuf[MAX_TRACE_PATHBUF_LEN]; - - path = android_fstrace_get_pathname(pathbuf, - MAX_TRACE_PATHBUF_LEN, - inode); - trace_android_fs_dataread_start(inode, page_offset(page), - PAGE_SIZE, current->pid, - path, current->comm); - } - ipage = f2fs_get_node_page(F2FS_I_SB(inode), inode->i_ino); if (IS_ERR(ipage)) { - trace_android_fs_dataread_end(inode, page_offset(page), - PAGE_SIZE); unlock_page(page); return PTR_ERR(ipage); } if (!f2fs_has_inline_data(inode)) { f2fs_put_page(ipage, 1); - trace_android_fs_dataread_end(inode, page_offset(page), - PAGE_SIZE); return -EAGAIN; } @@ -120,8 +105,6 @@ int f2fs_read_inline_data(struct inode *inode, struct page *page) if (!PageUptodate(page)) SetPageUptodate(page); f2fs_put_page(ipage, 1); - trace_android_fs_dataread_end(inode, page_offset(page), - PAGE_SIZE); unlock_page(page); return 0; } diff --git a/fs/f2fs/inode.c b/fs/f2fs/inode.c index d61e44a02328..20e621ad4f51 100644 --- a/fs/f2fs/inode.c +++ b/fs/f2fs/inode.c @@ -910,6 +910,7 @@ void f2fs_handle_failed_inode(struct inode *inode) } else { set_inode_flag(inode, FI_FREE_NID); } + out: f2fs_unlock_op(sbi); diff --git a/fs/f2fs/node.c b/fs/f2fs/node.c index c98620d0a54e..aa86e2020723 100644 --- a/fs/f2fs/node.c +++ b/fs/f2fs/node.c @@ -916,6 +916,7 @@ static int truncate_node(struct dnode_of_data *dn) dn->node_page = NULL; trace_f2fs_truncate_node(dn->inode, dn->nid, ni.blk_addr); + return 0; } @@ -941,6 +942,7 @@ static int truncate_dnode(struct dnode_of_data *dn) err = truncate_node(dn); if (err) return err; + return 1; } @@ -2378,6 +2380,7 @@ static int scan_nat_page(struct f2fs_sb_info *sbi, f2fs_bug_on(sbi, blk_addr == NEW_ADDR); if (blk_addr == NEW_ADDR) return -EINVAL; + if (blk_addr == NULL_ADDR) { add_free_nid(sbi, start_nid, true, true); } else { @@ -2386,6 +2389,7 @@ static int scan_nat_page(struct f2fs_sb_info *sbi, spin_unlock(&NM_I(sbi)->nid_list_lock); } } + return 0; } @@ -2513,15 +2517,18 @@ static int __f2fs_build_free_nids(struct f2fs_sb_info *sbi, f2fs_ra_meta_pages(sbi, NAT_BLOCK_OFFSET(nm_i->next_scan_nid), nm_i->ra_nid_pages, META_NAT, false); + return 0; } int f2fs_build_free_nids(struct f2fs_sb_info *sbi, bool sync, bool mount) { int ret; + mutex_lock(&NM_I(sbi)->build_lock); ret = __f2fs_build_free_nids(sbi, sync, mount); mutex_unlock(&NM_I(sbi)->build_lock); + return ret; } @@ -2707,6 +2714,7 @@ int f2fs_recover_xattr_data(struct inode *inode, struct page *page) err = f2fs_get_node_info(sbi, prev_xnid, &ni, false); if (err) return err; + f2fs_invalidate_blocks(sbi, ni.blk_addr); dec_valid_node_count(sbi, inode, false); set_node_addr(sbi, &ni, NULL_ADDR, false); @@ -2999,6 +3007,7 @@ static int __flush_nat_entry_set(struct f2fs_sb_info *sbi, page = get_next_nat_page(sbi, start_nid); if (IS_ERR(page)) return PTR_ERR(page); + nat_blk = page_address(page); f2fs_bug_on(sbi, !nat_blk); } From d5dd4704c2cc6fd74ae1b3b50d8b79ee4a7b3bd8 Mon Sep 17 00:00:00 2001 From: Andrzej Perczak Date: Sun, 3 Jul 2022 20:14:35 +0200 Subject: [PATCH 23/29] f2fs: pagevec_init fixup after removed argument Signed-off-by: Andrzej Perczak --- fs/f2fs/compress.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fs/f2fs/compress.c b/fs/f2fs/compress.c index 10a2a4789bd9..5b4ccd910029 100644 --- a/fs/f2fs/compress.c +++ b/fs/f2fs/compress.c @@ -1817,6 +1817,8 @@ void f2fs_invalidate_compress_pages(struct f2fs_sb_info *sbi, nid_t ino) if (!mapping->nrpages) return; + pagevec_init(&pvec); + do { unsigned int nr_pages; int i; From 009fdd350c006d5a2779393d94e0093619b1f02a Mon Sep 17 00:00:00 2001 From: Anh Tran Date: Mon, 6 Mar 2023 20:53:07 +0700 Subject: [PATCH 24/29] Revert "cpufreq: Kill userspace CPU boosting entirely" This reverts commit 6994c5044dcadcf33568b37b91b3d81becc0c179. --- drivers/cpufreq/cpufreq.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/drivers/cpufreq/cpufreq.c b/drivers/cpufreq/cpufreq.c index c99ba2f61984..ea51a776c6ca 100644 --- a/drivers/cpufreq/cpufreq.c +++ b/drivers/cpufreq/cpufreq.c @@ -726,9 +726,6 @@ static ssize_t store_##file_name \ int ret, temp; \ struct cpufreq_policy new_policy; \ \ - if (&policy->object == &policy->min) \ - return count; \ - \ memcpy(&new_policy, policy, sizeof(*policy)); \ new_policy.min = policy->user_policy.min; \ new_policy.max = policy->user_policy.max; \ From 3d00596f440a81e87c5272152b0271098d8ff953 Mon Sep 17 00:00:00 2001 From: Chris Ye Date: Sun, 21 Jul 2019 22:51:42 -0700 Subject: [PATCH 25/29] msm-camera: Enable initial skip for dual camera synchronization For portrait mode with dual camera synchronization, enable initial skip to make sure two sensors both start streaming with synchronization signal. This fixed the portrait mode switching stability issue. Bug: 136756925 Change-Id: I2e6e8c463bffd04da441f3da3033e6596f30e72a Signed-off-by: Chris Ye Signed-off-by: Yaroslav Furman Signed-off-by: Cyber Knight --- .../platform/msm/camera/cam_req_mgr/cam_req_mgr_core.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/drivers/media/platform/msm/camera/cam_req_mgr/cam_req_mgr_core.c b/drivers/media/platform/msm/camera/cam_req_mgr/cam_req_mgr_core.c index 6ef30dc38e65..3e8a98611db8 100644 --- a/drivers/media/platform/msm/camera/cam_req_mgr/cam_req_mgr_core.c +++ b/drivers/media/platform/msm/camera/cam_req_mgr/cam_req_mgr_core.c @@ -829,8 +829,13 @@ static int __cam_req_mgr_check_sync_for_mslave( } } } else { - if (link->initial_skip) + if (link->initial_skip) { + CAM_DBG(CAM_CRM, + "Initial skip Req: %lld on link: %x", + req_id, link->link_hdl); link->initial_skip = false; + return -EAGAIN; + } rc = __cam_req_mgr_inject_delay(link->req.l_tbl, slot->idx); if (rc) { From 380754518a950e3f81b00bded04016933fa63d4d Mon Sep 17 00:00:00 2001 From: Zlatan Radovanovic Date: Sun, 4 Jul 2021 06:05:38 +0200 Subject: [PATCH 26/29] Revert "msm: camera: icp: Enable hang dump on failure" This reverts commit 06f863cfe21d36c70ae2270e1cf151c0055d71f7. Signed-off-by: Cyber Knight --- .../msm/camera/cam_icp/icp_hw/icp_hw_mgr/cam_icp_hw_mgr.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/drivers/media/platform/msm/camera/cam_icp/icp_hw/icp_hw_mgr/cam_icp_hw_mgr.c b/drivers/media/platform/msm/camera/cam_icp/icp_hw/icp_hw_mgr/cam_icp_hw_mgr.c index 8bbf066bbc5d..ad8d91bbe3ee 100644 --- a/drivers/media/platform/msm/camera/cam_icp/icp_hw/icp_hw_mgr/cam_icp_hw_mgr.c +++ b/drivers/media/platform/msm/camera/cam_icp/icp_hw/icp_hw_mgr/cam_icp_hw_mgr.c @@ -1,4 +1,4 @@ -/* Copyright (c) 2017-2021, The Linux Foundation. All rights reserved. +/* Copyright (c) 2017-2020, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and @@ -1461,8 +1461,6 @@ static int cam_icp_hw_mgr_create_debugfs_entry(void) goto err; } - /* Set default hang dump lvl */ - icp_hw_mgr.a5_fw_dump_lvl = HFI_FW_DUMP_ON_FAILURE; return rc; err: debugfs_remove_recursive(icp_hw_mgr.dentry); From e58044b63f28ecb6910614d6fb48071147bf260d Mon Sep 17 00:00:00 2001 From: chenqiwu Date: Mon, 30 Dec 2019 10:07:34 +0800 Subject: [PATCH 27/29] ANDROID: drivers base/arch_topology: avoid a stuck risk when cpufreq policy free detect_share_cap_flag() calls cpufreq_cpu_get() to get cpufreq policy for each possible cpu, meanwhile, it also increments the kobject reference count of policy to mark it busy. However, a corresponding call to cpufreq_cpu_put() is ignored to decrement the kobject reference count back, which may lead to a potential stuck risk that percpu cpuhp thread deadly waits for dropping of kobject refcount when percpu cpufreq policy free. The call trace of stuck risk could be: cpufreq_online() //If cpufreq initialization failed, goto out_free_policy. ->cpufreq_policy_free() //Do cpufreq_policy free. ->cpufreq_policy_put_kobj() ->kobject_put() //Skip if policy kfref count is not 1. ->cpufreq_sysfs_release() ->complete() //Complete policy->kobj_unregister. ->wait_for_completion() //Wait for policy->kobj_unregister. With this patch, the cpuhp thread can be easily exercised by attempting to force an unbind of the CPUfreq driver. Bug: 120440300 Bug: 147378688 Signed-off-by: chenqiwu Signed-off-by: qiwu chen Signed-off-by: Quentin Perret Change-Id: I976fc697d4090324877b28fdb5bb5a5b63f6d947 Signed-off-by: Pranav Vashi --- drivers/base/arch_topology.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/drivers/base/arch_topology.c b/drivers/base/arch_topology.c index dfc67d8ab7eb..ec0784b2d93b 100644 --- a/drivers/base/arch_topology.c +++ b/drivers/base/arch_topology.c @@ -184,20 +184,25 @@ int detect_share_cap_flag(void) if (cpumask_equal(cpu_cpu_mask(cpu), policy->related_cpus)) { share_cap_level = share_cap_die; + cpufreq_cpu_put(policy); continue; } if (cpumask_equal(topology_core_cpumask(cpu), policy->related_cpus)) { share_cap_level = share_cap_core; + cpufreq_cpu_put(policy); continue; } if (cpumask_equal(topology_sibling_cpumask(cpu), policy->related_cpus)) { share_cap_level = share_cap_thread; + cpufreq_cpu_put(policy); continue; } + + cpufreq_cpu_put(policy); } if (share_cap != share_cap_level) { From 849786927e50ab2f24cdf034b7c910745e27645a Mon Sep 17 00:00:00 2001 From: Nauval Rizky Date: Mon, 6 Jun 2022 00:54:22 +0700 Subject: [PATCH 28/29] arch_topology: Report SCHED_CAPACITY_SCALE to the problematic userspace lybxlpsv said that some unity games also looking for the cpu_capacity to determine about their decision on affinity setup. So let's mitigate it too with is_sched_lib_based_app() just like on the previous attempt. Fixes: d43b69c4ad2a977406c84d47fe8a5261e0099e78 ("sched/core: fix userspace affining threads incorrectly") Signed-off-by: Nauval Rizky Signed-off-by: Pranav Vashi --- drivers/base/arch_topology.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/base/arch_topology.c b/drivers/base/arch_topology.c index ec0784b2d93b..93ad6be01e85 100644 --- a/drivers/base/arch_topology.c +++ b/drivers/base/arch_topology.c @@ -22,6 +22,7 @@ #include #include #include +#include #include DEFINE_PER_CPU(unsigned long, freq_scale) = SCHED_CAPACITY_SCALE; @@ -76,6 +77,9 @@ static ssize_t cpu_capacity_show(struct device *dev, { struct cpu *cpu = container_of(dev, struct cpu, dev); + if (is_sched_lib_based_app(current->pid)) + return scnprintf(buf, PAGE_SIZE, "%lu\n", SCHED_CAPACITY_SCALE); + return sprintf(buf, "%lu\n", topology_get_cpu_scale(NULL, cpu->dev.id)); } From ecc0a24f738dc2a2ccb9d9f59ec1546f1e4a78ca Mon Sep 17 00:00:00 2001 From: Arun Prakash Date: Fri, 23 Aug 2019 17:02:06 +0530 Subject: [PATCH 29/29] soc: qcom: smp2p: keeping inbound entry on freeze Avoiding inbound entry release during freeze callback to keep the irq domain as it is.Resetting inbound last value. Change-Id: Ic5374fa8094d0f4de914076cef348469158b4012 Signed-off-by: Arun Prakash Signed-off-by: Panchajanya1999 Signed-off-by: Pranav Vashi --- drivers/soc/qcom/smp2p.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/drivers/soc/qcom/smp2p.c b/drivers/soc/qcom/smp2p.c index 4d440a31665a..ec0fbc38d05c 100644 --- a/drivers/soc/qcom/smp2p.c +++ b/drivers/soc/qcom/smp2p.c @@ -753,7 +753,6 @@ static int qcom_smp2p_restore(struct device *dev) } } - enable_irq_wake(smp2p->irq); /* Kick the outgoing edge after allocating entries */ qcom_smp2p_kick(smp2p); return ret; @@ -774,7 +773,6 @@ static int qcom_smp2p_freeze(struct device *dev) struct smp2p_entry *entry; struct smp2p_entry *next_entry; - disable_irq_wake(smp2p->irq); /* Walk through the out bound list and release state and entry */ list_for_each_entry_safe(entry, next_entry, &smp2p->outbound, node) { qcom_smem_state_unregister(entry->state);