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