1 // SPDX-License-Identifier: GPL-2.0-only
3 * Wrapper for decompressing LZ4-compressed kernel, initramfs, and initrd
5 * Copyright (C) 2013, LG Electronics, Kyungsik Lee <kyungsik.lee@lge.com>
10 #include "lz4/lz4_decompress.c"
12 #include <linux/decompress/unlz4.h>
14 #include <linux/types.h>
15 #include <linux/lz4.h>
16 #include <linux/decompress/mm.h>
17 #include <linux/compiler.h>
19 #include <linux/unaligned.h>
22 * Note: Uncompressed chunk size is used in the compressor side
23 * (userspace side for compression).
24 * It is hardcoded because there is not proper way to extract it
25 * from the binary stream which is generated by the preliminary
26 * version of LZ4 tool so far.
28 #define LZ4_DEFAULT_UNCOMPRESSED_CHUNK_SIZE (8 << 20)
29 #define ARCHIVE_MAGICNUMBER 0x184C2102
31 STATIC inline int INIT unlz4(u8 *input, long in_len,
32 long (*fill)(void *, unsigned long),
33 long (*flush)(void *, unsigned long),
34 u8 *output, long *posp,
35 void (*error) (char *x))
39 size_t uncomp_chunksize = LZ4_DEFAULT_UNCOMPRESSED_CHUNK_SIZE;
45 size_t out_len = get_unaligned_le32(input + in_len);
53 error("NULL output pointer and no flush function provided");
56 outp = large_malloc(uncomp_chunksize);
58 error("Could not allocate output buffer");
64 error("Both input pointer and fill function provided,");
69 error("NULL input pointer and missing fill function");
72 inp = large_malloc(LZ4_compressBound(uncomp_chunksize));
74 error("Could not allocate input buffer");
86 error("data corrupted");
91 chunksize = get_unaligned_le32(inp);
92 if (chunksize == ARCHIVE_MAGICNUMBER) {
98 error("invalid header");
112 error("data corrupted");
115 } else if (size < 4) {
116 /* empty or end-of-file */
120 chunksize = get_unaligned_le32(inp);
121 if (chunksize == ARCHIVE_MAGICNUMBER) {
131 if (!fill && chunksize == 0) {
132 /* empty or end-of-file */
143 if (chunksize > LZ4_compressBound(uncomp_chunksize)) {
144 error("chunk length is longer than allocated");
147 size = fill(inp, chunksize);
148 if (size < chunksize) {
149 error("data corrupted");
154 if (out_len >= uncomp_chunksize) {
155 dest_len = uncomp_chunksize;
160 ret = LZ4_decompress_fast(inp, outp, dest_len);
163 dest_len = uncomp_chunksize;
165 ret = LZ4_decompress_safe(inp, outp, chunksize, dest_len);
169 error("Decoding failed");
174 if (flush && flush(outp, dest_len) != dest_len)
187 error("data corrupted");
198 large_free(inp_start);
207 STATIC int INIT __decompress(unsigned char *buf, long in_len,
208 long (*fill)(void*, unsigned long),
209 long (*flush)(void*, unsigned long),
210 unsigned char *output, long out_len,
212 void (*error)(char *x)
215 return unlz4(buf, in_len - 4, fill, flush, output, posp, error);