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