if: Multiple TX queue support step 3 of 3; map CPUID to subqueue
[dragonfly.git] / sys / net / bsd_comp.c
1 /* Because this code is derived from the 4.3BSD compress source:
2  *
3  *
4  * Copyright (c) 1985, 1986 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * James A. Woods, derived from original work by Spencer Thomas
9  * and Joseph Orost.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39
40 /*
41  * This version is for use with mbufs on BSD-derived systems.
42  *
43  * $FreeBSD: src/sys/net/bsd_comp.c,v 1.11.2.1 2002/04/14 21:41:48 luigi Exp $
44  */
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <net/ppp_layer/ppp_defs.h>
51
52 #define PACKETPTR       struct mbuf *
53 #include <net/ppp_layer/ppp_comp.h>
54
55 #if DO_BSD_COMPRESS
56 /*
57  * PPP "BSD compress" compression
58  *  The differences between this compression and the classic BSD LZW
59  *  source are obvious from the requirement that the classic code worked
60  *  with files while this handles arbitrarily long streams that
61  *  are broken into packets.  They are:
62  *
63  *      When the code size expands, a block of junk is not emitted by
64  *          the compressor and not expected by the decompressor.
65  *
66  *      New codes are not necessarily assigned every time an old
67  *          code is output by the compressor.  This is because a packet
68  *          end forces a code to be emitted, but does not imply that a
69  *          new sequence has been seen.
70  *
71  *      The compression ratio is checked at the first end of a packet
72  *          after the appropriate gap.  Besides simplifying and speeding
73  *          things up, this makes it more likely that the transmitter
74  *          and receiver will agree when the dictionary is cleared when
75  *          compression is not going well.
76  */
77
78 /*
79  * A dictionary for doing BSD compress.
80  */
81 struct bsd_db {
82     int     totlen;                     /* length of this structure */
83     u_int   hsize;                      /* size of the hash table */
84     u_char  hshift;                     /* used in hash function */
85     u_char  n_bits;                     /* current bits/code */
86     u_char  maxbits;
87     u_char  debug;
88     u_char  unit;
89     u_int16_t seqno;                    /* sequence # of next packet */
90     u_int   hdrlen;                     /* header length to preallocate */
91     u_int   mru;
92     u_int   maxmaxcode;                 /* largest valid code */
93     u_int   max_ent;                    /* largest code in use */
94     u_int   in_count;                   /* uncompressed bytes, aged */
95     u_int   bytes_out;                  /* compressed bytes, aged */
96     u_int   ratio;                      /* recent compression ratio */
97     u_int   checkpoint;                 /* when to next check the ratio */
98     u_int   clear_count;                /* times dictionary cleared */
99     u_int   incomp_count;               /* incompressible packets */
100     u_int   incomp_bytes;               /* incompressible bytes */
101     u_int   uncomp_count;               /* uncompressed packets */
102     u_int   uncomp_bytes;               /* uncompressed bytes */
103     u_int   comp_count;                 /* compressed packets */
104     u_int   comp_bytes;                 /* compressed bytes */
105     u_int16_t *lens;                    /* array of lengths of codes */
106     struct bsd_dict {
107         union {                         /* hash value */
108             u_int32_t   fcode;
109             struct {
110 #if BYTE_ORDER == LITTLE_ENDIAN
111                 u_int16_t prefix;       /* preceding code */
112                 u_char  suffix;         /* last character of new code */
113                 u_char  pad;
114 #else
115                 u_char  pad;
116                 u_char  suffix;         /* last character of new code */
117                 u_int16_t prefix;       /* preceding code */
118 #endif
119             } hs;
120         } f;
121         u_int16_t codem1;               /* output of hash table -1 */
122         u_int16_t cptr;                 /* map code to hash table entry */
123     } dict[1];
124 };
125
126 #define BSD_OVHD        2               /* BSD compress overhead/packet */
127 #define BSD_INIT_BITS   BSD_MIN_BITS
128
129 static void     bsd_clear (struct bsd_db *db);
130 static int      bsd_check (struct bsd_db *db);
131 static void     *bsd_alloc (u_char *options, int opt_len, int decomp);
132 static int      bsd_init (struct bsd_db *db, u_char *options, int opt_len,
133                               int unit, int hdrlen, int mru, int debug,
134                               int decomp);
135 static void     *bsd_comp_alloc (u_char *options, int opt_len);
136 static void     *bsd_decomp_alloc (u_char *options, int opt_len);
137 static void     bsd_free (void *state);
138 static int      bsd_comp_init (void *state, u_char *options, int opt_len,
139                                    int unit, int hdrlen, int debug);
140 static int      bsd_decomp_init (void *state, u_char *options, int opt_len,
141                                      int unit, int hdrlen, int mru, int debug);
142 static int      bsd_compress (void *state, struct mbuf **mret,
143                                   struct mbuf *mp, int slen, int maxolen);
144 static void     bsd_incomp (void *state, struct mbuf *dmsg);
145 static int      bsd_decompress (void *state, struct mbuf *cmp,
146                                     struct mbuf **dmpp);
147 static void     bsd_reset (void *state);
148 static void     bsd_comp_stats (void *state, struct compstat *stats);
149
150 /*
151  * Procedures exported to if_ppp.c.
152  */
153 struct compressor ppp_bsd_compress = {
154     CI_BSD_COMPRESS,            /* compress_proto */
155     bsd_comp_alloc,             /* comp_alloc */
156     bsd_free,                   /* comp_free */
157     bsd_comp_init,              /* comp_init */
158     bsd_reset,                  /* comp_reset */
159     bsd_compress,               /* compress */
160     bsd_comp_stats,             /* comp_stat */
161     bsd_decomp_alloc,           /* decomp_alloc */
162     bsd_free,                   /* decomp_free */
163     bsd_decomp_init,            /* decomp_init */
164     bsd_reset,                  /* decomp_reset */
165     bsd_decompress,             /* decompress */
166     bsd_incomp,                 /* incomp */
167     bsd_comp_stats,             /* decomp_stat */
168 };
169
170 /*
171  * the next two codes should not be changed lightly, as they must not
172  * lie within the contiguous general code space.
173  */
174 #define CLEAR   256                     /* table clear output code */
175 #define FIRST   257                     /* first free entry */
176 #define LAST    255
177
178 #define MAXCODE(b)      ((1 << (b)) - 1)
179 #define BADCODEM1       MAXCODE(BSD_MAX_BITS)
180
181 #define BSD_HASH(prefix,suffix,hshift)  ((((u_int32_t)(suffix)) << (hshift)) \
182                                          ^ (u_int32_t)(prefix))
183 #define BSD_KEY(prefix,suffix)          ((((u_int32_t)(suffix)) << 16) \
184                                          + (u_int32_t)(prefix))
185
186 #define CHECK_GAP       10000           /* Ratio check interval */
187
188 #define RATIO_SCALE_LOG 8
189 #define RATIO_SCALE     (1<<RATIO_SCALE_LOG)
190 #define RATIO_MAX       (0x7fffffff>>RATIO_SCALE_LOG)
191
192 /*
193  * clear the dictionary
194  */
195 static void
196 bsd_clear(struct bsd_db *db)
197 {
198     db->clear_count++;
199     db->max_ent = FIRST-1;
200     db->n_bits = BSD_INIT_BITS;
201     db->ratio = 0;
202     db->bytes_out = 0;
203     db->in_count = 0;
204     db->checkpoint = CHECK_GAP;
205 }
206
207 /*
208  * If the dictionary is full, then see if it is time to reset it.
209  *
210  * Compute the compression ratio using fixed-point arithmetic
211  * with 8 fractional bits.
212  *
213  * Since we have an infinite stream instead of a single file,
214  * watch only the local compression ratio.
215  *
216  * Since both peers must reset the dictionary at the same time even in
217  * the absence of CLEAR codes (while packets are incompressible), they
218  * must compute the same ratio.
219  *
220  * Return 1=output CLEAR
221  */
222 static int
223 bsd_check(struct bsd_db *db)
224 {
225     u_int new_ratio;
226
227     if (db->in_count >= db->checkpoint) {
228         /* age the ratio by limiting the size of the counts */
229         if (db->in_count >= RATIO_MAX
230             || db->bytes_out >= RATIO_MAX) {
231             db->in_count -= db->in_count/4;
232             db->bytes_out -= db->bytes_out/4;
233         }
234
235         db->checkpoint = db->in_count + CHECK_GAP;
236
237         if (db->max_ent >= db->maxmaxcode) {
238             /* Reset the dictionary only if the ratio is worse,
239              * or if it looks as if it has been poisoned
240              * by incompressible data.
241              *
242              * This does not overflow, because
243              *  db->in_count <= RATIO_MAX.
244              */
245             new_ratio = db->in_count << RATIO_SCALE_LOG;
246             if (db->bytes_out != 0)
247                 new_ratio /= db->bytes_out;
248
249             if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE) {
250                 bsd_clear(db);
251                 return 1;
252             }
253             db->ratio = new_ratio;
254         }
255     }
256     return 0;
257 }
258
259 /*
260  * Return statistics.
261  */
262 static void
263 bsd_comp_stats(void *state, struct compstat *stats)
264 {
265     struct bsd_db *db = (struct bsd_db *) state;
266     u_int out;
267
268     stats->unc_bytes = db->uncomp_bytes;
269     stats->unc_packets = db->uncomp_count;
270     stats->comp_bytes = db->comp_bytes;
271     stats->comp_packets = db->comp_count;
272     stats->inc_bytes = db->incomp_bytes;
273     stats->inc_packets = db->incomp_count;
274     stats->ratio = db->in_count;
275     out = db->bytes_out;
276     if (stats->ratio <= 0x7fffff)
277         stats->ratio <<= 8;
278     else
279         out >>= 8;
280     if (out != 0)
281         stats->ratio /= out;
282 }
283
284 /*
285  * Reset state, as on a CCP ResetReq.
286  */
287 static void
288 bsd_reset(void *state)
289 {
290     struct bsd_db *db = (struct bsd_db *) state;
291
292     db->seqno = 0;
293     bsd_clear(db);
294     db->clear_count = 0;
295 }
296
297 /*
298  * Allocate space for a (de) compressor.
299  */
300 static void *
301 bsd_alloc(u_char *options, int opt_len, int decomp)
302 {
303     int bits;
304     u_int newlen, hsize, hshift, maxmaxcode;
305     struct bsd_db *db;
306
307     if (opt_len < CILEN_BSD_COMPRESS || options[0] != CI_BSD_COMPRESS
308         || options[1] != CILEN_BSD_COMPRESS
309         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
310         return NULL;
311     bits = BSD_NBITS(options[2]);
312     switch (bits) {
313     case 9:                     /* needs 82152 for both directions */
314     case 10:                    /* needs 84144 */
315     case 11:                    /* needs 88240 */
316     case 12:                    /* needs 96432 */
317         hsize = 5003;
318         hshift = 4;
319         break;
320     case 13:                    /* needs 176784 */
321         hsize = 9001;
322         hshift = 5;
323         break;
324     case 14:                    /* needs 353744 */
325         hsize = 18013;
326         hshift = 6;
327         break;
328     case 15:                    /* needs 691440 */
329         hsize = 35023;
330         hshift = 7;
331         break;
332     case 16:                    /* needs 1366160--far too much, */
333         /* hsize = 69001; */    /* and 69001 is too big for cptr */
334         /* hshift = 8; */       /* in struct bsd_db */
335         /* break; */
336     default:
337         return NULL;
338     }
339
340     maxmaxcode = MAXCODE(bits);
341     newlen = sizeof(*db) + (hsize-1) * (sizeof(db->dict[0]));
342     db = kmalloc(newlen, M_DEVBUF, M_WAITOK);
343     bzero(db, sizeof(*db) - sizeof(db->dict));
344
345     if (!decomp) {
346         db->lens = NULL;
347     } else {
348         db->lens = kmalloc((maxmaxcode + 1) * sizeof(db->lens[0]), M_DEVBUF,
349                            M_WAITOK);
350     }
351
352     db->totlen = newlen;
353     db->hsize = hsize;
354     db->hshift = hshift;
355     db->maxmaxcode = maxmaxcode;
356     db->maxbits = bits;
357
358     return (void *) db;
359 }
360
361 static void
362 bsd_free(void *state)
363 {
364     struct bsd_db *db = (struct bsd_db *) state;
365
366     if (db->lens)
367         kfree(db->lens, M_DEVBUF);
368     kfree(db, M_DEVBUF);
369 }
370
371 static void *
372 bsd_comp_alloc(u_char *options, int opt_len)
373 {
374     return bsd_alloc(options, opt_len, 0);
375 }
376
377 static void *
378 bsd_decomp_alloc(u_char *options, int opt_len)
379 {
380     return bsd_alloc(options, opt_len, 1);
381 }
382
383 /*
384  * Initialize the database.
385  */
386 static int
387 bsd_init(struct bsd_db *db, u_char *options, int opt_len, int unit,
388     int hdrlen, int mru, int debug, int decomp)
389 {
390     int i;
391
392     if (opt_len < CILEN_BSD_COMPRESS || options[0] != CI_BSD_COMPRESS
393         || options[1] != CILEN_BSD_COMPRESS
394         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION
395         || BSD_NBITS(options[2]) != db->maxbits
396         || (decomp && db->lens == NULL))
397         return 0;
398
399     if (decomp) {
400         i = LAST+1;
401         while (i != 0)
402             db->lens[--i] = 1;
403     }
404     i = db->hsize;
405     while (i != 0) {
406         db->dict[--i].codem1 = BADCODEM1;
407         db->dict[i].cptr = 0;
408     }
409
410     db->unit = unit;
411     db->hdrlen = hdrlen;
412     db->mru = mru;
413 #ifndef DEBUG
414     if (debug)
415 #endif
416         db->debug = 1;
417
418     bsd_reset(db);
419
420     return 1;
421 }
422
423 static int
424 bsd_comp_init(void *state, u_char *options, int opt_len, int unit, 
425     int hdrlen, int debug)
426 {
427     return bsd_init((struct bsd_db *) state, options, opt_len,
428                     unit, hdrlen, 0, debug, 0);
429 }
430
431 static int
432 bsd_decomp_init(void *state, u_char *options, int opt_len, 
433     int unit, int hdrlen, int mru, int debug)
434 {
435         return bsd_init((struct bsd_db *) state, options, opt_len, 
436             unit, hdrlen, mru, debug, 1);
437 }
438
439
440 /*
441  * compress a packet
442  *      One change from the BSD compress command is that when the
443  *      code size expands, we do not output a bunch of padding.
444  *   **mret     - return compressed mbuf chain here
445  *   *mp        - from here
446  *   slen       - uncompressed length
447  *   maxolen    - max compressed length
448  *
449  * return new slen
450  */
451 int
452 bsd_compress(void *state, struct mbuf **mret, struct mbuf *mp, 
453     int slen, int maxolen)
454 {
455     struct bsd_db *db = (struct bsd_db *) state;
456     int hshift = db->hshift;
457     u_int max_ent = db->max_ent;
458     u_int n_bits = db->n_bits;
459     u_int bitno = 32;
460     u_int32_t accm = 0, fcode;
461     struct bsd_dict *dictp;
462     u_char c;
463     int hval, disp, ent, ilen;
464     u_char *rptr, *wptr;
465     u_char *cp_end;
466     int olen;
467     struct mbuf *m;
468
469 #define PUTBYTE(v) {                                    \
470     ++olen;                                             \
471     if (wptr) {                                         \
472         *wptr++ = (v);                                  \
473         if (wptr >= cp_end) {                           \
474             m->m_len = wptr - mtod(m, u_char *);        \
475             MGET(m->m_next, MB_DONTWAIT, MT_DATA);      \
476             m = m->m_next;                              \
477             if (m) {                                    \
478                 m->m_len = 0;                           \
479                 if (maxolen - olen > MLEN)              \
480                     MCLGET(m, MB_DONTWAIT);             \
481                 wptr = mtod(m, u_char *);               \
482                 cp_end = wptr + M_TRAILINGSPACE(m);     \
483             } else                                      \
484                 wptr = NULL;                            \
485         }                                               \
486     }                                                   \
487 }
488
489 #define OUTPUT(ent) {                                   \
490     bitno -= n_bits;                                    \
491     accm |= ((ent) << bitno);                           \
492     do {                                                \
493         PUTBYTE(accm >> 24);                            \
494         accm <<= 8;                                     \
495         bitno += 8;                                     \
496     } while (bitno <= 24);                              \
497 }
498
499     /*
500      * If the protocol is not in the range we're interested in,
501      * just return without compressing the packet.  If it is,
502      * the protocol becomes the first byte to compress.
503      */
504     rptr = mtod(mp, u_char *);
505     ent = PPP_PROTOCOL(rptr);
506     if (ent < 0x21 || ent > 0xf9) {
507         *mret = NULL;
508         return slen;
509     }
510
511     /* Don't generate compressed packets which are larger than
512        the uncompressed packet. */
513     if (maxolen > slen)
514         maxolen = slen;
515
516     /* Allocate one mbuf to start with. */
517     MGET(m, MB_DONTWAIT, MT_DATA);
518     *mret = m;
519     if (m != NULL) {
520         m->m_len = 0;
521         if (maxolen + db->hdrlen > MLEN)
522             MCLGET(m, MB_DONTWAIT);
523         m->m_data += db->hdrlen;
524         wptr = mtod(m, u_char *);
525         cp_end = wptr + M_TRAILINGSPACE(m);
526     } else
527         wptr = cp_end = NULL;
528
529     /*
530      * Copy the PPP header over, changing the protocol,
531      * and install the 2-byte packet sequence number.
532      */
533     if (wptr) {
534         *wptr++ = PPP_ADDRESS(rptr);    /* assumes the ppp header is */
535         *wptr++ = PPP_CONTROL(rptr);    /* all in one mbuf */
536         *wptr++ = 0;                    /* change the protocol */
537         *wptr++ = PPP_COMP;
538         *wptr++ = db->seqno >> 8;
539         *wptr++ = db->seqno;
540     }
541     ++db->seqno;
542
543     olen = 0;
544     rptr += PPP_HDRLEN;
545     slen = mp->m_len - PPP_HDRLEN;
546     ilen = slen + 1;
547     for (;;) {
548         if (slen <= 0) {
549             mp = mp->m_next;
550             if (!mp)
551                 break;
552             rptr = mtod(mp, u_char *);
553             slen = mp->m_len;
554             if (!slen)
555                 continue;   /* handle 0-length buffers */
556             ilen += slen;
557         }
558
559         slen--;
560         c = *rptr++;
561         fcode = BSD_KEY(ent, c);
562         hval = BSD_HASH(ent, c, hshift);
563         dictp = &db->dict[hval];
564
565         /* Validate and then check the entry. */
566         if (dictp->codem1 >= max_ent)
567             goto nomatch;
568         if (dictp->f.fcode == fcode) {
569             ent = dictp->codem1+1;
570             continue;   /* found (prefix,suffix) */
571         }
572
573         /* continue probing until a match or invalid entry */
574         disp = (hval == 0) ? 1 : hval;
575         do {
576             hval += disp;
577             if (hval >= db->hsize)
578                 hval -= db->hsize;
579             dictp = &db->dict[hval];
580             if (dictp->codem1 >= max_ent)
581                 goto nomatch;
582         } while (dictp->f.fcode != fcode);
583         ent = dictp->codem1 + 1;        /* finally found (prefix,suffix) */
584         continue;
585
586     nomatch:
587         OUTPUT(ent);            /* output the prefix */
588
589         /* code -> hashtable */
590         if (max_ent < db->maxmaxcode) {
591             struct bsd_dict *dictp2;
592             /* expand code size if needed */
593             if (max_ent >= MAXCODE(n_bits))
594                 db->n_bits = ++n_bits;
595
596             /* Invalidate old hash table entry using
597              * this code, and then take it over.
598              */
599             dictp2 = &db->dict[max_ent+1];
600             if (db->dict[dictp2->cptr].codem1 == max_ent)
601                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
602             dictp2->cptr = hval;
603             dictp->codem1 = max_ent;
604             dictp->f.fcode = fcode;
605
606             db->max_ent = ++max_ent;
607         }
608         ent = c;
609     }
610
611     OUTPUT(ent);                /* output the last code */
612     db->bytes_out += olen;
613     db->in_count += ilen;
614     if (bitno < 32)
615         ++db->bytes_out;        /* count complete bytes */
616
617     if (bsd_check(db))
618         OUTPUT(CLEAR);          /* do not count the CLEAR */
619
620     /*
621      * Pad dribble bits of last code with ones.
622      * Do not emit a completely useless byte of ones.
623      */
624     if (bitno != 32)
625         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
626
627     if (m != NULL) {
628         m->m_len = wptr - mtod(m, u_char *);
629         m->m_next = NULL;
630     }
631
632     /*
633      * Increase code size if we would have without the packet
634      * boundary and as the decompressor will.
635      */
636     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
637         db->n_bits++;
638
639     db->uncomp_bytes += ilen;
640     ++db->uncomp_count;
641     if (olen + PPP_HDRLEN + BSD_OVHD > maxolen) {
642         /* throw away the compressed stuff if it is longer than uncompressed */
643         if (*mret != NULL) {
644             m_freem(*mret);
645             *mret = NULL;
646         }
647         ++db->incomp_count;
648         db->incomp_bytes += ilen;
649     } else {
650         ++db->comp_count;
651         db->comp_bytes += olen + BSD_OVHD;
652     }
653
654     return olen + PPP_HDRLEN + BSD_OVHD;
655 #undef OUTPUT
656 #undef PUTBYTE
657 }
658
659
660 /*
661  * Update the "BSD Compress" dictionary on the receiver for
662  * incompressible data by pretending to compress the incoming data.
663  */
664 static void
665 bsd_incomp(void *state, struct mbuf *dmsg)
666 {
667     struct bsd_db *db = (struct bsd_db *) state;
668     u_int hshift = db->hshift;
669     u_int max_ent = db->max_ent;
670     u_int n_bits = db->n_bits;
671     struct bsd_dict *dictp;
672     u_int32_t fcode;
673     u_char c;
674     u_int32_t hval, disp;
675     int slen, ilen;
676     u_int bitno = 7;
677     u_char *rptr;
678     u_int ent;
679
680     /*
681      * If the protocol is not in the range we're interested in,
682      * just return without looking at the packet.  If it is,
683      * the protocol becomes the first byte to "compress".
684      */
685     rptr = mtod(dmsg, u_char *);
686     ent = PPP_PROTOCOL(rptr);
687     if (ent < 0x21 || ent > 0xf9)
688         return;
689
690     db->seqno++;
691     ilen = 1;           /* count the protocol as 1 byte */
692     rptr += PPP_HDRLEN;
693     slen = dmsg->m_len - PPP_HDRLEN;
694     for (;;) {
695         if (slen <= 0) {
696             dmsg = dmsg->m_next;
697             if (!dmsg)
698                 break;
699             rptr = mtod(dmsg, u_char *);
700             slen = dmsg->m_len;
701             continue;
702         }
703         ilen += slen;
704
705         do {
706             c = *rptr++;
707             fcode = BSD_KEY(ent, c);
708             hval = BSD_HASH(ent, c, hshift);
709             dictp = &db->dict[hval];
710
711             /* validate and then check the entry */
712             if (dictp->codem1 >= max_ent)
713                 goto nomatch;
714             if (dictp->f.fcode == fcode) {
715                 ent = dictp->codem1+1;
716                 continue;   /* found (prefix,suffix) */
717             }
718
719             /* continue probing until a match or invalid entry */
720             disp = (hval == 0) ? 1 : hval;
721             do {
722                 hval += disp;
723                 if (hval >= db->hsize)
724                     hval -= db->hsize;
725                 dictp = &db->dict[hval];
726                 if (dictp->codem1 >= max_ent)
727                     goto nomatch;
728             } while (dictp->f.fcode != fcode);
729             ent = dictp->codem1+1;
730             continue;   /* finally found (prefix,suffix) */
731
732         nomatch:                /* output (count) the prefix */
733             bitno += n_bits;
734
735             /* code -> hashtable */
736             if (max_ent < db->maxmaxcode) {
737                 struct bsd_dict *dictp2;
738                 /* expand code size if needed */
739                 if (max_ent >= MAXCODE(n_bits))
740                     db->n_bits = ++n_bits;
741
742                 /* Invalidate previous hash table entry
743                  * assigned this code, and then take it over.
744                  */
745                 dictp2 = &db->dict[max_ent+1];
746                 if (db->dict[dictp2->cptr].codem1 == max_ent)
747                     db->dict[dictp2->cptr].codem1 = BADCODEM1;
748                 dictp2->cptr = hval;
749                 dictp->codem1 = max_ent;
750                 dictp->f.fcode = fcode;
751
752                 db->max_ent = ++max_ent;
753                 db->lens[max_ent] = db->lens[ent]+1;
754             }
755             ent = c;
756         } while (--slen != 0);
757     }
758     bitno += n_bits;            /* output (count) the last code */
759     db->bytes_out += bitno/8;
760     db->in_count += ilen;
761     bsd_check(db);
762
763     ++db->incomp_count;
764     db->incomp_bytes += ilen;
765     ++db->uncomp_count;
766     db->uncomp_bytes += ilen;
767
768     /* Increase code size if we would have without the packet
769      * boundary and as the decompressor will.
770      */
771     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
772         db->n_bits++;
773 }
774
775
776 /*
777  * Decompress "BSD Compress".
778  *
779  * Because of patent problems, we return DECOMP_ERROR for errors
780  * found by inspecting the input data and for system problems, but
781  * DECOMP_FATALERROR for any errors which could possibly be said to
782  * be being detected "after" decompression.  For DECOMP_ERROR,
783  * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
784  * infringing a patent of Motorola's if we do, so we take CCP down
785  * instead.
786  *
787  * Given that the frame has the correct sequence number and a good FCS,
788  * errors such as invalid codes in the input most likely indicate a
789  * bug, so we return DECOMP_FATALERROR for them in order to turn off
790  * compression, even though they are detected by inspecting the input.
791  */
792 int
793 bsd_decompress(void *state, struct mbuf *cmp, struct mbuf **dmpp)
794 {
795     struct bsd_db *db = (struct bsd_db *) state;
796     u_int max_ent = db->max_ent;
797     u_int32_t accm = 0;
798     u_int bitno = 32;           /* 1st valid bit in accm */
799     u_int n_bits = db->n_bits;
800     u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
801     struct bsd_dict *dictp;
802     int explen, i, seq, len;
803     u_int incode, oldcode, finchar;
804     u_char *p, *rptr, *wptr;
805     struct mbuf *m, *dmp, *mret;
806     int adrs, ctrl, ilen;
807     int space, codelen, extra;
808
809     /*
810      * Save the address/control from the PPP header
811      * and then get the sequence number.
812      */
813     *dmpp = NULL;
814     rptr = mtod(cmp, u_char *);
815     adrs = PPP_ADDRESS(rptr);
816     ctrl = PPP_CONTROL(rptr);
817     rptr += PPP_HDRLEN;
818     len = cmp->m_len - PPP_HDRLEN;
819     seq = 0;
820     for (i = 0; i < 2; ++i) {
821         while (len <= 0) {
822             cmp = cmp->m_next;
823             if (cmp == NULL)
824                 return DECOMP_ERROR;
825             rptr = mtod(cmp, u_char *);
826             len = cmp->m_len;
827         }
828         seq = (seq << 8) + *rptr++;
829         --len;
830     }
831
832     /*
833      * Check the sequence number and give up if it differs from
834      * the value we're expecting.
835      */
836     if (seq != db->seqno) {
837         if (db->debug)
838             kprintf("bsd_decomp%d: bad sequence # %d, expected %d\n",
839                    db->unit, seq, db->seqno - 1);
840         return DECOMP_ERROR;
841     }
842     ++db->seqno;
843
844     /*
845      * Allocate one mbuf to start with.
846      */
847     MGETHDR(dmp, MB_DONTWAIT, MT_DATA);
848     if (dmp == NULL)
849         return DECOMP_ERROR;
850     mret = dmp;
851     dmp->m_len = 0;
852     dmp->m_next = NULL;
853     MCLGET(dmp, MB_DONTWAIT);
854     dmp->m_data += db->hdrlen;
855     wptr = mtod(dmp, u_char *);
856     space = M_TRAILINGSPACE(dmp) - PPP_HDRLEN + 1;
857
858     /*
859      * Fill in the ppp header, but not the last byte of the protocol
860      * (that comes from the decompressed data).
861      */
862     wptr[0] = adrs;
863     wptr[1] = ctrl;
864     wptr[2] = 0;
865     wptr += PPP_HDRLEN - 1;
866
867     ilen = len;
868     oldcode = CLEAR;
869     explen = 0;
870     for (;;) {
871         if (len == 0) {
872             cmp = cmp->m_next;
873             if (!cmp)           /* quit at end of message */
874                 break;
875             rptr = mtod(cmp, u_char *);
876             len = cmp->m_len;
877             ilen += len;
878             continue;           /* handle 0-length buffers */
879         }
880
881         /*
882          * Accumulate bytes until we have a complete code.
883          * Then get the next code, relying on the 32-bit,
884          * unsigned accm to mask the result.
885          */
886         bitno -= 8;
887         accm |= *rptr++ << bitno;
888         --len;
889         if (tgtbitno < bitno)
890             continue;
891         incode = accm >> tgtbitno;
892         accm <<= n_bits;
893         bitno += n_bits;
894
895         if (incode == CLEAR) {
896             /*
897              * The dictionary must only be cleared at
898              * the end of a packet.  But there could be an
899              * empty mbuf at the end.
900              */
901             if (len > 0 || cmp->m_next != NULL) {
902                 while ((cmp = cmp->m_next) != NULL)
903                     len += cmp->m_len;
904                 if (len > 0) {
905                     m_freem(mret);
906                     if (db->debug)
907                         kprintf("bsd_decomp%d: bad CLEAR\n", db->unit);
908                     return DECOMP_FATALERROR;   /* probably a bug */
909                 }
910             }
911             bsd_clear(db);
912             explen = ilen = 0;
913             break;
914         }
915
916         if (incode > max_ent + 2 || incode > db->maxmaxcode
917             || (incode > max_ent && oldcode == CLEAR)) {
918             m_freem(mret);
919             if (db->debug) {
920                 kprintf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
921                        db->unit, incode, oldcode);
922                 kprintf("max_ent=0x%x explen=%d seqno=%d\n",
923                        max_ent, explen, db->seqno);
924             }
925             return DECOMP_FATALERROR;   /* probably a bug */
926         }
927
928         /* Special case for KwKwK string. */
929         if (incode > max_ent) {
930             finchar = oldcode;
931             extra = 1;
932         } else {
933             finchar = incode;
934             extra = 0;
935         }
936
937         codelen = db->lens[finchar];
938         explen += codelen + extra;
939         if (explen > db->mru + 1) {
940             m_freem(mret);
941             if (db->debug) {
942                 kprintf("bsd_decomp%d: ran out of mru\n", db->unit);
943 #ifdef DEBUG
944                 while ((cmp = cmp->m_next) != NULL)
945                     len += cmp->m_len;
946                 kprintf("  len=%d, finchar=0x%x, codelen=%d, explen=%d\n",
947                        len, finchar, codelen, explen);
948 #endif
949             }
950             return DECOMP_FATALERROR;
951         }
952
953         /*
954          * For simplicity, the decoded characters go in a single mbuf,
955          * so we allocate a single extra cluster mbuf if necessary.
956          */
957         if ((space -= codelen + extra) < 0) {
958             dmp->m_len = wptr - mtod(dmp, u_char *);
959             MGET(m, MB_DONTWAIT, MT_DATA);
960             if (m == NULL) {
961                 m_freem(mret);
962                 return DECOMP_ERROR;
963             }
964             m->m_len = 0;
965             m->m_next = NULL;
966             dmp->m_next = m;
967             MCLGET(m, MB_DONTWAIT);
968             space = M_TRAILINGSPACE(m) - (codelen + extra);
969             if (space < 0) {
970                 /* now that's what I call *compression*. */
971                 m_freem(mret);
972                 return DECOMP_ERROR;
973             }
974             dmp = m;
975             wptr = mtod(dmp, u_char *);
976         }
977
978         /*
979          * Decode this code and install it in the decompressed buffer.
980          */
981         p = (wptr += codelen);
982         while (finchar > LAST) {
983             dictp = &db->dict[db->dict[finchar].cptr];
984 #ifdef DEBUG
985             if (--codelen <= 0 || dictp->codem1 != finchar-1)
986                 goto bad;
987 #endif
988             *--p = dictp->f.hs.suffix;
989             finchar = dictp->f.hs.prefix;
990         }
991         *--p = finchar;
992
993 #ifdef DEBUG
994         if (--codelen != 0)
995             kprintf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
996                    db->unit, codelen, incode, max_ent);
997 #endif
998
999         if (extra)              /* the KwKwK case again */
1000             *wptr++ = finchar;
1001
1002         /*
1003          * If not first code in a packet, and
1004          * if not out of code space, then allocate a new code.
1005          *
1006          * Keep the hash table correct so it can be used
1007          * with uncompressed packets.
1008          */
1009         if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
1010             struct bsd_dict *dictp2;
1011             u_int32_t fcode;
1012             u_int32_t hval, disp;
1013
1014             fcode = BSD_KEY(oldcode,finchar);
1015             hval = BSD_HASH(oldcode,finchar,db->hshift);
1016             dictp = &db->dict[hval];
1017
1018             /* look for a free hash table entry */
1019             if (dictp->codem1 < max_ent) {
1020                 disp = (hval == 0) ? 1 : hval;
1021                 do {
1022                     hval += disp;
1023                     if (hval >= db->hsize)
1024                         hval -= db->hsize;
1025                     dictp = &db->dict[hval];
1026                 } while (dictp->codem1 < max_ent);
1027             }
1028
1029             /*
1030              * Invalidate previous hash table entry
1031              * assigned this code, and then take it over
1032              */
1033             dictp2 = &db->dict[max_ent+1];
1034             if (db->dict[dictp2->cptr].codem1 == max_ent) {
1035                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
1036             }
1037             dictp2->cptr = hval;
1038             dictp->codem1 = max_ent;
1039             dictp->f.fcode = fcode;
1040
1041             db->max_ent = ++max_ent;
1042             db->lens[max_ent] = db->lens[oldcode]+1;
1043
1044             /* Expand code size if needed. */
1045             if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
1046                 db->n_bits = ++n_bits;
1047                 tgtbitno = 32-n_bits;
1048             }
1049         }
1050         oldcode = incode;
1051     }
1052     dmp->m_len = wptr - mtod(dmp, u_char *);
1053
1054     /*
1055      * Keep the checkpoint right so that incompressible packets
1056      * clear the dictionary at the right times.
1057      */
1058     db->bytes_out += ilen;
1059     db->in_count += explen;
1060     if (bsd_check(db) && db->debug) {
1061         kprintf("bsd_decomp%d: peer should have cleared dictionary\n",
1062                db->unit);
1063     }
1064
1065     ++db->comp_count;
1066     db->comp_bytes += ilen + BSD_OVHD;
1067     ++db->uncomp_count;
1068     db->uncomp_bytes += explen;
1069
1070     *dmpp = mret;
1071     return DECOMP_OK;
1072
1073 #ifdef DEBUG
1074  bad:
1075     if (codelen <= 0) {
1076         kprintf("bsd_decomp%d: fell off end of chain ", db->unit);
1077         kprintf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
1078                incode, finchar, db->dict[finchar].cptr, max_ent);
1079     } else if (dictp->codem1 != finchar-1) {
1080         kprintf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
1081                db->unit, incode, finchar);
1082         kprintf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
1083                db->dict[finchar].cptr, dictp->codem1);
1084     }
1085     m_freem(mret);
1086     return DECOMP_FATALERROR;
1087 #endif /* DEBUG */
1088 }
1089 #endif /* DO_BSD_COMPRESS */