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