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