xref: /freebsd/sys/netinet/tcp_subr.c (revision 94942af266ac119ede0ca836f9aa5a5ac0582938)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
30  * $FreeBSD$
31  */
32 
33 #include "opt_compat.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_mac.h"
38 #include "opt_tcpdebug.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/callout.h>
43 #include <sys/kernel.h>
44 #include <sys/sysctl.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #ifdef INET6
48 #include <sys/domain.h>
49 #endif
50 #include <sys/priv.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/protosw.h>
55 #include <sys/random.h>
56 
57 #include <vm/uma.h>
58 
59 #include <net/route.h>
60 #include <net/if.h>
61 
62 #include <netinet/in.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #ifdef INET6
66 #include <netinet/ip6.h>
67 #endif
68 #include <netinet/in_pcb.h>
69 #ifdef INET6
70 #include <netinet6/in6_pcb.h>
71 #endif
72 #include <netinet/in_var.h>
73 #include <netinet/ip_var.h>
74 #ifdef INET6
75 #include <netinet6/ip6_var.h>
76 #include <netinet6/scope6_var.h>
77 #include <netinet6/nd6.h>
78 #endif
79 #include <netinet/ip_icmp.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #ifdef INET6
86 #include <netinet6/tcp6_var.h>
87 #endif
88 #include <netinet/tcpip.h>
89 #ifdef TCPDEBUG
90 #include <netinet/tcp_debug.h>
91 #endif
92 #include <netinet6/ip6protosw.h>
93 
94 #ifdef IPSEC
95 #include <netinet6/ipsec.h>
96 #ifdef INET6
97 #include <netinet6/ipsec6.h>
98 #endif
99 #include <netkey/key.h>
100 #endif /*IPSEC*/
101 
102 #ifdef FAST_IPSEC
103 #include <netipsec/ipsec.h>
104 #include <netipsec/xform.h>
105 #ifdef INET6
106 #include <netipsec/ipsec6.h>
107 #endif
108 #include <netipsec/key.h>
109 #define	IPSEC
110 #endif /*FAST_IPSEC*/
111 
112 #include <machine/in_cksum.h>
113 #include <sys/md5.h>
114 
115 #include <security/mac/mac_framework.h>
116 
117 int	tcp_mssdflt = TCP_MSS;
118 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
119     &tcp_mssdflt, 0, "Default TCP Maximum Segment Size");
120 
121 #ifdef INET6
122 int	tcp_v6mssdflt = TCP6_MSS;
123 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
124     CTLFLAG_RW, &tcp_v6mssdflt , 0,
125     "Default TCP Maximum Segment Size for IPv6");
126 #endif
127 
128 /*
129  * Minimum MSS we accept and use. This prevents DoS attacks where
130  * we are forced to a ridiculous low MSS like 20 and send hundreds
131  * of packets instead of one. The effect scales with the available
132  * bandwidth and quickly saturates the CPU and network interface
133  * with packet generation and sending. Set to zero to disable MINMSS
134  * checking. This setting prevents us from sending too small packets.
135  */
136 int	tcp_minmss = TCP_MINMSS;
137 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW,
138     &tcp_minmss , 0, "Minmum TCP Maximum Segment Size");
139 
140 int	tcp_do_rfc1323 = 1;
141 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
142     &tcp_do_rfc1323, 0, "Enable rfc1323 (high performance TCP) extensions");
143 
144 static int	tcp_tcbhashsize = 0;
145 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
146     &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
147 
148 static int	do_tcpdrain = 1;
149 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW,
150     &do_tcpdrain, 0,
151     "Enable tcp_drain routine for extra help when low on mbufs");
152 
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
154     &tcbinfo.ipi_count, 0, "Number of active PCBs");
155 
156 static int	icmp_may_rst = 1;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW,
158     &icmp_may_rst, 0,
159     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
160 
161 static int	tcp_isn_reseed_interval = 0;
162 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
163     &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
164 
165 /*
166  * TCP bandwidth limiting sysctls.  Note that the default lower bound of
167  * 1024 exists only for debugging.  A good production default would be
168  * something like 6100.
169  */
170 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, inflight, CTLFLAG_RW, 0,
171     "TCP inflight data limiting");
172 
173 static int	tcp_inflight_enable = 1;
174 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, enable, CTLFLAG_RW,
175     &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
176 
177 static int	tcp_inflight_debug = 0;
178 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, debug, CTLFLAG_RW,
179     &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
180 
181 static int	tcp_inflight_rttthresh;
182 SYSCTL_PROC(_net_inet_tcp_inflight, OID_AUTO, rttthresh, CTLTYPE_INT|CTLFLAG_RW,
183     &tcp_inflight_rttthresh, 0, sysctl_msec_to_ticks, "I",
184     "RTT threshold below which inflight will deactivate itself");
185 
186 static int	tcp_inflight_min = 6144;
187 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, min, CTLFLAG_RW,
188     &tcp_inflight_min, 0, "Lower-bound for TCP inflight window");
189 
190 static int	tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
191 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, max, CTLFLAG_RW,
192     &tcp_inflight_max, 0, "Upper-bound for TCP inflight window");
193 
194 static int	tcp_inflight_stab = 20;
195 SYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, stab, CTLFLAG_RW,
196     &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets");
197 
198 uma_zone_t sack_hole_zone;
199 
200 static struct inpcb *tcp_notify(struct inpcb *, int);
201 static void	tcp_isn_tick(void *);
202 
203 /*
204  * Target size of TCP PCB hash tables. Must be a power of two.
205  *
206  * Note that this can be overridden by the kernel environment
207  * variable net.inet.tcp.tcbhashsize
208  */
209 #ifndef TCBHASHSIZE
210 #define TCBHASHSIZE	512
211 #endif
212 
213 /*
214  * XXX
215  * Callouts should be moved into struct tcp directly.  They are currently
216  * separate because the tcpcb structure is exported to userland for sysctl
217  * parsing purposes, which do not know about callouts.
218  */
219 struct tcpcb_mem {
220 	struct	tcpcb		tcb;
221 	struct	tcp_timer	tt;
222 };
223 
224 static uma_zone_t tcpcb_zone;
225 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
226 struct callout isn_callout;
227 static struct mtx isn_mtx;
228 
229 #define	ISN_LOCK_INIT()	mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
230 #define	ISN_LOCK()	mtx_lock(&isn_mtx)
231 #define	ISN_UNLOCK()	mtx_unlock(&isn_mtx)
232 
233 /*
234  * TCP initialization.
235  */
236 static void
237 tcp_zone_change(void *tag)
238 {
239 
240 	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
241 	uma_zone_set_max(tcpcb_zone, maxsockets);
242 	tcp_tw_zone_change();
243 }
244 
245 static int
246 tcp_inpcb_init(void *mem, int size, int flags)
247 {
248 	struct inpcb *inp = mem;
249 
250 	INP_LOCK_INIT(inp, "inp", "tcpinp");
251 	return (0);
252 }
253 
254 void
255 tcp_init(void)
256 {
257 
258 	int hashsize = TCBHASHSIZE;
259 	tcp_delacktime = TCPTV_DELACK;
260 	tcp_keepinit = TCPTV_KEEP_INIT;
261 	tcp_keepidle = TCPTV_KEEP_IDLE;
262 	tcp_keepintvl = TCPTV_KEEPINTVL;
263 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
264 	tcp_msl = TCPTV_MSL;
265 	tcp_rexmit_min = TCPTV_MIN;
266 	tcp_rexmit_slop = TCPTV_CPU_VAR;
267 	tcp_inflight_rttthresh = TCPTV_INFLIGHT_RTTTHRESH;
268 	tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
269 
270 	INP_INFO_LOCK_INIT(&tcbinfo, "tcp");
271 	LIST_INIT(&tcb);
272 	tcbinfo.ipi_listhead = &tcb;
273 	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
274 	if (!powerof2(hashsize)) {
275 		printf("WARNING: TCB hash size not a power of 2\n");
276 		hashsize = 512; /* safe default */
277 	}
278 	tcp_tcbhashsize = hashsize;
279 	tcbinfo.ipi_hashbase = hashinit(hashsize, M_PCB,
280 	    &tcbinfo.ipi_hashmask);
281 	tcbinfo.ipi_porthashbase = hashinit(hashsize, M_PCB,
282 	    &tcbinfo.ipi_porthashmask);
283 	tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb),
284 	    NULL, NULL, tcp_inpcb_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
285 	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
286 #ifdef INET6
287 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
288 #else /* INET6 */
289 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
290 #endif /* INET6 */
291 	if (max_protohdr < TCP_MINPROTOHDR)
292 		max_protohdr = TCP_MINPROTOHDR;
293 	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
294 		panic("tcp_init");
295 #undef TCP_MINPROTOHDR
296 	/*
297 	 * These have to be type stable for the benefit of the timers.
298 	 */
299 	tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
300 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
301 	uma_zone_set_max(tcpcb_zone, maxsockets);
302 	tcp_tw_init();
303 	syncache_init();
304 	tcp_hc_init();
305 	tcp_reass_init();
306 	ISN_LOCK_INIT();
307 	callout_init(&isn_callout, CALLOUT_MPSAFE);
308 	tcp_isn_tick(NULL);
309 	EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
310 		SHUTDOWN_PRI_DEFAULT);
311 	sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
312 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
313 	EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
314 		EVENTHANDLER_PRI_ANY);
315 }
316 
317 void
318 tcp_fini(void *xtp)
319 {
320 
321 	callout_stop(&isn_callout);
322 }
323 
324 /*
325  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
326  * tcp_template used to store this data in mbufs, but we now recopy it out
327  * of the tcpcb each time to conserve mbufs.
328  */
329 void
330 tcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
331 {
332 	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
333 
334 	INP_LOCK_ASSERT(inp);
335 
336 #ifdef INET6
337 	if ((inp->inp_vflag & INP_IPV6) != 0) {
338 		struct ip6_hdr *ip6;
339 
340 		ip6 = (struct ip6_hdr *)ip_ptr;
341 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
342 			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
343 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
344 			(IPV6_VERSION & IPV6_VERSION_MASK);
345 		ip6->ip6_nxt = IPPROTO_TCP;
346 		ip6->ip6_plen = sizeof(struct tcphdr);
347 		ip6->ip6_src = inp->in6p_laddr;
348 		ip6->ip6_dst = inp->in6p_faddr;
349 	} else
350 #endif
351 	{
352 		struct ip *ip;
353 
354 		ip = (struct ip *)ip_ptr;
355 		ip->ip_v = IPVERSION;
356 		ip->ip_hl = 5;
357 		ip->ip_tos = inp->inp_ip_tos;
358 		ip->ip_len = 0;
359 		ip->ip_id = 0;
360 		ip->ip_off = 0;
361 		ip->ip_ttl = inp->inp_ip_ttl;
362 		ip->ip_sum = 0;
363 		ip->ip_p = IPPROTO_TCP;
364 		ip->ip_src = inp->inp_laddr;
365 		ip->ip_dst = inp->inp_faddr;
366 	}
367 	th->th_sport = inp->inp_lport;
368 	th->th_dport = inp->inp_fport;
369 	th->th_seq = 0;
370 	th->th_ack = 0;
371 	th->th_x2 = 0;
372 	th->th_off = 5;
373 	th->th_flags = 0;
374 	th->th_win = 0;
375 	th->th_urp = 0;
376 	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
377 }
378 
379 /*
380  * Create template to be used to send tcp packets on a connection.
381  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
382  * use for this function is in keepalives, which use tcp_respond.
383  */
384 struct tcptemp *
385 tcpip_maketemplate(struct inpcb *inp)
386 {
387 	struct mbuf *m;
388 	struct tcptemp *n;
389 
390 	m = m_get(M_DONTWAIT, MT_DATA);
391 	if (m == NULL)
392 		return (0);
393 	m->m_len = sizeof(struct tcptemp);
394 	n = mtod(m, struct tcptemp *);
395 
396 	tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
397 	return (n);
398 }
399 
400 /*
401  * Send a single message to the TCP at address specified by
402  * the given TCP/IP header.  If m == NULL, then we make a copy
403  * of the tcpiphdr at ti and send directly to the addressed host.
404  * This is used to force keep alive messages out using the TCP
405  * template for a connection.  If flags are given then we send
406  * a message back to the TCP which originated the * segment ti,
407  * and discard the mbuf containing it and any other attached mbufs.
408  *
409  * In any case the ack and sequence number of the transmitted
410  * segment are as specified by the parameters.
411  *
412  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
413  */
414 void
415 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
416     tcp_seq ack, tcp_seq seq, int flags)
417 {
418 	int tlen;
419 	int win = 0;
420 	struct ip *ip;
421 	struct tcphdr *nth;
422 #ifdef INET6
423 	struct ip6_hdr *ip6;
424 	int isipv6;
425 #endif /* INET6 */
426 	int ipflags = 0;
427 	struct inpcb *inp;
428 
429 	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
430 
431 #ifdef INET6
432 	isipv6 = ((struct ip *)ipgen)->ip_v == 6;
433 	ip6 = ipgen;
434 #endif /* INET6 */
435 	ip = ipgen;
436 
437 	if (tp != NULL) {
438 		inp = tp->t_inpcb;
439 		KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
440 		INP_LOCK_ASSERT(inp);
441 	} else
442 		inp = NULL;
443 
444 	if (tp != NULL) {
445 		if (!(flags & TH_RST)) {
446 			win = sbspace(&inp->inp_socket->so_rcv);
447 			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
448 				win = (long)TCP_MAXWIN << tp->rcv_scale;
449 		}
450 	}
451 	if (m == NULL) {
452 		m = m_gethdr(M_DONTWAIT, MT_DATA);
453 		if (m == NULL)
454 			return;
455 		tlen = 0;
456 		m->m_data += max_linkhdr;
457 #ifdef INET6
458 		if (isipv6) {
459 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
460 			      sizeof(struct ip6_hdr));
461 			ip6 = mtod(m, struct ip6_hdr *);
462 			nth = (struct tcphdr *)(ip6 + 1);
463 		} else
464 #endif /* INET6 */
465 	      {
466 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
467 		ip = mtod(m, struct ip *);
468 		nth = (struct tcphdr *)(ip + 1);
469 	      }
470 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
471 		flags = TH_ACK;
472 	} else {
473 		m_freem(m->m_next);
474 		m->m_next = NULL;
475 		m->m_data = (caddr_t)ipgen;
476 		/* m_len is set later */
477 		tlen = 0;
478 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
479 #ifdef INET6
480 		if (isipv6) {
481 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
482 			nth = (struct tcphdr *)(ip6 + 1);
483 		} else
484 #endif /* INET6 */
485 	      {
486 		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
487 		nth = (struct tcphdr *)(ip + 1);
488 	      }
489 		if (th != nth) {
490 			/*
491 			 * this is usually a case when an extension header
492 			 * exists between the IPv6 header and the
493 			 * TCP header.
494 			 */
495 			nth->th_sport = th->th_sport;
496 			nth->th_dport = th->th_dport;
497 		}
498 		xchg(nth->th_dport, nth->th_sport, n_short);
499 #undef xchg
500 	}
501 #ifdef INET6
502 	if (isipv6) {
503 		ip6->ip6_flow = 0;
504 		ip6->ip6_vfc = IPV6_VERSION;
505 		ip6->ip6_nxt = IPPROTO_TCP;
506 		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
507 						tlen));
508 		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
509 	} else
510 #endif
511 	{
512 		tlen += sizeof (struct tcpiphdr);
513 		ip->ip_len = tlen;
514 		ip->ip_ttl = ip_defttl;
515 		if (path_mtu_discovery)
516 			ip->ip_off |= IP_DF;
517 	}
518 	m->m_len = tlen;
519 	m->m_pkthdr.len = tlen;
520 	m->m_pkthdr.rcvif = NULL;
521 #ifdef MAC
522 	if (inp != NULL) {
523 		/*
524 		 * Packet is associated with a socket, so allow the
525 		 * label of the response to reflect the socket label.
526 		 */
527 		INP_LOCK_ASSERT(inp);
528 		mac_create_mbuf_from_inpcb(inp, m);
529 	} else {
530 		/*
531 		 * Packet is not associated with a socket, so possibly
532 		 * update the label in place.
533 		 */
534 		mac_reflect_mbuf_tcp(m);
535 	}
536 #endif
537 	nth->th_seq = htonl(seq);
538 	nth->th_ack = htonl(ack);
539 	nth->th_x2 = 0;
540 	nth->th_off = sizeof (struct tcphdr) >> 2;
541 	nth->th_flags = flags;
542 	if (tp != NULL)
543 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
544 	else
545 		nth->th_win = htons((u_short)win);
546 	nth->th_urp = 0;
547 #ifdef INET6
548 	if (isipv6) {
549 		nth->th_sum = 0;
550 		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
551 					sizeof(struct ip6_hdr),
552 					tlen - sizeof(struct ip6_hdr));
553 		ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
554 		    NULL, NULL);
555 	} else
556 #endif /* INET6 */
557 	{
558 		nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
559 		    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
560 		m->m_pkthdr.csum_flags = CSUM_TCP;
561 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
562 	}
563 #ifdef TCPDEBUG
564 	if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
565 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
566 #endif
567 #ifdef INET6
568 	if (isipv6)
569 		(void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp);
570 	else
571 #endif /* INET6 */
572 	(void) ip_output(m, NULL, NULL, ipflags, NULL, inp);
573 }
574 
575 /*
576  * Create a new TCP control block, making an
577  * empty reassembly queue and hooking it to the argument
578  * protocol control block.  The `inp' parameter must have
579  * come from the zone allocator set up in tcp_init().
580  */
581 struct tcpcb *
582 tcp_newtcpcb(struct inpcb *inp)
583 {
584 	struct tcpcb_mem *tm;
585 	struct tcpcb *tp;
586 #ifdef INET6
587 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
588 #endif /* INET6 */
589 
590 	tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO);
591 	if (tm == NULL)
592 		return (NULL);
593 	tp = &tm->tcb;
594 	tp->t_timers = &tm->tt;
595 	/*	LIST_INIT(&tp->t_segq); */	/* XXX covered by M_ZERO */
596 	tp->t_maxseg = tp->t_maxopd =
597 #ifdef INET6
598 		isipv6 ? tcp_v6mssdflt :
599 #endif /* INET6 */
600 		tcp_mssdflt;
601 
602 	/* Set up our timeouts. */
603 	if (NET_CALLOUT_MPSAFE)
604 		callout_init_mtx(&tp->t_timers->tt_timer, &inp->inp_mtx,
605 		    CALLOUT_RETURNUNLOCKED);
606 	else
607 		callout_init_mtx(&tp->t_timers->tt_timer, &inp->inp_mtx,
608 		    (CALLOUT_RETURNUNLOCKED|CALLOUT_NETGIANT));
609 
610 	if (tcp_do_rfc1323)
611 		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
612 	if (tcp_do_sack)
613 		tp->t_flags |= TF_SACK_PERMIT;
614 	TAILQ_INIT(&tp->snd_holes);
615 	tp->t_inpcb = inp;	/* XXX */
616 	/*
617 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
618 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
619 	 * reasonable initial retransmit time.
620 	 */
621 	tp->t_srtt = TCPTV_SRTTBASE;
622 	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
623 	tp->t_rttmin = tcp_rexmit_min;
624 	tp->t_rxtcur = TCPTV_RTOBASE;
625 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
626 	tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
627 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
628 	tp->t_rcvtime = ticks;
629 	tp->t_bw_rtttime = ticks;
630 	/*
631 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
632 	 * because the socket may be bound to an IPv6 wildcard address,
633 	 * which may match an IPv4-mapped IPv6 address.
634 	 */
635 	inp->inp_ip_ttl = ip_defttl;
636 	inp->inp_ppcb = tp;
637 	return (tp);		/* XXX */
638 }
639 
640 /*
641  * Drop a TCP connection, reporting
642  * the specified error.  If connection is synchronized,
643  * then send a RST to peer.
644  */
645 struct tcpcb *
646 tcp_drop(struct tcpcb *tp, int errno)
647 {
648 	struct socket *so = tp->t_inpcb->inp_socket;
649 
650 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
651 	INP_LOCK_ASSERT(tp->t_inpcb);
652 
653 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
654 		tp->t_state = TCPS_CLOSED;
655 		(void) tcp_output(tp);
656 		tcpstat.tcps_drops++;
657 	} else
658 		tcpstat.tcps_conndrops++;
659 	if (errno == ETIMEDOUT && tp->t_softerror)
660 		errno = tp->t_softerror;
661 	so->so_error = errno;
662 	return (tcp_close(tp));
663 }
664 
665 void
666 tcp_discardcb(struct tcpcb *tp)
667 {
668 	struct tseg_qent *q;
669 	struct inpcb *inp = tp->t_inpcb;
670 	struct socket *so = inp->inp_socket;
671 #ifdef INET6
672 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
673 #endif /* INET6 */
674 
675 	INP_LOCK_ASSERT(inp);
676 
677 	/*
678 	 * Make sure that all of our timers are stopped before we
679 	 * delete the PCB.
680 	 *
681 	 * XXX: callout_stop() may race and a callout may already
682 	 * try to obtain the INP_LOCK.  Only callout_drain() would
683 	 * stop this but it would cause a LOR thus we can't use it.
684 	 * The tcp_timer() function contains a lot of checks to
685 	 * handle this case rather gracefully.
686 	 */
687 	tp->t_timers->tt_active = 0;
688 	callout_stop(&tp->t_timers->tt_timer);
689 
690 	/*
691 	 * If we got enough samples through the srtt filter,
692 	 * save the rtt and rttvar in the routing entry.
693 	 * 'Enough' is arbitrarily defined as 4 rtt samples.
694 	 * 4 samples is enough for the srtt filter to converge
695 	 * to within enough % of the correct value; fewer samples
696 	 * and we could save a bogus rtt. The danger is not high
697 	 * as tcp quickly recovers from everything.
698 	 * XXX: Works very well but needs some more statistics!
699 	 */
700 	if (tp->t_rttupdated >= 4) {
701 		struct hc_metrics_lite metrics;
702 		u_long ssthresh;
703 
704 		bzero(&metrics, sizeof(metrics));
705 		/*
706 		 * Update the ssthresh always when the conditions below
707 		 * are satisfied. This gives us better new start value
708 		 * for the congestion avoidance for new connections.
709 		 * ssthresh is only set if packet loss occured on a session.
710 		 *
711 		 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
712 		 * being torn down.  Ideally this code would not use 'so'.
713 		 */
714 		ssthresh = tp->snd_ssthresh;
715 		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
716 			/*
717 			 * convert the limit from user data bytes to
718 			 * packets then to packet data bytes.
719 			 */
720 			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
721 			if (ssthresh < 2)
722 				ssthresh = 2;
723 			ssthresh *= (u_long)(tp->t_maxseg +
724 #ifdef INET6
725 				      (isipv6 ? sizeof (struct ip6_hdr) +
726 					       sizeof (struct tcphdr) :
727 #endif
728 				       sizeof (struct tcpiphdr)
729 #ifdef INET6
730 				       )
731 #endif
732 				      );
733 		} else
734 			ssthresh = 0;
735 		metrics.rmx_ssthresh = ssthresh;
736 
737 		metrics.rmx_rtt = tp->t_srtt;
738 		metrics.rmx_rttvar = tp->t_rttvar;
739 		/* XXX: This wraps if the pipe is more than 4 Gbit per second */
740 		metrics.rmx_bandwidth = tp->snd_bandwidth;
741 		metrics.rmx_cwnd = tp->snd_cwnd;
742 		metrics.rmx_sendpipe = 0;
743 		metrics.rmx_recvpipe = 0;
744 
745 		tcp_hc_update(&inp->inp_inc, &metrics);
746 	}
747 
748 	/* free the reassembly queue, if any */
749 	while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
750 		LIST_REMOVE(q, tqe_q);
751 		m_freem(q->tqe_m);
752 		uma_zfree(tcp_reass_zone, q);
753 		tp->t_segqlen--;
754 		tcp_reass_qsize--;
755 	}
756 	tcp_free_sackholes(tp);
757 	inp->inp_ppcb = NULL;
758 	tp->t_inpcb = NULL;
759 	uma_zfree(tcpcb_zone, tp);
760 }
761 
762 /*
763  * Attempt to close a TCP control block, marking it as dropped, and freeing
764  * the socket if we hold the only reference.
765  */
766 struct tcpcb *
767 tcp_close(struct tcpcb *tp)
768 {
769 	struct inpcb *inp = tp->t_inpcb;
770 	struct socket *so;
771 
772 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
773 	INP_LOCK_ASSERT(inp);
774 
775 	in_pcbdrop(inp);
776 	tcpstat.tcps_closed++;
777 	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
778 	so = inp->inp_socket;
779 	soisdisconnected(so);
780 	if (inp->inp_vflag & INP_SOCKREF) {
781 		KASSERT(so->so_state & SS_PROTOREF,
782 		    ("tcp_close: !SS_PROTOREF"));
783 		inp->inp_vflag &= ~INP_SOCKREF;
784 		INP_UNLOCK(inp);
785 		ACCEPT_LOCK();
786 		SOCK_LOCK(so);
787 		so->so_state &= ~SS_PROTOREF;
788 		sofree(so);
789 		return (NULL);
790 	}
791 	return (tp);
792 }
793 
794 void
795 tcp_drain(void)
796 {
797 
798 	if (do_tcpdrain) {
799 		struct inpcb *inpb;
800 		struct tcpcb *tcpb;
801 		struct tseg_qent *te;
802 
803 	/*
804 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
805 	 * if there is one...
806 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
807 	 *      reassembly queue should be flushed, but in a situation
808 	 *	where we're really low on mbufs, this is potentially
809 	 *	usefull.
810 	 */
811 		INP_INFO_RLOCK(&tcbinfo);
812 		LIST_FOREACH(inpb, tcbinfo.ipi_listhead, inp_list) {
813 			if (inpb->inp_vflag & INP_TIMEWAIT)
814 				continue;
815 			INP_LOCK(inpb);
816 			if ((tcpb = intotcpcb(inpb)) != NULL) {
817 				while ((te = LIST_FIRST(&tcpb->t_segq))
818 			            != NULL) {
819 					LIST_REMOVE(te, tqe_q);
820 					m_freem(te->tqe_m);
821 					uma_zfree(tcp_reass_zone, te);
822 					tcpb->t_segqlen--;
823 					tcp_reass_qsize--;
824 				}
825 				tcp_clean_sackreport(tcpb);
826 			}
827 			INP_UNLOCK(inpb);
828 		}
829 		INP_INFO_RUNLOCK(&tcbinfo);
830 	}
831 }
832 
833 /*
834  * Notify a tcp user of an asynchronous error;
835  * store error as soft error, but wake up user
836  * (for now, won't do anything until can select for soft error).
837  *
838  * Do not wake up user since there currently is no mechanism for
839  * reporting soft errors (yet - a kqueue filter may be added).
840  */
841 static struct inpcb *
842 tcp_notify(struct inpcb *inp, int error)
843 {
844 	struct tcpcb *tp;
845 
846 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
847 	INP_LOCK_ASSERT(inp);
848 
849 	if ((inp->inp_vflag & INP_TIMEWAIT) ||
850 	    (inp->inp_vflag & INP_DROPPED))
851 		return (inp);
852 
853 	tp = intotcpcb(inp);
854 	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
855 
856 	/*
857 	 * Ignore some errors if we are hooked up.
858 	 * If connection hasn't completed, has retransmitted several times,
859 	 * and receives a second error, give up now.  This is better
860 	 * than waiting a long time to establish a connection that
861 	 * can never complete.
862 	 */
863 	if (tp->t_state == TCPS_ESTABLISHED &&
864 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
865 	     error == EHOSTDOWN)) {
866 		return (inp);
867 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
868 	    tp->t_softerror) {
869 		tp = tcp_drop(tp, error);
870 		if (tp != NULL)
871 			return (inp);
872 		else
873 			return (NULL);
874 	} else {
875 		tp->t_softerror = error;
876 		return (inp);
877 	}
878 #if 0
879 	wakeup( &so->so_timeo);
880 	sorwakeup(so);
881 	sowwakeup(so);
882 #endif
883 }
884 
885 static int
886 tcp_pcblist(SYSCTL_HANDLER_ARGS)
887 {
888 	int error, i, n;
889 	struct inpcb *inp, **inp_list;
890 	inp_gen_t gencnt;
891 	struct xinpgen xig;
892 
893 	/*
894 	 * The process of preparing the TCB list is too time-consuming and
895 	 * resource-intensive to repeat twice on every request.
896 	 */
897 	if (req->oldptr == NULL) {
898 		n = tcbinfo.ipi_count;
899 		req->oldidx = 2 * (sizeof xig)
900 			+ (n + n/8) * sizeof(struct xtcpcb);
901 		return (0);
902 	}
903 
904 	if (req->newptr != NULL)
905 		return (EPERM);
906 
907 	/*
908 	 * OK, now we're committed to doing something.
909 	 */
910 	INP_INFO_RLOCK(&tcbinfo);
911 	gencnt = tcbinfo.ipi_gencnt;
912 	n = tcbinfo.ipi_count;
913 	INP_INFO_RUNLOCK(&tcbinfo);
914 
915 	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
916 		+ n * sizeof(struct xtcpcb));
917 	if (error != 0)
918 		return (error);
919 
920 	xig.xig_len = sizeof xig;
921 	xig.xig_count = n;
922 	xig.xig_gen = gencnt;
923 	xig.xig_sogen = so_gencnt;
924 	error = SYSCTL_OUT(req, &xig, sizeof xig);
925 	if (error)
926 		return (error);
927 
928 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
929 	if (inp_list == NULL)
930 		return (ENOMEM);
931 
932 	INP_INFO_RLOCK(&tcbinfo);
933 	for (inp = LIST_FIRST(tcbinfo.ipi_listhead), i = 0; inp != NULL && i
934 	    < n; inp = LIST_NEXT(inp, inp_list)) {
935 		INP_LOCK(inp);
936 		if (inp->inp_gencnt <= gencnt) {
937 			/*
938 			 * XXX: This use of cr_cansee(), introduced with
939 			 * TCP state changes, is not quite right, but for
940 			 * now, better than nothing.
941 			 */
942 			if (inp->inp_vflag & INP_TIMEWAIT) {
943 				if (intotw(inp) != NULL)
944 					error = cr_cansee(req->td->td_ucred,
945 					    intotw(inp)->tw_cred);
946 				else
947 					error = EINVAL;	/* Skip this inp. */
948 			} else
949 				error = cr_canseesocket(req->td->td_ucred,
950 				    inp->inp_socket);
951 			if (error == 0)
952 				inp_list[i++] = inp;
953 		}
954 		INP_UNLOCK(inp);
955 	}
956 	INP_INFO_RUNLOCK(&tcbinfo);
957 	n = i;
958 
959 	error = 0;
960 	for (i = 0; i < n; i++) {
961 		inp = inp_list[i];
962 		INP_LOCK(inp);
963 		if (inp->inp_gencnt <= gencnt) {
964 			struct xtcpcb xt;
965 			void *inp_ppcb;
966 
967 			bzero(&xt, sizeof(xt));
968 			xt.xt_len = sizeof xt;
969 			/* XXX should avoid extra copy */
970 			bcopy(inp, &xt.xt_inp, sizeof *inp);
971 			inp_ppcb = inp->inp_ppcb;
972 			if (inp_ppcb == NULL)
973 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
974 			else if (inp->inp_vflag & INP_TIMEWAIT) {
975 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
976 				xt.xt_tp.t_state = TCPS_TIME_WAIT;
977 			} else
978 				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
979 			if (inp->inp_socket != NULL)
980 				sotoxsocket(inp->inp_socket, &xt.xt_socket);
981 			else {
982 				bzero(&xt.xt_socket, sizeof xt.xt_socket);
983 				xt.xt_socket.xso_protocol = IPPROTO_TCP;
984 			}
985 			xt.xt_inp.inp_gencnt = inp->inp_gencnt;
986 			INP_UNLOCK(inp);
987 			error = SYSCTL_OUT(req, &xt, sizeof xt);
988 		} else
989 			INP_UNLOCK(inp);
990 
991 	}
992 	if (!error) {
993 		/*
994 		 * Give the user an updated idea of our state.
995 		 * If the generation differs from what we told
996 		 * her before, she knows that something happened
997 		 * while we were processing this request, and it
998 		 * might be necessary to retry.
999 		 */
1000 		INP_INFO_RLOCK(&tcbinfo);
1001 		xig.xig_gen = tcbinfo.ipi_gencnt;
1002 		xig.xig_sogen = so_gencnt;
1003 		xig.xig_count = tcbinfo.ipi_count;
1004 		INP_INFO_RUNLOCK(&tcbinfo);
1005 		error = SYSCTL_OUT(req, &xig, sizeof xig);
1006 	}
1007 	free(inp_list, M_TEMP);
1008 	return (error);
1009 }
1010 
1011 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
1012     tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
1013 
1014 static int
1015 tcp_getcred(SYSCTL_HANDLER_ARGS)
1016 {
1017 	struct xucred xuc;
1018 	struct sockaddr_in addrs[2];
1019 	struct inpcb *inp;
1020 	int error;
1021 
1022 	error = priv_check_cred(req->td->td_ucred, PRIV_NETINET_GETCRED,
1023 	    SUSER_ALLOWJAIL);
1024 	if (error)
1025 		return (error);
1026 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1027 	if (error)
1028 		return (error);
1029 	INP_INFO_RLOCK(&tcbinfo);
1030 	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
1031 	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
1032 	if (inp == NULL) {
1033 		error = ENOENT;
1034 		goto outunlocked;
1035 	}
1036 	INP_LOCK(inp);
1037 	if (inp->inp_socket == NULL) {
1038 		error = ENOENT;
1039 		goto out;
1040 	}
1041 	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
1042 	if (error)
1043 		goto out;
1044 	cru2x(inp->inp_socket->so_cred, &xuc);
1045 out:
1046 	INP_UNLOCK(inp);
1047 outunlocked:
1048 	INP_INFO_RUNLOCK(&tcbinfo);
1049 	if (error == 0)
1050 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1051 	return (error);
1052 }
1053 
1054 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
1055     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1056     tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
1057 
1058 #ifdef INET6
1059 static int
1060 tcp6_getcred(SYSCTL_HANDLER_ARGS)
1061 {
1062 	struct xucred xuc;
1063 	struct sockaddr_in6 addrs[2];
1064 	struct inpcb *inp;
1065 	int error, mapped = 0;
1066 
1067 	error = priv_check_cred(req->td->td_ucred, PRIV_NETINET_GETCRED,
1068 	    SUSER_ALLOWJAIL);
1069 	if (error)
1070 		return (error);
1071 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1072 	if (error)
1073 		return (error);
1074 	if ((error = sa6_embedscope(&addrs[0], ip6_use_defzone)) != 0 ||
1075 	    (error = sa6_embedscope(&addrs[1], ip6_use_defzone)) != 0) {
1076 		return (error);
1077 	}
1078 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
1079 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
1080 			mapped = 1;
1081 		else
1082 			return (EINVAL);
1083 	}
1084 
1085 	INP_INFO_RLOCK(&tcbinfo);
1086 	if (mapped == 1)
1087 		inp = in_pcblookup_hash(&tcbinfo,
1088 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
1089 			addrs[1].sin6_port,
1090 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
1091 			addrs[0].sin6_port,
1092 			0, NULL);
1093 	else
1094 		inp = in6_pcblookup_hash(&tcbinfo,
1095 			&addrs[1].sin6_addr, addrs[1].sin6_port,
1096 			&addrs[0].sin6_addr, addrs[0].sin6_port, 0, NULL);
1097 	if (inp == NULL) {
1098 		error = ENOENT;
1099 		goto outunlocked;
1100 	}
1101 	INP_LOCK(inp);
1102 	if (inp->inp_socket == NULL) {
1103 		error = ENOENT;
1104 		goto out;
1105 	}
1106 	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
1107 	if (error)
1108 		goto out;
1109 	cru2x(inp->inp_socket->so_cred, &xuc);
1110 out:
1111 	INP_UNLOCK(inp);
1112 outunlocked:
1113 	INP_INFO_RUNLOCK(&tcbinfo);
1114 	if (error == 0)
1115 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1116 	return (error);
1117 }
1118 
1119 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
1120     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1121     tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
1122 #endif
1123 
1124 
1125 void
1126 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
1127 {
1128 	struct ip *ip = vip;
1129 	struct tcphdr *th;
1130 	struct in_addr faddr;
1131 	struct inpcb *inp;
1132 	struct tcpcb *tp;
1133 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1134 	struct icmp *icp;
1135 	struct in_conninfo inc;
1136 	tcp_seq icmp_tcp_seq;
1137 	int mtu;
1138 
1139 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
1140 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1141 		return;
1142 
1143 	if (cmd == PRC_MSGSIZE)
1144 		notify = tcp_mtudisc;
1145 	else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1146 		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
1147 		notify = tcp_drop_syn_sent;
1148 	/*
1149 	 * Redirects don't need to be handled up here.
1150 	 */
1151 	else if (PRC_IS_REDIRECT(cmd))
1152 		return;
1153 	/*
1154 	 * Source quench is depreciated.
1155 	 */
1156 	else if (cmd == PRC_QUENCH)
1157 		return;
1158 	/*
1159 	 * Hostdead is ugly because it goes linearly through all PCBs.
1160 	 * XXX: We never get this from ICMP, otherwise it makes an
1161 	 * excellent DoS attack on machines with many connections.
1162 	 */
1163 	else if (cmd == PRC_HOSTDEAD)
1164 		ip = NULL;
1165 	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
1166 		return;
1167 	if (ip != NULL) {
1168 		icp = (struct icmp *)((caddr_t)ip
1169 				      - offsetof(struct icmp, icmp_ip));
1170 		th = (struct tcphdr *)((caddr_t)ip
1171 				       + (ip->ip_hl << 2));
1172 		INP_INFO_WLOCK(&tcbinfo);
1173 		inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
1174 		    ip->ip_src, th->th_sport, 0, NULL);
1175 		if (inp != NULL)  {
1176 			INP_LOCK(inp);
1177 			if (!(inp->inp_vflag & INP_TIMEWAIT) &&
1178 			    !(inp->inp_vflag & INP_DROPPED) &&
1179 			    !(inp->inp_socket == NULL)) {
1180 				icmp_tcp_seq = htonl(th->th_seq);
1181 				tp = intotcpcb(inp);
1182 				if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
1183 				    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
1184 					if (cmd == PRC_MSGSIZE) {
1185 					    /*
1186 					     * MTU discovery:
1187 					     * If we got a needfrag set the MTU
1188 					     * in the route to the suggested new
1189 					     * value (if given) and then notify.
1190 					     */
1191 					    bzero(&inc, sizeof(inc));
1192 					    inc.inc_flags = 0;	/* IPv4 */
1193 					    inc.inc_faddr = faddr;
1194 
1195 					    mtu = ntohs(icp->icmp_nextmtu);
1196 					    /*
1197 					     * If no alternative MTU was
1198 					     * proposed, try the next smaller
1199 					     * one.  ip->ip_len has already
1200 					     * been swapped in icmp_input().
1201 					     */
1202 					    if (!mtu)
1203 						mtu = ip_next_mtu(ip->ip_len,
1204 						 1);
1205 					    if (mtu < max(296, (tcp_minmss)
1206 						 + sizeof(struct tcpiphdr)))
1207 						mtu = 0;
1208 					    if (!mtu)
1209 						mtu = tcp_mssdflt
1210 						 + sizeof(struct tcpiphdr);
1211 					    /*
1212 					     * Only cache the the MTU if it
1213 					     * is smaller than the interface
1214 					     * or route MTU.  tcp_mtudisc()
1215 					     * will do right thing by itself.
1216 					     */
1217 					    if (mtu <= tcp_maxmtu(&inc, NULL))
1218 						tcp_hc_updatemtu(&inc, mtu);
1219 					}
1220 
1221 					inp = (*notify)(inp, inetctlerrmap[cmd]);
1222 				}
1223 			}
1224 			if (inp != NULL)
1225 				INP_UNLOCK(inp);
1226 		} else {
1227 			inc.inc_fport = th->th_dport;
1228 			inc.inc_lport = th->th_sport;
1229 			inc.inc_faddr = faddr;
1230 			inc.inc_laddr = ip->ip_src;
1231 #ifdef INET6
1232 			inc.inc_isipv6 = 0;
1233 #endif
1234 			syncache_unreach(&inc, th);
1235 		}
1236 		INP_INFO_WUNLOCK(&tcbinfo);
1237 	} else
1238 		in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
1239 }
1240 
1241 #ifdef INET6
1242 void
1243 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
1244 {
1245 	struct tcphdr th;
1246 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1247 	struct ip6_hdr *ip6;
1248 	struct mbuf *m;
1249 	struct ip6ctlparam *ip6cp = NULL;
1250 	const struct sockaddr_in6 *sa6_src = NULL;
1251 	int off;
1252 	struct tcp_portonly {
1253 		u_int16_t th_sport;
1254 		u_int16_t th_dport;
1255 	} *thp;
1256 
1257 	if (sa->sa_family != AF_INET6 ||
1258 	    sa->sa_len != sizeof(struct sockaddr_in6))
1259 		return;
1260 
1261 	if (cmd == PRC_MSGSIZE)
1262 		notify = tcp_mtudisc;
1263 	else if (!PRC_IS_REDIRECT(cmd) &&
1264 		 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
1265 		return;
1266 	/* Source quench is depreciated. */
1267 	else if (cmd == PRC_QUENCH)
1268 		return;
1269 
1270 	/* if the parameter is from icmp6, decode it. */
1271 	if (d != NULL) {
1272 		ip6cp = (struct ip6ctlparam *)d;
1273 		m = ip6cp->ip6c_m;
1274 		ip6 = ip6cp->ip6c_ip6;
1275 		off = ip6cp->ip6c_off;
1276 		sa6_src = ip6cp->ip6c_src;
1277 	} else {
1278 		m = NULL;
1279 		ip6 = NULL;
1280 		off = 0;	/* fool gcc */
1281 		sa6_src = &sa6_any;
1282 	}
1283 
1284 	if (ip6 != NULL) {
1285 		struct in_conninfo inc;
1286 		/*
1287 		 * XXX: We assume that when IPV6 is non NULL,
1288 		 * M and OFF are valid.
1289 		 */
1290 
1291 		/* check if we can safely examine src and dst ports */
1292 		if (m->m_pkthdr.len < off + sizeof(*thp))
1293 			return;
1294 
1295 		bzero(&th, sizeof(th));
1296 		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
1297 
1298 		in6_pcbnotify(&tcbinfo, sa, th.th_dport,
1299 		    (struct sockaddr *)ip6cp->ip6c_src,
1300 		    th.th_sport, cmd, NULL, notify);
1301 
1302 		inc.inc_fport = th.th_dport;
1303 		inc.inc_lport = th.th_sport;
1304 		inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
1305 		inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
1306 		inc.inc_isipv6 = 1;
1307 		INP_INFO_WLOCK(&tcbinfo);
1308 		syncache_unreach(&inc, &th);
1309 		INP_INFO_WUNLOCK(&tcbinfo);
1310 	} else
1311 		in6_pcbnotify(&tcbinfo, sa, 0, (const struct sockaddr *)sa6_src,
1312 			      0, cmd, NULL, notify);
1313 }
1314 #endif /* INET6 */
1315 
1316 
1317 /*
1318  * Following is where TCP initial sequence number generation occurs.
1319  *
1320  * There are two places where we must use initial sequence numbers:
1321  * 1.  In SYN-ACK packets.
1322  * 2.  In SYN packets.
1323  *
1324  * All ISNs for SYN-ACK packets are generated by the syncache.  See
1325  * tcp_syncache.c for details.
1326  *
1327  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
1328  * depends on this property.  In addition, these ISNs should be
1329  * unguessable so as to prevent connection hijacking.  To satisfy
1330  * the requirements of this situation, the algorithm outlined in
1331  * RFC 1948 is used, with only small modifications.
1332  *
1333  * Implementation details:
1334  *
1335  * Time is based off the system timer, and is corrected so that it
1336  * increases by one megabyte per second.  This allows for proper
1337  * recycling on high speed LANs while still leaving over an hour
1338  * before rollover.
1339  *
1340  * As reading the *exact* system time is too expensive to be done
1341  * whenever setting up a TCP connection, we increment the time
1342  * offset in two ways.  First, a small random positive increment
1343  * is added to isn_offset for each connection that is set up.
1344  * Second, the function tcp_isn_tick fires once per clock tick
1345  * and increments isn_offset as necessary so that sequence numbers
1346  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
1347  * random positive increments serve only to ensure that the same
1348  * exact sequence number is never sent out twice (as could otherwise
1349  * happen when a port is recycled in less than the system tick
1350  * interval.)
1351  *
1352  * net.inet.tcp.isn_reseed_interval controls the number of seconds
1353  * between seeding of isn_secret.  This is normally set to zero,
1354  * as reseeding should not be necessary.
1355  *
1356  * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
1357  * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock.  In
1358  * general, this means holding an exclusive (write) lock.
1359  */
1360 
1361 #define ISN_BYTES_PER_SECOND 1048576
1362 #define ISN_STATIC_INCREMENT 4096
1363 #define ISN_RANDOM_INCREMENT (4096 - 1)
1364 
1365 static u_char isn_secret[32];
1366 static int isn_last_reseed;
1367 static u_int32_t isn_offset, isn_offset_old;
1368 static MD5_CTX isn_ctx;
1369 
1370 tcp_seq
1371 tcp_new_isn(struct tcpcb *tp)
1372 {
1373 	u_int32_t md5_buffer[4];
1374 	tcp_seq new_isn;
1375 
1376 	INP_LOCK_ASSERT(tp->t_inpcb);
1377 
1378 	ISN_LOCK();
1379 	/* Seed if this is the first use, reseed if requested. */
1380 	if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
1381 	     (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
1382 		< (u_int)ticks))) {
1383 		read_random(&isn_secret, sizeof(isn_secret));
1384 		isn_last_reseed = ticks;
1385 	}
1386 
1387 	/* Compute the md5 hash and return the ISN. */
1388 	MD5Init(&isn_ctx);
1389 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
1390 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
1391 #ifdef INET6
1392 	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
1393 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
1394 			  sizeof(struct in6_addr));
1395 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
1396 			  sizeof(struct in6_addr));
1397 	} else
1398 #endif
1399 	{
1400 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
1401 			  sizeof(struct in_addr));
1402 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
1403 			  sizeof(struct in_addr));
1404 	}
1405 	MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
1406 	MD5Final((u_char *) &md5_buffer, &isn_ctx);
1407 	new_isn = (tcp_seq) md5_buffer[0];
1408 	isn_offset += ISN_STATIC_INCREMENT +
1409 		(arc4random() & ISN_RANDOM_INCREMENT);
1410 	new_isn += isn_offset;
1411 	ISN_UNLOCK();
1412 	return (new_isn);
1413 }
1414 
1415 /*
1416  * Increment the offset to the next ISN_BYTES_PER_SECOND / hz boundary
1417  * to keep time flowing at a relatively constant rate.  If the random
1418  * increments have already pushed us past the projected offset, do nothing.
1419  */
1420 static void
1421 tcp_isn_tick(void *xtp)
1422 {
1423 	u_int32_t projected_offset;
1424 
1425 	ISN_LOCK();
1426 	projected_offset = isn_offset_old + ISN_BYTES_PER_SECOND / 100;
1427 
1428 	if (projected_offset > isn_offset)
1429 		isn_offset = projected_offset;
1430 
1431 	isn_offset_old = isn_offset;
1432 	callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL);
1433 	ISN_UNLOCK();
1434 }
1435 
1436 /*
1437  * When a specific ICMP unreachable message is received and the
1438  * connection state is SYN-SENT, drop the connection.  This behavior
1439  * is controlled by the icmp_may_rst sysctl.
1440  */
1441 struct inpcb *
1442 tcp_drop_syn_sent(struct inpcb *inp, int errno)
1443 {
1444 	struct tcpcb *tp;
1445 
1446 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1447 	INP_LOCK_ASSERT(inp);
1448 
1449 	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1450 	    (inp->inp_vflag & INP_DROPPED))
1451 		return (inp);
1452 
1453 	tp = intotcpcb(inp);
1454 	if (tp->t_state != TCPS_SYN_SENT)
1455 		return (inp);
1456 
1457 	tp = tcp_drop(tp, errno);
1458 	if (tp != NULL)
1459 		return (inp);
1460 	else
1461 		return (NULL);
1462 }
1463 
1464 /*
1465  * When `need fragmentation' ICMP is received, update our idea of the MSS
1466  * based on the new value in the route.  Also nudge TCP to send something,
1467  * since we know the packet we just sent was dropped.
1468  * This duplicates some code in the tcp_mss() function in tcp_input.c.
1469  */
1470 struct inpcb *
1471 tcp_mtudisc(struct inpcb *inp, int errno)
1472 {
1473 	struct tcpcb *tp;
1474 	struct socket *so = inp->inp_socket;
1475 	u_int maxmtu;
1476 	u_int romtu;
1477 	int mss;
1478 #ifdef INET6
1479 	int isipv6;
1480 #endif /* INET6 */
1481 
1482 	INP_LOCK_ASSERT(inp);
1483 	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1484 	    (inp->inp_vflag & INP_DROPPED))
1485 		return (inp);
1486 
1487 	tp = intotcpcb(inp);
1488 	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
1489 
1490 #ifdef INET6
1491 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1492 #endif
1493 	maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */
1494 	romtu =
1495 #ifdef INET6
1496 	    isipv6 ? tcp_maxmtu6(&inp->inp_inc, NULL) :
1497 #endif /* INET6 */
1498 	    tcp_maxmtu(&inp->inp_inc, NULL);
1499 	if (!maxmtu)
1500 		maxmtu = romtu;
1501 	else
1502 		maxmtu = min(maxmtu, romtu);
1503 	if (!maxmtu) {
1504 		tp->t_maxopd = tp->t_maxseg =
1505 #ifdef INET6
1506 			isipv6 ? tcp_v6mssdflt :
1507 #endif /* INET6 */
1508 			tcp_mssdflt;
1509 		return (inp);
1510 	}
1511 	mss = maxmtu -
1512 #ifdef INET6
1513 		(isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1514 #endif /* INET6 */
1515 		 sizeof(struct tcpiphdr)
1516 #ifdef INET6
1517 		 )
1518 #endif /* INET6 */
1519 		;
1520 
1521 	/*
1522 	 * XXX - The above conditional probably violates the TCP
1523 	 * spec.  The problem is that, since we don't know the
1524 	 * other end's MSS, we are supposed to use a conservative
1525 	 * default.  But, if we do that, then MTU discovery will
1526 	 * never actually take place, because the conservative
1527 	 * default is much less than the MTUs typically seen
1528 	 * on the Internet today.  For the moment, we'll sweep
1529 	 * this under the carpet.
1530 	 *
1531 	 * The conservative default might not actually be a problem
1532 	 * if the only case this occurs is when sending an initial
1533 	 * SYN with options and data to a host we've never talked
1534 	 * to before.  Then, they will reply with an MSS value which
1535 	 * will get recorded and the new parameters should get
1536 	 * recomputed.  For Further Study.
1537 	 */
1538 	if (tp->t_maxopd <= mss)
1539 		return (inp);
1540 	tp->t_maxopd = mss;
1541 
1542 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1543 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1544 		mss -= TCPOLEN_TSTAMP_APPA;
1545 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1546 	if (mss > MCLBYTES)
1547 		mss &= ~(MCLBYTES-1);
1548 #else
1549 	if (mss > MCLBYTES)
1550 		mss = mss / MCLBYTES * MCLBYTES;
1551 #endif
1552 	if (so->so_snd.sb_hiwat < mss)
1553 		mss = so->so_snd.sb_hiwat;
1554 
1555 	tp->t_maxseg = mss;
1556 
1557 	tcpstat.tcps_mturesent++;
1558 	tp->t_rtttime = 0;
1559 	tp->snd_nxt = tp->snd_una;
1560 	tcp_free_sackholes(tp);
1561 	tp->snd_recover = tp->snd_max;
1562 	if (tp->t_flags & TF_SACK_PERMIT)
1563 		EXIT_FASTRECOVERY(tp);
1564 	tcp_output(tp);
1565 	return (inp);
1566 }
1567 
1568 /*
1569  * Look-up the routing entry to the peer of this inpcb.  If no route
1570  * is found and it cannot be allocated, then return NULL.  This routine
1571  * is called by TCP routines that access the rmx structure and by tcp_mss
1572  * to get the interface MTU.
1573  */
1574 u_long
1575 tcp_maxmtu(struct in_conninfo *inc, int *flags)
1576 {
1577 	struct route sro;
1578 	struct sockaddr_in *dst;
1579 	struct ifnet *ifp;
1580 	u_long maxmtu = 0;
1581 
1582 	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
1583 
1584 	bzero(&sro, sizeof(sro));
1585 	if (inc->inc_faddr.s_addr != INADDR_ANY) {
1586 	        dst = (struct sockaddr_in *)&sro.ro_dst;
1587 		dst->sin_family = AF_INET;
1588 		dst->sin_len = sizeof(*dst);
1589 		dst->sin_addr = inc->inc_faddr;
1590 		rtalloc_ign(&sro, RTF_CLONING);
1591 	}
1592 	if (sro.ro_rt != NULL) {
1593 		ifp = sro.ro_rt->rt_ifp;
1594 		if (sro.ro_rt->rt_rmx.rmx_mtu == 0)
1595 			maxmtu = ifp->if_mtu;
1596 		else
1597 			maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
1598 
1599 		/* Report additional interface capabilities. */
1600 		if (flags != NULL) {
1601 			if (ifp->if_capenable & IFCAP_TSO4 &&
1602 			    ifp->if_hwassist & CSUM_TSO)
1603 				*flags |= CSUM_TSO;
1604 		}
1605 		RTFREE(sro.ro_rt);
1606 	}
1607 	return (maxmtu);
1608 }
1609 
1610 #ifdef INET6
1611 u_long
1612 tcp_maxmtu6(struct in_conninfo *inc, int *flags)
1613 {
1614 	struct route_in6 sro6;
1615 	struct ifnet *ifp;
1616 	u_long maxmtu = 0;
1617 
1618 	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
1619 
1620 	bzero(&sro6, sizeof(sro6));
1621 	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
1622 		sro6.ro_dst.sin6_family = AF_INET6;
1623 		sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
1624 		sro6.ro_dst.sin6_addr = inc->inc6_faddr;
1625 		rtalloc_ign((struct route *)&sro6, RTF_CLONING);
1626 	}
1627 	if (sro6.ro_rt != NULL) {
1628 		ifp = sro6.ro_rt->rt_ifp;
1629 		if (sro6.ro_rt->rt_rmx.rmx_mtu == 0)
1630 			maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp);
1631 		else
1632 			maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu,
1633 				     IN6_LINKMTU(sro6.ro_rt->rt_ifp));
1634 
1635 		/* Report additional interface capabilities. */
1636 		if (flags != NULL) {
1637 			if (ifp->if_capenable & IFCAP_TSO6 &&
1638 			    ifp->if_hwassist & CSUM_TSO)
1639 				*flags |= CSUM_TSO;
1640 		}
1641 		RTFREE(sro6.ro_rt);
1642 	}
1643 
1644 	return (maxmtu);
1645 }
1646 #endif /* INET6 */
1647 
1648 #ifdef IPSEC
1649 /* compute ESP/AH header size for TCP, including outer IP header. */
1650 size_t
1651 ipsec_hdrsiz_tcp(struct tcpcb *tp)
1652 {
1653 	struct inpcb *inp;
1654 	struct mbuf *m;
1655 	size_t hdrsiz;
1656 	struct ip *ip;
1657 #ifdef INET6
1658 	struct ip6_hdr *ip6;
1659 #endif
1660 	struct tcphdr *th;
1661 
1662 	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1663 		return (0);
1664 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1665 	if (!m)
1666 		return (0);
1667 
1668 #ifdef INET6
1669 	if ((inp->inp_vflag & INP_IPV6) != 0) {
1670 		ip6 = mtod(m, struct ip6_hdr *);
1671 		th = (struct tcphdr *)(ip6 + 1);
1672 		m->m_pkthdr.len = m->m_len =
1673 			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1674 		tcpip_fillheaders(inp, ip6, th);
1675 		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1676 	} else
1677 #endif /* INET6 */
1678 	{
1679 		ip = mtod(m, struct ip *);
1680 		th = (struct tcphdr *)(ip + 1);
1681 		m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1682 		tcpip_fillheaders(inp, ip, th);
1683 		hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1684 	}
1685 
1686 	m_free(m);
1687 	return (hdrsiz);
1688 }
1689 #endif /*IPSEC*/
1690 
1691 /*
1692  * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
1693  *
1694  * This code attempts to calculate the bandwidth-delay product as a
1695  * means of determining the optimal window size to maximize bandwidth,
1696  * minimize RTT, and avoid the over-allocation of buffers on interfaces and
1697  * routers.  This code also does a fairly good job keeping RTTs in check
1698  * across slow links like modems.  We implement an algorithm which is very
1699  * similar (but not meant to be) TCP/Vegas.  The code operates on the
1700  * transmitter side of a TCP connection and so only effects the transmit
1701  * side of the connection.
1702  *
1703  * BACKGROUND:  TCP makes no provision for the management of buffer space
1704  * at the end points or at the intermediate routers and switches.  A TCP
1705  * stream, whether using NewReno or not, will eventually buffer as
1706  * many packets as it is able and the only reason this typically works is
1707  * due to the fairly small default buffers made available for a connection
1708  * (typicaly 16K or 32K).  As machines use larger windows and/or window
1709  * scaling it is now fairly easy for even a single TCP connection to blow-out
1710  * all available buffer space not only on the local interface, but on
1711  * intermediate routers and switches as well.  NewReno makes a misguided
1712  * attempt to 'solve' this problem by waiting for an actual failure to occur,
1713  * then backing off, then steadily increasing the window again until another
1714  * failure occurs, ad-infinitum.  This results in terrible oscillation that
1715  * is only made worse as network loads increase and the idea of intentionally
1716  * blowing out network buffers is, frankly, a terrible way to manage network
1717  * resources.
1718  *
1719  * It is far better to limit the transmit window prior to the failure
1720  * condition being achieved.  There are two general ways to do this:  First
1721  * you can 'scan' through different transmit window sizes and locate the
1722  * point where the RTT stops increasing, indicating that you have filled the
1723  * pipe, then scan backwards until you note that RTT stops decreasing, then
1724  * repeat ad-infinitum.  This method works in principle but has severe
1725  * implementation issues due to RTT variances, timer granularity, and
1726  * instability in the algorithm which can lead to many false positives and
1727  * create oscillations as well as interact badly with other TCP streams
1728  * implementing the same algorithm.
1729  *
1730  * The second method is to limit the window to the bandwidth delay product
1731  * of the link.  This is the method we implement.  RTT variances and our
1732  * own manipulation of the congestion window, bwnd, can potentially
1733  * destabilize the algorithm.  For this reason we have to stabilize the
1734  * elements used to calculate the window.  We do this by using the minimum
1735  * observed RTT, the long term average of the observed bandwidth, and
1736  * by adding two segments worth of slop.  It isn't perfect but it is able
1737  * to react to changing conditions and gives us a very stable basis on
1738  * which to extend the algorithm.
1739  */
1740 void
1741 tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
1742 {
1743 	u_long bw;
1744 	u_long bwnd;
1745 	int save_ticks;
1746 
1747 	INP_LOCK_ASSERT(tp->t_inpcb);
1748 
1749 	/*
1750 	 * If inflight_enable is disabled in the middle of a tcp connection,
1751 	 * make sure snd_bwnd is effectively disabled.
1752 	 */
1753 	if (tcp_inflight_enable == 0 || tp->t_rttlow < tcp_inflight_rttthresh) {
1754 		tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1755 		tp->snd_bandwidth = 0;
1756 		return;
1757 	}
1758 
1759 	/*
1760 	 * Figure out the bandwidth.  Due to the tick granularity this
1761 	 * is a very rough number and it MUST be averaged over a fairly
1762 	 * long period of time.  XXX we need to take into account a link
1763 	 * that is not using all available bandwidth, but for now our
1764 	 * slop will ramp us up if this case occurs and the bandwidth later
1765 	 * increases.
1766 	 *
1767 	 * Note: if ticks rollover 'bw' may wind up negative.  We must
1768 	 * effectively reset t_bw_rtttime for this case.
1769 	 */
1770 	save_ticks = ticks;
1771 	if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1)
1772 		return;
1773 
1774 	bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz /
1775 	    (save_ticks - tp->t_bw_rtttime);
1776 	tp->t_bw_rtttime = save_ticks;
1777 	tp->t_bw_rtseq = ack_seq;
1778 	if (tp->t_bw_rtttime == 0 || (int)bw < 0)
1779 		return;
1780 	bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
1781 
1782 	tp->snd_bandwidth = bw;
1783 
1784 	/*
1785 	 * Calculate the semi-static bandwidth delay product, plus two maximal
1786 	 * segments.  The additional slop puts us squarely in the sweet
1787 	 * spot and also handles the bandwidth run-up case and stabilization.
1788 	 * Without the slop we could be locking ourselves into a lower
1789 	 * bandwidth.
1790 	 *
1791 	 * Situations Handled:
1792 	 *	(1) Prevents over-queueing of packets on LANs, especially on
1793 	 *	    high speed LANs, allowing larger TCP buffers to be
1794 	 *	    specified, and also does a good job preventing
1795 	 *	    over-queueing of packets over choke points like modems
1796 	 *	    (at least for the transmit side).
1797 	 *
1798 	 *	(2) Is able to handle changing network loads (bandwidth
1799 	 *	    drops so bwnd drops, bandwidth increases so bwnd
1800 	 *	    increases).
1801 	 *
1802 	 *	(3) Theoretically should stabilize in the face of multiple
1803 	 *	    connections implementing the same algorithm (this may need
1804 	 *	    a little work).
1805 	 *
1806 	 *	(4) Stability value (defaults to 20 = 2 maximal packets) can
1807 	 *	    be adjusted with a sysctl but typically only needs to be
1808 	 *	    on very slow connections.  A value no smaller then 5
1809 	 *	    should be used, but only reduce this default if you have
1810 	 *	    no other choice.
1811 	 */
1812 #define USERTT	((tp->t_srtt + tp->t_rttbest) / 2)
1813 	bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10;
1814 #undef USERTT
1815 
1816 	if (tcp_inflight_debug > 0) {
1817 		static int ltime;
1818 		if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
1819 			ltime = ticks;
1820 			printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
1821 			    tp,
1822 			    bw,
1823 			    tp->t_rttbest,
1824 			    tp->t_srtt,
1825 			    bwnd
1826 			);
1827 		}
1828 	}
1829 	if ((long)bwnd < tcp_inflight_min)
1830 		bwnd = tcp_inflight_min;
1831 	if (bwnd > tcp_inflight_max)
1832 		bwnd = tcp_inflight_max;
1833 	if ((long)bwnd < tp->t_maxseg * 2)
1834 		bwnd = tp->t_maxseg * 2;
1835 	tp->snd_bwnd = bwnd;
1836 }
1837 
1838 #ifdef TCP_SIGNATURE
1839 /*
1840  * Callback function invoked by m_apply() to digest TCP segment data
1841  * contained within an mbuf chain.
1842  */
1843 static int
1844 tcp_signature_apply(void *fstate, void *data, u_int len)
1845 {
1846 
1847 	MD5Update(fstate, (u_char *)data, len);
1848 	return (0);
1849 }
1850 
1851 /*
1852  * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
1853  *
1854  * Parameters:
1855  * m		pointer to head of mbuf chain
1856  * off0		offset to TCP header within the mbuf chain
1857  * len		length of TCP segment data, excluding options
1858  * optlen	length of TCP segment options
1859  * buf		pointer to storage for computed MD5 digest
1860  * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
1861  *
1862  * We do this over ip, tcphdr, segment data, and the key in the SADB.
1863  * When called from tcp_input(), we can be sure that th_sum has been
1864  * zeroed out and verified already.
1865  *
1866  * This function is for IPv4 use only. Calling this function with an
1867  * IPv6 packet in the mbuf chain will yield undefined results.
1868  *
1869  * Return 0 if successful, otherwise return -1.
1870  *
1871  * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
1872  * search with the destination IP address, and a 'magic SPI' to be
1873  * determined by the application. This is hardcoded elsewhere to 1179
1874  * right now. Another branch of this code exists which uses the SPD to
1875  * specify per-application flows but it is unstable.
1876  */
1877 int
1878 tcp_signature_compute(struct mbuf *m, int off0, int len, int optlen,
1879     u_char *buf, u_int direction)
1880 {
1881 	union sockaddr_union dst;
1882 	struct ippseudo ippseudo;
1883 	MD5_CTX ctx;
1884 	int doff;
1885 	struct ip *ip;
1886 	struct ipovly *ipovly;
1887 	struct secasvar *sav;
1888 	struct tcphdr *th;
1889 	u_short savecsum;
1890 
1891 	KASSERT(m != NULL, ("NULL mbuf chain"));
1892 	KASSERT(buf != NULL, ("NULL signature pointer"));
1893 
1894 	/* Extract the destination from the IP header in the mbuf. */
1895 	ip = mtod(m, struct ip *);
1896 	bzero(&dst, sizeof(union sockaddr_union));
1897 	dst.sa.sa_len = sizeof(struct sockaddr_in);
1898 	dst.sa.sa_family = AF_INET;
1899 	dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
1900 	    ip->ip_src : ip->ip_dst;
1901 
1902 	/* Look up an SADB entry which matches the address of the peer. */
1903 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
1904 	if (sav == NULL) {
1905 		printf("%s: SADB lookup failed for %s\n", __func__,
1906 		    inet_ntoa(dst.sin.sin_addr));
1907 		return (EINVAL);
1908 	}
1909 
1910 	MD5Init(&ctx);
1911 	ipovly = (struct ipovly *)ip;
1912 	th = (struct tcphdr *)((u_char *)ip + off0);
1913 	doff = off0 + sizeof(struct tcphdr) + optlen;
1914 
1915 	/*
1916 	 * Step 1: Update MD5 hash with IP pseudo-header.
1917 	 *
1918 	 * XXX The ippseudo header MUST be digested in network byte order,
1919 	 * or else we'll fail the regression test. Assume all fields we've
1920 	 * been doing arithmetic on have been in host byte order.
1921 	 * XXX One cannot depend on ipovly->ih_len here. When called from
1922 	 * tcp_output(), the underlying ip_len member has not yet been set.
1923 	 */
1924 	ippseudo.ippseudo_src = ipovly->ih_src;
1925 	ippseudo.ippseudo_dst = ipovly->ih_dst;
1926 	ippseudo.ippseudo_pad = 0;
1927 	ippseudo.ippseudo_p = IPPROTO_TCP;
1928 	ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen);
1929 	MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
1930 
1931 	/*
1932 	 * Step 2: Update MD5 hash with TCP header, excluding options.
1933 	 * The TCP checksum must be set to zero.
1934 	 */
1935 	savecsum = th->th_sum;
1936 	th->th_sum = 0;
1937 	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
1938 	th->th_sum = savecsum;
1939 
1940 	/*
1941 	 * Step 3: Update MD5 hash with TCP segment data.
1942 	 *         Use m_apply() to avoid an early m_pullup().
1943 	 */
1944 	if (len > 0)
1945 		m_apply(m, doff, len, tcp_signature_apply, &ctx);
1946 
1947 	/*
1948 	 * Step 4: Update MD5 hash with shared secret.
1949 	 */
1950 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
1951 	MD5Final(buf, &ctx);
1952 
1953 	key_sa_recordxfer(sav, m);
1954 	KEY_FREESAV(&sav);
1955 	return (0);
1956 }
1957 #endif /* TCP_SIGNATURE */
1958 
1959 static int
1960 sysctl_drop(SYSCTL_HANDLER_ARGS)
1961 {
1962 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
1963 	struct sockaddr_storage addrs[2];
1964 	struct inpcb *inp;
1965 	struct tcpcb *tp;
1966 	struct tcptw *tw;
1967 	struct sockaddr_in *fin, *lin;
1968 #ifdef INET6
1969 	struct sockaddr_in6 *fin6, *lin6;
1970 	struct in6_addr f6, l6;
1971 #endif
1972 	int error;
1973 
1974 	inp = NULL;
1975 	fin = lin = NULL;
1976 #ifdef INET6
1977 	fin6 = lin6 = NULL;
1978 #endif
1979 	error = 0;
1980 
1981 	if (req->oldptr != NULL || req->oldlen != 0)
1982 		return (EINVAL);
1983 	if (req->newptr == NULL)
1984 		return (EPERM);
1985 	if (req->newlen < sizeof(addrs))
1986 		return (ENOMEM);
1987 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
1988 	if (error)
1989 		return (error);
1990 
1991 	switch (addrs[0].ss_family) {
1992 #ifdef INET6
1993 	case AF_INET6:
1994 		fin6 = (struct sockaddr_in6 *)&addrs[0];
1995 		lin6 = (struct sockaddr_in6 *)&addrs[1];
1996 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
1997 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
1998 			return (EINVAL);
1999 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
2000 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
2001 				return (EINVAL);
2002 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
2003 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
2004 			fin = (struct sockaddr_in *)&addrs[0];
2005 			lin = (struct sockaddr_in *)&addrs[1];
2006 			break;
2007 		}
2008 		error = sa6_embedscope(fin6, ip6_use_defzone);
2009 		if (error)
2010 			return (error);
2011 		error = sa6_embedscope(lin6, ip6_use_defzone);
2012 		if (error)
2013 			return (error);
2014 		break;
2015 #endif
2016 	case AF_INET:
2017 		fin = (struct sockaddr_in *)&addrs[0];
2018 		lin = (struct sockaddr_in *)&addrs[1];
2019 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
2020 		    lin->sin_len != sizeof(struct sockaddr_in))
2021 			return (EINVAL);
2022 		break;
2023 	default:
2024 		return (EINVAL);
2025 	}
2026 	INP_INFO_WLOCK(&tcbinfo);
2027 	switch (addrs[0].ss_family) {
2028 #ifdef INET6
2029 	case AF_INET6:
2030 		inp = in6_pcblookup_hash(&tcbinfo, &f6, fin6->sin6_port,
2031 		    &l6, lin6->sin6_port, 0, NULL);
2032 		break;
2033 #endif
2034 	case AF_INET:
2035 		inp = in_pcblookup_hash(&tcbinfo, fin->sin_addr, fin->sin_port,
2036 		    lin->sin_addr, lin->sin_port, 0, NULL);
2037 		break;
2038 	}
2039 	if (inp != NULL) {
2040 		INP_LOCK(inp);
2041 		if (inp->inp_vflag & INP_TIMEWAIT) {
2042 			/*
2043 			 * XXXRW: There currently exists a state where an
2044 			 * inpcb is present, but its timewait state has been
2045 			 * discarded.  For now, don't allow dropping of this
2046 			 * type of inpcb.
2047 			 */
2048 			tw = intotw(inp);
2049 			if (tw != NULL)
2050 				tcp_twclose(tw, 0);
2051 		} else if (!(inp->inp_vflag & INP_DROPPED) &&
2052 			   !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
2053 			tp = intotcpcb(inp);
2054 			tcp_drop(tp, ECONNABORTED);
2055 		}
2056 		INP_UNLOCK(inp);
2057 	} else
2058 		error = ESRCH;
2059 	INP_INFO_WUNLOCK(&tcbinfo);
2060 	return (error);
2061 }
2062 
2063 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
2064     CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL,
2065     0, sysctl_drop, "", "Drop TCP connection");
2066 
2067 /*
2068  * Generate a standardized TCP log line for use throughout the
2069  * tcp subsystem.  Memory allocation is done with M_NOWAIT to
2070  * allow use in the interrupt context.
2071  *
2072  * NB: The caller MUST free(s, M_TCPLOG) the returned string.
2073  * NB: The function may return NULL if memory allocation failed.
2074  *
2075  * Due to header inclusion and ordering limitations the struct ip
2076  * and ip6_hdr pointers have to be passed as void pointers.
2077  */
2078 char *
2079 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
2080     void *ip6hdr)
2081 {
2082 	char *s, *sp;
2083 	size_t size;
2084 	struct ip *ip;
2085 #ifdef INET6
2086 	struct ip6_hdr *ip6;
2087 
2088 	ip6 = (struct ip6_hdr *)ip6hdr;
2089 #endif /* INET6 */
2090 	ip = (struct ip *)ip4hdr;
2091 
2092 	/*
2093 	 * XXX: The size calculation is evil.
2094 	 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags <RST>"
2095 	 */
2096 #ifdef INET6
2097 	size = 5 + 2 * (INET6_ADDRSTRLEN + 10) + 12 + 12 * 4 + 1;
2098 #else
2099 	size = 5 + 2 * (sizeof("192.168.172.190") + 10) + 12 + 12 *4 + 1;
2100 #endif /* INET6 */
2101 
2102 	s = sp = malloc(size, M_TCPLOG, (M_ZERO|M_NOWAIT));
2103 	if (s == NULL)
2104 		return (NULL);
2105 
2106 	strcat(s, "TCP: [");
2107 	sp = s + strlen(s);
2108 
2109 	if (inc && inc->inc_isipv6 == 0) {
2110 		inet_ntoa_r(inc->inc_faddr, sp);
2111 		sp = s + strlen(s);
2112 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
2113 		sp = s + strlen(s);
2114 		inet_ntoa_r(inc->inc_laddr, sp);
2115 		sp = s + strlen(s);
2116 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
2117 #ifdef INET6
2118 	} else if (inc) {
2119 		ip6_sprintf(sp, &inc->inc6_faddr);
2120 		sp = s + strlen(s);
2121 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
2122 		sp = s + strlen(s);
2123 		ip6_sprintf(sp, &inc->inc6_laddr);
2124 		sp = s + strlen(s);
2125 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
2126 	} else if (ip6 && th) {
2127 		ip6_sprintf(sp, &ip6->ip6_src);
2128 		sp = s + strlen(s);
2129 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
2130 		sp = s + strlen(s);
2131 		ip6_sprintf(sp, &ip6->ip6_dst);
2132 		sp = s + strlen(s);
2133 		sprintf(sp, "]:%i", ntohs(th->th_dport));
2134 #endif /* INET6 */
2135 	} else if (ip && th) {
2136 		inet_ntoa_r(ip->ip_src, sp);
2137 		sp = s + strlen(s);
2138 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
2139 		sp = s + strlen(s);
2140 		inet_ntoa_r(ip->ip_dst, sp);
2141 		sp = s + strlen(s);
2142 		sprintf(sp, "]:%i", ntohs(th->th_dport));
2143 	} else {
2144 		free(s, M_TCPLOG);
2145 		return (NULL);
2146 	}
2147 	sp = s + strlen(s);
2148 	if (th)
2149 		sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS);
2150 	if (s[size] != '\0')
2151 		panic("%s: string too long", __func__);
2152 	return (s);
2153 }
2154