2 * BTRFS filesystem implementation for U-Boot
4 * 2017 Marek Behun, CZ.NIC, marek.behun@nic.cz
6 * SPDX-License-Identifier: GPL-2.0+
10 #include <linux/lzo.h>
11 #include <u-boot/zlib.h>
12 #include <asm/unaligned.h>
14 static u32 decompress_lzo(const u8 *cbuf, u32 clen, u8 *dbuf, u32 dlen)
16 u32 tot_len, in_len, res;
23 tot_len = le32_to_cpu(get_unaligned((u32 *)cbuf));
28 if (tot_len == 0 && dlen)
36 in_len = le32_to_cpu(get_unaligned((u32 *)cbuf));
40 if (in_len > clen || tot_len < 4 + in_len)
43 tot_len -= 4 + in_len;
46 ret = lzo1x_decompress_safe(cbuf, in_len, dbuf, &out_len);
62 #define PRESET_DICT 0x20
64 static u32 decompress_zlib(const u8 *_cbuf, u32 clen, u8 *dbuf, u32 dlen)
66 int wbits = MAX_WBITS, ret = -1;
71 memset(&stream, 0, sizeof(stream));
77 stream.next_out = dbuf;
78 stream.avail_out = dlen;
81 /* skip adler32 check if deflate and no dictionary */
82 if (clen > 2 && !(cbuf[1] & PRESET_DICT) &&
83 ((cbuf[0] & 0x0f) == Z_DEFLATED) &&
84 !(((cbuf[0] << 8) + cbuf[1]) % 31)) {
85 wbits = -((cbuf[0] >> 4) + 8);
90 if (Z_OK != inflateInit2(&stream, wbits))
93 while (stream.total_in < clen) {
94 stream.next_in = cbuf + stream.total_in;
95 stream.avail_in = min((u32) (clen - stream.total_in),
96 (u32) btrfs_info.sb.sectorsize);
98 ret = inflate(&stream, Z_NO_FLUSH);
103 res = stream.total_out;
106 if (ret != Z_STREAM_END)
112 u32 btrfs_decompress(u8 type, const char *c, u32 clen, char *d, u32 dlen)
118 cbuf = (const u8 *) c;
122 case BTRFS_COMPRESS_NONE:
123 res = dlen < clen ? dlen : clen;
124 memcpy(dbuf, cbuf, res);
126 case BTRFS_COMPRESS_ZLIB:
127 return decompress_zlib(cbuf, clen, dbuf, dlen);
128 case BTRFS_COMPRESS_LZO:
129 return decompress_lzo(cbuf, clen, dbuf, dlen);
131 printf("%s: Unsupported compression in extent: %i\n", __func__,