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 /* lz4.c is unaltered (except removing unrelated code) from github.com/Cyan4973/lz4. */
15 #include "lz4.c" /* #include for inlining, do not link! */
17 #define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
19 int ulz4fn(const void *src, size_t srcn, void *dst, size_t *dstn)
21 const void *end = dst + *dstn;
24 int has_block_checksum;
28 { /* With in-place decompression the header may become invalid later. */
30 u8 flags, version, independent_blocks, has_content_size;
33 if (srcn < sizeof(u32) + 3*sizeof(u8))
34 return -EINVAL; /* input overrun */
36 magic = get_unaligned_le32(in);
40 block_desc = *(u8 *)in;
43 version = (flags >> 6) & 0x3;
44 independent_blocks = (flags >> 5) & 0x1;
45 has_block_checksum = (flags >> 4) & 0x1;
46 has_content_size = (flags >> 3) & 0x1;
48 /* We assume there's always only a single, standard frame. */
49 if (magic != LZ4F_MAGIC || version != 1)
50 return -EPROTONOSUPPORT; /* unknown format */
51 if ((flags & 0x03) || (block_desc & 0x8f))
52 return -EINVAL; /* reserved bits must be zero */
53 if (!independent_blocks)
54 return -EPROTONOSUPPORT; /* we can't support this yet */
56 if (has_content_size) {
57 if (srcn < sizeof(u32) + 3*sizeof(u8) + sizeof(u64))
58 return -EINVAL; /* input overrun */
61 /* Header checksum byte */
66 u32 block_header, block_size;
68 block_header = get_unaligned_le32(in);
70 block_size = block_header & ~LZ4F_BLOCKUNCOMPRESSED_FLAG;
72 if (in - src + block_size > srcn) {
73 ret = -EINVAL; /* input overrun */
78 ret = 0; /* decompression successful */
82 if (block_header & LZ4F_BLOCKUNCOMPRESSED_FLAG) {
83 size_t size = min((ptrdiff_t)block_size, end - out);
84 memcpy(out, in, size);
86 if (size < block_size) {
87 ret = -ENOBUFS; /* output overrun */
91 /* constant folding essential, do not touch params! */
92 ret = LZ4_decompress_generic(in, out, block_size,
93 end - out, endOnInputSize,
94 decode_full_block, noDict, out, NULL, 0);
96 ret = -EPROTO; /* decompression error */
103 if (has_block_checksum)