xref: /freebsd/sys/netinet/tcp_subr.c (revision 6de306ecee3831f48debaad1d0b22418faa48e10)
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
34  * $FreeBSD$
35  */
36 
37 #include "opt_compat.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_tcpdebug.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/callout.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.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 
57 #include <vm/vm_zone.h>
58 
59 #include <net/route.h>
60 #include <net/if.h>
61 
62 #define _IP_VHL
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 #endif
78 #include <netinet/tcp.h>
79 #include <netinet/tcp_fsm.h>
80 #include <netinet/tcp_seq.h>
81 #include <netinet/tcp_timer.h>
82 #include <netinet/tcp_var.h>
83 #ifdef INET6
84 #include <netinet6/tcp6_var.h>
85 #endif
86 #include <netinet/tcpip.h>
87 #ifdef TCPDEBUG
88 #include <netinet/tcp_debug.h>
89 #endif
90 #include <netinet6/ip6protosw.h>
91 
92 #ifdef IPSEC
93 #include <netinet6/ipsec.h>
94 #ifdef INET6
95 #include <netinet6/ipsec6.h>
96 #endif
97 #endif /*IPSEC*/
98 
99 #include <machine/in_cksum.h>
100 
101 int 	tcp_mssdflt = TCP_MSS;
102 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
103     &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
104 
105 #ifdef INET6
106 int	tcp_v6mssdflt = TCP6_MSS;
107 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
108 	CTLFLAG_RW, &tcp_v6mssdflt , 0,
109 	"Default TCP Maximum Segment Size for IPv6");
110 #endif
111 
112 #if 0
113 static int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
114 SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
115     &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time");
116 #endif
117 
118 static int	tcp_do_rfc1323 = 1;
119 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
120     &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
121 
122 static int	tcp_do_rfc1644 = 0;
123 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
124     &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions");
125 
126 static int	tcp_tcbhashsize = 0;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD,
128      &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
129 
130 static int	do_tcpdrain = 1;
131 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
132      "Enable tcp_drain routine for extra help when low on mbufs");
133 
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
135     &tcbinfo.ipi_count, 0, "Number of active PCBs");
136 
137 static int	icmp_may_rst = 1;
138 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
139     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
140 
141 static void	tcp_cleartaocache __P((void));
142 static void	tcp_notify __P((struct inpcb *, int));
143 
144 /*
145  * Target size of TCP PCB hash tables. Must be a power of two.
146  *
147  * Note that this can be overridden by the kernel environment
148  * variable net.inet.tcp.tcbhashsize
149  */
150 #ifndef TCBHASHSIZE
151 #define TCBHASHSIZE	512
152 #endif
153 
154 /*
155  * This is the actual shape of what we allocate using the zone
156  * allocator.  Doing it this way allows us to protect both structures
157  * using the same generation count, and also eliminates the overhead
158  * of allocating tcpcbs separately.  By hiding the structure here,
159  * we avoid changing most of the rest of the code (although it needs
160  * to be changed, eventually, for greater efficiency).
161  */
162 #define	ALIGNMENT	32
163 #define	ALIGNM1		(ALIGNMENT - 1)
164 struct	inp_tp {
165 	union {
166 		struct	inpcb inp;
167 		char	align[(sizeof(struct inpcb) + ALIGNM1) & ~ALIGNM1];
168 	} inp_tp_u;
169 	struct	tcpcb tcb;
170 	struct	callout inp_tp_rexmt, inp_tp_persist, inp_tp_keep, inp_tp_2msl;
171 	struct	callout inp_tp_delack;
172 };
173 #undef ALIGNMENT
174 #undef ALIGNM1
175 
176 /*
177  * Tcp initialization
178  */
179 void
180 tcp_init()
181 {
182 	int hashsize;
183 
184 	tcp_iss = arc4random();	/* wrong, but better than a constant */
185 	tcp_ccgen = 1;
186 	tcp_cleartaocache();
187 
188 	tcp_delacktime = TCPTV_DELACK;
189 	tcp_keepinit = TCPTV_KEEP_INIT;
190 	tcp_keepidle = TCPTV_KEEP_IDLE;
191 	tcp_keepintvl = TCPTV_KEEPINTVL;
192 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
193 	tcp_msl = TCPTV_MSL;
194 
195 	LIST_INIT(&tcb);
196 	tcbinfo.listhead = &tcb;
197 	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", TCBHASHSIZE, hashsize);
198 	if (!powerof2(hashsize)) {
199 		printf("WARNING: TCB hash size not a power of 2\n");
200 		hashsize = 512; /* safe default */
201 	}
202 	tcp_tcbhashsize = hashsize;
203 	tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
204 	tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
205 					&tcbinfo.porthashmask);
206 	tcbinfo.ipi_zone = zinit("tcpcb", sizeof(struct inp_tp), maxsockets,
207 				 ZONE_INTERRUPT, 0);
208 #ifdef INET6
209 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
210 #else /* INET6 */
211 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
212 #endif /* INET6 */
213 	if (max_protohdr < TCP_MINPROTOHDR)
214 		max_protohdr = TCP_MINPROTOHDR;
215 	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
216 		panic("tcp_init");
217 #undef TCP_MINPROTOHDR
218 }
219 
220 /*
221  * Create template to be used to send tcp packets on a connection.
222  * Call after host entry created, allocates an mbuf and fills
223  * in a skeletal tcp/ip header, minimizing the amount of work
224  * necessary when the connection is used.
225  */
226 struct tcptemp *
227 tcp_template(tp)
228 	struct tcpcb *tp;
229 {
230 	register struct inpcb *inp = tp->t_inpcb;
231 	register struct mbuf *m;
232 	register struct tcptemp *n;
233 
234 	if ((n = tp->t_template) == 0) {
235 		m = m_get(M_DONTWAIT, MT_HEADER);
236 		if (m == NULL)
237 			return (0);
238 		m->m_len = sizeof (struct tcptemp);
239 		n = mtod(m, struct tcptemp *);
240 	}
241 #ifdef INET6
242 	if ((inp->inp_vflag & INP_IPV6) != 0) {
243 		register struct ip6_hdr *ip6;
244 
245 		ip6 = (struct ip6_hdr *)n->tt_ipgen;
246 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
247 			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
248 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
249 			(IPV6_VERSION & IPV6_VERSION_MASK);
250 		ip6->ip6_nxt = IPPROTO_TCP;
251 		ip6->ip6_plen = sizeof(struct tcphdr);
252 		ip6->ip6_src = inp->in6p_laddr;
253 		ip6->ip6_dst = inp->in6p_faddr;
254 		n->tt_t.th_sum = 0;
255 	} else
256 #endif
257       {
258 	struct ip *ip = (struct ip *)n->tt_ipgen;
259 
260 	bzero(ip, sizeof(struct ip));		/* XXX overkill? */
261 	ip->ip_vhl = IP_VHL_BORING;
262 	ip->ip_p = IPPROTO_TCP;
263 	ip->ip_src = inp->inp_laddr;
264 	ip->ip_dst = inp->inp_faddr;
265 	n->tt_t.th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
266 	    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
267       }
268 	n->tt_t.th_sport = inp->inp_lport;
269 	n->tt_t.th_dport = inp->inp_fport;
270 	n->tt_t.th_seq = 0;
271 	n->tt_t.th_ack = 0;
272 	n->tt_t.th_x2 = 0;
273 	n->tt_t.th_off = 5;
274 	n->tt_t.th_flags = 0;
275 	n->tt_t.th_win = 0;
276 	n->tt_t.th_urp = 0;
277 	return (n);
278 }
279 
280 /*
281  * Send a single message to the TCP at address specified by
282  * the given TCP/IP header.  If m == 0, then we make a copy
283  * of the tcpiphdr at ti and send directly to the addressed host.
284  * This is used to force keep alive messages out using the TCP
285  * template for a connection tp->t_template.  If flags are given
286  * then we send a message back to the TCP which originated the
287  * segment ti, and discard the mbuf containing it and any other
288  * attached mbufs.
289  *
290  * In any case the ack and sequence number of the transmitted
291  * segment are as specified by the parameters.
292  *
293  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
294  */
295 void
296 tcp_respond(tp, ipgen, th, m, ack, seq, flags)
297 	struct tcpcb *tp;
298 	void *ipgen;
299 	register struct tcphdr *th;
300 	register struct mbuf *m;
301 	tcp_seq ack, seq;
302 	int flags;
303 {
304 	register int tlen;
305 	int win = 0;
306 	struct route *ro = 0;
307 	struct route sro;
308 	struct ip *ip;
309 	struct tcphdr *nth;
310 #ifdef INET6
311 	struct route_in6 *ro6 = 0;
312 	struct route_in6 sro6;
313 	struct ip6_hdr *ip6;
314 	int isipv6;
315 #endif /* INET6 */
316 	int ipflags = 0;
317 
318 #ifdef INET6
319 	isipv6 = IP_VHL_V(((struct ip *)ipgen)->ip_vhl) == 6;
320 	ip6 = ipgen;
321 #endif /* INET6 */
322 	ip = ipgen;
323 
324 	if (tp) {
325 		if (!(flags & TH_RST)) {
326 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
327 			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
328 				win = (long)TCP_MAXWIN << tp->rcv_scale;
329 		}
330 #ifdef INET6
331 		if (isipv6)
332 			ro6 = &tp->t_inpcb->in6p_route;
333 		else
334 #endif /* INET6 */
335 		ro = &tp->t_inpcb->inp_route;
336 	} else {
337 #ifdef INET6
338 		if (isipv6) {
339 			ro6 = &sro6;
340 			bzero(ro6, sizeof *ro6);
341 		} else
342 #endif /* INET6 */
343 	      {
344 		ro = &sro;
345 		bzero(ro, sizeof *ro);
346 	      }
347 	}
348 	if (m == 0) {
349 		m = m_gethdr(M_DONTWAIT, MT_HEADER);
350 		if (m == NULL)
351 			return;
352 #ifdef TCP_COMPAT_42
353 		tlen = 1;
354 #else
355 		tlen = 0;
356 #endif
357 		m->m_data += max_linkhdr;
358 #ifdef INET6
359 		if (isipv6) {
360 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
361 			      sizeof(struct ip6_hdr));
362 			ip6 = mtod(m, struct ip6_hdr *);
363 			nth = (struct tcphdr *)(ip6 + 1);
364 		} else
365 #endif /* INET6 */
366 	      {
367 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
368 		ip = mtod(m, struct ip *);
369 		nth = (struct tcphdr *)(ip + 1);
370 	      }
371 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
372 		flags = TH_ACK;
373 	} else {
374 		m_freem(m->m_next);
375 		m->m_next = 0;
376 		m->m_data = (caddr_t)ipgen;
377 		/* m_len is set later */
378 		tlen = 0;
379 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
380 #ifdef INET6
381 		if (isipv6) {
382 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
383 			nth = (struct tcphdr *)(ip6 + 1);
384 		} else
385 #endif /* INET6 */
386 	      {
387 		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
388 		nth = (struct tcphdr *)(ip + 1);
389 	      }
390 		if (th != nth) {
391 			/*
392 			 * this is usually a case when an extension header
393 			 * exists between the IPv6 header and the
394 			 * TCP header.
395 			 */
396 			nth->th_sport = th->th_sport;
397 			nth->th_dport = th->th_dport;
398 		}
399 		xchg(nth->th_dport, nth->th_sport, n_short);
400 #undef xchg
401 	}
402 #ifdef INET6
403 	if (isipv6) {
404 		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
405 						tlen));
406 		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
407 	} else
408 #endif
409       {
410 	tlen += sizeof (struct tcpiphdr);
411 	ip->ip_len = tlen;
412 	ip->ip_ttl = ip_defttl;
413       }
414 	m->m_len = tlen;
415 	m->m_pkthdr.len = tlen;
416 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
417 	nth->th_seq = htonl(seq);
418 	nth->th_ack = htonl(ack);
419 	nth->th_x2 = 0;
420 	nth->th_off = sizeof (struct tcphdr) >> 2;
421 	nth->th_flags = flags;
422 	if (tp)
423 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
424 	else
425 		nth->th_win = htons((u_short)win);
426 	nth->th_urp = 0;
427 #ifdef INET6
428 	if (isipv6) {
429 		nth->th_sum = 0;
430 		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
431 					sizeof(struct ip6_hdr),
432 					tlen - sizeof(struct ip6_hdr));
433 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL,
434 					       ro6 && ro6->ro_rt ?
435 					       ro6->ro_rt->rt_ifp :
436 					       NULL);
437 	} else
438 #endif /* INET6 */
439       {
440         nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
441 	    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
442         m->m_pkthdr.csum_flags = CSUM_TCP;
443         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
444       }
445 #ifdef TCPDEBUG
446 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
447 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
448 #endif
449 #ifdef IPSEC
450 	ipsec_setsocket(m, tp ? tp->t_inpcb->inp_socket : NULL);
451 #endif
452 #ifdef INET6
453 	if (isipv6) {
454 		(void)ip6_output(m, NULL, ro6, ipflags, NULL, NULL);
455 		if (ro6 == &sro6 && ro6->ro_rt) {
456 			RTFREE(ro6->ro_rt);
457 			ro6->ro_rt = NULL;
458 		}
459 	} else
460 #endif /* INET6 */
461       {
462 	(void) ip_output(m, NULL, ro, ipflags, NULL);
463 	if (ro == &sro && ro->ro_rt) {
464 		RTFREE(ro->ro_rt);
465 		ro->ro_rt = NULL;
466 	}
467       }
468 }
469 
470 /*
471  * Create a new TCP control block, making an
472  * empty reassembly queue and hooking it to the argument
473  * protocol control block.  The `inp' parameter must have
474  * come from the zone allocator set up in tcp_init().
475  */
476 struct tcpcb *
477 tcp_newtcpcb(inp)
478 	struct inpcb *inp;
479 {
480 	struct inp_tp *it;
481 	register struct tcpcb *tp;
482 #ifdef INET6
483 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
484 #endif /* INET6 */
485 
486 	it = (struct inp_tp *)inp;
487 	tp = &it->tcb;
488 	bzero((char *) tp, sizeof(struct tcpcb));
489 	LIST_INIT(&tp->t_segq);
490 	tp->t_maxseg = tp->t_maxopd =
491 #ifdef INET6
492 		isipv6 ? tcp_v6mssdflt :
493 #endif /* INET6 */
494 		tcp_mssdflt;
495 
496 	/* Set up our timeouts. */
497 	callout_init(tp->tt_rexmt = &it->inp_tp_rexmt, 0);
498 	callout_init(tp->tt_persist = &it->inp_tp_persist, 0);
499 	callout_init(tp->tt_keep = &it->inp_tp_keep, 0);
500 	callout_init(tp->tt_2msl = &it->inp_tp_2msl, 0);
501 	callout_init(tp->tt_delack = &it->inp_tp_delack, 0);
502 
503 	if (tcp_do_rfc1323)
504 		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
505 	if (tcp_do_rfc1644)
506 		tp->t_flags |= TF_REQ_CC;
507 	tp->t_inpcb = inp;	/* XXX */
508 	/*
509 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
510 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
511 	 * reasonable initial retransmit time.
512 	 */
513 	tp->t_srtt = TCPTV_SRTTBASE;
514 	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
515 	tp->t_rttmin = TCPTV_MIN;
516 	tp->t_rxtcur = TCPTV_RTOBASE;
517 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
518 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
519 	tp->t_rcvtime = ticks;
520         /*
521 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
522 	 * because the socket may be bound to an IPv6 wildcard address,
523 	 * which may match an IPv4-mapped IPv6 address.
524 	 */
525 	inp->inp_ip_ttl = ip_defttl;
526 	inp->inp_ppcb = (caddr_t)tp;
527 	return (tp);		/* XXX */
528 }
529 
530 /*
531  * Drop a TCP connection, reporting
532  * the specified error.  If connection is synchronized,
533  * then send a RST to peer.
534  */
535 struct tcpcb *
536 tcp_drop(tp, errno)
537 	register struct tcpcb *tp;
538 	int errno;
539 {
540 	struct socket *so = tp->t_inpcb->inp_socket;
541 
542 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
543 		tp->t_state = TCPS_CLOSED;
544 		(void) tcp_output(tp);
545 		tcpstat.tcps_drops++;
546 	} else
547 		tcpstat.tcps_conndrops++;
548 	if (errno == ETIMEDOUT && tp->t_softerror)
549 		errno = tp->t_softerror;
550 	so->so_error = errno;
551 	return (tcp_close(tp));
552 }
553 
554 /*
555  * Close a TCP control block:
556  *	discard all space held by the tcp
557  *	discard internet protocol block
558  *	wake up any sleepers
559  */
560 struct tcpcb *
561 tcp_close(tp)
562 	register struct tcpcb *tp;
563 {
564 	register struct tseg_qent *q;
565 	struct inpcb *inp = tp->t_inpcb;
566 	struct socket *so = inp->inp_socket;
567 #ifdef INET6
568 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
569 #endif /* INET6 */
570 	register struct rtentry *rt;
571 	int dosavessthresh;
572 
573 	/*
574 	 * Make sure that all of our timers are stopped before we
575 	 * delete the PCB.
576 	 */
577 	callout_stop(tp->tt_rexmt);
578 	callout_stop(tp->tt_persist);
579 	callout_stop(tp->tt_keep);
580 	callout_stop(tp->tt_2msl);
581 	callout_stop(tp->tt_delack);
582 
583 	/*
584 	 * If we got enough samples through the srtt filter,
585 	 * save the rtt and rttvar in the routing entry.
586 	 * 'Enough' is arbitrarily defined as the 16 samples.
587 	 * 16 samples is enough for the srtt filter to converge
588 	 * to within 5% of the correct value; fewer samples and
589 	 * we could save a very bogus rtt.
590 	 *
591 	 * Don't update the default route's characteristics and don't
592 	 * update anything that the user "locked".
593 	 */
594 	if (tp->t_rttupdated >= 16) {
595 		register u_long i = 0;
596 #ifdef INET6
597 		if (isipv6) {
598 			struct sockaddr_in6 *sin6;
599 
600 			if ((rt = inp->in6p_route.ro_rt) == NULL)
601 				goto no_valid_rt;
602 			sin6 = (struct sockaddr_in6 *)rt_key(rt);
603 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
604 				goto no_valid_rt;
605 		}
606 		else
607 #endif /* INET6 */
608 		if ((rt = inp->inp_route.ro_rt) == NULL ||
609 		    ((struct sockaddr_in *)rt_key(rt))->sin_addr.s_addr
610 		    == INADDR_ANY)
611 			goto no_valid_rt;
612 
613 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
614 			i = tp->t_srtt *
615 			    (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
616 			if (rt->rt_rmx.rmx_rtt && i)
617 				/*
618 				 * filter this update to half the old & half
619 				 * the new values, converting scale.
620 				 * See route.h and tcp_var.h for a
621 				 * description of the scaling constants.
622 				 */
623 				rt->rt_rmx.rmx_rtt =
624 				    (rt->rt_rmx.rmx_rtt + i) / 2;
625 			else
626 				rt->rt_rmx.rmx_rtt = i;
627 			tcpstat.tcps_cachedrtt++;
628 		}
629 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
630 			i = tp->t_rttvar *
631 			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
632 			if (rt->rt_rmx.rmx_rttvar && i)
633 				rt->rt_rmx.rmx_rttvar =
634 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
635 			else
636 				rt->rt_rmx.rmx_rttvar = i;
637 			tcpstat.tcps_cachedrttvar++;
638 		}
639 		/*
640 		 * The old comment here said:
641 		 * update the pipelimit (ssthresh) if it has been updated
642 		 * already or if a pipesize was specified & the threshhold
643 		 * got below half the pipesize.  I.e., wait for bad news
644 		 * before we start updating, then update on both good
645 		 * and bad news.
646 		 *
647 		 * But we want to save the ssthresh even if no pipesize is
648 		 * specified explicitly in the route, because such
649 		 * connections still have an implicit pipesize specified
650 		 * by the global tcp_sendspace.  In the absence of a reliable
651 		 * way to calculate the pipesize, it will have to do.
652 		 */
653 		i = tp->snd_ssthresh;
654 		if (rt->rt_rmx.rmx_sendpipe != 0)
655 			dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe / 2);
656 		else
657 			dosavessthresh = (i < so->so_snd.sb_hiwat / 2);
658 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
659 		     i != 0 && rt->rt_rmx.rmx_ssthresh != 0)
660 		    || dosavessthresh) {
661 			/*
662 			 * convert the limit from user data bytes to
663 			 * packets then to packet data bytes.
664 			 */
665 			i = (i + tp->t_maxseg / 2) / tp->t_maxseg;
666 			if (i < 2)
667 				i = 2;
668 			i *= (u_long)(tp->t_maxseg +
669 #ifdef INET6
670 				      (isipv6 ? sizeof (struct ip6_hdr) +
671 					       sizeof (struct tcphdr) :
672 #endif
673 				       sizeof (struct tcpiphdr)
674 #ifdef INET6
675 				       )
676 #endif
677 				      );
678 			if (rt->rt_rmx.rmx_ssthresh)
679 				rt->rt_rmx.rmx_ssthresh =
680 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
681 			else
682 				rt->rt_rmx.rmx_ssthresh = i;
683 			tcpstat.tcps_cachedssthresh++;
684 		}
685 	}
686 	rt = inp->inp_route.ro_rt;
687 	if (rt) {
688 		/*
689 		 * mark route for deletion if no information is
690 		 * cached.
691 		 */
692 		if ((tp->t_flags & TF_LQ_OVERFLOW) &&
693 		    ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0)){
694 			if (rt->rt_rmx.rmx_rtt == 0)
695 				rt->rt_flags |= RTF_DELCLONE;
696 		}
697 	}
698     no_valid_rt:
699 	/* free the reassembly queue, if any */
700 	while((q = LIST_FIRST(&tp->t_segq)) != NULL) {
701 		LIST_REMOVE(q, tqe_q);
702 		m_freem(q->tqe_m);
703 		FREE(q, M_TSEGQ);
704 	}
705 	if (tp->t_template)
706 		(void) m_free(dtom(tp->t_template));
707 	inp->inp_ppcb = NULL;
708 	soisdisconnected(so);
709 #ifdef INET6
710 	if (INP_CHECK_SOCKAF(so, AF_INET6))
711 		in6_pcbdetach(inp);
712 	else
713 #endif /* INET6 */
714 	in_pcbdetach(inp);
715 	tcpstat.tcps_closed++;
716 	return ((struct tcpcb *)0);
717 }
718 
719 void
720 tcp_drain()
721 {
722 	if (do_tcpdrain)
723 	{
724 		struct inpcb *inpb;
725 		struct tcpcb *tcpb;
726 		struct tseg_qent *te;
727 
728 	/*
729 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
730 	 * if there is one...
731 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
732 	 *      reassembly queue should be flushed, but in a situation
733 	 * 	where we're really low on mbufs, this is potentially
734 	 *  	usefull.
735 	 */
736 		for (inpb = LIST_FIRST(tcbinfo.listhead); inpb;
737 	    		inpb = LIST_NEXT(inpb, inp_list)) {
738 				if ((tcpb = intotcpcb(inpb))) {
739 					while ((te = LIST_FIRST(&tcpb->t_segq))
740 					       != NULL) {
741 					LIST_REMOVE(te, tqe_q);
742 					m_freem(te->tqe_m);
743 					FREE(te, M_TSEGQ);
744 				}
745 			}
746 		}
747 
748 	}
749 }
750 
751 /*
752  * Notify a tcp user of an asynchronous error;
753  * store error as soft error, but wake up user
754  * (for now, won't do anything until can select for soft error).
755  *
756  * Do not wake up user since there currently is no mechanism for
757  * reporting soft errors (yet - a kqueue filter may be added).
758  */
759 static void
760 tcp_notify(inp, error)
761 	struct inpcb *inp;
762 	int error;
763 {
764 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
765 
766 	/*
767 	 * Ignore some errors if we are hooked up.
768 	 * If connection hasn't completed, has retransmitted several times,
769 	 * and receives a second error, give up now.  This is better
770 	 * than waiting a long time to establish a connection that
771 	 * can never complete.
772 	 */
773 	if (tp->t_state == TCPS_ESTABLISHED &&
774 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
775 	      error == EHOSTDOWN)) {
776 		return;
777 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
778 	    tp->t_softerror)
779 		tcp_drop(tp, error);
780 	else
781 		tp->t_softerror = error;
782 #if 0
783 	wakeup((caddr_t) &so->so_timeo);
784 	sorwakeup(so);
785 	sowwakeup(so);
786 #endif
787 }
788 
789 static int
790 tcp_pcblist(SYSCTL_HANDLER_ARGS)
791 {
792 	int error, i, n, s;
793 	struct inpcb *inp, **inp_list;
794 	inp_gen_t gencnt;
795 	struct xinpgen xig;
796 
797 	/*
798 	 * The process of preparing the TCB list is too time-consuming and
799 	 * resource-intensive to repeat twice on every request.
800 	 */
801 	if (req->oldptr == 0) {
802 		n = tcbinfo.ipi_count;
803 		req->oldidx = 2 * (sizeof xig)
804 			+ (n + n/8) * sizeof(struct xtcpcb);
805 		return 0;
806 	}
807 
808 	if (req->newptr != 0)
809 		return EPERM;
810 
811 	/*
812 	 * OK, now we're committed to doing something.
813 	 */
814 	s = splnet();
815 	gencnt = tcbinfo.ipi_gencnt;
816 	n = tcbinfo.ipi_count;
817 	splx(s);
818 
819 	xig.xig_len = sizeof xig;
820 	xig.xig_count = n;
821 	xig.xig_gen = gencnt;
822 	xig.xig_sogen = so_gencnt;
823 	error = SYSCTL_OUT(req, &xig, sizeof xig);
824 	if (error)
825 		return error;
826 
827 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
828 	if (inp_list == 0)
829 		return ENOMEM;
830 
831 	s = splnet();
832 	for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp && i < n;
833 	     inp = LIST_NEXT(inp, inp_list)) {
834 		if (inp->inp_gencnt <= gencnt && !prison_xinpcb(req->p, inp))
835 			inp_list[i++] = inp;
836 	}
837 	splx(s);
838 	n = i;
839 
840 	error = 0;
841 	for (i = 0; i < n; i++) {
842 		inp = inp_list[i];
843 		if (inp->inp_gencnt <= gencnt) {
844 			struct xtcpcb xt;
845 			caddr_t inp_ppcb;
846 			xt.xt_len = sizeof xt;
847 			/* XXX should avoid extra copy */
848 			bcopy(inp, &xt.xt_inp, sizeof *inp);
849 			inp_ppcb = inp->inp_ppcb;
850 			if (inp_ppcb != NULL)
851 				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
852 			else
853 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
854 			if (inp->inp_socket)
855 				sotoxsocket(inp->inp_socket, &xt.xt_socket);
856 			error = SYSCTL_OUT(req, &xt, sizeof xt);
857 		}
858 	}
859 	if (!error) {
860 		/*
861 		 * Give the user an updated idea of our state.
862 		 * If the generation differs from what we told
863 		 * her before, she knows that something happened
864 		 * while we were processing this request, and it
865 		 * might be necessary to retry.
866 		 */
867 		s = splnet();
868 		xig.xig_gen = tcbinfo.ipi_gencnt;
869 		xig.xig_sogen = so_gencnt;
870 		xig.xig_count = tcbinfo.ipi_count;
871 		splx(s);
872 		error = SYSCTL_OUT(req, &xig, sizeof xig);
873 	}
874 	free(inp_list, M_TEMP);
875 	return error;
876 }
877 
878 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
879 	    tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
880 
881 static int
882 tcp_getcred(SYSCTL_HANDLER_ARGS)
883 {
884 	struct xucred xuc;
885 	struct sockaddr_in addrs[2];
886 	struct inpcb *inp;
887 	int error, s;
888 
889 	error = suser(req->p);
890 	if (error)
891 		return (error);
892 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
893 	if (error)
894 		return (error);
895 	s = splnet();
896 	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
897 	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
898 	if (inp == NULL || inp->inp_socket == NULL) {
899 		error = ENOENT;
900 		goto out;
901 	}
902 	bzero(&xuc, sizeof(xuc));
903 	xuc.cr_uid = inp->inp_socket->so_cred->cr_uid;
904 	xuc.cr_ngroups = inp->inp_socket->so_cred->cr_ngroups;
905 	bcopy(inp->inp_socket->so_cred->cr_groups, xuc.cr_groups,
906 	    sizeof(xuc.cr_groups));
907 	error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
908 out:
909 	splx(s);
910 	return (error);
911 }
912 
913 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
914     0, 0, tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
915 
916 #ifdef INET6
917 static int
918 tcp6_getcred(SYSCTL_HANDLER_ARGS)
919 {
920 	struct xucred xuc;
921 	struct sockaddr_in6 addrs[2];
922 	struct inpcb *inp;
923 	int error, s, mapped = 0;
924 
925 	error = suser(req->p);
926 	if (error)
927 		return (error);
928 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
929 	if (error)
930 		return (error);
931 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
932 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
933 			mapped = 1;
934 		else
935 			return (EINVAL);
936 	}
937 	s = splnet();
938 	if (mapped == 1)
939 		inp = in_pcblookup_hash(&tcbinfo,
940 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
941 			addrs[1].sin6_port,
942 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
943 			addrs[0].sin6_port,
944 			0, NULL);
945 	else
946 		inp = in6_pcblookup_hash(&tcbinfo, &addrs[1].sin6_addr,
947 				 addrs[1].sin6_port,
948 				 &addrs[0].sin6_addr, addrs[0].sin6_port,
949 				 0, NULL);
950 	if (inp == NULL || inp->inp_socket == NULL) {
951 		error = ENOENT;
952 		goto out;
953 	}
954 	bzero(&xuc, sizeof(xuc));
955 	xuc.cr_uid = inp->inp_socket->so_cred->cr_uid;
956 	xuc.cr_ngroups = inp->inp_socket->so_cred->cr_ngroups;
957 	bcopy(inp->inp_socket->so_cred->cr_groups, xuc.cr_groups,
958 	    sizeof(xuc.cr_groups));
959 	error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
960 out:
961 	splx(s);
962 	return (error);
963 }
964 
965 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
966 	    0, 0,
967 	    tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
968 #endif
969 
970 
971 void
972 tcp_ctlinput(cmd, sa, vip)
973 	int cmd;
974 	struct sockaddr *sa;
975 	void *vip;
976 {
977 	struct ip *ip = vip;
978 	struct tcphdr *th;
979 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
980 	tcp_seq tcp_sequence = 0;
981 	int tcp_seq_check = 0;
982 
983 	if (cmd == PRC_QUENCH)
984 		notify = tcp_quench;
985 	else if (icmp_may_rst && cmd == PRC_UNREACH_ADMIN_PROHIB && ip) {
986 		tcp_seq_check = 1;
987 		notify = tcp_drop_syn_sent;
988 	} else if (cmd == PRC_MSGSIZE)
989 		notify = tcp_mtudisc;
990 	else if (PRC_IS_REDIRECT(cmd)) {
991 		/*
992 		 * Redirects go to all references to the destination,
993 		 * and use in_rtchange to invalidate the route cache.
994 		 */
995 		ip = 0;
996 		notify = in_rtchange;
997 	} else if (cmd == PRC_HOSTDEAD)
998 		/*
999 		 * Dead host indications: notify all references to the
1000 		 * destination.
1001 		 */
1002 		ip = 0;
1003 	else if ((unsigned)cmd > PRC_NCMDS || inetctlerrmap[cmd] == 0)
1004 		return;
1005 	if (ip) {
1006 		th = (struct tcphdr *)((caddr_t)ip
1007 				       + (IP_VHL_HL(ip->ip_vhl) << 2));
1008 		if (tcp_seq_check == 1)
1009 			tcp_sequence = ntohl(th->th_seq);
1010 		in_pcbnotify(&tcb, sa, th->th_dport, ip->ip_src, th->th_sport,
1011 			cmd, notify, tcp_sequence, tcp_seq_check);
1012 	} else
1013 		in_pcbnotifyall(&tcb, sa, cmd, notify);
1014 }
1015 
1016 #ifdef INET6
1017 void
1018 tcp6_ctlinput(cmd, sa, d)
1019 	int cmd;
1020 	struct sockaddr *sa;
1021 	void *d;
1022 {
1023 	register struct tcphdr *thp;
1024 	struct tcphdr th;
1025 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1026 	struct sockaddr_in6 sa6;
1027 	struct ip6_hdr *ip6;
1028 	struct mbuf *m;
1029 	int off;
1030 
1031 	if (sa->sa_family != AF_INET6 ||
1032 	    sa->sa_len != sizeof(struct sockaddr_in6))
1033 		return;
1034 
1035 	if (cmd == PRC_QUENCH)
1036 		notify = tcp_quench;
1037 	else if (cmd == PRC_MSGSIZE)
1038 		notify = tcp_mtudisc;
1039 	else if (!PRC_IS_REDIRECT(cmd) &&
1040 		 ((unsigned)cmd > PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
1041 		return;
1042 
1043 	/* if the parameter is from icmp6, decode it. */
1044 	if (d != NULL) {
1045 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1046 		m = ip6cp->ip6c_m;
1047 		ip6 = ip6cp->ip6c_ip6;
1048 		off = ip6cp->ip6c_off;
1049 	} else {
1050 		m = NULL;
1051 		ip6 = NULL;
1052 		off = 0;	/* fool gcc */
1053 	}
1054 
1055 	/*
1056 	 * Translate addresses into internal form.
1057 	 * Sa check if it is AF_INET6 is done at the top of this funciton.
1058 	 */
1059 	sa6 = *(struct sockaddr_in6 *)sa;
1060 	if (IN6_IS_ADDR_LINKLOCAL(&sa6.sin6_addr) != 0 && m != NULL &&
1061 	    m->m_pkthdr.rcvif != NULL)
1062 		sa6.sin6_addr.s6_addr16[1] = htons(m->m_pkthdr.rcvif->if_index);
1063 
1064 	if (ip6) {
1065 		/*
1066 		 * XXX: We assume that when IPV6 is non NULL,
1067 		 * M and OFF are valid.
1068 		 */
1069 		struct in6_addr s;
1070 
1071 		/* translate addresses into internal form */
1072 		memcpy(&s, &ip6->ip6_src, sizeof(s));
1073 		if (IN6_IS_ADDR_LINKLOCAL(&s) != 0 && m != NULL &&
1074 		    m->m_pkthdr.rcvif != NULL)
1075 			s.s6_addr16[1] = htons(m->m_pkthdr.rcvif->if_index);
1076 
1077 		/* check if we can safely examine src and dst ports */
1078 		if (m->m_pkthdr.len < off + sizeof(th))
1079 			return;
1080 
1081 		if (m->m_len < off + sizeof(th)) {
1082 			/*
1083 			 * this should be rare case
1084 			 * because now MINCLSIZE is "(MHLEN + 1)",
1085 			 * so we compromise on this copy...
1086 			 */
1087 			m_copydata(m, off, sizeof(th), (caddr_t)&th);
1088 			thp = &th;
1089 		} else
1090 			thp = (struct tcphdr *)(mtod(m, caddr_t) + off);
1091 		in6_pcbnotify(&tcb, (struct sockaddr *)&sa6, thp->th_dport,
1092 			      &s, thp->th_sport, cmd, notify);
1093 	} else
1094 		in6_pcbnotify(&tcb, (struct sockaddr *)&sa6, 0, &zeroin6_addr,
1095 			      0, cmd, notify);
1096 }
1097 #endif /* INET6 */
1098 
1099 /*
1100  * Check if the supplied TCP sequence number is a sequence number
1101  * for a sent but unacknowledged packet on the given TCP session.
1102  */
1103 int
1104 tcp_seq_vs_sess(inp, tcp_sequence)
1105 	struct inpcb *inp;
1106 	tcp_seq tcp_sequence;
1107 {
1108 	struct tcpcb *tp = intotcpcb(inp);
1109 	/*
1110 	 * If the sequence number is less than that of the last
1111 	 * unacknowledged packet, or greater than that of the
1112 	 * last sent, the given sequence number is not that
1113 	 * of a sent but unacknowledged packet for this session.
1114 	 */
1115 	if (SEQ_LT(tcp_sequence, tp->snd_una) ||
1116 			SEQ_GT(tcp_sequence, tp->snd_max)) {
1117 		return(0);
1118 	} else {
1119 		return(1);
1120 	}
1121 }
1122 
1123 /*
1124  * When a source quench is received, close congestion window
1125  * to one segment.  We will gradually open it again as we proceed.
1126  */
1127 void
1128 tcp_quench(inp, errno)
1129 	struct inpcb *inp;
1130 	int errno;
1131 {
1132 	struct tcpcb *tp = intotcpcb(inp);
1133 
1134 	if (tp)
1135 		tp->snd_cwnd = tp->t_maxseg;
1136 }
1137 
1138 /*
1139  * When a specific ICMP unreachable message is received and the
1140  * connection state is SYN-SENT, drop the connection.  This behavior
1141  * is controlled by the icmp_may_rst sysctl.
1142  */
1143 void
1144 tcp_drop_syn_sent(inp, errno)
1145 	struct inpcb *inp;
1146 	int errno;
1147 {
1148 	struct tcpcb *tp = intotcpcb(inp);
1149 
1150 	if (tp && tp->t_state == TCPS_SYN_SENT)
1151 		tcp_drop(tp, errno);
1152 }
1153 
1154 /*
1155  * When `need fragmentation' ICMP is received, update our idea of the MSS
1156  * based on the new value in the route.  Also nudge TCP to send something,
1157  * since we know the packet we just sent was dropped.
1158  * This duplicates some code in the tcp_mss() function in tcp_input.c.
1159  */
1160 void
1161 tcp_mtudisc(inp, errno)
1162 	struct inpcb *inp;
1163 	int errno;
1164 {
1165 	struct tcpcb *tp = intotcpcb(inp);
1166 	struct rtentry *rt;
1167 	struct rmxp_tao *taop;
1168 	struct socket *so = inp->inp_socket;
1169 	int offered;
1170 	int mss;
1171 #ifdef INET6
1172 	int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1173 #endif /* INET6 */
1174 
1175 	if (tp) {
1176 #ifdef INET6
1177 		if (isipv6)
1178 			rt = tcp_rtlookup6(inp);
1179 		else
1180 #endif /* INET6 */
1181 		rt = tcp_rtlookup(inp);
1182 		if (!rt || !rt->rt_rmx.rmx_mtu) {
1183 			tp->t_maxopd = tp->t_maxseg =
1184 #ifdef INET6
1185 				isipv6 ? tcp_v6mssdflt :
1186 #endif /* INET6 */
1187 				tcp_mssdflt;
1188 			return;
1189 		}
1190 		taop = rmx_taop(rt->rt_rmx);
1191 		offered = taop->tao_mssopt;
1192 		mss = rt->rt_rmx.rmx_mtu -
1193 #ifdef INET6
1194 			(isipv6 ?
1195 			 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1196 #endif /* INET6 */
1197 			 sizeof(struct tcpiphdr)
1198 #ifdef INET6
1199 			 )
1200 #endif /* INET6 */
1201 			;
1202 
1203 		if (offered)
1204 			mss = min(mss, offered);
1205 		/*
1206 		 * XXX - The above conditional probably violates the TCP
1207 		 * spec.  The problem is that, since we don't know the
1208 		 * other end's MSS, we are supposed to use a conservative
1209 		 * default.  But, if we do that, then MTU discovery will
1210 		 * never actually take place, because the conservative
1211 		 * default is much less than the MTUs typically seen
1212 		 * on the Internet today.  For the moment, we'll sweep
1213 		 * this under the carpet.
1214 		 *
1215 		 * The conservative default might not actually be a problem
1216 		 * if the only case this occurs is when sending an initial
1217 		 * SYN with options and data to a host we've never talked
1218 		 * to before.  Then, they will reply with an MSS value which
1219 		 * will get recorded and the new parameters should get
1220 		 * recomputed.  For Further Study.
1221 		 */
1222 		if (tp->t_maxopd <= mss)
1223 			return;
1224 		tp->t_maxopd = mss;
1225 
1226 		if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1227 		    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1228 			mss -= TCPOLEN_TSTAMP_APPA;
1229 		if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
1230 		    (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC)
1231 			mss -= TCPOLEN_CC_APPA;
1232 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1233 		if (mss > MCLBYTES)
1234 			mss &= ~(MCLBYTES-1);
1235 #else
1236 		if (mss > MCLBYTES)
1237 			mss = mss / MCLBYTES * MCLBYTES;
1238 #endif
1239 		if (so->so_snd.sb_hiwat < mss)
1240 			mss = so->so_snd.sb_hiwat;
1241 
1242 		tp->t_maxseg = mss;
1243 
1244 		tcpstat.tcps_mturesent++;
1245 		tp->t_rtttime = 0;
1246 		tp->snd_nxt = tp->snd_una;
1247 		tcp_output(tp);
1248 	}
1249 }
1250 
1251 /*
1252  * Look-up the routing entry to the peer of this inpcb.  If no route
1253  * is found and it cannot be allocated the return NULL.  This routine
1254  * is called by TCP routines that access the rmx structure and by tcp_mss
1255  * to get the interface MTU.
1256  */
1257 struct rtentry *
1258 tcp_rtlookup(inp)
1259 	struct inpcb *inp;
1260 {
1261 	struct route *ro;
1262 	struct rtentry *rt;
1263 
1264 	ro = &inp->inp_route;
1265 	rt = ro->ro_rt;
1266 	if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1267 		/* No route yet, so try to acquire one */
1268 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1269 			ro->ro_dst.sa_family = AF_INET;
1270 			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1271 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1272 				inp->inp_faddr;
1273 			rtalloc(ro);
1274 			rt = ro->ro_rt;
1275 		}
1276 	}
1277 	return rt;
1278 }
1279 
1280 #ifdef INET6
1281 struct rtentry *
1282 tcp_rtlookup6(inp)
1283 	struct inpcb *inp;
1284 {
1285 	struct route_in6 *ro6;
1286 	struct rtentry *rt;
1287 
1288 	ro6 = &inp->in6p_route;
1289 	rt = ro6->ro_rt;
1290 	if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1291 		/* No route yet, so try to acquire one */
1292 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1293 			ro6->ro_dst.sin6_family = AF_INET6;
1294 			ro6->ro_dst.sin6_len = sizeof(ro6->ro_dst);
1295 			ro6->ro_dst.sin6_addr = inp->in6p_faddr;
1296 			rtalloc((struct route *)ro6);
1297 			rt = ro6->ro_rt;
1298 		}
1299 	}
1300 	return rt;
1301 }
1302 #endif /* INET6 */
1303 
1304 #ifdef IPSEC
1305 /* compute ESP/AH header size for TCP, including outer IP header. */
1306 size_t
1307 ipsec_hdrsiz_tcp(tp)
1308 	struct tcpcb *tp;
1309 {
1310 	struct inpcb *inp;
1311 	struct mbuf *m;
1312 	size_t hdrsiz;
1313 	struct ip *ip;
1314 #ifdef INET6
1315 	struct ip6_hdr *ip6;
1316 #endif /* INET6 */
1317 	struct tcphdr *th;
1318 
1319 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
1320 		return 0;
1321 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1322 	if (!m)
1323 		return 0;
1324 
1325 #ifdef INET6
1326 	if ((inp->inp_vflag & INP_IPV6) != 0) {
1327 		ip6 = mtod(m, struct ip6_hdr *);
1328 		th = (struct tcphdr *)(ip6 + 1);
1329 		m->m_pkthdr.len = m->m_len =
1330 			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1331 		bcopy((caddr_t)tp->t_template->tt_ipgen, (caddr_t)ip6,
1332 		      sizeof(struct ip6_hdr));
1333 		bcopy((caddr_t)&tp->t_template->tt_t, (caddr_t)th,
1334 		      sizeof(struct tcphdr));
1335 		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1336 	} else
1337 #endif /* INET6 */
1338       {
1339 	ip = mtod(m, struct ip *);
1340 	th = (struct tcphdr *)(ip + 1);
1341 	m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1342 	bcopy((caddr_t)tp->t_template->tt_ipgen, (caddr_t)ip,
1343 	      sizeof(struct ip));
1344 	bcopy((caddr_t)&tp->t_template->tt_t, (caddr_t)th,
1345 	      sizeof(struct tcphdr));
1346 	hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1347       }
1348 
1349 	m_free(m);
1350 	return hdrsiz;
1351 }
1352 #endif /*IPSEC*/
1353 
1354 /*
1355  * Return a pointer to the cached information about the remote host.
1356  * The cached information is stored in the protocol specific part of
1357  * the route metrics.
1358  */
1359 struct rmxp_tao *
1360 tcp_gettaocache(inp)
1361 	struct inpcb *inp;
1362 {
1363 	struct rtentry *rt;
1364 
1365 #ifdef INET6
1366 	if ((inp->inp_vflag & INP_IPV6) != 0)
1367 		rt = tcp_rtlookup6(inp);
1368 	else
1369 #endif /* INET6 */
1370 	rt = tcp_rtlookup(inp);
1371 
1372 	/* Make sure this is a host route and is up. */
1373 	if (rt == NULL ||
1374 	    (rt->rt_flags & (RTF_UP|RTF_HOST)) != (RTF_UP|RTF_HOST))
1375 		return NULL;
1376 
1377 	return rmx_taop(rt->rt_rmx);
1378 }
1379 
1380 /*
1381  * Clear all the TAO cache entries, called from tcp_init.
1382  *
1383  * XXX
1384  * This routine is just an empty one, because we assume that the routing
1385  * routing tables are initialized at the same time when TCP, so there is
1386  * nothing in the cache left over.
1387  */
1388 static void
1389 tcp_cleartaocache()
1390 {
1391 }
1392