tcp_timewait.c revision 162768
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 162768 2006-09-29 06:46:31Z maxim $
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;
182162767Ssilby
183162031Sglebiusstatic int
184162767Ssilbytcptw_auto_size(void)
185162767Ssilby{
186162767Ssilby	int halfrange;
187162767Ssilby
188162767Ssilby	/*
189162768Smaxim	 * Max out at half the ephemeral port range so that TIME_WAIT
190162768Smaxim	 * sockets don't tie up too many ephemeral ports.
191162768Smaxim	 */
192162767Ssilby	if (ipport_lastauto > ipport_firstauto)
193162767Ssilby		halfrange = (ipport_lastauto - ipport_firstauto) / 2;
194162767Ssilby	else
195162767Ssilby		halfrange = (ipport_firstauto - ipport_lastauto) / 2;
196162767Ssilby	/* Protect against goofy port ranges smaller than 32. */
197162767Ssilby	return (imin(imax(halfrange, 32), maxsockets / 5));
198162767Ssilby}
199162767Ssilby
200162767Ssilbystatic int
201162031Sglebiussysctl_maxtcptw(SYSCTL_HANDLER_ARGS)
202162031Sglebius{
203162031Sglebius	int error, new;
204157478Sglebius
205162031Sglebius	if (maxtcptw == 0)
206162767Ssilby		new = tcptw_auto_size();
207162031Sglebius	else
208162031Sglebius		new = maxtcptw;
209162031Sglebius	error = sysctl_handle_int(oidp, &new, sizeof(int), req);
210162767Ssilby	if (error == 0 && req->newptr)
211162767Ssilby		if (new >= 32) {
212162031Sglebius			maxtcptw = new;
213162035Sglebius			uma_zone_set_max(tcptw_zone, maxtcptw);
214162767Ssilby		}
215162031Sglebius	return (error);
216162031Sglebius}
217162031SglebiusSYSCTL_PROC(_net_inet_tcp, OID_AUTO, maxtcptw, CTLTYPE_INT|CTLFLAG_RW,
218162031Sglebius    &maxtcptw, 0, sysctl_maxtcptw, "IU",
219162031Sglebius    "Maximum number of compressed TCP TIME_WAIT entries");
220162031Sglebius
221162151Sglebiusstatic int	nolocaltimewait = 0;
222162151SglebiusSYSCTL_INT(_net_inet_tcp, OID_AUTO, nolocaltimewait, CTLFLAG_RW,
223162151Sglebius    &nolocaltimewait, 0, "Do not create compressed TCP TIME_WAIT entries"
224162151Sglebius			 "for local connections");
225162151Sglebius
226102017Sdillon/*
227133874Srwatson * TCP bandwidth limiting sysctls.  Note that the default lower bound of
228133874Srwatson * 1024 exists only for debugging.  A good production default would be
229102017Sdillon * something like 6100.
230102017Sdillon */
231133072SandreSYSCTL_NODE(_net_inet_tcp, OID_AUTO, inflight, CTLFLAG_RW, 0,
232133072Sandre    "TCP inflight data limiting");
233133072Sandre
234124199Sandrestatic int	tcp_inflight_enable = 1;
235133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, enable, CTLFLAG_RW,
236102017Sdillon    &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
237102017Sdillon
238104825Sdillonstatic int	tcp_inflight_debug = 0;
239133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, debug, CTLFLAG_RW,
240102017Sdillon    &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
241102017Sdillon
242155767Sandrestatic int	tcp_inflight_rttthresh;
243155767SandreSYSCTL_PROC(_net_inet_tcp_inflight, OID_AUTO, rttthresh, CTLTYPE_INT|CTLFLAG_RW,
244155767Sandre    &tcp_inflight_rttthresh, 0, sysctl_msec_to_ticks, "I",
245155767Sandre    "RTT threshold below which inflight will deactivate itself");
246155767Sandre
247107881Sdillonstatic int	tcp_inflight_min = 6144;
248133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, min, CTLFLAG_RW,
249102017Sdillon    &tcp_inflight_min, 0, "Lower-bound for TCP inflight window");
250102017Sdillon
251102017Sdillonstatic int	tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
252133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, max, CTLFLAG_RW,
253102017Sdillon    &tcp_inflight_max, 0, "Upper-bound for TCP inflight window");
254133072Sandre
255107881Sdillonstatic int	tcp_inflight_stab = 20;
256133072SandreSYSCTL_INT(_net_inet_tcp_inflight, OID_AUTO, stab, CTLFLAG_RW,
257107881Sdillon    &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets");
258102017Sdillon
259130989Spsuma_zone_t sack_hole_zone;
260130989Sps
26198211Shsustatic struct inpcb *tcp_notify(struct inpcb *, int);
262128452Ssilbystatic void	tcp_isn_tick(void *);
26312296Sphk
2647684Sdg/*
26532821Sdg * Target size of TCP PCB hash tables. Must be a power of two.
26643562Smsmith *
26743562Smsmith * Note that this can be overridden by the kernel environment
26843562Smsmith * variable net.inet.tcp.tcbhashsize
2697684Sdg */
2707684Sdg#ifndef TCBHASHSIZE
27132821Sdg#define TCBHASHSIZE	512
2727684Sdg#endif
2731541Srgrimes
2741541Srgrimes/*
275111145Sjlemon * XXX
276111145Sjlemon * Callouts should be moved into struct tcp directly.  They are currently
277123608Sjhb * separate because the tcpcb structure is exported to userland for sysctl
278111145Sjlemon * parsing purposes, which do not know about callouts.
27934881Swollman */
280111145Sjlemonstruct	tcpcb_mem {
28134881Swollman	struct	tcpcb tcb;
282111145Sjlemon	struct	callout tcpcb_mem_rexmt, tcpcb_mem_persist, tcpcb_mem_keep;
283111145Sjlemon	struct	callout tcpcb_mem_2msl, tcpcb_mem_delack;
28434881Swollman};
28534881Swollman
286111145Sjlemonstatic uma_zone_t tcpcb_zone;
287128452Ssilbystruct callout isn_callout;
288157967Srwatsonstatic struct mtx isn_mtx;
289111145Sjlemon
290157977Srwatson#define	ISN_LOCK_INIT()	mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
291157977Srwatson#define	ISN_LOCK()	mtx_lock(&isn_mtx)
292157977Srwatson#define	ISN_UNLOCK()	mtx_unlock(&isn_mtx)
293157977Srwatson
29434881Swollman/*
295157431Srwatson * TCP initialization.
2961541Srgrimes */
297157927Spsstatic void
298157927Spstcp_zone_change(void *tag)
299157927Sps{
300157927Sps
301157927Sps	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
302157927Sps	uma_zone_set_max(tcpcb_zone, maxsockets);
303162031Sglebius	if (maxtcptw == 0)
304162767Ssilby		uma_zone_set_max(tcptw_zone, tcptw_auto_size());
305157927Sps}
306157927Sps
307160491Supsstatic int
308160491Supstcp_inpcb_init(void *mem, int size, int flags)
309160491Sups{
310160491Sups	struct inpcb *inp = (struct inpcb *) mem;
311160491Sups	INP_LOCK_INIT(inp, "inp", "tcpinp");
312160491Sups	return (0);
313160491Sups}
314160491Sups
3151541Srgrimesvoid
316157431Srwatsontcp_init(void)
3171541Srgrimes{
31877843Speter	int hashsize = TCBHASHSIZE;
319133874Srwatson
32050673Sjlemon	tcp_delacktime = TCPTV_DELACK;
32150673Sjlemon	tcp_keepinit = TCPTV_KEEP_INIT;
32250673Sjlemon	tcp_keepidle = TCPTV_KEEP_IDLE;
32350673Sjlemon	tcp_keepintvl = TCPTV_KEEPINTVL;
32450673Sjlemon	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
32550673Sjlemon	tcp_msl = TCPTV_MSL;
326100335Sdillon	tcp_rexmit_min = TCPTV_MIN;
327100335Sdillon	tcp_rexmit_slop = TCPTV_CPU_VAR;
328155767Sandre	tcp_inflight_rttthresh = TCPTV_INFLIGHT_RTTTHRESH;
32950673Sjlemon
33098102Shsu	INP_INFO_LOCK_INIT(&tcbinfo, "tcp");
3317684Sdg	LIST_INIT(&tcb);
3327684Sdg	tcbinfo.listhead = &tcb;
33377900Speter	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
33443576Smsmith	if (!powerof2(hashsize)) {
33543562Smsmith		printf("WARNING: TCB hash size not a power of 2\n");
33643562Smsmith		hashsize = 512; /* safe default */
33743562Smsmith	}
33850426Sjlemon	tcp_tcbhashsize = hashsize;
33943562Smsmith	tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
34043562Smsmith	tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
34134923Sbde					&tcbinfo.porthashmask);
342133874Srwatson	tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb),
343160491Sups	    NULL, NULL, tcp_inpcb_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
34492760Sjeff	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
34555679Sshin#ifdef INET6
34655679Sshin#define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
34755679Sshin#else /* INET6 */
34855679Sshin#define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
34955679Sshin#endif /* INET6 */
35055679Sshin	if (max_protohdr < TCP_MINPROTOHDR)
35155679Sshin		max_protohdr = TCP_MINPROTOHDR;
35255679Sshin	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
3531541Srgrimes		panic("tcp_init");
35455679Sshin#undef TCP_MINPROTOHDR
355111145Sjlemon	/*
356111145Sjlemon	 * These have to be type stable for the benefit of the timers.
357111145Sjlemon	 */
358133874Srwatson	tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
359133517Sandre	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
360111145Sjlemon	uma_zone_set_max(tcpcb_zone, maxsockets);
361162031Sglebius	tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw),
362162031Sglebius	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
363157478Sglebius	TUNABLE_INT_FETCH("net.inet.tcp.maxtcptw", &maxtcptw);
364157478Sglebius	if (maxtcptw == 0)
365162767Ssilby		uma_zone_set_max(tcptw_zone, tcptw_auto_size());
366162031Sglebius	else
367162031Sglebius		uma_zone_set_max(tcptw_zone, maxtcptw);
368112009Sjlemon	tcp_timer_init();
36986764Sjlemon	syncache_init();
370122922Sandre	tcp_hc_init();
371126193Sandre	tcp_reass_init();
372157977Srwatson	ISN_LOCK_INIT();
373128452Ssilby	callout_init(&isn_callout, CALLOUT_MPSAFE);
374128452Ssilby	tcp_isn_tick(NULL);
375128452Ssilby	EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
376128452Ssilby		SHUTDOWN_PRI_DEFAULT);
377133874Srwatson	sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
378133517Sandre	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
379157927Sps	EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
380157927Sps		EVENTHANDLER_PRI_ANY);
3811541Srgrimes}
3821541Srgrimes
383128452Ssilbyvoid
384157431Srwatsontcp_fini(void *xtp)
385128452Ssilby{
386157431Srwatson
387128452Ssilby	callout_stop(&isn_callout);
388128452Ssilby}
389128452Ssilby
3901541Srgrimes/*
39178642Ssilby * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
39278642Ssilby * tcp_template used to store this data in mbufs, but we now recopy it out
39378642Ssilby * of the tcpcb each time to conserve mbufs.
3941541Srgrimes */
39578642Ssilbyvoid
396157431Srwatsontcpip_fillheaders(struct inpcb *inp, void *ip_ptr, void *tcp_ptr)
3971541Srgrimes{
398111144Sjlemon	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
3991541Srgrimes
400138410Srwatson	INP_LOCK_ASSERT(inp);
401138410Srwatson
40255679Sshin#ifdef INET6
40355679Sshin	if ((inp->inp_vflag & INP_IPV6) != 0) {
40478642Ssilby		struct ip6_hdr *ip6;
40555679Sshin
40678642Ssilby		ip6 = (struct ip6_hdr *)ip_ptr;
40755679Sshin		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
40855679Sshin			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
40955679Sshin		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
41055679Sshin			(IPV6_VERSION & IPV6_VERSION_MASK);
41155679Sshin		ip6->ip6_nxt = IPPROTO_TCP;
41255679Sshin		ip6->ip6_plen = sizeof(struct tcphdr);
41355679Sshin		ip6->ip6_src = inp->in6p_laddr;
41455679Sshin		ip6->ip6_dst = inp->in6p_faddr;
41555679Sshin	} else
41655679Sshin#endif
41778642Ssilby	{
418111144Sjlemon		struct ip *ip;
41955679Sshin
420111144Sjlemon		ip = (struct ip *)ip_ptr;
421111144Sjlemon		ip->ip_v = IPVERSION;
422111144Sjlemon		ip->ip_hl = 5;
423111144Sjlemon		ip->ip_tos = inp->inp_ip_tos;
424111144Sjlemon		ip->ip_len = 0;
425111144Sjlemon		ip->ip_id = 0;
426111144Sjlemon		ip->ip_off = 0;
427111144Sjlemon		ip->ip_ttl = inp->inp_ip_ttl;
428111144Sjlemon		ip->ip_sum = 0;
429111144Sjlemon		ip->ip_p = IPPROTO_TCP;
430111144Sjlemon		ip->ip_src = inp->inp_laddr;
431111144Sjlemon		ip->ip_dst = inp->inp_faddr;
43278642Ssilby	}
433111144Sjlemon	th->th_sport = inp->inp_lport;
434111144Sjlemon	th->th_dport = inp->inp_fport;
435111144Sjlemon	th->th_seq = 0;
436111144Sjlemon	th->th_ack = 0;
437111144Sjlemon	th->th_x2 = 0;
438111144Sjlemon	th->th_off = 5;
439111144Sjlemon	th->th_flags = 0;
440111144Sjlemon	th->th_win = 0;
441111144Sjlemon	th->th_urp = 0;
442111144Sjlemon	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
44378642Ssilby}
44478642Ssilby
44578642Ssilby/*
44678642Ssilby * Create template to be used to send tcp packets on a connection.
44778642Ssilby * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
44878642Ssilby * use for this function is in keepalives, which use tcp_respond.
44978642Ssilby */
45078642Ssilbystruct tcptemp *
451157431Srwatsontcpip_maketemplate(struct inpcb *inp)
45278642Ssilby{
45378642Ssilby	struct mbuf *m;
45478642Ssilby	struct tcptemp *n;
45578642Ssilby
456149635Sandre	m = m_get(M_DONTWAIT, MT_DATA);
45778642Ssilby	if (m == NULL)
45878642Ssilby		return (0);
45978642Ssilby	m->m_len = sizeof(struct tcptemp);
46078642Ssilby	n = mtod(m, struct tcptemp *);
46178642Ssilby
462111144Sjlemon	tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
4631541Srgrimes	return (n);
4641541Srgrimes}
4651541Srgrimes
4661541Srgrimes/*
4671541Srgrimes * Send a single message to the TCP at address specified by
468127870Srwatson * the given TCP/IP header.  If m == NULL, then we make a copy
4691541Srgrimes * of the tcpiphdr at ti and send directly to the addressed host.
4701541Srgrimes * This is used to force keep alive messages out using the TCP
47178642Ssilby * template for a connection.  If flags are given then we send
47278642Ssilby * a message back to the TCP which originated the * segment ti,
47378642Ssilby * and discard the mbuf containing it and any other attached mbufs.
4741541Srgrimes *
4751541Srgrimes * In any case the ack and sequence number of the transmitted
4761541Srgrimes * segment are as specified by the parameters.
47731848Sjulian *
47831848Sjulian * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
4791541Srgrimes */
4801541Srgrimesvoid
481157431Srwatsontcp_respond(struct tcpcb *tp, void *ipgen, register struct tcphdr *th,
482157431Srwatson    register struct mbuf *m, tcp_seq ack, tcp_seq seq, int flags)
4831541Srgrimes{
4841541Srgrimes	register int tlen;
4851541Srgrimes	int win = 0;
48655679Sshin	struct ip *ip;
48755679Sshin	struct tcphdr *nth;
48855679Sshin#ifdef INET6
48955679Sshin	struct ip6_hdr *ip6;
49055679Sshin	int isipv6;
49155679Sshin#endif /* INET6 */
49255679Sshin	int ipflags = 0;
493128905Srwatson	struct inpcb *inp;
4941541Srgrimes
495101137Srwatson	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
496101137Srwatson
49755679Sshin#ifdef INET6
498105586Sphk	isipv6 = ((struct ip *)ipgen)->ip_v == 6;
49955679Sshin	ip6 = ipgen;
50055679Sshin#endif /* INET6 */
50155679Sshin	ip = ipgen;
50255679Sshin
503127871Srwatson	if (tp != NULL) {
504122327Ssam		inp = tp->t_inpcb;
505122327Ssam		KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
506122327Ssam		INP_INFO_WLOCK_ASSERT(&tcbinfo);
507122327Ssam		INP_LOCK_ASSERT(inp);
508128905Srwatson	} else
509128905Srwatson		inp = NULL;
510128905Srwatson
511128905Srwatson	if (tp != NULL) {
51257576Sps		if (!(flags & TH_RST)) {
513122327Ssam			win = sbspace(&inp->inp_socket->so_rcv);
51457576Sps			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
51557576Sps				win = (long)TCP_MAXWIN << tp->rcv_scale;
51657576Sps		}
5171541Srgrimes	}
518127870Srwatson	if (m == NULL) {
519151967Sandre		m = m_gethdr(M_DONTWAIT, MT_DATA);
5201541Srgrimes		if (m == NULL)
5211541Srgrimes			return;
5221541Srgrimes		tlen = 0;
5231541Srgrimes		m->m_data += max_linkhdr;
52455679Sshin#ifdef INET6
52555679Sshin		if (isipv6) {
526133874Srwatson			bcopy((caddr_t)ip6, mtod(m, caddr_t),
52755679Sshin			      sizeof(struct ip6_hdr));
52855679Sshin			ip6 = mtod(m, struct ip6_hdr *);
52955679Sshin			nth = (struct tcphdr *)(ip6 + 1);
53055679Sshin		} else
53155679Sshin#endif /* INET6 */
53255679Sshin	      {
53355679Sshin		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
53455679Sshin		ip = mtod(m, struct ip *);
53555679Sshin		nth = (struct tcphdr *)(ip + 1);
53655679Sshin	      }
53755679Sshin		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
5381541Srgrimes		flags = TH_ACK;
5391541Srgrimes	} else {
5401541Srgrimes		m_freem(m->m_next);
541127870Srwatson		m->m_next = NULL;
54255679Sshin		m->m_data = (caddr_t)ipgen;
54355679Sshin		/* m_len is set later */
5441541Srgrimes		tlen = 0;
5451541Srgrimes#define xchg(a,b,type) { type t; t=a; a=b; b=t; }
54655679Sshin#ifdef INET6
54755679Sshin		if (isipv6) {
54855679Sshin			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
54955679Sshin			nth = (struct tcphdr *)(ip6 + 1);
55055679Sshin		} else
55155679Sshin#endif /* INET6 */
55255679Sshin	      {
55355679Sshin		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
55455679Sshin		nth = (struct tcphdr *)(ip + 1);
55555679Sshin	      }
55655679Sshin		if (th != nth) {
55755679Sshin			/*
55855679Sshin			 * this is usually a case when an extension header
55955679Sshin			 * exists between the IPv6 header and the
56055679Sshin			 * TCP header.
56155679Sshin			 */
56255679Sshin			nth->th_sport = th->th_sport;
56355679Sshin			nth->th_dport = th->th_dport;
56455679Sshin		}
56555679Sshin		xchg(nth->th_dport, nth->th_sport, n_short);
5661541Srgrimes#undef xchg
5671541Srgrimes	}
56855679Sshin#ifdef INET6
56955679Sshin	if (isipv6) {
57090198Sume		ip6->ip6_flow = 0;
57190198Sume		ip6->ip6_vfc = IPV6_VERSION;
57290198Sume		ip6->ip6_nxt = IPPROTO_TCP;
57355679Sshin		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
57455679Sshin						tlen));
57555679Sshin		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
57656039Sshin	} else
57755679Sshin#endif
578133874Srwatson	{
579133874Srwatson		tlen += sizeof (struct tcpiphdr);
580133874Srwatson		ip->ip_len = tlen;
581133874Srwatson		ip->ip_ttl = ip_defttl;
582133874Srwatson		if (path_mtu_discovery)
583133874Srwatson			ip->ip_off |= IP_DF;
584133874Srwatson	}
5851541Srgrimes	m->m_len = tlen;
5861541Srgrimes	m->m_pkthdr.len = tlen;
587127870Srwatson	m->m_pkthdr.rcvif = NULL;
588101106Srwatson#ifdef MAC
589122327Ssam	if (inp != NULL) {
590101106Srwatson		/*
591101106Srwatson		 * Packet is associated with a socket, so allow the
592101106Srwatson		 * label of the response to reflect the socket label.
593101106Srwatson		 */
594128905Srwatson		INP_LOCK_ASSERT(inp);
595128905Srwatson		mac_create_mbuf_from_inpcb(inp, m);
596101106Srwatson	} else {
597101106Srwatson		/*
598119245Srwatson		 * Packet is not associated with a socket, so possibly
599119245Srwatson		 * update the label in place.
600101106Srwatson		 */
601119245Srwatson		mac_reflect_mbuf_tcp(m);
602101106Srwatson	}
603101106Srwatson#endif
60455679Sshin	nth->th_seq = htonl(seq);
60555679Sshin	nth->th_ack = htonl(ack);
60655679Sshin	nth->th_x2 = 0;
60755679Sshin	nth->th_off = sizeof (struct tcphdr) >> 2;
60855679Sshin	nth->th_flags = flags;
609127870Srwatson	if (tp != NULL)
61055679Sshin		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
6111541Srgrimes	else
61255679Sshin		nth->th_win = htons((u_short)win);
61355679Sshin	nth->th_urp = 0;
61455679Sshin#ifdef INET6
61555679Sshin	if (isipv6) {
61659392Sshin		nth->th_sum = 0;
61755679Sshin		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
61855679Sshin					sizeof(struct ip6_hdr),
61955679Sshin					tlen - sizeof(struct ip6_hdr));
620127870Srwatson		ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
621127870Srwatson		    NULL, NULL);
62255679Sshin	} else
62355679Sshin#endif /* INET6 */
624133874Srwatson	{
625133874Srwatson		nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
626133874Srwatson		    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
627133874Srwatson		m->m_pkthdr.csum_flags = CSUM_TCP;
628133874Srwatson		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
629133874Srwatson	}
6306283Swollman#ifdef TCPDEBUG
631122327Ssam	if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
63255679Sshin		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
6336283Swollman#endif
63455679Sshin#ifdef INET6
635122922Sandre	if (isipv6)
636122922Sandre		(void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp);
637122922Sandre	else
63855679Sshin#endif /* INET6 */
639122922Sandre	(void) ip_output(m, NULL, NULL, ipflags, NULL, inp);
6401541Srgrimes}
6411541Srgrimes
6421541Srgrimes/*
6431541Srgrimes * Create a new TCP control block, making an
6441541Srgrimes * empty reassembly queue and hooking it to the argument
64534881Swollman * protocol control block.  The `inp' parameter must have
64634881Swollman * come from the zone allocator set up in tcp_init().
6471541Srgrimes */
6481541Srgrimesstruct tcpcb *
649157431Srwatsontcp_newtcpcb(struct inpcb *inp)
6501541Srgrimes{
651111145Sjlemon	struct tcpcb_mem *tm;
652111145Sjlemon	struct tcpcb *tp;
65355679Sshin#ifdef INET6
65455679Sshin	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
65555679Sshin#endif /* INET6 */
6561541Srgrimes
657111145Sjlemon	tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO);
658111145Sjlemon	if (tm == NULL)
659111145Sjlemon		return (NULL);
660111145Sjlemon	tp = &tm->tcb;
661111145Sjlemon	/*	LIST_INIT(&tp->t_segq); */	/* XXX covered by M_ZERO */
66255679Sshin	tp->t_maxseg = tp->t_maxopd =
66355679Sshin#ifdef INET6
66455679Sshin		isipv6 ? tcp_v6mssdflt :
66555679Sshin#endif /* INET6 */
66655679Sshin		tcp_mssdflt;
6671541Srgrimes
66850673Sjlemon	/* Set up our timeouts. */
669142906Sglebius	callout_init(tp->tt_rexmt = &tm->tcpcb_mem_rexmt, NET_CALLOUT_MPSAFE);
670142906Sglebius	callout_init(tp->tt_persist = &tm->tcpcb_mem_persist, NET_CALLOUT_MPSAFE);
671142906Sglebius	callout_init(tp->tt_keep = &tm->tcpcb_mem_keep, NET_CALLOUT_MPSAFE);
672142906Sglebius	callout_init(tp->tt_2msl = &tm->tcpcb_mem_2msl, NET_CALLOUT_MPSAFE);
673142906Sglebius	callout_init(tp->tt_delack = &tm->tcpcb_mem_delack, NET_CALLOUT_MPSAFE);
67450673Sjlemon
6756283Swollman	if (tcp_do_rfc1323)
6766283Swollman		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
677130989Sps	tp->sack_enable = tcp_do_sack;
678147735Sps	TAILQ_INIT(&tp->snd_holes);
67934881Swollman	tp->t_inpcb = inp;	/* XXX */
6801541Srgrimes	/*
6811541Srgrimes	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
68216367Swollman	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
6831541Srgrimes	 * reasonable initial retransmit time.
6841541Srgrimes	 */
6851541Srgrimes	tp->t_srtt = TCPTV_SRTTBASE;
68616367Swollman	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
687100335Sdillon	tp->t_rttmin = tcp_rexmit_min;
68816367Swollman	tp->t_rxtcur = TCPTV_RTOBASE;
6891541Srgrimes	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
690102017Sdillon	tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
6911541Srgrimes	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
69250673Sjlemon	tp->t_rcvtime = ticks;
693102017Sdillon	tp->t_bw_rtttime = ticks;
694133874Srwatson	/*
69556564Sshin	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
69656564Sshin	 * because the socket may be bound to an IPv6 wildcard address,
69756564Sshin	 * which may match an IPv4-mapped IPv6 address.
69856564Sshin	 */
69924570Sdg	inp->inp_ip_ttl = ip_defttl;
700157432Srwatson	inp->inp_ppcb = tp;
70134881Swollman	return (tp);		/* XXX */
7021541Srgrimes}
7031541Srgrimes
7041541Srgrimes/*
7051541Srgrimes * Drop a TCP connection, reporting
7061541Srgrimes * the specified error.  If connection is synchronized,
7071541Srgrimes * then send a RST to peer.
7081541Srgrimes */
7091541Srgrimesstruct tcpcb *
710157431Srwatsontcp_drop(struct tcpcb *tp, int errno)
7111541Srgrimes{
7121541Srgrimes	struct socket *so = tp->t_inpcb->inp_socket;
7131541Srgrimes
714146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
715138019Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
716146864Srwatson
7171541Srgrimes	if (TCPS_HAVERCVDSYN(tp->t_state)) {
7181541Srgrimes		tp->t_state = TCPS_CLOSED;
7191541Srgrimes		(void) tcp_output(tp);
7201541Srgrimes		tcpstat.tcps_drops++;
7211541Srgrimes	} else
7221541Srgrimes		tcpstat.tcps_conndrops++;
7231541Srgrimes	if (errno == ETIMEDOUT && tp->t_softerror)
7241541Srgrimes		errno = tp->t_softerror;
7251541Srgrimes	so->so_error = errno;
7261541Srgrimes	return (tcp_close(tp));
7271541Srgrimes}
7281541Srgrimes
729157376Srwatsonvoid
730157431Srwatsontcp_discardcb(struct tcpcb *tp)
7311541Srgrimes{
732111145Sjlemon	struct tseg_qent *q;
7331541Srgrimes	struct inpcb *inp = tp->t_inpcb;
7341541Srgrimes	struct socket *so = inp->inp_socket;
73555679Sshin#ifdef INET6
73655679Sshin	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
73755679Sshin#endif /* INET6 */
7381541Srgrimes
739138410Srwatson	INP_LOCK_ASSERT(inp);
740138410Srwatson
7411541Srgrimes	/*
74250673Sjlemon	 * Make sure that all of our timers are stopped before we
74350673Sjlemon	 * delete the PCB.
74450673Sjlemon	 */
74550673Sjlemon	callout_stop(tp->tt_rexmt);
74650673Sjlemon	callout_stop(tp->tt_persist);
74750673Sjlemon	callout_stop(tp->tt_keep);
74850673Sjlemon	callout_stop(tp->tt_2msl);
74950673Sjlemon	callout_stop(tp->tt_delack);
75050673Sjlemon
75150673Sjlemon	/*
7529373Swollman	 * If we got enough samples through the srtt filter,
7539373Swollman	 * save the rtt and rttvar in the routing entry.
754122922Sandre	 * 'Enough' is arbitrarily defined as 4 rtt samples.
755122922Sandre	 * 4 samples is enough for the srtt filter to converge
756122922Sandre	 * to within enough % of the correct value; fewer samples
757122922Sandre	 * and we could save a bogus rtt. The danger is not high
758122922Sandre	 * as tcp quickly recovers from everything.
759122922Sandre	 * XXX: Works very well but needs some more statistics!
7601541Srgrimes	 */
761122922Sandre	if (tp->t_rttupdated >= 4) {
762122922Sandre		struct hc_metrics_lite metrics;
763122922Sandre		u_long ssthresh;
7641541Srgrimes
765122922Sandre		bzero(&metrics, sizeof(metrics));
7661541Srgrimes		/*
767122922Sandre		 * Update the ssthresh always when the conditions below
768122922Sandre		 * are satisfied. This gives us better new start value
769122922Sandre		 * for the congestion avoidance for new connections.
770122922Sandre		 * ssthresh is only set if packet loss occured on a session.
771160925Srwatson		 *
772160925Srwatson		 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
773160925Srwatson		 * being torn down.  Ideally this code would not use 'so'.
7741541Srgrimes		 */
775122922Sandre		ssthresh = tp->snd_ssthresh;
776122922Sandre		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
7771541Srgrimes			/*
7781541Srgrimes			 * convert the limit from user data bytes to
7791541Srgrimes			 * packets then to packet data bytes.
7801541Srgrimes			 */
781122922Sandre			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
782122922Sandre			if (ssthresh < 2)
783122922Sandre				ssthresh = 2;
784122922Sandre			ssthresh *= (u_long)(tp->t_maxseg +
78555679Sshin#ifdef INET6
78655679Sshin				      (isipv6 ? sizeof (struct ip6_hdr) +
78755679Sshin					       sizeof (struct tcphdr) :
78855679Sshin#endif
78955679Sshin				       sizeof (struct tcpiphdr)
79055679Sshin#ifdef INET6
79155679Sshin				       )
79255679Sshin#endif
79355679Sshin				      );
794122922Sandre		} else
795122922Sandre			ssthresh = 0;
796122922Sandre		metrics.rmx_ssthresh = ssthresh;
797122922Sandre
798122922Sandre		metrics.rmx_rtt = tp->t_srtt;
799122922Sandre		metrics.rmx_rttvar = tp->t_rttvar;
800122922Sandre		/* XXX: This wraps if the pipe is more than 4 Gbit per second */
801122922Sandre		metrics.rmx_bandwidth = tp->snd_bandwidth;
802122922Sandre		metrics.rmx_cwnd = tp->snd_cwnd;
803133874Srwatson		metrics.rmx_sendpipe = 0;
804122922Sandre		metrics.rmx_recvpipe = 0;
805122922Sandre
806122922Sandre		tcp_hc_update(&inp->inp_inc, &metrics);
8071541Srgrimes	}
808122922Sandre
8091541Srgrimes	/* free the reassembly queue, if any */
810111145Sjlemon	while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
81155679Sshin		LIST_REMOVE(q, tqe_q);
81255679Sshin		m_freem(q->tqe_m);
813126193Sandre		uma_zfree(tcp_reass_zone, q);
814126193Sandre		tp->t_segqlen--;
815126193Sandre		tcp_reass_qsize--;
8161541Srgrimes	}
817130989Sps	tcp_free_sackholes(tp);
81832821Sdg	inp->inp_ppcb = NULL;
819108265Shsu	tp->t_inpcb = NULL;
820111145Sjlemon	uma_zfree(tcpcb_zone, tp);
821111145Sjlemon}
822111145Sjlemon
823111145Sjlemon/*
824157430Srwatson * Attempt to close a TCP control block, marking it as dropped, and freeing
825157430Srwatson * the socket if we hold the only reference.
826111145Sjlemon */
827111145Sjlemonstruct tcpcb *
828157431Srwatsontcp_close(struct tcpcb *tp)
829111145Sjlemon{
830111145Sjlemon	struct inpcb *inp = tp->t_inpcb;
831157376Srwatson	struct socket *so;
832111145Sjlemon
833146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
834138410Srwatson	INP_LOCK_ASSERT(inp);
835138410Srwatson
836158009Srwatson	in_pcbdrop(inp);
837157376Srwatson	tcpstat.tcps_closed++;
838157376Srwatson	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
839157376Srwatson	so = inp->inp_socket;
840157376Srwatson	soisdisconnected(so);
841157376Srwatson	if (inp->inp_vflag & INP_SOCKREF) {
842157376Srwatson		KASSERT(so->so_state & SS_PROTOREF,
843157376Srwatson		    ("tcp_close: !SS_PROTOREF"));
844157376Srwatson		inp->inp_vflag &= ~INP_SOCKREF;
845160549Srwatson		INP_UNLOCK(inp);
846157376Srwatson		ACCEPT_LOCK();
847157376Srwatson		SOCK_LOCK(so);
848157376Srwatson		so->so_state &= ~SS_PROTOREF;
849157376Srwatson		sofree(so);
850157376Srwatson		return (NULL);
851157376Srwatson	}
852157376Srwatson	return (tp);
8531541Srgrimes}
8541541Srgrimes
8551541Srgrimesvoid
856157431Srwatsontcp_drain(void)
8571541Srgrimes{
858157431Srwatson
859157431Srwatson	if (do_tcpdrain) {
86055198Smsmith		struct inpcb *inpb;
86155198Smsmith		struct tcpcb *tcpb;
86255679Sshin		struct tseg_qent *te;
8631541Srgrimes
86455198Smsmith	/*
86555198Smsmith	 * Walk the tcpbs, if existing, and flush the reassembly queue,
86655198Smsmith	 * if there is one...
86755198Smsmith	 * XXX: The "Net/3" implementation doesn't imply that the TCP
86855198Smsmith	 *      reassembly queue should be flushed, but in a situation
869133874Srwatson	 *	where we're really low on mbufs, this is potentially
870133874Srwatson	 *	usefull.
87155198Smsmith	 */
87298102Shsu		INP_INFO_RLOCK(&tcbinfo);
87374362Sphk		LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) {
874111145Sjlemon			if (inpb->inp_vflag & INP_TIMEWAIT)
875111145Sjlemon				continue;
87698102Shsu			INP_LOCK(inpb);
877127870Srwatson			if ((tcpb = intotcpcb(inpb)) != NULL) {
87874362Sphk				while ((te = LIST_FIRST(&tcpb->t_segq))
87974362Sphk			            != NULL) {
88055679Sshin					LIST_REMOVE(te, tqe_q);
88155679Sshin					m_freem(te->tqe_m);
882126193Sandre					uma_zfree(tcp_reass_zone, te);
883126193Sandre					tcpb->t_segqlen--;
884126193Sandre					tcp_reass_qsize--;
88555198Smsmith				}
886144857Sps				tcp_clean_sackreport(tcpb);
88755198Smsmith			}
88898102Shsu			INP_UNLOCK(inpb);
88955198Smsmith		}
89098102Shsu		INP_INFO_RUNLOCK(&tcbinfo);
89155198Smsmith	}
8921541Srgrimes}
8931541Srgrimes
8941541Srgrimes/*
8951541Srgrimes * Notify a tcp user of an asynchronous error;
8961541Srgrimes * store error as soft error, but wake up user
8971541Srgrimes * (for now, won't do anything until can select for soft error).
89872960Sjlemon *
89972960Sjlemon * Do not wake up user since there currently is no mechanism for
90072960Sjlemon * reporting soft errors (yet - a kqueue filter may be added).
9011541Srgrimes */
90298211Shsustatic struct inpcb *
903157431Srwatsontcp_notify(struct inpcb *inp, int error)
9041541Srgrimes{
905157432Srwatson	struct tcpcb *tp;
9061541Srgrimes
907146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
908138410Srwatson	INP_LOCK_ASSERT(inp);
909157433Srwatson
910157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
911157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
912157433Srwatson		return (inp);
913157433Srwatson
914157432Srwatson	tp = intotcpcb(inp);
915157433Srwatson	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
916138410Srwatson
9171541Srgrimes	/*
9181541Srgrimes	 * Ignore some errors if we are hooked up.
9191541Srgrimes	 * If connection hasn't completed, has retransmitted several times,
9201541Srgrimes	 * and receives a second error, give up now.  This is better
9211541Srgrimes	 * than waiting a long time to establish a connection that
9221541Srgrimes	 * can never complete.
9231541Srgrimes	 */
9241541Srgrimes	if (tp->t_state == TCPS_ESTABLISHED &&
925110896Shsu	    (error == EHOSTUNREACH || error == ENETUNREACH ||
926110896Shsu	     error == EHOSTDOWN)) {
927139222Srwatson		return (inp);
9281541Srgrimes	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
92998211Shsu	    tp->t_softerror) {
930157376Srwatson		tp = tcp_drop(tp, error);
931157376Srwatson		if (tp != NULL)
932157376Srwatson			return (inp);
933157376Srwatson		else
934157376Srwatson			return (NULL);
93598211Shsu	} else {
9361541Srgrimes		tp->t_softerror = error;
937139222Srwatson		return (inp);
93898211Shsu	}
93972960Sjlemon#if 0
940111748Sdes	wakeup( &so->so_timeo);
9411541Srgrimes	sorwakeup(so);
9421541Srgrimes	sowwakeup(so);
94372960Sjlemon#endif
9441541Srgrimes}
9451541Srgrimes
94636079Swollmanstatic int
94762573Sphktcp_pcblist(SYSCTL_HANDLER_ARGS)
94836079Swollman{
949148156Srwatson	int error, i, n;
95036079Swollman	struct inpcb *inp, **inp_list;
95136079Swollman	inp_gen_t gencnt;
95236079Swollman	struct xinpgen xig;
95336079Swollman
95436079Swollman	/*
95536079Swollman	 * The process of preparing the TCB list is too time-consuming and
95636079Swollman	 * resource-intensive to repeat twice on every request.
95736079Swollman	 */
958127870Srwatson	if (req->oldptr == NULL) {
95936079Swollman		n = tcbinfo.ipi_count;
96036079Swollman		req->oldidx = 2 * (sizeof xig)
96136079Swollman			+ (n + n/8) * sizeof(struct xtcpcb);
962139222Srwatson		return (0);
96336079Swollman	}
96436079Swollman
965127870Srwatson	if (req->newptr != NULL)
966139222Srwatson		return (EPERM);
96736079Swollman
96836079Swollman	/*
96936079Swollman	 * OK, now we're committed to doing something.
97036079Swollman	 */
97198102Shsu	INP_INFO_RLOCK(&tcbinfo);
97236079Swollman	gencnt = tcbinfo.ipi_gencnt;
97336079Swollman	n = tcbinfo.ipi_count;
97498102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
97536079Swollman
976126253Struckman	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
977100831Struckman		+ n * sizeof(struct xtcpcb));
978126253Struckman	if (error != 0)
979126253Struckman		return (error);
980100831Struckman
98136079Swollman	xig.xig_len = sizeof xig;
98236079Swollman	xig.xig_count = n;
98336079Swollman	xig.xig_gen = gencnt;
98436079Swollman	xig.xig_sogen = so_gencnt;
98536079Swollman	error = SYSCTL_OUT(req, &xig, sizeof xig);
98636079Swollman	if (error)
987139222Srwatson		return (error);
98836079Swollman
989111119Simp	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
990127870Srwatson	if (inp_list == NULL)
991139222Srwatson		return (ENOMEM);
992133874Srwatson
99398102Shsu	INP_INFO_RLOCK(&tcbinfo);
994127870Srwatson	for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp != NULL && i < n;
99571999Sphk	     inp = LIST_NEXT(inp, inp_list)) {
99698102Shsu		INP_LOCK(inp);
997113345Srwatson		if (inp->inp_gencnt <= gencnt) {
998113345Srwatson			/*
999113345Srwatson			 * XXX: This use of cr_cansee(), introduced with
1000113345Srwatson			 * TCP state changes, is not quite right, but for
1001113345Srwatson			 * now, better than nothing.
1002113345Srwatson			 */
1003157474Srwatson			if (inp->inp_vflag & INP_TIMEWAIT) {
1004157474Srwatson				if (intotw(inp) != NULL)
1005157474Srwatson					error = cr_cansee(req->td->td_ucred,
1006157474Srwatson					    intotw(inp)->tw_cred);
1007157474Srwatson				else
1008157474Srwatson					error = EINVAL;	/* Skip this inp. */
1009157474Srwatson			} else
1010113345Srwatson				error = cr_canseesocket(req->td->td_ucred,
1011113345Srwatson				    inp->inp_socket);
1012113345Srwatson			if (error == 0)
1013113345Srwatson				inp_list[i++] = inp;
1014113345Srwatson		}
101598102Shsu		INP_UNLOCK(inp);
101636079Swollman	}
101798102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
101836079Swollman	n = i;
101936079Swollman
102036079Swollman	error = 0;
102136079Swollman	for (i = 0; i < n; i++) {
102236079Swollman		inp = inp_list[i];
1023160491Sups		INP_LOCK(inp);
102436079Swollman		if (inp->inp_gencnt <= gencnt) {
102536079Swollman			struct xtcpcb xt;
1026157432Srwatson			void *inp_ppcb;
1027145978Scperciva
1028145978Scperciva			bzero(&xt, sizeof(xt));
102936079Swollman			xt.xt_len = sizeof xt;
103036079Swollman			/* XXX should avoid extra copy */
103136079Swollman			bcopy(inp, &xt.xt_inp, sizeof *inp);
103247960Stegge			inp_ppcb = inp->inp_ppcb;
1033111145Sjlemon			if (inp_ppcb == NULL)
1034111145Sjlemon				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1035111145Sjlemon			else if (inp->inp_vflag & INP_TIMEWAIT) {
1036111145Sjlemon				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1037111145Sjlemon				xt.xt_tp.t_state = TCPS_TIME_WAIT;
1038111145Sjlemon			} else
103947960Stegge				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
1040127870Srwatson			if (inp->inp_socket != NULL)
104136079Swollman				sotoxsocket(inp->inp_socket, &xt.xt_socket);
1042111145Sjlemon			else {
1043111145Sjlemon				bzero(&xt.xt_socket, sizeof xt.xt_socket);
1044111145Sjlemon				xt.xt_socket.xso_protocol = IPPROTO_TCP;
1045111145Sjlemon			}
1046110896Shsu			xt.xt_inp.inp_gencnt = inp->inp_gencnt;
1047160491Sups			INP_UNLOCK(inp);
104836079Swollman			error = SYSCTL_OUT(req, &xt, sizeof xt);
1049160491Sups		} else
1050160491Sups			INP_UNLOCK(inp);
1051160491Sups
105236079Swollman	}
105336079Swollman	if (!error) {
105436079Swollman		/*
105536079Swollman		 * Give the user an updated idea of our state.
105636079Swollman		 * If the generation differs from what we told
105736079Swollman		 * her before, she knows that something happened
105836079Swollman		 * while we were processing this request, and it
105936079Swollman		 * might be necessary to retry.
106036079Swollman		 */
106198102Shsu		INP_INFO_RLOCK(&tcbinfo);
106236079Swollman		xig.xig_gen = tcbinfo.ipi_gencnt;
106336079Swollman		xig.xig_sogen = so_gencnt;
106436079Swollman		xig.xig_count = tcbinfo.ipi_count;
106598102Shsu		INP_INFO_RUNLOCK(&tcbinfo);
106636079Swollman		error = SYSCTL_OUT(req, &xig, sizeof xig);
106736079Swollman	}
106836079Swollman	free(inp_list, M_TEMP);
1069139222Srwatson	return (error);
107036079Swollman}
107136079Swollman
107236079SwollmanSYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
107336079Swollman	    tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
107436079Swollman
107548758Sgreenstatic int
107662573Sphktcp_getcred(SYSCTL_HANDLER_ARGS)
107748758Sgreen{
107872650Sgreen	struct xucred xuc;
107948758Sgreen	struct sockaddr_in addrs[2];
108048758Sgreen	struct inpcb *inp;
1081148156Srwatson	int error;
108248758Sgreen
1083132653Scperciva	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
108448758Sgreen	if (error)
108548758Sgreen		return (error);
108648758Sgreen	error = SYSCTL_IN(req, addrs, sizeof(addrs));
108748758Sgreen	if (error)
108848758Sgreen		return (error);
108998102Shsu	INP_INFO_RLOCK(&tcbinfo);
109048758Sgreen	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
109154263Sshin	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
109298102Shsu	if (inp == NULL) {
109348758Sgreen		error = ENOENT;
109498102Shsu		goto outunlocked;
109548758Sgreen	}
109699837Struckman	INP_LOCK(inp);
109799837Struckman	if (inp->inp_socket == NULL) {
109899837Struckman		error = ENOENT;
109999837Struckman		goto out;
110099837Struckman	}
110192976Srwatson	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
110278697Sdwmalone	if (error)
110378697Sdwmalone		goto out;
110491354Sdd	cru2x(inp->inp_socket->so_cred, &xuc);
110548758Sgreenout:
110698102Shsu	INP_UNLOCK(inp);
110798102Shsuoutunlocked:
110898102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
110999838Struckman	if (error == 0)
111099838Struckman		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
111148758Sgreen	return (error);
111248758Sgreen}
111348758Sgreen
111478697SdwmaloneSYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
111578697Sdwmalone    CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
111678697Sdwmalone    tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
111748758Sgreen
111855679Sshin#ifdef INET6
111955679Sshinstatic int
112062573Sphktcp6_getcred(SYSCTL_HANDLER_ARGS)
112155679Sshin{
112272650Sgreen	struct xucred xuc;
112355679Sshin	struct sockaddr_in6 addrs[2];
112455679Sshin	struct inpcb *inp;
1125148156Srwatson	int error, mapped = 0;
112655679Sshin
1127132653Scperciva	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
112855679Sshin	if (error)
112955679Sshin		return (error);
113055679Sshin	error = SYSCTL_IN(req, addrs, sizeof(addrs));
113155679Sshin	if (error)
113255679Sshin		return (error);
1133148385Sume	if ((error = sa6_embedscope(&addrs[0], ip6_use_defzone)) != 0 ||
1134148385Sume	    (error = sa6_embedscope(&addrs[1], ip6_use_defzone)) != 0) {
1135148385Sume		return (error);
1136148385Sume	}
113755679Sshin	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
113855679Sshin		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
113955679Sshin			mapped = 1;
114055679Sshin		else
114155679Sshin			return (EINVAL);
114255679Sshin	}
1143148385Sume
114498102Shsu	INP_INFO_RLOCK(&tcbinfo);
114555679Sshin	if (mapped == 1)
114655679Sshin		inp = in_pcblookup_hash(&tcbinfo,
114755679Sshin			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
114855679Sshin			addrs[1].sin6_port,
114955679Sshin			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
115055679Sshin			addrs[0].sin6_port,
115155679Sshin			0, NULL);
115255679Sshin	else
1153151254Sphilip		inp = in6_pcblookup_hash(&tcbinfo,
1154151254Sphilip			&addrs[1].sin6_addr, addrs[1].sin6_port,
1155151254Sphilip			&addrs[0].sin6_addr, addrs[0].sin6_port, 0, NULL);
115698102Shsu	if (inp == NULL) {
115755679Sshin		error = ENOENT;
115898102Shsu		goto outunlocked;
115955679Sshin	}
116099837Struckman	INP_LOCK(inp);
116199837Struckman	if (inp->inp_socket == NULL) {
116299837Struckman		error = ENOENT;
116399837Struckman		goto out;
116499837Struckman	}
116592976Srwatson	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
116678697Sdwmalone	if (error)
116778697Sdwmalone		goto out;
116891354Sdd	cru2x(inp->inp_socket->so_cred, &xuc);
116955679Sshinout:
117098102Shsu	INP_UNLOCK(inp);
117198102Shsuoutunlocked:
117298102Shsu	INP_INFO_RUNLOCK(&tcbinfo);
117399838Struckman	if (error == 0)
117499838Struckman		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
117555679Sshin	return (error);
117655679Sshin}
117755679Sshin
117878697SdwmaloneSYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
117978697Sdwmalone    CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
118078697Sdwmalone    tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
118155679Sshin#endif
118255679Sshin
118355679Sshin
11841541Srgrimesvoid
1185157431Srwatsontcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
11861541Srgrimes{
118772959Sjlemon	struct ip *ip = vip;
118872959Sjlemon	struct tcphdr *th;
118973109Sjlemon	struct in_addr faddr;
119073109Sjlemon	struct inpcb *inp;
119173109Sjlemon	struct tcpcb *tp;
119298211Shsu	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1193145360Sandre	struct icmp *icp;
1194145360Sandre	struct in_conninfo inc;
1195145360Sandre	tcp_seq icmp_tcp_seq;
1196148156Srwatson	int mtu;
11971541Srgrimes
119873109Sjlemon	faddr = ((struct sockaddr_in *)sa)->sin_addr;
119973109Sjlemon	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
120073109Sjlemon		return;
120173109Sjlemon
1202145355Sandre	if (cmd == PRC_MSGSIZE)
1203145355Sandre		notify = tcp_mtudisc;
120474937Sjesper	else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
120599156Sjesper		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
120672959Sjlemon		notify = tcp_drop_syn_sent;
1207122922Sandre	/*
1208122922Sandre	 * Redirects don't need to be handled up here.
1209122922Sandre	 */
1210122922Sandre	else if (PRC_IS_REDIRECT(cmd))
1211122922Sandre		return;
1212122922Sandre	/*
1213145355Sandre	 * Source quench is depreciated.
1214145355Sandre	 */
1215145355Sandre	else if (cmd == PRC_QUENCH)
1216145355Sandre		return;
1217145355Sandre	/*
1218122922Sandre	 * Hostdead is ugly because it goes linearly through all PCBs.
1219122922Sandre	 * XXX: We never get this from ICMP, otherwise it makes an
1220122922Sandre	 * excellent DoS attack on machines with many connections.
1221122922Sandre	 */
1222122922Sandre	else if (cmd == PRC_HOSTDEAD)
1223127870Srwatson		ip = NULL;
1224119995Sru	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
12251541Srgrimes		return;
1226127870Srwatson	if (ip != NULL) {
1227145360Sandre		icp = (struct icmp *)((caddr_t)ip
1228145360Sandre				      - offsetof(struct icmp, icmp_ip));
1229133874Srwatson		th = (struct tcphdr *)((caddr_t)ip
1230105586Sphk				       + (ip->ip_hl << 2));
123198596Shsu		INP_INFO_WLOCK(&tcbinfo);
123273109Sjlemon		inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
123373109Sjlemon		    ip->ip_src, th->th_sport, 0, NULL);
123498102Shsu		if (inp != NULL)  {
123598102Shsu			INP_LOCK(inp);
1236157433Srwatson			if (!(inp->inp_vflag & INP_TIMEWAIT) &&
1237157433Srwatson			    !(inp->inp_vflag & INP_DROPPED) &&
1238157433Srwatson			    !(inp->inp_socket == NULL)) {
1239145360Sandre				icmp_tcp_seq = htonl(th->th_seq);
124098102Shsu				tp = intotcpcb(inp);
1241145360Sandre				if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
1242145360Sandre				    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
1243145360Sandre					if (cmd == PRC_MSGSIZE) {
1244145360Sandre					    /*
1245145360Sandre					     * MTU discovery:
1246145360Sandre					     * If we got a needfrag set the MTU
1247145360Sandre					     * in the route to the suggested new
1248145360Sandre					     * value (if given) and then notify.
1249145360Sandre					     */
1250145360Sandre					    bzero(&inc, sizeof(inc));
1251145360Sandre					    inc.inc_flags = 0;	/* IPv4 */
1252145360Sandre					    inc.inc_faddr = faddr;
1253145360Sandre
1254145360Sandre					    mtu = ntohs(icp->icmp_nextmtu);
1255145869Sandre					    /*
1256145869Sandre					     * If no alternative MTU was
1257145869Sandre					     * proposed, try the next smaller
1258149929Sandre					     * one.  ip->ip_len has already
1259149929Sandre					     * been swapped in icmp_input().
1260145869Sandre					     */
1261145360Sandre					    if (!mtu)
1262149929Sandre						mtu = ip_next_mtu(ip->ip_len,
1263145869Sandre						 1);
1264145869Sandre					    if (mtu < max(296, (tcp_minmss)
1265145869Sandre						 + sizeof(struct tcpiphdr)))
1266145869Sandre						mtu = 0;
1267145869Sandre					    if (!mtu)
1268145869Sandre						mtu = tcp_mssdflt
1269145869Sandre						 + sizeof(struct tcpiphdr);
1270145869Sandre					    /*
1271145869Sandre					     * Only cache the the MTU if it
1272145869Sandre					     * is smaller than the interface
1273145869Sandre					     * or route MTU.  tcp_mtudisc()
1274145869Sandre					     * will do right thing by itself.
1275145869Sandre					     */
1276162084Sandre					    if (mtu <= tcp_maxmtu(&inc, NULL))
1277145360Sandre						tcp_hc_updatemtu(&inc, mtu);
1278145360Sandre					}
1279145360Sandre
128098211Shsu					inp = (*notify)(inp, inetctlerrmap[cmd]);
1281145360Sandre				}
128298102Shsu			}
1283127870Srwatson			if (inp != NULL)
128498211Shsu				INP_UNLOCK(inp);
128586764Sjlemon		} else {
128686764Sjlemon			inc.inc_fport = th->th_dport;
128786764Sjlemon			inc.inc_lport = th->th_sport;
128886764Sjlemon			inc.inc_faddr = faddr;
128986764Sjlemon			inc.inc_laddr = ip->ip_src;
129086764Sjlemon#ifdef INET6
129186764Sjlemon			inc.inc_isipv6 = 0;
129286764Sjlemon#endif
129386764Sjlemon			syncache_unreach(&inc, th);
129473109Sjlemon		}
129598596Shsu		INP_INFO_WUNLOCK(&tcbinfo);
12961541Srgrimes	} else
129798102Shsu		in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
12981541Srgrimes}
12991541Srgrimes
130055679Sshin#ifdef INET6
130155679Sshinvoid
1302157431Srwatsontcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
130355679Sshin{
130455679Sshin	struct tcphdr th;
130598211Shsu	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
130655679Sshin	struct ip6_hdr *ip6;
130755679Sshin	struct mbuf *m;
130878064Sume	struct ip6ctlparam *ip6cp = NULL;
130978064Sume	const struct sockaddr_in6 *sa6_src = NULL;
131055679Sshin	int off;
131178064Sume	struct tcp_portonly {
131278064Sume		u_int16_t th_sport;
131378064Sume		u_int16_t th_dport;
131478064Sume	} *thp;
131555679Sshin
131655679Sshin	if (sa->sa_family != AF_INET6 ||
131755679Sshin	    sa->sa_len != sizeof(struct sockaddr_in6))
131855679Sshin		return;
131955679Sshin
1320145355Sandre	if (cmd == PRC_MSGSIZE)
132155679Sshin		notify = tcp_mtudisc;
132255679Sshin	else if (!PRC_IS_REDIRECT(cmd) &&
1323119995Sru		 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
132455679Sshin		return;
1325145355Sandre	/* Source quench is depreciated. */
1326145355Sandre	else if (cmd == PRC_QUENCH)
1327145355Sandre		return;
132855679Sshin
132955679Sshin	/* if the parameter is from icmp6, decode it. */
133055679Sshin	if (d != NULL) {
133178064Sume		ip6cp = (struct ip6ctlparam *)d;
133255679Sshin		m = ip6cp->ip6c_m;
133355679Sshin		ip6 = ip6cp->ip6c_ip6;
133455679Sshin		off = ip6cp->ip6c_off;
133578064Sume		sa6_src = ip6cp->ip6c_src;
133655679Sshin	} else {
133755679Sshin		m = NULL;
133855679Sshin		ip6 = NULL;
133967456Sitojun		off = 0;	/* fool gcc */
134078064Sume		sa6_src = &sa6_any;
134155679Sshin	}
134255679Sshin
1343127870Srwatson	if (ip6 != NULL) {
134486764Sjlemon		struct in_conninfo inc;
134555679Sshin		/*
134655679Sshin		 * XXX: We assume that when IPV6 is non NULL,
134755679Sshin		 * M and OFF are valid.
134855679Sshin		 */
134955679Sshin
135067456Sitojun		/* check if we can safely examine src and dst ports */
135178064Sume		if (m->m_pkthdr.len < off + sizeof(*thp))
135267456Sitojun			return;
135367456Sitojun
135478064Sume		bzero(&th, sizeof(th));
135578064Sume		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
135678064Sume
1357133192Srwatson		in6_pcbnotify(&tcbinfo, sa, th.th_dport,
135878064Sume		    (struct sockaddr *)ip6cp->ip6c_src,
1359125776Sume		    th.th_sport, cmd, NULL, notify);
136086764Sjlemon
136186764Sjlemon		inc.inc_fport = th.th_dport;
136286764Sjlemon		inc.inc_lport = th.th_sport;
136386764Sjlemon		inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
136486764Sjlemon		inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
136586764Sjlemon		inc.inc_isipv6 = 1;
1366133591Sdwmalone		INP_INFO_WLOCK(&tcbinfo);
136786764Sjlemon		syncache_unreach(&inc, &th);
1368133591Sdwmalone		INP_INFO_WUNLOCK(&tcbinfo);
136955679Sshin	} else
1370133192Srwatson		in6_pcbnotify(&tcbinfo, sa, 0, (const struct sockaddr *)sa6_src,
1371125776Sume			      0, cmd, NULL, notify);
137255679Sshin}
137355679Sshin#endif /* INET6 */
137455679Sshin
137580428Speter
137682122Ssilby/*
137782122Ssilby * Following is where TCP initial sequence number generation occurs.
137882122Ssilby *
137982122Ssilby * There are two places where we must use initial sequence numbers:
138082122Ssilby * 1.  In SYN-ACK packets.
138182122Ssilby * 2.  In SYN packets.
138282122Ssilby *
138394390Ssilby * All ISNs for SYN-ACK packets are generated by the syncache.  See
138494390Ssilby * tcp_syncache.c for details.
138582122Ssilby *
138682122Ssilby * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
138782122Ssilby * depends on this property.  In addition, these ISNs should be
138882122Ssilby * unguessable so as to prevent connection hijacking.  To satisfy
138982122Ssilby * the requirements of this situation, the algorithm outlined in
1390133874Srwatson * RFC 1948 is used, with only small modifications.
139182122Ssilby *
139282122Ssilby * Implementation details:
139382122Ssilby *
139482122Ssilby * Time is based off the system timer, and is corrected so that it
139582122Ssilby * increases by one megabyte per second.  This allows for proper
139682122Ssilby * recycling on high speed LANs while still leaving over an hour
139782122Ssilby * before rollover.
139882122Ssilby *
1399128452Ssilby * As reading the *exact* system time is too expensive to be done
1400128452Ssilby * whenever setting up a TCP connection, we increment the time
1401128452Ssilby * offset in two ways.  First, a small random positive increment
1402128452Ssilby * is added to isn_offset for each connection that is set up.
1403128452Ssilby * Second, the function tcp_isn_tick fires once per clock tick
1404128452Ssilby * and increments isn_offset as necessary so that sequence numbers
1405128452Ssilby * are incremented at approximately ISN_BYTES_PER_SECOND.  The
1406128452Ssilby * random positive increments serve only to ensure that the same
1407128452Ssilby * exact sequence number is never sent out twice (as could otherwise
1408128452Ssilby * happen when a port is recycled in less than the system tick
1409128452Ssilby * interval.)
1410128452Ssilby *
141182122Ssilby * net.inet.tcp.isn_reseed_interval controls the number of seconds
141282122Ssilby * between seeding of isn_secret.  This is normally set to zero,
141382122Ssilby * as reseeding should not be necessary.
141482122Ssilby *
1415138018Srwatson * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
1416138018Srwatson * isn_offset_old, and isn_ctx is performed using the TCP pcbinfo lock.  In
1417138018Srwatson * general, this means holding an exclusive (write) lock.
141882122Ssilby */
141979413Ssilby
142082122Ssilby#define ISN_BYTES_PER_SECOND 1048576
1421128452Ssilby#define ISN_STATIC_INCREMENT 4096
1422128452Ssilby#define ISN_RANDOM_INCREMENT (4096 - 1)
142379413Ssilby
1424138018Srwatsonstatic u_char isn_secret[32];
1425138018Srwatsonstatic int isn_last_reseed;
1426138018Srwatsonstatic u_int32_t isn_offset, isn_offset_old;
1427138018Srwatsonstatic MD5_CTX isn_ctx;
142875619Skris
142975619Skristcp_seq
1430157431Srwatsontcp_new_isn(struct tcpcb *tp)
143175619Skris{
143282122Ssilby	u_int32_t md5_buffer[4];
143382122Ssilby	tcp_seq new_isn;
143475619Skris
1435138410Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
1436138018Srwatson
1437157977Srwatson	ISN_LOCK();
143882122Ssilby	/* Seed if this is the first use, reseed if requested. */
143994390Ssilby	if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
144082122Ssilby	     (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
144182122Ssilby		< (u_int)ticks))) {
144282122Ssilby		read_random(&isn_secret, sizeof(isn_secret));
144382122Ssilby		isn_last_reseed = ticks;
144482122Ssilby	}
1445133874Srwatson
144682122Ssilby	/* Compute the md5 hash and return the ISN. */
144782122Ssilby	MD5Init(&isn_ctx);
144882122Ssilby	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
144982122Ssilby	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
145082122Ssilby#ifdef INET6
145182122Ssilby	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
145282122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
145382122Ssilby			  sizeof(struct in6_addr));
145482122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
145582122Ssilby			  sizeof(struct in6_addr));
145682122Ssilby	} else
145782122Ssilby#endif
145882122Ssilby	{
145982122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
146082122Ssilby			  sizeof(struct in_addr));
146182122Ssilby		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
146282122Ssilby			  sizeof(struct in_addr));
146382122Ssilby	}
146482122Ssilby	MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
146582122Ssilby	MD5Final((u_char *) &md5_buffer, &isn_ctx);
146682122Ssilby	new_isn = (tcp_seq) md5_buffer[0];
1467128452Ssilby	isn_offset += ISN_STATIC_INCREMENT +
1468128452Ssilby		(arc4random() & ISN_RANDOM_INCREMENT);
1469128452Ssilby	new_isn += isn_offset;
1470157977Srwatson	ISN_UNLOCK();
1471139222Srwatson	return (new_isn);
147275619Skris}
147375619Skris
14741541Srgrimes/*
1475128452Ssilby * Increment the offset to the next ISN_BYTES_PER_SECOND / hz boundary
1476128452Ssilby * to keep time flowing at a relatively constant rate.  If the random
1477128452Ssilby * increments have already pushed us past the projected offset, do nothing.
1478128452Ssilby */
1479128452Ssilbystatic void
1480157431Srwatsontcp_isn_tick(void *xtp)
1481128452Ssilby{
1482128452Ssilby	u_int32_t projected_offset;
1483133874Srwatson
1484157977Srwatson	ISN_LOCK();
1485141078Srwatson	projected_offset = isn_offset_old + ISN_BYTES_PER_SECOND / 100;
1486128452Ssilby
1487128452Ssilby	if (projected_offset > isn_offset)
1488128452Ssilby		isn_offset = projected_offset;
1489128452Ssilby
1490128452Ssilby	isn_offset_old = isn_offset;
1491141072Srwatson	callout_reset(&isn_callout, hz/100, tcp_isn_tick, NULL);
1492157977Srwatson	ISN_UNLOCK();
1493128452Ssilby}
1494128452Ssilby
1495128452Ssilby/*
149672959Sjlemon * When a specific ICMP unreachable message is received and the
149772959Sjlemon * connection state is SYN-SENT, drop the connection.  This behavior
149872959Sjlemon * is controlled by the icmp_may_rst sysctl.
149970103Sphk */
150098211Shsustruct inpcb *
1501157431Srwatsontcp_drop_syn_sent(struct inpcb *inp, int errno)
150270103Sphk{
1503157432Srwatson	struct tcpcb *tp;
150470103Sphk
1505146864Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1506138019Srwatson	INP_LOCK_ASSERT(inp);
1507157433Srwatson
1508157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1509157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
1510157433Srwatson		return (inp);
1511157433Srwatson
1512157432Srwatson	tp = intotcpcb(inp);
1513157433Srwatson	if (tp->t_state != TCPS_SYN_SENT)
1514157433Srwatson		return (inp);
1515146864Srwatson
1516157433Srwatson	tp = tcp_drop(tp, errno);
1517157433Srwatson	if (tp != NULL)
1518157433Srwatson		return (inp);
1519157433Srwatson	else
1520157433Srwatson		return (NULL);
152172638Sphk}
152272638Sphk
152372638Sphk/*
152410881Swollman * When `need fragmentation' ICMP is received, update our idea of the MSS
152510881Swollman * based on the new value in the route.  Also nudge TCP to send something,
152610881Swollman * since we know the packet we just sent was dropped.
152710930Swollman * This duplicates some code in the tcp_mss() function in tcp_input.c.
152810881Swollman */
152998211Shsustruct inpcb *
1530157431Srwatsontcp_mtudisc(struct inpcb *inp, int errno)
153110881Swollman{
1532157432Srwatson	struct tcpcb *tp;
153310930Swollman	struct socket *so = inp->inp_socket;
1534122922Sandre	u_int maxmtu;
1535122922Sandre	u_int romtu;
153610930Swollman	int mss;
153755679Sshin#ifdef INET6
1538134041Sandre	int isipv6;
153955679Sshin#endif /* INET6 */
154010881Swollman
1541138019Srwatson	INP_LOCK_ASSERT(inp);
1542157433Srwatson	if ((inp->inp_vflag & INP_TIMEWAIT) ||
1543157433Srwatson	    (inp->inp_vflag & INP_DROPPED))
1544157433Srwatson		return (inp);
1545157433Srwatson
1546157432Srwatson	tp = intotcpcb(inp);
1547157433Srwatson	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
1548157433Srwatson
1549134041Sandre#ifdef INET6
1550157433Srwatson	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1551134041Sandre#endif
1552157433Srwatson	maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */
1553157433Srwatson	romtu =
155455679Sshin#ifdef INET6
1555162084Sandre	    isipv6 ? tcp_maxmtu6(&inp->inp_inc, NULL) :
1556122922Sandre#endif /* INET6 */
1557162084Sandre	    tcp_maxmtu(&inp->inp_inc, NULL);
1558157433Srwatson	if (!maxmtu)
1559157433Srwatson		maxmtu = romtu;
1560157433Srwatson	else
1561157433Srwatson		maxmtu = min(maxmtu, romtu);
1562157433Srwatson	if (!maxmtu) {
1563157433Srwatson		tp->t_maxopd = tp->t_maxseg =
156455679Sshin#ifdef INET6
1565157433Srwatson			isipv6 ? tcp_v6mssdflt :
156655679Sshin#endif /* INET6 */
1567157433Srwatson			tcp_mssdflt;
1568157433Srwatson		return (inp);
1569157433Srwatson	}
1570157433Srwatson	mss = maxmtu -
157155679Sshin#ifdef INET6
1572157433Srwatson		(isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
157355679Sshin#endif /* INET6 */
1574157433Srwatson		 sizeof(struct tcpiphdr)
157555679Sshin#ifdef INET6
1576157433Srwatson		 )
157755679Sshin#endif /* INET6 */
1578157433Srwatson		;
157955679Sshin
1580157433Srwatson	/*
1581157433Srwatson	 * XXX - The above conditional probably violates the TCP
1582157433Srwatson	 * spec.  The problem is that, since we don't know the
1583157433Srwatson	 * other end's MSS, we are supposed to use a conservative
1584157433Srwatson	 * default.  But, if we do that, then MTU discovery will
1585157433Srwatson	 * never actually take place, because the conservative
1586157433Srwatson	 * default is much less than the MTUs typically seen
1587157433Srwatson	 * on the Internet today.  For the moment, we'll sweep
1588157433Srwatson	 * this under the carpet.
1589157433Srwatson	 *
1590157433Srwatson	 * The conservative default might not actually be a problem
1591157433Srwatson	 * if the only case this occurs is when sending an initial
1592157433Srwatson	 * SYN with options and data to a host we've never talked
1593157433Srwatson	 * to before.  Then, they will reply with an MSS value which
1594157433Srwatson	 * will get recorded and the new parameters should get
1595157433Srwatson	 * recomputed.  For Further Study.
1596157433Srwatson	 */
1597157433Srwatson	if (tp->t_maxopd <= mss)
1598157433Srwatson		return (inp);
1599157433Srwatson	tp->t_maxopd = mss;
160010930Swollman
1601157433Srwatson	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1602157433Srwatson	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1603157433Srwatson		mss -= TCPOLEN_TSTAMP_APPA;
160410930Swollman#if	(MCLBYTES & (MCLBYTES - 1)) == 0
1605157433Srwatson	if (mss > MCLBYTES)
1606157433Srwatson		mss &= ~(MCLBYTES-1);
160710930Swollman#else
1608157433Srwatson	if (mss > MCLBYTES)
1609157433Srwatson		mss = mss / MCLBYTES * MCLBYTES;
161010881Swollman#endif
1611157433Srwatson	if (so->so_snd.sb_hiwat < mss)
1612157433Srwatson		mss = so->so_snd.sb_hiwat;
161310930Swollman
1614157433Srwatson	tp->t_maxseg = mss;
161510930Swollman
1616157433Srwatson	tcpstat.tcps_mturesent++;
1617157433Srwatson	tp->t_rtttime = 0;
1618157433Srwatson	tp->snd_nxt = tp->snd_una;
1619161645Smohans	tcp_free_sackholes(tp);
1620161645Smohans	tp->snd_recover = tp->snd_max;
1621161645Smohans	if (tp->sack_enable)
1622161645Smohans		EXIT_FASTRECOVERY(tp);
1623157433Srwatson	tcp_output(tp);
1624139222Srwatson	return (inp);
162510881Swollman}
162610881Swollman
162710881Swollman/*
16286283Swollman * Look-up the routing entry to the peer of this inpcb.  If no route
1629108265Shsu * is found and it cannot be allocated, then return NULL.  This routine
16306283Swollman * is called by TCP routines that access the rmx structure and by tcp_mss
16316283Swollman * to get the interface MTU.
16326283Swollman */
1633133874Srwatsonu_long
1634162084Sandretcp_maxmtu(struct in_conninfo *inc, int *flags)
16356283Swollman{
1636122922Sandre	struct route sro;
1637122922Sandre	struct sockaddr_in *dst;
1638122922Sandre	struct ifnet *ifp;
1639122922Sandre	u_long maxmtu = 0;
16406283Swollman
1641122922Sandre	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
1642122922Sandre
1643122996Sandre	bzero(&sro, sizeof(sro));
1644122922Sandre	if (inc->inc_faddr.s_addr != INADDR_ANY) {
1645122922Sandre	        dst = (struct sockaddr_in *)&sro.ro_dst;
1646122922Sandre		dst->sin_family = AF_INET;
1647122922Sandre		dst->sin_len = sizeof(*dst);
1648122922Sandre		dst->sin_addr = inc->inc_faddr;
1649122922Sandre		rtalloc_ign(&sro, RTF_CLONING);
16506283Swollman	}
1651122922Sandre	if (sro.ro_rt != NULL) {
1652122922Sandre		ifp = sro.ro_rt->rt_ifp;
1653122922Sandre		if (sro.ro_rt->rt_rmx.rmx_mtu == 0)
1654122922Sandre			maxmtu = ifp->if_mtu;
1655122922Sandre		else
1656122922Sandre			maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
1657162084Sandre
1658162084Sandre		/* Report additional interface capabilities. */
1659162084Sandre		if (flags != NULL) {
1660162084Sandre			if (ifp->if_capenable & IFCAP_TSO4 &&
1661162084Sandre			    ifp->if_hwassist & CSUM_TSO)
1662162084Sandre				*flags |= CSUM_TSO;
1663162084Sandre		}
1664122922Sandre		RTFREE(sro.ro_rt);
1665122922Sandre	}
1666122922Sandre	return (maxmtu);
16676283Swollman}
16686283Swollman
166955679Sshin#ifdef INET6
1670122922Sandreu_long
1671162084Sandretcp_maxmtu6(struct in_conninfo *inc, int *flags)
167255679Sshin{
1673122922Sandre	struct route_in6 sro6;
1674122922Sandre	struct ifnet *ifp;
1675122922Sandre	u_long maxmtu = 0;
167655679Sshin
1677122922Sandre	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
1678122922Sandre
1679122996Sandre	bzero(&sro6, sizeof(sro6));
1680122922Sandre	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
1681122922Sandre		sro6.ro_dst.sin6_family = AF_INET6;
1682122922Sandre		sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
1683122922Sandre		sro6.ro_dst.sin6_addr = inc->inc6_faddr;
1684122922Sandre		rtalloc_ign((struct route *)&sro6, RTF_CLONING);
168555679Sshin	}
1686122922Sandre	if (sro6.ro_rt != NULL) {
1687122922Sandre		ifp = sro6.ro_rt->rt_ifp;
1688122922Sandre		if (sro6.ro_rt->rt_rmx.rmx_mtu == 0)
1689122922Sandre			maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp);
1690122922Sandre		else
1691122922Sandre			maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu,
1692122922Sandre				     IN6_LINKMTU(sro6.ro_rt->rt_ifp));
1693162084Sandre
1694162084Sandre		/* Report additional interface capabilities. */
1695162084Sandre		if (flags != NULL) {
1696162084Sandre			if (ifp->if_capenable & IFCAP_TSO6 &&
1697162084Sandre			    ifp->if_hwassist & CSUM_TSO)
1698162084Sandre				*flags |= CSUM_TSO;
1699162084Sandre		}
1700122922Sandre		RTFREE(sro6.ro_rt);
1701122922Sandre	}
1702122922Sandre
1703122922Sandre	return (maxmtu);
170455679Sshin}
170555679Sshin#endif /* INET6 */
170655679Sshin
170755679Sshin#ifdef IPSEC
170855679Sshin/* compute ESP/AH header size for TCP, including outer IP header. */
170955679Sshinsize_t
1710157431Srwatsonipsec_hdrsiz_tcp(struct tcpcb *tp)
171155679Sshin{
171255679Sshin	struct inpcb *inp;
171355679Sshin	struct mbuf *m;
171455679Sshin	size_t hdrsiz;
171555679Sshin	struct ip *ip;
171655679Sshin#ifdef INET6
171755679Sshin	struct ip6_hdr *ip6;
1718111145Sjlemon#endif
171955679Sshin	struct tcphdr *th;
172055679Sshin
172178642Ssilby	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1722139222Srwatson		return (0);
1723111119Simp	MGETHDR(m, M_DONTWAIT, MT_DATA);
172455679Sshin	if (!m)
1725139222Srwatson		return (0);
172655679Sshin
172755679Sshin#ifdef INET6
172855679Sshin	if ((inp->inp_vflag & INP_IPV6) != 0) {
172955679Sshin		ip6 = mtod(m, struct ip6_hdr *);
173055679Sshin		th = (struct tcphdr *)(ip6 + 1);
173155679Sshin		m->m_pkthdr.len = m->m_len =
173255679Sshin			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1733111144Sjlemon		tcpip_fillheaders(inp, ip6, th);
173455679Sshin		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
173555679Sshin	} else
173655679Sshin#endif /* INET6 */
1737133874Srwatson	{
1738133874Srwatson		ip = mtod(m, struct ip *);
1739133874Srwatson		th = (struct tcphdr *)(ip + 1);
1740133874Srwatson		m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1741133874Srwatson		tcpip_fillheaders(inp, ip, th);
1742133874Srwatson		hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1743133874Srwatson	}
174455679Sshin
174555679Sshin	m_free(m);
1746139222Srwatson	return (hdrsiz);
174755679Sshin}
174855679Sshin#endif /*IPSEC*/
174955679Sshin
17506283Swollman/*
1751111145Sjlemon * Move a TCP connection into TIME_WAIT state.
1752138410Srwatson *    tcbinfo is locked.
1753111145Sjlemon *    inp is locked, and is unlocked before returning.
1754111145Sjlemon */
1755111145Sjlemonvoid
1756157431Srwatsontcp_twstart(struct tcpcb *tp)
1757111145Sjlemon{
1758111145Sjlemon	struct tcptw *tw;
1759162151Sglebius	struct inpcb *inp = tp->t_inpcb;
1760162111Sru	int acknow;
1761111145Sjlemon	struct socket *so;
1762111145Sjlemon
1763138025Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);	/* tcp_timer_2msl_reset(). */
1764162151Sglebius	INP_LOCK_ASSERT(inp);
1765138020Srwatson
1766162151Sglebius	if (nolocaltimewait && in_localip(inp->inp_faddr)) {
1767162151Sglebius		tp = tcp_close(tp);
1768162151Sglebius		if (tp != NULL)
1769162151Sglebius			INP_UNLOCK(inp);
1770162151Sglebius		return;
1771162151Sglebius	}
1772162151Sglebius
1773112009Sjlemon	tw = uma_zalloc(tcptw_zone, M_NOWAIT);
1774112009Sjlemon	if (tw == NULL) {
1775112009Sjlemon		tw = tcp_timer_2msl_tw(1);
1776112009Sjlemon		if (tw == NULL) {
1777157376Srwatson			tp = tcp_close(tp);
1778157376Srwatson			if (tp != NULL)
1779162151Sglebius				INP_UNLOCK(inp);
1780112009Sjlemon			return;
1781112009Sjlemon		}
1782112009Sjlemon	}
1783111145Sjlemon	tw->tw_inpcb = inp;
1784111145Sjlemon
1785111145Sjlemon	/*
1786111145Sjlemon	 * Recover last window size sent.
1787111145Sjlemon	 */
1788111145Sjlemon	tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale;
1789111145Sjlemon
1790111145Sjlemon	/*
1791111145Sjlemon	 * Set t_recent if timestamps are used on the connection.
1792111145Sjlemon	 */
1793133874Srwatson	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
1794133874Srwatson	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
1795111145Sjlemon		tw->t_recent = tp->ts_recent;
1796111145Sjlemon	else
1797111145Sjlemon		tw->t_recent = 0;
1798111145Sjlemon
1799111145Sjlemon	tw->snd_nxt = tp->snd_nxt;
1800111145Sjlemon	tw->rcv_nxt = tp->rcv_nxt;
1801121850Ssilby	tw->iss     = tp->iss;
1802121884Ssilby	tw->irs     = tp->irs;
1803111145Sjlemon	tw->t_starttime = tp->t_starttime;
1804112009Sjlemon	tw->tw_time = 0;
1805111145Sjlemon
1806111145Sjlemon/* XXX
1807111145Sjlemon * If this code will
1808111145Sjlemon * be used for fin-wait-2 state also, then we may need
1809111145Sjlemon * a ts_recent from the last segment.
1810111145Sjlemon */
1811137139Sandre	acknow = tp->t_flags & TF_ACKNOW;
1812157376Srwatson
1813157376Srwatson	/*
1814157376Srwatson	 * First, discard tcpcb state, which includes stopping its timers and
1815157376Srwatson	 * freeing it.  tcp_discardcb() used to also release the inpcb, but
1816157376Srwatson	 * that work is now done in the caller.
1817160925Srwatson	 *
1818160925Srwatson	 * Note: soisdisconnected() call used to be made in tcp_discardcb(),
1819160925Srwatson	 * and might not be needed here any longer.
1820157376Srwatson	 */
1821111145Sjlemon	tcp_discardcb(tp);
1822111145Sjlemon	so = inp->inp_socket;
1823160925Srwatson	soisdisconnected(so);
1824130387Srwatson	SOCK_LOCK(so);
1825111145Sjlemon	tw->tw_cred = crhold(so->so_cred);
1826111145Sjlemon	tw->tw_so_options = so->so_options;
1827157376Srwatson	SOCK_UNLOCK(so);
1828114794Srwatson	if (acknow)
1829126351Srwatson		tcp_twrespond(tw, TH_ACK);
1830157432Srwatson	inp->inp_ppcb = tw;
1831111145Sjlemon	inp->inp_vflag |= INP_TIMEWAIT;
1832162111Sru	tcp_timer_2msl_reset(tw, 0);
1833157376Srwatson
1834157376Srwatson	/*
1835157376Srwatson	 * If the inpcb owns the sole reference to the socket, then we can
1836157376Srwatson	 * detach and free the socket as it is not needed in time wait.
1837157376Srwatson	 */
1838157376Srwatson	if (inp->inp_vflag & INP_SOCKREF) {
1839157376Srwatson		KASSERT(so->so_state & SS_PROTOREF,
1840157376Srwatson		    ("tcp_twstart: !SS_PROTOREF"));
1841157376Srwatson		inp->inp_vflag &= ~INP_SOCKREF;
1842157376Srwatson		INP_UNLOCK(inp);
1843157376Srwatson		ACCEPT_LOCK();
1844157376Srwatson		SOCK_LOCK(so);
1845157376Srwatson		so->so_state &= ~SS_PROTOREF;
1846157376Srwatson		sofree(so);
1847157376Srwatson	} else
1848157376Srwatson		INP_UNLOCK(inp);
1849111145Sjlemon}
1850111145Sjlemon
1851162064Sglebius#if 0
1852121850Ssilby/*
1853121884Ssilby * The appromixate rate of ISN increase of Microsoft TCP stacks;
1854121884Ssilby * the actual rate is slightly higher due to the addition of
1855121884Ssilby * random positive increments.
1856121884Ssilby *
1857121884Ssilby * Most other new OSes use semi-randomized ISN values, so we
1858121884Ssilby * do not need to worry about them.
1859121884Ssilby */
1860121884Ssilby#define MS_ISN_BYTES_PER_SECOND		250000
1861121884Ssilby
1862121884Ssilby/*
1863121850Ssilby * Determine if the ISN we will generate has advanced beyond the last
1864121850Ssilby * sequence number used by the previous connection.  If so, indicate
1865121850Ssilby * that it is safe to recycle this tw socket by returning 1.
1866121850Ssilby */
1867121850Ssilbyint
1868121850Ssilbytcp_twrecycleable(struct tcptw *tw)
1869121850Ssilby{
1870121884Ssilby	tcp_seq new_iss = tw->iss;
1871121884Ssilby	tcp_seq new_irs = tw->irs;
1872121850Ssilby
1873162064Sglebius	INP_INFO_WLOCK_ASSERT(&tcbinfo);
1874121884Ssilby	new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz);
1875121884Ssilby	new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz);
1876133874Srwatson
1877121884Ssilby	if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt))
1878139222Srwatson		return (1);
1879121850Ssilby	else
1880139222Srwatson		return (0);
1881121850Ssilby}
1882162064Sglebius#endif
1883121850Ssilby
1884157376Srwatsonvoid
1885112009Sjlemontcp_twclose(struct tcptw *tw, int reuse)
1886111145Sjlemon{
1887157376Srwatson	struct socket *so;
1888111145Sjlemon	struct inpcb *inp;
1889111145Sjlemon
1890157376Srwatson	/*
1891157386Srwatson	 * At this point, we are in one of two situations:
1892157376Srwatson	 *
1893160549Srwatson	 * (1) We have no socket, just an inpcb<->twtcp pair.  We can free
1894160549Srwatson	 *     all state.
1895157386Srwatson	 *
1896160549Srwatson	 * (2) We have a socket -- if we own a reference, release it and
1897160549Srwatson	 *     notify the socket layer.
1898157376Srwatson	 */
1899111145Sjlemon	inp = tw->tw_inpcb;
1900157376Srwatson	KASSERT((inp->inp_vflag & INP_TIMEWAIT), ("tcp_twclose: !timewait"));
1901157432Srwatson	KASSERT(intotw(inp) == tw, ("tcp_twclose: inp_ppcb != tw"));
1902138025Srwatson	INP_INFO_WLOCK_ASSERT(&tcbinfo);	/* tcp_timer_2msl_stop(). */
1903138020Srwatson	INP_LOCK_ASSERT(inp);
1904138020Srwatson
1905111145Sjlemon	tw->tw_inpcb = NULL;
1906112009Sjlemon	tcp_timer_2msl_stop(tw);
1907111145Sjlemon	inp->inp_ppcb = NULL;
1908158009Srwatson	in_pcbdrop(inp);
1909157376Srwatson
1910157376Srwatson	so = inp->inp_socket;
1911157386Srwatson	if (so != NULL) {
1912160549Srwatson		/*
1913160549Srwatson		 * If there's a socket, handle two cases: first, we own a
1914160549Srwatson		 * strong reference, which we will now release, or we don't
1915160549Srwatson		 * in which case another reference exists (XXXRW: think
1916160549Srwatson		 * about this more), and we don't need to take action.
1917160549Srwatson		 */
1918157386Srwatson		if (inp->inp_vflag & INP_SOCKREF) {
1919157386Srwatson			inp->inp_vflag &= ~INP_SOCKREF;
1920160549Srwatson			INP_UNLOCK(inp);
1921157386Srwatson			ACCEPT_LOCK();
1922157386Srwatson			SOCK_LOCK(so);
1923157386Srwatson			KASSERT(so->so_state & SS_PROTOREF,
1924157386Srwatson			    ("tcp_twclose: INP_SOCKREF && !SS_PROTOREF"));
1925157386Srwatson			so->so_state &= ~SS_PROTOREF;
1926157386Srwatson			sofree(so);
1927157376Srwatson		} else {
1928157386Srwatson			/*
1929157386Srwatson			 * If we don't own the only reference, the socket and
1930157386Srwatson			 * inpcb need to be left around to be handled by
1931157386Srwatson			 * tcp_usr_detach() later.
1932157386Srwatson			 */
1933157386Srwatson			INP_UNLOCK(inp);
1934157376Srwatson		}
1935157386Srwatson	} else {
1936157376Srwatson#ifdef INET6
1937157376Srwatson		if (inp->inp_vflag & INP_IPV6PROTO)
1938157376Srwatson			in6_pcbfree(inp);
1939157376Srwatson		else
1940157376Srwatson#endif
1941157376Srwatson			in_pcbfree(inp);
1942157386Srwatson	}
1943111145Sjlemon	tcpstat.tcps_closed++;
1944126002Spjd	crfree(tw->tw_cred);
1945126002Spjd	tw->tw_cred = NULL;
1946112009Sjlemon	if (reuse)
1947157376Srwatson		return;
1948112009Sjlemon	uma_zfree(tcptw_zone, tw);
1949111145Sjlemon}
1950111145Sjlemon
1951111145Sjlemonint
1952126351Srwatsontcp_twrespond(struct tcptw *tw, int flags)
1953111145Sjlemon{
1954111145Sjlemon	struct inpcb *inp = tw->tw_inpcb;
1955111145Sjlemon	struct tcphdr *th;
1956111145Sjlemon	struct mbuf *m;
1957111145Sjlemon	struct ip *ip = NULL;
1958111145Sjlemon	u_int8_t *optp;
1959111145Sjlemon	u_int hdrlen, optlen;
1960111145Sjlemon	int error;
1961111145Sjlemon#ifdef INET6
1962111145Sjlemon	struct ip6_hdr *ip6 = NULL;
1963111145Sjlemon	int isipv6 = inp->inp_inc.inc_isipv6;
1964111145Sjlemon#endif
1965111145Sjlemon
1966138020Srwatson	INP_LOCK_ASSERT(inp);
1967138020Srwatson
1968151967Sandre	m = m_gethdr(M_DONTWAIT, MT_DATA);
1969111145Sjlemon	if (m == NULL)
1970111145Sjlemon		return (ENOBUFS);
1971111145Sjlemon	m->m_data += max_linkhdr;
1972111145Sjlemon
1973114794Srwatson#ifdef MAC
1974123607Srwatson	mac_create_mbuf_from_inpcb(inp, m);
1975114794Srwatson#endif
1976114794Srwatson
1977111153Sjlemon#ifdef INET6
1978111145Sjlemon	if (isipv6) {
1979111145Sjlemon		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1980111145Sjlemon		ip6 = mtod(m, struct ip6_hdr *);
1981111145Sjlemon		th = (struct tcphdr *)(ip6 + 1);
1982111145Sjlemon		tcpip_fillheaders(inp, ip6, th);
1983111153Sjlemon	} else
1984111153Sjlemon#endif
1985111153Sjlemon	{
1986111145Sjlemon		hdrlen = sizeof(struct tcpiphdr);
1987111145Sjlemon		ip = mtod(m, struct ip *);
1988111145Sjlemon		th = (struct tcphdr *)(ip + 1);
1989111145Sjlemon		tcpip_fillheaders(inp, ip, th);
1990111145Sjlemon	}
1991111145Sjlemon	optp = (u_int8_t *)(th + 1);
1992133874Srwatson
1993133874Srwatson	/*
1994111145Sjlemon	 * Send a timestamp and echo-reply if both our side and our peer
1995111145Sjlemon	 * have sent timestamps in our SYN's and this is not a RST.
1996133874Srwatson	 */
1997111145Sjlemon	if (tw->t_recent && flags == TH_ACK) {
1998111145Sjlemon		u_int32_t *lp = (u_int32_t *)optp;
1999111145Sjlemon
2000133874Srwatson		/* Form timestamp option as shown in appendix A of RFC 1323. */
2001133874Srwatson		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
2002133874Srwatson		*lp++ = htonl(ticks);
2003133874Srwatson		*lp   = htonl(tw->t_recent);
2004133874Srwatson		optp += TCPOLEN_TSTAMP_APPA;
2005133874Srwatson	}
2006111145Sjlemon
2007111145Sjlemon	optlen = optp - (u_int8_t *)(th + 1);
2008111145Sjlemon
2009111145Sjlemon	m->m_len = hdrlen + optlen;
2010111145Sjlemon	m->m_pkthdr.len = m->m_len;
2011111145Sjlemon
2012111145Sjlemon	KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small"));
2013111145Sjlemon
2014111145Sjlemon	th->th_seq = htonl(tw->snd_nxt);
2015111145Sjlemon	th->th_ack = htonl(tw->rcv_nxt);
2016111145Sjlemon	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
2017111145Sjlemon	th->th_flags = flags;
2018111145Sjlemon	th->th_win = htons(tw->last_win);
2019111145Sjlemon
2020111153Sjlemon#ifdef INET6
2021111145Sjlemon	if (isipv6) {
2022111145Sjlemon		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
2023111145Sjlemon		    sizeof(struct tcphdr) + optlen);
2024122922Sandre		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
2025122922Sandre		error = ip6_output(m, inp->in6p_outputopts, NULL,
2026111145Sjlemon		    (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp);
2027111153Sjlemon	} else
2028111153Sjlemon#endif
2029111153Sjlemon	{
2030111145Sjlemon		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2031133874Srwatson		    htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP));
2032111145Sjlemon		m->m_pkthdr.csum_flags = CSUM_TCP;
2033111145Sjlemon		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2034111145Sjlemon		ip->ip_len = m->m_pkthdr.len;
2035124248Sandre		if (path_mtu_discovery)
2036124248Sandre			ip->ip_off |= IP_DF;
2037122922Sandre		error = ip_output(m, inp->inp_options, NULL,
2038134793Sjmg		    ((tw->tw_so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0),
2039134793Sjmg		    NULL, inp);
2040111145Sjlemon	}
2041111145Sjlemon	if (flags & TH_ACK)
2042111145Sjlemon		tcpstat.tcps_sndacks++;
2043111145Sjlemon	else
2044111145Sjlemon		tcpstat.tcps_sndctrl++;
2045111145Sjlemon	tcpstat.tcps_sndtotal++;
2046111145Sjlemon	return (error);
2047111145Sjlemon}
2048111145Sjlemon
2049111145Sjlemon/*
2050102017Sdillon * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
2051102017Sdillon *
2052102017Sdillon * This code attempts to calculate the bandwidth-delay product as a
2053102017Sdillon * means of determining the optimal window size to maximize bandwidth,
2054102017Sdillon * minimize RTT, and avoid the over-allocation of buffers on interfaces and
2055102017Sdillon * routers.  This code also does a fairly good job keeping RTTs in check
2056102017Sdillon * across slow links like modems.  We implement an algorithm which is very
2057102017Sdillon * similar (but not meant to be) TCP/Vegas.  The code operates on the
2058102017Sdillon * transmitter side of a TCP connection and so only effects the transmit
2059102017Sdillon * side of the connection.
2060102017Sdillon *
2061102017Sdillon * BACKGROUND:  TCP makes no provision for the management of buffer space
2062133874Srwatson * at the end points or at the intermediate routers and switches.  A TCP
2063102017Sdillon * stream, whether using NewReno or not, will eventually buffer as
2064102017Sdillon * many packets as it is able and the only reason this typically works is
2065102017Sdillon * due to the fairly small default buffers made available for a connection
2066102017Sdillon * (typicaly 16K or 32K).  As machines use larger windows and/or window
2067102017Sdillon * scaling it is now fairly easy for even a single TCP connection to blow-out
2068133874Srwatson * all available buffer space not only on the local interface, but on
2069102017Sdillon * intermediate routers and switches as well.  NewReno makes a misguided
2070102017Sdillon * attempt to 'solve' this problem by waiting for an actual failure to occur,
2071102017Sdillon * then backing off, then steadily increasing the window again until another
2072102017Sdillon * failure occurs, ad-infinitum.  This results in terrible oscillation that
2073102017Sdillon * is only made worse as network loads increase and the idea of intentionally
2074102017Sdillon * blowing out network buffers is, frankly, a terrible way to manage network
2075102017Sdillon * resources.
2076102017Sdillon *
2077102017Sdillon * It is far better to limit the transmit window prior to the failure
2078102017Sdillon * condition being achieved.  There are two general ways to do this:  First
2079102017Sdillon * you can 'scan' through different transmit window sizes and locate the
2080102017Sdillon * point where the RTT stops increasing, indicating that you have filled the
2081102017Sdillon * pipe, then scan backwards until you note that RTT stops decreasing, then
2082102017Sdillon * repeat ad-infinitum.  This method works in principle but has severe
2083102017Sdillon * implementation issues due to RTT variances, timer granularity, and
2084102017Sdillon * instability in the algorithm which can lead to many false positives and
2085102017Sdillon * create oscillations as well as interact badly with other TCP streams
2086102017Sdillon * implementing the same algorithm.
2087102017Sdillon *
2088102017Sdillon * The second method is to limit the window to the bandwidth delay product
2089102017Sdillon * of the link.  This is the method we implement.  RTT variances and our
2090133874Srwatson * own manipulation of the congestion window, bwnd, can potentially
2091102017Sdillon * destabilize the algorithm.  For this reason we have to stabilize the
2092102017Sdillon * elements used to calculate the window.  We do this by using the minimum
2093102017Sdillon * observed RTT, the long term average of the observed bandwidth, and
2094102017Sdillon * by adding two segments worth of slop.  It isn't perfect but it is able
2095102017Sdillon * to react to changing conditions and gives us a very stable basis on
2096102017Sdillon * which to extend the algorithm.
2097102017Sdillon */
2098102017Sdillonvoid
2099102017Sdillontcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
2100102017Sdillon{
2101102017Sdillon	u_long bw;
2102102017Sdillon	u_long bwnd;
2103102017Sdillon	int save_ticks;
2104102017Sdillon
2105138410Srwatson	INP_LOCK_ASSERT(tp->t_inpcb);
2106138410Srwatson
2107102017Sdillon	/*
2108102017Sdillon	 * If inflight_enable is disabled in the middle of a tcp connection,
2109102017Sdillon	 * make sure snd_bwnd is effectively disabled.
2110102017Sdillon	 */
2111155767Sandre	if (tcp_inflight_enable == 0 || tp->t_rttlow < tcp_inflight_rttthresh) {
2112102017Sdillon		tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2113102017Sdillon		tp->snd_bandwidth = 0;
2114102017Sdillon		return;
2115102017Sdillon	}
2116102017Sdillon
2117102017Sdillon	/*
2118102017Sdillon	 * Figure out the bandwidth.  Due to the tick granularity this
2119102017Sdillon	 * is a very rough number and it MUST be averaged over a fairly
2120102017Sdillon	 * long period of time.  XXX we need to take into account a link
2121102017Sdillon	 * that is not using all available bandwidth, but for now our
2122102017Sdillon	 * slop will ramp us up if this case occurs and the bandwidth later
2123102017Sdillon	 * increases.
2124102368Sdillon	 *
2125102368Sdillon	 * Note: if ticks rollover 'bw' may wind up negative.  We must
2126102368Sdillon	 * effectively reset t_bw_rtttime for this case.
2127102017Sdillon	 */
2128102017Sdillon	save_ticks = ticks;
2129102017Sdillon	if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1)
2130102017Sdillon		return;
2131102017Sdillon
2132133874Srwatson	bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz /
2133102017Sdillon	    (save_ticks - tp->t_bw_rtttime);
2134102017Sdillon	tp->t_bw_rtttime = save_ticks;
2135102017Sdillon	tp->t_bw_rtseq = ack_seq;
2136102368Sdillon	if (tp->t_bw_rtttime == 0 || (int)bw < 0)
2137102017Sdillon		return;
2138102017Sdillon	bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
2139102017Sdillon
2140102017Sdillon	tp->snd_bandwidth = bw;
2141102017Sdillon
2142102017Sdillon	/*
2143102017Sdillon	 * Calculate the semi-static bandwidth delay product, plus two maximal
2144102017Sdillon	 * segments.  The additional slop puts us squarely in the sweet
2145107881Sdillon	 * spot and also handles the bandwidth run-up case and stabilization.
2146107881Sdillon	 * Without the slop we could be locking ourselves into a lower
2147107881Sdillon	 * bandwidth.
2148102017Sdillon	 *
2149102017Sdillon	 * Situations Handled:
2150102017Sdillon	 *	(1) Prevents over-queueing of packets on LANs, especially on
2151102017Sdillon	 *	    high speed LANs, allowing larger TCP buffers to be
2152133874Srwatson	 *	    specified, and also does a good job preventing
2153102017Sdillon	 *	    over-queueing of packets over choke points like modems
2154102017Sdillon	 *	    (at least for the transmit side).
2155102017Sdillon	 *
2156102017Sdillon	 *	(2) Is able to handle changing network loads (bandwidth
2157102017Sdillon	 *	    drops so bwnd drops, bandwidth increases so bwnd
2158102017Sdillon	 *	    increases).
2159102017Sdillon	 *
2160102017Sdillon	 *	(3) Theoretically should stabilize in the face of multiple
2161102017Sdillon	 *	    connections implementing the same algorithm (this may need
2162102017Sdillon	 *	    a little work).
2163107881Sdillon	 *
2164107881Sdillon	 *	(4) Stability value (defaults to 20 = 2 maximal packets) can
2165107881Sdillon	 *	    be adjusted with a sysctl but typically only needs to be
2166107881Sdillon	 *	    on very slow connections.  A value no smaller then 5
2167107881Sdillon	 *	    should be used, but only reduce this default if you have
2168107881Sdillon	 *	    no other choice.
2169102017Sdillon	 */
2170102017Sdillon#define USERTT	((tp->t_srtt + tp->t_rttbest) / 2)
2171107881Sdillon	bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10;
2172102368Sdillon#undef USERTT
2173102017Sdillon
2174102017Sdillon	if (tcp_inflight_debug > 0) {
2175102017Sdillon		static int ltime;
2176102017Sdillon		if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
2177102017Sdillon			ltime = ticks;
2178102017Sdillon			printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
2179102017Sdillon			    tp,
2180102017Sdillon			    bw,
2181102017Sdillon			    tp->t_rttbest,
2182102017Sdillon			    tp->t_srtt,
2183102017Sdillon			    bwnd
2184102017Sdillon			);
2185102017Sdillon		}
2186102017Sdillon	}
2187102017Sdillon	if ((long)bwnd < tcp_inflight_min)
2188102017Sdillon		bwnd = tcp_inflight_min;
2189102017Sdillon	if (bwnd > tcp_inflight_max)
2190102017Sdillon		bwnd = tcp_inflight_max;
2191102017Sdillon	if ((long)bwnd < tp->t_maxseg * 2)
2192102017Sdillon		bwnd = tp->t_maxseg * 2;
2193102017Sdillon	tp->snd_bwnd = bwnd;
2194102017Sdillon}
2195102017Sdillon
2196125680Sbms#ifdef TCP_SIGNATURE
2197125680Sbms/*
2198125783Sbms * Callback function invoked by m_apply() to digest TCP segment data
2199125783Sbms * contained within an mbuf chain.
2200125783Sbms */
2201125783Sbmsstatic int
2202125783Sbmstcp_signature_apply(void *fstate, void *data, u_int len)
2203125783Sbms{
2204125783Sbms
2205125819Sbms	MD5Update(fstate, (u_char *)data, len);
2206125783Sbms	return (0);
2207125783Sbms}
2208125783Sbms
2209125783Sbms/*
2210125680Sbms * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
2211125680Sbms *
2212125741Sbms * Parameters:
2213125741Sbms * m		pointer to head of mbuf chain
2214125741Sbms * off0		offset to TCP header within the mbuf chain
2215125741Sbms * len		length of TCP segment data, excluding options
2216125741Sbms * optlen	length of TCP segment options
2217125741Sbms * buf		pointer to storage for computed MD5 digest
2218125741Sbms * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
2219125741Sbms *
2220125680Sbms * We do this over ip, tcphdr, segment data, and the key in the SADB.
2221125680Sbms * When called from tcp_input(), we can be sure that th_sum has been
2222125680Sbms * zeroed out and verified already.
2223125680Sbms *
2224125680Sbms * This function is for IPv4 use only. Calling this function with an
2225125680Sbms * IPv6 packet in the mbuf chain will yield undefined results.
2226125680Sbms *
2227125680Sbms * Return 0 if successful, otherwise return -1.
2228125680Sbms *
2229125680Sbms * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
2230125680Sbms * search with the destination IP address, and a 'magic SPI' to be
2231125680Sbms * determined by the application. This is hardcoded elsewhere to 1179
2232125680Sbms * right now. Another branch of this code exists which uses the SPD to
2233125680Sbms * specify per-application flows but it is unstable.
2234125680Sbms */
2235125680Sbmsint
2236125783Sbmstcp_signature_compute(struct mbuf *m, int off0, int len, int optlen,
2237125741Sbms    u_char *buf, u_int direction)
2238125680Sbms{
2239125680Sbms	union sockaddr_union dst;
2240125680Sbms	struct ippseudo ippseudo;
2241125680Sbms	MD5_CTX ctx;
2242125680Sbms	int doff;
2243125680Sbms	struct ip *ip;
2244125680Sbms	struct ipovly *ipovly;
2245125680Sbms	struct secasvar *sav;
2246125680Sbms	struct tcphdr *th;
2247125680Sbms	u_short savecsum;
2248125680Sbms
2249125741Sbms	KASSERT(m != NULL, ("NULL mbuf chain"));
2250125741Sbms	KASSERT(buf != NULL, ("NULL signature pointer"));
2251125741Sbms
2252125741Sbms	/* Extract the destination from the IP header in the mbuf. */
2253125680Sbms	ip = mtod(m, struct ip *);
2254125680Sbms	bzero(&dst, sizeof(union sockaddr_union));
2255125680Sbms	dst.sa.sa_len = sizeof(struct sockaddr_in);
2256125680Sbms	dst.sa.sa_family = AF_INET;
2257125680Sbms	dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
2258125680Sbms	    ip->ip_src : ip->ip_dst;
2259125741Sbms
2260125741Sbms	/* Look up an SADB entry which matches the address of the peer. */
2261125680Sbms	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2262125680Sbms	if (sav == NULL) {
2263125680Sbms		printf("%s: SADB lookup failed for %s\n", __func__,
2264125680Sbms		    inet_ntoa(dst.sin.sin_addr));
2265125680Sbms		return (EINVAL);
2266125680Sbms	}
2267125741Sbms
2268125680Sbms	MD5Init(&ctx);
2269125680Sbms	ipovly = (struct ipovly *)ip;
2270125680Sbms	th = (struct tcphdr *)((u_char *)ip + off0);
2271125680Sbms	doff = off0 + sizeof(struct tcphdr) + optlen;
2272125741Sbms
2273125680Sbms	/*
2274125680Sbms	 * Step 1: Update MD5 hash with IP pseudo-header.
2275125680Sbms	 *
2276125680Sbms	 * XXX The ippseudo header MUST be digested in network byte order,
2277125680Sbms	 * or else we'll fail the regression test. Assume all fields we've
2278125680Sbms	 * been doing arithmetic on have been in host byte order.
2279125680Sbms	 * XXX One cannot depend on ipovly->ih_len here. When called from
2280125680Sbms	 * tcp_output(), the underlying ip_len member has not yet been set.
2281125680Sbms	 */
2282125680Sbms	ippseudo.ippseudo_src = ipovly->ih_src;
2283125680Sbms	ippseudo.ippseudo_dst = ipovly->ih_dst;
2284125680Sbms	ippseudo.ippseudo_pad = 0;
2285125680Sbms	ippseudo.ippseudo_p = IPPROTO_TCP;
2286125680Sbms	ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen);
2287125680Sbms	MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
2288125741Sbms
2289125680Sbms	/*
2290125680Sbms	 * Step 2: Update MD5 hash with TCP header, excluding options.
2291125680Sbms	 * The TCP checksum must be set to zero.
2292125680Sbms	 */
2293125680Sbms	savecsum = th->th_sum;
2294125680Sbms	th->th_sum = 0;
2295125680Sbms	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
2296125680Sbms	th->th_sum = savecsum;
2297125741Sbms
2298125680Sbms	/*
2299125680Sbms	 * Step 3: Update MD5 hash with TCP segment data.
2300125680Sbms	 *         Use m_apply() to avoid an early m_pullup().
2301125680Sbms	 */
2302125680Sbms	if (len > 0)
2303125783Sbms		m_apply(m, doff, len, tcp_signature_apply, &ctx);
2304125741Sbms
2305125680Sbms	/*
2306125680Sbms	 * Step 4: Update MD5 hash with shared secret.
2307125680Sbms	 */
2308125680Sbms	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2309125680Sbms	MD5Final(buf, &ctx);
2310125741Sbms
2311125680Sbms	key_sa_recordxfer(sav, m);
2312125680Sbms	KEY_FREESAV(&sav);
2313125680Sbms	return (0);
2314125680Sbms}
2315125680Sbms#endif /* TCP_SIGNATURE */
2316141886Smaxim
2317141886Smaximstatic int
2318141886Smaximsysctl_drop(SYSCTL_HANDLER_ARGS)
2319141886Smaxim{
2320141886Smaxim	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
2321141886Smaxim	struct sockaddr_storage addrs[2];
2322141886Smaxim	struct inpcb *inp;
2323141886Smaxim	struct tcpcb *tp;
2324150804Smaxim	struct tcptw *tw;
2325141886Smaxim	struct sockaddr_in *fin, *lin;
2326141886Smaxim#ifdef INET6
2327141886Smaxim	struct sockaddr_in6 *fin6, *lin6;
2328141886Smaxim	struct in6_addr f6, l6;
2329141886Smaxim#endif
2330141886Smaxim	int error;
2331141886Smaxim
2332141886Smaxim	inp = NULL;
2333141886Smaxim	fin = lin = NULL;
2334141886Smaxim#ifdef INET6
2335141886Smaxim	fin6 = lin6 = NULL;
2336141886Smaxim#endif
2337141886Smaxim	error = 0;
2338141886Smaxim
2339141886Smaxim	if (req->oldptr != NULL || req->oldlen != 0)
2340141886Smaxim		return (EINVAL);
2341141886Smaxim	if (req->newptr == NULL)
2342141886Smaxim		return (EPERM);
2343141886Smaxim	if (req->newlen < sizeof(addrs))
2344141886Smaxim		return (ENOMEM);
2345141886Smaxim	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
2346141886Smaxim	if (error)
2347141886Smaxim		return (error);
2348141886Smaxim
2349141886Smaxim	switch (addrs[0].ss_family) {
2350141886Smaxim#ifdef INET6
2351141886Smaxim	case AF_INET6:
2352141886Smaxim		fin6 = (struct sockaddr_in6 *)&addrs[0];
2353141886Smaxim		lin6 = (struct sockaddr_in6 *)&addrs[1];
2354141886Smaxim		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
2355141886Smaxim		    lin6->sin6_len != sizeof(struct sockaddr_in6))
2356141886Smaxim			return (EINVAL);
2357141886Smaxim		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
2358141886Smaxim			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
2359141886Smaxim				return (EINVAL);
2360141886Smaxim			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
2361141886Smaxim			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
2362141886Smaxim			fin = (struct sockaddr_in *)&addrs[0];
2363141886Smaxim			lin = (struct sockaddr_in *)&addrs[1];
2364141886Smaxim			break;
2365141886Smaxim		}
2366148385Sume		error = sa6_embedscope(fin6, ip6_use_defzone);
2367141886Smaxim		if (error)
2368148385Sume			return (error);
2369148385Sume		error = sa6_embedscope(lin6, ip6_use_defzone);
2370148616Sume		if (error)
2371148385Sume			return (error);
2372141886Smaxim		break;
2373141886Smaxim#endif
2374141886Smaxim	case AF_INET:
2375141886Smaxim		fin = (struct sockaddr_in *)&addrs[0];
2376141886Smaxim		lin = (struct sockaddr_in *)&addrs[1];
2377141886Smaxim		if (fin->sin_len != sizeof(struct sockaddr_in) ||
2378141886Smaxim		    lin->sin_len != sizeof(struct sockaddr_in))
2379141886Smaxim			return (EINVAL);
2380141886Smaxim		break;
2381141886Smaxim	default:
2382141886Smaxim		return (EINVAL);
2383141886Smaxim	}
2384141886Smaxim	INP_INFO_WLOCK(&tcbinfo);
2385141886Smaxim	switch (addrs[0].ss_family) {
2386141886Smaxim#ifdef INET6
2387141886Smaxim	case AF_INET6:
2388141886Smaxim		inp = in6_pcblookup_hash(&tcbinfo, &f6, fin6->sin6_port,
2389141886Smaxim		    &l6, lin6->sin6_port, 0, NULL);
2390141886Smaxim		break;
2391141886Smaxim#endif
2392141886Smaxim	case AF_INET:
2393141886Smaxim		inp = in_pcblookup_hash(&tcbinfo, fin->sin_addr, fin->sin_port,
2394141886Smaxim		    lin->sin_addr, lin->sin_port, 0, NULL);
2395141886Smaxim		break;
2396141886Smaxim	}
2397141886Smaxim	if (inp != NULL) {
2398141886Smaxim		INP_LOCK(inp);
2399157427Srwatson		if (inp->inp_vflag & INP_TIMEWAIT) {
2400157474Srwatson			/*
2401157474Srwatson			 * XXXRW: There currently exists a state where an
2402157474Srwatson			 * inpcb is present, but its timewait state has been
2403157474Srwatson			 * discarded.  For now, don't allow dropping of this
2404157474Srwatson			 * type of inpcb.
2405157474Srwatson			 */
2406157427Srwatson			tw = intotw(inp);
2407157474Srwatson			if (tw != NULL)
2408157474Srwatson				tcp_twclose(tw, 0);
2409157427Srwatson		} else if (!(inp->inp_vflag & INP_DROPPED) &&
2410157427Srwatson			   !(inp->inp_socket->so_options & SO_ACCEPTCONN)) {
2411157427Srwatson			tp = intotcpcb(inp);
2412157427Srwatson			tcp_drop(tp, ECONNABORTED);
2413157427Srwatson		}
2414157427Srwatson		INP_UNLOCK(inp);
2415141886Smaxim	} else
2416141886Smaxim		error = ESRCH;
2417141886Smaxim	INP_INFO_WUNLOCK(&tcbinfo);
2418141886Smaxim	return (error);
2419141886Smaxim}
2420141886Smaxim
2421141886SmaximSYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
2422141886Smaxim    CTLTYPE_STRUCT|CTLFLAG_WR|CTLFLAG_SKIP, NULL,
2423141886Smaxim    0, sysctl_drop, "", "Drop TCP connection");
2424