xref: /openbmc/linux/lib/zlib_deflate/deflate.c (revision aa5b395b)
1 /* +++ deflate.c */
2 /* deflate.c -- compress data using the deflation algorithm
3  * Copyright (C) 1995-1996 Jean-loup Gailly.
4  * For conditions of distribution and use, see copyright notice in zlib.h
5  */
6 
7 /*
8  *  ALGORITHM
9  *
10  *      The "deflation" process depends on being able to identify portions
11  *      of the input text which are identical to earlier input (within a
12  *      sliding window trailing behind the input currently being processed).
13  *
14  *      The most straightforward technique turns out to be the fastest for
15  *      most input files: try all possible matches and select the longest.
16  *      The key feature of this algorithm is that insertions into the string
17  *      dictionary are very simple and thus fast, and deletions are avoided
18  *      completely. Insertions are performed at each input character, whereas
19  *      string matches are performed only when the previous match ends. So it
20  *      is preferable to spend more time in matches to allow very fast string
21  *      insertions and avoid deletions. The matching algorithm for small
22  *      strings is inspired from that of Rabin & Karp. A brute force approach
23  *      is used to find longer strings when a small match has been found.
24  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
25  *      (by Leonid Broukhis).
26  *         A previous version of this file used a more sophisticated algorithm
27  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
28  *      time, but has a larger average cost, uses more memory and is patented.
29  *      However the F&G algorithm may be faster for some highly redundant
30  *      files if the parameter max_chain_length (described below) is too large.
31  *
32  *  ACKNOWLEDGEMENTS
33  *
34  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
35  *      I found it in 'freeze' written by Leonid Broukhis.
36  *      Thanks to many people for bug reports and testing.
37  *
38  *  REFERENCES
39  *
40  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
41  *      Available in ftp://ds.internic.net/rfc/rfc1951.txt
42  *
43  *      A description of the Rabin and Karp algorithm is given in the book
44  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45  *
46  *      Fiala,E.R., and Greene,D.H.
47  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
48  *
49  */
50 
51 #include <linux/module.h>
52 #include <linux/zutil.h>
53 #include "defutil.h"
54 
55 /* architecture-specific bits */
56 #ifdef CONFIG_ZLIB_DFLTCC
57 #  include "../zlib_dfltcc/dfltcc.h"
58 #else
59 #define DEFLATE_RESET_HOOK(strm) do {} while (0)
60 #define DEFLATE_HOOK(strm, flush, bstate) 0
61 #define DEFLATE_NEED_CHECKSUM(strm) 1
62 #endif
63 
64 /* ===========================================================================
65  *  Function prototypes.
66  */
67 
68 typedef block_state (*compress_func) (deflate_state *s, int flush);
69 /* Compression function. Returns the block state after the call. */
70 
71 static void fill_window    (deflate_state *s);
72 static block_state deflate_stored (deflate_state *s, int flush);
73 static block_state deflate_fast   (deflate_state *s, int flush);
74 static block_state deflate_slow   (deflate_state *s, int flush);
75 static void lm_init        (deflate_state *s);
76 static void putShortMSB    (deflate_state *s, uInt b);
77 static int read_buf        (z_streamp strm, Byte *buf, unsigned size);
78 static uInt longest_match  (deflate_state *s, IPos cur_match);
79 
80 #ifdef DEBUG_ZLIB
81 static  void check_match (deflate_state *s, IPos start, IPos match,
82                          int length);
83 #endif
84 
85 /* ===========================================================================
86  * Local data
87  */
88 
89 #define NIL 0
90 /* Tail of hash chains */
91 
92 #ifndef TOO_FAR
93 #  define TOO_FAR 4096
94 #endif
95 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
96 
97 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
98 /* Minimum amount of lookahead, except at the end of the input file.
99  * See deflate.c for comments about the MIN_MATCH+1.
100  */
101 
102 /* Workspace to be allocated for deflate processing */
103 typedef struct deflate_workspace {
104     /* State memory for the deflator */
105     deflate_state deflate_memory;
106 #ifdef CONFIG_ZLIB_DFLTCC
107     /* State memory for s390 hardware deflate */
108     struct dfltcc_state dfltcc_memory;
109 #endif
110     Byte *window_memory;
111     Pos *prev_memory;
112     Pos *head_memory;
113     char *overlay_memory;
114 } deflate_workspace;
115 
116 #ifdef CONFIG_ZLIB_DFLTCC
117 /* dfltcc_state must be doubleword aligned for DFLTCC call */
118 static_assert(offsetof(struct deflate_workspace, dfltcc_memory) % 8 == 0);
119 #endif
120 
121 /* Values for max_lazy_match, good_match and max_chain_length, depending on
122  * the desired pack level (0..9). The values given below have been tuned to
123  * exclude worst case performance for pathological files. Better values may be
124  * found for specific files.
125  */
126 typedef struct config_s {
127    ush good_length; /* reduce lazy search above this match length */
128    ush max_lazy;    /* do not perform lazy search above this match length */
129    ush nice_length; /* quit search above this match length */
130    ush max_chain;
131    compress_func func;
132 } config;
133 
134 static const config configuration_table[10] = {
135 /*      good lazy nice chain */
136 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
137 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
138 /* 2 */ {4,    5, 16,    8, deflate_fast},
139 /* 3 */ {4,    6, 32,   32, deflate_fast},
140 
141 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
142 /* 5 */ {8,   16, 32,   32, deflate_slow},
143 /* 6 */ {8,   16, 128, 128, deflate_slow},
144 /* 7 */ {8,   32, 128, 256, deflate_slow},
145 /* 8 */ {32, 128, 258, 1024, deflate_slow},
146 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
147 
148 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
149  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
150  * meaning.
151  */
152 
153 #define EQUAL 0
154 /* result of memcmp for equal strings */
155 
156 /* ===========================================================================
157  * Update a hash value with the given input byte
158  * IN  assertion: all calls to UPDATE_HASH are made with consecutive
159  *    input characters, so that a running hash key can be computed from the
160  *    previous key instead of complete recalculation each time.
161  */
162 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
163 
164 
165 /* ===========================================================================
166  * Insert string str in the dictionary and set match_head to the previous head
167  * of the hash chain (the most recent string with same hash key). Return
168  * the previous length of the hash chain.
169  * IN  assertion: all calls to INSERT_STRING are made with consecutive
170  *    input characters and the first MIN_MATCH bytes of str are valid
171  *    (except for the last MIN_MATCH-1 bytes of the input file).
172  */
173 #define INSERT_STRING(s, str, match_head) \
174    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
175     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
176     s->head[s->ins_h] = (Pos)(str))
177 
178 /* ===========================================================================
179  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
180  * prev[] will be initialized on the fly.
181  */
182 #define CLEAR_HASH(s) \
183     s->head[s->hash_size-1] = NIL; \
184     memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head));
185 
186 /* ========================================================================= */
187 int zlib_deflateInit2(
188 	z_streamp strm,
189 	int  level,
190 	int  method,
191 	int  windowBits,
192 	int  memLevel,
193 	int  strategy
194 )
195 {
196     deflate_state *s;
197     int noheader = 0;
198     deflate_workspace *mem;
199     char *next;
200 
201     ush *overlay;
202     /* We overlay pending_buf and d_buf+l_buf. This works since the average
203      * output size for (length,distance) codes is <= 24 bits.
204      */
205 
206     if (strm == NULL) return Z_STREAM_ERROR;
207 
208     strm->msg = NULL;
209 
210     if (level == Z_DEFAULT_COMPRESSION) level = 6;
211 
212     mem = (deflate_workspace *) strm->workspace;
213 
214     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
215         noheader = 1;
216         windowBits = -windowBits;
217     }
218     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
219         windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
220 	strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
221         return Z_STREAM_ERROR;
222     }
223 
224     /*
225      * Direct the workspace's pointers to the chunks that were allocated
226      * along with the deflate_workspace struct.
227      */
228     next = (char *) mem;
229     next += sizeof(*mem);
230 #ifdef CONFIG_ZLIB_DFLTCC
231     /*
232      *  DFLTCC requires the window to be page aligned.
233      *  Thus, we overallocate and take the aligned portion of the buffer.
234      */
235     mem->window_memory = (Byte *) PTR_ALIGN(next, PAGE_SIZE);
236 #else
237     mem->window_memory = (Byte *) next;
238 #endif
239     next += zlib_deflate_window_memsize(windowBits);
240     mem->prev_memory = (Pos *) next;
241     next += zlib_deflate_prev_memsize(windowBits);
242     mem->head_memory = (Pos *) next;
243     next += zlib_deflate_head_memsize(memLevel);
244     mem->overlay_memory = next;
245 
246     s = (deflate_state *) &(mem->deflate_memory);
247     strm->state = (struct internal_state *)s;
248     s->strm = strm;
249 
250     s->noheader = noheader;
251     s->w_bits = windowBits;
252     s->w_size = 1 << s->w_bits;
253     s->w_mask = s->w_size - 1;
254 
255     s->hash_bits = memLevel + 7;
256     s->hash_size = 1 << s->hash_bits;
257     s->hash_mask = s->hash_size - 1;
258     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
259 
260     s->window = (Byte *) mem->window_memory;
261     s->prev   = (Pos *)  mem->prev_memory;
262     s->head   = (Pos *)  mem->head_memory;
263 
264     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
265 
266     overlay = (ush *) mem->overlay_memory;
267     s->pending_buf = (uch *) overlay;
268     s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
269 
270     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
271     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
272 
273     s->level = level;
274     s->strategy = strategy;
275     s->method = (Byte)method;
276 
277     return zlib_deflateReset(strm);
278 }
279 
280 /* ========================================================================= */
281 int zlib_deflateReset(
282 	z_streamp strm
283 )
284 {
285     deflate_state *s;
286 
287     if (strm == NULL || strm->state == NULL)
288         return Z_STREAM_ERROR;
289 
290     strm->total_in = strm->total_out = 0;
291     strm->msg = NULL;
292     strm->data_type = Z_UNKNOWN;
293 
294     s = (deflate_state *)strm->state;
295     s->pending = 0;
296     s->pending_out = s->pending_buf;
297 
298     if (s->noheader < 0) {
299         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
300     }
301     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
302     strm->adler = 1;
303     s->last_flush = Z_NO_FLUSH;
304 
305     zlib_tr_init(s);
306     lm_init(s);
307 
308     DEFLATE_RESET_HOOK(strm);
309 
310     return Z_OK;
311 }
312 
313 /* =========================================================================
314  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
315  * IN assertion: the stream state is correct and there is enough room in
316  * pending_buf.
317  */
318 static void putShortMSB(
319 	deflate_state *s,
320 	uInt b
321 )
322 {
323     put_byte(s, (Byte)(b >> 8));
324     put_byte(s, (Byte)(b & 0xff));
325 }
326 
327 /* ========================================================================= */
328 int zlib_deflate(
329 	z_streamp strm,
330 	int flush
331 )
332 {
333     int old_flush; /* value of flush param for previous deflate call */
334     deflate_state *s;
335 
336     if (strm == NULL || strm->state == NULL ||
337 	flush > Z_FINISH || flush < 0) {
338         return Z_STREAM_ERROR;
339     }
340     s = (deflate_state *) strm->state;
341 
342     if ((strm->next_in == NULL && strm->avail_in != 0) ||
343 	(s->status == FINISH_STATE && flush != Z_FINISH)) {
344         return Z_STREAM_ERROR;
345     }
346     if (strm->avail_out == 0) return Z_BUF_ERROR;
347 
348     s->strm = strm; /* just in case */
349     old_flush = s->last_flush;
350     s->last_flush = flush;
351 
352     /* Write the zlib header */
353     if (s->status == INIT_STATE) {
354 
355         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
356         uInt level_flags = (s->level-1) >> 1;
357 
358         if (level_flags > 3) level_flags = 3;
359         header |= (level_flags << 6);
360 	if (s->strstart != 0) header |= PRESET_DICT;
361         header += 31 - (header % 31);
362 
363         s->status = BUSY_STATE;
364         putShortMSB(s, header);
365 
366 	/* Save the adler32 of the preset dictionary: */
367 	if (s->strstart != 0) {
368 	    putShortMSB(s, (uInt)(strm->adler >> 16));
369 	    putShortMSB(s, (uInt)(strm->adler & 0xffff));
370 	}
371 	strm->adler = 1L;
372     }
373 
374     /* Flush as much pending output as possible */
375     if (s->pending != 0) {
376         flush_pending(strm);
377         if (strm->avail_out == 0) {
378 	    /* Since avail_out is 0, deflate will be called again with
379 	     * more output space, but possibly with both pending and
380 	     * avail_in equal to zero. There won't be anything to do,
381 	     * but this is not an error situation so make sure we
382 	     * return OK instead of BUF_ERROR at next call of deflate:
383              */
384 	    s->last_flush = -1;
385 	    return Z_OK;
386 	}
387 
388     /* Make sure there is something to do and avoid duplicate consecutive
389      * flushes. For repeated and useless calls with Z_FINISH, we keep
390      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
391      */
392     } else if (strm->avail_in == 0 && flush <= old_flush &&
393 	       flush != Z_FINISH) {
394         return Z_BUF_ERROR;
395     }
396 
397     /* User must not provide more input after the first FINISH: */
398     if (s->status == FINISH_STATE && strm->avail_in != 0) {
399         return Z_BUF_ERROR;
400     }
401 
402     /* Start a new block or continue the current one.
403      */
404     if (strm->avail_in != 0 || s->lookahead != 0 ||
405         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
406         block_state bstate;
407 
408 	bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate :
409 		 (*(configuration_table[s->level].func))(s, flush);
410 
411         if (bstate == finish_started || bstate == finish_done) {
412             s->status = FINISH_STATE;
413         }
414         if (bstate == need_more || bstate == finish_started) {
415 	    if (strm->avail_out == 0) {
416 	        s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
417 	    }
418 	    return Z_OK;
419 	    /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
420 	     * of deflate should use the same flush parameter to make sure
421 	     * that the flush is complete. So we don't have to output an
422 	     * empty block here, this will be done at next call. This also
423 	     * ensures that for a very small output buffer, we emit at most
424 	     * one empty block.
425 	     */
426 	}
427         if (bstate == block_done) {
428             if (flush == Z_PARTIAL_FLUSH) {
429                 zlib_tr_align(s);
430 	    } else if (flush == Z_PACKET_FLUSH) {
431 		/* Output just the 3-bit `stored' block type value,
432 		   but not a zero length. */
433 		zlib_tr_stored_type_only(s);
434             } else { /* FULL_FLUSH or SYNC_FLUSH */
435                 zlib_tr_stored_block(s, (char*)0, 0L, 0);
436                 /* For a full flush, this empty block will be recognized
437                  * as a special marker by inflate_sync().
438                  */
439                 if (flush == Z_FULL_FLUSH) {
440                     CLEAR_HASH(s);             /* forget history */
441                 }
442             }
443             flush_pending(strm);
444 	    if (strm->avail_out == 0) {
445 	      s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
446 	      return Z_OK;
447 	    }
448         }
449     }
450     Assert(strm->avail_out > 0, "bug2");
451 
452     if (flush != Z_FINISH) return Z_OK;
453     if (s->noheader) return Z_STREAM_END;
454 
455     /* Write the zlib trailer (adler32) */
456     putShortMSB(s, (uInt)(strm->adler >> 16));
457     putShortMSB(s, (uInt)(strm->adler & 0xffff));
458     flush_pending(strm);
459     /* If avail_out is zero, the application will call deflate again
460      * to flush the rest.
461      */
462     s->noheader = -1; /* write the trailer only once! */
463     return s->pending != 0 ? Z_OK : Z_STREAM_END;
464 }
465 
466 /* ========================================================================= */
467 int zlib_deflateEnd(
468 	z_streamp strm
469 )
470 {
471     int status;
472     deflate_state *s;
473 
474     if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
475     s = (deflate_state *) strm->state;
476 
477     status = s->status;
478     if (status != INIT_STATE && status != BUSY_STATE &&
479 	status != FINISH_STATE) {
480       return Z_STREAM_ERROR;
481     }
482 
483     strm->state = NULL;
484 
485     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
486 }
487 
488 /* ===========================================================================
489  * Read a new buffer from the current input stream, update the adler32
490  * and total number of bytes read.  All deflate() input goes through
491  * this function so some applications may wish to modify it to avoid
492  * allocating a large strm->next_in buffer and copying from it.
493  * (See also flush_pending()).
494  */
495 static int read_buf(
496 	z_streamp strm,
497 	Byte *buf,
498 	unsigned size
499 )
500 {
501     unsigned len = strm->avail_in;
502 
503     if (len > size) len = size;
504     if (len == 0) return 0;
505 
506     strm->avail_in  -= len;
507 
508     if (!DEFLATE_NEED_CHECKSUM(strm)) {}
509     else if (!((deflate_state *)(strm->state))->noheader) {
510         strm->adler = zlib_adler32(strm->adler, strm->next_in, len);
511     }
512     memcpy(buf, strm->next_in, len);
513     strm->next_in  += len;
514     strm->total_in += len;
515 
516     return (int)len;
517 }
518 
519 /* ===========================================================================
520  * Initialize the "longest match" routines for a new zlib stream
521  */
522 static void lm_init(
523 	deflate_state *s
524 )
525 {
526     s->window_size = (ulg)2L*s->w_size;
527 
528     CLEAR_HASH(s);
529 
530     /* Set the default configuration parameters:
531      */
532     s->max_lazy_match   = configuration_table[s->level].max_lazy;
533     s->good_match       = configuration_table[s->level].good_length;
534     s->nice_match       = configuration_table[s->level].nice_length;
535     s->max_chain_length = configuration_table[s->level].max_chain;
536 
537     s->strstart = 0;
538     s->block_start = 0L;
539     s->lookahead = 0;
540     s->match_length = s->prev_length = MIN_MATCH-1;
541     s->match_available = 0;
542     s->ins_h = 0;
543 }
544 
545 /* ===========================================================================
546  * Set match_start to the longest match starting at the given string and
547  * return its length. Matches shorter or equal to prev_length are discarded,
548  * in which case the result is equal to prev_length and match_start is
549  * garbage.
550  * IN assertions: cur_match is the head of the hash chain for the current
551  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
552  * OUT assertion: the match length is not greater than s->lookahead.
553  */
554 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
555  * match.S. The code will be functionally equivalent.
556  */
557 static uInt longest_match(
558 	deflate_state *s,
559 	IPos cur_match			/* current match */
560 )
561 {
562     unsigned chain_length = s->max_chain_length;/* max hash chain length */
563     register Byte *scan = s->window + s->strstart; /* current string */
564     register Byte *match;                       /* matched string */
565     register int len;                           /* length of current match */
566     int best_len = s->prev_length;              /* best match length so far */
567     int nice_match = s->nice_match;             /* stop if match long enough */
568     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
569         s->strstart - (IPos)MAX_DIST(s) : NIL;
570     /* Stop when cur_match becomes <= limit. To simplify the code,
571      * we prevent matches with the string of window index 0.
572      */
573     Pos *prev = s->prev;
574     uInt wmask = s->w_mask;
575 
576 #ifdef UNALIGNED_OK
577     /* Compare two bytes at a time. Note: this is not always beneficial.
578      * Try with and without -DUNALIGNED_OK to check.
579      */
580     register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
581     register ush scan_start = *(ush*)scan;
582     register ush scan_end   = *(ush*)(scan+best_len-1);
583 #else
584     register Byte *strend = s->window + s->strstart + MAX_MATCH;
585     register Byte scan_end1  = scan[best_len-1];
586     register Byte scan_end   = scan[best_len];
587 #endif
588 
589     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
590      * It is easy to get rid of this optimization if necessary.
591      */
592     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
593 
594     /* Do not waste too much time if we already have a good match: */
595     if (s->prev_length >= s->good_match) {
596         chain_length >>= 2;
597     }
598     /* Do not look for matches beyond the end of the input. This is necessary
599      * to make deflate deterministic.
600      */
601     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
602 
603     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
604 
605     do {
606         Assert(cur_match < s->strstart, "no future");
607         match = s->window + cur_match;
608 
609         /* Skip to next match if the match length cannot increase
610          * or if the match length is less than 2:
611          */
612 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
613         /* This code assumes sizeof(unsigned short) == 2. Do not use
614          * UNALIGNED_OK if your compiler uses a different size.
615          */
616         if (*(ush*)(match+best_len-1) != scan_end ||
617             *(ush*)match != scan_start) continue;
618 
619         /* It is not necessary to compare scan[2] and match[2] since they are
620          * always equal when the other bytes match, given that the hash keys
621          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
622          * strstart+3, +5, ... up to strstart+257. We check for insufficient
623          * lookahead only every 4th comparison; the 128th check will be made
624          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
625          * necessary to put more guard bytes at the end of the window, or
626          * to check more often for insufficient lookahead.
627          */
628         Assert(scan[2] == match[2], "scan[2]?");
629         scan++, match++;
630         do {
631         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
632                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
633                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
634                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
635                  scan < strend);
636         /* The funny "do {}" generates better code on most compilers */
637 
638         /* Here, scan <= window+strstart+257 */
639         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
640         if (*scan == *match) scan++;
641 
642         len = (MAX_MATCH - 1) - (int)(strend-scan);
643         scan = strend - (MAX_MATCH-1);
644 
645 #else /* UNALIGNED_OK */
646 
647         if (match[best_len]   != scan_end  ||
648             match[best_len-1] != scan_end1 ||
649             *match            != *scan     ||
650             *++match          != scan[1])      continue;
651 
652         /* The check at best_len-1 can be removed because it will be made
653          * again later. (This heuristic is not always a win.)
654          * It is not necessary to compare scan[2] and match[2] since they
655          * are always equal when the other bytes match, given that
656          * the hash keys are equal and that HASH_BITS >= 8.
657          */
658         scan += 2, match++;
659         Assert(*scan == *match, "match[2]?");
660 
661         /* We check for insufficient lookahead only every 8th comparison;
662          * the 256th check will be made at strstart+258.
663          */
664         do {
665         } while (*++scan == *++match && *++scan == *++match &&
666                  *++scan == *++match && *++scan == *++match &&
667                  *++scan == *++match && *++scan == *++match &&
668                  *++scan == *++match && *++scan == *++match &&
669                  scan < strend);
670 
671         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
672 
673         len = MAX_MATCH - (int)(strend - scan);
674         scan = strend - MAX_MATCH;
675 
676 #endif /* UNALIGNED_OK */
677 
678         if (len > best_len) {
679             s->match_start = cur_match;
680             best_len = len;
681             if (len >= nice_match) break;
682 #ifdef UNALIGNED_OK
683             scan_end = *(ush*)(scan+best_len-1);
684 #else
685             scan_end1  = scan[best_len-1];
686             scan_end   = scan[best_len];
687 #endif
688         }
689     } while ((cur_match = prev[cur_match & wmask]) > limit
690              && --chain_length != 0);
691 
692     if ((uInt)best_len <= s->lookahead) return best_len;
693     return s->lookahead;
694 }
695 
696 #ifdef DEBUG_ZLIB
697 /* ===========================================================================
698  * Check that the match at match_start is indeed a match.
699  */
700 static void check_match(
701 	deflate_state *s,
702 	IPos start,
703 	IPos match,
704 	int length
705 )
706 {
707     /* check that the match is indeed a match */
708     if (memcmp((char *)s->window + match,
709                 (char *)s->window + start, length) != EQUAL) {
710         fprintf(stderr, " start %u, match %u, length %d\n",
711 		start, match, length);
712         do {
713 	    fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
714 	} while (--length != 0);
715         z_error("invalid match");
716     }
717     if (z_verbose > 1) {
718         fprintf(stderr,"\\[%d,%d]", start-match, length);
719         do { putc(s->window[start++], stderr); } while (--length != 0);
720     }
721 }
722 #else
723 #  define check_match(s, start, match, length)
724 #endif
725 
726 /* ===========================================================================
727  * Fill the window when the lookahead becomes insufficient.
728  * Updates strstart and lookahead.
729  *
730  * IN assertion: lookahead < MIN_LOOKAHEAD
731  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
732  *    At least one byte has been read, or avail_in == 0; reads are
733  *    performed for at least two bytes (required for the zip translate_eol
734  *    option -- not supported here).
735  */
736 static void fill_window(
737 	deflate_state *s
738 )
739 {
740     register unsigned n, m;
741     register Pos *p;
742     unsigned more;    /* Amount of free space at the end of the window. */
743     uInt wsize = s->w_size;
744 
745     do {
746         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
747 
748         /* Deal with !@#$% 64K limit: */
749         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
750             more = wsize;
751 
752         } else if (more == (unsigned)(-1)) {
753             /* Very unlikely, but possible on 16 bit machine if strstart == 0
754              * and lookahead == 1 (input done one byte at time)
755              */
756             more--;
757 
758         /* If the window is almost full and there is insufficient lookahead,
759          * move the upper half to the lower one to make room in the upper half.
760          */
761         } else if (s->strstart >= wsize+MAX_DIST(s)) {
762 
763             memcpy((char *)s->window, (char *)s->window+wsize,
764                    (unsigned)wsize);
765             s->match_start -= wsize;
766             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
767             s->block_start -= (long) wsize;
768 
769             /* Slide the hash table (could be avoided with 32 bit values
770                at the expense of memory usage). We slide even when level == 0
771                to keep the hash table consistent if we switch back to level > 0
772                later. (Using level 0 permanently is not an optimal usage of
773                zlib, so we don't care about this pathological case.)
774              */
775             n = s->hash_size;
776             p = &s->head[n];
777             do {
778                 m = *--p;
779                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
780             } while (--n);
781 
782             n = wsize;
783             p = &s->prev[n];
784             do {
785                 m = *--p;
786                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
787                 /* If n is not on any hash chain, prev[n] is garbage but
788                  * its value will never be used.
789                  */
790             } while (--n);
791             more += wsize;
792         }
793         if (s->strm->avail_in == 0) return;
794 
795         /* If there was no sliding:
796          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
797          *    more == window_size - lookahead - strstart
798          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
799          * => more >= window_size - 2*WSIZE + 2
800          * In the BIG_MEM or MMAP case (not yet supported),
801          *   window_size == input_size + MIN_LOOKAHEAD  &&
802          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
803          * Otherwise, window_size == 2*WSIZE so more >= 2.
804          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
805          */
806         Assert(more >= 2, "more < 2");
807 
808         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
809         s->lookahead += n;
810 
811         /* Initialize the hash value now that we have some input: */
812         if (s->lookahead >= MIN_MATCH) {
813             s->ins_h = s->window[s->strstart];
814             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
815 #if MIN_MATCH != 3
816             Call UPDATE_HASH() MIN_MATCH-3 more times
817 #endif
818         }
819         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
820          * but this is not important since only literal bytes will be emitted.
821          */
822 
823     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
824 }
825 
826 /* ===========================================================================
827  * Flush the current block, with given end-of-file flag.
828  * IN assertion: strstart is set to the end of the current match.
829  */
830 #define FLUSH_BLOCK_ONLY(s, eof) { \
831    zlib_tr_flush_block(s, (s->block_start >= 0L ? \
832                    (char *)&s->window[(unsigned)s->block_start] : \
833                    NULL), \
834 		(ulg)((long)s->strstart - s->block_start), \
835 		(eof)); \
836    s->block_start = s->strstart; \
837    flush_pending(s->strm); \
838    Tracev((stderr,"[FLUSH]")); \
839 }
840 
841 /* Same but force premature exit if necessary. */
842 #define FLUSH_BLOCK(s, eof) { \
843    FLUSH_BLOCK_ONLY(s, eof); \
844    if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
845 }
846 
847 /* ===========================================================================
848  * Copy without compression as much as possible from the input stream, return
849  * the current block state.
850  * This function does not insert new strings in the dictionary since
851  * uncompressible data is probably not useful. This function is used
852  * only for the level=0 compression option.
853  * NOTE: this function should be optimized to avoid extra copying from
854  * window to pending_buf.
855  */
856 static block_state deflate_stored(
857 	deflate_state *s,
858 	int flush
859 )
860 {
861     /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
862      * to pending_buf_size, and each stored block has a 5 byte header:
863      */
864     ulg max_block_size = 0xffff;
865     ulg max_start;
866 
867     if (max_block_size > s->pending_buf_size - 5) {
868         max_block_size = s->pending_buf_size - 5;
869     }
870 
871     /* Copy as much as possible from input to output: */
872     for (;;) {
873         /* Fill the window as much as possible: */
874         if (s->lookahead <= 1) {
875 
876             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
877 		   s->block_start >= (long)s->w_size, "slide too late");
878 
879             fill_window(s);
880             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
881 
882             if (s->lookahead == 0) break; /* flush the current block */
883         }
884 	Assert(s->block_start >= 0L, "block gone");
885 
886 	s->strstart += s->lookahead;
887 	s->lookahead = 0;
888 
889 	/* Emit a stored block if pending_buf will be full: */
890  	max_start = s->block_start + max_block_size;
891         if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
892 	    /* strstart == 0 is possible when wraparound on 16-bit machine */
893 	    s->lookahead = (uInt)(s->strstart - max_start);
894 	    s->strstart = (uInt)max_start;
895             FLUSH_BLOCK(s, 0);
896 	}
897 	/* Flush if we may have to slide, otherwise block_start may become
898          * negative and the data will be gone:
899          */
900         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
901             FLUSH_BLOCK(s, 0);
902 	}
903     }
904     FLUSH_BLOCK(s, flush == Z_FINISH);
905     return flush == Z_FINISH ? finish_done : block_done;
906 }
907 
908 /* ===========================================================================
909  * Compress as much as possible from the input stream, return the current
910  * block state.
911  * This function does not perform lazy evaluation of matches and inserts
912  * new strings in the dictionary only for unmatched strings or for short
913  * matches. It is used only for the fast compression options.
914  */
915 static block_state deflate_fast(
916 	deflate_state *s,
917 	int flush
918 )
919 {
920     IPos hash_head = NIL; /* head of the hash chain */
921     int bflush;           /* set if current block must be flushed */
922 
923     for (;;) {
924         /* Make sure that we always have enough lookahead, except
925          * at the end of the input file. We need MAX_MATCH bytes
926          * for the next match, plus MIN_MATCH bytes to insert the
927          * string following the next match.
928          */
929         if (s->lookahead < MIN_LOOKAHEAD) {
930             fill_window(s);
931             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
932 	        return need_more;
933 	    }
934             if (s->lookahead == 0) break; /* flush the current block */
935         }
936 
937         /* Insert the string window[strstart .. strstart+2] in the
938          * dictionary, and set hash_head to the head of the hash chain:
939          */
940         if (s->lookahead >= MIN_MATCH) {
941             INSERT_STRING(s, s->strstart, hash_head);
942         }
943 
944         /* Find the longest match, discarding those <= prev_length.
945          * At this point we have always match_length < MIN_MATCH
946          */
947         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
948             /* To simplify the code, we prevent matches with the string
949              * of window index 0 (in particular we have to avoid a match
950              * of the string with itself at the start of the input file).
951              */
952             if (s->strategy != Z_HUFFMAN_ONLY) {
953                 s->match_length = longest_match (s, hash_head);
954             }
955             /* longest_match() sets match_start */
956         }
957         if (s->match_length >= MIN_MATCH) {
958             check_match(s, s->strstart, s->match_start, s->match_length);
959 
960             bflush = zlib_tr_tally(s, s->strstart - s->match_start,
961                                s->match_length - MIN_MATCH);
962 
963             s->lookahead -= s->match_length;
964 
965             /* Insert new strings in the hash table only if the match length
966              * is not too large. This saves time but degrades compression.
967              */
968             if (s->match_length <= s->max_insert_length &&
969                 s->lookahead >= MIN_MATCH) {
970                 s->match_length--; /* string at strstart already in hash table */
971                 do {
972                     s->strstart++;
973                     INSERT_STRING(s, s->strstart, hash_head);
974                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
975                      * always MIN_MATCH bytes ahead.
976                      */
977                 } while (--s->match_length != 0);
978                 s->strstart++;
979             } else {
980                 s->strstart += s->match_length;
981                 s->match_length = 0;
982                 s->ins_h = s->window[s->strstart];
983                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
984 #if MIN_MATCH != 3
985                 Call UPDATE_HASH() MIN_MATCH-3 more times
986 #endif
987                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
988                  * matter since it will be recomputed at next deflate call.
989                  */
990             }
991         } else {
992             /* No match, output a literal byte */
993             Tracevv((stderr,"%c", s->window[s->strstart]));
994             bflush = zlib_tr_tally (s, 0, s->window[s->strstart]);
995             s->lookahead--;
996             s->strstart++;
997         }
998         if (bflush) FLUSH_BLOCK(s, 0);
999     }
1000     FLUSH_BLOCK(s, flush == Z_FINISH);
1001     return flush == Z_FINISH ? finish_done : block_done;
1002 }
1003 
1004 /* ===========================================================================
1005  * Same as above, but achieves better compression. We use a lazy
1006  * evaluation for matches: a match is finally adopted only if there is
1007  * no better match at the next window position.
1008  */
1009 static block_state deflate_slow(
1010 	deflate_state *s,
1011 	int flush
1012 )
1013 {
1014     IPos hash_head = NIL;    /* head of hash chain */
1015     int bflush;              /* set if current block must be flushed */
1016 
1017     /* Process the input block. */
1018     for (;;) {
1019         /* Make sure that we always have enough lookahead, except
1020          * at the end of the input file. We need MAX_MATCH bytes
1021          * for the next match, plus MIN_MATCH bytes to insert the
1022          * string following the next match.
1023          */
1024         if (s->lookahead < MIN_LOOKAHEAD) {
1025             fill_window(s);
1026             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1027 	        return need_more;
1028 	    }
1029             if (s->lookahead == 0) break; /* flush the current block */
1030         }
1031 
1032         /* Insert the string window[strstart .. strstart+2] in the
1033          * dictionary, and set hash_head to the head of the hash chain:
1034          */
1035         if (s->lookahead >= MIN_MATCH) {
1036             INSERT_STRING(s, s->strstart, hash_head);
1037         }
1038 
1039         /* Find the longest match, discarding those <= prev_length.
1040          */
1041         s->prev_length = s->match_length, s->prev_match = s->match_start;
1042         s->match_length = MIN_MATCH-1;
1043 
1044         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1045             s->strstart - hash_head <= MAX_DIST(s)) {
1046             /* To simplify the code, we prevent matches with the string
1047              * of window index 0 (in particular we have to avoid a match
1048              * of the string with itself at the start of the input file).
1049              */
1050             if (s->strategy != Z_HUFFMAN_ONLY) {
1051                 s->match_length = longest_match (s, hash_head);
1052             }
1053             /* longest_match() sets match_start */
1054 
1055             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1056                  (s->match_length == MIN_MATCH &&
1057                   s->strstart - s->match_start > TOO_FAR))) {
1058 
1059                 /* If prev_match is also MIN_MATCH, match_start is garbage
1060                  * but we will ignore the current match anyway.
1061                  */
1062                 s->match_length = MIN_MATCH-1;
1063             }
1064         }
1065         /* If there was a match at the previous step and the current
1066          * match is not better, output the previous match:
1067          */
1068         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1069             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1070             /* Do not insert strings in hash table beyond this. */
1071 
1072             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1073 
1074             bflush = zlib_tr_tally(s, s->strstart -1 - s->prev_match,
1075 				   s->prev_length - MIN_MATCH);
1076 
1077             /* Insert in hash table all strings up to the end of the match.
1078              * strstart-1 and strstart are already inserted. If there is not
1079              * enough lookahead, the last two strings are not inserted in
1080              * the hash table.
1081              */
1082             s->lookahead -= s->prev_length-1;
1083             s->prev_length -= 2;
1084             do {
1085                 if (++s->strstart <= max_insert) {
1086                     INSERT_STRING(s, s->strstart, hash_head);
1087                 }
1088             } while (--s->prev_length != 0);
1089             s->match_available = 0;
1090             s->match_length = MIN_MATCH-1;
1091             s->strstart++;
1092 
1093             if (bflush) FLUSH_BLOCK(s, 0);
1094 
1095         } else if (s->match_available) {
1096             /* If there was no match at the previous position, output a
1097              * single literal. If there was a match but the current match
1098              * is longer, truncate the previous match to a single literal.
1099              */
1100             Tracevv((stderr,"%c", s->window[s->strstart-1]));
1101             if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) {
1102                 FLUSH_BLOCK_ONLY(s, 0);
1103             }
1104             s->strstart++;
1105             s->lookahead--;
1106             if (s->strm->avail_out == 0) return need_more;
1107         } else {
1108             /* There is no previous match to compare with, wait for
1109              * the next step to decide.
1110              */
1111             s->match_available = 1;
1112             s->strstart++;
1113             s->lookahead--;
1114         }
1115     }
1116     Assert (flush != Z_NO_FLUSH, "no flush?");
1117     if (s->match_available) {
1118         Tracevv((stderr,"%c", s->window[s->strstart-1]));
1119         zlib_tr_tally (s, 0, s->window[s->strstart-1]);
1120         s->match_available = 0;
1121     }
1122     FLUSH_BLOCK(s, flush == Z_FINISH);
1123     return flush == Z_FINISH ? finish_done : block_done;
1124 }
1125 
1126 int zlib_deflate_workspacesize(int windowBits, int memLevel)
1127 {
1128     if (windowBits < 0) /* undocumented feature: suppress zlib header */
1129         windowBits = -windowBits;
1130 
1131     /* Since the return value is typically passed to vmalloc() unchecked... */
1132     BUG_ON(memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 ||
1133 							windowBits > 15);
1134 
1135     return sizeof(deflate_workspace)
1136         + zlib_deflate_window_memsize(windowBits)
1137         + zlib_deflate_prev_memsize(windowBits)
1138         + zlib_deflate_head_memsize(memLevel)
1139         + zlib_deflate_overlay_memsize(memLevel);
1140 }
1141