1 // SPDX-License-Identifier: GPL 2.0+ OR BSD-3-Clause
3 * Copyright 2015 Google Inc.
8 #include <linux/kernel.h>
9 #include <linux/types.h>
11 static u16 LZ4_readLE16(const void *src) { return le16_to_cpu(*(u16 *)src); }
12 static void LZ4_copy4(void *dst, const void *src) { *(u32 *)dst = *(u32 *)src; }
13 static void LZ4_copy8(void *dst, const void *src) { *(u64 *)dst = *(u64 *)src; }
21 #define FORCE_INLINE static inline __attribute__((always_inline))
23 /* Unaltered (except removing unrelated code) from github.com/Cyan4973/lz4. */
24 #include "lz4.c" /* #include for inlining, do not link! */
26 #define LZ4F_MAGIC 0x184D2204
28 struct lz4_frame_header {
34 u8 has_content_checksum:1;
35 u8 has_content_size:1;
36 u8 has_block_checksum:1;
37 u8 independent_blocks:1;
49 /* + u64 content_size iff has_content_size is set */
50 /* + u8 header_checksum */
53 struct lz4_block_header {
61 /* + size bytes of data */
62 /* + u32 block_checksum iff has_block_checksum is set */
65 int ulz4fn(const void *src, size_t srcn, void *dst, size_t *dstn)
67 const void *end = dst + *dstn;
70 int has_block_checksum;
74 { /* With in-place decompression the header may become invalid later. */
75 const struct lz4_frame_header *h = in;
77 if (srcn < sizeof(*h) + sizeof(u64) + sizeof(u8))
78 return -EINVAL; /* input overrun */
80 /* We assume there's always only a single, standard frame. */
81 if (le32_to_cpu(h->magic) != LZ4F_MAGIC || h->version != 1)
82 return -EPROTONOSUPPORT; /* unknown format */
83 if (h->reserved0 || h->reserved1 || h->reserved2)
84 return -EINVAL; /* reserved must be zero */
85 if (!h->independent_blocks)
86 return -EPROTONOSUPPORT; /* we can't support this yet */
87 has_block_checksum = h->has_block_checksum;
90 if (h->has_content_size)
96 struct lz4_block_header b;
98 b.raw = le32_to_cpu(*(u32 *)in);
99 in += sizeof(struct lz4_block_header);
101 if (in - src + b.size > srcn) {
102 ret = -EINVAL; /* input overrun */
107 ret = 0; /* decompression successful */
111 if (b.not_compressed) {
112 size_t size = min((ptrdiff_t)b.size, end - out);
113 memcpy(out, in, size);
116 ret = -ENOBUFS; /* output overrun */
120 /* constant folding essential, do not touch params! */
121 ret = LZ4_decompress_generic(in, out, b.size,
122 end - out, endOnInputSize,
123 full, 0, noDict, out, NULL, 0);
125 ret = -EPROTO; /* decompression error */
132 if (has_block_checksum)