3 * Lei Wen <leiwen@marvell.com>, Marvell Inc.
5 * SPDX-License-Identifier: GPL-2.0+
14 #include <u-boot/zlib.h>
15 #include "zlib/zutil.h"
17 #ifndef CONFIG_GZIP_COMPRESS_DEF_SZ
18 #define CONFIG_GZIP_COMPRESS_DEF_SZ 0x200
20 #define ZALLOC_ALIGNMENT 16
22 static void *zalloc(void *x
, unsigned items
, unsigned size
)
27 size
= (size
+ ZALLOC_ALIGNMENT
- 1) & ~(ZALLOC_ALIGNMENT
- 1);
29 p
= malloc_cache_aligned(size
);
34 static void zfree(void *x
, void *addr
, unsigned nb
)
39 int gzip(void *dst
, unsigned long *lenp
,
40 unsigned char *src
, unsigned long srclen
)
42 return zzip(dst
, lenp
, src
, srclen
, 1, NULL
);
46 * Compress blocks with zlib
48 int zzip(void *dst
, unsigned long *lenp
, unsigned char *src
,
49 unsigned long srclen
, int stoponerr
,
50 int (*func
)(unsigned long, unsigned long))
53 int r
, flush
, orig
, window
;
54 unsigned long comp_len
, left_len
;
62 window
= 2 * MAX_WBITS
;
69 r
= deflateInit2_(&s
, Z_BEST_SPEED
, Z_DEFLATED
, window
,
70 DEF_MEM_LEVEL
, Z_DEFAULT_STRATEGY
,
71 ZLIB_VERSION
, sizeof(z_stream
));
73 printf ("Error: deflateInit2_() returned %d\n", r
);
78 comp_len
= (srclen
> CONFIG_GZIP_COMPRESS_DEF_SZ
) ?
79 CONFIG_GZIP_COMPRESS_DEF_SZ
: srclen
;
82 s
.avail_in
= comp_len
;
83 flush
= (srclen
> CONFIG_GZIP_COMPRESS_DEF_SZ
)?
84 Z_NO_FLUSH
: Z_FINISH
;
87 left_len
= (*lenp
> CONFIG_GZIP_COMPRESS_DEF_SZ
) ?
88 CONFIG_GZIP_COMPRESS_DEF_SZ
: *lenp
;
90 s
.avail_out
= left_len
;
91 r
= deflate(&s
, flush
);
92 if (r
== Z_STREAM_ERROR
&& stoponerr
== 1) {
93 printf("Error: deflate() returned %d\n", r
);
98 dst
+= (left_len
- s
.avail_out
);
99 *lenp
-= (left_len
- s
.avail_out
);
100 } else if (left_len
- s
.avail_out
> 0) {
101 r
= func((unsigned long)dst
,
102 left_len
- s
.avail_out
);
106 } while (s
.avail_out
== 0 && (*lenp
> 0));
108 printf("Deflate failed to consume %u bytes", s
.avail_in
);
113 printf("Deflate need more space to compress "
114 "left %lu bytes\n", srclen
);
125 *lenp
= orig
- *lenp
;