tcp_timewait.c revision 162064
1139823Simp/*-
211150Swollman * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
31541Srgrimes *	The Regents of the University of California.  All rights reserved.
41541Srgrimes *
51541Srgrimes * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
81541Srgrimes * 1. Redistributions of source code must retain the above copyright
91541Srgrimes *    notice, this list of conditions and the following disclaimer.
101541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111541Srgrimes *    notice, this list of conditions and the following disclaimer in the
121541Srgrimes *    documentation and/or other materials provided with the distribution.
131541Srgrimes * 4. Neither the name of the University nor the names of its contributors
141541Srgrimes *    may be used to endorse or promote products derived from this software
151541Srgrimes *    without specific prior written permission.
161541Srgrimes *
171541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271541Srgrimes * SUCH DAMAGE.
281541Srgrimes *
2911150Swollman *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
3050477Speter * $FreeBSD: head/sys/netinet/tcp_timewait.c 162064 2006-09-06 13:56:35Z glebius $
311541Srgrimes */
321541Srgrimes
3332752Seivind#include "opt_compat.h"
34125680Sbms#include "opt_inet.h"
3554263Sshin#include "opt_inet6.h"
3656041Sshin#include "opt_ipsec.h"
37101106Srwatson#include "opt_mac.h"
3829514Sjoerg#include "opt_tcpdebug.h"
39130989Sps#include "opt_tcp_sack.h"
4029514Sjoerg
411541Srgrimes#include <sys/param.h>
421541Srgrimes#include <sys/systm.h>
4350673Sjlemon#include <sys/callout.h>
4412172Sphk#include <sys/kernel.h>
4512172Sphk#include <sys/sysctl.h>
46101106Srwatson#include <sys/mac.h>
471541Srgrimes#include <sys/malloc.h>
481541Srgrimes#include <sys/mbuf.h>
4955679Sshin#ifdef INET6
5055679Sshin#include <sys/domain.h>
5155679Sshin#endif
5248758Sgreen#include <sys/proc.h>
531541Srgrimes#include <sys/socket.h>
541541Srgrimes#include <sys/socketvar.h>
551541Srgrimes#include <sys/protosw.h>
5675619Skris#include <sys/random.h>
5734923Sbde
5892760Sjeff#include <vm/uma.h>
591541Srgrimes
601541Srgrimes#include <net/route.h>
611541Srgrimes#include <net/if.h>
621541Srgrimes
631541Srgrimes#include <netinet/in.h>
641541Srgrimes#include <netinet/in_systm.h>
651541Srgrimes#include <netinet/ip.h>
6655679Sshin#ifdef INET6
6755679Sshin#include <netinet/ip6.h>
6855679Sshin#endif
691541Srgrimes#include <netinet/in_pcb.h>
7055679Sshin#ifdef INET6
7155679Sshin#include <netinet6/in6_pcb.h>
7255679Sshin#endif
737090Sbde#include <netinet/in_var.h>
741541Srgrimes#include <netinet/ip_var.h>
7555679Sshin#ifdef INET6
7655679Sshin#include <netinet6/ip6_var.h>
77148385Sume#include <netinet6/scope6_var.h>
78122922Sandre#include <netinet6/nd6.h>
7955679Sshin#endif
80145360Sandre#include <netinet/ip_icmp.h>
811541Srgrimes#include <netinet/tcp.h>
821541Srgrimes#include <netinet/tcp_fsm.h>
831541Srgrimes#include <netinet/tcp_seq.h>
841541Srgrimes#include <netinet/tcp_timer.h>
851541Srgrimes#include <netinet/tcp_var.h>
8655679Sshin#ifdef INET6
8755679Sshin#include <netinet6/tcp6_var.h>
8855679Sshin#endif
891541Srgrimes#include <netinet/tcpip.h>
906283Swollman#ifdef TCPDEBUG
916283Swollman#include <netinet/tcp_debug.h>
926283Swollman#endif
9355679Sshin#include <netinet6/ip6protosw.h>
941541Srgrimes
9555679Sshin#ifdef IPSEC
9655679Sshin#include <netinet6/ipsec.h>
9762587Sitojun#ifdef INET6
9862587Sitojun#include <netinet6/ipsec6.h>
9962587Sitojun#endif
100137396Ssuz#include <netkey/key.h>
10155679Sshin#endif /*IPSEC*/
10255679Sshin
103105199Ssam#ifdef FAST_IPSEC
104105199Ssam#include <netipsec/ipsec.h>
105125680Sbms#include <netipsec/xform.h>
106105199Ssam#ifdef INET6
107105199Ssam#include <netipsec/ipsec6.h>
108105199Ssam#endif
109125680Sbms#include <netipsec/key.h>
110105199Ssam#define	IPSEC
111105199Ssam#endif /*FAST_IPSEC*/
112105199Ssam
11358698Sjlemon#include <machine/in_cksum.h>
11482122Ssilby#include <sys/md5.h>
11558698Sjlemon
116133874Srwatsonint	tcp_mssdflt = TCP_MSS;
117133874SrwatsonSYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
11846381Sbillf    &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
11912296Sphk
12052904Sshin#ifdef INET6
12152904Sshinint	tcp_v6mssdflt = TCP6_MSS;
12252904SshinSYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
12355679Sshin	CTLFLAG_RW, &tcp_v6mssdflt , 0,
12455679Sshin	"Default TCP Maximum Segment Size for IPv6");
12552904Sshin#endif
12652904Sshin
127124258Sandre/*
128124258Sandre * Minimum MSS we accept and use. This prevents DoS attacks where
129124258Sandre * we are forced to a ridiculous low MSS like 20 and send hundreds
130124258Sandre * of packets instead of one. The effect scales with the available
131124258Sandre * bandwidth and quickly saturates the CPU and network interface
132124258Sandre * with packet generation and sending. Set to zero to disable MINMSS
133124258Sandre * checking. This setting prevents us from sending too small packets.
134124258Sandre */
135124258Sandreint	tcp_minmss = TCP_MINMSS;
136124258SandreSYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW,
137124258Sandre    &tcp_minmss , 0, "Minmum TCP Maximum Segment Size");
138124258Sandre/*
139124258Sandre * Number of TCP segments per second we accept from remote host
140124258Sandre * before we start to calculate average segment size. If average
141124258Sandre * segment size drops below the minimum TCP MSS we assume a DoS
142124258Sandre * attack and reset+drop the connection. Care has to be taken not to
143124258Sandre * set this value too small to not kill interactive type connections
144124258Sandre * (telnet, SSH) which send many small packets.
145124258Sandre */
146124258Sandreint     tcp_minmssoverload = TCP_MINMSSOVERLOAD;
147124258SandreSYSCTL_INT(_net_inet_tcp, OID_AUTO, minmssoverload, CTLFLAG_RW,
148124258Sandre    &tcp_minmssoverload , 0, "Number of TCP Segments per Second allowed to"
149124258Sandre    "be under the MINMSS Size");
150124258Sandre
15150673Sjlemon#if 0
152133874Srwatsonstatic int	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
153133874SrwatsonSYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
15446381Sbillf    &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time");
15550673Sjlemon#endif
15612296Sphk
15786764Sjlemonint	tcp_do_rfc1323 = 1;
158133874SrwatsonSYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
15946381Sbillf    &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
16012296Sphk
16150426Sjlemonstatic int	tcp_tcbhashsize = 0;
162121307SsilbySYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
16350426Sjlemon     &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
16450426Sjlemon
16555198Smsmithstatic int	do_tcpdrain = 1;
16666376SbmilekicSYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
16766376Sbmilekic     "Enable tcp_drain routine for extra help when low on mbufs");
16855198Smsmith
169133874SrwatsonSYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
17046381Sbillf    &tcbinfo.ipi_count, 0, "Number of active PCBs");
17136079Swollman
17272959Sjlemonstatic int	icmp_may_rst = 1;
173133874SrwatsonSYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
17472959Sjlemon    "Certain ICMP unreachable messages may abort connections in SYN_SENT");
17570103Sphk
17682122Ssilbystatic int	tcp_isn_reseed_interval = 0;
17782122SsilbySYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
17882122Ssilby    &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
17982122Ssilby
180162035Sglebiusstatic uma_zone_t tcptw_zone;
181157478Sglebiusstatic int	maxtcptw;
182162031Sglebiusstatic int
183162031Sglebiussysctl_maxtcptw(SYSCTL_HANDLER_ARGS)
184162031Sglebius{
185162031Sglebius	int error, new;
186157478Sglebius
187162031Sglebius	if (maxtcptw == 0)
188162031Sglebius		new = maxsockets / 5;
189162031Sglebius	else
190162031Sglebius		new = maxtcptw;
191162031Sglebius	error = sysctl_handle_int(oidp, &new, sizeof(int), req);
192162031Sglebius	if (error == 0 && req->newptr) {
193162035Sglebius		if (new > maxtcptw) {
194162031Sglebius			maxtcptw = new;
195162035Sglebius			uma_zone_set_max(tcptw_zone, maxtcptw);
196162035Sglebius		} else
197162031Sglebius			error = EINVAL;
198162031Sglebius	}
199162031Sglebius	return (error);
200162031Sglebius}
201162031SglebiusSYSCTL_PROC(_net_inet_tcp, OID_AUTO, maxtcptw, CTLTYPE_INT|CTLFLAG_RW,
202162031Sglebius    &maxtcptw, 0, sysctl_maxtcptw, "IU",
203162031Sglebius    "Maximum number of compressed TCP TIME_WAIT entries");
204162031Sglebius
205102017Sdillon/*
206133874Srwatson * TCP bandwidth limiting sysctls.  Note that the default lower bound of
207133874Srwatson * 1024 exists only for debugging.  A good production default would be
208102017Sdillon * something like 6100.
209102017Sdillon */
210133072SandreSYSCTL_NODE(_net_inet_tcp, OID_AUTO, inflight, CTLFLAG_RW, 0,
211133072Sandre    "TCP inflight data limiting");
212133072Sandre
213124199Sandrestatic int	tcp_inflight_enable = 1;
214133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, enable, CTLFLAG_RW,
215102017Sdillon    &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
216102017Sdillon
217104825Sdillonstatic int	tcp_inflight_debug = 0;
218133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, debug, CTLFLAG_RW,
219102017Sdillon    &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
220102017Sdillon
221155767Sandrestatic int	tcp_inflight_rttthresh;
222155767SandreSYSCTL_PROC(_net_inet_tcp_inflight, OID_AUTO, rttthresh, CTLTYPE_INT|CTLFLAG_RW,
223155767Sandre    &tcp_inflight_rttthresh, 0, sysctl_msec_to_ticks, "I",
224155767Sandre    "RTT threshold below which inflight will deactivate itself");
225155767Sandre
226107881Sdillonstatic int	tcp_inflight_min = 6144;
227133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, min, CTLFLAG_RW,
228102017Sdillon    &tcp_inflight_min, 0, "Lower-bound for TCP inflight window");
229102017Sdillon
230102017Sdillonstatic int	tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
231133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, max, CTLFLAG_RW,
232102017Sdillon    &tcp_inflight_max, 0, "Upper-bound for TCP inflight window");
233133072Sandre
234107881Sdillonstatic int	tcp_inflight_stab = 20;
235133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, stab, CTLFLAG_RW,
236107881Sdillon    &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets");
237102017Sdillon
238130989Spsuma_zone_t sack_hole_zone;
239130989Sps
24098211Shsustatic struct inpcb *tcp_notify(struct inpcb *, int);
241128452Ssilbystatic void	tcp_isn_tick(void *);
24212296Sphk
2437684Sdg/*
24432821Sdg * Target size of TCP PCB hash tables. Must be a power of two.
24543562Smsmith *
24643562Smsmith * Note that this can be overridden by the kernel environment
24743562Smsmith * variable net.inet.tcp.tcbhashsize
2487684Sdg */
2497684Sdg#ifndef TCBHASHSIZE
25032821Sdg#define TCBHASHSIZE	512
2517684Sdg#endif
2521541Srgrimes
2531541Srgrimes/*
254111145Sjlemon * XXX
255111145Sjlemon * Callouts should be moved into struct tcp directly.  They are currently
256123608Sjhb * separate because the tcpcb structure is exported to userland for sysctl
257111145Sjlemon * parsing purposes, which do not know about callouts.
25834881Swollman */
259111145Sjlemonstruct	tcpcb_mem {
26034881Swollman	struct	tcpcb tcb;
261111145Sjlemon	struct	callout tcpcb_mem_rexmt, tcpcb_mem_persist, tcpcb_mem_keep;
262111145Sjlemon	struct	callout tcpcb_mem_2msl, tcpcb_mem_delack;
26334881Swollman};
26434881Swollman
265111145Sjlemonstatic uma_zone_t tcpcb_zone;
266128452Ssilbystruct callout isn_callout;
267157967Srwatsonstatic struct mtx isn_mtx;
268111145Sjlemon
269157977Srwatson#define	ISN_LOCK_INIT()	mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
270157977Srwatson#define	ISN_LOCK()	mtx_lock(&isn_mtx)
271157977Srwatson#define	ISN_UNLOCK()	mtx_unlock(&isn_mtx)
272157977Srwatson
27334881Swollman/*
274157431Srwatson * TCP initialization.
2751541Srgrimes */
276157927Spsstatic void
277157927Spstcp_zone_change(void *tag)
278157927Sps{
279157927Sps
280157927Sps	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
281157927Sps	uma_zone_set_max(tcpcb_zone, maxsockets);
282162031Sglebius	if (maxtcptw == 0)
283162031Sglebius		uma_zone_set_max(tcptw_zone, maxsockets / 5);
284157927Sps}
285157927Sps
286160491Supsstatic int
287160491Supstcp_inpcb_init(void *mem, int size, int flags)
288160491Sups{
289160491Sups	struct inpcb *inp = (struct inpcb *) mem;
290160491Sups	INP_LOCK_INIT(inp, "inp", "tcpinp");
291160491Sups	return (0);
292160491Sups}
293160491Sups
2941541Srgrimesvoid
295157431Srwatsontcp_init(void)
2961541Srgrimes{
29777843Speter	int hashsize = TCBHASHSIZE;
298133874Srwatson
29950673Sjlemon	tcp_delacktime = TCPTV_DELACK;
30050673Sjlemon	tcp_keepinit = TCPTV_KEEP_INIT;
30150673Sjlemon	tcp_keepidle = TCPTV_KEEP_IDLE;
30250673Sjlemon	tcp_keepintvl = TCPTV_KEEPINTVL;
30350673Sjlemon	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
30450673Sjlemon	tcp_msl = TCPTV_MSL;
305100335Sdillon	tcp_rexmit_min = TCPTV_MIN;
306100335Sdillon	tcp_rexmit_slop = TCPTV_CPU_VAR;
307155767Sandre	tcp_inflight_rttthresh = TCPTV_INFLIGHT_RTTTHRESH;
30850673Sjlemon
30998102Shsu	INP_INFO_LOCK_INIT(&tcbinfo, "tcp");
3107684Sdg	LIST_INIT(&tcb);
3117684Sdg	tcbinfo.listhead = &tcb;
31277900Speter	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
31343576Smsmith	if (!powerof2(hashsize)) {
31443562Smsmith		printf("WARNING: TCB hash size not a power of 2\n");
31543562Smsmith		hashsize = 512; /* safe default */
31643562Smsmith	}
31750426Sjlemon	tcp_tcbhashsize = hashsize;
31843562Smsmith	tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
31943562Smsmith	tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
32034923Sbde					&tcbinfo.porthashmask);
321133874Srwatson	tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb),
322160491Sups	    NULL, NULL, tcp_inpcb_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
32392760Sjeff	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
32455679Sshin#ifdef INET6
32555679Sshin#define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
32655679Sshin#else /* INET6 */
32755679Sshin#define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
32855679Sshin#endif /* INET6 */
32955679Sshin	if (max_protohdr < TCP_MINPROTOHDR)
33055679Sshin		max_protohdr = TCP_MINPROTOHDR;
33155679Sshin	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
3321541Srgrimes		panic("tcp_init");
33355679Sshin#undef TCP_MINPROTOHDR
334111145Sjlemon	/*
335111145Sjlemon	 * These have to be type stable for the benefit of the timers.
336111145Sjlemon	 */
337133874Srwatson	tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
338133517Sandre	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
339111145Sjlemon	uma_zone_set_max(tcpcb_zone, maxsockets);
340162031Sglebius	tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw),
341162031Sglebius	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
342157478Sglebius	TUNABLE_INT_FETCH("net.inet.tcp.maxtcptw", &maxtcptw);
343157478Sglebius	if (maxtcptw == 0)
344162031Sglebius		uma_zone_set_max(tcptw_zone, maxsockets / 5);
345162031Sglebius	else
346162031Sglebius		uma_zone_set_max(tcptw_zone, maxtcptw);
347112009Sjlemon	tcp_timer_init();
34886764Sjlemon	syncache_init();
349122922Sandre	tcp_hc_init();
350126193Sandre	tcp_reass_init();
351157977Srwatson	ISN_LOCK_INIT();
352128452Ssilby	callout_init(&isn_callout, CALLOUT_MPSAFE);
353128452Ssilby	tcp_isn_tick(NULL);
354128452Ssilby	EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
355128452Ssilby		SHUTDOWN_PRI_DEFAULT);
356133874Srwatson	sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
357133517Sandre	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
358157927Sps	EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
359157927Sps		EVENTHANDLER_PRI_ANY);
3601541Srgrimes}
3611541Srgrimes
362128452Ssilbyvoid
363157431Srwatsontcp_fini(void *xtp)
364128452Ssilby{
365157431Srwatson
366128452Ssilby	callout_stop(&isn_callout);
367128452Ssilby}
368128452Ssilby
3691541Srgrimes/*
37078642Ssilby * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
37178642Ssilby * tcp_template used to store this data in mbufs, but we now recopy it out
37278642Ssilby * of the tcpcb each time to conserve mbufs.
3731541Srgrimes */
37478642Ssilbyvoid
375157431Srwatsontcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
3761541Srgrimes{
377111144Sjlemon	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
3781541Srgrimes
379138410Srwatson	INP_LOCK_ASSERT(inp);
380138410Srwatson
38155679Sshin#ifdef INET6
38255679Sshin	if ((inp->inp_vflag & INP_IPV6) != 0) {
38378642Ssilby		struct ip6_hdr *ip6;
38455679Sshin
38578642Ssilby		ip6 = (struct ip6_hdr *)ip_ptr;
38655679Sshin		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
38755679Sshin			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
38855679Sshin		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
38955679Sshin			(IPV6_VERSION & IPV6_VERSION_MASK);
39055679Sshin		ip6->ip6_nxt = IPPROTO_TCP;
39155679Sshin		ip6->ip6_plen = sizeof(struct tcphdr);
39255679Sshin		ip6->ip6_src = inp->in6p_laddr;
39355679Sshin		ip6->ip6_dst = inp->in6p_faddr;
39455679Sshin	} else
39555679Sshin#endif
39678642Ssilby	{
397111144Sjlemon		struct ip *ip;
39855679Sshin
399111144Sjlemon		ip = (struct ip *)ip_ptr;
400111144Sjlemon		ip->ip_v = IPVERSION;
401111144Sjlemon		ip->ip_hl = 5;
402111144Sjlemon		ip->ip_tos = inp->inp_ip_tos;
403111144Sjlemon		ip->ip_len = 0;
404111144Sjlemon		ip->ip_id = 0;
405111144Sjlemon		ip->ip_off = 0;
406111144Sjlemon		ip->ip_ttl = inp->inp_ip_ttl;
407111144Sjlemon		ip->ip_sum = 0;
408111144Sjlemon		ip->ip_p = IPPROTO_TCP;
409111144Sjlemon		ip->ip_src = inp->inp_laddr;
410111144Sjlemon		ip->ip_dst = inp->inp_faddr;
41178642Ssilby	}
412111144Sjlemon	th->th_sport = inp->inp_lport;
413111144Sjlemon	th->th_dport = inp->inp_fport;
414111144Sjlemon	th->th_seq = 0;
415111144Sjlemon	th->th_ack = 0;
416111144Sjlemon	th->th_x2 = 0;
417111144Sjlemon	th->th_off = 5;
418111144Sjlemon	th->th_flags = 0;
419111144Sjlemon	th->th_win = 0;
420111144Sjlemon	th->th_urp = 0;
421111144Sjlemon	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
42278642Ssilby}
42378642Ssilby
42478642Ssilby/*
42578642Ssilby * Create template to be used to send tcp packets on a connection.
42678642Ssilby * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
42778642Ssilby * use for this function is in keepalives, which use tcp_respond.
42878642Ssilby */
42978642Ssilbystruct tcptemp *
430157431Srwatsontcpip_maketemplate(struct inpcb *inp)
43178642Ssilby{
43278642Ssilby	struct mbuf *m;
43378642Ssilby	struct tcptemp *n;
43478642Ssilby
435149635Sandre	m = m_get(M_DONTWAIT, MT_DATA);
43678642Ssilby	if (m == NULL)
43778642Ssilby		return (0);
43878642Ssilby	m->m_len = sizeof(struct tcptemp);
43978642Ssilby	n = mtod(m, struct tcptemp *);
44078642Ssilby
441111144Sjlemon	tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
4421541Srgrimes	return (n);
4431541Srgrimes}
4441541Srgrimes
4451541Srgrimes/*
4461541Srgrimes * Send a single message to the TCP at address specified by
447127870Srwatson * the given TCP/IP header.  If m == NULL, then we make a copy
4481541Srgrimes * of the tcpiphdr at ti and send directly to the addressed host.
4491541Srgrimes * This is used to force keep alive messages out using the TCP
45078642Ssilby * template for a connection.  If flags are given then we send
45178642Ssilby * a message back to the TCP which originated the * segment ti,
45278642Ssilby * and discard the mbuf containing it and any other attached mbufs.
4531541Srgrimes *
4541541Srgrimes * In any case the ack and sequence number of the transmitted
4551541Srgrimes * segment are as specified by the parameters.
45631848Sjulian *
45731848Sjulian * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
4581541Srgrimes */
4591541Srgrimesvoid
460157431Srwatsontcp_respond(struct tcpcb *tp, void *ipgen, register struct tcphdr *th,
461157431Srwatson    register struct mbuf *m, tcp_seq ack, tcp_seq seq, int flags)
4621541Srgrimes{
4631541Srgrimes	register int tlen;
4641541Srgrimes	int win = 0;
46555679Sshin	struct ip *ip;
46655679Sshin	struct tcphdr *nth;
46755679Sshin#ifdef INET6
46855679Sshin	struct ip6_hdr *ip6;
46955679Sshin	int isipv6;
47055679Sshin#endif /* INET6 */
47155679Sshin	int ipflags = 0;
472128905Srwatson	struct inpcb *inp;
4731541Srgrimes
474101137Srwatson	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
475101137Srwatson
47655679Sshin#ifdef INET6
477105586Sphk	isipv6 = ((struct ip *)ipgen)->ip_v == 6;
47855679Sshin	ip6 = ipgen;
47955679Sshin#endif /* INET6 */
48055679Sshin	ip = ipgen;
48155679Sshin
482127871Srwatson	if (tp != NULL) {
483122327Ssam		inp = tp->t_inpcb;
484122327Ssam		KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
485122327Ssam		INP_INFO_WLOCK_ASSERT(&tcbinfo);
486122327Ssam		INP_LOCK_ASSERT(inp);
487128905Srwatson	} else
488128905Srwatson		inp = NULL;
489128905Srwatson
490128905Srwatson	if (tp != NULL) {
49157576Sps		if (!(flags & TH_RST)) {
492122327Ssam			win = sbspace(&inp->inp_socket->so_rcv);
49357576Sps			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
49457576Sps				win = (long)TCP_MAXWIN << tp->rcv_scale;
49557576Sps		}
4961541Srgrimes	}
497127870Srwatson	if (m == NULL) {
498151967Sandre		m = m_gethdr(M_DONTWAIT, MT_DATA);
4991541Srgrimes		if (m == NULL)
5001541Srgrimes			return;
5011541Srgrimes		tlen = 0;
5021541Srgrimes		m->m_data += max_linkhdr;
50355679Sshin#ifdef INET6
50455679Sshin		if (isipv6) {
505133874Srwatson			bcopy((caddr_t)ip6, mtod(m, caddr_t),
50655679Sshin			      sizeof(struct ip6_hdr));
50755679Sshin			ip6 = mtod(m, struct ip6_hdr *);
50855679Sshin			nth = (struct tcphdr *)(ip6 + 1);
50955679Sshin		} else
51055679Sshin#endif /* INET6 */
51155679Sshin	      {
51255679Sshin		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
51355679Sshin		ip = mtod(m, struct ip *);
51455679Sshin		nth = (struct tcphdr *)(ip + 1);
51555679Sshin	      }
51655679Sshin		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
5171541Srgrimes		flags = TH_ACK;
5181541Srgrimes	} else {
5191541Srgrimes		m_freem(m->m_next);
520127870Srwatson		m->m_next = NULL;
52155679Sshin		m->m_data = (caddr_t)ipgen;
52255679Sshin		/* m_len is set later */
5231541Srgrimes		tlen = 0;
5241541Srgrimes#define xchg(a,b,type) { type t; t=a; a=b; b=t; }
52555679Sshin#ifdef INET6
52655679Sshin		if (isipv6) {
52755679Sshin			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
52855679Sshin			nth = (struct tcphdr *)(ip6 + 1);
52955679Sshin		} else
53055679Sshin#endif /* INET6 */
53155679Sshin	      {
53255679Sshin		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
53355679Sshin		nth = (struct tcphdr *)(ip + 1);
53455679Sshin	      }
53555679Sshin		if (th != nth) {
53655679Sshin			/*
53755679Sshin			 * this is usually a case when an extension header
53855679Sshin			 * exists between the IPv6 header and the
53955679Sshin			 * TCP header.
54055679Sshin			 */
54155679Sshin			nth->th_sport = th->th_sport;
54255679Sshin			nth->th_dport = th->th_dport;
54355679Sshin		}
54455679Sshin		xchg(nth->th_dport, nth->th_sport, n_short);
5451541Srgrimes#undef xchg
5461541Srgrimes	}
54755679Sshin#ifdef INET6
54855679Sshin	if (isipv6) {
54990198Sume		ip6->ip6_flow = 0;
55090198Sume		ip6->ip6_vfc = IPV6_VERSION;
55190198Sume		ip6->ip6_nxt = IPPROTO_TCP;
55255679Sshin		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
55355679Sshin						tlen));
55455679Sshin		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
55556039Sshin	} else
55655679Sshin#endif
557133874Srwatson	{
558133874Srwatson		tlen += sizeof (struct tcpiphdr);
559133874Srwatson		ip->ip_len = tlen;
560133874Srwatson		ip->ip_ttl = ip_defttl;
561133874Srwatson		if (path_mtu_discovery)
562133874Srwatson			ip->ip_off |= IP_DF;
563133874Srwatson	}
5641541Srgrimes	m->m_len = tlen;
5651541Srgrimes	m->m_pkthdr.len = tlen;
566127870Srwatson	m->m_pkthdr.rcvif = NULL;
567101106Srwatson#ifdef MAC
568122327Ssam	if (inp != NULL) {
569101106Srwatson		/*
570101106Srwatson		 * Packet is associated with a socket, so allow the
571101106Srwatson		 * label of the response to reflect the socket label.
572101106Srwatson		 */
573128905Srwatson		INP_LOCK_ASSERT(inp);
574128905Srwatson		mac_create_mbuf_from_inpcb(inp, m);
575101106Srwatson	} else {
576101106Srwatson		/*
577119245Srwatson		 * Packet is not associated with a socket, so possibly
578119245Srwatson		 * update the label in place.
579101106Srwatson		 */
580119245Srwatson		mac_reflect_mbuf_tcp(m);
581101106Srwatson	}
582101106Srwatson#endif
58355679Sshin	nth->th_seq = htonl(seq);
58455679Sshin	nth->th_ack = htonl(ack);
58555679Sshin	nth->th_x2 = 0;
58655679Sshin	nth->th_off = sizeof (struct tcphdr) >> 2;
58755679Sshin	nth->th_flags = flags;
588127870Srwatson	if (tp != NULL)
58955679Sshin		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
5901541Srgrimes	else
59155679Sshin		nth->th_win = htons((u_short)win);
59255679Sshin	nth->th_urp = 0;
59355679Sshin#ifdef INET6
59455679Sshin	if (isipv6) {
59559392Sshin		nth->th_sum = 0;
59655679Sshin		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
59755679Sshin					sizeof(struct ip6_hdr),
59855679Sshin					tlen - sizeof(struct ip6_hdr));
599127870Srwatson		ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
600127870Srwatson		    NULL, NULL);
60155679Sshin	} else
60255679Sshin#endif /* INET6 */
603133874Srwatson	{
604133874Srwatson		nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
605133874Srwatson		    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
606133874Srwatson		m->m_pkthdr.csum_flags = CSUM_TCP;
607133874Srwatson		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
608133874Srwatson	}
6096283Swollman#ifdef TCPDEBUG
610122327Ssam	if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
61155679Sshin		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
6126283Swollman#endif
61355679Sshin#ifdef INET6
614122922Sandre	if (isipv6)
615122922Sandre		(void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp);
616122922Sandre	else
61755679Sshin#endif /* INET6 */
618122922Sandre	(void) ip_output(m, NULL, NULL, ipflags, NULL, inp);
6191541Srgrimes}
6201541Srgrimes
6211541Srgrimes/*
6221541Srgrimes * Create a new TCP control block, making an
6231541Srgrimes * empty reassembly queue and hooking it to the argument
62434881Swollman * protocol control block.  The `inp' parameter must have
62534881Swollman * come from the zone allocator set up in tcp_init().
6261541Srgrimes */
6271541Srgrimesstruct tcpcb *
628157431Srwatsontcp_newtcpcb(struct inpcb *inp)
6291541Srgrimes{
630111145Sjlemon	struct tcpcb_mem *tm;
631111145Sjlemon	struct tcpcb *tp;
63255679Sshin#ifdef INET6
63355679Sshin	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
63455679Sshin#endif /* INET6 */
6351541Srgrimes
636111145Sjlemon	tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO);
637111145Sjlemon	if (tm == NULL)
638111145Sjlemon		return (NULL);
639111145Sjlemon	tp = &tm->tcb;
640111145Sjlemon	/*	LIST_INIT(&tp->t_segq); */	/* XXX covered by M_ZERO */
64155679Sshin	tp->t_maxseg = tp->t_maxopd =
64255679Sshin#ifdef INET6
64355679Sshin		isipv6 ? tcp_v6mssdflt :
64455679Sshin#endif /* INET6 */
64555679Sshin		tcp_mssdflt;
6461541Srgrimes
64750673Sjlemon	/* Set up our timeouts. */
648142906Sglebius	callout_init(tp->tt_rexmt = &tm->tcpcb_mem_rexmt, NET_CALLOUT_MPSAFE);
649142906Sglebius	callout_init(tp->tt_persist = &tm->tcpcb_mem_persist, NET_CALLOUT_MPSAFE);
650142906Sglebius	callout_init(tp->tt_keep = &tm->tcpcb_mem_keep, NET_CALLOUT_MPSAFE);
651142906Sglebius	callout_init(tp->tt_2msl = &tm->tcpcb_mem_2msl, NET_CALLOUT_MPSAFE);
652142906Sglebius	callout_init(tp->tt_delack = &tm->tcpcb_mem_delack, NET_CALLOUT_MPSAFE);
65350673Sjlemon
6546283Swollman	if (tcp_do_rfc1323)
6556283Swollman		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
656130989Sps	tp->sack_enable = tcp_do_sack;
657147735Sps	TAILQ_INIT(&tp->snd_holes);
65834881Swollman	tp->t_inpcb = inp;	/* XXX */
6591541Srgrimes	/*
6601541Srgrimes	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
66116367Swollman	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
6621541Srgrimes	 * reasonable initial retransmit time.
6631541Srgrimes	 */
6641541Srgrimes	tp->t_srtt = TCPTV_SRTTBASE;
66516367Swollman	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
666100335Sdillon	tp->t_rttmin = tcp_rexmit_min;
66716367Swollman	tp->t_rxtcur = TCPTV_RTOBASE;
6681541Srgrimes	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
669102017Sdillon	tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
6701541Srgrimes	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
67150673Sjlemon	tp->t_rcvtime = ticks;
672102017Sdillon	tp->t_bw_rtttime = ticks;
673133874Srwatson	/*
67456564Sshin	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
67556564Sshin	 * because the socket may be bound to an IPv6 wildcard address,
67656564Sshin	 * which may match an IPv4-mapped IPv6 address.
67756564Sshin	 */
67824570Sdg	inp->inp_ip_ttl = ip_defttl;
679157432Srwatson	inp->inp_ppcb = tp;
68034881Swollman	return (tp);		/* XXX */
6811541Srgrimes}
6821541Srgrimes
6831541Srgrimes/*
6841541Srgrimes * Drop a TCP connection, reporting
6851541Srgrimes * the specified error.  If connection is synchronized,
6861541Srgrimes * then send a RST to peer.
6871541Srgrimes */
6881541Srgrimesstruct tcpcb *
689157431Srwatsontcp_drop(struct tcpcb *tp, int errno)
6901541Srgrimes{
6911541Srgrimes	struct socket *so = tp->t_inpcb->inp_socket;
6921541Srgrimes
693146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
694138019Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
695146864Srwatson
6961541Srgrimes	if (TCPS_HAVERCVDSYN(tp->t_state)) {
6971541Srgrimes		tp->t_state = TCPS_CLOSED;
6981541Srgrimes		(void) tcp_output(tp);
6991541Srgrimes		tcpstat.tcps_drops++;
7001541Srgrimes	} else
7011541Srgrimes		tcpstat.tcps_conndrops++;
7021541Srgrimes	if (errno == ETIMEDOUT && tp->t_softerror)
7031541Srgrimes		errno = tp->t_softerror;
7041541Srgrimes	so->so_error = errno;
7051541Srgrimes	return (tcp_close(tp));
7061541Srgrimes}
7071541Srgrimes
708157376Srwatsonvoid
709157431Srwatsontcp_discardcb(struct tcpcb *tp)
7101541Srgrimes{
711111145Sjlemon	struct tseg_qent *q;
7121541Srgrimes	struct inpcb *inp = tp->t_inpcb;
7131541Srgrimes	struct socket *so = inp->inp_socket;
71455679Sshin#ifdef INET6
71555679Sshin	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
71655679Sshin#endif /* INET6 */
7171541Srgrimes
718138410Srwatson	INP_LOCK_ASSERT(inp);
719138410Srwatson
7201541Srgrimes	/*
72150673Sjlemon	 * Make sure that all of our timers are stopped before we
72250673Sjlemon	 * delete the PCB.
72350673Sjlemon	 */
72450673Sjlemon	callout_stop(tp->tt_rexmt);
72550673Sjlemon	callout_stop(tp->tt_persist);
72650673Sjlemon	callout_stop(tp->tt_keep);
72750673Sjlemon	callout_stop(tp->tt_2msl);
72850673Sjlemon	callout_stop(tp->tt_delack);
72950673Sjlemon
73050673Sjlemon	/*
7319373Swollman	 * If we got enough samples through the srtt filter,
7329373Swollman	 * save the rtt and rttvar in the routing entry.
733122922Sandre	 * 'Enough' is arbitrarily defined as 4 rtt samples.
734122922Sandre	 * 4 samples is enough for the srtt filter to converge
735122922Sandre	 * to within enough % of the correct value; fewer samples
736122922Sandre	 * and we could save a bogus rtt. The danger is not high
737122922Sandre	 * as tcp quickly recovers from everything.
738122922Sandre	 * XXX: Works very well but needs some more statistics!
7391541Srgrimes	 */
740122922Sandre	if (tp->t_rttupdated >= 4) {
741122922Sandre		struct hc_metrics_lite metrics;
742122922Sandre		u_long ssthresh;
7431541Srgrimes
744122922Sandre		bzero(&metrics, sizeof(metrics));
7451541Srgrimes		/*
746122922Sandre		 * Update the ssthresh always when the conditions below
747122922Sandre		 * are satisfied. This gives us better new start value
748122922Sandre		 * for the congestion avoidance for new connections.
749122922Sandre		 * ssthresh is only set if packet loss occured on a session.
750160925Srwatson		 *
751160925Srwatson		 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
752160925Srwatson		 * being torn down.  Ideally this code would not use 'so'.
7531541Srgrimes		 */
754122922Sandre		ssthresh = tp->snd_ssthresh;
755122922Sandre		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
7561541Srgrimes			/*
7571541Srgrimes			 * convert the limit from user data bytes to
7581541Srgrimes			 * packets then to packet data bytes.
7591541Srgrimes			 */
760122922Sandre			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
761122922Sandre			if (ssthresh < 2)
762122922Sandre				ssthresh = 2;
763122922Sandre			ssthresh *= (u_long)(tp->t_maxseg +
76455679Sshin#ifdef INET6
76555679Sshin				      (isipv6 ? sizeof (struct ip6_hdr) +
76655679Sshin					       sizeof (struct tcphdr) :
76755679Sshin#endif
76855679Sshin				       sizeof (struct tcpiphdr)
76955679Sshin#ifdef INET6
77055679Sshin				       )
77155679Sshin#endif
77255679Sshin				      );
773122922Sandre		} else
774122922Sandre			ssthresh = 0;
775122922Sandre		metrics.rmx_ssthresh = ssthresh;
776122922Sandre
777122922Sandre		metrics.rmx_rtt = tp->t_srtt;
778122922Sandre		metrics.rmx_rttvar = tp->t_rttvar;
779122922Sandre		/* XXX: This wraps if the pipe is more than 4 Gbit per second */
780122922Sandre		metrics.rmx_bandwidth = tp->snd_bandwidth;
781122922Sandre		metrics.rmx_cwnd = tp->snd_cwnd;
782133874Srwatson		metrics.rmx_sendpipe = 0;
783122922Sandre		metrics.rmx_recvpipe = 0;
784122922Sandre
785122922Sandre		tcp_hc_update(&inp->inp_inc, &metrics);
7861541Srgrimes	}
787122922Sandre
7881541Srgrimes	/* free the reassembly queue, if any */
789111145Sjlemon	while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
79055679Sshin		LIST_REMOVE(q, tqe_q);
79155679Sshin		m_freem(q->tqe_m);
792126193Sandre		uma_zfree(tcp_reass_zone, q);
793126193Sandre		tp->t_segqlen--;
794126193Sandre		tcp_reass_qsize--;
7951541Srgrimes	}
796130989Sps	tcp_free_sackholes(tp);
79732821Sdg	inp->inp_ppcb = NULL;
798108265Shsu	tp->t_inpcb = NULL;
799111145Sjlemon	uma_zfree(tcpcb_zone, tp);
800111145Sjlemon}
801111145Sjlemon
802111145Sjlemon/*
803157430Srwatson * Attempt to close a TCP control block, marking it as dropped, and freeing
804157430Srwatson * the socket if we hold the only reference.
805111145Sjlemon */
806111145Sjlemonstruct tcpcb *
807157431Srwatsontcp_close(struct tcpcb *tp)
808111145Sjlemon{
809111145Sjlemon	struct inpcb *inp = tp->t_inpcb;
810157376Srwatson	struct socket *so;
811111145Sjlemon
812146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
813138410Srwatson	INP_LOCK_ASSERT(inp);
814138410Srwatson
815158009Srwatson	in_pcbdrop(inp);
816157376Srwatson	tcpstat.tcps_closed++;
817157376Srwatson	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
818157376Srwatson	so = inp->inp_socket;
819157376Srwatson	soisdisconnected(so);
820157376Srwatson	if (inp->inp_vflag & INP_SOCKREF) {
821157376Srwatson		KASSERT(so->so_state & SS_PROTOREF,
822157376Srwatson		    ("tcp_close: !SS_PROTOREF"));
823157376Srwatson		inp->inp_vflag &= ~INP_SOCKREF;
824160549Srwatson		INP_UNLOCK(inp);
825157376Srwatson		ACCEPT_LOCK();
826157376Srwatson		SOCK_LOCK(so);
827157376Srwatson		so->so_state &= ~SS_PROTOREF;
828157376Srwatson		sofree(so);
829157376Srwatson		return (NULL);
830157376Srwatson	}
831157376Srwatson	return (tp);
8321541Srgrimes}
8331541Srgrimes
8341541Srgrimesvoid
835157431Srwatsontcp_drain(void)
8361541Srgrimes{
837157431Srwatson
838157431Srwatson	if (do_tcpdrain) {
83955198Smsmith		struct inpcb *inpb;
84055198Smsmith		struct tcpcb *tcpb;
84155679Sshin		struct tseg_qent *te;
8421541Srgrimes
84355198Smsmith	/*
84455198Smsmith	 * Walk the tcpbs, if existing, and flush the reassembly queue,
84555198Smsmith	 * if there is one...
84655198Smsmith	 * XXX: The "Net/3" implementation doesn't imply that the TCP
84755198Smsmith	 *      reassembly queue should be flushed, but in a situation
848133874Srwatson	 *	where we're really low on mbufs, this is potentially
849133874Srwatson	 *	usefull.
85055198Smsmith	 */
85198102Shsu		INP_INFO_RLOCK(&tcbinfo);
85274362Sphk		LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) {
853111145Sjlemon			if (inpb->inp_vflag & INP_TIMEWAIT)
854111145Sjlemon				continue;
85598102Shsu			INP_LOCK(inpb);
856127870Srwatson			if ((tcpb = intotcpcb(inpb)) != NULL) {
85774362Sphk				while ((te = LIST_FIRST(&tcpb->t_segq))
85874362Sphk			            != NULL) {
85955679Sshin					LIST_REMOVE(te, tqe_q);
86055679Sshin					m_freem(te->tqe_m);
861126193Sandre					uma_zfree(tcp_reass_zone, te);
862126193Sandre					tcpb->t_segqlen--;
863126193Sandre					tcp_reass_qsize--;
86455198Smsmith				}
865144857Sps				tcp_clean_sackreport(tcpb);
86655198Smsmith			}
86798102Shsu			INP_UNLOCK(inpb);
86855198Smsmith		}
86998102Shsu		INP_INFO_RUNLOCK(&tcbinfo);
87055198Smsmith	}
8711541Srgrimes}
8721541Srgrimes
8731541Srgrimes/*
8741541Srgrimes * Notify a tcp user of an asynchronous error;
8751541Srgrimes * store error as soft error, but wake up user
8761541Srgrimes * (for now, won't do anything until can select for soft error).
87772960Sjlemon *
87872960Sjlemon * Do not wake up user since there currently is no mechanism for
87972960Sjlemon * reporting soft errors (yet - a kqueue filter may be added).
8801541Srgrimes */
88198211Shsustatic struct inpcb *
882157431Srwatsontcp_notify(struct inpcb *inp, int error)
8831541Srgrimes{
884157432Srwatson	struct tcpcb *tp;
8851541Srgrimes
886146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
887138410Srwatson	INP_LOCK_ASSERT(inp);
888157433Srwatson
889157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
890157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
891157433Srwatson		return (inp);
892157433Srwatson
893157432Srwatson	tp = intotcpcb(inp);
894157433Srwatson	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
895138410Srwatson
8961541Srgrimes	/*
8971541Srgrimes	 * Ignore some errors if we are hooked up.
8981541Srgrimes	 * If connection hasn't completed, has retransmitted several times,
8991541Srgrimes	 * and receives a second error, give up now.  This is better
9001541Srgrimes	 * than waiting a long time to establish a connection that
9011541Srgrimes	 * can never complete.
9021541Srgrimes	 */
9031541Srgrimes	if (tp->t_state == TCPS_ESTABLISHED &&
904110896Shsu	    (error == EHOSTUNREACH || error == ENETUNREACH ||
905110896Shsu	     error == EHOSTDOWN)) {
906139222Srwatson		return (inp);
9071541Srgrimes	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
90898211Shsu	    tp->t_softerror) {
909157376Srwatson		tp = tcp_drop(tp, error);
910157376Srwatson		if (tp != NULL)
911157376Srwatson			return (inp);
912157376Srwatson		else
913157376Srwatson			return (NULL);
91498211Shsu	} else {
9151541Srgrimes		tp->t_softerror = error;
916139222Srwatson		return (inp);
91798211Shsu	}
91872960Sjlemon#if 0
919111748Sdes	wakeup( &so->so_timeo);
9201541Srgrimes	sorwakeup(so);
9211541Srgrimes	sowwakeup(so);
92272960Sjlemon#endif
9231541Srgrimes}
9241541Srgrimes
92536079Swollmanstatic int
92662573Sphktcp_pcblist(SYSCTL_HANDLER_ARGS)
92736079Swollman{
928148156Srwatson	int error, i, n;
92936079Swollman	struct inpcb *inp, **inp_list;
93036079Swollman	inp_gen_t gencnt;
93136079Swollman	struct xinpgen xig;
93236079Swollman
93336079Swollman	/*
93436079Swollman	 * The process of preparing the TCB list is too time-consuming and
93536079Swollman	 * resource-intensive to repeat twice on every request.
93636079Swollman	 */
937127870Srwatson	if (req->oldptr == NULL) {
93836079Swollman		n = tcbinfo.ipi_count;
93936079Swollman		req->oldidx = 2 * (sizeof xig)
94036079Swollman			+ (n + n/8) * sizeof(struct xtcpcb);
941139222Srwatson		return (0);
94236079Swollman	}
94336079Swollman
944127870Srwatson	if (req->newptr != NULL)
945139222Srwatson		return (EPERM);
94636079Swollman
94736079Swollman	/*
94836079Swollman	 * OK, now we're committed to doing something.
94936079Swollman	 */
95098102Shsu	INP_INFO_RLOCK(&tcbinfo);
95136079Swollman	gencnt = tcbinfo.ipi_gencnt;
95236079Swollman	n = tcbinfo.ipi_count;
95398102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
95436079Swollman
955126253Struckman	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
956100831Struckman		+ n * sizeof(struct xtcpcb));
957126253Struckman	if (error != 0)
958126253Struckman		return (error);
959100831Struckman
96036079Swollman	xig.xig_len = sizeof xig;
96136079Swollman	xig.xig_count = n;
96236079Swollman	xig.xig_gen = gencnt;
96336079Swollman	xig.xig_sogen = so_gencnt;
96436079Swollman	error = SYSCTL_OUT(req, &xig, sizeof xig);
96536079Swollman	if (error)
966139222Srwatson		return (error);
96736079Swollman
968111119Simp	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
969127870Srwatson	if (inp_list == NULL)
970139222Srwatson		return (ENOMEM);
971133874Srwatson
97298102Shsu	INP_INFO_RLOCK(&tcbinfo);
973127870Srwatson	for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp != NULL && i < n;
97471999Sphk	     inp = LIST_NEXT(inp, inp_list)) {
97598102Shsu		INP_LOCK(inp);
976113345Srwatson		if (inp->inp_gencnt <= gencnt) {
977113345Srwatson			/*
978113345Srwatson			 * XXX: This use of cr_cansee(), introduced with
979113345Srwatson			 * TCP state changes, is not quite right, but for
980113345Srwatson			 * now, better than nothing.
981113345Srwatson			 */
982157474Srwatson			if (inp->inp_vflag & INP_TIMEWAIT) {
983157474Srwatson				if (intotw(inp) != NULL)
984157474Srwatson					error = cr_cansee(req->td->td_ucred,
985157474Srwatson					    intotw(inp)->tw_cred);
986157474Srwatson				else
987157474Srwatson					error = EINVAL;	/* Skip this inp. */
988157474Srwatson			} else
989113345Srwatson				error = cr_canseesocket(req->td->td_ucred,
990113345Srwatson				    inp->inp_socket);
991113345Srwatson			if (error == 0)
992113345Srwatson				inp_list[i++] = inp;
993113345Srwatson		}
99498102Shsu		INP_UNLOCK(inp);
99536079Swollman	}
99698102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
99736079Swollman	n = i;
99836079Swollman
99936079Swollman	error = 0;
100036079Swollman	for (i = 0; i < n; i++) {
100136079Swollman		inp = inp_list[i];
1002160491Sups		INP_LOCK(inp);
100336079Swollman		if (inp->inp_gencnt <= gencnt) {
100436079Swollman			struct xtcpcb xt;
1005157432Srwatson			void *inp_ppcb;
1006145978Scperciva
1007145978Scperciva			bzero(&xt, sizeof(xt));
100836079Swollman			xt.xt_len = sizeof xt;
100936079Swollman			/* XXX should avoid extra copy */
101036079Swollman			bcopy(inp, &xt.xt_inp, sizeof *inp);
101147960Stegge			inp_ppcb = inp->inp_ppcb;
1012111145Sjlemon			if (inp_ppcb == NULL)
1013111145Sjlemon				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1014111145Sjlemon			else if (inp->inp_vflag & INP_TIMEWAIT) {
1015111145Sjlemon				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1016111145Sjlemon				xt.xt_tp.t_state = TCPS_TIME_WAIT;
1017111145Sjlemon			} else
101847960Stegge				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
1019127870Srwatson			if (inp->inp_socket != NULL)
102036079Swollman				sotoxsocket(inp->inp_socket, &xt.xt_socket);
1021111145Sjlemon			else {
1022111145Sjlemon				bzero(&xt.xt_socket, sizeof xt.xt_socket);
1023111145Sjlemon				xt.xt_socket.xso_protocol = IPPROTO_TCP;
1024111145Sjlemon			}
1025110896Shsu			xt.xt_inp.inp_gencnt = inp->inp_gencnt;
1026160491Sups			INP_UNLOCK(inp);
102736079Swollman			error = SYSCTL_OUT(req, &xt, sizeof xt);
1028160491Sups		} else
1029160491Sups			INP_UNLOCK(inp);
1030160491Sups
103136079Swollman	}
103236079Swollman	if (!error) {
103336079Swollman		/*
103436079Swollman		 * Give the user an updated idea of our state.
103536079Swollman		 * If the generation differs from what we told
103636079Swollman		 * her before, she knows that something happened
103736079Swollman		 * while we were processing this request, and it
103836079Swollman		 * might be necessary to retry.
103936079Swollman		 */
104098102Shsu		INP_INFO_RLOCK(&tcbinfo);
104136079Swollman		xig.xig_gen = tcbinfo.ipi_gencnt;
104236079Swollman		xig.xig_sogen = so_gencnt;
104336079Swollman		xig.xig_count = tcbinfo.ipi_count;
104498102Shsu		INP_INFO_RUNLOCK(&tcbinfo);
104536079Swollman		error = SYSCTL_OUT(req, &xig, sizeof xig);
104636079Swollman	}
104736079Swollman	free(inp_list, M_TEMP);
1048139222Srwatson	return (error);
104936079Swollman}
105036079Swollman
105136079SwollmanSYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
105236079Swollman	    tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
105336079Swollman
105448758Sgreenstatic int
105562573Sphktcp_getcred(SYSCTL_HANDLER_ARGS)
105648758Sgreen{
105772650Sgreen	struct xucred xuc;
105848758Sgreen	struct sockaddr_in addrs[2];
105948758Sgreen	struct inpcb *inp;
1060148156Srwatson	int error;
106148758Sgreen
1062132653Scperciva	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
106348758Sgreen	if (error)
106448758Sgreen		return (error);
106548758Sgreen	error = SYSCTL_IN(req, addrs, sizeof(addrs));
106648758Sgreen	if (error)
106748758Sgreen		return (error);
106898102Shsu	INP_INFO_RLOCK(&tcbinfo);
106948758Sgreen	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
107054263Sshin	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
107198102Shsu	if (inp == NULL) {
107248758Sgreen		error = ENOENT;
107398102Shsu		goto outunlocked;
107448758Sgreen	}
107599837Struckman	INP_LOCK(inp);
107699837Struckman	if (inp->inp_socket == NULL) {
107799837Struckman		error = ENOENT;
107899837Struckman		goto out;
107999837Struckman	}
108092976Srwatson	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
108178697Sdwmalone	if (error)
108278697Sdwmalone		goto out;
108391354Sdd	cru2x(inp->inp_socket->so_cred, &xuc);
108448758Sgreenout:
108598102Shsu	INP_UNLOCK(inp);
108698102Shsuoutunlocked:
108798102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
108899838Struckman	if (error == 0)
108999838Struckman		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
109048758Sgreen	return (error);
109148758Sgreen}
109248758Sgreen
109378697SdwmaloneSYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
109478697Sdwmalone    CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
109578697Sdwmalone    tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
109648758Sgreen
109755679Sshin#ifdef INET6
109855679Sshinstatic int
109962573Sphktcp6_getcred(SYSCTL_HANDLER_ARGS)
110055679Sshin{
110172650Sgreen	struct xucred xuc;
110255679Sshin	struct sockaddr_in6 addrs[2];
110355679Sshin	struct inpcb *inp;
1104148156Srwatson	int error, mapped = 0;
110555679Sshin
1106132653Scperciva	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
110755679Sshin	if (error)
110855679Sshin		return (error);
110955679Sshin	error = SYSCTL_IN(req, addrs, sizeof(addrs));
111055679Sshin	if (error)
111155679Sshin		return (error);
1112148385Sume	if ((error = sa6_embedscope(&addrs[0], ip6_use_defzone)) != 0 ||
1113148385Sume	    (error = sa6_embedscope(&addrs[1], ip6_use_defzone)) != 0) {
1114148385Sume		return (error);
1115148385Sume	}
111655679Sshin	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
111755679Sshin		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
111855679Sshin			mapped = 1;
111955679Sshin		else
112055679Sshin			return (EINVAL);
112155679Sshin	}
1122148385Sume
112398102Shsu	INP_INFO_RLOCK(&tcbinfo);
112455679Sshin	if (mapped == 1)
112555679Sshin		inp = in_pcblookup_hash(&tcbinfo,
112655679Sshin			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
112755679Sshin			addrs[1].sin6_port,
112855679Sshin			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
112955679Sshin			addrs[0].sin6_port,
113055679Sshin			0, NULL);
113155679Sshin	else
1132151254Sphilip		inp = in6_pcblookup_hash(&tcbinfo,
1133151254Sphilip			&addrs[1].sin6_addr, addrs[1].sin6_port,
1134151254Sphilip			&addrs[0].sin6_addr, addrs[0].sin6_port, 0, NULL);
113598102Shsu	if (inp == NULL) {
113655679Sshin		error = ENOENT;
113798102Shsu		goto outunlocked;
113855679Sshin	}
113999837Struckman	INP_LOCK(inp);
114099837Struckman	if (inp->inp_socket == NULL) {
114199837Struckman		error = ENOENT;
114299837Struckman		goto out;
114399837Struckman	}
114492976Srwatson	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
114578697Sdwmalone	if (error)
114678697Sdwmalone		goto out;
114791354Sdd	cru2x(inp->inp_socket->so_cred, &xuc);
114855679Sshinout:
114998102Shsu	INP_UNLOCK(inp);
115098102Shsuoutunlocked:
115198102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
115299838Struckman	if (error == 0)
115399838Struckman		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
115455679Sshin	return (error);
115555679Sshin}
115655679Sshin
115778697SdwmaloneSYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
115878697Sdwmalone    CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
115978697Sdwmalone    tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
116055679Sshin#endif
116155679Sshin
116255679Sshin
11631541Srgrimesvoid
1164157431Srwatsontcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
11651541Srgrimes{
116672959Sjlemon	struct ip *ip = vip;
116772959Sjlemon	struct tcphdr *th;
116873109Sjlemon	struct in_addr faddr;
116973109Sjlemon	struct inpcb *inp;
117073109Sjlemon	struct tcpcb *tp;
117198211Shsu	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1172145360Sandre	struct icmp *icp;
1173145360Sandre	struct in_conninfo inc;
1174145360Sandre	tcp_seq icmp_tcp_seq;
1175148156Srwatson	int mtu;
11761541Srgrimes
117773109Sjlemon	faddr = ((struct sockaddr_in *)sa)->sin_addr;
117873109Sjlemon	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
117973109Sjlemon		return;
118073109Sjlemon
1181145355Sandre	if (cmd == PRC_MSGSIZE)
1182145355Sandre		notify = tcp_mtudisc;
118374937Sjesper	else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
118499156Sjesper		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
118572959Sjlemon		notify = tcp_drop_syn_sent;
1186122922Sandre	/*
1187122922Sandre	 * Redirects don't need to be handled up here.
1188122922Sandre	 */
1189122922Sandre	else if (PRC_IS_REDIRECT(cmd))
1190122922Sandre		return;
1191122922Sandre	/*
1192145355Sandre	 * Source quench is depreciated.
1193145355Sandre	 */
1194145355Sandre	else if (cmd == PRC_QUENCH)
1195145355Sandre		return;
1196145355Sandre	/*
1197122922Sandre	 * Hostdead is ugly because it goes linearly through all PCBs.
1198122922Sandre	 * XXX: We never get this from ICMP, otherwise it makes an
1199122922Sandre	 * excellent DoS attack on machines with many connections.
1200122922Sandre	 */
1201122922Sandre	else if (cmd == PRC_HOSTDEAD)
1202127870Srwatson		ip = NULL;
1203119995Sru	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
12041541Srgrimes		return;
1205127870Srwatson	if (ip != NULL) {
1206145360Sandre		icp = (struct icmp *)((caddr_t)ip
1207145360Sandre				      - offsetof(struct icmp, icmp_ip));
1208133874Srwatson		th = (struct tcphdr *)((caddr_t)ip
1209105586Sphk				       + (ip->ip_hl << 2));
121098596Shsu		INP_INFO_WLOCK(&tcbinfo);
121173109Sjlemon		inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
121273109Sjlemon		    ip->ip_src, th->th_sport, 0, NULL);
121398102Shsu		if (inp != NULL)  {
121498102Shsu			INP_LOCK(inp);
1215157433Srwatson			if (!(inp->inp_vflag & INP_TIMEWAIT) &&
1216157433Srwatson			    !(inp->inp_vflag & INP_DROPPED) &&
1217157433Srwatson			    !(inp->inp_socket == NULL)) {
1218145360Sandre				icmp_tcp_seq = htonl(th->th_seq);
121998102Shsu				tp = intotcpcb(inp);
1220145360Sandre				if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
1221145360Sandre				    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
1222145360Sandre					if (cmd == PRC_MSGSIZE) {
1223145360Sandre					    /*
1224145360Sandre					     * MTU discovery:
1225145360Sandre					     * If we got a needfrag set the MTU
1226145360Sandre					     * in the route to the suggested new
1227145360Sandre					     * value (if given) and then notify.
1228145360Sandre					     */
1229145360Sandre					    bzero(&inc, sizeof(inc));
1230145360Sandre					    inc.inc_flags = 0;	/* IPv4 */
1231145360Sandre					    inc.inc_faddr = faddr;
1232145360Sandre
1233145360Sandre					    mtu = ntohs(icp->icmp_nextmtu);
1234145869Sandre					    /*
1235145869Sandre					     * If no alternative MTU was
1236145869Sandre					     * proposed, try the next smaller
1237149929Sandre					     * one.  ip->ip_len has already
1238149929Sandre					     * been swapped in icmp_input().
1239145869Sandre					     */
1240145360Sandre					    if (!mtu)
1241149929Sandre						mtu = ip_next_mtu(ip->ip_len,
1242145869Sandre						 1);
1243145869Sandre					    if (mtu < max(296, (tcp_minmss)
1244145869Sandre						 + sizeof(struct tcpiphdr)))
1245145869Sandre						mtu = 0;
1246145869Sandre					    if (!mtu)
1247145869Sandre						mtu = tcp_mssdflt
1248145869Sandre						 + sizeof(struct tcpiphdr);
1249145869Sandre					    /*
1250145869Sandre					     * Only cache the the MTU if it
1251145869Sandre					     * is smaller than the interface
1252145869Sandre					     * or route MTU.  tcp_mtudisc()
1253145869Sandre					     * will do right thing by itself.
1254145869Sandre					     */
1255145869Sandre					    if (mtu <= tcp_maxmtu(&inc))
1256145360Sandre						tcp_hc_updatemtu(&inc, mtu);
1257145360Sandre					}
1258145360Sandre
125998211Shsu					inp = (*notify)(inp, inetctlerrmap[cmd]);
1260145360Sandre				}
126198102Shsu			}
1262127870Srwatson			if (inp != NULL)
126398211Shsu				INP_UNLOCK(inp);
126486764Sjlemon		} else {
126586764Sjlemon			inc.inc_fport = th->th_dport;
126686764Sjlemon			inc.inc_lport = th->th_sport;
126786764Sjlemon			inc.inc_faddr = faddr;
126886764Sjlemon			inc.inc_laddr = ip->ip_src;
126986764Sjlemon#ifdef INET6
127086764Sjlemon			inc.inc_isipv6 = 0;
127186764Sjlemon#endif
127286764Sjlemon			syncache_unreach(&inc, th);
127373109Sjlemon		}
127498596Shsu		INP_INFO_WUNLOCK(&tcbinfo);
12751541Srgrimes	} else
127698102Shsu		in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
12771541Srgrimes}
12781541Srgrimes
127955679Sshin#ifdef INET6
128055679Sshinvoid
1281157431Srwatsontcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
128255679Sshin{
128355679Sshin	struct tcphdr th;
128498211Shsu	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
128555679Sshin	struct ip6_hdr *ip6;
128655679Sshin	struct mbuf *m;
128778064Sume	struct ip6ctlparam *ip6cp = NULL;
128878064Sume	const struct sockaddr_in6 *sa6_src = NULL;
128955679Sshin	int off;
129078064Sume	struct tcp_portonly {
129178064Sume		u_int16_t th_sport;
129278064Sume		u_int16_t th_dport;
129378064Sume	} *thp;
129455679Sshin
129555679Sshin	if (sa->sa_family != AF_INET6 ||
129655679Sshin	    sa->sa_len != sizeof(struct sockaddr_in6))
129755679Sshin		return;
129855679Sshin
1299145355Sandre	if (cmd == PRC_MSGSIZE)
130055679Sshin		notify = tcp_mtudisc;
130155679Sshin	else if (!PRC_IS_REDIRECT(cmd) &&
1302119995Sru		 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
130355679Sshin		return;
1304145355Sandre	/* Source quench is depreciated. */
1305145355Sandre	else if (cmd == PRC_QUENCH)
1306145355Sandre		return;
130755679Sshin
130855679Sshin	/* if the parameter is from icmp6, decode it. */
130955679Sshin	if (d != NULL) {
131078064Sume		ip6cp = (struct ip6ctlparam *)d;
131155679Sshin		m = ip6cp->ip6c_m;
131255679Sshin		ip6 = ip6cp->ip6c_ip6;
131355679Sshin		off = ip6cp->ip6c_off;
131478064Sume		sa6_src = ip6cp->ip6c_src;
131555679Sshin	} else {
131655679Sshin		m = NULL;
131755679Sshin		ip6 = NULL;
131867456Sitojun		off = 0;	/* fool gcc */
131978064Sume		sa6_src = &sa6_any;
132055679Sshin	}
132155679Sshin
1322127870Srwatson	if (ip6 != NULL) {
132386764Sjlemon		struct in_conninfo inc;
132455679Sshin		/*
132555679Sshin		 * XXX: We assume that when IPV6 is non NULL,
132655679Sshin		 * M and OFF are valid.
132755679Sshin		 */
132855679Sshin
132967456Sitojun		/* check if we can safely examine src and dst ports */
133078064Sume		if (m->m_pkthdr.len < off + sizeof(*thp))
133167456Sitojun			return;
133267456Sitojun
133378064Sume		bzero(&th, sizeof(th));
133478064Sume		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
133578064Sume
1336133192Srwatson		in6_pcbnotify(&tcbinfo, sa, th.th_dport,
133778064Sume		    (struct sockaddr *)ip6cp->ip6c_src,
1338125776Sume		    th.th_sport, cmd, NULL, notify);
133986764Sjlemon
134086764Sjlemon		inc.inc_fport = th.th_dport;
134186764Sjlemon		inc.inc_lport = th.th_sport;
134286764Sjlemon		inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
134386764Sjlemon		inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
134486764Sjlemon		inc.inc_isipv6 = 1;
1345133591Sdwmalone		INP_INFO_WLOCK(&tcbinfo);
134686764Sjlemon		syncache_unreach(&inc, &th);
1347133591Sdwmalone		INP_INFO_WUNLOCK(&tcbinfo);
134855679Sshin	} else
1349133192Srwatson		in6_pcbnotify(&tcbinfo, sa, 0, (const struct sockaddr *)sa6_src,
1350125776Sume			      0, cmd, NULL, notify);
135155679Sshin}
135255679Sshin#endif /* INET6 */
135355679Sshin
135480428Speter
135582122Ssilby/*
135682122Ssilby * Following is where TCP initial sequence number generation occurs.
135782122Ssilby *
135882122Ssilby * There are two places where we must use initial sequence numbers:
135982122Ssilby * 1.  In SYN-ACK packets.
136082122Ssilby * 2.  In SYN packets.
136182122Ssilby *
136294390Ssilby * All ISNs for SYN-ACK packets are generated by the syncache.  See
136394390Ssilby * tcp_syncache.c for details.
136482122Ssilby *
136582122Ssilby * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
136682122Ssilby * depends on this property.  In addition, these ISNs should be
136782122Ssilby * unguessable so as to prevent connection hijacking.  To satisfy
136882122Ssilby * the requirements of this situation, the algorithm outlined in
1369133874Srwatson * RFC 1948 is used, with only small modifications.
137082122Ssilby *
137182122Ssilby * Implementation details:
137282122Ssilby *
137382122Ssilby * Time is based off the system timer, and is corrected so that it
137482122Ssilby * increases by one megabyte per second.  This allows for proper
137582122Ssilby * recycling on high speed LANs while still leaving over an hour
137682122Ssilby * before rollover.
137782122Ssilby *
1378128452Ssilby * As reading the *exact* system time is too expensive to be done
1379128452Ssilby * whenever setting up a TCP connection, we increment the time
1380128452Ssilby * offset in two ways.  First, a small random positive increment
1381128452Ssilby * is added to isn_offset for each connection that is set up.
1382128452Ssilby * Second, the function tcp_isn_tick fires once per clock tick
1383128452Ssilby * and increments isn_offset as necessary so that sequence numbers
1384128452Ssilby * are incremented at approximately ISN_BYTES_PER_SECOND.  The
1385128452Ssilby * random positive increments serve only to ensure that the same
1386128452Ssilby * exact sequence number is never sent out twice (as could otherwise
1387128452Ssilby * happen when a port is recycled in less than the system tick
1388128452Ssilby * interval.)
1389128452Ssilby *
139082122Ssilby * net.inet.tcp.isn_reseed_interval controls the number of seconds
139182122Ssilby * between seeding of isn_secret.  This is normally set to zero,
139282122Ssilby * as reseeding should not be necessary.
139382122Ssilby *
1394138018Srwatson * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
1395138018Srwatson * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock.  In
1396138018Srwatson * general, this means holding an exclusive (write) lock.
139782122Ssilby */
139879413Ssilby
139982122Ssilby#define ISN_BYTES_PER_SECOND 1048576
1400128452Ssilby#define ISN_STATIC_INCREMENT 4096
1401128452Ssilby#define ISN_RANDOM_INCREMENT (4096 - 1)
140279413Ssilby
1403138018Srwatsonstatic u_char isn_secret[32];
1404138018Srwatsonstatic int isn_last_reseed;
1405138018Srwatsonstatic u_int32_t isn_offset, isn_offset_old;
1406138018Srwatsonstatic MD5_CTX isn_ctx;
140775619Skris
140875619Skristcp_seq
1409157431Srwatsontcp_new_isn(struct tcpcb *tp)
141075619Skris{
141182122Ssilby	u_int32_t md5_buffer[4];
141282122Ssilby	tcp_seq new_isn;
141375619Skris
1414138410Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
1415138018Srwatson
1416157977Srwatson	ISN_LOCK();
141782122Ssilby	/* Seed if this is the first use, reseed if requested. */
141894390Ssilby	if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
141982122Ssilby	     (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
142082122Ssilby		< (u_int)ticks))) {
142182122Ssilby		read_random(&isn_secret, sizeof(isn_secret));
142282122Ssilby		isn_last_reseed = ticks;
142382122Ssilby	}
1424133874Srwatson
142582122Ssilby	/* Compute the md5 hash and return the ISN. */
142682122Ssilby	MD5Init(&isn_ctx);
142782122Ssilby	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
142882122Ssilby	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
142982122Ssilby#ifdef INET6
143082122Ssilby	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
143182122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
143282122Ssilby			  sizeof(struct in6_addr));
143382122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
143482122Ssilby			  sizeof(struct in6_addr));
143582122Ssilby	} else
143682122Ssilby#endif
143782122Ssilby	{
143882122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
143982122Ssilby			  sizeof(struct in_addr));
144082122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
144182122Ssilby			  sizeof(struct in_addr));
144282122Ssilby	}
144382122Ssilby	MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
144482122Ssilby	MD5Final((u_char *) &md5_buffer, &isn_ctx);
144582122Ssilby	new_isn = (tcp_seq) md5_buffer[0];
1446128452Ssilby	isn_offset += ISN_STATIC_INCREMENT +
1447128452Ssilby		(arc4random() & ISN_RANDOM_INCREMENT);
1448128452Ssilby	new_isn += isn_offset;
1449157977Srwatson	ISN_UNLOCK();
1450139222Srwatson	return (new_isn);
145175619Skris}
145275619Skris
14531541Srgrimes/*
1454128452Ssilby * Increment the offset to the next ISN_BYTES_PER_SECOND / hz boundary
1455128452Ssilby * to keep time flowing at a relatively constant rate.  If the random
1456128452Ssilby * increments have already pushed us past the projected offset, do nothing.
1457128452Ssilby */
1458128452Ssilbystatic void
1459157431Srwatsontcp_isn_tick(void *xtp)
1460128452Ssilby{
1461128452Ssilby	u_int32_t projected_offset;
1462133874Srwatson
1463157977Srwatson	ISN_LOCK();
1464141078Srwatson	projected_offset = isn_offset_old + ISN_BYTES_PER_SECOND / 100;
1465128452Ssilby
1466128452Ssilby	if (projected_offset > isn_offset)
1467128452Ssilby		isn_offset = projected_offset;
1468128452Ssilby
1469128452Ssilby	isn_offset_old = isn_offset;
1470141072Srwatson	callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL);
1471157977Srwatson	ISN_UNLOCK();
1472128452Ssilby}
1473128452Ssilby
1474128452Ssilby/*
147572959Sjlemon * When a specific ICMP unreachable message is received and the
147672959Sjlemon * connection state is SYN-SENT, drop the connection.  This behavior
147772959Sjlemon * is controlled by the icmp_may_rst sysctl.
147870103Sphk */
147998211Shsustruct inpcb *
1480157431Srwatsontcp_drop_syn_sent(struct inpcb *inp, int errno)
148170103Sphk{
1482157432Srwatson	struct tcpcb *tp;
148370103Sphk
1484146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1485138019Srwatson	INP_LOCK_ASSERT(inp);
1486157433Srwatson
1487157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1488157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
1489157433Srwatson		return (inp);
1490157433Srwatson
1491157432Srwatson	tp = intotcpcb(inp);
1492157433Srwatson	if (tp->t_state != TCPS_SYN_SENT)
1493157433Srwatson		return (inp);
1494146864Srwatson
1495157433Srwatson	tp = tcp_drop(tp, errno);
1496157433Srwatson	if (tp != NULL)
1497157433Srwatson		return (inp);
1498157433Srwatson	else
1499157433Srwatson		return (NULL);
150072638Sphk}
150172638Sphk
150272638Sphk/*
150310881Swollman * When `need fragmentation' ICMP is received, update our idea of the MSS
150410881Swollman * based on the new value in the route.  Also nudge TCP to send something,
150510881Swollman * since we know the packet we just sent was dropped.
150610930Swollman * This duplicates some code in the tcp_mss() function in tcp_input.c.
150710881Swollman */
150898211Shsustruct inpcb *
1509157431Srwatsontcp_mtudisc(struct inpcb *inp, int errno)
151010881Swollman{
1511157432Srwatson	struct tcpcb *tp;
151210930Swollman	struct socket *so = inp->inp_socket;
1513122922Sandre	u_int maxmtu;
1514122922Sandre	u_int romtu;
151510930Swollman	int mss;
151655679Sshin#ifdef INET6
1517134041Sandre	int isipv6;
151855679Sshin#endif /* INET6 */
151910881Swollman
1520138019Srwatson	INP_LOCK_ASSERT(inp);
1521157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1522157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
1523157433Srwatson		return (inp);
1524157433Srwatson
1525157432Srwatson	tp = intotcpcb(inp);
1526157433Srwatson	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
1527157433Srwatson
1528134041Sandre#ifdef INET6
1529157433Srwatson	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1530134041Sandre#endif
1531157433Srwatson	maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */
1532157433Srwatson	romtu =
153355679Sshin#ifdef INET6
1534157433Srwatson	    isipv6 ? tcp_maxmtu6(&inp->inp_inc) :
1535122922Sandre#endif /* INET6 */
1536157433Srwatson	    tcp_maxmtu(&inp->inp_inc);
1537157433Srwatson	if (!maxmtu)
1538157433Srwatson		maxmtu = romtu;
1539157433Srwatson	else
1540157433Srwatson		maxmtu = min(maxmtu, romtu);
1541157433Srwatson	if (!maxmtu) {
1542157433Srwatson		tp->t_maxopd = tp->t_maxseg =
154355679Sshin#ifdef INET6
1544157433Srwatson			isipv6 ? tcp_v6mssdflt :
154555679Sshin#endif /* INET6 */
1546157433Srwatson			tcp_mssdflt;
1547157433Srwatson		return (inp);
1548157433Srwatson	}
1549157433Srwatson	mss = maxmtu -
155055679Sshin#ifdef INET6
1551157433Srwatson		(isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
155255679Sshin#endif /* INET6 */
1553157433Srwatson		 sizeof(struct tcpiphdr)
155455679Sshin#ifdef INET6
1555157433Srwatson		 )
155655679Sshin#endif /* INET6 */
1557157433Srwatson		;
155855679Sshin
1559157433Srwatson	/*
1560157433Srwatson	 * XXX - The above conditional probably violates the TCP
1561157433Srwatson	 * spec.  The problem is that, since we don't know the
1562157433Srwatson	 * other end's MSS, we are supposed to use a conservative
1563157433Srwatson	 * default.  But, if we do that, then MTU discovery will
1564157433Srwatson	 * never actually take place, because the conservative
1565157433Srwatson	 * default is much less than the MTUs typically seen
1566157433Srwatson	 * on the Internet today.  For the moment, we'll sweep
1567157433Srwatson	 * this under the carpet.
1568157433Srwatson	 *
1569157433Srwatson	 * The conservative default might not actually be a problem
1570157433Srwatson	 * if the only case this occurs is when sending an initial
1571157433Srwatson	 * SYN with options and data to a host we've never talked
1572157433Srwatson	 * to before.  Then, they will reply with an MSS value which
1573157433Srwatson	 * will get recorded and the new parameters should get
1574157433Srwatson	 * recomputed.  For Further Study.
1575157433Srwatson	 */
1576157433Srwatson	if (tp->t_maxopd <= mss)
1577157433Srwatson		return (inp);
1578157433Srwatson	tp->t_maxopd = mss;
157910930Swollman
1580157433Srwatson	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1581157433Srwatson	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1582157433Srwatson		mss -= TCPOLEN_TSTAMP_APPA;
158310930Swollman#if	(MCLBYTES & (MCLBYTES - 1)) == 0
1584157433Srwatson	if (mss > MCLBYTES)
1585157433Srwatson		mss &= ~(MCLBYTES-1);
158610930Swollman#else
1587157433Srwatson	if (mss > MCLBYTES)
1588157433Srwatson		mss = mss / MCLBYTES * MCLBYTES;
158910881Swollman#endif
1590157433Srwatson	if (so->so_snd.sb_hiwat < mss)
1591157433Srwatson		mss = so->so_snd.sb_hiwat;
159210930Swollman
1593157433Srwatson	tp->t_maxseg = mss;
159410930Swollman
1595157433Srwatson	tcpstat.tcps_mturesent++;
1596157433Srwatson	tp->t_rtttime = 0;
1597157433Srwatson	tp->snd_nxt = tp->snd_una;
1598161645Smohans	tcp_free_sackholes(tp);
1599161645Smohans	tp->snd_recover = tp->snd_max;
1600161645Smohans	if (tp->sack_enable)
1601161645Smohans		EXIT_FASTRECOVERY(tp);
1602157433Srwatson	tcp_output(tp);
1603139222Srwatson	return (inp);
160410881Swollman}
160510881Swollman
160610881Swollman/*
16076283Swollman * Look-up the routing entry to the peer of this inpcb.  If no route
1608108265Shsu * is found and it cannot be allocated, then return NULL.  This routine
16096283Swollman * is called by TCP routines that access the rmx structure and by tcp_mss
16106283Swollman * to get the interface MTU.
16116283Swollman */
1612133874Srwatsonu_long
1613157431Srwatsontcp_maxmtu(struct in_conninfo *inc)
16146283Swollman{
1615122922Sandre	struct route sro;
1616122922Sandre	struct sockaddr_in *dst;
1617122922Sandre	struct ifnet *ifp;
1618122922Sandre	u_long maxmtu = 0;
16196283Swollman
1620122922Sandre	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
1621122922Sandre
1622122996Sandre	bzero(&sro, sizeof(sro));
1623122922Sandre	if (inc->inc_faddr.s_addr != INADDR_ANY) {
1624122922Sandre	        dst = (struct sockaddr_in *)&sro.ro_dst;
1625122922Sandre		dst->sin_family = AF_INET;
1626122922Sandre		dst->sin_len = sizeof(*dst);
1627122922Sandre		dst->sin_addr = inc->inc_faddr;
1628122922Sandre		rtalloc_ign(&sro, RTF_CLONING);
16296283Swollman	}
1630122922Sandre	if (sro.ro_rt != NULL) {
1631122922Sandre		ifp = sro.ro_rt->rt_ifp;
1632122922Sandre		if (sro.ro_rt->rt_rmx.rmx_mtu == 0)
1633122922Sandre			maxmtu = ifp->if_mtu;
1634122922Sandre		else
1635122922Sandre			maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
1636122922Sandre		RTFREE(sro.ro_rt);
1637122922Sandre	}
1638122922Sandre	return (maxmtu);
16396283Swollman}
16406283Swollman
164155679Sshin#ifdef INET6
1642122922Sandreu_long
1643157431Srwatsontcp_maxmtu6(struct in_conninfo *inc)
164455679Sshin{
1645122922Sandre	struct route_in6 sro6;
1646122922Sandre	struct ifnet *ifp;
1647122922Sandre	u_long maxmtu = 0;
164855679Sshin
1649122922Sandre	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
1650122922Sandre
1651122996Sandre	bzero(&sro6, sizeof(sro6));
1652122922Sandre	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
1653122922Sandre		sro6.ro_dst.sin6_family = AF_INET6;
1654122922Sandre		sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
1655122922Sandre		sro6.ro_dst.sin6_addr = inc->inc6_faddr;
1656122922Sandre		rtalloc_ign((struct route *)&sro6, RTF_CLONING);
165755679Sshin	}
1658122922Sandre	if (sro6.ro_rt != NULL) {
1659122922Sandre		ifp = sro6.ro_rt->rt_ifp;
1660122922Sandre		if (sro6.ro_rt->rt_rmx.rmx_mtu == 0)
1661122922Sandre			maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp);
1662122922Sandre		else
1663122922Sandre			maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu,
1664122922Sandre				     IN6_LINKMTU(sro6.ro_rt->rt_ifp));
1665122922Sandre		RTFREE(sro6.ro_rt);
1666122922Sandre	}
1667122922Sandre
1668122922Sandre	return (maxmtu);
166955679Sshin}
167055679Sshin#endif /* INET6 */
167155679Sshin
167255679Sshin#ifdef IPSEC
167355679Sshin/* compute ESP/AH header size for TCP, including outer IP header. */
167455679Sshinsize_t
1675157431Srwatsonipsec_hdrsiz_tcp(struct tcpcb *tp)
167655679Sshin{
167755679Sshin	struct inpcb *inp;
167855679Sshin	struct mbuf *m;
167955679Sshin	size_t hdrsiz;
168055679Sshin	struct ip *ip;
168155679Sshin#ifdef INET6
168255679Sshin	struct ip6_hdr *ip6;
1683111145Sjlemon#endif
168455679Sshin	struct tcphdr *th;
168555679Sshin
168678642Ssilby	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1687139222Srwatson		return (0);
1688111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
168955679Sshin	if (!m)
1690139222Srwatson		return (0);
169155679Sshin
169255679Sshin#ifdef INET6
169355679Sshin	if ((inp->inp_vflag & INP_IPV6) != 0) {
169455679Sshin		ip6 = mtod(m, struct ip6_hdr *);
169555679Sshin		th = (struct tcphdr *)(ip6 + 1);
169655679Sshin		m->m_pkthdr.len = m->m_len =
169755679Sshin			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1698111144Sjlemon		tcpip_fillheaders(inp, ip6, th);
169955679Sshin		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
170055679Sshin	} else
170155679Sshin#endif /* INET6 */
1702133874Srwatson	{
1703133874Srwatson		ip = mtod(m, struct ip *);
1704133874Srwatson		th = (struct tcphdr *)(ip + 1);
1705133874Srwatson		m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1706133874Srwatson		tcpip_fillheaders(inp, ip, th);
1707133874Srwatson		hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1708133874Srwatson	}
170955679Sshin
171055679Sshin	m_free(m);
1711139222Srwatson	return (hdrsiz);
171255679Sshin}
171355679Sshin#endif /*IPSEC*/
171455679Sshin
17156283Swollman/*
1716111145Sjlemon * Move a TCP connection into TIME_WAIT state.
1717138410Srwatson *    tcbinfo is locked.
1718111145Sjlemon *    inp is locked, and is unlocked before returning.
1719111145Sjlemon */
1720111145Sjlemonvoid
1721157431Srwatsontcp_twstart(struct tcpcb *tp)
1722111145Sjlemon{
1723111145Sjlemon	struct tcptw *tw;
1724111145Sjlemon	struct inpcb *inp;
1725111145Sjlemon	int tw_time, acknow;
1726111145Sjlemon	struct socket *so;
1727111145Sjlemon
1728138025Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);	/* tcp_timer_2msl_reset(). */
1729138020Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
1730138020Srwatson
1731112009Sjlemon	tw = uma_zalloc(tcptw_zone, M_NOWAIT);
1732112009Sjlemon	if (tw == NULL) {
1733112009Sjlemon		tw = tcp_timer_2msl_tw(1);
1734112009Sjlemon		if (tw == NULL) {
1735157376Srwatson			tp = tcp_close(tp);
1736157376Srwatson			if (tp != NULL)
1737157376Srwatson				INP_UNLOCK(tp->t_inpcb);
1738112009Sjlemon			return;
1739112009Sjlemon		}
1740112009Sjlemon	}
1741111145Sjlemon	inp = tp->t_inpcb;
1742111145Sjlemon	tw->tw_inpcb = inp;
1743111145Sjlemon
1744111145Sjlemon	/*
1745111145Sjlemon	 * Recover last window size sent.
1746111145Sjlemon	 */
1747111145Sjlemon	tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale;
1748111145Sjlemon
1749111145Sjlemon	/*
1750111145Sjlemon	 * Set t_recent if timestamps are used on the connection.
1751111145Sjlemon	 */
1752133874Srwatson	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
1753133874Srwatson	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
1754111145Sjlemon		tw->t_recent = tp->ts_recent;
1755111145Sjlemon	else
1756111145Sjlemon		tw->t_recent = 0;
1757111145Sjlemon
1758111145Sjlemon	tw->snd_nxt = tp->snd_nxt;
1759111145Sjlemon	tw->rcv_nxt = tp->rcv_nxt;
1760121850Ssilby	tw->iss     = tp->iss;
1761121884Ssilby	tw->irs     = tp->irs;
1762111145Sjlemon	tw->t_starttime = tp->t_starttime;
1763112009Sjlemon	tw->tw_time = 0;
1764111145Sjlemon
1765111145Sjlemon/* XXX
1766111145Sjlemon * If this code will
1767111145Sjlemon * be used for fin-wait-2 state also, then we may need
1768111145Sjlemon * a ts_recent from the last segment.
1769111145Sjlemon */
1770137139Sandre	tw_time = 2 * tcp_msl;
1771137139Sandre	acknow = tp->t_flags & TF_ACKNOW;
1772157376Srwatson
1773157376Srwatson	/*
1774157376Srwatson	 * First, discard tcpcb state, which includes stopping its timers and
1775157376Srwatson	 * freeing it.  tcp_discardcb() used to also release the inpcb, but
1776157376Srwatson	 * that work is now done in the caller.
1777160925Srwatson	 *
1778160925Srwatson	 * Note: soisdisconnected() call used to be made in tcp_discardcb(),
1779160925Srwatson	 * and might not be needed here any longer.
1780157376Srwatson	 */
1781111145Sjlemon	tcp_discardcb(tp);
1782111145Sjlemon	so = inp->inp_socket;
1783160925Srwatson	soisdisconnected(so);
1784130387Srwatson	SOCK_LOCK(so);
1785111145Sjlemon	tw->tw_cred = crhold(so->so_cred);
1786111145Sjlemon	tw->tw_so_options = so->so_options;
1787157376Srwatson	SOCK_UNLOCK(so);
1788114794Srwatson	if (acknow)
1789126351Srwatson		tcp_twrespond(tw, TH_ACK);
1790157432Srwatson	inp->inp_ppcb = tw;
1791111145Sjlemon	inp->inp_vflag |= INP_TIMEWAIT;
1792161226Smohans	tcp_timer_2msl_reset(tw, tw_time, 0);
1793157376Srwatson
1794157376Srwatson	/*
1795157376Srwatson	 * If the inpcb owns the sole reference to the socket, then we can
1796157376Srwatson	 * detach and free the socket as it is not needed in time wait.
1797157376Srwatson	 */
1798157376Srwatson	if (inp->inp_vflag & INP_SOCKREF) {
1799157376Srwatson		KASSERT(so->so_state & SS_PROTOREF,
1800157376Srwatson		    ("tcp_twstart: !SS_PROTOREF"));
1801157376Srwatson		inp->inp_vflag &= ~INP_SOCKREF;
1802157376Srwatson		INP_UNLOCK(inp);
1803157376Srwatson		ACCEPT_LOCK();
1804157376Srwatson		SOCK_LOCK(so);
1805157376Srwatson		so->so_state &= ~SS_PROTOREF;
1806157376Srwatson		sofree(so);
1807157376Srwatson	} else
1808157376Srwatson		INP_UNLOCK(inp);
1809111145Sjlemon}
1810111145Sjlemon
1811162064Sglebius#if 0
1812121850Ssilby/*
1813121884Ssilby * The appromixate rate of ISN increase of Microsoft TCP stacks;
1814121884Ssilby * the actual rate is slightly higher due to the addition of
1815121884Ssilby * random positive increments.
1816121884Ssilby *
1817121884Ssilby * Most other new OSes use semi-randomized ISN values, so we
1818121884Ssilby * do not need to worry about them.
1819121884Ssilby */
1820121884Ssilby#define MS_ISN_BYTES_PER_SECOND		250000
1821121884Ssilby
1822121884Ssilby/*
1823121850Ssilby * Determine if the ISN we will generate has advanced beyond the last
1824121850Ssilby * sequence number used by the previous connection.  If so, indicate
1825121850Ssilby * that it is safe to recycle this tw socket by returning 1.
1826121850Ssilby */
1827121850Ssilbyint
1828121850Ssilbytcp_twrecycleable(struct tcptw *tw)
1829121850Ssilby{
1830121884Ssilby	tcp_seq new_iss = tw->iss;
1831121884Ssilby	tcp_seq new_irs = tw->irs;
1832121850Ssilby
1833162064Sglebius	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1834121884Ssilby	new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz);
1835121884Ssilby	new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz);
1836133874Srwatson
1837121884Ssilby	if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt))
1838139222Srwatson		return (1);
1839121850Ssilby	else
1840139222Srwatson		return (0);
1841121850Ssilby}
1842162064Sglebius#endif
1843121850Ssilby
1844157376Srwatsonvoid
1845112009Sjlemontcp_twclose(struct tcptw *tw, int reuse)
1846111145Sjlemon{
1847157376Srwatson	struct socket *so;
1848111145Sjlemon	struct inpcb *inp;
1849111145Sjlemon
1850157376Srwatson	/*
1851157386Srwatson	 * At this point, we are in one of two situations:
1852157376Srwatson	 *
1853160549Srwatson	 * (1) We have no socket, just an inpcb<->twtcp pair.  We can free
1854160549Srwatson	 *     all state.
1855157386Srwatson	 *
1856160549Srwatson	 * (2) We have a socket -- if we own a reference, release it and
1857160549Srwatson	 *     notify the socket layer.
1858157376Srwatson	 */
1859111145Sjlemon	inp = tw->tw_inpcb;
1860157376Srwatson	KASSERT((inp->inp_vflag & INP_TIMEWAIT), ("tcp_twclose: !timewait"));
1861157432Srwatson	KASSERT(intotw(inp) == tw, ("tcp_twclose: inp_ppcb != tw"));
1862138025Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);	/* tcp_timer_2msl_stop(). */
1863138020Srwatson	INP_LOCK_ASSERT(inp);
1864138020Srwatson
1865111145Sjlemon	tw->tw_inpcb = NULL;
1866112009Sjlemon	tcp_timer_2msl_stop(tw);
1867111145Sjlemon	inp->inp_ppcb = NULL;
1868158009Srwatson	in_pcbdrop(inp);
1869157376Srwatson
1870157376Srwatson	so = inp->inp_socket;
1871157386Srwatson	if (so != NULL) {
1872160549Srwatson		/*
1873160549Srwatson		 * If there's a socket, handle two cases: first, we own a
1874160549Srwatson		 * strong reference, which we will now release, or we don't
1875160549Srwatson		 * in which case another reference exists (XXXRW: think
1876160549Srwatson		 * about this more), and we don't need to take action.
1877160549Srwatson		 */
1878157386Srwatson		if (inp->inp_vflag & INP_SOCKREF) {
1879157386Srwatson			inp->inp_vflag &= ~INP_SOCKREF;
1880160549Srwatson			INP_UNLOCK(inp);
1881157386Srwatson			ACCEPT_LOCK();
1882157386Srwatson			SOCK_LOCK(so);
1883157386Srwatson			KASSERT(so->so_state & SS_PROTOREF,
1884157386Srwatson			    ("tcp_twclose: INP_SOCKREF && !SS_PROTOREF"));
1885157386Srwatson			so->so_state &= ~SS_PROTOREF;
1886157386Srwatson			sofree(so);
1887157376Srwatson		} else {
1888157386Srwatson			/*
1889157386Srwatson			 * If we don't own the only reference, the socket and
1890157386Srwatson			 * inpcb need to be left around to be handled by
1891157386Srwatson			 * tcp_usr_detach() later.
1892157386Srwatson			 */
1893157386Srwatson			INP_UNLOCK(inp);
1894157376Srwatson		}
1895157386Srwatson	} else {
1896157376Srwatson#ifdef INET6
1897157376Srwatson		if (inp->inp_vflag & INP_IPV6PROTO)
1898157376Srwatson			in6_pcbfree(inp);
1899157376Srwatson		else
1900157376Srwatson#endif
1901157376Srwatson			in_pcbfree(inp);
1902157386Srwatson	}
1903111145Sjlemon	tcpstat.tcps_closed++;
1904126002Spjd	crfree(tw->tw_cred);
1905126002Spjd	tw->tw_cred = NULL;
1906112009Sjlemon	if (reuse)
1907157376Srwatson		return;
1908112009Sjlemon	uma_zfree(tcptw_zone, tw);
1909111145Sjlemon}
1910111145Sjlemon
1911111145Sjlemonint
1912126351Srwatsontcp_twrespond(struct tcptw *tw, int flags)
1913111145Sjlemon{
1914111145Sjlemon	struct inpcb *inp = tw->tw_inpcb;
1915111145Sjlemon	struct tcphdr *th;
1916111145Sjlemon	struct mbuf *m;
1917111145Sjlemon	struct ip *ip = NULL;
1918111145Sjlemon	u_int8_t *optp;
1919111145Sjlemon	u_int hdrlen, optlen;
1920111145Sjlemon	int error;
1921111145Sjlemon#ifdef INET6
1922111145Sjlemon	struct ip6_hdr *ip6 = NULL;
1923111145Sjlemon	int isipv6 = inp->inp_inc.inc_isipv6;
1924111145Sjlemon#endif
1925111145Sjlemon
1926138020Srwatson	INP_LOCK_ASSERT(inp);
1927138020Srwatson
1928151967Sandre	m = m_gethdr(M_DONTWAIT, MT_DATA);
1929111145Sjlemon	if (m == NULL)
1930111145Sjlemon		return (ENOBUFS);
1931111145Sjlemon	m->m_data += max_linkhdr;
1932111145Sjlemon
1933114794Srwatson#ifdef MAC
1934123607Srwatson	mac_create_mbuf_from_inpcb(inp, m);
1935114794Srwatson#endif
1936114794Srwatson
1937111153Sjlemon#ifdef INET6
1938111145Sjlemon	if (isipv6) {
1939111145Sjlemon		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1940111145Sjlemon		ip6 = mtod(m, struct ip6_hdr *);
1941111145Sjlemon		th = (struct tcphdr *)(ip6 + 1);
1942111145Sjlemon		tcpip_fillheaders(inp, ip6, th);
1943111153Sjlemon	} else
1944111153Sjlemon#endif
1945111153Sjlemon	{
1946111145Sjlemon		hdrlen = sizeof(struct tcpiphdr);
1947111145Sjlemon		ip = mtod(m, struct ip *);
1948111145Sjlemon		th = (struct tcphdr *)(ip + 1);
1949111145Sjlemon		tcpip_fillheaders(inp, ip, th);
1950111145Sjlemon	}
1951111145Sjlemon	optp = (u_int8_t *)(th + 1);
1952133874Srwatson
1953133874Srwatson	/*
1954111145Sjlemon	 * Send a timestamp and echo-reply if both our side and our peer
1955111145Sjlemon	 * have sent timestamps in our SYN's and this is not a RST.
1956133874Srwatson	 */
1957111145Sjlemon	if (tw->t_recent && flags == TH_ACK) {
1958111145Sjlemon		u_int32_t *lp = (u_int32_t *)optp;
1959111145Sjlemon
1960133874Srwatson		/* Form timestamp option as shown in appendix A of RFC 1323. */
1961133874Srwatson		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1962133874Srwatson		*lp++ = htonl(ticks);
1963133874Srwatson		*lp   = htonl(tw->t_recent);
1964133874Srwatson		optp += TCPOLEN_TSTAMP_APPA;
1965133874Srwatson	}
1966111145Sjlemon
1967111145Sjlemon	optlen = optp - (u_int8_t *)(th + 1);
1968111145Sjlemon
1969111145Sjlemon	m->m_len = hdrlen + optlen;
1970111145Sjlemon	m->m_pkthdr.len = m->m_len;
1971111145Sjlemon
1972111145Sjlemon	KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small"));
1973111145Sjlemon
1974111145Sjlemon	th->th_seq = htonl(tw->snd_nxt);
1975111145Sjlemon	th->th_ack = htonl(tw->rcv_nxt);
1976111145Sjlemon	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1977111145Sjlemon	th->th_flags = flags;
1978111145Sjlemon	th->th_win = htons(tw->last_win);
1979111145Sjlemon
1980111153Sjlemon#ifdef INET6
1981111145Sjlemon	if (isipv6) {
1982111145Sjlemon		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
1983111145Sjlemon		    sizeof(struct tcphdr) + optlen);
1984122922Sandre		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
1985122922Sandre		error = ip6_output(m, inp->in6p_outputopts, NULL,
1986111145Sjlemon		    (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp);
1987111153Sjlemon	} else
1988111153Sjlemon#endif
1989111153Sjlemon	{
1990111145Sjlemon		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1991133874Srwatson		    htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP));
1992111145Sjlemon		m->m_pkthdr.csum_flags = CSUM_TCP;
1993111145Sjlemon		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1994111145Sjlemon		ip->ip_len = m->m_pkthdr.len;
1995124248Sandre		if (path_mtu_discovery)
1996124248Sandre			ip->ip_off |= IP_DF;
1997122922Sandre		error = ip_output(m, inp->inp_options, NULL,
1998134793Sjmg		    ((tw->tw_so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0),
1999134793Sjmg		    NULL, inp);
2000111145Sjlemon	}
2001111145Sjlemon	if (flags & TH_ACK)
2002111145Sjlemon		tcpstat.tcps_sndacks++;
2003111145Sjlemon	else
2004111145Sjlemon		tcpstat.tcps_sndctrl++;
2005111145Sjlemon	tcpstat.tcps_sndtotal++;
2006111145Sjlemon	return (error);
2007111145Sjlemon}
2008111145Sjlemon
2009111145Sjlemon/*
2010102017Sdillon * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
2011102017Sdillon *
2012102017Sdillon * This code attempts to calculate the bandwidth-delay product as a
2013102017Sdillon * means of determining the optimal window size to maximize bandwidth,
2014102017Sdillon * minimize RTT, and avoid the over-allocation of buffers on interfaces and
2015102017Sdillon * routers.  This code also does a fairly good job keeping RTTs in check
2016102017Sdillon * across slow links like modems.  We implement an algorithm which is very
2017102017Sdillon * similar (but not meant to be) TCP/Vegas.  The code operates on the
2018102017Sdillon * transmitter side of a TCP connection and so only effects the transmit
2019102017Sdillon * side of the connection.
2020102017Sdillon *
2021102017Sdillon * BACKGROUND:  TCP makes no provision for the management of buffer space
2022133874Srwatson * at the end points or at the intermediate routers and switches.  A TCP
2023102017Sdillon * stream, whether using NewReno or not, will eventually buffer as
2024102017Sdillon * many packets as it is able and the only reason this typically works is
2025102017Sdillon * due to the fairly small default buffers made available for a connection
2026102017Sdillon * (typicaly 16K or 32K).  As machines use larger windows and/or window
2027102017Sdillon * scaling it is now fairly easy for even a single TCP connection to blow-out
2028133874Srwatson * all available buffer space not only on the local interface, but on
2029102017Sdillon * intermediate routers and switches as well.  NewReno makes a misguided
2030102017Sdillon * attempt to 'solve' this problem by waiting for an actual failure to occur,
2031102017Sdillon * then backing off, then steadily increasing the window again until another
2032102017Sdillon * failure occurs, ad-infinitum.  This results in terrible oscillation that
2033102017Sdillon * is only made worse as network loads increase and the idea of intentionally
2034102017Sdillon * blowing out network buffers is, frankly, a terrible way to manage network
2035102017Sdillon * resources.
2036102017Sdillon *
2037102017Sdillon * It is far better to limit the transmit window prior to the failure
2038102017Sdillon * condition being achieved.  There are two general ways to do this:  First
2039102017Sdillon * you can 'scan' through different transmit window sizes and locate the
2040102017Sdillon * point where the RTT stops increasing, indicating that you have filled the
2041102017Sdillon * pipe, then scan backwards until you note that RTT stops decreasing, then
2042102017Sdillon * repeat ad-infinitum.  This method works in principle but has severe
2043102017Sdillon * implementation issues due to RTT variances, timer granularity, and
2044102017Sdillon * instability in the algorithm which can lead to many false positives and
2045102017Sdillon * create oscillations as well as interact badly with other TCP streams
2046102017Sdillon * implementing the same algorithm.
2047102017Sdillon *
2048102017Sdillon * The second method is to limit the window to the bandwidth delay product
2049102017Sdillon * of the link.  This is the method we implement.  RTT variances and our
2050133874Srwatson * own manipulation of the congestion window, bwnd, can potentially
2051102017Sdillon * destabilize the algorithm.  For this reason we have to stabilize the
2052102017Sdillon * elements used to calculate the window.  We do this by using the minimum
2053102017Sdillon * observed RTT, the long term average of the observed bandwidth, and
2054102017Sdillon * by adding two segments worth of slop.  It isn't perfect but it is able
2055102017Sdillon * to react to changing conditions and gives us a very stable basis on
2056102017Sdillon * which to extend the algorithm.
2057102017Sdillon */
2058102017Sdillonvoid
2059102017Sdillontcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
2060102017Sdillon{
2061102017Sdillon	u_long bw;
2062102017Sdillon	u_long bwnd;
2063102017Sdillon	int save_ticks;
2064102017Sdillon
2065138410Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
2066138410Srwatson
2067102017Sdillon	/*
2068102017Sdillon	 * If inflight_enable is disabled in the middle of a tcp connection,
2069102017Sdillon	 * make sure snd_bwnd is effectively disabled.
2070102017Sdillon	 */
2071155767Sandre	if (tcp_inflight_enable == 0 || tp->t_rttlow < tcp_inflight_rttthresh) {
2072102017Sdillon		tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2073102017Sdillon		tp->snd_bandwidth = 0;
2074102017Sdillon		return;
2075102017Sdillon	}
2076102017Sdillon
2077102017Sdillon	/*
2078102017Sdillon	 * Figure out the bandwidth.  Due to the tick granularity this
2079102017Sdillon	 * is a very rough number and it MUST be averaged over a fairly
2080102017Sdillon	 * long period of time.  XXX we need to take into account a link
2081102017Sdillon	 * that is not using all available bandwidth, but for now our
2082102017Sdillon	 * slop will ramp us up if this case occurs and the bandwidth later
2083102017Sdillon	 * increases.
2084102368Sdillon	 *
2085102368Sdillon	 * Note: if ticks rollover 'bw' may wind up negative.  We must
2086102368Sdillon	 * effectively reset t_bw_rtttime for this case.
2087102017Sdillon	 */
2088102017Sdillon	save_ticks = ticks;
2089102017Sdillon	if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1)
2090102017Sdillon		return;
2091102017Sdillon
2092133874Srwatson	bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz /
2093102017Sdillon	    (save_ticks - tp->t_bw_rtttime);
2094102017Sdillon	tp->t_bw_rtttime = save_ticks;
2095102017Sdillon	tp->t_bw_rtseq = ack_seq;
2096102368Sdillon	if (tp->t_bw_rtttime == 0 || (int)bw < 0)
2097102017Sdillon		return;
2098102017Sdillon	bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
2099102017Sdillon
2100102017Sdillon	tp->snd_bandwidth = bw;
2101102017Sdillon
2102102017Sdillon	/*
2103102017Sdillon	 * Calculate the semi-static bandwidth delay product, plus two maximal
2104102017Sdillon	 * segments.  The additional slop puts us squarely in the sweet
2105107881Sdillon	 * spot and also handles the bandwidth run-up case and stabilization.
2106107881Sdillon	 * Without the slop we could be locking ourselves into a lower
2107107881Sdillon	 * bandwidth.
2108102017Sdillon	 *
2109102017Sdillon	 * Situations Handled:
2110102017Sdillon	 *	(1) Prevents over-queueing of packets on LANs, especially on
2111102017Sdillon	 *	    high speed LANs, allowing larger TCP buffers to be
2112133874Srwatson	 *	    specified, and also does a good job preventing
2113102017Sdillon	 *	    over-queueing of packets over choke points like modems
2114102017Sdillon	 *	    (at least for the transmit side).
2115102017Sdillon	 *
2116102017Sdillon	 *	(2) Is able to handle changing network loads (bandwidth
2117102017Sdillon	 *	    drops so bwnd drops, bandwidth increases so bwnd
2118102017Sdillon	 *	    increases).
2119102017Sdillon	 *
2120102017Sdillon	 *	(3) Theoretically should stabilize in the face of multiple
2121102017Sdillon	 *	    connections implementing the same algorithm (this may need
2122102017Sdillon	 *	    a little work).
2123107881Sdillon	 *
2124107881Sdillon	 *	(4) Stability value (defaults to 20 = 2 maximal packets) can
2125107881Sdillon	 *	    be adjusted with a sysctl but typically only needs to be
2126107881Sdillon	 *	    on very slow connections.  A value no smaller then 5
2127107881Sdillon	 *	    should be used, but only reduce this default if you have
2128107881Sdillon	 *	    no other choice.
2129102017Sdillon	 */
2130102017Sdillon#define USERTT	((tp->t_srtt + tp->t_rttbest) / 2)
2131107881Sdillon	bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10;
2132102368Sdillon#undef USERTT
2133102017Sdillon
2134102017Sdillon	if (tcp_inflight_debug > 0) {
2135102017Sdillon		static int ltime;
2136102017Sdillon		if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
2137102017Sdillon			ltime = ticks;
2138102017Sdillon			printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
2139102017Sdillon			    tp,
2140102017Sdillon			    bw,
2141102017Sdillon			    tp->t_rttbest,
2142102017Sdillon			    tp->t_srtt,
2143102017Sdillon			    bwnd
2144102017Sdillon			);
2145102017Sdillon		}
2146102017Sdillon	}
2147102017Sdillon	if ((long)bwnd < tcp_inflight_min)
2148102017Sdillon		bwnd = tcp_inflight_min;
2149102017Sdillon	if (bwnd > tcp_inflight_max)
2150102017Sdillon		bwnd = tcp_inflight_max;
2151102017Sdillon	if ((long)bwnd < tp->t_maxseg * 2)
2152102017Sdillon		bwnd = tp->t_maxseg * 2;
2153102017Sdillon	tp->snd_bwnd = bwnd;
2154102017Sdillon}
2155102017Sdillon
2156125680Sbms#ifdef TCP_SIGNATURE
2157125680Sbms/*
2158125783Sbms * Callback function invoked by m_apply() to digest TCP segment data
2159125783Sbms * contained within an mbuf chain.
2160125783Sbms */
2161125783Sbmsstatic int
2162125783Sbmstcp_signature_apply(void *fstate, void *data, u_int len)
2163125783Sbms{
2164125783Sbms
2165125819Sbms	MD5Update(fstate, (u_char *)data, len);
2166125783Sbms	return (0);
2167125783Sbms}
2168125783Sbms
2169125783Sbms/*
2170125680Sbms * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
2171125680Sbms *
2172125741Sbms * Parameters:
2173125741Sbms * m		pointer to head of mbuf chain
2174125741Sbms * off0		offset to TCP header within the mbuf chain
2175125741Sbms * len		length of TCP segment data, excluding options
2176125741Sbms * optlen	length of TCP segment options
2177125741Sbms * buf		pointer to storage for computed MD5 digest
2178125741Sbms * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
2179125741Sbms *
2180125680Sbms * We do this over ip, tcphdr, segment data, and the key in the SADB.
2181125680Sbms * When called from tcp_input(), we can be sure that th_sum has been
2182125680Sbms * zeroed out and verified already.
2183125680Sbms *
2184125680Sbms * This function is for IPv4 use only. Calling this function with an
2185125680Sbms * IPv6 packet in the mbuf chain will yield undefined results.
2186125680Sbms *
2187125680Sbms * Return 0 if successful, otherwise return -1.
2188125680Sbms *
2189125680Sbms * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
2190125680Sbms * search with the destination IP address, and a 'magic SPI' to be
2191125680Sbms * determined by the application. This is hardcoded elsewhere to 1179
2192125680Sbms * right now. Another branch of this code exists which uses the SPD to
2193125680Sbms * specify per-application flows but it is unstable.
2194125680Sbms */
2195125680Sbmsint
2196125783Sbmstcp_signature_compute(struct mbuf *m, int off0, int len, int optlen,
2197125741Sbms    u_char *buf, u_int direction)
2198125680Sbms{
2199125680Sbms	union sockaddr_union dst;
2200125680Sbms	struct ippseudo ippseudo;
2201125680Sbms	MD5_CTX ctx;
2202125680Sbms	int doff;
2203125680Sbms	struct ip *ip;
2204125680Sbms	struct ipovly *ipovly;
2205125680Sbms	struct secasvar *sav;
2206125680Sbms	struct tcphdr *th;
2207125680Sbms	u_short savecsum;
2208125680Sbms
2209125741Sbms	KASSERT(m != NULL, ("NULL mbuf chain"));
2210125741Sbms	KASSERT(buf != NULL, ("NULL signature pointer"));
2211125741Sbms
2212125741Sbms	/* Extract the destination from the IP header in the mbuf. */
2213125680Sbms	ip = mtod(m, struct ip *);
2214125680Sbms	bzero(&dst, sizeof(union sockaddr_union));
2215125680Sbms	dst.sa.sa_len = sizeof(struct sockaddr_in);
2216125680Sbms	dst.sa.sa_family = AF_INET;
2217125680Sbms	dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
2218125680Sbms	    ip->ip_src : ip->ip_dst;
2219125741Sbms
2220125741Sbms	/* Look up an SADB entry which matches the address of the peer. */
2221125680Sbms	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2222125680Sbms	if (sav == NULL) {
2223125680Sbms		printf("%s: SADB lookup failed for %s\n", __func__,
2224125680Sbms		    inet_ntoa(dst.sin.sin_addr));
2225125680Sbms		return (EINVAL);
2226125680Sbms	}
2227125741Sbms
2228125680Sbms	MD5Init(&ctx);
2229125680Sbms	ipovly = (struct ipovly *)ip;
2230125680Sbms	th = (struct tcphdr *)((u_char *)ip + off0);
2231125680Sbms	doff = off0 + sizeof(struct tcphdr) + optlen;
2232125741Sbms
2233125680Sbms	/*
2234125680Sbms	 * Step 1: Update MD5 hash with IP pseudo-header.
2235125680Sbms	 *
2236125680Sbms	 * XXX The ippseudo header MUST be digested in network byte order,
2237125680Sbms	 * or else we'll fail the regression test. Assume all fields we've
2238125680Sbms	 * been doing arithmetic on have been in host byte order.
2239125680Sbms	 * XXX One cannot depend on ipovly->ih_len here. When called from
2240125680Sbms	 * tcp_output(), the underlying ip_len member has not yet been set.
2241125680Sbms	 */
2242125680Sbms	ippseudo.ippseudo_src = ipovly->ih_src;
2243125680Sbms	ippseudo.ippseudo_dst = ipovly->ih_dst;
2244125680Sbms	ippseudo.ippseudo_pad = 0;
2245125680Sbms	ippseudo.ippseudo_p = IPPROTO_TCP;
2246125680Sbms	ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen);
2247125680Sbms	MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
2248125741Sbms
2249125680Sbms	/*
2250125680Sbms	 * Step 2: Update MD5 hash with TCP header, excluding options.
2251125680Sbms	 * The TCP checksum must be set to zero.
2252125680Sbms	 */
2253125680Sbms	savecsum = th->th_sum;
2254125680Sbms	th->th_sum = 0;
2255125680Sbms	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
2256125680Sbms	th->th_sum = savecsum;
2257125741Sbms
2258125680Sbms	/*
2259125680Sbms	 * Step 3: Update MD5 hash with TCP segment data.
2260125680Sbms	 *         Use m_apply() to avoid an early m_pullup().
2261125680Sbms	 */
2262125680Sbms	if (len > 0)
2263125783Sbms		m_apply(m, doff, len, tcp_signature_apply, &ctx);
2264125741Sbms
2265125680Sbms	/*
2266125680Sbms	 * Step 4: Update MD5 hash with shared secret.
2267125680Sbms	 */
2268125680Sbms	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2269125680Sbms	MD5Final(buf, &ctx);
2270125741Sbms
2271125680Sbms	key_sa_recordxfer(sav, m);
2272125680Sbms	KEY_FREESAV(&sav);
2273125680Sbms	return (0);
2274125680Sbms}
2275125680Sbms#endif /* TCP_SIGNATURE */
2276141886Smaxim
2277141886Smaximstatic int
2278141886Smaximsysctl_drop(SYSCTL_HANDLER_ARGS)
2279141886Smaxim{
2280141886Smaxim	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
2281141886Smaxim	struct sockaddr_storage addrs[2];
2282141886Smaxim	struct inpcb *inp;
2283141886Smaxim	struct tcpcb *tp;
2284150804Smaxim	struct tcptw *tw;
2285141886Smaxim	struct sockaddr_in *fin, *lin;
2286141886Smaxim#ifdef INET6
2287141886Smaxim	struct sockaddr_in6 *fin6, *lin6;
2288141886Smaxim	struct in6_addr f6, l6;
2289141886Smaxim#endif
2290141886Smaxim	int error;
2291141886Smaxim
2292141886Smaxim	inp = NULL;
2293141886Smaxim	fin = lin = NULL;
2294141886Smaxim#ifdef INET6
2295141886Smaxim	fin6 = lin6 = NULL;
2296141886Smaxim#endif
2297141886Smaxim	error = 0;
2298141886Smaxim
2299141886Smaxim	if (req->oldptr != NULL || req->oldlen != 0)
2300141886Smaxim		return (EINVAL);
2301141886Smaxim	if (req->newptr == NULL)
2302141886Smaxim		return (EPERM);
2303141886Smaxim	if (req->newlen < sizeof(addrs))
2304141886Smaxim		return (ENOMEM);
2305141886Smaxim	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
2306141886Smaxim	if (error)
2307141886Smaxim		return (error);
2308141886Smaxim
2309141886Smaxim	switch (addrs[0].ss_family) {
2310141886Smaxim#ifdef INET6
2311141886Smaxim	case AF_INET6:
2312141886Smaxim		fin6 = (struct sockaddr_in6 *)&addrs[0];
2313141886Smaxim		lin6 = (struct sockaddr_in6 *)&addrs[1];
2314141886Smaxim		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
2315141886Smaxim		    lin6->sin6_len != sizeof(struct sockaddr_in6))
2316141886Smaxim			return (EINVAL);
2317141886Smaxim		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
2318141886Smaxim			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
2319141886Smaxim				return (EINVAL);
2320141886Smaxim			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
2321141886Smaxim			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
2322141886Smaxim			fin = (struct sockaddr_in *)&addrs[0];
2323141886Smaxim			lin = (struct sockaddr_in *)&addrs[1];
2324141886Smaxim			break;
2325141886Smaxim		}
2326148385Sume		error = sa6_embedscope(fin6, ip6_use_defzone);
2327141886Smaxim		if (error)
2328148385Sume			return (error);
2329148385Sume		error = sa6_embedscope(lin6, ip6_use_defzone);
2330148616Sume		if (error)
2331148385Sume			return (error);
2332141886Smaxim		break;
2333141886Smaxim#endif
2334141886Smaxim	case AF_INET:
2335141886Smaxim		fin = (struct sockaddr_in *)&addrs[0];
2336141886Smaxim		lin = (struct sockaddr_in *)&addrs[1];
2337141886Smaxim		if (fin->sin_len != sizeof(struct sockaddr_in) ||
2338141886Smaxim		    lin->sin_len != sizeof(struct sockaddr_in))
2339141886Smaxim			return (EINVAL);
2340141886Smaxim		break;
2341141886Smaxim	default:
2342141886Smaxim		return (EINVAL);
2343141886Smaxim	}
2344141886Smaxim	INP_INFO_WLOCK(&tcbinfo);
2345141886Smaxim	switch (addrs[0].ss_family) {
2346141886Smaxim#ifdef INET6
2347141886Smaxim	case AF_INET6:
2348141886Smaxim		inp = in6_pcblookup_hash(&tcbinfo, &f6, fin6->sin6_port,
2349141886Smaxim		    &l6, lin6->sin6_port, 0, NULL);
2350141886Smaxim		break;
2351141886Smaxim#endif
2352141886Smaxim	case AF_INET:
2353141886Smaxim		inp = in_pcblookup_hash(&tcbinfo, fin->sin_addr, fin->sin_port,
2354141886Smaxim		    lin->sin_addr, lin->sin_port, 0, NULL);
2355141886Smaxim		break;
2356141886Smaxim	}
2357141886Smaxim	if (inp != NULL) {
2358141886Smaxim		INP_LOCK(inp);
2359157427Srwatson		if (inp->inp_vflag & INP_TIMEWAIT) {
2360157474Srwatson			/*
2361157474Srwatson			 * XXXRW: There currently exists a state where an
2362157474Srwatson			 * inpcb is present, but its timewait state has been
2363157474Srwatson			 * discarded.  For now, don't allow dropping of this
2364157474Srwatson			 * type of inpcb.
2365157474Srwatson			 */
2366157427Srwatson			tw = intotw(inp);
2367157474Srwatson			if (tw != NULL)
2368157474Srwatson				tcp_twclose(tw, 0);
2369157427Srwatson		} else if (!(inp->inp_vflag & INP_DROPPED) &&
2370157427Srwatson			   !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
2371157427Srwatson			tp = intotcpcb(inp);
2372157427Srwatson			tcp_drop(tp, ECONNABORTED);
2373157427Srwatson		}
2374157427Srwatson		INP_UNLOCK(inp);
2375141886Smaxim	} else
2376141886Smaxim		error = ESRCH;
2377141886Smaxim	INP_INFO_WUNLOCK(&tcbinfo);
2378141886Smaxim	return (error);
2379141886Smaxim}
2380141886Smaxim
2381141886SmaximSYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
2382141886Smaxim    CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL,
2383141886Smaxim    0, sysctl_drop, "", "Drop TCP connection");
2384