source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ 0e16fa45

5
Last change on this file since 0e16fa45 was cb68253, checked in by Sebastian Huber <sebastian.huber@…>, on 09/07/18 at 04:19:02

network: Use kernel/user space header files

Add and use <machine/rtems-bsd-kernel-space.h> and
<machine/rtems-bsd-user-space.h> similar to the libbsd to avoid command
line defines and defines scattered throught the code base.

Simplify cpukit/libnetworking/Makefile.am.

Update #3375.

  • Property mode set to 100644
File size: 60.2 KB
Line 
1#include <machine/rtems-bsd-kernel-space.h>
2
3/*
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
5 *      The Regents of the University of California.  All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
32 */
33
34#ifdef HAVE_CONFIG_H
35#include "config.h"
36#endif
37
38#include "opt_tcpdebug.h"
39
40#ifndef TUBA_INCLUDE
41#include <sys/param.h>
42#include <sys/queue.h>
43#include <sys/systm.h>
44#include <sys/kernel.h>
45#include <sys/sysctl.h>
46#include <sys/malloc.h>
47#include <sys/mbuf.h>
48#include <sys/protosw.h>
49#include <sys/socket.h>
50#include <sys/socketvar.h>
51#include <errno.h>
52#include <sys/syslog.h>
53
54#include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
55
56#include <net/if.h>
57#include <net/if_var.h>
58#include <net/route.h>
59
60#include <netinet/in.h>
61#include <rtems/rtems_netinet_in.h>
62#include <netinet/in_systm.h>
63#include <netinet/ip.h>
64#include <netinet/in_pcb.h>
65#include <netinet/ip_var.h>
66#include <netinet/tcp.h>
67#include <netinet/tcp_fsm.h>
68#include <netinet/tcp_seq.h>
69#include <netinet/tcp_timer.h>
70#include <netinet/tcp_var.h>
71#include <netinet/tcpip.h>
72#ifdef TCPDEBUG
73#include <netinet/tcp_debug.h>
74static struct   tcpiphdr tcp_saveti;
75#endif
76
77static int      tcprexmtthresh = 3;
78tcp_seq tcp_iss;
79tcp_cc  tcp_ccgen;
80
81struct  tcpstat tcpstat;
82SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats,
83        CTLFLAG_RD, &tcpstat , tcpstat, "");
84
85static int log_in_vain = 0;
86SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
87        &log_in_vain, 0, "");
88
89u_long  tcp_now;
90struct inpcbhead tcb;
91struct inpcbinfo tcbinfo;
92
93static void      tcp_dooptions(struct tcpcb *,
94            u_char *, int, struct tcpiphdr *, struct tcpopt *);
95static void      tcp_pulloutofband(struct socket *,
96            struct tcpiphdr *, struct mbuf *);
97static int       tcp_reass(struct tcpcb *, struct tcpiphdr *, struct mbuf *);
98static void      tcp_xmit_timer(struct tcpcb *, int);
99
100#endif /* TUBA_INCLUDE */
101
102/*
103 * Insert segment ti into reassembly queue of tcp with
104 * control block tp.  Return TH_FIN if reassembly now includes
105 * a segment with FIN.  The macro form does the common case inline
106 * (segment is the next to be received on an established connection,
107 * and the queue is empty), avoiding linkage into and removal
108 * from the queue and repetition of various conversions.
109 * Set DELACK for segments received in order, but ack immediately
110 * when segments are out of order (so fast retransmit can work).
111 */
112#ifdef TCP_ACK_HACK
113#define TCP_REASS(tp, ti, m, so, flags) { \
114        if ((ti)->ti_seq == (tp)->rcv_nxt && \
115            (tp)->seg_next == (struct tcpiphdr *)(tp) && \
116            (tp)->t_state == TCPS_ESTABLISHED) { \
117                if (ti->ti_flags & TH_PUSH) \
118                        tp->t_flags |= TF_ACKNOW; \
119                else \
120                        tp->t_flags |= TF_DELACK; \
121                (tp)->rcv_nxt += (ti)->ti_len; \
122                flags = (ti)->ti_flags & TH_FIN; \
123                tcpstat.tcps_rcvpack++;\
124                tcpstat.tcps_rcvbyte += (ti)->ti_len;\
125                sbappend(&(so)->so_rcv, (m)); \
126                sorwakeup(so); \
127        } else { \
128                (flags) = tcp_reass((tp), (ti), (m)); \
129                tp->t_flags |= TF_ACKNOW; \
130        } \
131}
132#else
133#define TCP_REASS(tp, ti, m, so, flags) { \
134        if ((ti)->ti_seq == (tp)->rcv_nxt && \
135            (tp)->seg_next == (struct tcpiphdr *)(tp) && \
136            (tp)->t_state == TCPS_ESTABLISHED) { \
137                tp->t_flags |= TF_DELACK; \
138                (tp)->rcv_nxt += (ti)->ti_len; \
139                flags = (ti)->ti_flags & TH_FIN; \
140                tcpstat.tcps_rcvpack++;\
141                tcpstat.tcps_rcvbyte += (ti)->ti_len;\
142                sbappend(&(so)->so_rcv, (m)); \
143                sorwakeup(so); \
144        } else { \
145                (flags) = tcp_reass((tp), (ti), (m)); \
146                tp->t_flags |= TF_ACKNOW; \
147        } \
148}
149#endif
150#ifndef TUBA_INCLUDE
151
152static int
153tcp_reass(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m)
154{
155        register struct tcpiphdr *q;
156        struct socket *so = tp->t_inpcb->inp_socket;
157        int flags;
158        /*
159         * Call with ti==0 after become established to
160         * force pre-ESTABLISHED data up to user socket.
161         */
162        if (ti == 0)
163                goto present;
164
165        /*
166         * Find a segment which begins after this one does.
167         */
168        for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
169            q = (struct tcpiphdr *)q->ti_next)
170                if (SEQ_GT(q->ti_seq, ti->ti_seq))
171                        break;
172
173        /*
174         * If there is a preceding segment, it may provide some of
175         * our data already.  If so, drop the data from the incoming
176         * segment.  If it provides all of our data, drop us.
177         */
178        if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
179                register int i;
180                q = (struct tcpiphdr *)q->ti_prev;
181                /* conversion to int (in i) handles seq wraparound */
182                i = q->ti_seq + q->ti_len - ti->ti_seq;
183                if (i > 0) {
184                        if (i >= ti->ti_len) {
185                                tcpstat.tcps_rcvduppack++;
186                                tcpstat.tcps_rcvdupbyte += ti->ti_len;
187                                m_freem(m);
188                                /*
189                                 * Try to present any queued data
190                                 * at the left window edge to the user.
191                                 * This is needed after the 3-WHS
192                                 * completes.
193                                 */
194                                goto present;   /* ??? */
195                        }
196                        m_adj(m, i);
197                        ti->ti_len -= i;
198                        ti->ti_seq += i;
199                }
200                q = (struct tcpiphdr *)(q->ti_next);
201        }
202        tcpstat.tcps_rcvoopack++;
203        tcpstat.tcps_rcvoobyte += ti->ti_len;
204#if (defined(__GNUC__) && (defined(__arm__) || defined(__mips__)))
205    STR32_UNALGN(ti,m);
206#else
207        REASS_MBUF(ti) = m;             /* XXX */
208#endif
209        /*
210         * While we overlap succeeding segments trim them or,
211         * if they are completely covered, dequeue them.
212         */
213        while (q != (struct tcpiphdr *)tp) {
214                register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
215                if (i <= 0)
216                        break;
217                if (i < q->ti_len) {
218                        q->ti_seq += i;
219                        q->ti_len -= i;
220#if (defined(__GNUC__) && (defined(__arm__) || defined(__mips__)))
221            LD32_UNALGN(q,m);
222            m_adj(m, i);
223#else
224                        m_adj(REASS_MBUF(q), i);
225#endif
226                        break;
227                }
228                q = (struct tcpiphdr *)q->ti_next;
229#if (defined(__GNUC__) && (defined(__arm__) || defined(__mips__)))
230        LD32_UNALGN((struct tcpiphdr *)q->ti_prev,m);
231#else
232                m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
233#endif
234                remque(q->ti_prev);
235        m_freem(m);
236        }
237
238        /*
239         * Stick new segment in its place.
240         */
241        insque(ti, q->ti_prev);
242
243present:
244        /*
245         * Present data to user, advancing rcv_nxt through
246         * completed sequence space.
247         */
248        if (!TCPS_HAVEESTABLISHED(tp->t_state))
249                return (0);
250        ti = tp->seg_next;
251        if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
252                return (0);
253        do {
254                tp->rcv_nxt += ti->ti_len;
255                flags = ti->ti_flags & TH_FIN;
256                remque(ti);
257#if (defined(__GNUC__) && (defined(__arm__) || defined(__mips__)))
258        LD32_UNALGN(ti,m);
259#else
260                m = REASS_MBUF(ti);
261#endif
262                ti = (struct tcpiphdr *)ti->ti_next;
263                if (so->so_state & SS_CANTRCVMORE)
264                        m_freem(m);
265                else
266                        sbappend(&so->so_rcv, m);
267        } while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
268        sorwakeup(so);
269        return (flags);
270}
271
272/*
273 * TCP input routine, follows pages 65-76 of the
274 * protocol specification dated September, 1981 very closely.
275 */
276void
277tcp_input(struct mbuf *m, int iphlen)
278{
279        register struct tcpiphdr *ti;
280        register struct inpcb *inp;
281        u_char *optp = NULL;
282        int optlen = 0;
283        int len, tlen, off;
284        register struct tcpcb *tp = 0;
285        register int tiflags;
286        struct socket *so = 0;
287        int todrop, acked, ourfinisacked, needoutput = 0;
288        struct in_addr laddr;
289        int dropsocket = 0;
290        int iss = 0;
291        u_long tiwin;
292        struct tcpopt to;               /* options in this segment */
293        struct rmxp_tao *taop;          /* pointer to our TAO cache entry */
294        struct rmxp_tao tao_noncached;  /* in case there's no cached entry */
295#ifdef TCPDEBUG
296        short ostate = 0;
297#endif
298
299        bzero((char *)&to, sizeof(to));
300
301        tcpstat.tcps_rcvtotal++;
302        /*
303         * Get IP and TCP header together in first mbuf.
304         * Note: IP leaves IP header in first mbuf.
305         */
306        ti = mtod(m, struct tcpiphdr *);
307        if (iphlen > sizeof (struct ip))
308                ip_stripoptions(m, (struct mbuf *)0);
309        if (m->m_len < sizeof (struct tcpiphdr)) {
310                if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
311                        tcpstat.tcps_rcvshort++;
312                        return;
313                }
314                ti = mtod(m, struct tcpiphdr *);
315        }
316
317        /*
318         * Checksum extended TCP header and data.
319         */
320        tlen = ((struct ip *)ti)->ip_len;
321        len = sizeof (struct ip) + tlen;
322        ti->ti_next = ti->ti_prev = 0;
323        ti->ti_x1 = 0;
324        ti->ti_len = (u_short)tlen;
325        HTONS(ti->ti_len);
326        ti->ti_sum = in_cksum(m, len);
327        if (ti->ti_sum) {
328                tcpstat.tcps_rcvbadsum++;
329                goto drop;
330        }
331#endif /* TUBA_INCLUDE */
332
333        /*
334         * Check that TCP offset makes sense,
335         * pull out TCP options and adjust length.              XXX
336         */
337        off = ti->ti_off << 2;
338        if (off < sizeof (struct tcphdr) || off > tlen) {
339                tcpstat.tcps_rcvbadoff++;
340                goto drop;
341        }
342        tlen -= off;
343        ti->ti_len = tlen;
344        if (off > sizeof (struct tcphdr)) {
345                if (m->m_len < sizeof(struct ip) + off) {
346                        if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
347                                tcpstat.tcps_rcvshort++;
348                                return;
349                        }
350                        ti = mtod(m, struct tcpiphdr *);
351                }
352                optlen = off - sizeof (struct tcphdr);
353                optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
354        }
355        tiflags = ti->ti_flags;
356
357        /*
358         * Convert TCP protocol specific fields to host format.
359         */
360        NTOHL(ti->ti_seq);
361        NTOHL(ti->ti_ack);
362        NTOHS(ti->ti_win);
363        NTOHS(ti->ti_urp);
364
365        /*
366         * Drop TCP, IP headers and TCP options.
367         */
368        m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
369        m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
370
371        /*
372         * Locate pcb for segment.
373         */
374findpcb:
375        inp = in_pcblookuphash(&tcbinfo, ti->ti_src, ti->ti_sport,
376            ti->ti_dst, ti->ti_dport, 1);
377
378        /*
379         * If the state is CLOSED (i.e., TCB does not exist) then
380         * all data in the incoming segment is discarded.
381         * If the TCB exists but is in CLOSED state, it is embryonic,
382         * but should either do a listen or a connect soon.
383         */
384        if (inp == NULL) {
385                if (log_in_vain && tiflags & TH_SYN) {
386                        char buf0[INET_ADDRSTRLEN];
387                        char buf1[INET_ADDRSTRLEN];
388
389                        log(LOG_INFO, "Connection attempt to TCP %s:%d"
390                            " from %s:%d\n",
391                            inet_ntoa_r(ti->ti_dst, buf0), ntohs(ti->ti_dport),
392                            inet_ntoa_r(ti->ti_src, buf1), ntohs(ti->ti_sport));
393                }
394                goto dropwithreset;
395        }
396        tp = intotcpcb(inp);
397        if (tp == 0)
398                goto dropwithreset;
399        if (tp->t_state == TCPS_CLOSED)
400                goto drop;
401
402        /* Unscale the window into a 32-bit value. */
403        if ((tiflags & TH_SYN) == 0)
404                tiwin = ti->ti_win << tp->snd_scale;
405        else
406                tiwin = ti->ti_win;
407
408        so = inp->inp_socket;
409        if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
410#ifdef TCPDEBUG
411                if (so->so_options & SO_DEBUG) {
412                        ostate = tp->t_state;
413                        tcp_saveti = *ti;
414                }
415#endif
416                if (so->so_options & SO_ACCEPTCONN) {
417                        register struct tcpcb *tp0 = tp;
418                        struct socket *so2;
419                        if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
420                                /*
421                                 * Note: dropwithreset makes sure we don't
422                                 * send a RST in response to a RST.
423                                 */
424                                if (tiflags & TH_ACK) {
425                                        tcpstat.tcps_badsyn++;
426                                        goto dropwithreset;
427                                }
428                                goto drop;
429                        }
430                        so2 = sonewconn(so, 0);
431                        if (so2 == 0) {
432                                tcpstat.tcps_listendrop++;
433                                so2 = sodropablereq(so);
434                                if (so2) {
435                                        tcp_drop(sototcpcb(so2), ETIMEDOUT);
436                                        so2 = sonewconn(so, 0);
437                                }
438                                if (!so2)
439                                        goto drop;
440                        }
441                        so = so2;
442                        /*
443                         * This is ugly, but ....
444                         *
445                         * Mark socket as temporary until we're
446                         * committed to keeping it.  The code at
447                         * ``drop'' and ``dropwithreset'' check the
448                         * flag dropsocket to see if the temporary
449                         * socket created here should be discarded.
450                         * We mark the socket as discardable until
451                         * we're committed to it below in TCPS_LISTEN.
452                         */
453                        dropsocket++;
454                        inp = (struct inpcb *)so->so_pcb;
455                        inp->inp_laddr = ti->ti_dst;
456                        inp->inp_lport = ti->ti_dport;
457                        in_pcbrehash(inp);
458#if BSD>=43
459                        inp->inp_options = ip_srcroute();
460#endif
461                        tp = intotcpcb(inp);
462                        tp->t_state = TCPS_LISTEN;
463                        tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
464
465                        /* Compute proper scaling value from buffer space */
466                        while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
467                           TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
468                                tp->request_r_scale++;
469                }
470        }
471
472        /*
473         * Segment received on connection.
474         * Reset idle time and keep-alive timer.
475         */
476        tp->t_idle = 0;
477        if (TCPS_HAVEESTABLISHED(tp->t_state))
478                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
479
480        /*
481         * Process options if not in LISTEN state,
482         * else do it below (after getting remote address).
483         */
484        if (tp->t_state != TCPS_LISTEN)
485                tcp_dooptions(tp, optp, optlen, ti, &to);
486
487        /*
488         * Header prediction: check for the two common cases
489         * of a uni-directional data xfer.  If the packet has
490         * no control flags, is in-sequence, the window didn't
491         * change and we're not retransmitting, it's a
492         * candidate.  If the length is zero and the ack moved
493         * forward, we're the sender side of the xfer.  Just
494         * free the data acked & wake any higher level process
495         * that was blocked waiting for space.  If the length
496         * is non-zero and the ack didn't move, we're the
497         * receiver side.  If we're getting packets in-order
498         * (the reassembly queue is empty), add the data to
499         * the socket buffer and note that we need a delayed ack.
500         * Make sure that the hidden state-flags are also off.
501         * Since we check for TCPS_ESTABLISHED above, it can only
502         * be TH_NEEDSYN.
503         */
504        if (tp->t_state == TCPS_ESTABLISHED &&
505            (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
506            ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
507            ((to.to_flags & TOF_TS) == 0 ||
508             TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
509            /*
510             * Using the CC option is compulsory if once started:
511             *   the segment is OK if no T/TCP was negotiated or
512             *   if the segment has a CC option equal to CCrecv
513             */
514            ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
515             ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
516            ti->ti_seq == tp->rcv_nxt &&
517            tiwin && tiwin == tp->snd_wnd &&
518            tp->snd_nxt == tp->snd_max) {
519
520                /*
521                 * If last ACK falls within this segment's sequence numbers,
522                 * record the timestamp.
523                 * NOTE that the test is modified according to the latest
524                 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
525                 */
526                if ((to.to_flags & TOF_TS) != 0 &&
527                   SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
528                        tp->ts_recent_age = tcp_now;
529                        tp->ts_recent = to.to_tsval;
530                }
531
532                if (ti->ti_len == 0) {
533                        if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
534                            SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
535                            tp->snd_cwnd >= tp->snd_wnd &&
536                            tp->t_dupacks < tcprexmtthresh) {
537                                /*
538                                 * this is a pure ack for outstanding data.
539                                 */
540                                ++tcpstat.tcps_predack;
541                                if ((to.to_flags & TOF_TS) != 0)
542                                        tcp_xmit_timer(tp,
543                                            tcp_now - to.to_tsecr + 1);
544                                else if (tp->t_rtt &&
545                                            SEQ_GT(ti->ti_ack, tp->t_rtseq))
546                                        tcp_xmit_timer(tp, tp->t_rtt);
547                                acked = ti->ti_ack - tp->snd_una;
548                                tcpstat.tcps_rcvackpack++;
549                                tcpstat.tcps_rcvackbyte += acked;
550                                sbdrop(&so->so_snd, acked);
551                                tp->snd_una = ti->ti_ack;
552                                m_freem(m);
553
554                                /*
555                                 * If all outstanding data are acked, stop
556                                 * retransmit timer, otherwise restart timer
557                                 * using current (possibly backed-off) value.
558                                 * If process is waiting for space,
559                                 * wakeup/selwakeup/signal.  If data
560                                 * are ready to send, let tcp_output
561                                 * decide between more output or persist.
562                                 */
563                                if (tp->snd_una == tp->snd_max)
564                                        tp->t_timer[TCPT_REXMT] = 0;
565                                else if (tp->t_timer[TCPT_PERSIST] == 0)
566                                        tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
567
568                                if (so->so_snd.sb_flags & SB_NOTIFY)
569                                        sowwakeup(so);
570                                if (so->so_snd.sb_cc)
571                                        (void) tcp_output(tp);
572                                return;
573                        }
574                } else if (ti->ti_ack == tp->snd_una &&
575                    tp->seg_next == (struct tcpiphdr *)tp &&
576                    ti->ti_len <= sbspace(&so->so_rcv)) {
577                        /*
578                         * this is a pure, in-sequence data packet
579                         * with nothing on the reassembly queue and
580                         * we have enough buffer space to take it.
581                         */
582                        ++tcpstat.tcps_preddat;
583                        tp->rcv_nxt += ti->ti_len;
584                        tcpstat.tcps_rcvpack++;
585                        tcpstat.tcps_rcvbyte += ti->ti_len;
586                        /*
587                         * Add data to socket buffer.
588                         */
589                        sbappend(&so->so_rcv, m);
590                        sorwakeup(so);
591#ifdef TCP_ACK_HACK
592                        /*
593                         * If this is a short packet, then ACK now - with Nagel
594                         *      congestion avoidance sender won't send more until
595                         *      he gets an ACK.
596                         */
597                        if (tiflags & TH_PUSH) {
598                                tp->t_flags |= TF_ACKNOW;
599                                tcp_output(tp);
600                        } else {
601                                tp->t_flags |= TF_DELACK;
602                        }
603#else
604                        tp->t_flags |= TF_DELACK;
605#endif
606                        return;
607                }
608        }
609
610        /*
611         * Calculate amount of space in receive window,
612         * and then do TCP input processing.
613         * Receive window is amount of space in rcv queue,
614         * but not less than advertised window.
615         */
616        { int win;
617
618        win = sbspace(&so->so_rcv);
619        if (win < 0)
620                win = 0;
621        tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
622        }
623
624        switch (tp->t_state) {
625
626        /*
627         * If the state is LISTEN then ignore segment if it contains an RST.
628         * If the segment contains an ACK then it is bad and send a RST.
629         * If it does not contain a SYN then it is not interesting; drop it.
630         * If it is from this socket, drop it, it must be forged.
631         * Don't bother responding if the destination was a broadcast.
632         * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
633         * tp->iss, and send a segment:
634         *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
635         * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
636         * Fill in remote peer address fields if not previously specified.
637         * Enter SYN_RECEIVED state, and process any other fields of this
638         * segment in this state.
639         */
640        case TCPS_LISTEN: {
641                struct mbuf *am;
642                register struct sockaddr_in *sin;
643
644                if (tiflags & TH_RST)
645                        goto drop;
646                if (tiflags & TH_ACK)
647                        goto dropwithreset;
648                if ((tiflags & TH_SYN) == 0)
649                        goto drop;
650                if ((ti->ti_dport == ti->ti_sport) &&
651                    (ti->ti_dst.s_addr == ti->ti_src.s_addr))
652                        goto drop;
653                /*
654                 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
655                 * in_broadcast() should never return true on a received
656                 * packet with M_BCAST not set.
657                 */
658                if (m->m_flags & (M_BCAST|M_MCAST) ||
659                    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
660                        goto drop;
661                am = m_get(M_DONTWAIT, MT_SONAME);      /* XXX */
662                if (am == NULL)
663                        goto drop;
664                am->m_len = sizeof (struct sockaddr_in);
665                sin = mtod(am, struct sockaddr_in *);
666                sin->sin_family = AF_INET;
667                sin->sin_len = sizeof(*sin);
668                sin->sin_addr = ti->ti_src;
669                sin->sin_port = ti->ti_sport;
670                bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
671                laddr = inp->inp_laddr;
672                if (inp->inp_laddr.s_addr == INADDR_ANY)
673                        inp->inp_laddr = ti->ti_dst;
674                if (in_pcbconnect(inp, am)) {
675                        inp->inp_laddr = laddr;
676                        (void) m_free(am);
677                        goto drop;
678                }
679                (void) m_free(am);
680                tp->t_template = tcp_template(tp);
681                if (tp->t_template == 0) {
682                        tp = tcp_drop(tp, ENOBUFS);
683                        dropsocket = 0;         /* socket is already gone */
684                        goto drop;
685                }
686                if ((taop = tcp_gettaocache(inp)) == NULL) {
687                        taop = &tao_noncached;
688                        bzero(taop, sizeof(*taop));
689                }
690                tcp_dooptions(tp, optp, optlen, ti, &to);
691                if (iss)
692                        tp->iss = iss;
693                else
694                        tp->iss = tcp_iss;
695                tcp_iss += TCP_ISSINCR/4;
696                tp->irs = ti->ti_seq;
697                tcp_sendseqinit(tp);
698                tcp_rcvseqinit(tp);
699                /*
700                 * Initialization of the tcpcb for transaction;
701                 *   set SND.WND = SEG.WND,
702                 *   initialize CCsend and CCrecv.
703                 */
704                tp->snd_wnd = tiwin;    /* initial send-window */
705                tp->cc_send = CC_INC(tcp_ccgen);
706                tp->cc_recv = to.to_cc;
707                /*
708                 * Perform TAO test on incoming CC (SEG.CC) option, if any.
709                 * - compare SEG.CC against cached CC from the same host,
710                 *      if any.
711                 * - if SEG.CC > chached value, SYN must be new and is accepted
712                 *      immediately: save new CC in the cache, mark the socket
713                 *      connected, enter ESTABLISHED state, turn on flag to
714                 *      send a SYN in the next segment.
715                 *      A virtual advertised window is set in rcv_adv to
716                 *      initialize SWS prevention.  Then enter normal segment
717                 *      processing: drop SYN, process data and FIN.
718                 * - otherwise do a normal 3-way handshake.
719                 */
720                if ((to.to_flags & TOF_CC) != 0) {
721                    if (taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
722                        taop->tao_cc = to.to_cc;
723                        tp->t_state = TCPS_ESTABLISHED;
724
725                        /*
726                         * If there is a FIN, or if there is data and the
727                         * connection is local, then delay SYN,ACK(SYN) in
728                         * the hope of piggy-backing it on a response
729                         * segment.  Otherwise must send ACK now in case
730                         * the other side is slow starting.
731                         */
732                        if ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
733                            in_localaddr(inp->inp_faddr)))
734                                tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
735                        else
736                                tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
737
738                        /*
739                         * Limit the `virtual advertised window' to TCP_MAXWIN
740                         * here.  Even if we requested window scaling, it will
741                         * become effective only later when our SYN is acked.
742                         */
743                        tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
744                        tcpstat.tcps_connects++;
745                        soisconnected(so);
746                        tp->t_timer[TCPT_KEEP] = tcp_keepinit;
747                        dropsocket = 0;         /* committed to socket */
748                        tcpstat.tcps_accepts++;
749                        goto trimthenstep6;
750                    }
751                /* else do standard 3-way handshake */
752                } else {
753                    /*
754                     * No CC option, but maybe CC.NEW:
755                     *   invalidate cached value.
756                     */
757                     taop->tao_cc = 0;
758                }
759                /*
760                 * TAO test failed or there was no CC option,
761                 *    do a standard 3-way handshake.
762                 */
763                tp->t_flags |= TF_ACKNOW;
764                tp->t_state = TCPS_SYN_RECEIVED;
765                tp->t_timer[TCPT_KEEP] = tcp_keepinit;
766                dropsocket = 0;         /* committed to socket */
767                tcpstat.tcps_accepts++;
768                goto trimthenstep6;
769                }
770
771        /*
772         * If the state is SYN_RECEIVED:
773         *      if seg contains SYN/ACK, send a RST.
774         *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
775         */
776        case TCPS_SYN_RECEIVED:
777                if (tiflags & TH_ACK) {
778                        if (tiflags & TH_SYN) {
779                                tcpstat.tcps_badsyn++;
780                                goto dropwithreset;
781                        }
782                        if (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
783                            SEQ_GT(ti->ti_ack, tp->snd_max))
784                                goto dropwithreset;
785                }
786                break;
787
788        /*
789         * If the state is SYN_SENT:
790         *      if seg contains an ACK, but not for our SYN, drop the input.
791         *      if seg contains a RST, then drop the connection.
792         *      if seg does not contain SYN, then drop it.
793         * Otherwise this is an acceptable SYN segment
794         *      initialize tp->rcv_nxt and tp->irs
795         *      if seg contains ack then advance tp->snd_una
796         *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
797         *      arrange for segment to be acked (eventually)
798         *      continue processing rest of data/controls, beginning with URG
799         */
800        case TCPS_SYN_SENT:
801                if ((taop = tcp_gettaocache(inp)) == NULL) {
802                        taop = &tao_noncached;
803                        bzero(taop, sizeof(*taop));
804                }
805
806                if ((tiflags & TH_ACK) &&
807                    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
808                     SEQ_GT(ti->ti_ack, tp->snd_max))) {
809                        /*
810                         * If we have a cached CCsent for the remote host,
811                         * hence we haven't just crashed and restarted,
812                         * do not send a RST.  This may be a retransmission
813                         * from the other side after our earlier ACK was lost.
814                         * Our new SYN, when it arrives, will serve as the
815                         * needed ACK.
816                         */
817                        if (taop->tao_ccsent != 0)
818                                goto drop;
819                        else
820                                goto dropwithreset;
821                }
822                if (tiflags & TH_RST) {
823                        if (tiflags & TH_ACK)
824                                tp = tcp_drop(tp, ECONNREFUSED);
825                        goto drop;
826                }
827                if ((tiflags & TH_SYN) == 0)
828                        goto drop;
829                tp->snd_wnd = ti->ti_win;       /* initial send window */
830                tp->cc_recv = to.to_cc;         /* foreign CC */
831
832                tp->irs = ti->ti_seq;
833                tcp_rcvseqinit(tp);
834                if (tiflags & TH_ACK) {
835                        /*
836                         * Our SYN was acked.  If segment contains CC.ECHO
837                         * option, check it to make sure this segment really
838                         * matches our SYN.  If not, just drop it as old
839                         * duplicate, but send an RST if we're still playing
840                         * by the old rules.  If no CC.ECHO option, make sure
841                         * we don't get fooled into using T/TCP.
842                         */
843                        if (to.to_flags & TOF_CCECHO) {
844                                if (tp->cc_send != to.to_ccecho) {
845                                        if (taop->tao_ccsent != 0)
846                                                goto drop;
847                                        else
848                                                goto dropwithreset;
849                                }
850                        } else
851                                tp->t_flags &= ~TF_RCVD_CC;
852                        tcpstat.tcps_connects++;
853                        soisconnected(so);
854                        /* Do window scaling on this connection? */
855                        if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
856                                (TF_RCVD_SCALE|TF_REQ_SCALE)) {
857                                tp->snd_scale = tp->requested_s_scale;
858                                tp->rcv_scale = tp->request_r_scale;
859                        }
860                        /* Segment is acceptable, update cache if undefined. */
861                        if (taop->tao_ccsent == 0)
862                                taop->tao_ccsent = to.to_ccecho;
863
864                        tp->rcv_adv += tp->rcv_wnd;
865                        tp->snd_una++;          /* SYN is acked */
866                        /*
867                         * If there's data, delay ACK; if there's also a FIN
868                         * ACKNOW will be turned on later.
869                         */
870                        if (ti->ti_len != 0)
871                                tp->t_flags |= TF_DELACK;
872                        else
873                                tp->t_flags |= TF_ACKNOW;
874                        /*
875                         * Received <SYN,ACK> in SYN_SENT[*] state.
876                         * Transitions:
877                         *      SYN_SENT  --> ESTABLISHED
878                         *      SYN_SENT* --> FIN_WAIT_1
879                         */
880                        if (tp->t_flags & TF_NEEDFIN) {
881                                tp->t_state = TCPS_FIN_WAIT_1;
882                                tp->t_flags &= ~TF_NEEDFIN;
883                                tiflags &= ~TH_SYN;
884                        } else {
885                                tp->t_state = TCPS_ESTABLISHED;
886                                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
887                        }
888                } else {
889                /*
890                 *  Received initial SYN in SYN-SENT[*] state => simul-
891                 *  taneous open.  If segment contains CC option and there is
892                 *  a cached CC, apply TAO test; if it succeeds, connection is
893                 *  half-synchronized.  Otherwise, do 3-way handshake:
894                 *        SYN-SENT -> SYN-RECEIVED
895                 *        SYN-SENT* -> SYN-RECEIVED*
896                 *  If there was no CC option, clear cached CC value.
897                 */
898                        tp->t_flags |= TF_ACKNOW;
899                        tp->t_timer[TCPT_REXMT] = 0;
900                        if (to.to_flags & TOF_CC) {
901                                if (taop->tao_cc != 0 &&
902                                    CC_GT(to.to_cc, taop->tao_cc)) {
903                                        /*
904                                         * update cache and make transition:
905                                         *        SYN-SENT -> ESTABLISHED*
906                                         *        SYN-SENT* -> FIN-WAIT-1*
907                                         */
908                                        taop->tao_cc = to.to_cc;
909                                        if (tp->t_flags & TF_NEEDFIN) {
910                                                tp->t_state = TCPS_FIN_WAIT_1;
911                                                tp->t_flags &= ~TF_NEEDFIN;
912                                        } else {
913                                                tp->t_state = TCPS_ESTABLISHED;
914                                                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
915                                        }
916                                        tp->t_flags |= TF_NEEDSYN;
917                                } else
918                                        tp->t_state = TCPS_SYN_RECEIVED;
919                        } else {
920                                /* CC.NEW or no option => invalidate cache */
921                                taop->tao_cc = 0;
922                                tp->t_state = TCPS_SYN_RECEIVED;
923                        }
924                }
925
926trimthenstep6:
927                /*
928                 * Advance ti->ti_seq to correspond to first data byte.
929                 * If data, trim to stay within window,
930                 * dropping FIN if necessary.
931                 */
932                ti->ti_seq++;
933                if (ti->ti_len > tp->rcv_wnd) {
934                        todrop = ti->ti_len - tp->rcv_wnd;
935                        m_adj(m, -todrop);
936                        ti->ti_len = tp->rcv_wnd;
937                        tiflags &= ~TH_FIN;
938                        tcpstat.tcps_rcvpackafterwin++;
939                        tcpstat.tcps_rcvbyteafterwin += todrop;
940                }
941                tp->snd_wl1 = ti->ti_seq - 1;
942                tp->rcv_up = ti->ti_seq;
943                /*
944                 *  Client side of transaction: already sent SYN and data.
945                 *  If the remote host used T/TCP to validate the SYN,
946                 *  our data will be ACK'd; if so, enter normal data segment
947                 *  processing in the middle of step 5, ack processing.
948                 *  Otherwise, goto step 6.
949                 */
950                if (tiflags & TH_ACK)
951                        goto process_ACK;
952                goto step6;
953        /*
954         * If the state is LAST_ACK or CLOSING or TIME_WAIT:
955         *      if segment contains a SYN and CC [not CC.NEW] option:
956         *              if state == TIME_WAIT and connection duration > MSL,
957         *                  drop packet and send RST;
958         *
959         *              if SEG.CC > CCrecv then is new SYN, and can implicitly
960         *                  ack the FIN (and data) in retransmission queue.
961         *                  Complete close and delete TCPCB.  Then reprocess
962         *                  segment, hoping to find new TCPCB in LISTEN state;
963         *
964         *              else must be old SYN; drop it.
965         *      else do normal processing.
966         */
967        case TCPS_LAST_ACK:
968        case TCPS_CLOSING:
969        case TCPS_TIME_WAIT:
970                if ((tiflags & TH_SYN) &&
971                    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
972                        if (tp->t_state == TCPS_TIME_WAIT &&
973                                        tp->t_duration > TCPTV_MSL)
974                                goto dropwithreset;
975                        if (CC_GT(to.to_cc, tp->cc_recv)) {
976                                tp = tcp_close(tp);
977                                goto findpcb;
978                        }
979                        else
980                                goto drop;
981                }
982                break;  /* continue normal processing */
983        }
984
985        /*
986         * States other than LISTEN or SYN_SENT.
987         * First check timestamp, if present.
988         * Then check the connection count, if present.
989         * Then check that at least some bytes of segment are within
990         * receive window.  If segment begins before rcv_nxt,
991         * drop leading data (and SYN); if nothing left, just ack.
992         *
993         * RFC 1323 PAWS: If we have a timestamp reply on this segment
994         * and it's less than ts_recent, drop it.
995         */
996        if ((to.to_flags & TOF_TS) != 0 && (tiflags & TH_RST) == 0 &&
997            tp->ts_recent && TSTMP_LT(to.to_tsval, tp->ts_recent)) {
998
999                /* Check to see if ts_recent is over 24 days old.  */
1000                if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1001                        /*
1002                         * Invalidate ts_recent.  If this segment updates
1003                         * ts_recent, the age will be reset later and ts_recent
1004                         * will get a valid value.  If it does not, setting
1005                         * ts_recent to zero will at least satisfy the
1006                         * requirement that zero be placed in the timestamp
1007                         * echo reply when ts_recent isn't valid.  The
1008                         * age isn't reset until we get a valid ts_recent
1009                         * because we don't want out-of-order segments to be
1010                         * dropped when ts_recent is old.
1011                         */
1012                        tp->ts_recent = 0;
1013                } else {
1014                        tcpstat.tcps_rcvduppack++;
1015                        tcpstat.tcps_rcvdupbyte += ti->ti_len;
1016                        tcpstat.tcps_pawsdrop++;
1017                        goto dropafterack;
1018                }
1019        }
1020
1021        /*
1022         * T/TCP mechanism
1023         *   If T/TCP was negotiated and the segment doesn't have CC,
1024         *   or if it's CC is wrong then drop the segment.
1025         *   RST segments do not have to comply with this.
1026         */
1027        if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1028            ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc) &&
1029            (tiflags & TH_RST) == 0)
1030                goto dropafterack;
1031
1032        todrop = tp->rcv_nxt - ti->ti_seq;
1033        if (todrop > 0) {
1034                if (tiflags & TH_SYN) {
1035                        tiflags &= ~TH_SYN;
1036                        ti->ti_seq++;
1037                        if (ti->ti_urp > 1)
1038                                ti->ti_urp--;
1039                        else
1040                                tiflags &= ~TH_URG;
1041                        todrop--;
1042                }
1043                /*
1044                 * Following if statement from Stevens, vol. 2, p. 960.
1045                 */
1046                if (todrop > ti->ti_len
1047                    || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1048                        /*
1049                         * Any valid FIN must be to the left of the window.
1050                         * At this point the FIN must be a duplicate or out
1051                         * of sequence; drop it.
1052                         */
1053                        tiflags &= ~TH_FIN;
1054
1055                        /*
1056                         * Send an ACK to resynchronize and drop any data.
1057                         * But keep on processing for RST or ACK.
1058                         */
1059                        tp->t_flags |= TF_ACKNOW;
1060                        todrop = ti->ti_len;
1061                        tcpstat.tcps_rcvduppack++;
1062                        tcpstat.tcps_rcvdupbyte += todrop;
1063                } else {
1064                        tcpstat.tcps_rcvpartduppack++;
1065                        tcpstat.tcps_rcvpartdupbyte += todrop;
1066                }
1067                m_adj(m, todrop);
1068                ti->ti_seq += todrop;
1069                ti->ti_len -= todrop;
1070                if (ti->ti_urp > todrop)
1071                        ti->ti_urp -= todrop;
1072                else {
1073                        tiflags &= ~TH_URG;
1074                        ti->ti_urp = 0;
1075                }
1076        }
1077
1078        /*
1079         * If new data are received on a connection after the
1080         * user processes are gone, then RST the other end.
1081         */
1082        if ((so->so_state & SS_NOFDREF) &&
1083            tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1084                tp = tcp_close(tp);
1085                tcpstat.tcps_rcvafterclose++;
1086                goto dropwithreset;
1087        }
1088
1089        /*
1090         * If segment ends after window, drop trailing data
1091         * (and PUSH and FIN); if nothing left, just ACK.
1092         */
1093        todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1094        if (todrop > 0) {
1095                tcpstat.tcps_rcvpackafterwin++;
1096                if (todrop >= ti->ti_len) {
1097                        tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1098                        /*
1099                         * If a new connection request is received
1100                         * while in TIME_WAIT, drop the old connection
1101                         * and start over if the sequence numbers
1102                         * are above the previous ones.
1103                         */
1104                        if (tiflags & TH_SYN &&
1105                            tp->t_state == TCPS_TIME_WAIT &&
1106                            SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1107                                iss = tp->rcv_nxt + TCP_ISSINCR;
1108                                tp = tcp_close(tp);
1109                                goto findpcb;
1110                        }
1111                        /*
1112                         * If window is closed can only take segments at
1113                         * window edge, and have to drop data and PUSH from
1114                         * incoming segments.  Continue processing, but
1115                         * remember to ack.  Otherwise, drop segment
1116                         * and ack.
1117                         */
1118                        if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1119                                tp->t_flags |= TF_ACKNOW;
1120                                tcpstat.tcps_rcvwinprobe++;
1121                        } else
1122                                goto dropafterack;
1123                } else
1124                        tcpstat.tcps_rcvbyteafterwin += todrop;
1125                m_adj(m, -todrop);
1126                ti->ti_len -= todrop;
1127                tiflags &= ~(TH_PUSH|TH_FIN);
1128        }
1129
1130        /*
1131         * If last ACK falls within this segment's sequence numbers,
1132         * record its timestamp.
1133         * NOTE that the test is modified according to the latest
1134         * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1135         */
1136        if ((to.to_flags & TOF_TS) != 0 &&
1137            SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1138                tp->ts_recent_age = tcp_now;
1139                tp->ts_recent = to.to_tsval;
1140        }
1141
1142        /*
1143         * If the RST bit is set examine the state:
1144         *    SYN_RECEIVED STATE:
1145         *      If passive open, return to LISTEN state.
1146         *      If active open, inform user that connection was refused.
1147         *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1148         *      Inform user that connection was reset, and close tcb.
1149         *    CLOSING, LAST_ACK, TIME_WAIT STATES
1150         *      Close the tcb.
1151         */
1152        if (tiflags&TH_RST) switch (tp->t_state) {
1153
1154        case TCPS_SYN_RECEIVED:
1155                so->so_error = ECONNREFUSED;
1156                goto close;
1157
1158        case TCPS_ESTABLISHED:
1159        case TCPS_FIN_WAIT_1:
1160        case TCPS_FIN_WAIT_2:
1161        case TCPS_CLOSE_WAIT:
1162                so->so_error = ECONNRESET;
1163        close:
1164                tp->t_state = TCPS_CLOSED;
1165                tcpstat.tcps_drops++;
1166                tp = tcp_close(tp);
1167                goto drop;
1168
1169        case TCPS_CLOSING:
1170        case TCPS_LAST_ACK:
1171        case TCPS_TIME_WAIT:
1172                tp = tcp_close(tp);
1173                goto drop;
1174        }
1175
1176        /*
1177         * If a SYN is in the window, then this is an
1178         * error and we send an RST and drop the connection.
1179         */
1180        if (tiflags & TH_SYN) {
1181                tp = tcp_drop(tp, ECONNRESET);
1182                goto dropwithreset;
1183        }
1184
1185        /*
1186         * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1187         * flag is on (half-synchronized state), then queue data for
1188         * later processing; else drop segment and return.
1189         */
1190        if ((tiflags & TH_ACK) == 0) {
1191                if (tp->t_state == TCPS_SYN_RECEIVED ||
1192                    (tp->t_flags & TF_NEEDSYN))
1193                        goto step6;
1194                else
1195                        goto drop;
1196        }
1197
1198        /*
1199         * Ack processing.
1200         */
1201        switch (tp->t_state) {
1202
1203        /*
1204         * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1205         * ESTABLISHED state and continue processing.
1206         * The ACK was checked above.
1207         */
1208        case TCPS_SYN_RECEIVED:
1209
1210                tcpstat.tcps_connects++;
1211                soisconnected(so);
1212                /* Do window scaling? */
1213                if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1214                        (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1215                        tp->snd_scale = tp->requested_s_scale;
1216                        tp->rcv_scale = tp->request_r_scale;
1217                }
1218                /*
1219                 * Upon successful completion of 3-way handshake,
1220                 * update cache.CC if it was undefined, pass any queued
1221                 * data to the user, and advance state appropriately.
1222                 */
1223                if ((taop = tcp_gettaocache(inp)) != NULL &&
1224                    taop->tao_cc == 0)
1225                        taop->tao_cc = tp->cc_recv;
1226
1227                /*
1228                 * Make transitions:
1229                 *      SYN-RECEIVED  -> ESTABLISHED
1230                 *      SYN-RECEIVED* -> FIN-WAIT-1
1231                 */
1232                if (tp->t_flags & TF_NEEDFIN) {
1233                        tp->t_state = TCPS_FIN_WAIT_1;
1234                        tp->t_flags &= ~TF_NEEDFIN;
1235                } else {
1236                        tp->t_state = TCPS_ESTABLISHED;
1237                        tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1238                }
1239                /*
1240                 * If segment contains data or ACK, will call tcp_reass()
1241                 * later; if not, do so now to pass queued data to user.
1242                 */
1243                if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1244                        (void) tcp_reass(tp, (struct tcpiphdr *)0,
1245                            (struct mbuf *)0);
1246                tp->snd_wl1 = ti->ti_seq - 1;
1247                /* fall into ... */
1248
1249        /*
1250         * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1251         * ACKs.  If the ack is in the range
1252         *      tp->snd_una < ti->ti_ack <= tp->snd_max
1253         * then advance tp->snd_una to ti->ti_ack and drop
1254         * data from the retransmission queue.  If this ACK reflects
1255         * more up to date window information we update our window information.
1256         */
1257        case TCPS_ESTABLISHED:
1258        case TCPS_FIN_WAIT_1:
1259        case TCPS_FIN_WAIT_2:
1260        case TCPS_CLOSE_WAIT:
1261        case TCPS_CLOSING:
1262        case TCPS_LAST_ACK:
1263        case TCPS_TIME_WAIT:
1264
1265                if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1266                        if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1267                                tcpstat.tcps_rcvdupack++;
1268                                /*
1269                                 * If we have outstanding data (other than
1270                                 * a window probe), this is a completely
1271                                 * duplicate ack (ie, window info didn't
1272                                 * change), the ack is the biggest we've
1273                                 * seen and we've seen exactly our rexmt
1274                                 * threshhold of them, assume a packet
1275                                 * has been dropped and retransmit it.
1276                                 * Kludge snd_nxt & the congestion
1277                                 * window so we send only this one
1278                                 * packet.
1279                                 *
1280                                 * We know we're losing at the current
1281                                 * window size so do congestion avoidance
1282                                 * (set ssthresh to half the current window
1283                                 * and pull our congestion window back to
1284                                 * the new ssthresh).
1285                                 *
1286                                 * Dup acks mean that packets have left the
1287                                 * network (they're now cached at the receiver)
1288                                 * so bump cwnd by the amount in the receiver
1289                                 * to keep a constant cwnd packets in the
1290                                 * network.
1291                                 */
1292                                if (tp->t_timer[TCPT_REXMT] == 0 ||
1293                                    ti->ti_ack != tp->snd_una)
1294                                        tp->t_dupacks = 0;
1295                                else if (++tp->t_dupacks == tcprexmtthresh) {
1296                                        tcp_seq onxt = tp->snd_nxt;
1297                                        u_int win =
1298                                            min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1299                                                tp->t_maxseg;
1300
1301                                        if (win < 2)
1302                                                win = 2;
1303                                        tp->snd_ssthresh = win * tp->t_maxseg;
1304                                        tp->t_timer[TCPT_REXMT] = 0;
1305                                        tp->t_rtt = 0;
1306                                        tp->snd_nxt = ti->ti_ack;
1307                                        tp->snd_cwnd = tp->t_maxseg;
1308                                        (void) tcp_output(tp);
1309                                        tp->snd_cwnd = tp->snd_ssthresh +
1310                                               tp->t_maxseg * tp->t_dupacks;
1311                                        if (SEQ_GT(onxt, tp->snd_nxt))
1312                                                tp->snd_nxt = onxt;
1313                                        goto drop;
1314                                } else if (tp->t_dupacks > tcprexmtthresh) {
1315                                        tp->snd_cwnd += tp->t_maxseg;
1316                                        (void) tcp_output(tp);
1317                                        goto drop;
1318                                }
1319                        } else
1320                                tp->t_dupacks = 0;
1321                        break;
1322                }
1323                /*
1324                 * If the congestion window was inflated to account
1325                 * for the other side's cached packets, retract it.
1326                 */
1327                if (tp->t_dupacks >= tcprexmtthresh &&
1328                    tp->snd_cwnd > tp->snd_ssthresh)
1329                        tp->snd_cwnd = tp->snd_ssthresh;
1330                tp->t_dupacks = 0;
1331                if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1332                        tcpstat.tcps_rcvacktoomuch++;
1333                        goto dropafterack;
1334                }
1335                /*
1336                 *  If we reach this point, ACK is not a duplicate,
1337                 *     i.e., it ACKs something we sent.
1338                 */
1339                if (tp->t_flags & TF_NEEDSYN) {
1340                        /*
1341                         * T/TCP: Connection was half-synchronized, and our
1342                         * SYN has been ACK'd (so connection is now fully
1343                         * synchronized).  Go to non-starred state,
1344                         * increment snd_una for ACK of SYN, and check if
1345                         * we can do window scaling.
1346                         */
1347                        tp->t_flags &= ~TF_NEEDSYN;
1348                        tp->snd_una++;
1349                        /* Do window scaling? */
1350                        if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1351                                (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1352                                tp->snd_scale = tp->requested_s_scale;
1353                                tp->rcv_scale = tp->request_r_scale;
1354                        }
1355                }
1356
1357process_ACK:
1358                acked = ti->ti_ack - tp->snd_una;
1359                tcpstat.tcps_rcvackpack++;
1360                tcpstat.tcps_rcvackbyte += acked;
1361
1362                /*
1363                 * If we have a timestamp reply, update smoothed
1364                 * round trip time.  If no timestamp is present but
1365                 * transmit timer is running and timed sequence
1366                 * number was acked, update smoothed round trip time.
1367                 * Since we now have an rtt measurement, cancel the
1368                 * timer backoff (cf., Phil Karn's retransmit alg.).
1369                 * Recompute the initial retransmit timer.
1370                 */
1371                if (to.to_flags & TOF_TS)
1372                        tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1373                else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1374                        tcp_xmit_timer(tp,tp->t_rtt);
1375
1376                /*
1377                 * If all outstanding data is acked, stop retransmit
1378                 * timer and remember to restart (more output or persist).
1379                 * If there is more data to be acked, restart retransmit
1380                 * timer, using current (possibly backed-off) value.
1381                 */
1382                if (ti->ti_ack == tp->snd_max) {
1383                        tp->t_timer[TCPT_REXMT] = 0;
1384                        needoutput = 1;
1385                } else if (tp->t_timer[TCPT_PERSIST] == 0)
1386                        tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1387
1388                /*
1389                 * If no data (only SYN) was ACK'd,
1390                 *    skip rest of ACK processing.
1391                 */
1392                if (acked == 0)
1393                        goto step6;
1394
1395                /*
1396                 * When new data is acked, open the congestion window.
1397                 * If the window gives us less than ssthresh packets
1398                 * in flight, open exponentially (maxseg per packet).
1399                 * Otherwise open linearly: maxseg per window
1400                 * (maxseg^2 / cwnd per packet).
1401                 */
1402                {
1403                register u_int cw = tp->snd_cwnd;
1404                register u_int incr = tp->t_maxseg;
1405
1406                if (cw > tp->snd_ssthresh)
1407                        incr = incr * incr / cw;
1408                tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1409                }
1410                if (acked > so->so_snd.sb_cc) {
1411                        tp->snd_wnd -= so->so_snd.sb_cc;
1412                        sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1413                        ourfinisacked = 1;
1414                } else {
1415                        sbdrop(&so->so_snd, acked);
1416                        tp->snd_wnd -= acked;
1417                        ourfinisacked = 0;
1418                }
1419                if (so->so_snd.sb_flags & SB_NOTIFY)
1420                        sowwakeup(so);
1421                tp->snd_una = ti->ti_ack;
1422                if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1423                        tp->snd_nxt = tp->snd_una;
1424
1425                switch (tp->t_state) {
1426
1427                /*
1428                 * In FIN_WAIT_1 STATE in addition to the processing
1429                 * for the ESTABLISHED state if our FIN is now acknowledged
1430                 * then enter FIN_WAIT_2.
1431                 */
1432                case TCPS_FIN_WAIT_1:
1433                        if (ourfinisacked) {
1434                                /*
1435                                 * If we can't receive any more
1436                                 * data, then closing user can proceed.
1437                                 * Starting the timer is contrary to the
1438                                 * specification, but if we don't get a FIN
1439                                 * we'll hang forever.
1440                                 */
1441                                if (so->so_state & SS_CANTRCVMORE) {
1442                                        soisdisconnected(so);
1443                                        tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1444                                }
1445                                tp->t_state = TCPS_FIN_WAIT_2;
1446                        }
1447                        break;
1448
1449                /*
1450                 * In CLOSING STATE in addition to the processing for
1451                 * the ESTABLISHED state if the ACK acknowledges our FIN
1452                 * then enter the TIME-WAIT state, otherwise ignore
1453                 * the segment.
1454                 */
1455                case TCPS_CLOSING:
1456                        if (ourfinisacked) {
1457                                tp->t_state = TCPS_TIME_WAIT;
1458                                tcp_canceltimers(tp);
1459                                /* Shorten TIME_WAIT [RFC-1644, p.28] */
1460                                if (tp->cc_recv != 0 &&
1461                                    tp->t_duration < TCPTV_MSL)
1462                                        tp->t_timer[TCPT_2MSL] =
1463                                            tp->t_rxtcur * TCPTV_TWTRUNC;
1464                                else
1465                                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1466                                soisdisconnected(so);
1467                        }
1468                        break;
1469
1470                /*
1471                 * In LAST_ACK, we may still be waiting for data to drain
1472                 * and/or to be acked, as well as for the ack of our FIN.
1473                 * If our FIN is now acknowledged, delete the TCB,
1474                 * enter the closed state and return.
1475                 */
1476                case TCPS_LAST_ACK:
1477                        if (ourfinisacked) {
1478                                tp = tcp_close(tp);
1479                                goto drop;
1480                        }
1481                        break;
1482
1483                /*
1484                 * In TIME_WAIT state the only thing that should arrive
1485                 * is a retransmission of the remote FIN.  Acknowledge
1486                 * it and restart the finack timer.
1487                 */
1488                case TCPS_TIME_WAIT:
1489                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1490                        goto dropafterack;
1491                }
1492        }
1493
1494step6:
1495        /*
1496         * Update window information.
1497         * Don't look at window if no ACK: TAC's send garbage on first SYN.
1498         */
1499        if ((tiflags & TH_ACK) &&
1500            (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1501            (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1502             (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1503                /* keep track of pure window updates */
1504                if (ti->ti_len == 0 &&
1505                    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1506                        tcpstat.tcps_rcvwinupd++;
1507                tp->snd_wnd = tiwin;
1508                tp->snd_wl1 = ti->ti_seq;
1509                tp->snd_wl2 = ti->ti_ack;
1510                if (tp->snd_wnd > tp->max_sndwnd)
1511                        tp->max_sndwnd = tp->snd_wnd;
1512                needoutput = 1;
1513        }
1514
1515        /*
1516         * Process segments with URG.
1517         */
1518        if ((tiflags & TH_URG) && ti->ti_urp &&
1519            TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1520                /*
1521                 * This is a kludge, but if we receive and accept
1522                 * random urgent pointers, we'll crash in
1523                 * soreceive.  It's hard to imagine someone
1524                 * actually wanting to send this much urgent data.
1525                 */
1526                if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1527                        ti->ti_urp = 0;                 /* XXX */
1528                        tiflags &= ~TH_URG;             /* XXX */
1529                        goto dodata;                    /* XXX */
1530                }
1531                /*
1532                 * If this segment advances the known urgent pointer,
1533                 * then mark the data stream.  This should not happen
1534                 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1535                 * a FIN has been received from the remote side.
1536                 * In these states we ignore the URG.
1537                 *
1538                 * According to RFC961 (Assigned Protocols),
1539                 * the urgent pointer points to the last octet
1540                 * of urgent data.  We continue, however,
1541                 * to consider it to indicate the first octet
1542                 * of data past the urgent section as the original
1543                 * spec states (in one of two places).
1544                 */
1545                if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1546                        tp->rcv_up = ti->ti_seq + ti->ti_urp;
1547                        so->so_oobmark = so->so_rcv.sb_cc +
1548                            (tp->rcv_up - tp->rcv_nxt) - 1;
1549                        if (so->so_oobmark == 0)
1550                                so->so_state |= SS_RCVATMARK;
1551                        sohasoutofband(so);
1552                        tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1553                }
1554                /*
1555                 * Remove out of band data so doesn't get presented to user.
1556                 * This can happen independent of advancing the URG pointer,
1557                 * but if two URG's are pending at once, some out-of-band
1558                 * data may creep in... ick.
1559                 */
1560                if (ti->ti_urp <= (u_long)ti->ti_len
1561#ifdef SO_OOBINLINE
1562                     && (so->so_options & SO_OOBINLINE) == 0
1563#endif
1564                     )
1565                        tcp_pulloutofband(so, ti, m);
1566        } else
1567                /*
1568                 * If no out of band data is expected,
1569                 * pull receive urgent pointer along
1570                 * with the receive window.
1571                 */
1572                if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1573                        tp->rcv_up = tp->rcv_nxt;
1574dodata:                                                 /* XXX */
1575
1576        /*
1577         * Process the segment text, merging it into the TCP sequencing queue,
1578         * and arranging for acknowledgment of receipt if necessary.
1579         * This process logically involves adjusting tp->rcv_wnd as data
1580         * is presented to the user (this happens in tcp_usrreq.c,
1581         * case PRU_RCVD).  If a FIN has already been received on this
1582         * connection then we just ignore the text.
1583         */
1584        if ((ti->ti_len || (tiflags&TH_FIN)) &&
1585            TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1586                TCP_REASS(tp, ti, m, so, tiflags);
1587                /*
1588                 * Note the amount of data that peer has sent into
1589                 * our window, in order to estimate the sender's
1590                 * buffer size.
1591                 */
1592                len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1593        } else {
1594                m_freem(m);
1595                tiflags &= ~TH_FIN;
1596        }
1597
1598        /*
1599         * If FIN is received ACK the FIN and let the user know
1600         * that the connection is closing.
1601         */
1602        if (tiflags & TH_FIN) {
1603                if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1604                        socantrcvmore(so);
1605                        /*
1606                         *  If connection is half-synchronized
1607                         *  (ie NEEDSYN flag on) then delay ACK,
1608                         *  so it may be piggybacked when SYN is sent.
1609                         *  Otherwise, since we received a FIN then no
1610                         *  more input can be expected, send ACK now.
1611                         */
1612                        if (tp->t_flags & TF_NEEDSYN)
1613                                tp->t_flags |= TF_DELACK;
1614                        else
1615                                tp->t_flags |= TF_ACKNOW;
1616                        tp->rcv_nxt++;
1617                }
1618                switch (tp->t_state) {
1619
1620                /*
1621                 * In SYN_RECEIVED and ESTABLISHED STATES
1622                 * enter the CLOSE_WAIT state.
1623                 */
1624                case TCPS_SYN_RECEIVED:
1625                case TCPS_ESTABLISHED:
1626                        tp->t_state = TCPS_CLOSE_WAIT;
1627                        break;
1628
1629                /*
1630                 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1631                 * enter the CLOSING state.
1632                 */
1633                case TCPS_FIN_WAIT_1:
1634                        tp->t_state = TCPS_CLOSING;
1635                        break;
1636
1637                /*
1638                 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1639                 * starting the time-wait timer, turning off the other
1640                 * standard timers.
1641                 */
1642                case TCPS_FIN_WAIT_2:
1643                        tp->t_state = TCPS_TIME_WAIT;
1644                        tcp_canceltimers(tp);
1645                        /* Shorten TIME_WAIT [RFC-1644, p.28] */
1646                        if (tp->cc_recv != 0 &&
1647                            tp->t_duration < TCPTV_MSL) {
1648                                tp->t_timer[TCPT_2MSL] =
1649                                    tp->t_rxtcur * TCPTV_TWTRUNC;
1650                                /* For transaction client, force ACK now. */
1651                                tp->t_flags |= TF_ACKNOW;
1652                        }
1653                        else
1654                                tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1655                        soisdisconnected(so);
1656                        break;
1657
1658                /*
1659                 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1660                 */
1661                case TCPS_TIME_WAIT:
1662                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1663                        break;
1664                }
1665        }
1666#ifdef TCPDEBUG
1667        if (so->so_options & SO_DEBUG)
1668                tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1669#endif
1670
1671        /*
1672         * Return any desired output.
1673         */
1674        if (needoutput || (tp->t_flags & TF_ACKNOW))
1675                (void) tcp_output(tp);
1676        return;
1677
1678dropafterack:
1679        /*
1680         * Generate an ACK dropping incoming segment if it occupies
1681         * sequence space, where the ACK reflects our state.
1682         */
1683        if (tiflags & TH_RST)
1684                goto drop;
1685#ifdef TCPDEBUG
1686        if (so->so_options & SO_DEBUG)
1687                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1688#endif
1689        m_freem(m);
1690        tp->t_flags |= TF_ACKNOW;
1691        (void) tcp_output(tp);
1692        return;
1693
1694dropwithreset:
1695        /*
1696         * Generate a RST, dropping incoming segment.
1697         * Make ACK acceptable to originator of segment.
1698         * Don't bother to respond if destination was broadcast/multicast.
1699         */
1700        if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1701            IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1702                goto drop;
1703#ifdef TCPDEBUG
1704        if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1705                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1706#endif
1707        if (tiflags & TH_ACK)
1708                tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1709        else {
1710                if (tiflags & TH_SYN)
1711                        ti->ti_len++;
1712                tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1713                    TH_RST|TH_ACK);
1714        }
1715        /* destroy temporarily created socket */
1716        if (dropsocket)
1717                (void) soabort(so);
1718        return;
1719
1720drop:
1721        /*
1722         * Drop space held by incoming segment and return.
1723         */
1724#ifdef TCPDEBUG
1725        if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1726                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1727#endif
1728        m_freem(m);
1729        /* destroy temporarily created socket */
1730        if (dropsocket)
1731                (void) soabort(so);
1732        return;
1733#ifndef TUBA_INCLUDE
1734}
1735
1736static void
1737tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti,
1738        struct tcpopt *to)
1739{
1740        u_short mss = 0;
1741        int opt, optlen;
1742
1743        for (; cnt > 0; cnt -= optlen, cp += optlen) {
1744                opt = cp[0];
1745                if (opt == TCPOPT_EOL)
1746                        break;
1747                if (opt == TCPOPT_NOP)
1748                        optlen = 1;
1749                else {
1750                        optlen = cp[1];
1751                        if (optlen <= 0)
1752                                break;
1753                }
1754                switch (opt) {
1755
1756                default:
1757                        continue;
1758
1759                case TCPOPT_MAXSEG:
1760                        if (optlen != TCPOLEN_MAXSEG)
1761                                continue;
1762                        if (!(ti->ti_flags & TH_SYN))
1763                                continue;
1764                        bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1765                        NTOHS(mss);
1766                        break;
1767
1768                case TCPOPT_WINDOW:
1769                        if (optlen != TCPOLEN_WINDOW)
1770                                continue;
1771                        if (!(ti->ti_flags & TH_SYN))
1772                                continue;
1773                        tp->t_flags |= TF_RCVD_SCALE;
1774                        tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1775                        break;
1776
1777                case TCPOPT_TIMESTAMP:
1778                        if (optlen != TCPOLEN_TIMESTAMP)
1779                                continue;
1780                        to->to_flags |= TOF_TS;
1781                        bcopy((char *)cp + 2,
1782                            (char *)&to->to_tsval, sizeof(to->to_tsval));
1783                        NTOHL(to->to_tsval);
1784                        bcopy((char *)cp + 6,
1785                            (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1786                        NTOHL(to->to_tsecr);
1787
1788                        /*
1789                         * A timestamp received in a SYN makes
1790                         * it ok to send timestamp requests and replies.
1791                         */
1792                        if (ti->ti_flags & TH_SYN) {
1793                                tp->t_flags |= TF_RCVD_TSTMP;
1794                                tp->ts_recent = to->to_tsval;
1795                                tp->ts_recent_age = tcp_now;
1796                        }
1797                        break;
1798                case TCPOPT_CC:
1799                        if (optlen != TCPOLEN_CC)
1800                                continue;
1801                        to->to_flags |= TOF_CC;
1802                        bcopy((char *)cp + 2,
1803                            (char *)&to->to_cc, sizeof(to->to_cc));
1804                        NTOHL(to->to_cc);
1805                        /*
1806                         * A CC or CC.new option received in a SYN makes
1807                         * it ok to send CC in subsequent segments.
1808                         */
1809                        if (ti->ti_flags & TH_SYN)
1810                                tp->t_flags |= TF_RCVD_CC;
1811                        break;
1812                case TCPOPT_CCNEW:
1813                        if (optlen != TCPOLEN_CC)
1814                                continue;
1815                        if (!(ti->ti_flags & TH_SYN))
1816                                continue;
1817                        to->to_flags |= TOF_CCNEW;
1818                        bcopy((char *)cp + 2,
1819                            (char *)&to->to_cc, sizeof(to->to_cc));
1820                        NTOHL(to->to_cc);
1821                        /*
1822                         * A CC or CC.new option received in a SYN makes
1823                         * it ok to send CC in subsequent segments.
1824                         */
1825                        tp->t_flags |= TF_RCVD_CC;
1826                        break;
1827                case TCPOPT_CCECHO:
1828                        if (optlen != TCPOLEN_CC)
1829                                continue;
1830                        if (!(ti->ti_flags & TH_SYN))
1831                                continue;
1832                        to->to_flags |= TOF_CCECHO;
1833                        bcopy((char *)cp + 2,
1834                            (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1835                        NTOHL(to->to_ccecho);
1836                        break;
1837                }
1838        }
1839        if (ti->ti_flags & TH_SYN)
1840                tcp_mss(tp, mss);       /* sets t_maxseg */
1841}
1842
1843/*
1844 * Pull out of band byte out of a segment so
1845 * it doesn't appear in the user's data queue.
1846 * It is still reflected in the segment length for
1847 * sequencing purposes.
1848 */
1849static void
1850tcp_pulloutofband(struct socket *so, struct tcpiphdr *ti, struct mbuf *m)
1851{
1852        int cnt = ti->ti_urp - 1;
1853
1854        while (cnt >= 0) {
1855                if (m->m_len > cnt) {
1856                        char *cp = mtod(m, caddr_t) + cnt;
1857                        struct tcpcb *tp = sototcpcb(so);
1858
1859                        tp->t_iobc = *cp;
1860                        tp->t_oobflags |= TCPOOB_HAVEDATA;
1861                        bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1862                        m->m_len--;
1863                        return;
1864                }
1865                cnt -= m->m_len;
1866                m = m->m_next;
1867                if (m == 0)
1868                        break;
1869        }
1870        panic("tcp_pulloutofband");
1871}
1872
1873/*
1874 * Collect new round-trip time estimate
1875 * and update averages and current timeout.
1876 */
1877static void
1878tcp_xmit_timer(struct tcpcb *tp, int rtt)
1879{
1880        int delta;
1881
1882        tcpstat.tcps_rttupdated++;
1883        tp->t_rttupdated++;
1884        if (tp->t_srtt != 0) {
1885                /*
1886                 * srtt is stored as fixed point with 5 bits after the
1887                 * binary point (i.e., scaled by 8).  The following magic
1888                 * is equivalent to the smoothing algorithm in rfc793 with
1889                 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1890                 * point).  Adjust rtt to origin 0.
1891                 */
1892                delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1893                        - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1894
1895                if ((tp->t_srtt += delta) <= 0)
1896                        tp->t_srtt = 1;
1897
1898                /*
1899                 * We accumulate a smoothed rtt variance (actually, a
1900                 * smoothed mean difference), then set the retransmit
1901                 * timer to smoothed rtt + 4 times the smoothed variance.
1902                 * rttvar is stored as fixed point with 4 bits after the
1903                 * binary point (scaled by 16).  The following is
1904                 * equivalent to rfc793 smoothing with an alpha of .75
1905                 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1906                 * rfc793's wired-in beta.
1907                 */
1908                if (delta < 0)
1909                        delta = -delta;
1910                delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
1911                if ((tp->t_rttvar += delta) <= 0)
1912                        tp->t_rttvar = 1;
1913        } else {
1914                /*
1915                 * No rtt measurement yet - use the unsmoothed rtt.
1916                 * Set the variance to half the rtt (so our first
1917                 * retransmit happens at 3*rtt).
1918                 */
1919                tp->t_srtt = rtt << TCP_RTT_SHIFT;
1920                tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1921        }
1922        tp->t_rtt = 0;
1923        tp->t_rxtshift = 0;
1924
1925        /*
1926         * the retransmit should happen at rtt + 4 * rttvar.
1927         * Because of the way we do the smoothing, srtt and rttvar
1928         * will each average +1/2 tick of bias.  When we compute
1929         * the retransmit timer, we want 1/2 tick of rounding and
1930         * 1 extra tick because of +-1/2 tick uncertainty in the
1931         * firing of the timer.  The bias will give us exactly the
1932         * 1.5 tick we need.  But, because the bias is
1933         * statistical, we have to test that we don't drop below
1934         * the minimum feasible timer (which is 2 ticks).
1935         */
1936        TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1937                      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
1938
1939        /*
1940         * We received an ack for a packet that wasn't retransmitted;
1941         * it is probably safe to discard any error indications we've
1942         * received recently.  This isn't quite right, but close enough
1943         * for now (a route might have failed after we sent a segment,
1944         * and the return path might not be symmetrical).
1945         */
1946        tp->t_softerror = 0;
1947}
1948
1949/*
1950 * Determine a reasonable value for maxseg size.
1951 * If the route is known, check route for mtu.
1952 * If none, use an mss that can be handled on the outgoing
1953 * interface without forcing IP to fragment; if bigger than
1954 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1955 * to utilize large mbufs.  If no route is found, route has no mtu,
1956 * or the destination isn't local, use a default, hopefully conservative
1957 * size (usually 512 or the default IP max size, but no more than the mtu
1958 * of the interface), as we can't discover anything about intervening
1959 * gateways or networks.  We also initialize the congestion/slow start
1960 * window to be a single segment if the destination isn't local.
1961 * While looking at the routing entry, we also initialize other path-dependent
1962 * parameters from pre-set or cached values in the routing entry.
1963 *
1964 * Also take into account the space needed for options that we
1965 * send regularly.  Make maxseg shorter by that amount to assure
1966 * that we can send maxseg amount of data even when the options
1967 * are present.  Store the upper limit of the length of options plus
1968 * data in maxopd.
1969 *
1970 * NOTE that this routine is only called when we process an incoming
1971 * segment, for outgoing segments only tcp_mssopt is called.
1972 *
1973 * In case of T/TCP, we call this routine during implicit connection
1974 * setup as well (offer = -1), to initialize maxseg from the cached
1975 * MSS of our peer.
1976 */
1977void
1978tcp_mss(struct tcpcb *tp, int offer)
1979{
1980        register struct rtentry *rt;
1981        struct ifnet *ifp;
1982        register int rtt, mss;
1983        u_long bufsize;
1984        struct inpcb *inp;
1985        struct socket *so;
1986        struct rmxp_tao *taop;
1987        int origoffer = offer;
1988
1989        inp = tp->t_inpcb;
1990        if ((rt = tcp_rtlookup(inp)) == NULL) {
1991                tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
1992                return;
1993        }
1994        ifp = rt->rt_ifp;
1995        so = inp->inp_socket;
1996
1997        taop = rmx_taop(rt->rt_rmx);
1998        /*
1999         * Offer == -1 means that we didn't receive SYN yet,
2000         * use cached value in that case;
2001         */
2002        if (offer == -1)
2003                offer = taop->tao_mssopt;
2004        /*
2005         * Offer == 0 means that there was no MSS on the SYN segment,
2006         * in this case we use tcp_mssdflt.
2007         */
2008        if (offer == 0)
2009                offer = tcp_mssdflt;
2010        else
2011                /*
2012                 * Sanity check: make sure that maxopd will be large
2013                 * enough to allow some data on segments even is the
2014                 * all the option space is used (40bytes).  Otherwise
2015                 * funny things may happen in tcp_output.
2016                 */
2017                offer = max(offer, 64);
2018        taop->tao_mssopt = offer;
2019
2020        /*
2021         * While we're here, check if there's an initial rtt
2022         * or rttvar.  Convert from the route-table units
2023         * to scaled multiples of the slow timeout timer.
2024         */
2025        if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2026                /*
2027                 * XXX the lock bit for RTT indicates that the value
2028                 * is also a minimum value; this is subject to time.
2029                 */
2030                if (rt->rt_rmx.rmx_locks & RTV_RTT)
2031                        tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2032                tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2033                tcpstat.tcps_usedrtt++;
2034                if (rt->rt_rmx.rmx_rttvar) {
2035                        tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2036                            (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2037                        tcpstat.tcps_usedrttvar++;
2038                } else {
2039                        /* default variation is +- 1 rtt */
2040                        tp->t_rttvar =
2041                            tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2042                }
2043                TCPT_RANGESET(tp->t_rxtcur,
2044                    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2045                    tp->t_rttmin, TCPTV_REXMTMAX);
2046        }
2047        /*
2048         * if there's an mtu associated with the route, use it
2049         */
2050        if (rt->rt_rmx.rmx_mtu)
2051                mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2052        else
2053        {
2054                mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2055                if (!in_localaddr(inp->inp_faddr))
2056                        mss = min(mss, tcp_mssdflt);
2057        }
2058        mss = min(mss, offer);
2059        /*
2060         * maxopd stores the maximum length of data AND options
2061         * in a segment; maxseg is the amount of data in a normal
2062         * segment.  We need to store this value (maxopd) apart
2063         * from maxseg, because now every segment carries options
2064         * and thus we normally have somewhat less data in segments.
2065         */
2066        tp->t_maxopd = mss;
2067
2068        /*
2069         * In case of T/TCP, origoffer==-1 indicates, that no segments
2070         * were received yet.  In this case we just guess, otherwise
2071         * we do the same as before T/TCP.
2072         */
2073        if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2074            (origoffer == -1 ||
2075             (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2076                mss -= TCPOLEN_TSTAMP_APPA;
2077        if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2078            (origoffer == -1 ||
2079             (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2080                mss -= TCPOLEN_CC_APPA;
2081
2082#if     (MCLBYTES & (MCLBYTES - 1)) == 0
2083                if (mss > MCLBYTES)
2084                        mss &= ~(MCLBYTES-1);
2085#else
2086                if (mss > MCLBYTES)
2087                        mss = mss / MCLBYTES * MCLBYTES;
2088#endif
2089        /*
2090         * If there's a pipesize, change the socket buffer
2091         * to that size.  Make the socket buffers an integral
2092         * number of mss units; if the mss is larger than
2093         * the socket buffer, decrease the mss.
2094         */
2095#ifdef RTV_SPIPE
2096        if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2097#endif
2098                bufsize = so->so_snd.sb_hiwat;
2099        if (bufsize < mss)
2100                mss = bufsize;
2101        else {
2102                bufsize = roundup(bufsize, mss);
2103                if (bufsize > sb_max)
2104                        bufsize = sb_max;
2105                (void)sbreserve(&so->so_snd, bufsize);
2106        }
2107        tp->t_maxseg = mss;
2108
2109#ifdef RTV_RPIPE
2110        if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2111#endif
2112                bufsize = so->so_rcv.sb_hiwat;
2113        if (bufsize > mss) {
2114                bufsize = roundup(bufsize, mss);
2115                if (bufsize > sb_max)
2116                        bufsize = sb_max;
2117                (void)sbreserve(&so->so_rcv, bufsize);
2118        }
2119        /*
2120         * Don't force slow-start on local network.
2121         */
2122        if (!in_localaddr(inp->inp_faddr))
2123                tp->snd_cwnd = mss;
2124
2125        if (rt->rt_rmx.rmx_ssthresh) {
2126                /*
2127                 * There's some sort of gateway or interface
2128                 * buffer limit on the path.  Use this to set
2129                 * the slow start threshhold, but set the
2130                 * threshold to no less than 2*mss.
2131                 */
2132                tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2133                tcpstat.tcps_usedssthresh++;
2134        }
2135}
2136
2137/*
2138 * Determine the MSS option to send on an outgoing SYN.
2139 */
2140int
2141tcp_mssopt(struct tcpcb *tp)
2142{
2143        struct rtentry *rt;
2144
2145        rt = tcp_rtlookup(tp->t_inpcb);
2146        if (rt == NULL)
2147                return tcp_mssdflt;
2148
2149        return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2150}
2151#endif /* TUBA_INCLUDE */
Note: See TracBrowser for help on using the repository browser.