xref: /netbsd-src/sys/netinet/tcp_subr.c (revision 89c5a767f8fc7a4633b2d409966e2becbb98ff92)
1 /*	$NetBSD: tcp_subr.c,v 1.89 2000/03/01 12:49:42 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * 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  * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 
32 /*-
33  * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
38  * Facility, NASA Ames Research Center.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed by the NetBSD
51  *	Foundation, Inc. and its contributors.
52  * 4. Neither the name of The NetBSD Foundation nor the names of its
53  *    contributors may be used to endorse or promote products derived
54  *    from this software without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66  * POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 /*
70  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
71  *	The Regents of the University of California.  All rights reserved.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *	This product includes software developed by the University of
84  *	California, Berkeley and its contributors.
85  * 4. Neither the name of the University nor the names of its contributors
86  *    may be used to endorse or promote products derived from this software
87  *    without specific prior written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  *
101  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
102  */
103 
104 #include "opt_inet.h"
105 #include "opt_ipsec.h"
106 #include "opt_tcp_compat_42.h"
107 #include "rnd.h"
108 
109 #include <sys/param.h>
110 #include <sys/proc.h>
111 #include <sys/systm.h>
112 #include <sys/malloc.h>
113 #include <sys/mbuf.h>
114 #include <sys/socket.h>
115 #include <sys/socketvar.h>
116 #include <sys/protosw.h>
117 #include <sys/errno.h>
118 #include <sys/kernel.h>
119 #include <sys/pool.h>
120 #if NRND > 0
121 #include <sys/rnd.h>
122 #endif
123 
124 #include <net/route.h>
125 #include <net/if.h>
126 
127 #include <netinet/in.h>
128 #include <netinet/in_systm.h>
129 #include <netinet/ip.h>
130 #include <netinet/in_pcb.h>
131 #include <netinet/ip_var.h>
132 #include <netinet/ip_icmp.h>
133 
134 #ifdef INET6
135 #ifndef INET
136 #include <netinet/in.h>
137 #endif
138 #include <netinet/ip6.h>
139 #include <netinet6/in6_pcb.h>
140 #include <netinet6/ip6_var.h>
141 #include <netinet6/in6_var.h>
142 #include <netinet6/ip6protosw.h>
143 #endif
144 
145 #include <netinet/tcp.h>
146 #include <netinet/tcp_fsm.h>
147 #include <netinet/tcp_seq.h>
148 #include <netinet/tcp_timer.h>
149 #include <netinet/tcp_var.h>
150 #include <netinet/tcpip.h>
151 
152 #ifdef IPSEC
153 #include <netinet6/ipsec.h>
154 #endif /*IPSEC*/
155 
156 #ifdef INET6
157 struct in6pcb tcb6;
158 #endif
159 
160 /* patchable/settable parameters for tcp */
161 int 	tcp_mssdflt = TCP_MSS;
162 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
163 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
164 int	tcp_do_sack = 1;	/* selective acknowledgement */
165 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
166 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
167 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
168 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
169 int	tcp_init_win = 1;
170 int	tcp_mss_ifmtu = 0;
171 #ifdef TCP_COMPAT_42
172 int	tcp_compat_42 = 1;
173 #else
174 int	tcp_compat_42 = 0;
175 #endif
176 
177 #ifndef TCBHASHSIZE
178 #define	TCBHASHSIZE	128
179 #endif
180 int	tcbhashsize = TCBHASHSIZE;
181 
182 int	tcp_freeq __P((struct tcpcb *));
183 
184 struct pool tcpcb_pool;
185 
186 /*
187  * Tcp initialization
188  */
189 void
190 tcp_init()
191 {
192 	int hlen;
193 
194 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
195 	    0, NULL, NULL, M_PCB);
196 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
197 #ifdef INET6
198 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
199 #endif
200 	LIST_INIT(&tcp_delacks);
201 
202 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
203 #ifdef INET6
204 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
205 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
206 #endif
207 	if (max_protohdr < hlen)
208 		max_protohdr = hlen;
209 	if (max_linkhdr + hlen > MHLEN)
210 		panic("tcp_init");
211 
212 	/* Initialize the compressed state engine. */
213 	syn_cache_init();
214 }
215 
216 /*
217  * Create template to be used to send tcp packets on a connection.
218  * Call after host entry created, allocates an mbuf and fills
219  * in a skeletal tcp/ip header, minimizing the amount of work
220  * necessary when the connection is used.
221  */
222 struct mbuf *
223 tcp_template(tp)
224 	struct tcpcb *tp;
225 {
226 	register struct inpcb *inp = tp->t_inpcb;
227 #ifdef INET6
228 	register struct in6pcb *in6p = tp->t_in6pcb;
229 #endif
230 	register struct tcphdr *n;
231 	register struct mbuf *m;
232 	int hlen;
233 
234 	switch (tp->t_family) {
235 	case AF_INET:
236 		hlen = sizeof(struct ip);
237 		if (inp)
238 			break;
239 #ifdef INET6
240 		if (in6p) {
241 			/* mapped addr case */
242 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
243 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
244 				break;
245 		}
246 #endif
247 		return NULL;	/*EINVAL*/
248 #ifdef INET6
249 	case AF_INET6:
250 		hlen = sizeof(struct ip6_hdr);
251 		if (in6p) {
252 			/* more sainty check? */
253 			break;
254 		}
255 		return NULL;	/*EINVAL*/
256 #endif
257 	default:
258 		hlen = 0;	/*pacify gcc*/
259 		return NULL;	/*EAFNOSUPPORT*/
260 	}
261 	if ((m = tp->t_template) == 0) {
262 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
263 		if (m) {
264 			MCLGET(m, M_DONTWAIT);
265 			if ((m->m_flags & M_EXT) == 0) {
266 				m_free(m);
267 				m = NULL;
268 			}
269 		}
270 		if (m == NULL)
271 			return NULL;
272 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
273 	}
274 	bzero(mtod(m, caddr_t), m->m_len);
275 	switch (tp->t_family) {
276 	case AF_INET:
277 	    {
278 		struct ipovly *ipov;
279 		mtod(m, struct ip *)->ip_v = 4;
280 		ipov = mtod(m, struct ipovly *);
281 		ipov->ih_pr = IPPROTO_TCP;
282 		ipov->ih_len = htons(sizeof(struct tcphdr));
283 		if (inp) {
284 			ipov->ih_src = inp->inp_laddr;
285 			ipov->ih_dst = inp->inp_faddr;
286 		}
287 #ifdef INET6
288 		else if (in6p) {
289 			/* mapped addr case */
290 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
291 				sizeof(ipov->ih_src));
292 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
293 				sizeof(ipov->ih_dst));
294 		}
295 #endif
296 		break;
297 	    }
298 #ifdef INET6
299 	case AF_INET6:
300 	    {
301 		struct ip6_hdr *ip6;
302 		mtod(m, struct ip *)->ip_v = 6;
303 		ip6 = mtod(m, struct ip6_hdr *);
304 		ip6->ip6_nxt = IPPROTO_TCP;
305 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
306 		ip6->ip6_src = in6p->in6p_laddr;
307 		ip6->ip6_dst = in6p->in6p_faddr;
308 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
309 		if (ip6_auto_flowlabel) {
310 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
311 			ip6->ip6_flow |=
312 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
313 		}
314 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
315 		ip6->ip6_vfc |= IPV6_VERSION;
316 		break;
317 	    }
318 #endif
319 	}
320 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
321 	if (inp) {
322 		n->th_sport = inp->inp_lport;
323 		n->th_dport = inp->inp_fport;
324 	}
325 #ifdef INET6
326 	else if (in6p) {
327 		n->th_sport = in6p->in6p_lport;
328 		n->th_dport = in6p->in6p_fport;
329 	}
330 #endif
331 	n->th_seq = 0;
332 	n->th_ack = 0;
333 	n->th_x2 = 0;
334 	n->th_off = 5;
335 	n->th_flags = 0;
336 	n->th_win = 0;
337 	n->th_sum = 0;
338 	n->th_urp = 0;
339 	return (m);
340 }
341 
342 /*
343  * Send a single message to the TCP at address specified by
344  * the given TCP/IP header.  If m == 0, then we make a copy
345  * of the tcpiphdr at ti and send directly to the addressed host.
346  * This is used to force keep alive messages out using the TCP
347  * template for a connection tp->t_template.  If flags are given
348  * then we send a message back to the TCP which originated the
349  * segment ti, and discard the mbuf containing it and any other
350  * attached mbufs.
351  *
352  * In any case the ack and sequence number of the transmitted
353  * segment are as specified by the parameters.
354  */
355 int
356 tcp_respond(tp, template, m, th0, ack, seq, flags)
357 	struct tcpcb *tp;
358 	struct mbuf *template;
359 	register struct mbuf *m;
360 	struct tcphdr *th0;
361 	tcp_seq ack, seq;
362 	int flags;
363 {
364 #ifndef INET6
365 	struct route iproute;
366 #else
367 	struct route_in6 iproute;	/* sizeof(route_in6) > sizeof(route) */
368 #endif
369 	struct route *ro;
370 	struct rtentry *rt;
371 	int error, tlen, win = 0;
372 	int hlen;
373 	struct ip *ip;
374 #ifdef INET6
375 	struct ip6_hdr *ip6;
376 #endif
377 	int family;	/* family on packet, not inpcb/in6pcb! */
378 	struct tcphdr *th;
379 
380 	if (tp != NULL && (flags & TH_RST) == 0) {
381 		if (tp->t_inpcb)
382 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
383 #ifdef INET6
384 		else if (tp->t_in6pcb)
385 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
386 #endif
387 	}
388 
389 	ip = NULL;
390 #ifdef INET6
391 	ip6 = NULL;
392 #endif
393 	if (m == 0) {
394 		if (!template)
395 			return EINVAL;
396 
397 		/* get family information from template */
398 		switch (mtod(template, struct ip *)->ip_v) {
399 		case 4:
400 			family = AF_INET;
401 			hlen = sizeof(struct ip);
402 			break;
403 #ifdef INET6
404 		case 6:
405 			family = AF_INET6;
406 			hlen = sizeof(struct ip6_hdr);
407 			break;
408 #endif
409 		default:
410 			return EAFNOSUPPORT;
411 		}
412 
413 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
414 		if (m) {
415 			MCLGET(m, M_DONTWAIT);
416 			if ((m->m_flags & M_EXT) == 0) {
417 				m_free(m);
418 				m = NULL;
419 			}
420 		}
421 		if (m == NULL)
422 			return (ENOBUFS);
423 
424 		if (tcp_compat_42)
425 			tlen = 1;
426 		else
427 			tlen = 0;
428 
429 		m->m_data += max_linkhdr;
430 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
431 			template->m_len);
432 		switch (family) {
433 		case AF_INET:
434 			ip = mtod(m, struct ip *);
435 			th = (struct tcphdr *)(ip + 1);
436 			break;
437 #ifdef INET6
438 		case AF_INET6:
439 			ip6 = mtod(m, struct ip6_hdr *);
440 			th = (struct tcphdr *)(ip6 + 1);
441 			break;
442 #endif
443 #if 0
444 		default:
445 			/* noone will visit here */
446 			m_freem(m);
447 			return EAFNOSUPPORT;
448 #endif
449 		}
450 		flags = TH_ACK;
451 	} else {
452 		/* get family information from m */
453 		switch (mtod(m, struct ip *)->ip_v) {
454 		case 4:
455 			family = AF_INET;
456 			hlen = sizeof(struct ip);
457 			break;
458 #ifdef INET6
459 		case 6:
460 			family = AF_INET6;
461 			hlen = sizeof(struct ip6_hdr);
462 			break;
463 #endif
464 		default:
465 			m_freem(m);
466 			return EAFNOSUPPORT;
467 		}
468 
469 		/* template pointer almost has no meaning */
470 		m_freem(m->m_next);
471 		m->m_next = 0;
472 		m->m_len = hlen + sizeof(struct tcphdr);
473 		if ((m->m_flags & M_PKTHDR) == 0) {
474 			printf("non PKTHDR to tcp_respond\n");
475 			m_freem(m);
476 			return EINVAL;
477 		}
478 
479 		tlen = 0;
480 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
481 		switch (family) {
482 		case AF_INET:
483 			ip = mtod(m, struct ip *);
484 			th = (struct tcphdr *)(ip + 1);
485 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
486 			ip->ip_p = IPPROTO_TCP;
487 			break;
488 #ifdef INET6
489 		case AF_INET6:
490 			ip6 = mtod(m, struct ip6_hdr *);
491 			th = (struct tcphdr *)(ip6 + 1);
492 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
493 			ip6->ip6_nxt = IPPROTO_TCP;
494 			break;
495 #endif
496 		}
497 		*th = *th0;
498 		xchg(th->th_dport, th->th_sport, u_int16_t);
499 #undef xchg
500 	}
501 	th->th_seq = htonl(seq);
502 	th->th_ack = htonl(ack);
503 	th->th_x2 = 0;
504 	if ((flags & TH_SYN) == 0) {
505 		if (tp)
506 			win >>= tp->rcv_scale;
507 		if (win > TCP_MAXWIN)
508 			win = TCP_MAXWIN;
509 		th->th_win = htons((u_int16_t)win);
510 		th->th_off = sizeof (struct tcphdr) >> 2;
511 		tlen += sizeof (struct tcphdr);
512 	} else
513 		tlen += th->th_off << 2;
514 	m->m_len = hlen + tlen;
515 	m->m_pkthdr.len = hlen + tlen;
516 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
517 	th->th_flags = flags;
518 	th->th_urp = 0;
519 
520 	switch (family) {
521 	case AF_INET:
522 	    {
523 		struct ipovly *ipov = (struct ipovly *)ip;
524 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
525 		ipov->ih_len = htons((u_int16_t)tlen);
526 
527 		th->th_sum = 0;
528 		th->th_sum = in_cksum(m, hlen + tlen);
529 		ip->ip_len = hlen + tlen;	/*will be flipped on output*/
530 		ip->ip_ttl = ip_defttl;
531 		break;
532 	    }
533 #ifdef INET6
534 	case AF_INET6:
535 	    {
536 		th->th_sum = 0;
537 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
538 				tlen);
539 		ip6->ip6_plen = ntohs(tlen);
540 		if (tp && tp->t_in6pcb) {
541 			struct ifnet *oifp;
542 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
543 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
544 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
545 		} else
546 			ip6->ip6_hlim = ip6_defhlim;
547 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
548 		if (ip6_auto_flowlabel) {
549 			ip6->ip6_flow |=
550 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
551 		}
552 		break;
553 	    }
554 #endif
555 	}
556 
557 #ifdef IPSEC
558 	ipsec_setsocket(m, NULL);
559 #endif /*IPSEC*/
560 
561 	/*
562 	 * If we're doing Path MTU discovery, we need to set DF unless
563 	 * the route's MTU is locked.  If we lack a route, we need to
564 	 * look it up now.
565 	 *
566 	 * ip_output() could do this for us, but it's convenient to just
567 	 * do it here unconditionally.
568 	 */
569 	if (tp != NULL && tp->t_inpcb != NULL) {
570 		ro = &tp->t_inpcb->inp_route;
571 #ifdef IPSEC
572 		ipsec_setsocket(m, tp->t_inpcb->inp_socket);
573 #endif
574 #ifdef DIAGNOSTIC
575 		if (family != AF_INET)
576 			panic("tcp_respond: address family mismatch");
577 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
578 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
579 			    ntohl(ip->ip_dst.s_addr),
580 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
581 		}
582 #endif
583 	}
584 #ifdef INET6
585 	else if (tp != NULL && tp->t_in6pcb != NULL) {
586 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
587 #ifdef IPSEC
588 		ipsec_setsocket(m, tp->t_in6pcb->in6p_socket);
589 #endif
590 #ifdef DIAGNOSTIC
591 		if (family == AF_INET) {
592 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
593 				panic("tcp_respond: not mapped addr");
594 			if (bcmp(&ip->ip_dst,
595 					&tp->t_in6pcb->in6p_faddr.s6_addr32[3],
596 					sizeof(ip->ip_dst)) != 0) {
597 				panic("tcp_respond: ip_dst != in6p_faddr");
598 			}
599 		} else if (family == AF_INET6) {
600 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &tp->t_in6pcb->in6p_faddr))
601 				panic("tcp_respond: ip6_dst != in6p_faddr");
602 		} else
603 			panic("tcp_respond: address family mismatch");
604 #endif
605 	}
606 #endif
607 	else {
608 		ro = (struct route *)&iproute;
609 		bzero(ro, sizeof(iproute));
610 	}
611 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
612 		if (ro->ro_rt != NULL) {
613 			RTFREE(ro->ro_rt);
614 			ro->ro_rt = NULL;
615 		}
616 		switch (family) {
617 		case AF_INET:
618 		    {
619 			struct sockaddr_in *dst;
620 			dst = satosin(&ro->ro_dst);
621 			dst->sin_family = AF_INET;
622 			dst->sin_len = sizeof(*dst);
623 			dst->sin_addr = ip->ip_dst;
624 			break;
625 		    }
626 #ifdef INET6
627 		case AF_INET6:
628 		    {
629 			struct sockaddr_in6 *dst;
630 			dst = satosin6(&ro->ro_dst);
631 			bzero(dst, sizeof(*dst));
632 			dst->sin6_family = AF_INET6;
633 			dst->sin6_len = sizeof(*dst);
634 			dst->sin6_addr = ip6->ip6_dst;
635 			break;
636 		    }
637 #endif
638 		}
639 		rtalloc(ro);
640 		if ((rt = ro->ro_rt) == NULL) {
641 			m_freem(m);
642 			switch (family) {
643 			case AF_INET:
644 				ipstat.ips_noroute++;
645 				break;
646 #ifdef INET6
647 			case AF_INET6:
648 				ip6stat.ip6s_noroute++;
649 				break;
650 #endif
651 			}
652 			return (EHOSTUNREACH);
653 		}
654 	}
655 	switch (family) {
656 	case AF_INET:
657 		if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
658 			ip->ip_off |= IP_DF;
659 
660 		error = ip_output(m, NULL, ro, 0, NULL);
661 		break;
662 #ifdef INET6
663 	case AF_INET6:
664 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL,
665 			NULL);
666 		break;
667 #endif
668 	default:
669 		error = EAFNOSUPPORT;
670 		break;
671 	}
672 
673 	if (ro == (struct route *)&iproute) {
674 		RTFREE(ro->ro_rt);
675 		ro->ro_rt = NULL;
676 	}
677 
678 	return (error);
679 }
680 
681 /*
682  * Create a new TCP control block, making an
683  * empty reassembly queue and hooking it to the argument
684  * protocol control block.
685  */
686 struct tcpcb *
687 tcp_newtcpcb(family, aux)
688 	int family;	/* selects inpcb, or in6pcb */
689 	void *aux;
690 {
691 	register struct tcpcb *tp;
692 
693 	switch (family) {
694 	case PF_INET:
695 		break;
696 #ifdef INET6
697 	case PF_INET6:
698 		break;
699 #endif
700 	default:
701 		return NULL;
702 	}
703 
704 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
705 	if (tp == NULL)
706 		return (NULL);
707 	bzero((caddr_t)tp, sizeof(struct tcpcb));
708 	LIST_INIT(&tp->segq);
709 	LIST_INIT(&tp->timeq);
710 	tp->t_family = family;		/* may be overridden later on */
711 	tp->t_peermss = tcp_mssdflt;
712 	tp->t_ourmss = tcp_mssdflt;
713 	tp->t_segsz = tcp_mssdflt;
714 	LIST_INIT(&tp->t_sc);
715 
716 	tp->t_flags = 0;
717 	if (tcp_do_rfc1323 && tcp_do_win_scale)
718 		tp->t_flags |= TF_REQ_SCALE;
719 	if (tcp_do_rfc1323 && tcp_do_timestamps)
720 		tp->t_flags |= TF_REQ_TSTMP;
721 	if (tcp_do_sack == 2)
722 		tp->t_flags |= TF_WILL_SACK;
723 	else if (tcp_do_sack == 1)
724 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
725 	tp->t_flags |= TF_CANT_TXSACK;
726 	switch (family) {
727 	case PF_INET:
728 		tp->t_inpcb = (struct inpcb *)aux;
729 		break;
730 #ifdef INET6
731 	case PF_INET6:
732 		tp->t_in6pcb = (struct in6pcb *)aux;
733 		break;
734 #endif
735 	}
736 	/*
737 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
738 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
739 	 * reasonable initial retransmit time.
740 	 */
741 	tp->t_srtt = TCPTV_SRTTBASE;
742 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
743 	tp->t_rttmin = TCPTV_MIN;
744 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
745 	    TCPTV_MIN, TCPTV_REXMTMAX);
746 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
747 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
748 	if (family == AF_INET) {
749 		struct inpcb *inp = (struct inpcb *)aux;
750 		inp->inp_ip.ip_ttl = ip_defttl;
751 		inp->inp_ppcb = (caddr_t)tp;
752 	}
753 #ifdef INET6
754 	else if (family == AF_INET6) {
755 		struct in6pcb *in6p = (struct in6pcb *)aux;
756 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
757 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
758 					       : NULL);
759 		in6p->in6p_ppcb = (caddr_t)tp;
760 	}
761 #endif
762 	return (tp);
763 }
764 
765 /*
766  * Drop a TCP connection, reporting
767  * the specified error.  If connection is synchronized,
768  * then send a RST to peer.
769  */
770 struct tcpcb *
771 tcp_drop(tp, errno)
772 	register struct tcpcb *tp;
773 	int errno;
774 {
775 	struct socket *so;
776 
777 	if (tp->t_inpcb)
778 		so = tp->t_inpcb->inp_socket;
779 #ifdef INET6
780 	else if (tp->t_in6pcb)
781 		so = tp->t_in6pcb->in6p_socket;
782 #endif
783 	else
784 		return NULL;
785 
786 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
787 		tp->t_state = TCPS_CLOSED;
788 		(void) tcp_output(tp);
789 		tcpstat.tcps_drops++;
790 	} else
791 		tcpstat.tcps_conndrops++;
792 	if (errno == ETIMEDOUT && tp->t_softerror)
793 		errno = tp->t_softerror;
794 	so->so_error = errno;
795 	return (tcp_close(tp));
796 }
797 
798 /*
799  * Close a TCP control block:
800  *	discard all space held by the tcp
801  *	discard internet protocol block
802  *	wake up any sleepers
803  */
804 struct tcpcb *
805 tcp_close(tp)
806 	register struct tcpcb *tp;
807 {
808 	struct inpcb *inp;
809 #ifdef INET6
810 	struct in6pcb *in6p;
811 #endif
812 	struct socket *so;
813 #ifdef RTV_RTT
814 	register struct rtentry *rt;
815 #endif
816 	struct route *ro;
817 
818 	inp = tp->t_inpcb;
819 #ifdef INET6
820 	in6p = tp->t_in6pcb;
821 #endif
822 	so = NULL;
823 	ro = NULL;
824 	if (inp) {
825 		so = inp->inp_socket;
826 		ro = &inp->inp_route;
827 	}
828 #ifdef INET6
829 	else if (in6p) {
830 		so = in6p->in6p_socket;
831 		ro = (struct route *)&in6p->in6p_route;
832 	}
833 #endif
834 
835 #ifdef RTV_RTT
836 	/*
837 	 * If we sent enough data to get some meaningful characteristics,
838 	 * save them in the routing entry.  'Enough' is arbitrarily
839 	 * defined as the sendpipesize (default 4K) * 16.  This would
840 	 * give us 16 rtt samples assuming we only get one sample per
841 	 * window (the usual case on a long haul net).  16 samples is
842 	 * enough for the srtt filter to converge to within 5% of the correct
843 	 * value; fewer samples and we could save a very bogus rtt.
844 	 *
845 	 * Don't update the default route's characteristics and don't
846 	 * update anything that the user "locked".
847 	 */
848 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
849 	    ro && (rt = ro->ro_rt) &&
850 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
851 		register u_long i = 0;
852 
853 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
854 			i = tp->t_srtt *
855 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
856 			if (rt->rt_rmx.rmx_rtt && i)
857 				/*
858 				 * filter this update to half the old & half
859 				 * the new values, converting scale.
860 				 * See route.h and tcp_var.h for a
861 				 * description of the scaling constants.
862 				 */
863 				rt->rt_rmx.rmx_rtt =
864 				    (rt->rt_rmx.rmx_rtt + i) / 2;
865 			else
866 				rt->rt_rmx.rmx_rtt = i;
867 		}
868 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
869 			i = tp->t_rttvar *
870 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
871 			if (rt->rt_rmx.rmx_rttvar && i)
872 				rt->rt_rmx.rmx_rttvar =
873 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
874 			else
875 				rt->rt_rmx.rmx_rttvar = i;
876 		}
877 		/*
878 		 * update the pipelimit (ssthresh) if it has been updated
879 		 * already or if a pipesize was specified & the threshhold
880 		 * got below half the pipesize.  I.e., wait for bad news
881 		 * before we start updating, then update on both good
882 		 * and bad news.
883 		 */
884 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
885 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
886 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
887 			/*
888 			 * convert the limit from user data bytes to
889 			 * packets then to packet data bytes.
890 			 */
891 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
892 			if (i < 2)
893 				i = 2;
894 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
895 			if (rt->rt_rmx.rmx_ssthresh)
896 				rt->rt_rmx.rmx_ssthresh =
897 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
898 			else
899 				rt->rt_rmx.rmx_ssthresh = i;
900 		}
901 	}
902 #endif /* RTV_RTT */
903 	/* free the reassembly queue, if any */
904 	TCP_REASS_LOCK(tp);
905 	(void) tcp_freeq(tp);
906 	TCP_REASS_UNLOCK(tp);
907 
908 	TCP_CLEAR_DELACK(tp);
909 	syn_cache_cleanup(tp);
910 
911 	if (tp->t_template) {
912 		m_free(tp->t_template);
913 		tp->t_template = NULL;
914 	}
915 	pool_put(&tcpcb_pool, tp);
916 	if (inp) {
917 		inp->inp_ppcb = 0;
918 		soisdisconnected(so);
919 		in_pcbdetach(inp);
920 	}
921 #ifdef INET6
922 	else if (in6p) {
923 		in6p->in6p_ppcb = 0;
924 		soisdisconnected(so);
925 		in6_pcbdetach(in6p);
926 	}
927 #endif
928 	tcpstat.tcps_closed++;
929 	return ((struct tcpcb *)0);
930 }
931 
932 int
933 tcp_freeq(tp)
934 	struct tcpcb *tp;
935 {
936 	register struct ipqent *qe;
937 	int rv = 0;
938 #ifdef TCPREASS_DEBUG
939 	int i = 0;
940 #endif
941 
942 	TCP_REASS_LOCK_CHECK(tp);
943 
944 	while ((qe = tp->segq.lh_first) != NULL) {
945 #ifdef TCPREASS_DEBUG
946 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
947 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
948 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
949 #endif
950 		LIST_REMOVE(qe, ipqe_q);
951 		LIST_REMOVE(qe, ipqe_timeq);
952 		m_freem(qe->ipqe_m);
953 		pool_put(&ipqent_pool, qe);
954 		rv = 1;
955 	}
956 	return (rv);
957 }
958 
959 /*
960  * Protocol drain routine.  Called when memory is in short supply.
961  */
962 void
963 tcp_drain()
964 {
965 	register struct inpcb *inp;
966 	register struct tcpcb *tp;
967 
968 	/*
969 	 * Free the sequence queue of all TCP connections.
970 	 */
971 	inp = tcbtable.inpt_queue.cqh_first;
972 	if (inp)						/* XXX */
973 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue;
974 	    inp = inp->inp_queue.cqe_next) {
975 		if ((tp = intotcpcb(inp)) != NULL) {
976 			/*
977 			 * We may be called from a device's interrupt
978 			 * context.  If the tcpcb is already busy,
979 			 * just bail out now.
980 			 */
981 			if (tcp_reass_lock_try(tp) == 0)
982 				continue;
983 			if (tcp_freeq(tp))
984 				tcpstat.tcps_connsdrained++;
985 			TCP_REASS_UNLOCK(tp);
986 		}
987 	}
988 }
989 
990 /*
991  * Notify a tcp user of an asynchronous error;
992  * store error as soft error, but wake up user
993  * (for now, won't do anything until can select for soft error).
994  */
995 void
996 tcp_notify(inp, error)
997 	struct inpcb *inp;
998 	int error;
999 {
1000 	register struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1001 	register struct socket *so = inp->inp_socket;
1002 
1003 	/*
1004 	 * Ignore some errors if we are hooked up.
1005 	 * If connection hasn't completed, has retransmitted several times,
1006 	 * and receives a second error, give up now.  This is better
1007 	 * than waiting a long time to establish a connection that
1008 	 * can never complete.
1009 	 */
1010 	if (tp->t_state == TCPS_ESTABLISHED &&
1011 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1012 	      error == EHOSTDOWN)) {
1013 		return;
1014 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1015 	    tp->t_rxtshift > 3 && tp->t_softerror)
1016 		so->so_error = error;
1017 	else
1018 		tp->t_softerror = error;
1019 	wakeup((caddr_t) &so->so_timeo);
1020 	sorwakeup(so);
1021 	sowwakeup(so);
1022 }
1023 
1024 #if defined(INET6) && !defined(TCP6)
1025 void
1026 tcp6_notify(in6p, error)
1027 	struct in6pcb *in6p;
1028 	int error;
1029 {
1030 	register struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1031 	register struct socket *so = in6p->in6p_socket;
1032 
1033 	/*
1034 	 * Ignore some errors if we are hooked up.
1035 	 * If connection hasn't completed, has retransmitted several times,
1036 	 * and receives a second error, give up now.  This is better
1037 	 * than waiting a long time to establish a connection that
1038 	 * can never complete.
1039 	 */
1040 	if (tp->t_state == TCPS_ESTABLISHED &&
1041 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1042 	      error == EHOSTDOWN)) {
1043 		return;
1044 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1045 	    tp->t_rxtshift > 3 && tp->t_softerror)
1046 		so->so_error = error;
1047 	else
1048 		tp->t_softerror = error;
1049 	wakeup((caddr_t) &so->so_timeo);
1050 	sorwakeup(so);
1051 	sowwakeup(so);
1052 }
1053 #endif
1054 
1055 #if defined(INET6) && !defined(TCP6)
1056 void
1057 tcp6_ctlinput(cmd, sa, d)
1058 	int cmd;
1059 	struct sockaddr *sa;
1060 	void *d;
1061 {
1062 	register struct tcphdr *thp;
1063 	struct tcphdr th;
1064 	void (*notify) __P((struct in6pcb *, int)) = tcp6_notify;
1065 	int nmatch;
1066 	extern struct in6_addr zeroin6_addr;	/* netinet6/in6_pcb.c */
1067 	struct sockaddr_in6 sa6;
1068 	register struct ip6_hdr *ip6;
1069 	struct mbuf *m;
1070 	int off;
1071 
1072 	if (sa->sa_family != AF_INET6 ||
1073 	    sa->sa_len != sizeof(struct sockaddr_in6))
1074 		return;
1075 	if ((unsigned)cmd >= PRC_NCMDS)
1076 		return;
1077 	else if (cmd == PRC_QUENCH) {
1078 		/* XXX there's no PRC_QUENCH in IPv6 */
1079 		notify = tcp6_quench;
1080 	} else if (PRC_IS_REDIRECT(cmd))
1081 		notify = in6_rtchange, d = NULL;
1082 	else if (cmd == PRC_MSGSIZE)
1083 		notify = tcp6_mtudisc, d = NULL;
1084 	else if (cmd == PRC_HOSTDEAD)
1085 		d = NULL;
1086 	else if (inet6ctlerrmap[cmd] == 0)
1087 		return;
1088 
1089 	/* if the parameter is from icmp6, decode it. */
1090 	if (d != NULL) {
1091 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1092 		m = ip6cp->ip6c_m;
1093 		ip6 = ip6cp->ip6c_ip6;
1094 		off = ip6cp->ip6c_off;
1095 	} else {
1096 		m = NULL;
1097 		ip6 = NULL;
1098 	}
1099 
1100 	/* translate addresses into internal form */
1101 	sa6 = *(struct sockaddr_in6 *)sa;
1102 	if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr) && m && m->m_pkthdr.rcvif)
1103 		sa6.sin6_addr.s6_addr16[1] = htons(m->m_pkthdr.rcvif->if_index);
1104 
1105 	if (ip6) {
1106 		/*
1107 		 * XXX: We assume that when ip6 is non NULL,
1108 		 * M and OFF are valid.
1109 		 */
1110 		struct in6_addr s;
1111 
1112 		/* translate addresses into internal form */
1113 		memcpy(&s, &ip6->ip6_src, sizeof(s));
1114 		if (IN6_IS_ADDR_LINKLOCAL(&s))
1115 			s.s6_addr16[1] = htons(m->m_pkthdr.rcvif->if_index);
1116 
1117 		if (m->m_len < off + sizeof(th)) {
1118 			/*
1119 			 * this should be rare case,
1120 			 * so we compromise on this copy...
1121 			 */
1122 			m_copydata(m, off, sizeof(th), (caddr_t)&th);
1123 			thp = &th;
1124 		} else
1125 			thp = (struct tcphdr *)(mtod(m, caddr_t) + off);
1126 		nmatch = in6_pcbnotify(&tcb6, (struct sockaddr *)&sa6,
1127 		    thp->th_dport, &s, thp->th_sport, cmd, notify);
1128 		if (nmatch == 0 && syn_cache_count &&
1129 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1130 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1131 		     inet6ctlerrmap[cmd] == EHOSTDOWN)) {
1132 			struct sockaddr_in6 sin6;
1133 			bzero(&sin6, sizeof(sin6));
1134 			sin6.sin6_len = sizeof(sin6);
1135 			sin6.sin6_family = AF_INET6;
1136 			sin6.sin6_port = thp->th_sport;
1137 			sin6.sin6_addr = s;
1138 			syn_cache_unreach((struct sockaddr *)&sin6, sa, thp);
1139 		}
1140 	} else {
1141 		(void) in6_pcbnotify(&tcb6, (struct sockaddr *)&sa6, 0,
1142 				     &zeroin6_addr, 0, cmd, notify);
1143 	}
1144 }
1145 #endif
1146 
1147 /* assumes that ip header and tcp header are contiguous on mbuf */
1148 void *
1149 tcp_ctlinput(cmd, sa, v)
1150 	int cmd;
1151 	struct sockaddr *sa;
1152 	register void *v;
1153 {
1154 	register struct ip *ip = v;
1155 	register struct tcphdr *th;
1156 	extern int inetctlerrmap[];
1157 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1158 	int errno;
1159 	int nmatch;
1160 
1161 	if (sa->sa_family != AF_INET ||
1162 	    sa->sa_len != sizeof(struct sockaddr_in))
1163 		return NULL;
1164 	if ((unsigned)cmd >= PRC_NCMDS)
1165 		return NULL;
1166 	errno = inetctlerrmap[cmd];
1167 	if (cmd == PRC_QUENCH)
1168 		notify = tcp_quench;
1169 	else if (PRC_IS_REDIRECT(cmd))
1170 		notify = in_rtchange, ip = 0;
1171 	else if (cmd == PRC_MSGSIZE && ip_mtudisc)
1172 		notify = tcp_mtudisc, ip = 0;
1173 	else if (cmd == PRC_HOSTDEAD)
1174 		ip = 0;
1175 	else if (errno == 0)
1176 		return NULL;
1177 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1178 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1179 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
1180 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1181 		if (nmatch == 0 && syn_cache_count &&
1182 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1183 		    inetctlerrmap[cmd] == ENETUNREACH ||
1184 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1185 			struct sockaddr_in sin;
1186 			bzero(&sin, sizeof(sin));
1187 			sin.sin_len = sizeof(sin);
1188 			sin.sin_family = AF_INET;
1189 			sin.sin_port = th->th_sport;
1190 			sin.sin_addr = ip->ip_src;
1191 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1192 		}
1193 
1194 		/* XXX mapped address case */
1195 	}
1196 	else {
1197 		(void)in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
1198 		    notify);
1199 	}
1200 	return NULL;
1201 }
1202 
1203 /*
1204  * When a source quence is received, we are being notifed of congestion.
1205  * Close the congestion window down to the Loss Window (one segment).
1206  * We will gradually open it again as we proceed.
1207  */
1208 void
1209 tcp_quench(inp, errno)
1210 	struct inpcb *inp;
1211 	int errno;
1212 {
1213 	struct tcpcb *tp = intotcpcb(inp);
1214 
1215 	if (tp)
1216 		tp->snd_cwnd = tp->t_segsz;
1217 }
1218 
1219 #if defined(INET6) && !defined(TCP6)
1220 void
1221 tcp6_quench(in6p, errno)
1222 	struct in6pcb *in6p;
1223 	int errno;
1224 {
1225 	struct tcpcb *tp = in6totcpcb(in6p);
1226 
1227 	if (tp)
1228 		tp->snd_cwnd = tp->t_segsz;
1229 }
1230 #endif
1231 
1232 /*
1233  * On receipt of path MTU corrections, flush old route and replace it
1234  * with the new one.  Retransmit all unacknowledged packets, to ensure
1235  * that all packets will be received.
1236  */
1237 void
1238 tcp_mtudisc(inp, errno)
1239 	struct inpcb *inp;
1240 	int errno;
1241 {
1242 	struct tcpcb *tp = intotcpcb(inp);
1243 	struct rtentry *rt = in_pcbrtentry(inp);
1244 
1245 	if (tp != 0) {
1246 		if (rt != 0) {
1247 			/*
1248 			 * If this was not a host route, remove and realloc.
1249 			 */
1250 			if ((rt->rt_flags & RTF_HOST) == 0) {
1251 				in_rtchange(inp, errno);
1252 				if ((rt = in_pcbrtentry(inp)) == 0)
1253 					return;
1254 			}
1255 
1256 			/*
1257 			 * Slow start out of the error condition.  We
1258 			 * use the MTU because we know it's smaller
1259 			 * than the previously transmitted segment.
1260 			 *
1261 			 * Note: This is more conservative than the
1262 			 * suggestion in draft-floyd-incr-init-win-03.
1263 			 */
1264 			if (rt->rt_rmx.rmx_mtu != 0)
1265 				tp->snd_cwnd =
1266 				    TCP_INITIAL_WINDOW(tcp_init_win,
1267 				    rt->rt_rmx.rmx_mtu);
1268 		}
1269 
1270 		/*
1271 		 * Resend unacknowledged packets.
1272 		 */
1273 		tp->snd_nxt = tp->snd_una;
1274 		tcp_output(tp);
1275 	}
1276 }
1277 
1278 #if defined(INET6) && !defined(TCP6)
1279 void
1280 tcp6_mtudisc(in6p, errno)
1281 	struct in6pcb *in6p;
1282 	int errno;
1283 {
1284 	struct tcpcb *tp = in6totcpcb(in6p);
1285 	struct rtentry *rt = in6_pcbrtentry(in6p);
1286 
1287 	if (tp != 0) {
1288 		if (rt != 0) {
1289 			/*
1290 			 * If this was not a host route, remove and realloc.
1291 			 */
1292 			if ((rt->rt_flags & RTF_HOST) == 0) {
1293 				in6_rtchange(in6p, errno);
1294 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1295 					return;
1296 			}
1297 
1298 			/*
1299 			 * Slow start out of the error condition.  We
1300 			 * use the MTU because we know it's smaller
1301 			 * than the previously transmitted segment.
1302 			 *
1303 			 * Note: This is more conservative than the
1304 			 * suggestion in draft-floyd-incr-init-win-03.
1305 			 */
1306 			if (rt->rt_rmx.rmx_mtu != 0)
1307 				tp->snd_cwnd =
1308 				    TCP_INITIAL_WINDOW(tcp_init_win,
1309 				    rt->rt_rmx.rmx_mtu);
1310 		}
1311 
1312 		/*
1313 		 * Resend unacknowledged packets.
1314 		 */
1315 		tp->snd_nxt = tp->snd_una;
1316 		tcp_output(tp);
1317 	}
1318 }
1319 #endif
1320 
1321 /*
1322  * Compute the MSS to advertise to the peer.  Called only during
1323  * the 3-way handshake.  If we are the server (peer initiated
1324  * connection), we are called with a pointer to the interface
1325  * on which the SYN packet arrived.  If we are the client (we
1326  * initiated connection), we are called with a pointer to the
1327  * interface out which this connection should go.
1328  *
1329  * NOTE: Do not subtract IP option/extension header size nor IPsec
1330  * header size from MSS advertisement.  MSS option must hold the maximum
1331  * segment size we can accept, so it must always be:
1332  *	 max(if mtu) - ip header - tcp header
1333  */
1334 u_long
1335 tcp_mss_to_advertise(ifp, af)
1336 	const struct ifnet *ifp;
1337 	int af;
1338 {
1339 	extern u_long in_maxmtu;
1340 	u_long mss = 0;
1341 	u_long hdrsiz;
1342 
1343 	/*
1344 	 * In order to avoid defeating path MTU discovery on the peer,
1345 	 * we advertise the max MTU of all attached networks as our MSS,
1346 	 * per RFC 1191, section 3.1.
1347 	 *
1348 	 * We provide the option to advertise just the MTU of
1349 	 * the interface on which we hope this connection will
1350 	 * be receiving.  If we are responding to a SYN, we
1351 	 * will have a pretty good idea about this, but when
1352 	 * initiating a connection there is a bit more doubt.
1353 	 *
1354 	 * We also need to ensure that loopback has a large enough
1355 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1356 	 */
1357 
1358 	if (ifp != NULL)
1359 		mss = ifp->if_mtu;
1360 
1361 	if (tcp_mss_ifmtu == 0)
1362 		mss = max(in_maxmtu, mss);
1363 
1364 	switch (af) {
1365 	case AF_INET:
1366 		hdrsiz = sizeof(struct ip);
1367 		break;
1368 #ifdef INET6
1369 	case AF_INET6:
1370 		hdrsiz = sizeof(struct ip6_hdr);
1371 		break;
1372 #endif
1373 	default:
1374 		hdrsiz = 0;
1375 		break;
1376 	}
1377 	hdrsiz += sizeof(struct tcphdr);
1378 	if (mss > hdrsiz)
1379 		mss -= hdrsiz;
1380 
1381 	mss = max(tcp_mssdflt, mss);
1382 	return (mss);
1383 }
1384 
1385 /*
1386  * Set connection variables based on the peer's advertised MSS.
1387  * We are passed the TCPCB for the actual connection.  If we
1388  * are the server, we are called by the compressed state engine
1389  * when the 3-way handshake is complete.  If we are the client,
1390  * we are called when we recieve the SYN,ACK from the server.
1391  *
1392  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1393  * before this routine is called!
1394  */
1395 void
1396 tcp_mss_from_peer(tp, offer)
1397 	struct tcpcb *tp;
1398 	int offer;
1399 {
1400 	struct socket *so;
1401 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1402 	struct rtentry *rt;
1403 #endif
1404 	u_long bufsize;
1405 	int mss;
1406 
1407 	so = NULL;
1408 	rt = NULL;
1409 	if (tp->t_inpcb) {
1410 		so = tp->t_inpcb->inp_socket;
1411 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1412 		rt = in_pcbrtentry(tp->t_inpcb);
1413 #endif
1414 	}
1415 #ifdef INET6
1416 	else if (tp->t_in6pcb) {
1417 		so = tp->t_in6pcb->in6p_socket;
1418 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1419 #ifdef TCP6
1420 		rt = NULL;
1421 #else
1422 		rt = in6_pcbrtentry(tp->t_in6pcb);
1423 #endif
1424 #endif
1425 	}
1426 #endif
1427 
1428 	/*
1429 	 * As per RFC1122, use the default MSS value, unless they
1430 	 * sent us an offer.  Do not accept offers less than 32 bytes.
1431 	 */
1432 	mss = tcp_mssdflt;
1433 	if (offer)
1434 		mss = offer;
1435 	mss = max(mss, 32);		/* sanity */
1436 	tp->t_peermss = mss;
1437 	mss -= tcp_optlen(tp);
1438 	if (tp->t_inpcb)
1439 		mss -= ip_optlen(tp->t_inpcb);
1440 #ifdef INET6
1441 	else if (tp->t_in6pcb)
1442 		mss -= ip6_optlen(tp->t_in6pcb);
1443 #endif
1444 
1445 	/*
1446 	 * If there's a pipesize, change the socket buffer to that size.
1447 	 * Make the socket buffer an integral number of MSS units.  If
1448 	 * the MSS is larger than the socket buffer, artificially decrease
1449 	 * the MSS.
1450 	 */
1451 #ifdef RTV_SPIPE
1452 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
1453 		bufsize = rt->rt_rmx.rmx_sendpipe;
1454 	else
1455 #endif
1456 		bufsize = so->so_snd.sb_hiwat;
1457 	if (bufsize < mss)
1458 		mss = bufsize;
1459 	else {
1460 		bufsize = roundup(bufsize, mss);
1461 		if (bufsize > sb_max)
1462 			bufsize = sb_max;
1463 		(void) sbreserve(&so->so_snd, bufsize);
1464 	}
1465 	tp->t_segsz = mss;
1466 
1467 #ifdef RTV_SSTHRESH
1468 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
1469 		/*
1470 		 * There's some sort of gateway or interface buffer
1471 		 * limit on the path.  Use this to set the slow
1472 		 * start threshold, but set the threshold to no less
1473 		 * than 2 * MSS.
1474 		 */
1475 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1476 	}
1477 #endif
1478 }
1479 
1480 /*
1481  * Processing necessary when a TCP connection is established.
1482  */
1483 void
1484 tcp_established(tp)
1485 	struct tcpcb *tp;
1486 {
1487 	struct socket *so;
1488 #ifdef RTV_RPIPE
1489 	struct rtentry *rt;
1490 #endif
1491 	u_long bufsize;
1492 
1493 	so = NULL;
1494 	rt = NULL;
1495 	if (tp->t_inpcb) {
1496 		so = tp->t_inpcb->inp_socket;
1497 #if defined(RTV_RPIPE)
1498 		rt = in_pcbrtentry(tp->t_inpcb);
1499 #endif
1500 	}
1501 #ifdef INET6
1502 	else if (tp->t_in6pcb) {
1503 		so = tp->t_in6pcb->in6p_socket;
1504 #if defined(RTV_RPIPE)
1505 #ifdef TCP6
1506 		rt = NULL;
1507 #else
1508 		rt = in6_pcbrtentry(tp->t_in6pcb);
1509 #endif
1510 #endif
1511 	}
1512 #endif
1513 
1514 	tp->t_state = TCPS_ESTABLISHED;
1515 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1516 
1517 #ifdef RTV_RPIPE
1518 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
1519 		bufsize = rt->rt_rmx.rmx_recvpipe;
1520 	else
1521 #endif
1522 		bufsize = so->so_rcv.sb_hiwat;
1523 	if (bufsize > tp->t_ourmss) {
1524 		bufsize = roundup(bufsize, tp->t_ourmss);
1525 		if (bufsize > sb_max)
1526 			bufsize = sb_max;
1527 		(void) sbreserve(&so->so_rcv, bufsize);
1528 	}
1529 }
1530 
1531 /*
1532  * Check if there's an initial rtt or rttvar.  Convert from the
1533  * route-table units to scaled multiples of the slow timeout timer.
1534  * Called only during the 3-way handshake.
1535  */
1536 void
1537 tcp_rmx_rtt(tp)
1538 	struct tcpcb *tp;
1539 {
1540 #ifdef RTV_RTT
1541 	struct rtentry *rt = NULL;
1542 	int rtt;
1543 
1544 	if (tp->t_inpcb)
1545 		rt = in_pcbrtentry(tp->t_inpcb);
1546 #ifdef INET6
1547 	else if (tp->t_in6pcb) {
1548 #ifdef TCP6
1549 		rt = NULL;
1550 #else
1551 		rt = in6_pcbrtentry(tp->t_in6pcb);
1552 #endif
1553 	}
1554 #endif
1555 	if (rt == NULL)
1556 		return;
1557 
1558 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1559 		/*
1560 		 * XXX The lock bit for MTU indicates that the value
1561 		 * is also a minimum value; this is subject to time.
1562 		 */
1563 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1564 			TCPT_RANGESET(tp->t_rttmin,
1565 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
1566 			    TCPTV_MIN, TCPTV_REXMTMAX);
1567 		tp->t_srtt = rtt /
1568 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1569 		if (rt->rt_rmx.rmx_rttvar) {
1570 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1571 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
1572 				(TCP_RTTVAR_SHIFT + 2));
1573 		} else {
1574 			/* Default variation is +- 1 rtt */
1575 			tp->t_rttvar =
1576 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
1577 		}
1578 		TCPT_RANGESET(tp->t_rxtcur,
1579 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
1580 		    tp->t_rttmin, TCPTV_REXMTMAX);
1581 	}
1582 #endif
1583 }
1584 
1585 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
1586 
1587 /*
1588  * Get a new sequence value given a tcp control block
1589  */
1590 tcp_seq
1591 tcp_new_iss(tp, len, addin)
1592 	void            *tp;
1593 	u_long           len;
1594 	tcp_seq		 addin;
1595 {
1596 	tcp_seq          tcp_iss;
1597 
1598 	/*
1599 	 * Randomize.
1600 	 */
1601 #if NRND > 0
1602 	rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
1603 #else
1604 	tcp_iss = random();
1605 #endif
1606 
1607 	/*
1608 	 * If we were asked to add some amount to a known value,
1609 	 * we will take a random value obtained above, mask off the upper
1610 	 * bits, and add in the known value.  We also add in a constant to
1611 	 * ensure that we are at least a certain distance from the original
1612 	 * value.
1613 	 *
1614 	 * This is used when an old connection is in timed wait
1615 	 * and we have a new one coming in, for instance.
1616 	 */
1617 	if (addin != 0) {
1618 #ifdef TCPISS_DEBUG
1619 		printf("Random %08x, ", tcp_iss);
1620 #endif
1621 		tcp_iss &= TCP_ISS_RANDOM_MASK;
1622 		tcp_iss += addin + TCP_ISSINCR;
1623 #ifdef TCPISS_DEBUG
1624 		printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
1625 #endif
1626 	} else {
1627 		tcp_iss &= TCP_ISS_RANDOM_MASK;
1628 		tcp_iss += tcp_iss_seq;
1629 		tcp_iss_seq += TCP_ISSINCR;
1630 #ifdef TCPISS_DEBUG
1631 		printf("ISS %08x\n", tcp_iss);
1632 #endif
1633 	}
1634 
1635 	if (tcp_compat_42) {
1636 		/*
1637 		 * Limit it to the positive range for really old TCP
1638 		 * implementations.
1639 		 */
1640 		if (tcp_iss >= 0x80000000)
1641 			tcp_iss &= 0x7fffffff;		/* XXX */
1642 	}
1643 
1644 	return tcp_iss;
1645 }
1646 
1647 #ifdef IPSEC
1648 /* compute ESP/AH header size for TCP, including outer IP header. */
1649 size_t
1650 ipsec4_hdrsiz_tcp(tp)
1651 	struct tcpcb *tp;
1652 {
1653 	struct inpcb *inp;
1654 	size_t hdrsiz;
1655 
1656 	/* XXX mapped addr case (tp->t_in6pcb) */
1657 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
1658 		return 0;
1659 	switch (tp->t_family) {
1660 	case AF_INET:
1661 		/* XXX: should use currect direction. */
1662 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
1663 		break;
1664 	default:
1665 		hdrsiz = 0;
1666 		break;
1667 	}
1668 
1669 	return hdrsiz;
1670 }
1671 
1672 #if defined(INET6) && !defined(TCP6)
1673 size_t
1674 ipsec6_hdrsiz_tcp(tp)
1675 	struct tcpcb *tp;
1676 {
1677 	struct in6pcb *in6p;
1678 	size_t hdrsiz;
1679 
1680 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
1681 		return 0;
1682 	switch (tp->t_family) {
1683 	case AF_INET6:
1684 		/* XXX: should use currect direction. */
1685 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
1686 		break;
1687 	case AF_INET:
1688 		/* mapped address case - tricky */
1689 	default:
1690 		hdrsiz = 0;
1691 		break;
1692 	}
1693 
1694 	return hdrsiz;
1695 }
1696 #endif
1697 #endif /*IPSEC*/
1698 
1699 /*
1700  * Determine the length of the TCP options for this connection.
1701  *
1702  * XXX:  What do we do for SACK, when we add that?  Just reserve
1703  *       all of the space?  Otherwise we can't exactly be incrementing
1704  *       cwnd by an amount that varies depending on the amount we last
1705  *       had to SACK!
1706  */
1707 
1708 u_int
1709 tcp_optlen(tp)
1710 	struct tcpcb *tp;
1711 {
1712 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
1713 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
1714 		return TCPOLEN_TSTAMP_APPA;
1715 	else
1716 		return 0;
1717 }
1718