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