1 // SPDX-License-Identifier: GPL-2.0+
4 * Lei Wen <leiwen@marvell.com>, Marvell Inc.
13 #include <u-boot/zlib.h>
14 #include "zlib/zutil.h"
16 #ifndef CONFIG_GZIP_COMPRESS_DEF_SZ
17 #define CONFIG_GZIP_COMPRESS_DEF_SZ 0x200
19 #define ZALLOC_ALIGNMENT 16
21 static void *zalloc(void *x
, unsigned items
, unsigned size
)
26 size
= (size
+ ZALLOC_ALIGNMENT
- 1) & ~(ZALLOC_ALIGNMENT
- 1);
28 p
= malloc_cache_aligned(size
);
33 static void zfree(void *x
, void *addr
, unsigned nb
)
38 int gzip(void *dst
, unsigned long *lenp
,
39 unsigned char *src
, unsigned long srclen
)
41 return zzip(dst
, lenp
, src
, srclen
, 1, NULL
);
45 * Compress blocks with zlib
47 int zzip(void *dst
, unsigned long *lenp
, unsigned char *src
,
48 unsigned long srclen
, int stoponerr
,
49 int (*func
)(unsigned long, unsigned long))
52 int r
, flush
, orig
, window
;
53 unsigned long comp_len
, left_len
;
61 window
= 2 * MAX_WBITS
;
68 r
= deflateInit2_(&s
, Z_BEST_SPEED
, Z_DEFLATED
, window
,
69 DEF_MEM_LEVEL
, Z_DEFAULT_STRATEGY
,
70 ZLIB_VERSION
, sizeof(z_stream
));
72 printf ("Error: deflateInit2_() returned %d\n", r
);
77 comp_len
= (srclen
> CONFIG_GZIP_COMPRESS_DEF_SZ
) ?
78 CONFIG_GZIP_COMPRESS_DEF_SZ
: srclen
;
81 s
.avail_in
= comp_len
;
82 flush
= (srclen
> CONFIG_GZIP_COMPRESS_DEF_SZ
)?
83 Z_NO_FLUSH
: Z_FINISH
;
86 left_len
= (*lenp
> CONFIG_GZIP_COMPRESS_DEF_SZ
) ?
87 CONFIG_GZIP_COMPRESS_DEF_SZ
: *lenp
;
89 s
.avail_out
= left_len
;
90 r
= deflate(&s
, flush
);
91 if (r
== Z_STREAM_ERROR
&& stoponerr
== 1) {
92 printf("Error: deflate() returned %d\n", r
);
97 dst
+= (left_len
- s
.avail_out
);
98 *lenp
-= (left_len
- s
.avail_out
);
99 } else if (left_len
- s
.avail_out
> 0) {
100 r
= func((unsigned long)dst
,
101 left_len
- s
.avail_out
);
105 } while (s
.avail_out
== 0 && (*lenp
> 0));
107 printf("Deflate failed to consume %u bytes", s
.avail_in
);
112 printf("Deflate need more space to compress "
113 "left %lu bytes\n", srclen
);
124 *lenp
= orig
- *lenp
;