xref: /openbmc/linux/arch/xtensa/boot/lib/zmem.c (revision 2a598d0b)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/zlib.h>
3 
4 /* bits taken from ppc */
5 
6 extern void *avail_ram, *end_avail;
7 
8 void exit (void)
9 {
10   for (;;);
11 }
12 
13 void *zalloc(unsigned size)
14 {
15         void *p = avail_ram;
16 
17         size = (size + 7) & -8;
18         avail_ram += size;
19         if (avail_ram > end_avail) {
20                 //puts("oops... out of memory\n");
21                 //pause();
22                 exit ();
23         }
24         return p;
25 }
26 
27 #define HEAD_CRC        2
28 #define EXTRA_FIELD     4
29 #define ORIG_NAME       8
30 #define COMMENT         0x10
31 #define RESERVED        0xe0
32 
33 #define DEFLATED        8
34 
35 void gunzip (void *dst, int dstlen, unsigned char *src, int *lenp)
36 {
37 	z_stream s;
38 	int r, i, flags;
39 
40         /* skip header */
41         i = 10;
42         flags = src[3];
43         if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
44                 //puts("bad gzipped data\n");
45                 exit();
46         }
47         if ((flags & EXTRA_FIELD) != 0)
48                 i = 12 + src[10] + (src[11] << 8);
49         if ((flags & ORIG_NAME) != 0)
50                 while (src[i++] != 0)
51                         ;
52         if ((flags & COMMENT) != 0)
53                 while (src[i++] != 0)
54                         ;
55         if ((flags & HEAD_CRC) != 0)
56                 i += 2;
57         if (i >= *lenp) {
58                 //puts("gunzip: ran out of data in header\n");
59                 exit();
60         }
61 
62 	s.workspace = zalloc(zlib_inflate_workspacesize());
63         r = zlib_inflateInit2(&s, -MAX_WBITS);
64         if (r != Z_OK) {
65                 //puts("inflateInit2 returned "); puthex(r); puts("\n");
66                 exit();
67         }
68         s.next_in = src + i;
69         s.avail_in = *lenp - i;
70         s.next_out = dst;
71         s.avail_out = dstlen;
72         r = zlib_inflate(&s, Z_FINISH);
73         if (r != Z_OK && r != Z_STREAM_END) {
74                 //puts("inflate returned "); puthex(r); puts("\n");
75                 exit();
76         }
77         *lenp = s.next_out - (unsigned char *) dst;
78         zlib_inflateEnd(&s);
79 }
80 
81