1 // SPDX-License-Identifier: GPL 2.0+ OR BSD-3-Clause
3 * Copyright 2015 Google Inc.
9 #include <linux/kernel.h>
10 #include <linux/types.h>
11 #include <asm/unaligned.h>
12 #include <u-boot/lz4.h>
14 static u16 LZ4_readLE16(const void *src)
16 return get_unaligned_le16(src);
18 static void LZ4_copy4(void *dst, const void *src)
20 put_unaligned(get_unaligned((const u32 *)src), (u32 *)dst);
22 static void LZ4_copy8(void *dst, const void *src)
24 put_unaligned(get_unaligned((const u64 *)src), (u64 *)dst);
33 #define FORCE_INLINE static inline __attribute__((always_inline))
35 /* lz4.c is unaltered (except removing unrelated code) from github.com/Cyan4973/lz4. */
36 #include "lz4.c" /* #include for inlining, do not link! */
38 #define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
40 int ulz4fn(const void *src, size_t srcn, void *dst, size_t *dstn)
42 const void *end = dst + *dstn;
45 int has_block_checksum;
49 { /* With in-place decompression the header may become invalid later. */
51 u8 flags, version, independent_blocks, has_content_size;
54 if (srcn < sizeof(u32) + 3*sizeof(u8))
55 return -EINVAL; /* input overrun */
57 magic = get_unaligned_le32(in);
61 block_desc = *(u8 *)in;
64 version = (flags >> 6) & 0x3;
65 independent_blocks = (flags >> 5) & 0x1;
66 has_block_checksum = (flags >> 4) & 0x1;
67 has_content_size = (flags >> 3) & 0x1;
69 /* We assume there's always only a single, standard frame. */
70 if (magic != LZ4F_MAGIC || version != 1)
71 return -EPROTONOSUPPORT; /* unknown format */
72 if ((flags & 0x03) || (block_desc & 0x8f))
73 return -EINVAL; /* reserved bits must be zero */
74 if (!independent_blocks)
75 return -EPROTONOSUPPORT; /* we can't support this yet */
77 if (has_content_size) {
78 if (srcn < sizeof(u32) + 3*sizeof(u8) + sizeof(u64))
79 return -EINVAL; /* input overrun */
82 /* Header checksum byte */
87 u32 block_header, block_size;
89 block_header = get_unaligned_le32(in);
91 block_size = block_header & ~LZ4F_BLOCKUNCOMPRESSED_FLAG;
93 if (in - src + block_size > srcn) {
94 ret = -EINVAL; /* input overrun */
99 ret = 0; /* decompression successful */
103 if (block_header & LZ4F_BLOCKUNCOMPRESSED_FLAG) {
104 size_t size = min((ptrdiff_t)block_size, end - out);
105 memcpy(out, in, size);
107 if (size < block_size) {
108 ret = -ENOBUFS; /* output overrun */
112 /* constant folding essential, do not touch params! */
113 ret = LZ4_decompress_generic(in, out, block_size,
114 end - out, endOnInputSize,
115 full, 0, noDict, out, NULL, 0);
117 ret = -EPROTO; /* decompression error */
124 if (has_block_checksum)