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