1 // SPDX-License-Identifier: GPL 2.0+ OR BSD-3-Clause
3 * Copyright 2015 Google Inc.
10 #include <linux/kernel.h>
11 #include <linux/types.h>
12 #include <asm/unaligned.h>
14 static u16 LZ4_readLE16(const void *src) { return le16_to_cpu(*(u16 *)src); }
15 static void LZ4_copy4(void *dst, const void *src) { *(u32 *)dst = *(u32 *)src; }
16 static void LZ4_copy8(void *dst, const void *src) { *(u64 *)dst = *(u64 *)src; }
24 #define FORCE_INLINE static inline __attribute__((always_inline))
26 /* lz4.c is unaltered (except removing unrelated code) from github.com/Cyan4973/lz4. */
27 #include "lz4.c" /* #include for inlining, do not link! */
29 #define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
31 int ulz4fn(const void *src, size_t srcn, void *dst, size_t *dstn)
33 const void *end = dst + *dstn;
36 int has_block_checksum;
40 { /* With in-place decompression the header may become invalid later. */
42 u8 flags, version, independent_blocks, has_content_size;
45 if (srcn < sizeof(u32) + 3*sizeof(u8))
46 return -EINVAL; /* input overrun */
48 magic = get_unaligned_le32(in);
52 block_desc = *(u8 *)in;
55 version = (flags >> 6) & 0x3;
56 independent_blocks = (flags >> 5) & 0x1;
57 has_block_checksum = (flags >> 4) & 0x1;
58 has_content_size = (flags >> 3) & 0x1;
60 /* We assume there's always only a single, standard frame. */
61 if (magic != LZ4F_MAGIC || version != 1)
62 return -EPROTONOSUPPORT; /* unknown format */
63 if ((flags & 0x03) || (block_desc & 0x8f))
64 return -EINVAL; /* reserved bits must be zero */
65 if (!independent_blocks)
66 return -EPROTONOSUPPORT; /* we can't support this yet */
68 if (has_content_size) {
69 if (srcn < sizeof(u32) + 3*sizeof(u8) + sizeof(u64))
70 return -EINVAL; /* input overrun */
73 /* Header checksum byte */
78 u32 block_header, block_size;
80 block_header = get_unaligned_le32(in);
82 block_size = block_header & ~LZ4F_BLOCKUNCOMPRESSED_FLAG;
84 if (in - src + block_size > srcn) {
85 ret = -EINVAL; /* input overrun */
90 ret = 0; /* decompression successful */
94 if (block_header & LZ4F_BLOCKUNCOMPRESSED_FLAG) {
95 size_t size = min((ptrdiff_t)block_size, end - out);
96 memcpy(out, in, size);
98 if (size < block_size) {
99 ret = -ENOBUFS; /* output overrun */
103 /* constant folding essential, do not touch params! */
104 ret = LZ4_decompress_generic(in, out, block_size,
105 end - out, endOnInputSize,
106 full, 0, noDict, out, NULL, 0);
108 ret = -EPROTO; /* decompression error */
115 if (has_block_checksum)