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