xref: /netbsd-src/sys/netinet/tcp_subr.c (revision 28c37e673e4d9b6cbdc7483062b915cc61d1ccf5)
1 /*	$NetBSD: tcp_subr.c,v 1.134 2002/09/25 11:19:23 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, 2000, 2001 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 <sys/cdefs.h>
105 __KERNEL_RCSID(0, "$NetBSD: tcp_subr.c,v 1.134 2002/09/25 11:19:23 itojun Exp $");
106 
107 #include "opt_inet.h"
108 #include "opt_ipsec.h"
109 #include "opt_tcp_compat_42.h"
110 #include "opt_inet_csum.h"
111 #include "rnd.h"
112 
113 #include <sys/param.h>
114 #include <sys/proc.h>
115 #include <sys/systm.h>
116 #include <sys/malloc.h>
117 #include <sys/mbuf.h>
118 #include <sys/socket.h>
119 #include <sys/socketvar.h>
120 #include <sys/protosw.h>
121 #include <sys/errno.h>
122 #include <sys/kernel.h>
123 #include <sys/pool.h>
124 #if NRND > 0
125 #include <sys/md5.h>
126 #include <sys/rnd.h>
127 #endif
128 
129 #include <net/route.h>
130 #include <net/if.h>
131 
132 #include <netinet/in.h>
133 #include <netinet/in_systm.h>
134 #include <netinet/ip.h>
135 #include <netinet/in_pcb.h>
136 #include <netinet/ip_var.h>
137 #include <netinet/ip_icmp.h>
138 
139 #ifdef INET6
140 #ifndef INET
141 #include <netinet/in.h>
142 #endif
143 #include <netinet/ip6.h>
144 #include <netinet6/in6_pcb.h>
145 #include <netinet6/ip6_var.h>
146 #include <netinet6/in6_var.h>
147 #include <netinet6/ip6protosw.h>
148 #include <netinet/icmp6.h>
149 #include <netinet6/nd6.h>
150 #endif
151 
152 #include <netinet/tcp.h>
153 #include <netinet/tcp_fsm.h>
154 #include <netinet/tcp_seq.h>
155 #include <netinet/tcp_timer.h>
156 #include <netinet/tcp_var.h>
157 #include <netinet/tcpip.h>
158 
159 #ifdef IPSEC
160 #include <netinet6/ipsec.h>
161 #endif /*IPSEC*/
162 
163 #ifdef INET6
164 struct in6pcb tcb6;
165 #endif
166 
167 struct	inpcbtable tcbtable;	/* head of queue of active tcpcb's */
168 struct	tcpstat tcpstat;	/* tcp statistics */
169 u_int32_t tcp_now;		/* for RFC 1323 timestamps */
170 
171 /* patchable/settable parameters for tcp */
172 int 	tcp_mssdflt = TCP_MSS;
173 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
174 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
175 #if NRND > 0
176 int	tcp_do_rfc1948 = 0;	/* ISS by cryptographic hash */
177 #endif
178 int	tcp_do_sack = 1;	/* selective acknowledgement */
179 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
180 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
181 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
182 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
183 int	tcp_init_win = 1;
184 int	tcp_mss_ifmtu = 0;
185 #ifdef TCP_COMPAT_42
186 int	tcp_compat_42 = 1;
187 #else
188 int	tcp_compat_42 = 0;
189 #endif
190 int	tcp_rst_ppslim = 100;	/* 100pps */
191 
192 /* tcb hash */
193 #ifndef TCBHASHSIZE
194 #define	TCBHASHSIZE	128
195 #endif
196 int	tcbhashsize = TCBHASHSIZE;
197 
198 /* syn hash parameters */
199 #define	TCP_SYN_HASH_SIZE	293
200 #define	TCP_SYN_BUCKET_SIZE	35
201 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
202 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
203 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
204 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
205 
206 int	tcp_freeq __P((struct tcpcb *));
207 
208 #ifdef INET
209 void	tcp_mtudisc_callback __P((struct in_addr));
210 #endif
211 #ifdef INET6
212 void	tcp6_mtudisc_callback __P((struct in6_addr *));
213 #endif
214 
215 void	tcp_mtudisc __P((struct inpcb *, int));
216 #ifdef INET6
217 void	tcp6_mtudisc __P((struct in6pcb *, int));
218 #endif
219 
220 struct pool tcpcb_pool;
221 
222 #ifdef TCP_CSUM_COUNTERS
223 #include <sys/device.h>
224 
225 struct evcnt tcp_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
226     NULL, "tcp", "hwcsum bad");
227 struct evcnt tcp_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
228     NULL, "tcp", "hwcsum ok");
229 struct evcnt tcp_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
230     NULL, "tcp", "hwcsum data");
231 struct evcnt tcp_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
232     NULL, "tcp", "swcsum");
233 #endif /* TCP_CSUM_COUNTERS */
234 
235 #ifdef TCP_OUTPUT_COUNTERS
236 #include <sys/device.h>
237 
238 struct evcnt tcp_output_bigheader = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
239     NULL, "tcp", "output big header");
240 struct evcnt tcp_output_copysmall = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
241     NULL, "tcp", "output copy small");
242 struct evcnt tcp_output_copybig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
243     NULL, "tcp", "output copy big");
244 struct evcnt tcp_output_refbig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
245     NULL, "tcp", "output reference big");
246 #endif /* TCP_OUTPUT_COUNTERS */
247 
248 #ifdef TCP_REASS_COUNTERS
249 #include <sys/device.h>
250 
251 struct evcnt tcp_reass_ = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
252     NULL, "tcp_reass", "calls");
253 struct evcnt tcp_reass_empty = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
254     &tcp_reass_, "tcp_reass", "insert into empty queue");
255 struct evcnt tcp_reass_iteration[8] = {
256     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", ">7 iterations"),
257     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "1 iteration"),
258     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "2 iterations"),
259     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "3 iterations"),
260     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "4 iterations"),
261     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "5 iterations"),
262     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "6 iterations"),
263     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "7 iterations"),
264 };
265 struct evcnt tcp_reass_prependfirst = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
266     &tcp_reass_, "tcp_reass", "prepend to first");
267 struct evcnt tcp_reass_prepend = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
268     &tcp_reass_, "tcp_reass", "prepend");
269 struct evcnt tcp_reass_insert = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
270     &tcp_reass_, "tcp_reass", "insert");
271 struct evcnt tcp_reass_inserttail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
272     &tcp_reass_, "tcp_reass", "insert at tail");
273 struct evcnt tcp_reass_append = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
274     &tcp_reass_, "tcp_reass", "append");
275 struct evcnt tcp_reass_appendtail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
276     &tcp_reass_, "tcp_reass", "append to tail fragment");
277 struct evcnt tcp_reass_overlaptail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
278     &tcp_reass_, "tcp_reass", "overlap at end");
279 struct evcnt tcp_reass_overlapfront = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
280     &tcp_reass_, "tcp_reass", "overlap at start");
281 struct evcnt tcp_reass_segdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
282     &tcp_reass_, "tcp_reass", "duplicate segment");
283 struct evcnt tcp_reass_fragdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
284     &tcp_reass_, "tcp_reass", "duplicate fragment");
285 
286 #endif /* TCP_REASS_COUNTERS */
287 
288 /*
289  * Tcp initialization
290  */
291 void
292 tcp_init()
293 {
294 	int hlen;
295 
296 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
297 	    NULL);
298 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
299 #ifdef INET6
300 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
301 #endif
302 
303 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
304 #ifdef INET6
305 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
306 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
307 #endif
308 	if (max_protohdr < hlen)
309 		max_protohdr = hlen;
310 	if (max_linkhdr + hlen > MHLEN)
311 		panic("tcp_init");
312 
313 #ifdef INET
314 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
315 #endif
316 #ifdef INET6
317 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
318 #endif
319 
320 	/* Initialize timer state. */
321 	tcp_timer_init();
322 
323 	/* Initialize the compressed state engine. */
324 	syn_cache_init();
325 
326 #ifdef TCP_CSUM_COUNTERS
327 	evcnt_attach_static(&tcp_hwcsum_bad);
328 	evcnt_attach_static(&tcp_hwcsum_ok);
329 	evcnt_attach_static(&tcp_hwcsum_data);
330 	evcnt_attach_static(&tcp_swcsum);
331 #endif /* TCP_CSUM_COUNTERS */
332 
333 #ifdef TCP_OUTPUT_COUNTERS
334 	evcnt_attach_static(&tcp_output_bigheader);
335 	evcnt_attach_static(&tcp_output_copysmall);
336 	evcnt_attach_static(&tcp_output_copybig);
337 	evcnt_attach_static(&tcp_output_refbig);
338 #endif /* TCP_OUTPUT_COUNTERS */
339 
340 #ifdef TCP_REASS_COUNTERS
341 	evcnt_attach_static(&tcp_reass_);
342 	evcnt_attach_static(&tcp_reass_empty);
343 	evcnt_attach_static(&tcp_reass_iteration[0]);
344 	evcnt_attach_static(&tcp_reass_iteration[1]);
345 	evcnt_attach_static(&tcp_reass_iteration[2]);
346 	evcnt_attach_static(&tcp_reass_iteration[3]);
347 	evcnt_attach_static(&tcp_reass_iteration[4]);
348 	evcnt_attach_static(&tcp_reass_iteration[5]);
349 	evcnt_attach_static(&tcp_reass_iteration[6]);
350 	evcnt_attach_static(&tcp_reass_iteration[7]);
351 	evcnt_attach_static(&tcp_reass_prependfirst);
352 	evcnt_attach_static(&tcp_reass_prepend);
353 	evcnt_attach_static(&tcp_reass_insert);
354 	evcnt_attach_static(&tcp_reass_inserttail);
355 	evcnt_attach_static(&tcp_reass_append);
356 	evcnt_attach_static(&tcp_reass_appendtail);
357 	evcnt_attach_static(&tcp_reass_overlaptail);
358 	evcnt_attach_static(&tcp_reass_overlapfront);
359 	evcnt_attach_static(&tcp_reass_segdup);
360 	evcnt_attach_static(&tcp_reass_fragdup);
361 #endif /* TCP_REASS_COUNTERS */
362 }
363 
364 /*
365  * Create template to be used to send tcp packets on a connection.
366  * Call after host entry created, allocates an mbuf and fills
367  * in a skeletal tcp/ip header, minimizing the amount of work
368  * necessary when the connection is used.
369  */
370 struct mbuf *
371 tcp_template(tp)
372 	struct tcpcb *tp;
373 {
374 	struct inpcb *inp = tp->t_inpcb;
375 #ifdef INET6
376 	struct in6pcb *in6p = tp->t_in6pcb;
377 #endif
378 	struct tcphdr *n;
379 	struct mbuf *m;
380 	int hlen;
381 
382 	switch (tp->t_family) {
383 	case AF_INET:
384 		hlen = sizeof(struct ip);
385 		if (inp)
386 			break;
387 #ifdef INET6
388 		if (in6p) {
389 			/* mapped addr case */
390 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
391 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
392 				break;
393 		}
394 #endif
395 		return NULL;	/*EINVAL*/
396 #ifdef INET6
397 	case AF_INET6:
398 		hlen = sizeof(struct ip6_hdr);
399 		if (in6p) {
400 			/* more sainty check? */
401 			break;
402 		}
403 		return NULL;	/*EINVAL*/
404 #endif
405 	default:
406 		hlen = 0;	/*pacify gcc*/
407 		return NULL;	/*EAFNOSUPPORT*/
408 	}
409 #ifdef DIAGNOSTIC
410 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
411 		panic("mclbytes too small for t_template");
412 #endif
413 	m = tp->t_template;
414 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
415 		;
416 	else {
417 		if (m)
418 			m_freem(m);
419 		m = tp->t_template = NULL;
420 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
421 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
422 			MCLGET(m, M_DONTWAIT);
423 			if ((m->m_flags & M_EXT) == 0) {
424 				m_free(m);
425 				m = NULL;
426 			}
427 		}
428 		if (m == NULL)
429 			return NULL;
430 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
431 	}
432 
433 	bzero(mtod(m, caddr_t), m->m_len);
434 
435 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
436 
437 	switch (tp->t_family) {
438 	case AF_INET:
439 	    {
440 		struct ipovly *ipov;
441 		mtod(m, struct ip *)->ip_v = 4;
442 		ipov = mtod(m, struct ipovly *);
443 		ipov->ih_pr = IPPROTO_TCP;
444 		ipov->ih_len = htons(sizeof(struct tcphdr));
445 		if (inp) {
446 			ipov->ih_src = inp->inp_laddr;
447 			ipov->ih_dst = inp->inp_faddr;
448 		}
449 #ifdef INET6
450 		else if (in6p) {
451 			/* mapped addr case */
452 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
453 				sizeof(ipov->ih_src));
454 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
455 				sizeof(ipov->ih_dst));
456 		}
457 #endif
458 		/*
459 		 * Compute the pseudo-header portion of the checksum
460 		 * now.  We incrementally add in the TCP option and
461 		 * payload lengths later, and then compute the TCP
462 		 * checksum right before the packet is sent off onto
463 		 * the wire.
464 		 */
465 		n->th_sum = in_cksum_phdr(ipov->ih_src.s_addr,
466 		    ipov->ih_dst.s_addr,
467 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
468 		break;
469 	    }
470 #ifdef INET6
471 	case AF_INET6:
472 	    {
473 		struct ip6_hdr *ip6;
474 		mtod(m, struct ip *)->ip_v = 6;
475 		ip6 = mtod(m, struct ip6_hdr *);
476 		ip6->ip6_nxt = IPPROTO_TCP;
477 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
478 		ip6->ip6_src = in6p->in6p_laddr;
479 		ip6->ip6_dst = in6p->in6p_faddr;
480 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
481 		if (ip6_auto_flowlabel) {
482 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
483 			ip6->ip6_flow |=
484 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
485 		}
486 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
487 		ip6->ip6_vfc |= IPV6_VERSION;
488 
489 		/*
490 		 * Compute the pseudo-header portion of the checksum
491 		 * now.  We incrementally add in the TCP option and
492 		 * payload lengths later, and then compute the TCP
493 		 * checksum right before the packet is sent off onto
494 		 * the wire.
495 		 */
496 		n->th_sum = in6_cksum_phdr(&in6p->in6p_laddr,
497 		    &in6p->in6p_faddr, htonl(sizeof(struct tcphdr)),
498 		    htonl(IPPROTO_TCP));
499 		break;
500 	    }
501 #endif
502 	}
503 	if (inp) {
504 		n->th_sport = inp->inp_lport;
505 		n->th_dport = inp->inp_fport;
506 	}
507 #ifdef INET6
508 	else if (in6p) {
509 		n->th_sport = in6p->in6p_lport;
510 		n->th_dport = in6p->in6p_fport;
511 	}
512 #endif
513 	n->th_seq = 0;
514 	n->th_ack = 0;
515 	n->th_x2 = 0;
516 	n->th_off = 5;
517 	n->th_flags = 0;
518 	n->th_win = 0;
519 	n->th_urp = 0;
520 	return (m);
521 }
522 
523 /*
524  * Send a single message to the TCP at address specified by
525  * the given TCP/IP header.  If m == 0, then we make a copy
526  * of the tcpiphdr at ti and send directly to the addressed host.
527  * This is used to force keep alive messages out using the TCP
528  * template for a connection tp->t_template.  If flags are given
529  * then we send a message back to the TCP which originated the
530  * segment ti, and discard the mbuf containing it and any other
531  * attached mbufs.
532  *
533  * In any case the ack and sequence number of the transmitted
534  * segment are as specified by the parameters.
535  */
536 int
537 tcp_respond(tp, template, m, th0, ack, seq, flags)
538 	struct tcpcb *tp;
539 	struct mbuf *template;
540 	struct mbuf *m;
541 	struct tcphdr *th0;
542 	tcp_seq ack, seq;
543 	int flags;
544 {
545 	struct route *ro;
546 	int error, tlen, win = 0;
547 	int hlen;
548 	struct ip *ip;
549 #ifdef INET6
550 	struct ip6_hdr *ip6;
551 #endif
552 	int family;	/* family on packet, not inpcb/in6pcb! */
553 	struct tcphdr *th;
554 
555 	if (tp != NULL && (flags & TH_RST) == 0) {
556 #ifdef DIAGNOSTIC
557 		if (tp->t_inpcb && tp->t_in6pcb)
558 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
559 #endif
560 #ifdef INET
561 		if (tp->t_inpcb)
562 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
563 #endif
564 #ifdef INET6
565 		if (tp->t_in6pcb)
566 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
567 #endif
568 	}
569 
570 	ip = NULL;
571 #ifdef INET6
572 	ip6 = NULL;
573 #endif
574 	if (m == 0) {
575 		if (!template)
576 			return EINVAL;
577 
578 		/* get family information from template */
579 		switch (mtod(template, struct ip *)->ip_v) {
580 		case 4:
581 			family = AF_INET;
582 			hlen = sizeof(struct ip);
583 			break;
584 #ifdef INET6
585 		case 6:
586 			family = AF_INET6;
587 			hlen = sizeof(struct ip6_hdr);
588 			break;
589 #endif
590 		default:
591 			return EAFNOSUPPORT;
592 		}
593 
594 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
595 		if (m) {
596 			MCLGET(m, M_DONTWAIT);
597 			if ((m->m_flags & M_EXT) == 0) {
598 				m_free(m);
599 				m = NULL;
600 			}
601 		}
602 		if (m == NULL)
603 			return (ENOBUFS);
604 
605 		if (tcp_compat_42)
606 			tlen = 1;
607 		else
608 			tlen = 0;
609 
610 		m->m_data += max_linkhdr;
611 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
612 			template->m_len);
613 		switch (family) {
614 		case AF_INET:
615 			ip = mtod(m, struct ip *);
616 			th = (struct tcphdr *)(ip + 1);
617 			break;
618 #ifdef INET6
619 		case AF_INET6:
620 			ip6 = mtod(m, struct ip6_hdr *);
621 			th = (struct tcphdr *)(ip6 + 1);
622 			break;
623 #endif
624 #if 0
625 		default:
626 			/* noone will visit here */
627 			m_freem(m);
628 			return EAFNOSUPPORT;
629 #endif
630 		}
631 		flags = TH_ACK;
632 	} else {
633 
634 		if ((m->m_flags & M_PKTHDR) == 0) {
635 #if 0
636 			printf("non PKTHDR to tcp_respond\n");
637 #endif
638 			m_freem(m);
639 			return EINVAL;
640 		}
641 #ifdef DIAGNOSTIC
642 		if (!th0)
643 			panic("th0 == NULL in tcp_respond");
644 #endif
645 
646 		/* get family information from m */
647 		switch (mtod(m, struct ip *)->ip_v) {
648 		case 4:
649 			family = AF_INET;
650 			hlen = sizeof(struct ip);
651 			ip = mtod(m, struct ip *);
652 			break;
653 #ifdef INET6
654 		case 6:
655 			family = AF_INET6;
656 			hlen = sizeof(struct ip6_hdr);
657 			ip6 = mtod(m, struct ip6_hdr *);
658 			break;
659 #endif
660 		default:
661 			m_freem(m);
662 			return EAFNOSUPPORT;
663 		}
664 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
665 			tlen = sizeof(*th0);
666 		else
667 			tlen = th0->th_off << 2;
668 
669 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
670 		    mtod(m, caddr_t) + hlen == (caddr_t)th0) {
671 			m->m_len = hlen + tlen;
672 			m_freem(m->m_next);
673 			m->m_next = NULL;
674 		} else {
675 			struct mbuf *n;
676 
677 #ifdef DIAGNOSTIC
678 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
679 				m_freem(m);
680 				return EMSGSIZE;
681 			}
682 #endif
683 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
684 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
685 				MCLGET(n, M_DONTWAIT);
686 				if ((n->m_flags & M_EXT) == 0) {
687 					m_freem(n);
688 					n = NULL;
689 				}
690 			}
691 			if (!n) {
692 				m_freem(m);
693 				return ENOBUFS;
694 			}
695 
696 			n->m_data += max_linkhdr;
697 			n->m_len = hlen + tlen;
698 			m_copyback(n, 0, hlen, mtod(m, caddr_t));
699 			m_copyback(n, hlen, tlen, (caddr_t)th0);
700 
701 			m_freem(m);
702 			m = n;
703 			n = NULL;
704 		}
705 
706 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
707 		switch (family) {
708 		case AF_INET:
709 			ip = mtod(m, struct ip *);
710 			th = (struct tcphdr *)(ip + 1);
711 			ip->ip_p = IPPROTO_TCP;
712 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
713 			ip->ip_p = IPPROTO_TCP;
714 			break;
715 #ifdef INET6
716 		case AF_INET6:
717 			ip6 = mtod(m, struct ip6_hdr *);
718 			th = (struct tcphdr *)(ip6 + 1);
719 			ip6->ip6_nxt = IPPROTO_TCP;
720 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
721 			ip6->ip6_nxt = IPPROTO_TCP;
722 			break;
723 #endif
724 #if 0
725 		default:
726 			/* noone will visit here */
727 			m_freem(m);
728 			return EAFNOSUPPORT;
729 #endif
730 		}
731 		xchg(th->th_dport, th->th_sport, u_int16_t);
732 #undef xchg
733 		tlen = 0;	/*be friendly with the following code*/
734 	}
735 	th->th_seq = htonl(seq);
736 	th->th_ack = htonl(ack);
737 	th->th_x2 = 0;
738 	if ((flags & TH_SYN) == 0) {
739 		if (tp)
740 			win >>= tp->rcv_scale;
741 		if (win > TCP_MAXWIN)
742 			win = TCP_MAXWIN;
743 		th->th_win = htons((u_int16_t)win);
744 		th->th_off = sizeof (struct tcphdr) >> 2;
745 		tlen += sizeof(*th);
746 	} else
747 		tlen += th->th_off << 2;
748 	m->m_len = hlen + tlen;
749 	m->m_pkthdr.len = hlen + tlen;
750 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
751 	th->th_flags = flags;
752 	th->th_urp = 0;
753 
754 	switch (family) {
755 #ifdef INET
756 	case AF_INET:
757 	    {
758 		struct ipovly *ipov = (struct ipovly *)ip;
759 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
760 		ipov->ih_len = htons((u_int16_t)tlen);
761 
762 		th->th_sum = 0;
763 		th->th_sum = in_cksum(m, hlen + tlen);
764 		ip->ip_len = htons(hlen + tlen);
765 		ip->ip_ttl = ip_defttl;
766 		break;
767 	    }
768 #endif
769 #ifdef INET6
770 	case AF_INET6:
771 	    {
772 		th->th_sum = 0;
773 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
774 				tlen);
775 		ip6->ip6_plen = ntohs(tlen);
776 		if (tp && tp->t_in6pcb) {
777 			struct ifnet *oifp;
778 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
779 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
780 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
781 		} else
782 			ip6->ip6_hlim = ip6_defhlim;
783 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
784 		if (ip6_auto_flowlabel) {
785 			ip6->ip6_flow |=
786 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
787 		}
788 		break;
789 	    }
790 #endif
791 	}
792 
793 #ifdef IPSEC
794 	(void)ipsec_setsocket(m, NULL);
795 #endif /*IPSEC*/
796 
797 	if (tp != NULL && tp->t_inpcb != NULL) {
798 		ro = &tp->t_inpcb->inp_route;
799 #ifdef IPSEC
800 		if (ipsec_setsocket(m, tp->t_inpcb->inp_socket) != 0) {
801 			m_freem(m);
802 			return ENOBUFS;
803 		}
804 #endif
805 #ifdef DIAGNOSTIC
806 		if (family != AF_INET)
807 			panic("tcp_respond: address family mismatch");
808 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
809 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
810 			    ntohl(ip->ip_dst.s_addr),
811 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
812 		}
813 #endif
814 	}
815 #ifdef INET6
816 	else if (tp != NULL && tp->t_in6pcb != NULL) {
817 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
818 #ifdef IPSEC
819 		if (ipsec_setsocket(m, tp->t_in6pcb->in6p_socket) != 0) {
820 			m_freem(m);
821 			return ENOBUFS;
822 		}
823 #endif
824 #ifdef DIAGNOSTIC
825 		if (family == AF_INET) {
826 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
827 				panic("tcp_respond: not mapped addr");
828 			if (bcmp(&ip->ip_dst,
829 			    &tp->t_in6pcb->in6p_faddr.s6_addr32[3],
830 			    sizeof(ip->ip_dst)) != 0) {
831 				panic("tcp_respond: ip_dst != in6p_faddr");
832 			}
833 		} else if (family == AF_INET6) {
834 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
835 			    &tp->t_in6pcb->in6p_faddr))
836 				panic("tcp_respond: ip6_dst != in6p_faddr");
837 		} else
838 			panic("tcp_respond: address family mismatch");
839 #endif
840 	}
841 #endif
842 	else
843 		ro = NULL;
844 
845 	switch (family) {
846 #ifdef INET
847 	case AF_INET:
848 		error = ip_output(m, NULL, ro,
849 		    (tp && tp->t_mtudisc ? IP_MTUDISC : 0),
850 		    NULL);
851 		break;
852 #endif
853 #ifdef INET6
854 	case AF_INET6:
855 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL,
856 		    NULL);
857 		break;
858 #endif
859 	default:
860 		error = EAFNOSUPPORT;
861 		break;
862 	}
863 
864 	return (error);
865 }
866 
867 /*
868  * Create a new TCP control block, making an
869  * empty reassembly queue and hooking it to the argument
870  * protocol control block.
871  */
872 struct tcpcb *
873 tcp_newtcpcb(family, aux)
874 	int family;	/* selects inpcb, or in6pcb */
875 	void *aux;
876 {
877 	struct tcpcb *tp;
878 	int i;
879 
880 	switch (family) {
881 	case PF_INET:
882 		break;
883 #ifdef INET6
884 	case PF_INET6:
885 		break;
886 #endif
887 	default:
888 		return NULL;
889 	}
890 
891 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
892 	if (tp == NULL)
893 		return (NULL);
894 	bzero((caddr_t)tp, sizeof(struct tcpcb));
895 	TAILQ_INIT(&tp->segq);
896 	TAILQ_INIT(&tp->timeq);
897 	tp->t_family = family;		/* may be overridden later on */
898 	tp->t_peermss = tcp_mssdflt;
899 	tp->t_ourmss = tcp_mssdflt;
900 	tp->t_segsz = tcp_mssdflt;
901 	LIST_INIT(&tp->t_sc);
902 
903 	callout_init(&tp->t_delack_ch);
904 	for (i = 0; i < TCPT_NTIMERS; i++)
905 		TCP_TIMER_INIT(tp, i);
906 
907 	tp->t_flags = 0;
908 	if (tcp_do_rfc1323 && tcp_do_win_scale)
909 		tp->t_flags |= TF_REQ_SCALE;
910 	if (tcp_do_rfc1323 && tcp_do_timestamps)
911 		tp->t_flags |= TF_REQ_TSTMP;
912 	if (tcp_do_sack == 2)
913 		tp->t_flags |= TF_WILL_SACK;
914 	else if (tcp_do_sack == 1)
915 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
916 	tp->t_flags |= TF_CANT_TXSACK;
917 	switch (family) {
918 	case PF_INET:
919 		tp->t_inpcb = (struct inpcb *)aux;
920 		tp->t_mtudisc = ip_mtudisc;
921 		break;
922 #ifdef INET6
923 	case PF_INET6:
924 		tp->t_in6pcb = (struct in6pcb *)aux;
925 		/* for IPv6, always try to run path MTU discovery */
926 		tp->t_mtudisc = 1;
927 		break;
928 #endif
929 	}
930 	/*
931 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
932 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
933 	 * reasonable initial retransmit time.
934 	 */
935 	tp->t_srtt = TCPTV_SRTTBASE;
936 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
937 	tp->t_rttmin = TCPTV_MIN;
938 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
939 	    TCPTV_MIN, TCPTV_REXMTMAX);
940 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
941 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
942 	if (family == AF_INET) {
943 		struct inpcb *inp = (struct inpcb *)aux;
944 		inp->inp_ip.ip_ttl = ip_defttl;
945 		inp->inp_ppcb = (caddr_t)tp;
946 	}
947 #ifdef INET6
948 	else if (family == AF_INET6) {
949 		struct in6pcb *in6p = (struct in6pcb *)aux;
950 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
951 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
952 					       : NULL);
953 		in6p->in6p_ppcb = (caddr_t)tp;
954 	}
955 #endif
956 
957 	/*
958 	 * Initialize our timebase.  When we send timestamps, we take
959 	 * the delta from tcp_now -- this means each connection always
960 	 * gets a timebase of 0, which makes it, among other things,
961 	 * more difficult to determine how long a system has been up,
962 	 * and thus how many TCP sequence increments have occurred.
963 	 */
964 	tp->ts_timebase = tcp_now;
965 
966 	return (tp);
967 }
968 
969 /*
970  * Drop a TCP connection, reporting
971  * the specified error.  If connection is synchronized,
972  * then send a RST to peer.
973  */
974 struct tcpcb *
975 tcp_drop(tp, errno)
976 	struct tcpcb *tp;
977 	int errno;
978 {
979 	struct socket *so = NULL;
980 
981 #ifdef DIAGNOSTIC
982 	if (tp->t_inpcb && tp->t_in6pcb)
983 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
984 #endif
985 #ifdef INET
986 	if (tp->t_inpcb)
987 		so = tp->t_inpcb->inp_socket;
988 #endif
989 #ifdef INET6
990 	if (tp->t_in6pcb)
991 		so = tp->t_in6pcb->in6p_socket;
992 #endif
993 	if (!so)
994 		return NULL;
995 
996 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
997 		tp->t_state = TCPS_CLOSED;
998 		(void) tcp_output(tp);
999 		tcpstat.tcps_drops++;
1000 	} else
1001 		tcpstat.tcps_conndrops++;
1002 	if (errno == ETIMEDOUT && tp->t_softerror)
1003 		errno = tp->t_softerror;
1004 	so->so_error = errno;
1005 	return (tcp_close(tp));
1006 }
1007 
1008 /*
1009  * Close a TCP control block:
1010  *	discard all space held by the tcp
1011  *	discard internet protocol block
1012  *	wake up any sleepers
1013  */
1014 struct tcpcb *
1015 tcp_close(tp)
1016 	struct tcpcb *tp;
1017 {
1018 	struct inpcb *inp;
1019 #ifdef INET6
1020 	struct in6pcb *in6p;
1021 #endif
1022 	struct socket *so;
1023 #ifdef RTV_RTT
1024 	struct rtentry *rt;
1025 #endif
1026 	struct route *ro;
1027 
1028 	inp = tp->t_inpcb;
1029 #ifdef INET6
1030 	in6p = tp->t_in6pcb;
1031 #endif
1032 	so = NULL;
1033 	ro = NULL;
1034 	if (inp) {
1035 		so = inp->inp_socket;
1036 		ro = &inp->inp_route;
1037 	}
1038 #ifdef INET6
1039 	else if (in6p) {
1040 		so = in6p->in6p_socket;
1041 		ro = (struct route *)&in6p->in6p_route;
1042 	}
1043 #endif
1044 
1045 #ifdef RTV_RTT
1046 	/*
1047 	 * If we sent enough data to get some meaningful characteristics,
1048 	 * save them in the routing entry.  'Enough' is arbitrarily
1049 	 * defined as the sendpipesize (default 4K) * 16.  This would
1050 	 * give us 16 rtt samples assuming we only get one sample per
1051 	 * window (the usual case on a long haul net).  16 samples is
1052 	 * enough for the srtt filter to converge to within 5% of the correct
1053 	 * value; fewer samples and we could save a very bogus rtt.
1054 	 *
1055 	 * Don't update the default route's characteristics and don't
1056 	 * update anything that the user "locked".
1057 	 */
1058 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
1059 	    ro && (rt = ro->ro_rt) &&
1060 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
1061 		u_long i = 0;
1062 
1063 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
1064 			i = tp->t_srtt *
1065 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1066 			if (rt->rt_rmx.rmx_rtt && i)
1067 				/*
1068 				 * filter this update to half the old & half
1069 				 * the new values, converting scale.
1070 				 * See route.h and tcp_var.h for a
1071 				 * description of the scaling constants.
1072 				 */
1073 				rt->rt_rmx.rmx_rtt =
1074 				    (rt->rt_rmx.rmx_rtt + i) / 2;
1075 			else
1076 				rt->rt_rmx.rmx_rtt = i;
1077 		}
1078 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
1079 			i = tp->t_rttvar *
1080 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
1081 			if (rt->rt_rmx.rmx_rttvar && i)
1082 				rt->rt_rmx.rmx_rttvar =
1083 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
1084 			else
1085 				rt->rt_rmx.rmx_rttvar = i;
1086 		}
1087 		/*
1088 		 * update the pipelimit (ssthresh) if it has been updated
1089 		 * already or if a pipesize was specified & the threshhold
1090 		 * got below half the pipesize.  I.e., wait for bad news
1091 		 * before we start updating, then update on both good
1092 		 * and bad news.
1093 		 */
1094 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
1095 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
1096 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
1097 			/*
1098 			 * convert the limit from user data bytes to
1099 			 * packets then to packet data bytes.
1100 			 */
1101 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
1102 			if (i < 2)
1103 				i = 2;
1104 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
1105 			if (rt->rt_rmx.rmx_ssthresh)
1106 				rt->rt_rmx.rmx_ssthresh =
1107 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
1108 			else
1109 				rt->rt_rmx.rmx_ssthresh = i;
1110 		}
1111 	}
1112 #endif /* RTV_RTT */
1113 	/* free the reassembly queue, if any */
1114 	TCP_REASS_LOCK(tp);
1115 	(void) tcp_freeq(tp);
1116 	TCP_REASS_UNLOCK(tp);
1117 
1118 	tcp_canceltimers(tp);
1119 	TCP_CLEAR_DELACK(tp);
1120 	syn_cache_cleanup(tp);
1121 
1122 	if (tp->t_template) {
1123 		m_free(tp->t_template);
1124 		tp->t_template = NULL;
1125 	}
1126 	pool_put(&tcpcb_pool, tp);
1127 	if (inp) {
1128 		inp->inp_ppcb = 0;
1129 		soisdisconnected(so);
1130 		in_pcbdetach(inp);
1131 	}
1132 #ifdef INET6
1133 	else if (in6p) {
1134 		in6p->in6p_ppcb = 0;
1135 		soisdisconnected(so);
1136 		in6_pcbdetach(in6p);
1137 	}
1138 #endif
1139 	tcpstat.tcps_closed++;
1140 	return ((struct tcpcb *)0);
1141 }
1142 
1143 int
1144 tcp_freeq(tp)
1145 	struct tcpcb *tp;
1146 {
1147 	struct ipqent *qe;
1148 	int rv = 0;
1149 #ifdef TCPREASS_DEBUG
1150 	int i = 0;
1151 #endif
1152 
1153 	TCP_REASS_LOCK_CHECK(tp);
1154 
1155 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
1156 #ifdef TCPREASS_DEBUG
1157 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
1158 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
1159 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
1160 #endif
1161 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
1162 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
1163 		m_freem(qe->ipqe_m);
1164 		pool_put(&ipqent_pool, qe);
1165 		rv = 1;
1166 	}
1167 	return (rv);
1168 }
1169 
1170 /*
1171  * Protocol drain routine.  Called when memory is in short supply.
1172  */
1173 void
1174 tcp_drain()
1175 {
1176 	struct inpcb *inp;
1177 	struct tcpcb *tp;
1178 
1179 	/*
1180 	 * Free the sequence queue of all TCP connections.
1181 	 */
1182 	inp = CIRCLEQ_FIRST(&tcbtable.inpt_queue);
1183 	if (inp)						/* XXX */
1184 	CIRCLEQ_FOREACH(inp, &tcbtable.inpt_queue, inp_queue) {
1185 		if ((tp = intotcpcb(inp)) != NULL) {
1186 			/*
1187 			 * We may be called from a device's interrupt
1188 			 * context.  If the tcpcb is already busy,
1189 			 * just bail out now.
1190 			 */
1191 			if (tcp_reass_lock_try(tp) == 0)
1192 				continue;
1193 			if (tcp_freeq(tp))
1194 				tcpstat.tcps_connsdrained++;
1195 			TCP_REASS_UNLOCK(tp);
1196 		}
1197 	}
1198 }
1199 
1200 #ifdef INET6
1201 void
1202 tcp6_drain()
1203 {
1204 	struct in6pcb *in6p;
1205 	struct tcpcb *tp;
1206 	struct in6pcb *head = &tcb6;
1207 
1208 	/*
1209 	 * Free the sequence queue of all TCP connections.
1210 	 */
1211 	for (in6p = head->in6p_next; in6p != head; in6p = in6p->in6p_next) {
1212 		if ((tp = in6totcpcb(in6p)) != NULL) {
1213 			/*
1214 			 * We may be called from a device's interrupt
1215 			 * context.  If the tcpcb is already busy,
1216 			 * just bail out now.
1217 			 */
1218 			if (tcp_reass_lock_try(tp) == 0)
1219 				continue;
1220 			if (tcp_freeq(tp))
1221 				tcpstat.tcps_connsdrained++;
1222 			TCP_REASS_UNLOCK(tp);
1223 		}
1224 	}
1225 }
1226 #endif
1227 
1228 /*
1229  * Notify a tcp user of an asynchronous error;
1230  * store error as soft error, but wake up user
1231  * (for now, won't do anything until can select for soft error).
1232  */
1233 void
1234 tcp_notify(inp, error)
1235 	struct inpcb *inp;
1236 	int error;
1237 {
1238 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1239 	struct socket *so = inp->inp_socket;
1240 
1241 	/*
1242 	 * Ignore some errors if we are hooked up.
1243 	 * If connection hasn't completed, has retransmitted several times,
1244 	 * and receives a second error, give up now.  This is better
1245 	 * than waiting a long time to establish a connection that
1246 	 * can never complete.
1247 	 */
1248 	if (tp->t_state == TCPS_ESTABLISHED &&
1249 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1250 	      error == EHOSTDOWN)) {
1251 		return;
1252 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1253 	    tp->t_rxtshift > 3 && tp->t_softerror)
1254 		so->so_error = error;
1255 	else
1256 		tp->t_softerror = error;
1257 	wakeup((caddr_t) &so->so_timeo);
1258 	sorwakeup(so);
1259 	sowwakeup(so);
1260 }
1261 
1262 #ifdef INET6
1263 void
1264 tcp6_notify(in6p, error)
1265 	struct in6pcb *in6p;
1266 	int error;
1267 {
1268 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1269 	struct socket *so = in6p->in6p_socket;
1270 
1271 	/*
1272 	 * Ignore some errors if we are hooked up.
1273 	 * If connection hasn't completed, has retransmitted several times,
1274 	 * and receives a second error, give up now.  This is better
1275 	 * than waiting a long time to establish a connection that
1276 	 * can never complete.
1277 	 */
1278 	if (tp->t_state == TCPS_ESTABLISHED &&
1279 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1280 	      error == EHOSTDOWN)) {
1281 		return;
1282 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1283 	    tp->t_rxtshift > 3 && tp->t_softerror)
1284 		so->so_error = error;
1285 	else
1286 		tp->t_softerror = error;
1287 	wakeup((caddr_t) &so->so_timeo);
1288 	sorwakeup(so);
1289 	sowwakeup(so);
1290 }
1291 #endif
1292 
1293 #ifdef INET6
1294 void
1295 tcp6_ctlinput(cmd, sa, d)
1296 	int cmd;
1297 	struct sockaddr *sa;
1298 	void *d;
1299 {
1300 	struct tcphdr th;
1301 	void (*notify) __P((struct in6pcb *, int)) = tcp6_notify;
1302 	int nmatch;
1303 	struct ip6_hdr *ip6;
1304 	const struct sockaddr_in6 *sa6_src = NULL;
1305 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
1306 	struct mbuf *m;
1307 	int off;
1308 
1309 	if (sa->sa_family != AF_INET6 ||
1310 	    sa->sa_len != sizeof(struct sockaddr_in6))
1311 		return;
1312 	if ((unsigned)cmd >= PRC_NCMDS)
1313 		return;
1314 	else if (cmd == PRC_QUENCH) {
1315 		/* XXX there's no PRC_QUENCH in IPv6 */
1316 		notify = tcp6_quench;
1317 	} else if (PRC_IS_REDIRECT(cmd))
1318 		notify = in6_rtchange, d = NULL;
1319 	else if (cmd == PRC_MSGSIZE)
1320 		; /* special code is present, see below */
1321 	else if (cmd == PRC_HOSTDEAD)
1322 		d = NULL;
1323 	else if (inet6ctlerrmap[cmd] == 0)
1324 		return;
1325 
1326 	/* if the parameter is from icmp6, decode it. */
1327 	if (d != NULL) {
1328 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1329 		m = ip6cp->ip6c_m;
1330 		ip6 = ip6cp->ip6c_ip6;
1331 		off = ip6cp->ip6c_off;
1332 		sa6_src = ip6cp->ip6c_src;
1333 	} else {
1334 		m = NULL;
1335 		ip6 = NULL;
1336 		sa6_src = &sa6_any;
1337 	}
1338 
1339 	if (ip6) {
1340 		/*
1341 		 * XXX: We assume that when ip6 is non NULL,
1342 		 * M and OFF are valid.
1343 		 */
1344 
1345 		/* check if we can safely examine src and dst ports */
1346 		if (m->m_pkthdr.len < off + sizeof(th)) {
1347 			if (cmd == PRC_MSGSIZE)
1348 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
1349 			return;
1350 		}
1351 
1352 		bzero(&th, sizeof(th));
1353 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
1354 
1355 		if (cmd == PRC_MSGSIZE) {
1356 			int valid = 0;
1357 
1358 			/*
1359 			 * Check to see if we have a valid TCP connection
1360 			 * corresponding to the address in the ICMPv6 message
1361 			 * payload.
1362 			 */
1363 			if (in6_pcblookup_connect(&tcb6, &sa6->sin6_addr,
1364 			    th.th_dport, (struct in6_addr *)&sa6_src->sin6_addr,
1365 			    th.th_sport, 0))
1366 				valid++;
1367 
1368 			/*
1369 			 * Depending on the value of "valid" and routing table
1370 			 * size (mtudisc_{hi,lo}wat), we will:
1371 			 * - recalcurate the new MTU and create the
1372 			 *   corresponding routing entry, or
1373 			 * - ignore the MTU change notification.
1374 			 */
1375 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
1376 
1377 			/*
1378 			 * no need to call in6_pcbnotify, it should have been
1379 			 * called via callback if necessary
1380 			 */
1381 			return;
1382 		}
1383 
1384 		nmatch = in6_pcbnotify(&tcb6, sa, th.th_dport,
1385 		    (struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
1386 		if (nmatch == 0 && syn_cache_count &&
1387 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1388 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1389 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
1390 			syn_cache_unreach((struct sockaddr *)sa6_src,
1391 					  sa, &th);
1392 	} else {
1393 		(void) in6_pcbnotify(&tcb6, sa, 0, (struct sockaddr *)sa6_src,
1394 		    0, cmd, NULL, notify);
1395 	}
1396 }
1397 #endif
1398 
1399 #ifdef INET
1400 /* assumes that ip header and tcp header are contiguous on mbuf */
1401 void *
1402 tcp_ctlinput(cmd, sa, v)
1403 	int cmd;
1404 	struct sockaddr *sa;
1405 	void *v;
1406 {
1407 	struct ip *ip = v;
1408 	struct tcphdr *th;
1409 	struct icmp *icp;
1410 	extern const int inetctlerrmap[];
1411 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1412 	int errno;
1413 	int nmatch;
1414 #ifdef INET6
1415 	struct in6_addr src6, dst6;
1416 #endif
1417 
1418 	if (sa->sa_family != AF_INET ||
1419 	    sa->sa_len != sizeof(struct sockaddr_in))
1420 		return NULL;
1421 	if ((unsigned)cmd >= PRC_NCMDS)
1422 		return NULL;
1423 	errno = inetctlerrmap[cmd];
1424 	if (cmd == PRC_QUENCH)
1425 		notify = tcp_quench;
1426 	else if (PRC_IS_REDIRECT(cmd))
1427 		notify = in_rtchange, ip = 0;
1428 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
1429 		/*
1430 		 * Check to see if we have a valid TCP connection
1431 		 * corresponding to the address in the ICMP message
1432 		 * payload.
1433 		 *
1434 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
1435 		 */
1436 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1437 #ifdef INET6
1438 		memset(&src6, 0, sizeof(src6));
1439 		memset(&dst6, 0, sizeof(dst6));
1440 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
1441 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
1442 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
1443 #endif
1444 		if (in_pcblookup_connect(&tcbtable, ip->ip_dst, th->th_dport,
1445 		    ip->ip_src, th->th_sport) != NULL)
1446 			;
1447 #ifdef INET6
1448 		else if (in6_pcblookup_connect(&tcb6, &dst6,
1449 		    th->th_dport, &src6, th->th_sport, 0) != NULL)
1450 			;
1451 #endif
1452 		else
1453 			return NULL;
1454 
1455 		/*
1456 		 * Now that we've validated that we are actually communicating
1457 		 * with the host indicated in the ICMP message, locate the
1458 		 * ICMP header, recalculate the new MTU, and create the
1459 		 * corresponding routing entry.
1460 		 */
1461 		icp = (struct icmp *)((caddr_t)ip -
1462 		    offsetof(struct icmp, icmp_ip));
1463 		icmp_mtudisc(icp, ip->ip_dst);
1464 
1465 		return NULL;
1466 	} else if (cmd == PRC_HOSTDEAD)
1467 		ip = 0;
1468 	else if (errno == 0)
1469 		return NULL;
1470 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1471 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1472 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
1473 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1474 		if (nmatch == 0 && syn_cache_count &&
1475 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1476 		    inetctlerrmap[cmd] == ENETUNREACH ||
1477 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1478 			struct sockaddr_in sin;
1479 			bzero(&sin, sizeof(sin));
1480 			sin.sin_len = sizeof(sin);
1481 			sin.sin_family = AF_INET;
1482 			sin.sin_port = th->th_sport;
1483 			sin.sin_addr = ip->ip_src;
1484 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1485 		}
1486 
1487 		/* XXX mapped address case */
1488 	} else
1489 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
1490 		    notify);
1491 	return NULL;
1492 }
1493 
1494 /*
1495  * When a source quence is received, we are being notifed of congestion.
1496  * Close the congestion window down to the Loss Window (one segment).
1497  * We will gradually open it again as we proceed.
1498  */
1499 void
1500 tcp_quench(inp, errno)
1501 	struct inpcb *inp;
1502 	int errno;
1503 {
1504 	struct tcpcb *tp = intotcpcb(inp);
1505 
1506 	if (tp)
1507 		tp->snd_cwnd = tp->t_segsz;
1508 }
1509 #endif
1510 
1511 #ifdef INET6
1512 void
1513 tcp6_quench(in6p, errno)
1514 	struct in6pcb *in6p;
1515 	int errno;
1516 {
1517 	struct tcpcb *tp = in6totcpcb(in6p);
1518 
1519 	if (tp)
1520 		tp->snd_cwnd = tp->t_segsz;
1521 }
1522 #endif
1523 
1524 #ifdef INET
1525 /*
1526  * Path MTU Discovery handlers.
1527  */
1528 void
1529 tcp_mtudisc_callback(faddr)
1530 	struct in_addr faddr;
1531 {
1532 #ifdef INET6
1533 	struct in6_addr in6;
1534 #endif
1535 
1536 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
1537 #ifdef INET6
1538 	memset(&in6, 0, sizeof(in6));
1539 	in6.s6_addr16[5] = 0xffff;
1540 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
1541 	tcp6_mtudisc_callback(&in6);
1542 #endif
1543 }
1544 
1545 /*
1546  * On receipt of path MTU corrections, flush old route and replace it
1547  * with the new one.  Retransmit all unacknowledged packets, to ensure
1548  * that all packets will be received.
1549  */
1550 void
1551 tcp_mtudisc(inp, errno)
1552 	struct inpcb *inp;
1553 	int errno;
1554 {
1555 	struct tcpcb *tp = intotcpcb(inp);
1556 	struct rtentry *rt = in_pcbrtentry(inp);
1557 
1558 	if (tp != 0) {
1559 		if (rt != 0) {
1560 			/*
1561 			 * If this was not a host route, remove and realloc.
1562 			 */
1563 			if ((rt->rt_flags & RTF_HOST) == 0) {
1564 				in_rtchange(inp, errno);
1565 				if ((rt = in_pcbrtentry(inp)) == 0)
1566 					return;
1567 			}
1568 
1569 			/*
1570 			 * Slow start out of the error condition.  We
1571 			 * use the MTU because we know it's smaller
1572 			 * than the previously transmitted segment.
1573 			 *
1574 			 * Note: This is more conservative than the
1575 			 * suggestion in draft-floyd-incr-init-win-03.
1576 			 */
1577 			if (rt->rt_rmx.rmx_mtu != 0)
1578 				tp->snd_cwnd =
1579 				    TCP_INITIAL_WINDOW(tcp_init_win,
1580 				    rt->rt_rmx.rmx_mtu);
1581 		}
1582 
1583 		/*
1584 		 * Resend unacknowledged packets.
1585 		 */
1586 		tp->snd_nxt = tp->snd_una;
1587 		tcp_output(tp);
1588 	}
1589 }
1590 #endif
1591 
1592 #ifdef INET6
1593 /*
1594  * Path MTU Discovery handlers.
1595  */
1596 void
1597 tcp6_mtudisc_callback(faddr)
1598 	struct in6_addr *faddr;
1599 {
1600 	struct sockaddr_in6 sin6;
1601 
1602 	bzero(&sin6, sizeof(sin6));
1603 	sin6.sin6_family = AF_INET6;
1604 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1605 	sin6.sin6_addr = *faddr;
1606 	(void) in6_pcbnotify(&tcb6, (struct sockaddr *)&sin6, 0,
1607 	    (struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
1608 }
1609 
1610 void
1611 tcp6_mtudisc(in6p, errno)
1612 	struct in6pcb *in6p;
1613 	int errno;
1614 {
1615 	struct tcpcb *tp = in6totcpcb(in6p);
1616 	struct rtentry *rt = in6_pcbrtentry(in6p);
1617 
1618 	if (tp != 0) {
1619 		if (rt != 0) {
1620 			/*
1621 			 * If this was not a host route, remove and realloc.
1622 			 */
1623 			if ((rt->rt_flags & RTF_HOST) == 0) {
1624 				in6_rtchange(in6p, errno);
1625 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1626 					return;
1627 			}
1628 
1629 			/*
1630 			 * Slow start out of the error condition.  We
1631 			 * use the MTU because we know it's smaller
1632 			 * than the previously transmitted segment.
1633 			 *
1634 			 * Note: This is more conservative than the
1635 			 * suggestion in draft-floyd-incr-init-win-03.
1636 			 */
1637 			if (rt->rt_rmx.rmx_mtu != 0)
1638 				tp->snd_cwnd =
1639 				    TCP_INITIAL_WINDOW(tcp_init_win,
1640 				    rt->rt_rmx.rmx_mtu);
1641 		}
1642 
1643 		/*
1644 		 * Resend unacknowledged packets.
1645 		 */
1646 		tp->snd_nxt = tp->snd_una;
1647 		tcp_output(tp);
1648 	}
1649 }
1650 #endif /* INET6 */
1651 
1652 /*
1653  * Compute the MSS to advertise to the peer.  Called only during
1654  * the 3-way handshake.  If we are the server (peer initiated
1655  * connection), we are called with a pointer to the interface
1656  * on which the SYN packet arrived.  If we are the client (we
1657  * initiated connection), we are called with a pointer to the
1658  * interface out which this connection should go.
1659  *
1660  * NOTE: Do not subtract IP option/extension header size nor IPsec
1661  * header size from MSS advertisement.  MSS option must hold the maximum
1662  * segment size we can accept, so it must always be:
1663  *	 max(if mtu) - ip header - tcp header
1664  */
1665 u_long
1666 tcp_mss_to_advertise(ifp, af)
1667 	const struct ifnet *ifp;
1668 	int af;
1669 {
1670 	extern u_long in_maxmtu;
1671 	u_long mss = 0;
1672 	u_long hdrsiz;
1673 
1674 	/*
1675 	 * In order to avoid defeating path MTU discovery on the peer,
1676 	 * we advertise the max MTU of all attached networks as our MSS,
1677 	 * per RFC 1191, section 3.1.
1678 	 *
1679 	 * We provide the option to advertise just the MTU of
1680 	 * the interface on which we hope this connection will
1681 	 * be receiving.  If we are responding to a SYN, we
1682 	 * will have a pretty good idea about this, but when
1683 	 * initiating a connection there is a bit more doubt.
1684 	 *
1685 	 * We also need to ensure that loopback has a large enough
1686 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1687 	 */
1688 
1689 	if (ifp != NULL)
1690 		switch (af) {
1691 		case AF_INET:
1692 			mss = ifp->if_mtu;
1693 			break;
1694 #ifdef INET6
1695 		case AF_INET6:
1696 			mss = IN6_LINKMTU(ifp);
1697 			break;
1698 #endif
1699 		}
1700 
1701 	if (tcp_mss_ifmtu == 0)
1702 		switch (af) {
1703 		case AF_INET:
1704 			mss = max(in_maxmtu, mss);
1705 			break;
1706 #ifdef INET6
1707 		case AF_INET6:
1708 			mss = max(in6_maxmtu, mss);
1709 			break;
1710 #endif
1711 		}
1712 
1713 	switch (af) {
1714 	case AF_INET:
1715 		hdrsiz = sizeof(struct ip);
1716 		break;
1717 #ifdef INET6
1718 	case AF_INET6:
1719 		hdrsiz = sizeof(struct ip6_hdr);
1720 		break;
1721 #endif
1722 	default:
1723 		hdrsiz = 0;
1724 		break;
1725 	}
1726 	hdrsiz += sizeof(struct tcphdr);
1727 	if (mss > hdrsiz)
1728 		mss -= hdrsiz;
1729 
1730 	mss = max(tcp_mssdflt, mss);
1731 	return (mss);
1732 }
1733 
1734 /*
1735  * Set connection variables based on the peer's advertised MSS.
1736  * We are passed the TCPCB for the actual connection.  If we
1737  * are the server, we are called by the compressed state engine
1738  * when the 3-way handshake is complete.  If we are the client,
1739  * we are called when we receive the SYN,ACK from the server.
1740  *
1741  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1742  * before this routine is called!
1743  */
1744 void
1745 tcp_mss_from_peer(tp, offer)
1746 	struct tcpcb *tp;
1747 	int offer;
1748 {
1749 	struct socket *so;
1750 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1751 	struct rtentry *rt;
1752 #endif
1753 	u_long bufsize;
1754 	int mss;
1755 
1756 #ifdef DIAGNOSTIC
1757 	if (tp->t_inpcb && tp->t_in6pcb)
1758 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
1759 #endif
1760 	so = NULL;
1761 	rt = NULL;
1762 #ifdef INET
1763 	if (tp->t_inpcb) {
1764 		so = tp->t_inpcb->inp_socket;
1765 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1766 		rt = in_pcbrtentry(tp->t_inpcb);
1767 #endif
1768 	}
1769 #endif
1770 #ifdef INET6
1771 	if (tp->t_in6pcb) {
1772 		so = tp->t_in6pcb->in6p_socket;
1773 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1774 		rt = in6_pcbrtentry(tp->t_in6pcb);
1775 #endif
1776 	}
1777 #endif
1778 
1779 	/*
1780 	 * As per RFC1122, use the default MSS value, unless they
1781 	 * sent us an offer.  Do not accept offers less than 32 bytes.
1782 	 */
1783 	mss = tcp_mssdflt;
1784 	if (offer)
1785 		mss = offer;
1786 	mss = max(mss, 32);		/* sanity */
1787 	tp->t_peermss = mss;
1788 	mss -= tcp_optlen(tp);
1789 #ifdef INET
1790 	if (tp->t_inpcb)
1791 		mss -= ip_optlen(tp->t_inpcb);
1792 #endif
1793 #ifdef INET6
1794 	if (tp->t_in6pcb)
1795 		mss -= ip6_optlen(tp->t_in6pcb);
1796 #endif
1797 
1798 	/*
1799 	 * If there's a pipesize, change the socket buffer to that size.
1800 	 * Make the socket buffer an integral number of MSS units.  If
1801 	 * the MSS is larger than the socket buffer, artificially decrease
1802 	 * the MSS.
1803 	 */
1804 #ifdef RTV_SPIPE
1805 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
1806 		bufsize = rt->rt_rmx.rmx_sendpipe;
1807 	else
1808 #endif
1809 		bufsize = so->so_snd.sb_hiwat;
1810 	if (bufsize < mss)
1811 		mss = bufsize;
1812 	else {
1813 		bufsize = roundup(bufsize, mss);
1814 		if (bufsize > sb_max)
1815 			bufsize = sb_max;
1816 		(void) sbreserve(&so->so_snd, bufsize);
1817 	}
1818 	tp->t_segsz = mss;
1819 
1820 #ifdef RTV_SSTHRESH
1821 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
1822 		/*
1823 		 * There's some sort of gateway or interface buffer
1824 		 * limit on the path.  Use this to set the slow
1825 		 * start threshold, but set the threshold to no less
1826 		 * than 2 * MSS.
1827 		 */
1828 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1829 	}
1830 #endif
1831 }
1832 
1833 /*
1834  * Processing necessary when a TCP connection is established.
1835  */
1836 void
1837 tcp_established(tp)
1838 	struct tcpcb *tp;
1839 {
1840 	struct socket *so;
1841 #ifdef RTV_RPIPE
1842 	struct rtentry *rt;
1843 #endif
1844 	u_long bufsize;
1845 
1846 #ifdef DIAGNOSTIC
1847 	if (tp->t_inpcb && tp->t_in6pcb)
1848 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
1849 #endif
1850 	so = NULL;
1851 	rt = NULL;
1852 #ifdef INET
1853 	if (tp->t_inpcb) {
1854 		so = tp->t_inpcb->inp_socket;
1855 #if defined(RTV_RPIPE)
1856 		rt = in_pcbrtentry(tp->t_inpcb);
1857 #endif
1858 	}
1859 #endif
1860 #ifdef INET6
1861 	if (tp->t_in6pcb) {
1862 		so = tp->t_in6pcb->in6p_socket;
1863 #if defined(RTV_RPIPE)
1864 		rt = in6_pcbrtentry(tp->t_in6pcb);
1865 #endif
1866 	}
1867 #endif
1868 
1869 	tp->t_state = TCPS_ESTABLISHED;
1870 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1871 
1872 #ifdef RTV_RPIPE
1873 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
1874 		bufsize = rt->rt_rmx.rmx_recvpipe;
1875 	else
1876 #endif
1877 		bufsize = so->so_rcv.sb_hiwat;
1878 	if (bufsize > tp->t_ourmss) {
1879 		bufsize = roundup(bufsize, tp->t_ourmss);
1880 		if (bufsize > sb_max)
1881 			bufsize = sb_max;
1882 		(void) sbreserve(&so->so_rcv, bufsize);
1883 	}
1884 }
1885 
1886 /*
1887  * Check if there's an initial rtt or rttvar.  Convert from the
1888  * route-table units to scaled multiples of the slow timeout timer.
1889  * Called only during the 3-way handshake.
1890  */
1891 void
1892 tcp_rmx_rtt(tp)
1893 	struct tcpcb *tp;
1894 {
1895 #ifdef RTV_RTT
1896 	struct rtentry *rt = NULL;
1897 	int rtt;
1898 
1899 #ifdef DIAGNOSTIC
1900 	if (tp->t_inpcb && tp->t_in6pcb)
1901 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
1902 #endif
1903 #ifdef INET
1904 	if (tp->t_inpcb)
1905 		rt = in_pcbrtentry(tp->t_inpcb);
1906 #endif
1907 #ifdef INET6
1908 	if (tp->t_in6pcb)
1909 		rt = in6_pcbrtentry(tp->t_in6pcb);
1910 #endif
1911 	if (rt == NULL)
1912 		return;
1913 
1914 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1915 		/*
1916 		 * XXX The lock bit for MTU indicates that the value
1917 		 * is also a minimum value; this is subject to time.
1918 		 */
1919 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1920 			TCPT_RANGESET(tp->t_rttmin,
1921 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
1922 			    TCPTV_MIN, TCPTV_REXMTMAX);
1923 		tp->t_srtt = rtt /
1924 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1925 		if (rt->rt_rmx.rmx_rttvar) {
1926 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1927 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
1928 				(TCP_RTTVAR_SHIFT + 2));
1929 		} else {
1930 			/* Default variation is +- 1 rtt */
1931 			tp->t_rttvar =
1932 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
1933 		}
1934 		TCPT_RANGESET(tp->t_rxtcur,
1935 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
1936 		    tp->t_rttmin, TCPTV_REXMTMAX);
1937 	}
1938 #endif
1939 }
1940 
1941 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
1942 #if NRND > 0
1943 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
1944 #endif
1945 
1946 /*
1947  * Get a new sequence value given a tcp control block
1948  */
1949 tcp_seq
1950 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
1951 {
1952 
1953 #ifdef INET
1954 	if (tp->t_inpcb != NULL) {
1955 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
1956 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
1957 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
1958 		    addin));
1959 	}
1960 #endif
1961 #ifdef INET6
1962 	if (tp->t_in6pcb != NULL) {
1963 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
1964 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
1965 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
1966 		    addin));
1967 	}
1968 #endif
1969 	/* Not possible. */
1970 	panic("tcp_new_iss");
1971 }
1972 
1973 /*
1974  * This routine actually generates a new TCP initial sequence number.
1975  */
1976 tcp_seq
1977 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
1978     size_t addrsz, tcp_seq addin)
1979 {
1980 	tcp_seq tcp_iss;
1981 
1982 #if NRND > 0
1983 	static int beenhere;
1984 
1985 	/*
1986 	 * If we haven't been here before, initialize our cryptographic
1987 	 * hash secret.
1988 	 */
1989 	if (beenhere == 0) {
1990 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
1991 		    RND_EXTRACT_ANY);
1992 		beenhere = 1;
1993 	}
1994 
1995 	if (tcp_do_rfc1948) {
1996 		MD5_CTX ctx;
1997 		u_int8_t hash[16];	/* XXX MD5 knowledge */
1998 
1999 		/*
2000 		 * Compute the base value of the ISS.  It is a hash
2001 		 * of (saddr, sport, daddr, dport, secret).
2002 		 */
2003 		MD5Init(&ctx);
2004 
2005 		MD5Update(&ctx, (u_char *) laddr, addrsz);
2006 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
2007 
2008 		MD5Update(&ctx, (u_char *) faddr, addrsz);
2009 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
2010 
2011 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
2012 
2013 		MD5Final(hash, &ctx);
2014 
2015 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
2016 
2017 		/*
2018 		 * Now increment our "timer", and add it in to
2019 		 * the computed value.
2020 		 *
2021 		 * XXX Use `addin'?
2022 		 * XXX TCP_ISSINCR too large to use?
2023 		 */
2024 		tcp_iss_seq += TCP_ISSINCR;
2025 #ifdef TCPISS_DEBUG
2026 		printf("ISS hash 0x%08x, ", tcp_iss);
2027 #endif
2028 		tcp_iss += tcp_iss_seq + addin;
2029 #ifdef TCPISS_DEBUG
2030 		printf("new ISS 0x%08x\n", tcp_iss);
2031 #endif
2032 	} else
2033 #endif /* NRND > 0 */
2034 	{
2035 		/*
2036 		 * Randomize.
2037 		 */
2038 #if NRND > 0
2039 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
2040 #else
2041 		tcp_iss = arc4random();
2042 #endif
2043 
2044 		/*
2045 		 * If we were asked to add some amount to a known value,
2046 		 * we will take a random value obtained above, mask off
2047 		 * the upper bits, and add in the known value.  We also
2048 		 * add in a constant to ensure that we are at least a
2049 		 * certain distance from the original value.
2050 		 *
2051 		 * This is used when an old connection is in timed wait
2052 		 * and we have a new one coming in, for instance.
2053 		 */
2054 		if (addin != 0) {
2055 #ifdef TCPISS_DEBUG
2056 			printf("Random %08x, ", tcp_iss);
2057 #endif
2058 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2059 			tcp_iss += addin + TCP_ISSINCR;
2060 #ifdef TCPISS_DEBUG
2061 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
2062 #endif
2063 		} else {
2064 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2065 			tcp_iss += tcp_iss_seq;
2066 			tcp_iss_seq += TCP_ISSINCR;
2067 #ifdef TCPISS_DEBUG
2068 			printf("ISS %08x\n", tcp_iss);
2069 #endif
2070 		}
2071 	}
2072 
2073 	if (tcp_compat_42) {
2074 		/*
2075 		 * Limit it to the positive range for really old TCP
2076 		 * implementations.
2077 		 */
2078 		if (tcp_iss >= 0x80000000)
2079 			tcp_iss &= 0x7fffffff;		/* XXX */
2080 	}
2081 
2082 	return (tcp_iss);
2083 }
2084 
2085 #ifdef IPSEC
2086 /* compute ESP/AH header size for TCP, including outer IP header. */
2087 size_t
2088 ipsec4_hdrsiz_tcp(tp)
2089 	struct tcpcb *tp;
2090 {
2091 	struct inpcb *inp;
2092 	size_t hdrsiz;
2093 
2094 	/* XXX mapped addr case (tp->t_in6pcb) */
2095 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
2096 		return 0;
2097 	switch (tp->t_family) {
2098 	case AF_INET:
2099 		/* XXX: should use currect direction. */
2100 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
2101 		break;
2102 	default:
2103 		hdrsiz = 0;
2104 		break;
2105 	}
2106 
2107 	return hdrsiz;
2108 }
2109 
2110 #ifdef INET6
2111 size_t
2112 ipsec6_hdrsiz_tcp(tp)
2113 	struct tcpcb *tp;
2114 {
2115 	struct in6pcb *in6p;
2116 	size_t hdrsiz;
2117 
2118 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
2119 		return 0;
2120 	switch (tp->t_family) {
2121 	case AF_INET6:
2122 		/* XXX: should use currect direction. */
2123 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
2124 		break;
2125 	case AF_INET:
2126 		/* mapped address case - tricky */
2127 	default:
2128 		hdrsiz = 0;
2129 		break;
2130 	}
2131 
2132 	return hdrsiz;
2133 }
2134 #endif
2135 #endif /*IPSEC*/
2136 
2137 /*
2138  * Determine the length of the TCP options for this connection.
2139  *
2140  * XXX:  What do we do for SACK, when we add that?  Just reserve
2141  *       all of the space?  Otherwise we can't exactly be incrementing
2142  *       cwnd by an amount that varies depending on the amount we last
2143  *       had to SACK!
2144  */
2145 
2146 u_int
2147 tcp_optlen(tp)
2148 	struct tcpcb *tp;
2149 {
2150 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
2151 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
2152 		return TCPOLEN_TSTAMP_APPA;
2153 	else
2154 		return 0;
2155 }
2156