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