xref: /netbsd-src/sys/netinet/tcp_subr.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: tcp_subr.c,v 1.140 2003/06/23 11:02:15 martin Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1997, 1998, 2000, 2001 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
38  * Facility, NASA Ames Research Center.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed by the NetBSD
51  *	Foundation, Inc. and its contributors.
52  * 4. Neither the name of The NetBSD Foundation nor the names of its
53  *    contributors may be used to endorse or promote products derived
54  *    from this software without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66  * POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 /*
70  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
71  *	The Regents of the University of California.  All rights reserved.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *	This product includes software developed by the University of
84  *	California, Berkeley and its contributors.
85  * 4. Neither the name of the University nor the names of its contributors
86  *    may be used to endorse or promote products derived from this software
87  *    without specific prior written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  *
101  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
102  */
103 
104 #include <sys/cdefs.h>
105 __KERNEL_RCSID(0, "$NetBSD: tcp_subr.c,v 1.140 2003/06/23 11:02:15 martin Exp $");
106 
107 #include "opt_inet.h"
108 #include "opt_ipsec.h"
109 #include "opt_tcp_compat_42.h"
110 #include "opt_inet_csum.h"
111 #include "opt_mbuftrace.h"
112 #include "rnd.h"
113 
114 #include <sys/param.h>
115 #include <sys/proc.h>
116 #include <sys/systm.h>
117 #include <sys/malloc.h>
118 #include <sys/mbuf.h>
119 #include <sys/socket.h>
120 #include <sys/socketvar.h>
121 #include <sys/protosw.h>
122 #include <sys/errno.h>
123 #include <sys/kernel.h>
124 #include <sys/pool.h>
125 #if NRND > 0
126 #include <sys/md5.h>
127 #include <sys/rnd.h>
128 #endif
129 
130 #include <net/route.h>
131 #include <net/if.h>
132 
133 #include <netinet/in.h>
134 #include <netinet/in_systm.h>
135 #include <netinet/ip.h>
136 #include <netinet/in_pcb.h>
137 #include <netinet/ip_var.h>
138 #include <netinet/ip_icmp.h>
139 
140 #ifdef INET6
141 #ifndef INET
142 #include <netinet/in.h>
143 #endif
144 #include <netinet/ip6.h>
145 #include <netinet6/in6_pcb.h>
146 #include <netinet6/ip6_var.h>
147 #include <netinet6/in6_var.h>
148 #include <netinet6/ip6protosw.h>
149 #include <netinet/icmp6.h>
150 #include <netinet6/nd6.h>
151 #endif
152 
153 #include <netinet/tcp.h>
154 #include <netinet/tcp_fsm.h>
155 #include <netinet/tcp_seq.h>
156 #include <netinet/tcp_timer.h>
157 #include <netinet/tcp_var.h>
158 #include <netinet/tcpip.h>
159 
160 #ifdef IPSEC
161 #include <netinet6/ipsec.h>
162 #endif /*IPSEC*/
163 
164 #ifdef INET6
165 struct in6pcb tcb6;
166 #endif
167 
168 struct	inpcbtable tcbtable;	/* head of queue of active tcpcb's */
169 struct	tcpstat tcpstat;	/* tcp statistics */
170 u_int32_t tcp_now;		/* for RFC 1323 timestamps */
171 
172 /* patchable/settable parameters for tcp */
173 int 	tcp_mssdflt = TCP_MSS;
174 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
175 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
176 #if NRND > 0
177 int	tcp_do_rfc1948 = 0;	/* ISS by cryptographic hash */
178 #endif
179 int	tcp_do_sack = 1;	/* selective acknowledgement */
180 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
181 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
182 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
183 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
184 int	tcp_init_win = 1;	/* initial slow start window */
185 int	tcp_init_win_local = 4;	/* initial slow start window for local nets */
186 int	tcp_mss_ifmtu = 0;
187 #ifdef TCP_COMPAT_42
188 int	tcp_compat_42 = 1;
189 #else
190 int	tcp_compat_42 = 0;
191 #endif
192 int	tcp_rst_ppslim = 100;	/* 100pps */
193 
194 /* tcb hash */
195 #ifndef TCBHASHSIZE
196 #define	TCBHASHSIZE	128
197 #endif
198 int	tcbhashsize = TCBHASHSIZE;
199 
200 /* syn hash parameters */
201 #define	TCP_SYN_HASH_SIZE	293
202 #define	TCP_SYN_BUCKET_SIZE	35
203 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
204 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
205 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
206 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
207 
208 int	tcp_freeq __P((struct tcpcb *));
209 
210 #ifdef INET
211 void	tcp_mtudisc_callback __P((struct in_addr));
212 #endif
213 #ifdef INET6
214 void	tcp6_mtudisc_callback __P((struct in6_addr *));
215 #endif
216 
217 void	tcp_mtudisc __P((struct inpcb *, int));
218 #ifdef INET6
219 void	tcp6_mtudisc __P((struct in6pcb *, int));
220 #endif
221 
222 struct pool tcpcb_pool;
223 
224 #ifdef TCP_CSUM_COUNTERS
225 #include <sys/device.h>
226 
227 struct evcnt tcp_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
228     NULL, "tcp", "hwcsum bad");
229 struct evcnt tcp_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
230     NULL, "tcp", "hwcsum ok");
231 struct evcnt tcp_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
232     NULL, "tcp", "hwcsum data");
233 struct evcnt tcp_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
234     NULL, "tcp", "swcsum");
235 #endif /* TCP_CSUM_COUNTERS */
236 
237 #ifdef TCP_OUTPUT_COUNTERS
238 #include <sys/device.h>
239 
240 struct evcnt tcp_output_bigheader = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
241     NULL, "tcp", "output big header");
242 struct evcnt tcp_output_copysmall = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
243     NULL, "tcp", "output copy small");
244 struct evcnt tcp_output_copybig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
245     NULL, "tcp", "output copy big");
246 struct evcnt tcp_output_refbig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
247     NULL, "tcp", "output reference big");
248 #endif /* TCP_OUTPUT_COUNTERS */
249 
250 #ifdef TCP_REASS_COUNTERS
251 #include <sys/device.h>
252 
253 struct evcnt tcp_reass_ = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
254     NULL, "tcp_reass", "calls");
255 struct evcnt tcp_reass_empty = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
256     &tcp_reass_, "tcp_reass", "insert into empty queue");
257 struct evcnt tcp_reass_iteration[8] = {
258     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", ">7 iterations"),
259     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "1 iteration"),
260     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "2 iterations"),
261     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "3 iterations"),
262     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "4 iterations"),
263     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "5 iterations"),
264     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "6 iterations"),
265     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "7 iterations"),
266 };
267 struct evcnt tcp_reass_prependfirst = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
268     &tcp_reass_, "tcp_reass", "prepend to first");
269 struct evcnt tcp_reass_prepend = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
270     &tcp_reass_, "tcp_reass", "prepend");
271 struct evcnt tcp_reass_insert = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
272     &tcp_reass_, "tcp_reass", "insert");
273 struct evcnt tcp_reass_inserttail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
274     &tcp_reass_, "tcp_reass", "insert at tail");
275 struct evcnt tcp_reass_append = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
276     &tcp_reass_, "tcp_reass", "append");
277 struct evcnt tcp_reass_appendtail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
278     &tcp_reass_, "tcp_reass", "append to tail fragment");
279 struct evcnt tcp_reass_overlaptail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
280     &tcp_reass_, "tcp_reass", "overlap at end");
281 struct evcnt tcp_reass_overlapfront = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
282     &tcp_reass_, "tcp_reass", "overlap at start");
283 struct evcnt tcp_reass_segdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
284     &tcp_reass_, "tcp_reass", "duplicate segment");
285 struct evcnt tcp_reass_fragdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
286     &tcp_reass_, "tcp_reass", "duplicate fragment");
287 
288 #endif /* TCP_REASS_COUNTERS */
289 
290 #ifdef MBUFTRACE
291 struct mowner tcp_mowner = { "tcp" };
292 struct mowner tcp_rx_mowner = { "tcp", "rx" };
293 struct mowner tcp_tx_mowner = { "tcp", "tx" };
294 #endif
295 
296 /*
297  * Tcp initialization
298  */
299 void
300 tcp_init()
301 {
302 	int hlen;
303 
304 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
305 	    NULL);
306 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
307 #ifdef INET6
308 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
309 #endif
310 
311 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
312 #ifdef INET6
313 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
314 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
315 #endif
316 	if (max_protohdr < hlen)
317 		max_protohdr = hlen;
318 	if (max_linkhdr + hlen > MHLEN)
319 		panic("tcp_init");
320 
321 #ifdef INET
322 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
323 #endif
324 #ifdef INET6
325 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
326 #endif
327 
328 	/* Initialize timer state. */
329 	tcp_timer_init();
330 
331 	/* Initialize the compressed state engine. */
332 	syn_cache_init();
333 
334 #ifdef TCP_CSUM_COUNTERS
335 	evcnt_attach_static(&tcp_hwcsum_bad);
336 	evcnt_attach_static(&tcp_hwcsum_ok);
337 	evcnt_attach_static(&tcp_hwcsum_data);
338 	evcnt_attach_static(&tcp_swcsum);
339 #endif /* TCP_CSUM_COUNTERS */
340 
341 #ifdef TCP_OUTPUT_COUNTERS
342 	evcnt_attach_static(&tcp_output_bigheader);
343 	evcnt_attach_static(&tcp_output_copysmall);
344 	evcnt_attach_static(&tcp_output_copybig);
345 	evcnt_attach_static(&tcp_output_refbig);
346 #endif /* TCP_OUTPUT_COUNTERS */
347 
348 #ifdef TCP_REASS_COUNTERS
349 	evcnt_attach_static(&tcp_reass_);
350 	evcnt_attach_static(&tcp_reass_empty);
351 	evcnt_attach_static(&tcp_reass_iteration[0]);
352 	evcnt_attach_static(&tcp_reass_iteration[1]);
353 	evcnt_attach_static(&tcp_reass_iteration[2]);
354 	evcnt_attach_static(&tcp_reass_iteration[3]);
355 	evcnt_attach_static(&tcp_reass_iteration[4]);
356 	evcnt_attach_static(&tcp_reass_iteration[5]);
357 	evcnt_attach_static(&tcp_reass_iteration[6]);
358 	evcnt_attach_static(&tcp_reass_iteration[7]);
359 	evcnt_attach_static(&tcp_reass_prependfirst);
360 	evcnt_attach_static(&tcp_reass_prepend);
361 	evcnt_attach_static(&tcp_reass_insert);
362 	evcnt_attach_static(&tcp_reass_inserttail);
363 	evcnt_attach_static(&tcp_reass_append);
364 	evcnt_attach_static(&tcp_reass_appendtail);
365 	evcnt_attach_static(&tcp_reass_overlaptail);
366 	evcnt_attach_static(&tcp_reass_overlapfront);
367 	evcnt_attach_static(&tcp_reass_segdup);
368 	evcnt_attach_static(&tcp_reass_fragdup);
369 #endif /* TCP_REASS_COUNTERS */
370 
371 	MOWNER_ATTACH(&tcp_tx_mowner);
372 	MOWNER_ATTACH(&tcp_rx_mowner);
373 	MOWNER_ATTACH(&tcp_mowner);
374 }
375 
376 /*
377  * Create template to be used to send tcp packets on a connection.
378  * Call after host entry created, allocates an mbuf and fills
379  * in a skeletal tcp/ip header, minimizing the amount of work
380  * necessary when the connection is used.
381  */
382 struct mbuf *
383 tcp_template(tp)
384 	struct tcpcb *tp;
385 {
386 	struct inpcb *inp = tp->t_inpcb;
387 #ifdef INET6
388 	struct in6pcb *in6p = tp->t_in6pcb;
389 #endif
390 	struct tcphdr *n;
391 	struct mbuf *m;
392 	int hlen;
393 
394 	switch (tp->t_family) {
395 	case AF_INET:
396 		hlen = sizeof(struct ip);
397 		if (inp)
398 			break;
399 #ifdef INET6
400 		if (in6p) {
401 			/* mapped addr case */
402 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
403 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
404 				break;
405 		}
406 #endif
407 		return NULL;	/*EINVAL*/
408 #ifdef INET6
409 	case AF_INET6:
410 		hlen = sizeof(struct ip6_hdr);
411 		if (in6p) {
412 			/* more sainty check? */
413 			break;
414 		}
415 		return NULL;	/*EINVAL*/
416 #endif
417 	default:
418 		hlen = 0;	/*pacify gcc*/
419 		return NULL;	/*EAFNOSUPPORT*/
420 	}
421 #ifdef DIAGNOSTIC
422 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
423 		panic("mclbytes too small for t_template");
424 #endif
425 	m = tp->t_template;
426 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
427 		;
428 	else {
429 		if (m)
430 			m_freem(m);
431 		m = tp->t_template = NULL;
432 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
433 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
434 			MCLGET(m, M_DONTWAIT);
435 			if ((m->m_flags & M_EXT) == 0) {
436 				m_free(m);
437 				m = NULL;
438 			}
439 		}
440 		if (m == NULL)
441 			return NULL;
442 		MCLAIM(m, &tcp_mowner);
443 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
444 	}
445 
446 	bzero(mtod(m, caddr_t), m->m_len);
447 
448 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
449 
450 	switch (tp->t_family) {
451 	case AF_INET:
452 	    {
453 		struct ipovly *ipov;
454 		mtod(m, struct ip *)->ip_v = 4;
455 		ipov = mtod(m, struct ipovly *);
456 		ipov->ih_pr = IPPROTO_TCP;
457 		ipov->ih_len = htons(sizeof(struct tcphdr));
458 		if (inp) {
459 			ipov->ih_src = inp->inp_laddr;
460 			ipov->ih_dst = inp->inp_faddr;
461 		}
462 #ifdef INET6
463 		else if (in6p) {
464 			/* mapped addr case */
465 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
466 				sizeof(ipov->ih_src));
467 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
468 				sizeof(ipov->ih_dst));
469 		}
470 #endif
471 		/*
472 		 * Compute the pseudo-header portion of the checksum
473 		 * now.  We incrementally add in the TCP option and
474 		 * payload lengths later, and then compute the TCP
475 		 * checksum right before the packet is sent off onto
476 		 * the wire.
477 		 */
478 		n->th_sum = in_cksum_phdr(ipov->ih_src.s_addr,
479 		    ipov->ih_dst.s_addr,
480 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
481 		break;
482 	    }
483 #ifdef INET6
484 	case AF_INET6:
485 	    {
486 		struct ip6_hdr *ip6;
487 		mtod(m, struct ip *)->ip_v = 6;
488 		ip6 = mtod(m, struct ip6_hdr *);
489 		ip6->ip6_nxt = IPPROTO_TCP;
490 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
491 		ip6->ip6_src = in6p->in6p_laddr;
492 		ip6->ip6_dst = in6p->in6p_faddr;
493 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
494 		if (ip6_auto_flowlabel) {
495 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
496 			ip6->ip6_flow |=
497 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
498 		}
499 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
500 		ip6->ip6_vfc |= IPV6_VERSION;
501 
502 		/*
503 		 * Compute the pseudo-header portion of the checksum
504 		 * now.  We incrementally add in the TCP option and
505 		 * payload lengths later, and then compute the TCP
506 		 * checksum right before the packet is sent off onto
507 		 * the wire.
508 		 */
509 		n->th_sum = in6_cksum_phdr(&in6p->in6p_laddr,
510 		    &in6p->in6p_faddr, htonl(sizeof(struct tcphdr)),
511 		    htonl(IPPROTO_TCP));
512 		break;
513 	    }
514 #endif
515 	}
516 	if (inp) {
517 		n->th_sport = inp->inp_lport;
518 		n->th_dport = inp->inp_fport;
519 	}
520 #ifdef INET6
521 	else if (in6p) {
522 		n->th_sport = in6p->in6p_lport;
523 		n->th_dport = in6p->in6p_fport;
524 	}
525 #endif
526 	n->th_seq = 0;
527 	n->th_ack = 0;
528 	n->th_x2 = 0;
529 	n->th_off = 5;
530 	n->th_flags = 0;
531 	n->th_win = 0;
532 	n->th_urp = 0;
533 	return (m);
534 }
535 
536 /*
537  * Send a single message to the TCP at address specified by
538  * the given TCP/IP header.  If m == 0, then we make a copy
539  * of the tcpiphdr at ti and send directly to the addressed host.
540  * This is used to force keep alive messages out using the TCP
541  * template for a connection tp->t_template.  If flags are given
542  * then we send a message back to the TCP which originated the
543  * segment ti, and discard the mbuf containing it and any other
544  * attached mbufs.
545  *
546  * In any case the ack and sequence number of the transmitted
547  * segment are as specified by the parameters.
548  */
549 int
550 tcp_respond(tp, template, m, th0, ack, seq, flags)
551 	struct tcpcb *tp;
552 	struct mbuf *template;
553 	struct mbuf *m;
554 	struct tcphdr *th0;
555 	tcp_seq ack, seq;
556 	int flags;
557 {
558 	struct route *ro;
559 	int error, tlen, win = 0;
560 	int hlen;
561 	struct ip *ip;
562 #ifdef INET6
563 	struct ip6_hdr *ip6;
564 #endif
565 	int family;	/* family on packet, not inpcb/in6pcb! */
566 	struct tcphdr *th;
567 
568 	if (tp != NULL && (flags & TH_RST) == 0) {
569 #ifdef DIAGNOSTIC
570 		if (tp->t_inpcb && tp->t_in6pcb)
571 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
572 #endif
573 #ifdef INET
574 		if (tp->t_inpcb)
575 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
576 #endif
577 #ifdef INET6
578 		if (tp->t_in6pcb)
579 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
580 #endif
581 	}
582 
583 	th = NULL;	/* Quell uninitialized warning */
584 	ip = NULL;
585 #ifdef INET6
586 	ip6 = NULL;
587 #endif
588 	if (m == 0) {
589 		if (!template)
590 			return EINVAL;
591 
592 		/* get family information from template */
593 		switch (mtod(template, struct ip *)->ip_v) {
594 		case 4:
595 			family = AF_INET;
596 			hlen = sizeof(struct ip);
597 			break;
598 #ifdef INET6
599 		case 6:
600 			family = AF_INET6;
601 			hlen = sizeof(struct ip6_hdr);
602 			break;
603 #endif
604 		default:
605 			return EAFNOSUPPORT;
606 		}
607 
608 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
609 		if (m) {
610 			MCLAIM(m, &tcp_tx_mowner);
611 			MCLGET(m, M_DONTWAIT);
612 			if ((m->m_flags & M_EXT) == 0) {
613 				m_free(m);
614 				m = NULL;
615 			}
616 		}
617 		if (m == NULL)
618 			return (ENOBUFS);
619 
620 		if (tcp_compat_42)
621 			tlen = 1;
622 		else
623 			tlen = 0;
624 
625 		m->m_data += max_linkhdr;
626 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
627 			template->m_len);
628 		switch (family) {
629 		case AF_INET:
630 			ip = mtod(m, struct ip *);
631 			th = (struct tcphdr *)(ip + 1);
632 			break;
633 #ifdef INET6
634 		case AF_INET6:
635 			ip6 = mtod(m, struct ip6_hdr *);
636 			th = (struct tcphdr *)(ip6 + 1);
637 			break;
638 #endif
639 #if 0
640 		default:
641 			/* noone will visit here */
642 			m_freem(m);
643 			return EAFNOSUPPORT;
644 #endif
645 		}
646 		flags = TH_ACK;
647 	} else {
648 
649 		if ((m->m_flags & M_PKTHDR) == 0) {
650 #if 0
651 			printf("non PKTHDR to tcp_respond\n");
652 #endif
653 			m_freem(m);
654 			return EINVAL;
655 		}
656 #ifdef DIAGNOSTIC
657 		if (!th0)
658 			panic("th0 == NULL in tcp_respond");
659 #endif
660 
661 		/* get family information from m */
662 		switch (mtod(m, struct ip *)->ip_v) {
663 		case 4:
664 			family = AF_INET;
665 			hlen = sizeof(struct ip);
666 			ip = mtod(m, struct ip *);
667 			break;
668 #ifdef INET6
669 		case 6:
670 			family = AF_INET6;
671 			hlen = sizeof(struct ip6_hdr);
672 			ip6 = mtod(m, struct ip6_hdr *);
673 			break;
674 #endif
675 		default:
676 			m_freem(m);
677 			return EAFNOSUPPORT;
678 		}
679 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
680 			tlen = sizeof(*th0);
681 		else
682 			tlen = th0->th_off << 2;
683 
684 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
685 		    mtod(m, caddr_t) + hlen == (caddr_t)th0) {
686 			m->m_len = hlen + tlen;
687 			m_freem(m->m_next);
688 			m->m_next = NULL;
689 		} else {
690 			struct mbuf *n;
691 
692 #ifdef DIAGNOSTIC
693 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
694 				m_freem(m);
695 				return EMSGSIZE;
696 			}
697 #endif
698 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
699 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
700 				MCLGET(n, M_DONTWAIT);
701 				if ((n->m_flags & M_EXT) == 0) {
702 					m_freem(n);
703 					n = NULL;
704 				}
705 			}
706 			if (!n) {
707 				m_freem(m);
708 				return ENOBUFS;
709 			}
710 
711 			MCLAIM(n, &tcp_tx_mowner);
712 			n->m_data += max_linkhdr;
713 			n->m_len = hlen + tlen;
714 			m_copyback(n, 0, hlen, mtod(m, caddr_t));
715 			m_copyback(n, hlen, tlen, (caddr_t)th0);
716 
717 			m_freem(m);
718 			m = n;
719 			n = NULL;
720 		}
721 
722 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
723 		switch (family) {
724 		case AF_INET:
725 			ip = mtod(m, struct ip *);
726 			th = (struct tcphdr *)(ip + 1);
727 			ip->ip_p = IPPROTO_TCP;
728 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
729 			ip->ip_p = IPPROTO_TCP;
730 			break;
731 #ifdef INET6
732 		case AF_INET6:
733 			ip6 = mtod(m, struct ip6_hdr *);
734 			th = (struct tcphdr *)(ip6 + 1);
735 			ip6->ip6_nxt = IPPROTO_TCP;
736 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
737 			ip6->ip6_nxt = IPPROTO_TCP;
738 			break;
739 #endif
740 #if 0
741 		default:
742 			/* noone will visit here */
743 			m_freem(m);
744 			return EAFNOSUPPORT;
745 #endif
746 		}
747 		xchg(th->th_dport, th->th_sport, u_int16_t);
748 #undef xchg
749 		tlen = 0;	/*be friendly with the following code*/
750 	}
751 	th->th_seq = htonl(seq);
752 	th->th_ack = htonl(ack);
753 	th->th_x2 = 0;
754 	if ((flags & TH_SYN) == 0) {
755 		if (tp)
756 			win >>= tp->rcv_scale;
757 		if (win > TCP_MAXWIN)
758 			win = TCP_MAXWIN;
759 		th->th_win = htons((u_int16_t)win);
760 		th->th_off = sizeof (struct tcphdr) >> 2;
761 		tlen += sizeof(*th);
762 	} else
763 		tlen += th->th_off << 2;
764 	m->m_len = hlen + tlen;
765 	m->m_pkthdr.len = hlen + tlen;
766 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
767 	th->th_flags = flags;
768 	th->th_urp = 0;
769 
770 	switch (family) {
771 #ifdef INET
772 	case AF_INET:
773 	    {
774 		struct ipovly *ipov = (struct ipovly *)ip;
775 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
776 		ipov->ih_len = htons((u_int16_t)tlen);
777 
778 		th->th_sum = 0;
779 		th->th_sum = in_cksum(m, hlen + tlen);
780 		ip->ip_len = htons(hlen + tlen);
781 		ip->ip_ttl = ip_defttl;
782 		break;
783 	    }
784 #endif
785 #ifdef INET6
786 	case AF_INET6:
787 	    {
788 		th->th_sum = 0;
789 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
790 				tlen);
791 		ip6->ip6_plen = ntohs(tlen);
792 		if (tp && tp->t_in6pcb) {
793 			struct ifnet *oifp;
794 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
795 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
796 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
797 		} else
798 			ip6->ip6_hlim = ip6_defhlim;
799 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
800 		if (ip6_auto_flowlabel) {
801 			ip6->ip6_flow |=
802 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
803 		}
804 		break;
805 	    }
806 #endif
807 	}
808 
809 #ifdef IPSEC
810 	(void)ipsec_setsocket(m, NULL);
811 #endif /*IPSEC*/
812 
813 	if (tp != NULL && tp->t_inpcb != NULL) {
814 		ro = &tp->t_inpcb->inp_route;
815 #ifdef IPSEC
816 		if (ipsec_setsocket(m, tp->t_inpcb->inp_socket) != 0) {
817 			m_freem(m);
818 			return ENOBUFS;
819 		}
820 #endif
821 #ifdef DIAGNOSTIC
822 		if (family != AF_INET)
823 			panic("tcp_respond: address family mismatch");
824 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
825 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
826 			    ntohl(ip->ip_dst.s_addr),
827 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
828 		}
829 #endif
830 	}
831 #ifdef INET6
832 	else if (tp != NULL && tp->t_in6pcb != NULL) {
833 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
834 #ifdef IPSEC
835 		if (ipsec_setsocket(m, tp->t_in6pcb->in6p_socket) != 0) {
836 			m_freem(m);
837 			return ENOBUFS;
838 		}
839 #endif
840 #ifdef DIAGNOSTIC
841 		if (family == AF_INET) {
842 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
843 				panic("tcp_respond: not mapped addr");
844 			if (bcmp(&ip->ip_dst,
845 			    &tp->t_in6pcb->in6p_faddr.s6_addr32[3],
846 			    sizeof(ip->ip_dst)) != 0) {
847 				panic("tcp_respond: ip_dst != in6p_faddr");
848 			}
849 		} else if (family == AF_INET6) {
850 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
851 			    &tp->t_in6pcb->in6p_faddr))
852 				panic("tcp_respond: ip6_dst != in6p_faddr");
853 		} else
854 			panic("tcp_respond: address family mismatch");
855 #endif
856 	}
857 #endif
858 	else
859 		ro = NULL;
860 
861 	switch (family) {
862 #ifdef INET
863 	case AF_INET:
864 		error = ip_output(m, NULL, ro,
865 		    (tp && tp->t_mtudisc ? IP_MTUDISC : 0),
866 		    NULL);
867 		break;
868 #endif
869 #ifdef INET6
870 	case AF_INET6:
871 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL,
872 		    NULL);
873 		break;
874 #endif
875 	default:
876 		error = EAFNOSUPPORT;
877 		break;
878 	}
879 
880 	return (error);
881 }
882 
883 /*
884  * Create a new TCP control block, making an
885  * empty reassembly queue and hooking it to the argument
886  * protocol control block.
887  */
888 struct tcpcb *
889 tcp_newtcpcb(family, aux)
890 	int family;	/* selects inpcb, or in6pcb */
891 	void *aux;
892 {
893 	struct tcpcb *tp;
894 	int i;
895 
896 	switch (family) {
897 	case PF_INET:
898 		break;
899 #ifdef INET6
900 	case PF_INET6:
901 		break;
902 #endif
903 	default:
904 		return NULL;
905 	}
906 
907 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
908 	if (tp == NULL)
909 		return (NULL);
910 	bzero((caddr_t)tp, sizeof(struct tcpcb));
911 	TAILQ_INIT(&tp->segq);
912 	TAILQ_INIT(&tp->timeq);
913 	tp->t_family = family;		/* may be overridden later on */
914 	tp->t_peermss = tcp_mssdflt;
915 	tp->t_ourmss = tcp_mssdflt;
916 	tp->t_segsz = tcp_mssdflt;
917 	LIST_INIT(&tp->t_sc);
918 
919 	callout_init(&tp->t_delack_ch);
920 	for (i = 0; i < TCPT_NTIMERS; i++)
921 		TCP_TIMER_INIT(tp, i);
922 
923 	tp->t_flags = 0;
924 	if (tcp_do_rfc1323 && tcp_do_win_scale)
925 		tp->t_flags |= TF_REQ_SCALE;
926 	if (tcp_do_rfc1323 && tcp_do_timestamps)
927 		tp->t_flags |= TF_REQ_TSTMP;
928 	if (tcp_do_sack == 2)
929 		tp->t_flags |= TF_WILL_SACK;
930 	else if (tcp_do_sack == 1)
931 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
932 	tp->t_flags |= TF_CANT_TXSACK;
933 	switch (family) {
934 	case PF_INET:
935 		tp->t_inpcb = (struct inpcb *)aux;
936 		tp->t_mtudisc = ip_mtudisc;
937 		break;
938 #ifdef INET6
939 	case PF_INET6:
940 		tp->t_in6pcb = (struct in6pcb *)aux;
941 		/* for IPv6, always try to run path MTU discovery */
942 		tp->t_mtudisc = 1;
943 		break;
944 #endif
945 	}
946 	/*
947 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
948 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
949 	 * reasonable initial retransmit time.
950 	 */
951 	tp->t_srtt = TCPTV_SRTTBASE;
952 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
953 	tp->t_rttmin = TCPTV_MIN;
954 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
955 	    TCPTV_MIN, TCPTV_REXMTMAX);
956 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
957 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
958 	if (family == AF_INET) {
959 		struct inpcb *inp = (struct inpcb *)aux;
960 		inp->inp_ip.ip_ttl = ip_defttl;
961 		inp->inp_ppcb = (caddr_t)tp;
962 	}
963 #ifdef INET6
964 	else if (family == AF_INET6) {
965 		struct in6pcb *in6p = (struct in6pcb *)aux;
966 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
967 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
968 					       : NULL);
969 		in6p->in6p_ppcb = (caddr_t)tp;
970 	}
971 #endif
972 
973 	/*
974 	 * Initialize our timebase.  When we send timestamps, we take
975 	 * the delta from tcp_now -- this means each connection always
976 	 * gets a timebase of 0, which makes it, among other things,
977 	 * more difficult to determine how long a system has been up,
978 	 * and thus how many TCP sequence increments have occurred.
979 	 */
980 	tp->ts_timebase = tcp_now;
981 
982 	return (tp);
983 }
984 
985 /*
986  * Drop a TCP connection, reporting
987  * the specified error.  If connection is synchronized,
988  * then send a RST to peer.
989  */
990 struct tcpcb *
991 tcp_drop(tp, errno)
992 	struct tcpcb *tp;
993 	int errno;
994 {
995 	struct socket *so = NULL;
996 
997 #ifdef DIAGNOSTIC
998 	if (tp->t_inpcb && tp->t_in6pcb)
999 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
1000 #endif
1001 #ifdef INET
1002 	if (tp->t_inpcb)
1003 		so = tp->t_inpcb->inp_socket;
1004 #endif
1005 #ifdef INET6
1006 	if (tp->t_in6pcb)
1007 		so = tp->t_in6pcb->in6p_socket;
1008 #endif
1009 	if (!so)
1010 		return NULL;
1011 
1012 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
1013 		tp->t_state = TCPS_CLOSED;
1014 		(void) tcp_output(tp);
1015 		tcpstat.tcps_drops++;
1016 	} else
1017 		tcpstat.tcps_conndrops++;
1018 	if (errno == ETIMEDOUT && tp->t_softerror)
1019 		errno = tp->t_softerror;
1020 	so->so_error = errno;
1021 	return (tcp_close(tp));
1022 }
1023 
1024 /*
1025  * Close a TCP control block:
1026  *	discard all space held by the tcp
1027  *	discard internet protocol block
1028  *	wake up any sleepers
1029  */
1030 struct tcpcb *
1031 tcp_close(tp)
1032 	struct tcpcb *tp;
1033 {
1034 	struct inpcb *inp;
1035 #ifdef INET6
1036 	struct in6pcb *in6p;
1037 #endif
1038 	struct socket *so;
1039 #ifdef RTV_RTT
1040 	struct rtentry *rt;
1041 #endif
1042 	struct route *ro;
1043 
1044 	inp = tp->t_inpcb;
1045 #ifdef INET6
1046 	in6p = tp->t_in6pcb;
1047 #endif
1048 	so = NULL;
1049 	ro = NULL;
1050 	if (inp) {
1051 		so = inp->inp_socket;
1052 		ro = &inp->inp_route;
1053 	}
1054 #ifdef INET6
1055 	else if (in6p) {
1056 		so = in6p->in6p_socket;
1057 		ro = (struct route *)&in6p->in6p_route;
1058 	}
1059 #endif
1060 
1061 #ifdef RTV_RTT
1062 	/*
1063 	 * If we sent enough data to get some meaningful characteristics,
1064 	 * save them in the routing entry.  'Enough' is arbitrarily
1065 	 * defined as the sendpipesize (default 4K) * 16.  This would
1066 	 * give us 16 rtt samples assuming we only get one sample per
1067 	 * window (the usual case on a long haul net).  16 samples is
1068 	 * enough for the srtt filter to converge to within 5% of the correct
1069 	 * value; fewer samples and we could save a very bogus rtt.
1070 	 *
1071 	 * Don't update the default route's characteristics and don't
1072 	 * update anything that the user "locked".
1073 	 */
1074 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
1075 	    ro && (rt = ro->ro_rt) &&
1076 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
1077 		u_long i = 0;
1078 
1079 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
1080 			i = tp->t_srtt *
1081 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1082 			if (rt->rt_rmx.rmx_rtt && i)
1083 				/*
1084 				 * filter this update to half the old & half
1085 				 * the new values, converting scale.
1086 				 * See route.h and tcp_var.h for a
1087 				 * description of the scaling constants.
1088 				 */
1089 				rt->rt_rmx.rmx_rtt =
1090 				    (rt->rt_rmx.rmx_rtt + i) / 2;
1091 			else
1092 				rt->rt_rmx.rmx_rtt = i;
1093 		}
1094 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
1095 			i = tp->t_rttvar *
1096 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
1097 			if (rt->rt_rmx.rmx_rttvar && i)
1098 				rt->rt_rmx.rmx_rttvar =
1099 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
1100 			else
1101 				rt->rt_rmx.rmx_rttvar = i;
1102 		}
1103 		/*
1104 		 * update the pipelimit (ssthresh) if it has been updated
1105 		 * already or if a pipesize was specified & the threshhold
1106 		 * got below half the pipesize.  I.e., wait for bad news
1107 		 * before we start updating, then update on both good
1108 		 * and bad news.
1109 		 */
1110 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
1111 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
1112 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
1113 			/*
1114 			 * convert the limit from user data bytes to
1115 			 * packets then to packet data bytes.
1116 			 */
1117 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
1118 			if (i < 2)
1119 				i = 2;
1120 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
1121 			if (rt->rt_rmx.rmx_ssthresh)
1122 				rt->rt_rmx.rmx_ssthresh =
1123 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
1124 			else
1125 				rt->rt_rmx.rmx_ssthresh = i;
1126 		}
1127 	}
1128 #endif /* RTV_RTT */
1129 	/* free the reassembly queue, if any */
1130 	TCP_REASS_LOCK(tp);
1131 	(void) tcp_freeq(tp);
1132 	TCP_REASS_UNLOCK(tp);
1133 
1134 	tcp_canceltimers(tp);
1135 	TCP_CLEAR_DELACK(tp);
1136 	syn_cache_cleanup(tp);
1137 
1138 	if (tp->t_template) {
1139 		m_free(tp->t_template);
1140 		tp->t_template = NULL;
1141 	}
1142 	pool_put(&tcpcb_pool, tp);
1143 	if (inp) {
1144 		inp->inp_ppcb = 0;
1145 		soisdisconnected(so);
1146 		in_pcbdetach(inp);
1147 	}
1148 #ifdef INET6
1149 	else if (in6p) {
1150 		in6p->in6p_ppcb = 0;
1151 		soisdisconnected(so);
1152 		in6_pcbdetach(in6p);
1153 	}
1154 #endif
1155 	tcpstat.tcps_closed++;
1156 	return ((struct tcpcb *)0);
1157 }
1158 
1159 int
1160 tcp_freeq(tp)
1161 	struct tcpcb *tp;
1162 {
1163 	struct ipqent *qe;
1164 	int rv = 0;
1165 #ifdef TCPREASS_DEBUG
1166 	int i = 0;
1167 #endif
1168 
1169 	TCP_REASS_LOCK_CHECK(tp);
1170 
1171 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
1172 #ifdef TCPREASS_DEBUG
1173 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
1174 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
1175 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
1176 #endif
1177 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
1178 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
1179 		m_freem(qe->ipqe_m);
1180 		pool_put(&ipqent_pool, qe);
1181 		rv = 1;
1182 	}
1183 	return (rv);
1184 }
1185 
1186 /*
1187  * Protocol drain routine.  Called when memory is in short supply.
1188  */
1189 void
1190 tcp_drain()
1191 {
1192 	struct inpcb *inp;
1193 	struct tcpcb *tp;
1194 
1195 	/*
1196 	 * Free the sequence queue of all TCP connections.
1197 	 */
1198 	inp = CIRCLEQ_FIRST(&tcbtable.inpt_queue);
1199 	if (inp)						/* XXX */
1200 	CIRCLEQ_FOREACH(inp, &tcbtable.inpt_queue, inp_queue) {
1201 		if ((tp = intotcpcb(inp)) != NULL) {
1202 			/*
1203 			 * We may be called from a device's interrupt
1204 			 * context.  If the tcpcb is already busy,
1205 			 * just bail out now.
1206 			 */
1207 			if (tcp_reass_lock_try(tp) == 0)
1208 				continue;
1209 			if (tcp_freeq(tp))
1210 				tcpstat.tcps_connsdrained++;
1211 			TCP_REASS_UNLOCK(tp);
1212 		}
1213 	}
1214 }
1215 
1216 #ifdef INET6
1217 void
1218 tcp6_drain()
1219 {
1220 	struct in6pcb *in6p;
1221 	struct tcpcb *tp;
1222 	struct in6pcb *head = &tcb6;
1223 
1224 	/*
1225 	 * Free the sequence queue of all TCP connections.
1226 	 */
1227 	for (in6p = head->in6p_next; in6p != head; in6p = in6p->in6p_next) {
1228 		if ((tp = in6totcpcb(in6p)) != NULL) {
1229 			/*
1230 			 * We may be called from a device's interrupt
1231 			 * context.  If the tcpcb is already busy,
1232 			 * just bail out now.
1233 			 */
1234 			if (tcp_reass_lock_try(tp) == 0)
1235 				continue;
1236 			if (tcp_freeq(tp))
1237 				tcpstat.tcps_connsdrained++;
1238 			TCP_REASS_UNLOCK(tp);
1239 		}
1240 	}
1241 }
1242 #endif
1243 
1244 /*
1245  * Notify a tcp user of an asynchronous error;
1246  * store error as soft error, but wake up user
1247  * (for now, won't do anything until can select for soft error).
1248  */
1249 void
1250 tcp_notify(inp, error)
1251 	struct inpcb *inp;
1252 	int error;
1253 {
1254 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1255 	struct socket *so = inp->inp_socket;
1256 
1257 	/*
1258 	 * Ignore some errors if we are hooked up.
1259 	 * If connection hasn't completed, has retransmitted several times,
1260 	 * and receives a second error, give up now.  This is better
1261 	 * than waiting a long time to establish a connection that
1262 	 * can never complete.
1263 	 */
1264 	if (tp->t_state == TCPS_ESTABLISHED &&
1265 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1266 	      error == EHOSTDOWN)) {
1267 		return;
1268 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1269 	    tp->t_rxtshift > 3 && tp->t_softerror)
1270 		so->so_error = error;
1271 	else
1272 		tp->t_softerror = error;
1273 	wakeup((caddr_t) &so->so_timeo);
1274 	sorwakeup(so);
1275 	sowwakeup(so);
1276 }
1277 
1278 #ifdef INET6
1279 void
1280 tcp6_notify(in6p, error)
1281 	struct in6pcb *in6p;
1282 	int error;
1283 {
1284 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1285 	struct socket *so = in6p->in6p_socket;
1286 
1287 	/*
1288 	 * Ignore some errors if we are hooked up.
1289 	 * If connection hasn't completed, has retransmitted several times,
1290 	 * and receives a second error, give up now.  This is better
1291 	 * than waiting a long time to establish a connection that
1292 	 * can never complete.
1293 	 */
1294 	if (tp->t_state == TCPS_ESTABLISHED &&
1295 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1296 	      error == EHOSTDOWN)) {
1297 		return;
1298 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1299 	    tp->t_rxtshift > 3 && tp->t_softerror)
1300 		so->so_error = error;
1301 	else
1302 		tp->t_softerror = error;
1303 	wakeup((caddr_t) &so->so_timeo);
1304 	sorwakeup(so);
1305 	sowwakeup(so);
1306 }
1307 #endif
1308 
1309 #ifdef INET6
1310 void
1311 tcp6_ctlinput(cmd, sa, d)
1312 	int cmd;
1313 	struct sockaddr *sa;
1314 	void *d;
1315 {
1316 	struct tcphdr th;
1317 	void (*notify) __P((struct in6pcb *, int)) = tcp6_notify;
1318 	int nmatch;
1319 	struct ip6_hdr *ip6;
1320 	const struct sockaddr_in6 *sa6_src = NULL;
1321 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
1322 	struct mbuf *m;
1323 	int off;
1324 
1325 	if (sa->sa_family != AF_INET6 ||
1326 	    sa->sa_len != sizeof(struct sockaddr_in6))
1327 		return;
1328 	if ((unsigned)cmd >= PRC_NCMDS)
1329 		return;
1330 	else if (cmd == PRC_QUENCH) {
1331 		/* XXX there's no PRC_QUENCH in IPv6 */
1332 		notify = tcp6_quench;
1333 	} else if (PRC_IS_REDIRECT(cmd))
1334 		notify = in6_rtchange, d = NULL;
1335 	else if (cmd == PRC_MSGSIZE)
1336 		; /* special code is present, see below */
1337 	else if (cmd == PRC_HOSTDEAD)
1338 		d = NULL;
1339 	else if (inet6ctlerrmap[cmd] == 0)
1340 		return;
1341 
1342 	/* if the parameter is from icmp6, decode it. */
1343 	if (d != NULL) {
1344 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1345 		m = ip6cp->ip6c_m;
1346 		ip6 = ip6cp->ip6c_ip6;
1347 		off = ip6cp->ip6c_off;
1348 		sa6_src = ip6cp->ip6c_src;
1349 	} else {
1350 		m = NULL;
1351 		ip6 = NULL;
1352 		sa6_src = &sa6_any;
1353 	}
1354 
1355 	if (ip6) {
1356 		/*
1357 		 * XXX: We assume that when ip6 is non NULL,
1358 		 * M and OFF are valid.
1359 		 */
1360 
1361 		/* check if we can safely examine src and dst ports */
1362 		if (m->m_pkthdr.len < off + sizeof(th)) {
1363 			if (cmd == PRC_MSGSIZE)
1364 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
1365 			return;
1366 		}
1367 
1368 		bzero(&th, sizeof(th));
1369 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
1370 
1371 		if (cmd == PRC_MSGSIZE) {
1372 			int valid = 0;
1373 
1374 			/*
1375 			 * Check to see if we have a valid TCP connection
1376 			 * corresponding to the address in the ICMPv6 message
1377 			 * payload.
1378 			 */
1379 			if (in6_pcblookup_connect(&tcb6, &sa6->sin6_addr,
1380 			    th.th_dport, (struct in6_addr *)&sa6_src->sin6_addr,
1381 			    th.th_sport, 0))
1382 				valid++;
1383 
1384 			/*
1385 			 * Depending on the value of "valid" and routing table
1386 			 * size (mtudisc_{hi,lo}wat), we will:
1387 			 * - recalcurate the new MTU and create the
1388 			 *   corresponding routing entry, or
1389 			 * - ignore the MTU change notification.
1390 			 */
1391 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
1392 
1393 			/*
1394 			 * no need to call in6_pcbnotify, it should have been
1395 			 * called via callback if necessary
1396 			 */
1397 			return;
1398 		}
1399 
1400 		nmatch = in6_pcbnotify(&tcb6, sa, th.th_dport,
1401 		    (struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
1402 		if (nmatch == 0 && syn_cache_count &&
1403 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1404 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1405 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
1406 			syn_cache_unreach((struct sockaddr *)sa6_src,
1407 					  sa, &th);
1408 	} else {
1409 		(void) in6_pcbnotify(&tcb6, sa, 0, (struct sockaddr *)sa6_src,
1410 		    0, cmd, NULL, notify);
1411 	}
1412 }
1413 #endif
1414 
1415 #ifdef INET
1416 /* assumes that ip header and tcp header are contiguous on mbuf */
1417 void *
1418 tcp_ctlinput(cmd, sa, v)
1419 	int cmd;
1420 	struct sockaddr *sa;
1421 	void *v;
1422 {
1423 	struct ip *ip = v;
1424 	struct tcphdr *th;
1425 	struct icmp *icp;
1426 	extern const int inetctlerrmap[];
1427 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1428 	int errno;
1429 	int nmatch;
1430 #ifdef INET6
1431 	struct in6_addr src6, dst6;
1432 #endif
1433 
1434 	if (sa->sa_family != AF_INET ||
1435 	    sa->sa_len != sizeof(struct sockaddr_in))
1436 		return NULL;
1437 	if ((unsigned)cmd >= PRC_NCMDS)
1438 		return NULL;
1439 	errno = inetctlerrmap[cmd];
1440 	if (cmd == PRC_QUENCH)
1441 		notify = tcp_quench;
1442 	else if (PRC_IS_REDIRECT(cmd))
1443 		notify = in_rtchange, ip = 0;
1444 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
1445 		/*
1446 		 * Check to see if we have a valid TCP connection
1447 		 * corresponding to the address in the ICMP message
1448 		 * payload.
1449 		 *
1450 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
1451 		 */
1452 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1453 #ifdef INET6
1454 		memset(&src6, 0, sizeof(src6));
1455 		memset(&dst6, 0, sizeof(dst6));
1456 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
1457 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
1458 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
1459 #endif
1460 		if (in_pcblookup_connect(&tcbtable, ip->ip_dst, th->th_dport,
1461 		    ip->ip_src, th->th_sport) != NULL)
1462 			;
1463 #ifdef INET6
1464 		else if (in6_pcblookup_connect(&tcb6, &dst6,
1465 		    th->th_dport, &src6, th->th_sport, 0) != NULL)
1466 			;
1467 #endif
1468 		else
1469 			return NULL;
1470 
1471 		/*
1472 		 * Now that we've validated that we are actually communicating
1473 		 * with the host indicated in the ICMP message, locate the
1474 		 * ICMP header, recalculate the new MTU, and create the
1475 		 * corresponding routing entry.
1476 		 */
1477 		icp = (struct icmp *)((caddr_t)ip -
1478 		    offsetof(struct icmp, icmp_ip));
1479 		icmp_mtudisc(icp, ip->ip_dst);
1480 
1481 		return NULL;
1482 	} else if (cmd == PRC_HOSTDEAD)
1483 		ip = 0;
1484 	else if (errno == 0)
1485 		return NULL;
1486 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1487 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1488 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
1489 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1490 		if (nmatch == 0 && syn_cache_count &&
1491 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1492 		    inetctlerrmap[cmd] == ENETUNREACH ||
1493 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1494 			struct sockaddr_in sin;
1495 			bzero(&sin, sizeof(sin));
1496 			sin.sin_len = sizeof(sin);
1497 			sin.sin_family = AF_INET;
1498 			sin.sin_port = th->th_sport;
1499 			sin.sin_addr = ip->ip_src;
1500 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1501 		}
1502 
1503 		/* XXX mapped address case */
1504 	} else
1505 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
1506 		    notify);
1507 	return NULL;
1508 }
1509 
1510 /*
1511  * When a source quence is received, we are being notifed of congestion.
1512  * Close the congestion window down to the Loss Window (one segment).
1513  * We will gradually open it again as we proceed.
1514  */
1515 void
1516 tcp_quench(inp, errno)
1517 	struct inpcb *inp;
1518 	int errno;
1519 {
1520 	struct tcpcb *tp = intotcpcb(inp);
1521 
1522 	if (tp)
1523 		tp->snd_cwnd = tp->t_segsz;
1524 }
1525 #endif
1526 
1527 #ifdef INET6
1528 void
1529 tcp6_quench(in6p, errno)
1530 	struct in6pcb *in6p;
1531 	int errno;
1532 {
1533 	struct tcpcb *tp = in6totcpcb(in6p);
1534 
1535 	if (tp)
1536 		tp->snd_cwnd = tp->t_segsz;
1537 }
1538 #endif
1539 
1540 #ifdef INET
1541 /*
1542  * Path MTU Discovery handlers.
1543  */
1544 void
1545 tcp_mtudisc_callback(faddr)
1546 	struct in_addr faddr;
1547 {
1548 #ifdef INET6
1549 	struct in6_addr in6;
1550 #endif
1551 
1552 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
1553 #ifdef INET6
1554 	memset(&in6, 0, sizeof(in6));
1555 	in6.s6_addr16[5] = 0xffff;
1556 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
1557 	tcp6_mtudisc_callback(&in6);
1558 #endif
1559 }
1560 
1561 /*
1562  * On receipt of path MTU corrections, flush old route and replace it
1563  * with the new one.  Retransmit all unacknowledged packets, to ensure
1564  * that all packets will be received.
1565  */
1566 void
1567 tcp_mtudisc(inp, errno)
1568 	struct inpcb *inp;
1569 	int errno;
1570 {
1571 	struct tcpcb *tp = intotcpcb(inp);
1572 	struct rtentry *rt = in_pcbrtentry(inp);
1573 
1574 	if (tp != 0) {
1575 		if (rt != 0) {
1576 			/*
1577 			 * If this was not a host route, remove and realloc.
1578 			 */
1579 			if ((rt->rt_flags & RTF_HOST) == 0) {
1580 				in_rtchange(inp, errno);
1581 				if ((rt = in_pcbrtentry(inp)) == 0)
1582 					return;
1583 			}
1584 
1585 			/*
1586 			 * Slow start out of the error condition.  We
1587 			 * use the MTU because we know it's smaller
1588 			 * than the previously transmitted segment.
1589 			 *
1590 			 * Note: This is more conservative than the
1591 			 * suggestion in draft-floyd-incr-init-win-03.
1592 			 */
1593 			if (rt->rt_rmx.rmx_mtu != 0)
1594 				tp->snd_cwnd =
1595 				    TCP_INITIAL_WINDOW(tcp_init_win,
1596 				    rt->rt_rmx.rmx_mtu);
1597 		}
1598 
1599 		/*
1600 		 * Resend unacknowledged packets.
1601 		 */
1602 		tp->snd_nxt = tp->snd_una;
1603 		tcp_output(tp);
1604 	}
1605 }
1606 #endif
1607 
1608 #ifdef INET6
1609 /*
1610  * Path MTU Discovery handlers.
1611  */
1612 void
1613 tcp6_mtudisc_callback(faddr)
1614 	struct in6_addr *faddr;
1615 {
1616 	struct sockaddr_in6 sin6;
1617 
1618 	bzero(&sin6, sizeof(sin6));
1619 	sin6.sin6_family = AF_INET6;
1620 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1621 	sin6.sin6_addr = *faddr;
1622 	(void) in6_pcbnotify(&tcb6, (struct sockaddr *)&sin6, 0,
1623 	    (struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
1624 }
1625 
1626 void
1627 tcp6_mtudisc(in6p, errno)
1628 	struct in6pcb *in6p;
1629 	int errno;
1630 {
1631 	struct tcpcb *tp = in6totcpcb(in6p);
1632 	struct rtentry *rt = in6_pcbrtentry(in6p);
1633 
1634 	if (tp != 0) {
1635 		if (rt != 0) {
1636 			/*
1637 			 * If this was not a host route, remove and realloc.
1638 			 */
1639 			if ((rt->rt_flags & RTF_HOST) == 0) {
1640 				in6_rtchange(in6p, errno);
1641 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1642 					return;
1643 			}
1644 
1645 			/*
1646 			 * Slow start out of the error condition.  We
1647 			 * use the MTU because we know it's smaller
1648 			 * than the previously transmitted segment.
1649 			 *
1650 			 * Note: This is more conservative than the
1651 			 * suggestion in draft-floyd-incr-init-win-03.
1652 			 */
1653 			if (rt->rt_rmx.rmx_mtu != 0)
1654 				tp->snd_cwnd =
1655 				    TCP_INITIAL_WINDOW(tcp_init_win,
1656 				    rt->rt_rmx.rmx_mtu);
1657 		}
1658 
1659 		/*
1660 		 * Resend unacknowledged packets.
1661 		 */
1662 		tp->snd_nxt = tp->snd_una;
1663 		tcp_output(tp);
1664 	}
1665 }
1666 #endif /* INET6 */
1667 
1668 /*
1669  * Compute the MSS to advertise to the peer.  Called only during
1670  * the 3-way handshake.  If we are the server (peer initiated
1671  * connection), we are called with a pointer to the interface
1672  * on which the SYN packet arrived.  If we are the client (we
1673  * initiated connection), we are called with a pointer to the
1674  * interface out which this connection should go.
1675  *
1676  * NOTE: Do not subtract IP option/extension header size nor IPsec
1677  * header size from MSS advertisement.  MSS option must hold the maximum
1678  * segment size we can accept, so it must always be:
1679  *	 max(if mtu) - ip header - tcp header
1680  */
1681 u_long
1682 tcp_mss_to_advertise(ifp, af)
1683 	const struct ifnet *ifp;
1684 	int af;
1685 {
1686 	extern u_long in_maxmtu;
1687 	u_long mss = 0;
1688 	u_long hdrsiz;
1689 
1690 	/*
1691 	 * In order to avoid defeating path MTU discovery on the peer,
1692 	 * we advertise the max MTU of all attached networks as our MSS,
1693 	 * per RFC 1191, section 3.1.
1694 	 *
1695 	 * We provide the option to advertise just the MTU of
1696 	 * the interface on which we hope this connection will
1697 	 * be receiving.  If we are responding to a SYN, we
1698 	 * will have a pretty good idea about this, but when
1699 	 * initiating a connection there is a bit more doubt.
1700 	 *
1701 	 * We also need to ensure that loopback has a large enough
1702 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1703 	 */
1704 
1705 	if (ifp != NULL)
1706 		switch (af) {
1707 		case AF_INET:
1708 			mss = ifp->if_mtu;
1709 			break;
1710 #ifdef INET6
1711 		case AF_INET6:
1712 			mss = IN6_LINKMTU(ifp);
1713 			break;
1714 #endif
1715 		}
1716 
1717 	if (tcp_mss_ifmtu == 0)
1718 		switch (af) {
1719 		case AF_INET:
1720 			mss = max(in_maxmtu, mss);
1721 			break;
1722 #ifdef INET6
1723 		case AF_INET6:
1724 			mss = max(in6_maxmtu, mss);
1725 			break;
1726 #endif
1727 		}
1728 
1729 	switch (af) {
1730 	case AF_INET:
1731 		hdrsiz = sizeof(struct ip);
1732 		break;
1733 #ifdef INET6
1734 	case AF_INET6:
1735 		hdrsiz = sizeof(struct ip6_hdr);
1736 		break;
1737 #endif
1738 	default:
1739 		hdrsiz = 0;
1740 		break;
1741 	}
1742 	hdrsiz += sizeof(struct tcphdr);
1743 	if (mss > hdrsiz)
1744 		mss -= hdrsiz;
1745 
1746 	mss = max(tcp_mssdflt, mss);
1747 	return (mss);
1748 }
1749 
1750 /*
1751  * Set connection variables based on the peer's advertised MSS.
1752  * We are passed the TCPCB for the actual connection.  If we
1753  * are the server, we are called by the compressed state engine
1754  * when the 3-way handshake is complete.  If we are the client,
1755  * we are called when we receive the SYN,ACK from the server.
1756  *
1757  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1758  * before this routine is called!
1759  */
1760 void
1761 tcp_mss_from_peer(tp, offer)
1762 	struct tcpcb *tp;
1763 	int offer;
1764 {
1765 	struct socket *so;
1766 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1767 	struct rtentry *rt;
1768 #endif
1769 	u_long bufsize;
1770 	int mss;
1771 
1772 #ifdef DIAGNOSTIC
1773 	if (tp->t_inpcb && tp->t_in6pcb)
1774 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
1775 #endif
1776 	so = NULL;
1777 	rt = NULL;
1778 #ifdef INET
1779 	if (tp->t_inpcb) {
1780 		so = tp->t_inpcb->inp_socket;
1781 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1782 		rt = in_pcbrtentry(tp->t_inpcb);
1783 #endif
1784 	}
1785 #endif
1786 #ifdef INET6
1787 	if (tp->t_in6pcb) {
1788 		so = tp->t_in6pcb->in6p_socket;
1789 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1790 		rt = in6_pcbrtentry(tp->t_in6pcb);
1791 #endif
1792 	}
1793 #endif
1794 
1795 	/*
1796 	 * As per RFC1122, use the default MSS value, unless they
1797 	 * sent us an offer.  Do not accept offers less than 32 bytes.
1798 	 */
1799 	mss = tcp_mssdflt;
1800 	if (offer)
1801 		mss = offer;
1802 	mss = max(mss, 32);		/* sanity */
1803 	tp->t_peermss = mss;
1804 	mss -= tcp_optlen(tp);
1805 #ifdef INET
1806 	if (tp->t_inpcb)
1807 		mss -= ip_optlen(tp->t_inpcb);
1808 #endif
1809 #ifdef INET6
1810 	if (tp->t_in6pcb)
1811 		mss -= ip6_optlen(tp->t_in6pcb);
1812 #endif
1813 
1814 	/*
1815 	 * If there's a pipesize, change the socket buffer to that size.
1816 	 * Make the socket buffer an integral number of MSS units.  If
1817 	 * the MSS is larger than the socket buffer, artificially decrease
1818 	 * the MSS.
1819 	 */
1820 #ifdef RTV_SPIPE
1821 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
1822 		bufsize = rt->rt_rmx.rmx_sendpipe;
1823 	else
1824 #endif
1825 		bufsize = so->so_snd.sb_hiwat;
1826 	if (bufsize < mss)
1827 		mss = bufsize;
1828 	else {
1829 		bufsize = roundup(bufsize, mss);
1830 		if (bufsize > sb_max)
1831 			bufsize = sb_max;
1832 		(void) sbreserve(&so->so_snd, bufsize);
1833 	}
1834 	tp->t_segsz = mss;
1835 
1836 #ifdef RTV_SSTHRESH
1837 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
1838 		/*
1839 		 * There's some sort of gateway or interface buffer
1840 		 * limit on the path.  Use this to set the slow
1841 		 * start threshold, but set the threshold to no less
1842 		 * than 2 * MSS.
1843 		 */
1844 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1845 	}
1846 #endif
1847 }
1848 
1849 /*
1850  * Processing necessary when a TCP connection is established.
1851  */
1852 void
1853 tcp_established(tp)
1854 	struct tcpcb *tp;
1855 {
1856 	struct socket *so;
1857 #ifdef RTV_RPIPE
1858 	struct rtentry *rt;
1859 #endif
1860 	u_long bufsize;
1861 
1862 #ifdef DIAGNOSTIC
1863 	if (tp->t_inpcb && tp->t_in6pcb)
1864 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
1865 #endif
1866 	so = NULL;
1867 	rt = NULL;
1868 #ifdef INET
1869 	if (tp->t_inpcb) {
1870 		so = tp->t_inpcb->inp_socket;
1871 #if defined(RTV_RPIPE)
1872 		rt = in_pcbrtentry(tp->t_inpcb);
1873 #endif
1874 	}
1875 #endif
1876 #ifdef INET6
1877 	if (tp->t_in6pcb) {
1878 		so = tp->t_in6pcb->in6p_socket;
1879 #if defined(RTV_RPIPE)
1880 		rt = in6_pcbrtentry(tp->t_in6pcb);
1881 #endif
1882 	}
1883 #endif
1884 
1885 	tp->t_state = TCPS_ESTABLISHED;
1886 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1887 
1888 #ifdef RTV_RPIPE
1889 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
1890 		bufsize = rt->rt_rmx.rmx_recvpipe;
1891 	else
1892 #endif
1893 		bufsize = so->so_rcv.sb_hiwat;
1894 	if (bufsize > tp->t_ourmss) {
1895 		bufsize = roundup(bufsize, tp->t_ourmss);
1896 		if (bufsize > sb_max)
1897 			bufsize = sb_max;
1898 		(void) sbreserve(&so->so_rcv, bufsize);
1899 	}
1900 }
1901 
1902 /*
1903  * Check if there's an initial rtt or rttvar.  Convert from the
1904  * route-table units to scaled multiples of the slow timeout timer.
1905  * Called only during the 3-way handshake.
1906  */
1907 void
1908 tcp_rmx_rtt(tp)
1909 	struct tcpcb *tp;
1910 {
1911 #ifdef RTV_RTT
1912 	struct rtentry *rt = NULL;
1913 	int rtt;
1914 
1915 #ifdef DIAGNOSTIC
1916 	if (tp->t_inpcb && tp->t_in6pcb)
1917 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
1918 #endif
1919 #ifdef INET
1920 	if (tp->t_inpcb)
1921 		rt = in_pcbrtentry(tp->t_inpcb);
1922 #endif
1923 #ifdef INET6
1924 	if (tp->t_in6pcb)
1925 		rt = in6_pcbrtentry(tp->t_in6pcb);
1926 #endif
1927 	if (rt == NULL)
1928 		return;
1929 
1930 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1931 		/*
1932 		 * XXX The lock bit for MTU indicates that the value
1933 		 * is also a minimum value; this is subject to time.
1934 		 */
1935 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1936 			TCPT_RANGESET(tp->t_rttmin,
1937 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
1938 			    TCPTV_MIN, TCPTV_REXMTMAX);
1939 		tp->t_srtt = rtt /
1940 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1941 		if (rt->rt_rmx.rmx_rttvar) {
1942 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1943 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
1944 				(TCP_RTTVAR_SHIFT + 2));
1945 		} else {
1946 			/* Default variation is +- 1 rtt */
1947 			tp->t_rttvar =
1948 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
1949 		}
1950 		TCPT_RANGESET(tp->t_rxtcur,
1951 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
1952 		    tp->t_rttmin, TCPTV_REXMTMAX);
1953 	}
1954 #endif
1955 }
1956 
1957 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
1958 #if NRND > 0
1959 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
1960 #endif
1961 
1962 /*
1963  * Get a new sequence value given a tcp control block
1964  */
1965 tcp_seq
1966 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
1967 {
1968 
1969 #ifdef INET
1970 	if (tp->t_inpcb != NULL) {
1971 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
1972 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
1973 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
1974 		    addin));
1975 	}
1976 #endif
1977 #ifdef INET6
1978 	if (tp->t_in6pcb != NULL) {
1979 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
1980 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
1981 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
1982 		    addin));
1983 	}
1984 #endif
1985 	/* Not possible. */
1986 	panic("tcp_new_iss");
1987 }
1988 
1989 /*
1990  * This routine actually generates a new TCP initial sequence number.
1991  */
1992 tcp_seq
1993 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
1994     size_t addrsz, tcp_seq addin)
1995 {
1996 	tcp_seq tcp_iss;
1997 
1998 #if NRND > 0
1999 	static int beenhere;
2000 
2001 	/*
2002 	 * If we haven't been here before, initialize our cryptographic
2003 	 * hash secret.
2004 	 */
2005 	if (beenhere == 0) {
2006 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
2007 		    RND_EXTRACT_ANY);
2008 		beenhere = 1;
2009 	}
2010 
2011 	if (tcp_do_rfc1948) {
2012 		MD5_CTX ctx;
2013 		u_int8_t hash[16];	/* XXX MD5 knowledge */
2014 
2015 		/*
2016 		 * Compute the base value of the ISS.  It is a hash
2017 		 * of (saddr, sport, daddr, dport, secret).
2018 		 */
2019 		MD5Init(&ctx);
2020 
2021 		MD5Update(&ctx, (u_char *) laddr, addrsz);
2022 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
2023 
2024 		MD5Update(&ctx, (u_char *) faddr, addrsz);
2025 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
2026 
2027 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
2028 
2029 		MD5Final(hash, &ctx);
2030 
2031 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
2032 
2033 		/*
2034 		 * Now increment our "timer", and add it in to
2035 		 * the computed value.
2036 		 *
2037 		 * XXX Use `addin'?
2038 		 * XXX TCP_ISSINCR too large to use?
2039 		 */
2040 		tcp_iss_seq += TCP_ISSINCR;
2041 #ifdef TCPISS_DEBUG
2042 		printf("ISS hash 0x%08x, ", tcp_iss);
2043 #endif
2044 		tcp_iss += tcp_iss_seq + addin;
2045 #ifdef TCPISS_DEBUG
2046 		printf("new ISS 0x%08x\n", tcp_iss);
2047 #endif
2048 	} else
2049 #endif /* NRND > 0 */
2050 	{
2051 		/*
2052 		 * Randomize.
2053 		 */
2054 #if NRND > 0
2055 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
2056 #else
2057 		tcp_iss = arc4random();
2058 #endif
2059 
2060 		/*
2061 		 * If we were asked to add some amount to a known value,
2062 		 * we will take a random value obtained above, mask off
2063 		 * the upper bits, and add in the known value.  We also
2064 		 * add in a constant to ensure that we are at least a
2065 		 * certain distance from the original value.
2066 		 *
2067 		 * This is used when an old connection is in timed wait
2068 		 * and we have a new one coming in, for instance.
2069 		 */
2070 		if (addin != 0) {
2071 #ifdef TCPISS_DEBUG
2072 			printf("Random %08x, ", tcp_iss);
2073 #endif
2074 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2075 			tcp_iss += addin + TCP_ISSINCR;
2076 #ifdef TCPISS_DEBUG
2077 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
2078 #endif
2079 		} else {
2080 			tcp_iss &= TCP_ISS_RANDOM_MASK;
2081 			tcp_iss += tcp_iss_seq;
2082 			tcp_iss_seq += TCP_ISSINCR;
2083 #ifdef TCPISS_DEBUG
2084 			printf("ISS %08x\n", tcp_iss);
2085 #endif
2086 		}
2087 	}
2088 
2089 	if (tcp_compat_42) {
2090 		/*
2091 		 * Limit it to the positive range for really old TCP
2092 		 * implementations.
2093 		 * Just AND off the top bit instead of checking if
2094 		 * is set first - saves a branch 50% of the time.
2095 		 */
2096 		tcp_iss &= 0x7fffffff;		/* XXX */
2097 	}
2098 
2099 	return (tcp_iss);
2100 }
2101 
2102 #ifdef IPSEC
2103 /* compute ESP/AH header size for TCP, including outer IP header. */
2104 size_t
2105 ipsec4_hdrsiz_tcp(tp)
2106 	struct tcpcb *tp;
2107 {
2108 	struct inpcb *inp;
2109 	size_t hdrsiz;
2110 
2111 	/* XXX mapped addr case (tp->t_in6pcb) */
2112 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
2113 		return 0;
2114 	switch (tp->t_family) {
2115 	case AF_INET:
2116 		/* XXX: should use currect direction. */
2117 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
2118 		break;
2119 	default:
2120 		hdrsiz = 0;
2121 		break;
2122 	}
2123 
2124 	return hdrsiz;
2125 }
2126 
2127 #ifdef INET6
2128 size_t
2129 ipsec6_hdrsiz_tcp(tp)
2130 	struct tcpcb *tp;
2131 {
2132 	struct in6pcb *in6p;
2133 	size_t hdrsiz;
2134 
2135 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
2136 		return 0;
2137 	switch (tp->t_family) {
2138 	case AF_INET6:
2139 		/* XXX: should use currect direction. */
2140 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
2141 		break;
2142 	case AF_INET:
2143 		/* mapped address case - tricky */
2144 	default:
2145 		hdrsiz = 0;
2146 		break;
2147 	}
2148 
2149 	return hdrsiz;
2150 }
2151 #endif
2152 #endif /*IPSEC*/
2153 
2154 /*
2155  * Determine the length of the TCP options for this connection.
2156  *
2157  * XXX:  What do we do for SACK, when we add that?  Just reserve
2158  *       all of the space?  Otherwise we can't exactly be incrementing
2159  *       cwnd by an amount that varies depending on the amount we last
2160  *       had to SACK!
2161  */
2162 
2163 u_int
2164 tcp_optlen(tp)
2165 	struct tcpcb *tp;
2166 {
2167 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
2168 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
2169 		return TCPOLEN_TSTAMP_APPA;
2170 	else
2171 		return 0;
2172 }
2173