xref: /openbsd-src/sys/netinet/tcp_usrreq.c (revision ff0e7be1ebbcc809ea8ad2b6dafe215824da9e46)
1 /*	$OpenBSD: tcp_usrreq.c,v 1.219 2023/05/23 09:16:16 jan Exp $	*/
2 /*	$NetBSD: tcp_usrreq.c,v 1.20 1996/02/13 23:44:16 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/protosw.h>
77 #include <sys/stat.h>
78 #include <sys/sysctl.h>
79 #include <sys/domain.h>
80 #include <sys/kernel.h>
81 #include <sys/pool.h>
82 #include <sys/proc.h>
83 
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/route.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_var.h>
90 #include <netinet/ip.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet/ip_var.h>
93 #include <netinet/tcp.h>
94 #include <netinet/tcp_fsm.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_timer.h>
97 #include <netinet/tcp_var.h>
98 #include <netinet/tcp_debug.h>
99 
100 #ifdef INET6
101 #include <netinet6/in6_var.h>
102 #endif
103 
104 #ifndef TCP_SENDSPACE
105 #define	TCP_SENDSPACE	1024*16
106 #endif
107 u_int	tcp_sendspace = TCP_SENDSPACE;
108 #ifndef TCP_RECVSPACE
109 #define	TCP_RECVSPACE	1024*16
110 #endif
111 u_int	tcp_recvspace = TCP_RECVSPACE;
112 u_int	tcp_autorcvbuf_inc = 16 * 1024;
113 
114 const struct pr_usrreqs tcp_usrreqs = {
115 	.pru_attach	= tcp_attach,
116 	.pru_detach	= tcp_detach,
117 	.pru_bind	= tcp_bind,
118 	.pru_listen	= tcp_listen,
119 	.pru_connect	= tcp_connect,
120 	.pru_accept	= tcp_accept,
121 	.pru_disconnect	= tcp_disconnect,
122 	.pru_shutdown	= tcp_shutdown,
123 	.pru_rcvd	= tcp_rcvd,
124 	.pru_send	= tcp_send,
125 	.pru_abort	= tcp_abort,
126 	.pru_sense	= tcp_sense,
127 	.pru_rcvoob	= tcp_rcvoob,
128 	.pru_sendoob	= tcp_sendoob,
129 	.pru_control	= in_control,
130 	.pru_sockaddr	= tcp_sockaddr,
131 	.pru_peeraddr	= tcp_peeraddr,
132 };
133 
134 #ifdef INET6
135 const struct pr_usrreqs tcp6_usrreqs = {
136 	.pru_attach	= tcp_attach,
137 	.pru_detach	= tcp_detach,
138 	.pru_bind	= tcp_bind,
139 	.pru_listen	= tcp_listen,
140 	.pru_connect	= tcp_connect,
141 	.pru_accept	= tcp_accept,
142 	.pru_disconnect	= tcp_disconnect,
143 	.pru_shutdown	= tcp_shutdown,
144 	.pru_rcvd	= tcp_rcvd,
145 	.pru_send	= tcp_send,
146 	.pru_abort	= tcp_abort,
147 	.pru_sense	= tcp_sense,
148 	.pru_rcvoob	= tcp_rcvoob,
149 	.pru_sendoob	= tcp_sendoob,
150 	.pru_control	= in6_control,
151 	.pru_sockaddr	= tcp_sockaddr,
152 	.pru_peeraddr	= tcp_peeraddr,
153 };
154 #endif
155 
156 const struct sysctl_bounded_args tcpctl_vars[] = {
157 	{ TCPCTL_RFC1323, &tcp_do_rfc1323, 0, 1 },
158 	{ TCPCTL_SACK, &tcp_do_sack, 0, 1 },
159 	{ TCPCTL_MSSDFLT, &tcp_mssdflt, TCP_MSS, 65535 },
160 	{ TCPCTL_RSTPPSLIMIT, &tcp_rst_ppslim, 1, 1000 * 1000 },
161 	{ TCPCTL_ACK_ON_PUSH, &tcp_ack_on_push, 0, 1 },
162 #ifdef TCP_ECN
163 	{ TCPCTL_ECN, &tcp_do_ecn, 0, 1 },
164 #endif
165 	{ TCPCTL_SYN_CACHE_LIMIT, &tcp_syn_cache_limit, 1, 1000 * 1000 },
166 	{ TCPCTL_SYN_BUCKET_LIMIT, &tcp_syn_bucket_limit, 1, INT_MAX },
167 	{ TCPCTL_RFC3390, &tcp_do_rfc3390, 0, 2 },
168 	{ TCPCTL_ALWAYS_KEEPALIVE, &tcp_always_keepalive, 0, 1 },
169 	{ TCPCTL_TSO, &tcp_do_tso, 0, 1 },
170 };
171 
172 struct	inpcbtable tcbtable;
173 
174 int	tcp_fill_info(struct tcpcb *, struct socket *, struct mbuf *);
175 int	tcp_ident(void *, size_t *, void *, size_t, int);
176 
177 static inline int tcp_sogetpcb(struct socket *, struct inpcb **,
178                       struct tcpcb **);
179 
180 static inline int
181 tcp_sogetpcb(struct socket *so, struct inpcb **rinp, struct tcpcb **rtp)
182 {
183 	struct inpcb *inp;
184 	struct tcpcb *tp;
185 
186 	/*
187 	 * When a TCP is attached to a socket, then there will be
188 	 * a (struct inpcb) pointed at by the socket, and this
189 	 * structure will point at a subsidiary (struct tcpcb).
190 	 */
191 	if ((inp = sotoinpcb(so)) == NULL || (tp = intotcpcb(inp)) == NULL) {
192 		if (so->so_error)
193 			return so->so_error;
194 		return EINVAL;
195 	}
196 
197 	*rinp = inp;
198 	*rtp = tp;
199 
200 	return 0;
201 }
202 
203 /*
204  * Export internal TCP state information via a struct tcp_info without
205  * leaking any sensitive information. Sequence numbers are reported
206  * relative to the initial sequence number.
207  */
208 int
209 tcp_fill_info(struct tcpcb *tp, struct socket *so, struct mbuf *m)
210 {
211 	struct proc *p = curproc;
212 	struct tcp_info *ti;
213 	u_int t = 1000;		/* msec => usec */
214 	uint32_t now;
215 
216 	if (sizeof(*ti) > MLEN) {
217 		MCLGETL(m, M_WAITOK, sizeof(*ti));
218 		if (!ISSET(m->m_flags, M_EXT))
219 			return ENOMEM;
220 	}
221 	ti = mtod(m, struct tcp_info *);
222 	m->m_len = sizeof(*ti);
223 	memset(ti, 0, sizeof(*ti));
224 	now = tcp_now();
225 
226 	ti->tcpi_state = tp->t_state;
227 	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
228 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
229 	if (tp->t_flags & TF_SACK_PERMIT)
230 		ti->tcpi_options |= TCPI_OPT_SACK;
231 	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
232 		ti->tcpi_options |= TCPI_OPT_WSCALE;
233 		ti->tcpi_snd_wscale = tp->snd_scale;
234 		ti->tcpi_rcv_wscale = tp->rcv_scale;
235 	}
236 #ifdef TCP_ECN
237 	if (tp->t_flags & TF_ECN_PERMIT)
238 		ti->tcpi_options |= TCPI_OPT_ECN;
239 #endif
240 
241 	ti->tcpi_rto = tp->t_rxtcur * t;
242 	ti->tcpi_snd_mss = tp->t_maxseg;
243 	ti->tcpi_rcv_mss = tp->t_peermss;
244 
245 	ti->tcpi_last_data_sent = (now - tp->t_sndtime) * t;
246 	ti->tcpi_last_ack_sent = (now - tp->t_sndacktime) * t;
247 	ti->tcpi_last_data_recv = (now - tp->t_rcvtime) * t;
248 	ti->tcpi_last_ack_recv = (now - tp->t_rcvacktime) * t;
249 
250 	ti->tcpi_rtt = ((uint64_t)tp->t_srtt * t) >>
251 	    (TCP_RTT_SHIFT + TCP_RTT_BASE_SHIFT);
252 	ti->tcpi_rttvar = ((uint64_t)tp->t_rttvar * t) >>
253 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT);
254 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
255 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
256 
257 	ti->tcpi_rcv_space = tp->rcv_wnd;
258 
259 	/*
260 	 * Provide only minimal information for unprivileged processes.
261 	 */
262 	if (suser(p) != 0)
263 		return 0;
264 
265 	/* FreeBSD-specific extension fields for tcp_info.  */
266 	ti->tcpi_snd_wnd = tp->snd_wnd;
267 	ti->tcpi_snd_nxt = tp->snd_nxt - tp->iss;
268 	ti->tcpi_rcv_nxt = tp->rcv_nxt - tp->irs;
269 	/* missing tcpi_toe_tid */
270 	ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
271 	ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
272 	ti->tcpi_snd_zerowin = tp->t_sndzerowin;
273 
274 	/* OpenBSD extensions */
275 	ti->tcpi_rttmin = tp->t_rttmin * t;
276 	ti->tcpi_max_sndwnd = tp->max_sndwnd;
277 	ti->tcpi_rcv_adv = tp->rcv_adv - tp->irs;
278 	ti->tcpi_rcv_up = tp->rcv_up - tp->irs;
279 	ti->tcpi_snd_una = tp->snd_una - tp->iss;
280 	ti->tcpi_snd_up = tp->snd_up - tp->iss;
281 	ti->tcpi_snd_wl1 = tp->snd_wl1 - tp->iss;
282 	ti->tcpi_snd_wl2 = tp->snd_wl2 - tp->iss;
283 	ti->tcpi_snd_max = tp->snd_max - tp->iss;
284 
285 	ti->tcpi_ts_recent = tp->ts_recent; /* XXX value from the wire */
286 	ti->tcpi_ts_recent_age = (now - tp->ts_recent_age) * t;
287 	ti->tcpi_rfbuf_cnt = tp->rfbuf_cnt;
288 	ti->tcpi_rfbuf_ts = (now - tp->rfbuf_ts) * t;
289 
290 	ti->tcpi_so_rcv_sb_cc = so->so_rcv.sb_cc;
291 	ti->tcpi_so_rcv_sb_hiwat = so->so_rcv.sb_hiwat;
292 	ti->tcpi_so_rcv_sb_lowat = so->so_rcv.sb_lowat;
293 	ti->tcpi_so_rcv_sb_wat = so->so_rcv.sb_wat;
294 	ti->tcpi_so_snd_sb_cc = so->so_snd.sb_cc;
295 	ti->tcpi_so_snd_sb_hiwat = so->so_snd.sb_hiwat;
296 	ti->tcpi_so_snd_sb_lowat = so->so_snd.sb_lowat;
297 	ti->tcpi_so_snd_sb_wat = so->so_snd.sb_wat;
298 
299 	return 0;
300 }
301 
302 int
303 tcp_ctloutput(int op, struct socket *so, int level, int optname,
304     struct mbuf *m)
305 {
306 	int error = 0;
307 	struct inpcb *inp;
308 	struct tcpcb *tp;
309 	int i;
310 
311 	inp = sotoinpcb(so);
312 	if (inp == NULL)
313 		return (ECONNRESET);
314 	if (level != IPPROTO_TCP) {
315 		switch (so->so_proto->pr_domain->dom_family) {
316 #ifdef INET6
317 		case PF_INET6:
318 			error = ip6_ctloutput(op, so, level, optname, m);
319 			break;
320 #endif /* INET6 */
321 		case PF_INET:
322 			error = ip_ctloutput(op, so, level, optname, m);
323 			break;
324 		default:
325 			error = EAFNOSUPPORT;	/*?*/
326 			break;
327 		}
328 		return (error);
329 	}
330 	tp = intotcpcb(inp);
331 
332 	switch (op) {
333 
334 	case PRCO_SETOPT:
335 		switch (optname) {
336 
337 		case TCP_NODELAY:
338 			if (m == NULL || m->m_len < sizeof (int))
339 				error = EINVAL;
340 			else if (*mtod(m, int *))
341 				tp->t_flags |= TF_NODELAY;
342 			else
343 				tp->t_flags &= ~TF_NODELAY;
344 			break;
345 
346 		case TCP_NOPUSH:
347 			if (m == NULL || m->m_len < sizeof (int))
348 				error = EINVAL;
349 			else if (*mtod(m, int *))
350 				tp->t_flags |= TF_NOPUSH;
351 			else if (tp->t_flags & TF_NOPUSH) {
352 				tp->t_flags &= ~TF_NOPUSH;
353 				if (TCPS_HAVEESTABLISHED(tp->t_state))
354 					error = tcp_output(tp);
355 			}
356 			break;
357 
358 		case TCP_MAXSEG:
359 			if (m == NULL || m->m_len < sizeof (int)) {
360 				error = EINVAL;
361 				break;
362 			}
363 
364 			i = *mtod(m, int *);
365 			if (i > 0 && i <= tp->t_maxseg)
366 				tp->t_maxseg = i;
367 			else
368 				error = EINVAL;
369 			break;
370 
371 		case TCP_SACK_ENABLE:
372 			if (m == NULL || m->m_len < sizeof (int)) {
373 				error = EINVAL;
374 				break;
375 			}
376 
377 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
378 				error = EPERM;
379 				break;
380 			}
381 
382 			if (tp->t_flags & TF_SIGNATURE) {
383 				error = EPERM;
384 				break;
385 			}
386 
387 			if (*mtod(m, int *))
388 				tp->sack_enable = 1;
389 			else
390 				tp->sack_enable = 0;
391 			break;
392 #ifdef TCP_SIGNATURE
393 		case TCP_MD5SIG:
394 			if (m == NULL || m->m_len < sizeof (int)) {
395 				error = EINVAL;
396 				break;
397 			}
398 
399 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
400 				error = EPERM;
401 				break;
402 			}
403 
404 			if (*mtod(m, int *)) {
405 				tp->t_flags |= TF_SIGNATURE;
406 				tp->sack_enable = 0;
407 			} else
408 				tp->t_flags &= ~TF_SIGNATURE;
409 			break;
410 #endif /* TCP_SIGNATURE */
411 		default:
412 			error = ENOPROTOOPT;
413 			break;
414 		}
415 		break;
416 
417 	case PRCO_GETOPT:
418 		switch (optname) {
419 		case TCP_NODELAY:
420 			m->m_len = sizeof(int);
421 			*mtod(m, int *) = tp->t_flags & TF_NODELAY;
422 			break;
423 		case TCP_NOPUSH:
424 			m->m_len = sizeof(int);
425 			*mtod(m, int *) = tp->t_flags & TF_NOPUSH;
426 			break;
427 		case TCP_MAXSEG:
428 			m->m_len = sizeof(int);
429 			*mtod(m, int *) = tp->t_maxseg;
430 			break;
431 		case TCP_SACK_ENABLE:
432 			m->m_len = sizeof(int);
433 			*mtod(m, int *) = tp->sack_enable;
434 			break;
435 		case TCP_INFO:
436 			error = tcp_fill_info(tp, so, m);
437 			break;
438 #ifdef TCP_SIGNATURE
439 		case TCP_MD5SIG:
440 			m->m_len = sizeof(int);
441 			*mtod(m, int *) = tp->t_flags & TF_SIGNATURE;
442 			break;
443 #endif
444 		default:
445 			error = ENOPROTOOPT;
446 			break;
447 		}
448 		break;
449 	}
450 	return (error);
451 }
452 
453 /*
454  * Attach TCP protocol to socket, allocating
455  * internet protocol control block, tcp control block,
456  * buffer space, and entering LISTEN state to accept connections.
457  */
458 int
459 tcp_attach(struct socket *so, int proto, int wait)
460 {
461 	struct tcpcb *tp;
462 	struct inpcb *inp;
463 	int error;
464 
465 	if (so->so_pcb)
466 		return EISCONN;
467 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0 ||
468 	    sbcheckreserve(so->so_snd.sb_wat, tcp_sendspace) ||
469 	    sbcheckreserve(so->so_rcv.sb_wat, tcp_recvspace)) {
470 		error = soreserve(so, tcp_sendspace, tcp_recvspace);
471 		if (error)
472 			return (error);
473 	}
474 
475 	NET_ASSERT_LOCKED();
476 	error = in_pcballoc(so, &tcbtable, wait);
477 	if (error)
478 		return (error);
479 	inp = sotoinpcb(so);
480 	tp = tcp_newtcpcb(inp, wait);
481 	if (tp == NULL) {
482 		unsigned int nofd = so->so_state & SS_NOFDREF;	/* XXX */
483 
484 		so->so_state &= ~SS_NOFDREF;	/* don't free the socket yet */
485 		in_pcbdetach(inp);
486 		so->so_state |= nofd;
487 		return (ENOBUFS);
488 	}
489 	tp->t_state = TCPS_CLOSED;
490 #ifdef INET6
491 	/* we disallow IPv4 mapped address completely. */
492 	if (inp->inp_flags & INP_IPV6)
493 		tp->pf = PF_INET6;
494 	else
495 		tp->pf = PF_INET;
496 #else
497 	tp->pf = PF_INET;
498 #endif
499 	if ((so->so_options & SO_LINGER) && so->so_linger == 0)
500 		so->so_linger = TCP_LINGERTIME;
501 
502 	if (so->so_options & SO_DEBUG)
503 		tcp_trace(TA_USER, TCPS_CLOSED, tp, tp, NULL, PRU_ATTACH, 0);
504 	return (0);
505 }
506 
507 int
508 tcp_detach(struct socket *so)
509 {
510 	struct inpcb *inp;
511 	struct tcpcb *otp = NULL, *tp;
512 	int error = 0;
513 	short ostate;
514 
515 	soassertlocked(so);
516 
517 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
518 		return (error);
519 
520 	if (so->so_options & SO_DEBUG) {
521 		otp = tp;
522 		ostate = tp->t_state;
523 	}
524 
525 	/*
526 	 * Detach the TCP protocol from the socket.
527 	 * If the protocol state is non-embryonic, then can't
528 	 * do this directly: have to initiate a PRU_DISCONNECT,
529 	 * which may finish later; embryonic TCB's can just
530 	 * be discarded here.
531 	 */
532 	tp = tcp_dodisconnect(tp);
533 
534 	if (otp)
535 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_DETACH, 0);
536 	return (error);
537 }
538 
539 /*
540  * Give the socket an address.
541  */
542 int
543 tcp_bind(struct socket *so, struct mbuf *nam, struct proc *p)
544 {
545 	struct inpcb *inp;
546 	struct tcpcb *tp;
547 	int error;
548 	short ostate;
549 
550 	soassertlocked(so);
551 
552 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
553 		return (error);
554 
555 	if (so->so_options & SO_DEBUG)
556 		ostate = tp->t_state;
557 
558 	error = in_pcbbind(inp, nam, p);
559 
560 	if (so->so_options & SO_DEBUG)
561 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_BIND, 0);
562 	return (error);
563 }
564 
565 /*
566  * Prepare to accept connections.
567  */
568 int
569 tcp_listen(struct socket *so)
570 {
571 	struct inpcb *inp;
572 	struct tcpcb *tp, *otp = NULL;
573 	int error;
574 	short ostate;
575 
576 	soassertlocked(so);
577 
578 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
579 		return (error);
580 
581 	if (so->so_options & SO_DEBUG) {
582 		otp = tp;
583 		ostate = tp->t_state;
584 	}
585 
586 	if (inp->inp_lport == 0)
587 		if ((error = in_pcbbind(inp, NULL, curproc)))
588 			goto out;
589 
590 	/*
591 	 * If the in_pcbbind() above is called, the tp->pf
592 	 * should still be whatever it was before.
593 	 */
594 	tp->t_state = TCPS_LISTEN;
595 
596 out:
597 	if (otp)
598 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_LISTEN, 0);
599 	return (error);
600 }
601 
602 /*
603  * Initiate connection to peer.
604  * Create a template for use in transmissions on this connection.
605  * Enter SYN_SENT state, and mark socket as connecting.
606  * Start keep-alive timer, and seed output sequence space.
607  * Send initial segment on connection.
608  */
609 int
610 tcp_connect(struct socket *so, struct mbuf *nam)
611 {
612 	struct inpcb *inp;
613 	struct tcpcb *tp, *otp = NULL;
614 	int error;
615 	short ostate;
616 
617 	soassertlocked(so);
618 
619 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
620 		return (error);
621 
622 	if (so->so_options & SO_DEBUG) {
623 		otp = tp;
624 		ostate = tp->t_state;
625 	}
626 
627 #ifdef INET6
628 	if (inp->inp_flags & INP_IPV6) {
629 		struct sockaddr_in6 *sin6;
630 
631 		if ((error = in6_nam2sin6(nam, &sin6)))
632 			goto out;
633 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
634 		    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
635 			error = EINVAL;
636 			goto out;
637 		}
638 		error = in6_pcbconnect(inp, nam);
639 	} else
640 #endif /* INET6 */
641 	{
642 		struct sockaddr_in *sin;
643 
644 		if ((error = in_nam2sin(nam, &sin)))
645 			goto out;
646 		if ((sin->sin_addr.s_addr == INADDR_ANY) ||
647 		    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
648 		    IN_MULTICAST(sin->sin_addr.s_addr) ||
649 		    in_broadcast(sin->sin_addr, inp->inp_rtableid)) {
650 			error = EINVAL;
651 			goto out;
652 		}
653 		error = in_pcbconnect(inp, nam);
654 	}
655 	if (error)
656 		goto out;
657 
658 	tp->t_template = tcp_template(tp);
659 	if (tp->t_template == 0) {
660 		in_pcbdisconnect(inp);
661 		error = ENOBUFS;
662 		goto out;
663 	}
664 
665 	so->so_state |= SS_CONNECTOUT;
666 
667 	/* Compute window scaling to request.  */
668 	tcp_rscale(tp, sb_max);
669 
670 	soisconnecting(so);
671 	tcpstat_inc(tcps_connattempt);
672 	tp->t_state = TCPS_SYN_SENT;
673 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcptv_keep_init);
674 	tcp_set_iss_tsm(tp);
675 	tcp_sendseqinit(tp);
676 	tp->snd_last = tp->snd_una;
677 	error = tcp_output(tp);
678 
679 out:
680 	if (otp)
681 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_CONNECT, 0);
682 	return (error);
683 }
684 
685 /*
686  * Accept a connection.  Essentially all the work is done at higher
687  * levels; just return the address of the peer, storing through addr.
688  */
689 int
690 tcp_accept(struct socket *so, struct mbuf *nam)
691 {
692 	struct inpcb *inp;
693 	struct tcpcb *tp;
694 	int error;
695 	short ostate;
696 
697 	soassertlocked(so);
698 
699 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
700 		return (error);
701 
702 	if (so->so_options & SO_DEBUG)
703 		ostate = tp->t_state;
704 
705 #ifdef INET6
706 	if (inp->inp_flags & INP_IPV6)
707 		in6_setpeeraddr(inp, nam);
708 	else
709 #endif
710 		in_setpeeraddr(inp, nam);
711 
712 	if (so->so_options & SO_DEBUG)
713 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_ACCEPT, 0);
714 	return (error);
715 }
716 
717 /*
718  * Initiate disconnect from peer.
719  * If connection never passed embryonic stage, just drop;
720  * else if don't need to let data drain, then can just drop anyways,
721  * else have to begin TCP shutdown process: mark socket disconnecting,
722  * drain unread data, state switch to reflect user close, and
723  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
724  * when peer sends FIN and acks ours.
725  *
726  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
727  */
728 int
729 tcp_disconnect(struct socket *so)
730 {
731 	struct inpcb *inp;
732 	struct tcpcb *tp, *otp = NULL;
733 	int error;
734 	short ostate;
735 
736 	soassertlocked(so);
737 
738 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
739 		return (error);
740 
741 	if (so->so_options & SO_DEBUG) {
742 		otp = tp;
743 		ostate = tp->t_state;
744 	}
745 
746 	tp = tcp_dodisconnect(tp);
747 
748 	if (otp)
749 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_DISCONNECT, 0);
750 	return (0);
751 }
752 
753 /*
754  * Mark the connection as being incapable of further output.
755  */
756 int
757 tcp_shutdown(struct socket *so)
758 {
759 	struct inpcb *inp;
760 	struct tcpcb *tp, *otp = NULL;
761 	int error;
762 	short ostate;
763 
764 	soassertlocked(so);
765 
766 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
767 		return (error);
768 
769 	if (so->so_options & SO_DEBUG) {
770 		otp = tp;
771 		ostate = tp->t_state;
772 	}
773 
774 	if (so->so_snd.sb_state & SS_CANTSENDMORE)
775 		goto out;
776 
777 	socantsendmore(so);
778 	tp = tcp_usrclosed(tp);
779 	if (tp)
780 		error = tcp_output(tp);
781 
782 out:
783 	if (otp)
784 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_SHUTDOWN, 0);
785 	return (error);
786 }
787 
788 /*
789  * After a receive, possibly send window update to peer.
790  */
791 void
792 tcp_rcvd(struct socket *so)
793 {
794 	struct inpcb *inp;
795 	struct tcpcb *tp;
796 	short ostate;
797 
798 	soassertlocked(so);
799 
800 	if (tcp_sogetpcb(so, &inp, &tp))
801 		return;
802 
803 	if (so->so_options & SO_DEBUG)
804 		ostate = tp->t_state;
805 
806 	/*
807 	 * soreceive() calls this function when a user receives
808 	 * ancillary data on a listening socket. We don't call
809 	 * tcp_output in such a case, since there is no header
810 	 * template for a listening socket and hence the kernel
811 	 * will panic.
812 	 */
813 	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) != 0)
814 		(void) tcp_output(tp);
815 
816 	if (so->so_options & SO_DEBUG)
817 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_RCVD, 0);
818 }
819 
820 /*
821  * Do a send by putting data in output queue and updating urgent
822  * marker if URG set.  Possibly send more data.
823  */
824 int
825 tcp_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
826     struct mbuf *control)
827 {
828 	struct inpcb *inp;
829 	struct tcpcb *tp;
830 	int error;
831 	short ostate;
832 
833 	soassertlocked(so);
834 
835 	if (control && control->m_len) {
836 		error = EINVAL;
837 		goto out;
838 	}
839 
840 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
841 		goto out;
842 
843 	if (so->so_options & SO_DEBUG)
844 		ostate = tp->t_state;
845 
846 	sbappendstream(so, &so->so_snd, m);
847 	m = NULL;
848 
849 	error = tcp_output(tp);
850 
851 	if (so->so_options & SO_DEBUG)
852 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_SEND, 0);
853 
854 out:
855 	m_freem(control);
856 	m_freem(m);
857 
858 	return (error);
859 }
860 
861 /*
862  * Abort the TCP.
863  */
864 void
865 tcp_abort(struct socket *so)
866 {
867 	struct inpcb *inp;
868 	struct tcpcb *tp, *otp = NULL;
869 	short ostate;
870 
871 	soassertlocked(so);
872 
873 	if (tcp_sogetpcb(so, &inp, &tp))
874 		return;
875 
876 	if (so->so_options & SO_DEBUG) {
877 		otp = tp;
878 		ostate = tp->t_state;
879 	}
880 
881 	tp = tcp_drop(tp, ECONNABORTED);
882 
883 	if (otp)
884 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_ABORT, 0);
885 }
886 
887 int
888 tcp_sense(struct socket *so, struct stat *ub)
889 {
890 	struct inpcb *inp;
891 	struct tcpcb *tp;
892 	int error;
893 
894 	soassertlocked(so);
895 
896 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
897 		return (error);
898 
899 	ub->st_blksize = so->so_snd.sb_hiwat;
900 
901 	if (so->so_options & SO_DEBUG)
902 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_SENSE, 0);
903 	return (0);
904 }
905 
906 int
907 tcp_rcvoob(struct socket *so, struct mbuf *m, int flags)
908 {
909 	struct inpcb *inp;
910 	struct tcpcb *tp;
911 	int error;
912 
913 	soassertlocked(so);
914 
915 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
916 		return (error);
917 
918 	if ((so->so_oobmark == 0 &&
919 	    (so->so_rcv.sb_state & SS_RCVATMARK) == 0) ||
920 	    so->so_options & SO_OOBINLINE ||
921 	    tp->t_oobflags & TCPOOB_HADDATA) {
922 		error = EINVAL;
923 		goto out;
924 	}
925 	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
926 		error = EWOULDBLOCK;
927 		goto out;
928 	}
929 	m->m_len = 1;
930 	*mtod(m, caddr_t) = tp->t_iobc;
931 	if ((flags & MSG_PEEK) == 0)
932 		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
933 out:
934 	if (so->so_options & SO_DEBUG)
935 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_RCVOOB, 0);
936 	return (error);
937 }
938 
939 int
940 tcp_sendoob(struct socket *so, struct mbuf *m, struct mbuf *nam,
941     struct mbuf *control)
942 {
943 	struct inpcb *inp;
944 	struct tcpcb *tp;
945 	int error;
946 	short ostate;
947 
948 	soassertlocked(so);
949 
950 	if (control && control->m_len) {
951 		error = EINVAL;
952 		goto release;
953 	}
954 
955 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
956 		goto release;
957 
958 	if (so->so_options & SO_DEBUG)
959 		ostate = tp->t_state;
960 
961 	if (sbspace(so, &so->so_snd) < -512) {
962 		error = ENOBUFS;
963 		goto out;
964 	}
965 
966 	/*
967 	 * According to RFC961 (Assigned Protocols),
968 	 * the urgent pointer points to the last octet
969 	 * of urgent data.  We continue, however,
970 	 * to consider it to indicate the first octet
971 	 * of data past the urgent section.
972 	 * Otherwise, snd_up should be one lower.
973 	 */
974 	sbappendstream(so, &so->so_snd, m);
975 	m = NULL;
976 	tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
977 	tp->t_force = 1;
978 	error = tcp_output(tp);
979 	tp->t_force = 0;
980 
981 out:
982 	if (so->so_options & SO_DEBUG)
983 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_SENDOOB, 0);
984 
985 release:
986 	m_freem(control);
987 	m_freem(m);
988 
989 	return (error);
990 }
991 
992 int
993 tcp_sockaddr(struct socket *so, struct mbuf *nam)
994 {
995 	struct inpcb *inp;
996 	struct tcpcb *tp;
997 	int error;
998 
999 	soassertlocked(so);
1000 
1001 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
1002 		return (error);
1003 
1004 #ifdef INET6
1005 	if (inp->inp_flags & INP_IPV6)
1006 		in6_setsockaddr(inp, nam);
1007 	else
1008 #endif
1009 		in_setsockaddr(inp, nam);
1010 
1011 	if (so->so_options & SO_DEBUG)
1012 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL,
1013 		    PRU_SOCKADDR, 0);
1014 	return (0);
1015 }
1016 
1017 int
1018 tcp_peeraddr(struct socket *so, struct mbuf *nam)
1019 {
1020 	struct inpcb *inp;
1021 	struct tcpcb *tp;
1022 	int error;
1023 
1024 	soassertlocked(so);
1025 
1026 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
1027 		return (error);
1028 
1029 #ifdef INET6
1030 	if (inp->inp_flags & INP_IPV6)
1031 		in6_setpeeraddr(inp, nam);
1032 	else
1033 #endif
1034 		in_setpeeraddr(inp, nam);
1035 
1036 	if (so->so_options & SO_DEBUG)
1037 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL,
1038 		    PRU_PEERADDR, 0);
1039 	return (0);
1040 }
1041 
1042 /*
1043  * Initiate (or continue) disconnect.
1044  * If embryonic state, just send reset (once).
1045  * If in ``let data drain'' option and linger null, just drop.
1046  * Otherwise (hard), mark socket disconnecting and drop
1047  * current input data; switch states based on user close, and
1048  * send segment to peer (with FIN).
1049  */
1050 struct tcpcb *
1051 tcp_dodisconnect(struct tcpcb *tp)
1052 {
1053 	struct socket *so = tp->t_inpcb->inp_socket;
1054 
1055 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
1056 		tp = tcp_close(tp);
1057 	else if ((so->so_options & SO_LINGER) && so->so_linger == 0)
1058 		tp = tcp_drop(tp, 0);
1059 	else {
1060 		soisdisconnecting(so);
1061 		sbflush(so, &so->so_rcv);
1062 		tp = tcp_usrclosed(tp);
1063 		if (tp)
1064 			(void) tcp_output(tp);
1065 	}
1066 	return (tp);
1067 }
1068 
1069 /*
1070  * User issued close, and wish to trail through shutdown states:
1071  * if never received SYN, just forget it.  If got a SYN from peer,
1072  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1073  * If already got a FIN from peer, then almost done; go to LAST_ACK
1074  * state.  In all other cases, have already sent FIN to peer (e.g.
1075  * after PRU_SHUTDOWN), and just have to play tedious game waiting
1076  * for peer to send FIN or not respond to keep-alives, etc.
1077  * We can let the user exit from the close as soon as the FIN is acked.
1078  */
1079 struct tcpcb *
1080 tcp_usrclosed(struct tcpcb *tp)
1081 {
1082 
1083 	switch (tp->t_state) {
1084 
1085 	case TCPS_CLOSED:
1086 	case TCPS_LISTEN:
1087 	case TCPS_SYN_SENT:
1088 		tp->t_state = TCPS_CLOSED;
1089 		tp = tcp_close(tp);
1090 		break;
1091 
1092 	case TCPS_SYN_RECEIVED:
1093 	case TCPS_ESTABLISHED:
1094 		tp->t_state = TCPS_FIN_WAIT_1;
1095 		break;
1096 
1097 	case TCPS_CLOSE_WAIT:
1098 		tp->t_state = TCPS_LAST_ACK;
1099 		break;
1100 	}
1101 	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1102 		soisdisconnected(tp->t_inpcb->inp_socket);
1103 		/*
1104 		 * If we are in FIN_WAIT_2, we arrived here because the
1105 		 * application did a shutdown of the send side.  Like the
1106 		 * case of a transition from FIN_WAIT_1 to FIN_WAIT_2 after
1107 		 * a full close, we start a timer to make sure sockets are
1108 		 * not left in FIN_WAIT_2 forever.
1109 		 */
1110 		if (tp->t_state == TCPS_FIN_WAIT_2)
1111 			TCP_TIMER_ARM(tp, TCPT_2MSL, tcp_maxidle);
1112 	}
1113 	return (tp);
1114 }
1115 
1116 /*
1117  * Look up a socket for ident or tcpdrop, ...
1118  */
1119 int
1120 tcp_ident(void *oldp, size_t *oldlenp, void *newp, size_t newlen, int dodrop)
1121 {
1122 	int error = 0;
1123 	struct tcp_ident_mapping tir;
1124 	struct inpcb *inp;
1125 	struct tcpcb *tp = NULL;
1126 	struct sockaddr_in *fin, *lin;
1127 #ifdef INET6
1128 	struct sockaddr_in6 *fin6, *lin6;
1129 	struct in6_addr f6, l6;
1130 #endif
1131 
1132 	NET_ASSERT_LOCKED();
1133 
1134 	if (dodrop) {
1135 		if (oldp != NULL || *oldlenp != 0)
1136 			return (EINVAL);
1137 		if (newp == NULL)
1138 			return (EPERM);
1139 		if (newlen < sizeof(tir))
1140 			return (ENOMEM);
1141 		if ((error = copyin(newp, &tir, sizeof (tir))) != 0 )
1142 			return (error);
1143 	} else {
1144 		if (oldp == NULL)
1145 			return (EINVAL);
1146 		if (*oldlenp < sizeof(tir))
1147 			return (ENOMEM);
1148 		if (newp != NULL || newlen != 0)
1149 			return (EINVAL);
1150 		if ((error = copyin(oldp, &tir, sizeof (tir))) != 0 )
1151 			return (error);
1152 	}
1153 	switch (tir.faddr.ss_family) {
1154 #ifdef INET6
1155 	case AF_INET6:
1156 		fin6 = (struct sockaddr_in6 *)&tir.faddr;
1157 		error = in6_embedscope(&f6, fin6, NULL);
1158 		if (error)
1159 			return EINVAL;	/*?*/
1160 		lin6 = (struct sockaddr_in6 *)&tir.laddr;
1161 		error = in6_embedscope(&l6, lin6, NULL);
1162 		if (error)
1163 			return EINVAL;	/*?*/
1164 		break;
1165 #endif
1166 	case AF_INET:
1167 		fin = (struct sockaddr_in *)&tir.faddr;
1168 		lin = (struct sockaddr_in *)&tir.laddr;
1169 		break;
1170 	default:
1171 		return (EINVAL);
1172 	}
1173 
1174 	switch (tir.faddr.ss_family) {
1175 #ifdef INET6
1176 	case AF_INET6:
1177 		inp = in6_pcblookup(&tcbtable, &f6,
1178 		    fin6->sin6_port, &l6, lin6->sin6_port, tir.rdomain);
1179 		break;
1180 #endif
1181 	case AF_INET:
1182 		inp = in_pcblookup(&tcbtable, fin->sin_addr,
1183 		    fin->sin_port, lin->sin_addr, lin->sin_port, tir.rdomain);
1184 		break;
1185 	default:
1186 		unhandled_af(tir.faddr.ss_family);
1187 	}
1188 
1189 	if (dodrop) {
1190 		if (inp && (tp = intotcpcb(inp)) &&
1191 		    ((inp->inp_socket->so_options & SO_ACCEPTCONN) == 0))
1192 			tp = tcp_drop(tp, ECONNABORTED);
1193 		else
1194 			error = ESRCH;
1195 		in_pcbunref(inp);
1196 		return (error);
1197 	}
1198 
1199 	if (inp == NULL) {
1200 		tcpstat_inc(tcps_pcbhashmiss);
1201 		switch (tir.faddr.ss_family) {
1202 #ifdef INET6
1203 		case AF_INET6:
1204 			inp = in6_pcblookup_listen(&tcbtable,
1205 			    &l6, lin6->sin6_port, NULL, tir.rdomain);
1206 			break;
1207 #endif
1208 		case AF_INET:
1209 			inp = in_pcblookup_listen(&tcbtable,
1210 			    lin->sin_addr, lin->sin_port, NULL, tir.rdomain);
1211 			break;
1212 		}
1213 	}
1214 
1215 	if (inp != NULL && (inp->inp_socket->so_state & SS_CONNECTOUT)) {
1216 		tir.ruid = inp->inp_socket->so_ruid;
1217 		tir.euid = inp->inp_socket->so_euid;
1218 	} else {
1219 		tir.ruid = -1;
1220 		tir.euid = -1;
1221 	}
1222 
1223 	*oldlenp = sizeof (tir);
1224 	error = copyout((void *)&tir, oldp, sizeof (tir));
1225 	in_pcbunref(inp);
1226 	return (error);
1227 }
1228 
1229 int
1230 tcp_sysctl_tcpstat(void *oldp, size_t *oldlenp, void *newp)
1231 {
1232 	uint64_t counters[tcps_ncounters];
1233 	struct tcpstat tcpstat;
1234 	struct syn_cache_set *set;
1235 	int i = 0;
1236 
1237 #define ASSIGN(field)	do { tcpstat.field = counters[i++]; } while (0)
1238 
1239 	memset(&tcpstat, 0, sizeof tcpstat);
1240 	counters_read(tcpcounters, counters, nitems(counters));
1241 	ASSIGN(tcps_connattempt);
1242 	ASSIGN(tcps_accepts);
1243 	ASSIGN(tcps_connects);
1244 	ASSIGN(tcps_drops);
1245 	ASSIGN(tcps_conndrops);
1246 	ASSIGN(tcps_closed);
1247 	ASSIGN(tcps_segstimed);
1248 	ASSIGN(tcps_rttupdated);
1249 	ASSIGN(tcps_delack);
1250 	ASSIGN(tcps_timeoutdrop);
1251 	ASSIGN(tcps_rexmttimeo);
1252 	ASSIGN(tcps_persisttimeo);
1253 	ASSIGN(tcps_persistdrop);
1254 	ASSIGN(tcps_keeptimeo);
1255 	ASSIGN(tcps_keepprobe);
1256 	ASSIGN(tcps_keepdrops);
1257 	ASSIGN(tcps_sndtotal);
1258 	ASSIGN(tcps_sndpack);
1259 	ASSIGN(tcps_sndbyte);
1260 	ASSIGN(tcps_sndrexmitpack);
1261 	ASSIGN(tcps_sndrexmitbyte);
1262 	ASSIGN(tcps_sndrexmitfast);
1263 	ASSIGN(tcps_sndacks);
1264 	ASSIGN(tcps_sndprobe);
1265 	ASSIGN(tcps_sndurg);
1266 	ASSIGN(tcps_sndwinup);
1267 	ASSIGN(tcps_sndctrl);
1268 	ASSIGN(tcps_rcvtotal);
1269 	ASSIGN(tcps_rcvpack);
1270 	ASSIGN(tcps_rcvbyte);
1271 	ASSIGN(tcps_rcvbadsum);
1272 	ASSIGN(tcps_rcvbadoff);
1273 	ASSIGN(tcps_rcvmemdrop);
1274 	ASSIGN(tcps_rcvnosec);
1275 	ASSIGN(tcps_rcvshort);
1276 	ASSIGN(tcps_rcvduppack);
1277 	ASSIGN(tcps_rcvdupbyte);
1278 	ASSIGN(tcps_rcvpartduppack);
1279 	ASSIGN(tcps_rcvpartdupbyte);
1280 	ASSIGN(tcps_rcvoopack);
1281 	ASSIGN(tcps_rcvoobyte);
1282 	ASSIGN(tcps_rcvpackafterwin);
1283 	ASSIGN(tcps_rcvbyteafterwin);
1284 	ASSIGN(tcps_rcvafterclose);
1285 	ASSIGN(tcps_rcvwinprobe);
1286 	ASSIGN(tcps_rcvdupack);
1287 	ASSIGN(tcps_rcvacktoomuch);
1288 	ASSIGN(tcps_rcvacktooold);
1289 	ASSIGN(tcps_rcvackpack);
1290 	ASSIGN(tcps_rcvackbyte);
1291 	ASSIGN(tcps_rcvwinupd);
1292 	ASSIGN(tcps_pawsdrop);
1293 	ASSIGN(tcps_predack);
1294 	ASSIGN(tcps_preddat);
1295 	ASSIGN(tcps_pcbhashmiss);
1296 	ASSIGN(tcps_noport);
1297 	ASSIGN(tcps_badsyn);
1298 	ASSIGN(tcps_dropsyn);
1299 	ASSIGN(tcps_rcvbadsig);
1300 	ASSIGN(tcps_rcvgoodsig);
1301 	ASSIGN(tcps_inswcsum);
1302 	ASSIGN(tcps_outswcsum);
1303 	ASSIGN(tcps_ecn_accepts);
1304 	ASSIGN(tcps_ecn_rcvece);
1305 	ASSIGN(tcps_ecn_rcvcwr);
1306 	ASSIGN(tcps_ecn_rcvce);
1307 	ASSIGN(tcps_ecn_sndect);
1308 	ASSIGN(tcps_ecn_sndece);
1309 	ASSIGN(tcps_ecn_sndcwr);
1310 	ASSIGN(tcps_cwr_ecn);
1311 	ASSIGN(tcps_cwr_frecovery);
1312 	ASSIGN(tcps_cwr_timeout);
1313 	ASSIGN(tcps_sc_added);
1314 	ASSIGN(tcps_sc_completed);
1315 	ASSIGN(tcps_sc_timed_out);
1316 	ASSIGN(tcps_sc_overflowed);
1317 	ASSIGN(tcps_sc_reset);
1318 	ASSIGN(tcps_sc_unreach);
1319 	ASSIGN(tcps_sc_bucketoverflow);
1320 	ASSIGN(tcps_sc_aborted);
1321 	ASSIGN(tcps_sc_dupesyn);
1322 	ASSIGN(tcps_sc_dropped);
1323 	ASSIGN(tcps_sc_collisions);
1324 	ASSIGN(tcps_sc_retransmitted);
1325 	ASSIGN(tcps_sc_seedrandom);
1326 	ASSIGN(tcps_sc_hash_size);
1327 	ASSIGN(tcps_sc_entry_count);
1328 	ASSIGN(tcps_sc_entry_limit);
1329 	ASSIGN(tcps_sc_bucket_maxlen);
1330 	ASSIGN(tcps_sc_bucket_limit);
1331 	ASSIGN(tcps_sc_uses_left);
1332 	ASSIGN(tcps_conndrained);
1333 	ASSIGN(tcps_sack_recovery_episode);
1334 	ASSIGN(tcps_sack_rexmits);
1335 	ASSIGN(tcps_sack_rexmit_bytes);
1336 	ASSIGN(tcps_sack_rcv_opts);
1337 	ASSIGN(tcps_sack_snd_opts);
1338 	ASSIGN(tcps_sack_drop_opts);
1339 	ASSIGN(tcps_outswtso);
1340 	ASSIGN(tcps_outhwtso);
1341 	ASSIGN(tcps_outpkttso);
1342 	ASSIGN(tcps_outbadtso);
1343 	ASSIGN(tcps_inhwlro);
1344 	ASSIGN(tcps_inpktlro);
1345 	ASSIGN(tcps_inbadlro);
1346 
1347 #undef ASSIGN
1348 
1349 	set = &tcp_syn_cache[tcp_syn_cache_active];
1350 	tcpstat.tcps_sc_hash_size = set->scs_size;
1351 	tcpstat.tcps_sc_entry_count = set->scs_count;
1352 	tcpstat.tcps_sc_entry_limit = tcp_syn_cache_limit;
1353 	tcpstat.tcps_sc_bucket_maxlen = 0;
1354 	for (i = 0; i < set->scs_size; i++) {
1355 		if (tcpstat.tcps_sc_bucket_maxlen <
1356 		    set->scs_buckethead[i].sch_length)
1357 			tcpstat.tcps_sc_bucket_maxlen =
1358 				set->scs_buckethead[i].sch_length;
1359 	}
1360 	tcpstat.tcps_sc_bucket_limit = tcp_syn_bucket_limit;
1361 	tcpstat.tcps_sc_uses_left = set->scs_use;
1362 
1363 	return (sysctl_rdstruct(oldp, oldlenp, newp,
1364 	    &tcpstat, sizeof(tcpstat)));
1365 }
1366 
1367 /*
1368  * Sysctl for tcp variables.
1369  */
1370 int
1371 tcp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
1372     size_t newlen)
1373 {
1374 	int error, nval;
1375 
1376 	/* All sysctl names at this level are terminal. */
1377 	if (namelen != 1)
1378 		return (ENOTDIR);
1379 
1380 	switch (name[0]) {
1381 	case TCPCTL_KEEPINITTIME:
1382 		NET_LOCK();
1383 		nval = tcptv_keep_init / TCP_TIME(1);
1384 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1385 		    1, 3 * (TCPTV_KEEP_INIT / TCP_TIME(1)));
1386 		if (!error)
1387 			tcptv_keep_init = TCP_TIME(nval);
1388 		NET_UNLOCK();
1389 		return (error);
1390 
1391 	case TCPCTL_KEEPIDLE:
1392 		NET_LOCK();
1393 		nval = tcp_keepidle / TCP_TIME(1);
1394 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1395 		    1, 5 * (TCPTV_KEEP_IDLE / TCP_TIME(1)));
1396 		if (!error)
1397 			tcp_keepidle = TCP_TIME(nval);
1398 		NET_UNLOCK();
1399 		return (error);
1400 
1401 	case TCPCTL_KEEPINTVL:
1402 		NET_LOCK();
1403 		nval = tcp_keepintvl / TCP_TIME(1);
1404 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1405 		    1, 3 * (TCPTV_KEEPINTVL / TCP_TIME(1)));
1406 		if (!error)
1407 			tcp_keepintvl = TCP_TIME(nval);
1408 		NET_UNLOCK();
1409 		return (error);
1410 
1411 	case TCPCTL_BADDYNAMIC:
1412 		NET_LOCK();
1413 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
1414 		    baddynamicports.tcp, sizeof(baddynamicports.tcp));
1415 		NET_UNLOCK();
1416 		return (error);
1417 
1418 	case TCPCTL_ROOTONLY:
1419 		if (newp && securelevel > 0)
1420 			return (EPERM);
1421 		NET_LOCK();
1422 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
1423 		    rootonlyports.tcp, sizeof(rootonlyports.tcp));
1424 		NET_UNLOCK();
1425 		return (error);
1426 
1427 	case TCPCTL_IDENT:
1428 		NET_LOCK();
1429 		error = tcp_ident(oldp, oldlenp, newp, newlen, 0);
1430 		NET_UNLOCK();
1431 		return (error);
1432 
1433 	case TCPCTL_DROP:
1434 		NET_LOCK();
1435 		error = tcp_ident(oldp, oldlenp, newp, newlen, 1);
1436 		NET_UNLOCK();
1437 		return (error);
1438 
1439 	case TCPCTL_REASS_LIMIT:
1440 		NET_LOCK();
1441 		nval = tcp_reass_limit;
1442 		error = sysctl_int(oldp, oldlenp, newp, newlen, &nval);
1443 		if (!error && nval != tcp_reass_limit) {
1444 			error = pool_sethardlimit(&tcpqe_pool, nval, NULL, 0);
1445 			if (!error)
1446 				tcp_reass_limit = nval;
1447 		}
1448 		NET_UNLOCK();
1449 		return (error);
1450 
1451 	case TCPCTL_SACKHOLE_LIMIT:
1452 		NET_LOCK();
1453 		nval = tcp_sackhole_limit;
1454 		error = sysctl_int(oldp, oldlenp, newp, newlen, &nval);
1455 		if (!error && nval != tcp_sackhole_limit) {
1456 			error = pool_sethardlimit(&sackhl_pool, nval, NULL, 0);
1457 			if (!error)
1458 				tcp_sackhole_limit = nval;
1459 		}
1460 		NET_UNLOCK();
1461 		return (error);
1462 
1463 	case TCPCTL_STATS:
1464 		return (tcp_sysctl_tcpstat(oldp, oldlenp, newp));
1465 
1466 	case TCPCTL_SYN_USE_LIMIT:
1467 		NET_LOCK();
1468 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen,
1469 		    &tcp_syn_use_limit, 0, INT_MAX);
1470 		if (!error && newp != NULL) {
1471 			/*
1472 			 * Global tcp_syn_use_limit is used when reseeding a
1473 			 * new cache.  Also update the value in active cache.
1474 			 */
1475 			if (tcp_syn_cache[0].scs_use > tcp_syn_use_limit)
1476 				tcp_syn_cache[0].scs_use = tcp_syn_use_limit;
1477 			if (tcp_syn_cache[1].scs_use > tcp_syn_use_limit)
1478 				tcp_syn_cache[1].scs_use = tcp_syn_use_limit;
1479 		}
1480 		NET_UNLOCK();
1481 		return (error);
1482 
1483 	case TCPCTL_SYN_HASH_SIZE:
1484 		NET_LOCK();
1485 		nval = tcp_syn_hash_size;
1486 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen,
1487 		    &nval, 1, 100000);
1488 		if (!error && nval != tcp_syn_hash_size) {
1489 			/*
1490 			 * If global hash size has been changed,
1491 			 * switch sets as soon as possible.  Then
1492 			 * the actual hash array will be reallocated.
1493 			 */
1494 			if (tcp_syn_cache[0].scs_size != nval)
1495 				tcp_syn_cache[0].scs_use = 0;
1496 			if (tcp_syn_cache[1].scs_size != nval)
1497 				tcp_syn_cache[1].scs_use = 0;
1498 			tcp_syn_hash_size = nval;
1499 		}
1500 		NET_UNLOCK();
1501 		return (error);
1502 
1503 	default:
1504 		NET_LOCK();
1505 		error = sysctl_bounded_arr(tcpctl_vars, nitems(tcpctl_vars),
1506 		    name, namelen, oldp, oldlenp, newp, newlen);
1507 		NET_UNLOCK();
1508 		return (error);
1509 	}
1510 	/* NOTREACHED */
1511 }
1512 
1513 /*
1514  * Scale the send buffer so that inflight data is not accounted against
1515  * the limit. The buffer will scale with the congestion window, if the
1516  * the receiver stops acking data the window will shrink and therefore
1517  * the buffer size will shrink as well.
1518  * In low memory situation try to shrink the buffer to the initial size
1519  * disabling the send buffer scaling as long as the situation persists.
1520  */
1521 void
1522 tcp_update_sndspace(struct tcpcb *tp)
1523 {
1524 	struct socket *so = tp->t_inpcb->inp_socket;
1525 	u_long nmax = so->so_snd.sb_hiwat;
1526 
1527 	if (sbchecklowmem()) {
1528 		/* low on memory try to get rid of some */
1529 		if (tcp_sendspace < nmax)
1530 			nmax = tcp_sendspace;
1531 	} else if (so->so_snd.sb_wat != tcp_sendspace)
1532 		/* user requested buffer size, auto-scaling disabled */
1533 		nmax = so->so_snd.sb_wat;
1534 	else
1535 		/* automatic buffer scaling */
1536 		nmax = MIN(sb_max, so->so_snd.sb_wat + tp->snd_max -
1537 		    tp->snd_una);
1538 
1539 	/* a writable socket must be preserved because of poll(2) semantics */
1540 	if (sbspace(so, &so->so_snd) >= so->so_snd.sb_lowat) {
1541 		if (nmax < so->so_snd.sb_cc + so->so_snd.sb_lowat)
1542 			nmax = so->so_snd.sb_cc + so->so_snd.sb_lowat;
1543 		/* keep in sync with sbreserve() calculation */
1544 		if (nmax * 8 < so->so_snd.sb_mbcnt + so->so_snd.sb_lowat)
1545 			nmax = (so->so_snd.sb_mbcnt+so->so_snd.sb_lowat+7) / 8;
1546 	}
1547 
1548 	/* round to MSS boundary */
1549 	nmax = roundup(nmax, tp->t_maxseg);
1550 
1551 	if (nmax != so->so_snd.sb_hiwat)
1552 		sbreserve(so, &so->so_snd, nmax);
1553 }
1554 
1555 /*
1556  * Scale the recv buffer by looking at how much data was transferred in
1557  * one approximated RTT. If more than a big part of the recv buffer was
1558  * transferred during that time we increase the buffer by a constant.
1559  * In low memory situation try to shrink the buffer to the initial size.
1560  */
1561 void
1562 tcp_update_rcvspace(struct tcpcb *tp)
1563 {
1564 	struct socket *so = tp->t_inpcb->inp_socket;
1565 	u_long nmax = so->so_rcv.sb_hiwat;
1566 
1567 	if (sbchecklowmem()) {
1568 		/* low on memory try to get rid of some */
1569 		if (tcp_recvspace < nmax)
1570 			nmax = tcp_recvspace;
1571 	} else if (so->so_rcv.sb_wat != tcp_recvspace)
1572 		/* user requested buffer size, auto-scaling disabled */
1573 		nmax = so->so_rcv.sb_wat;
1574 	else {
1575 		/* automatic buffer scaling */
1576 		if (tp->rfbuf_cnt > so->so_rcv.sb_hiwat / 8 * 7)
1577 			nmax = MIN(sb_max, so->so_rcv.sb_hiwat +
1578 			    tcp_autorcvbuf_inc);
1579 	}
1580 
1581 	/* a readable socket must be preserved because of poll(2) semantics */
1582 	if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat &&
1583 	    nmax < so->so_snd.sb_lowat)
1584 		nmax = so->so_snd.sb_lowat;
1585 
1586 	if (nmax == so->so_rcv.sb_hiwat)
1587 		return;
1588 
1589 	/* round to MSS boundary */
1590 	nmax = roundup(nmax, tp->t_maxseg);
1591 	sbreserve(so, &so->so_rcv, nmax);
1592 }
1593