xref: /freebsd/sys/netinet/tcp_usrreq.c (revision 500f4659d7c8947082dba040a1d58e7d228f8d44)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2006-2007 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Robert N. M. Watson under
11  * contract to Juniper Networks, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	From: @(#)tcp_usrreq.c	8.2 (Berkeley) 1/3/94
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_ddb.h"
44 #include "opt_inet.h"
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_kern_tls.h"
48 #include "opt_tcpdebug.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/arb.h>
53 #include <sys/limits.h>
54 #include <sys/malloc.h>
55 #include <sys/refcount.h>
56 #include <sys/kernel.h>
57 #include <sys/ktls.h>
58 #include <sys/qmath.h>
59 #include <sys/sysctl.h>
60 #include <sys/mbuf.h>
61 #ifdef INET6
62 #include <sys/domain.h>
63 #endif /* INET6 */
64 #include <sys/socket.h>
65 #include <sys/socketvar.h>
66 #include <sys/protosw.h>
67 #include <sys/proc.h>
68 #include <sys/jail.h>
69 #include <sys/syslog.h>
70 #include <sys/stats.h>
71 
72 #ifdef DDB
73 #include <ddb/ddb.h>
74 #endif
75 
76 #include <net/if.h>
77 #include <net/if_var.h>
78 #include <net/route.h>
79 #include <net/vnet.h>
80 
81 #include <netinet/in.h>
82 #include <netinet/in_kdtrace.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/in_systm.h>
85 #include <netinet/in_var.h>
86 #include <netinet/ip_var.h>
87 #ifdef INET6
88 #include <netinet/ip6.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/scope6_var.h>
92 #endif
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_log_buf.h>
99 #include <netinet/tcpip.h>
100 #include <netinet/cc/cc.h>
101 #include <netinet/tcp_fastopen.h>
102 #include <netinet/tcp_hpts.h>
103 #ifdef TCPPCAP
104 #include <netinet/tcp_pcap.h>
105 #endif
106 #ifdef TCPDEBUG
107 #include <netinet/tcp_debug.h>
108 #endif
109 #ifdef TCP_OFFLOAD
110 #include <netinet/tcp_offload.h>
111 #endif
112 #include <netipsec/ipsec_support.h>
113 
114 #include <vm/vm.h>
115 #include <vm/vm_param.h>
116 #include <vm/pmap.h>
117 #include <vm/vm_extern.h>
118 #include <vm/vm_map.h>
119 #include <vm/vm_page.h>
120 
121 /*
122  * TCP protocol interface to socket abstraction.
123  */
124 #ifdef INET
125 static int	tcp_connect(struct tcpcb *, struct sockaddr *,
126 		    struct thread *td);
127 #endif /* INET */
128 #ifdef INET6
129 static int	tcp6_connect(struct tcpcb *, struct sockaddr *,
130 		    struct thread *td);
131 #endif /* INET6 */
132 static void	tcp_disconnect(struct tcpcb *);
133 static void	tcp_usrclosed(struct tcpcb *);
134 static void	tcp_fill_info(struct tcpcb *, struct tcp_info *);
135 
136 static int	tcp_pru_options_support(struct tcpcb *tp, int flags);
137 
138 #ifdef TCPDEBUG
139 #define	TCPDEBUG0	int ostate = 0
140 #define	TCPDEBUG1()	ostate = tp ? tp->t_state : 0
141 #define	TCPDEBUG2(req)	if (tp && (so->so_options & SO_DEBUG)) \
142 				tcp_trace(TA_USER, ostate, tp, 0, 0, req)
143 #else
144 #define	TCPDEBUG0
145 #define	TCPDEBUG1()
146 #define	TCPDEBUG2(req)
147 #endif
148 
149 /*
150  * tcp_require_unique port requires a globally-unique source port for each
151  * outgoing connection.  The default is to require the 4-tuple to be unique.
152  */
153 VNET_DEFINE(int, tcp_require_unique_port) = 0;
154 SYSCTL_INT(_net_inet_tcp, OID_AUTO, require_unique_port,
155     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_require_unique_port), 0,
156     "Require globally-unique ephemeral port for outgoing connections");
157 #define	V_tcp_require_unique_port	VNET(tcp_require_unique_port)
158 
159 /*
160  * TCP attaches to socket via pru_attach(), reserving space,
161  * and an internet control block.
162  */
163 static int
164 tcp_usr_attach(struct socket *so, int proto, struct thread *td)
165 {
166 	struct inpcb *inp;
167 	struct tcpcb *tp = NULL;
168 	int error;
169 	TCPDEBUG0;
170 
171 	inp = sotoinpcb(so);
172 	KASSERT(inp == NULL, ("tcp_usr_attach: inp != NULL"));
173 	TCPDEBUG1();
174 
175 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
176 		error = soreserve(so, V_tcp_sendspace, V_tcp_recvspace);
177 		if (error)
178 			goto out;
179 	}
180 
181 	so->so_rcv.sb_flags |= SB_AUTOSIZE;
182 	so->so_snd.sb_flags |= SB_AUTOSIZE;
183 	error = in_pcballoc(so, &V_tcbinfo);
184 	if (error)
185 		goto out;
186 	inp = sotoinpcb(so);
187 #ifdef INET6
188 	if (inp->inp_vflag & INP_IPV6PROTO) {
189 		inp->inp_vflag |= INP_IPV6;
190 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
191 			inp->inp_vflag |= INP_IPV4;
192 		inp->in6p_hops = -1;	/* use kernel default */
193 	}
194 	else
195 #endif
196 		inp->inp_vflag |= INP_IPV4;
197 	tp = tcp_newtcpcb(inp);
198 	if (tp == NULL) {
199 		error = ENOBUFS;
200 		in_pcbdetach(inp);
201 		in_pcbfree(inp);
202 		goto out;
203 	}
204 	tp->t_state = TCPS_CLOSED;
205 	INP_WUNLOCK(inp);
206 	TCPSTATES_INC(TCPS_CLOSED);
207 out:
208 	TCPDEBUG2(PRU_ATTACH);
209 	TCP_PROBE2(debug__user, tp, PRU_ATTACH);
210 	return (error);
211 }
212 
213 /*
214  * tcp_usr_detach is called when the socket layer loses its final reference
215  * to the socket, be it a file descriptor reference, a reference from TCP,
216  * etc.  At this point, there is only one case in which we will keep around
217  * inpcb state: time wait.
218  */
219 static void
220 tcp_usr_detach(struct socket *so)
221 {
222 	struct inpcb *inp;
223 	struct tcpcb *tp;
224 
225 	inp = sotoinpcb(so);
226 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
227 	INP_WLOCK(inp);
228 	KASSERT(so->so_pcb == inp && inp->inp_socket == so,
229 		("%s: socket %p inp %p mismatch", __func__, so, inp));
230 
231 	tp = intotcpcb(inp);
232 
233 	if (inp->inp_flags & INP_TIMEWAIT) {
234 		/*
235 		 * There are two cases to handle: one in which the time wait
236 		 * state is being discarded (INP_DROPPED), and one in which
237 		 * this connection will remain in timewait.  In the former,
238 		 * it is time to discard all state (except tcptw, which has
239 		 * already been discarded by the timewait close code, which
240 		 * should be further up the call stack somewhere).  In the
241 		 * latter case, we detach from the socket, but leave the pcb
242 		 * present until timewait ends.
243 		 *
244 		 * XXXRW: Would it be cleaner to free the tcptw here?
245 		 *
246 		 * Astute question indeed, from twtcp perspective there are
247 		 * four cases to consider:
248 		 *
249 		 * #1 tcp_usr_detach is called at tcptw creation time by
250 		 *  tcp_twstart, then do not discard the newly created tcptw
251 		 *  and leave inpcb present until timewait ends
252 		 * #2 tcp_usr_detach is called at tcptw creation time by
253 		 *  tcp_twstart, but connection is local and tw will be
254 		 *  discarded immediately
255 		 * #3 tcp_usr_detach is called at timewait end (or reuse) by
256 		 *  tcp_twclose, then the tcptw has already been discarded
257 		 *  (or reused) and inpcb is freed here
258 		 * #4 tcp_usr_detach is called() after timewait ends (or reuse)
259 		 *  (e.g. by soclose), then tcptw has already been discarded
260 		 *  (or reused) and inpcb is freed here
261 		 *
262 		 *  In all three cases the tcptw should not be freed here.
263 		 */
264 		if (inp->inp_flags & INP_DROPPED) {
265 			in_pcbdetach(inp);
266 			if (__predict_true(tp == NULL)) {
267 				in_pcbfree(inp);
268 			} else {
269 				/*
270 				 * This case should not happen as in TIMEWAIT
271 				 * state the inp should not be destroyed before
272 				 * its tcptw.  If INVARIANTS is defined, panic.
273 				 */
274 #ifdef INVARIANTS
275 				panic("%s: Panic before an inp double-free: "
276 				    "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
277 				    , __func__);
278 #else
279 				log(LOG_ERR, "%s: Avoid an inp double-free: "
280 				    "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
281 				    , __func__);
282 #endif
283 				INP_WUNLOCK(inp);
284 			}
285 		} else {
286 			in_pcbdetach(inp);
287 			INP_WUNLOCK(inp);
288 		}
289 	} else {
290 		/*
291 		 * If the connection is not in timewait, we consider two
292 		 * two conditions: one in which no further processing is
293 		 * necessary (dropped || embryonic), and one in which TCP is
294 		 * not yet done, but no longer requires the socket, so the
295 		 * pcb will persist for the time being.
296 		 *
297 		 * XXXRW: Does the second case still occur?
298 		 */
299 		if (inp->inp_flags & INP_DROPPED ||
300 		    tp->t_state < TCPS_SYN_SENT) {
301 			tcp_discardcb(tp);
302 			in_pcbdetach(inp);
303 			in_pcbfree(inp);
304 		} else {
305 			in_pcbdetach(inp);
306 			INP_WUNLOCK(inp);
307 		}
308 	}
309 }
310 
311 #ifdef INET
312 /*
313  * Give the socket an address.
314  */
315 static int
316 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
317 {
318 	int error = 0;
319 	struct inpcb *inp;
320 	struct tcpcb *tp = NULL;
321 	struct sockaddr_in *sinp;
322 
323 	sinp = (struct sockaddr_in *)nam;
324 	if (nam->sa_len != sizeof (*sinp))
325 		return (EINVAL);
326 	/*
327 	 * Must check for multicast addresses and disallow binding
328 	 * to them.
329 	 */
330 	if (sinp->sin_family == AF_INET &&
331 	    IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
332 		return (EAFNOSUPPORT);
333 
334 	TCPDEBUG0;
335 	inp = sotoinpcb(so);
336 	KASSERT(inp != NULL, ("tcp_usr_bind: inp == NULL"));
337 	INP_WLOCK(inp);
338 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
339 		error = EINVAL;
340 		goto out;
341 	}
342 	tp = intotcpcb(inp);
343 	TCPDEBUG1();
344 	INP_HASH_WLOCK(&V_tcbinfo);
345 	error = in_pcbbind(inp, nam, td->td_ucred);
346 	INP_HASH_WUNLOCK(&V_tcbinfo);
347 out:
348 	TCPDEBUG2(PRU_BIND);
349 	TCP_PROBE2(debug__user, tp, PRU_BIND);
350 	INP_WUNLOCK(inp);
351 
352 	return (error);
353 }
354 #endif /* INET */
355 
356 #ifdef INET6
357 static int
358 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
359 {
360 	int error = 0;
361 	struct inpcb *inp;
362 	struct tcpcb *tp = NULL;
363 	struct sockaddr_in6 *sin6;
364 	u_char vflagsav;
365 
366 	sin6 = (struct sockaddr_in6 *)nam;
367 	if (nam->sa_len != sizeof (*sin6))
368 		return (EINVAL);
369 	/*
370 	 * Must check for multicast addresses and disallow binding
371 	 * to them.
372 	 */
373 	if (sin6->sin6_family == AF_INET6 &&
374 	    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
375 		return (EAFNOSUPPORT);
376 
377 	TCPDEBUG0;
378 	inp = sotoinpcb(so);
379 	KASSERT(inp != NULL, ("tcp6_usr_bind: inp == NULL"));
380 	INP_WLOCK(inp);
381 	vflagsav = inp->inp_vflag;
382 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
383 		error = EINVAL;
384 		goto out;
385 	}
386 	tp = intotcpcb(inp);
387 	TCPDEBUG1();
388 	INP_HASH_WLOCK(&V_tcbinfo);
389 	inp->inp_vflag &= ~INP_IPV4;
390 	inp->inp_vflag |= INP_IPV6;
391 #ifdef INET
392 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
393 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
394 			inp->inp_vflag |= INP_IPV4;
395 		else if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
396 			struct sockaddr_in sin;
397 
398 			in6_sin6_2_sin(&sin, sin6);
399 			if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
400 				error = EAFNOSUPPORT;
401 				INP_HASH_WUNLOCK(&V_tcbinfo);
402 				goto out;
403 			}
404 			inp->inp_vflag |= INP_IPV4;
405 			inp->inp_vflag &= ~INP_IPV6;
406 			error = in_pcbbind(inp, (struct sockaddr *)&sin,
407 			    td->td_ucred);
408 			INP_HASH_WUNLOCK(&V_tcbinfo);
409 			goto out;
410 		}
411 	}
412 #endif
413 	error = in6_pcbbind(inp, nam, td->td_ucred);
414 	INP_HASH_WUNLOCK(&V_tcbinfo);
415 out:
416 	if (error != 0)
417 		inp->inp_vflag = vflagsav;
418 	TCPDEBUG2(PRU_BIND);
419 	TCP_PROBE2(debug__user, tp, PRU_BIND);
420 	INP_WUNLOCK(inp);
421 	return (error);
422 }
423 #endif /* INET6 */
424 
425 #ifdef INET
426 /*
427  * Prepare to accept connections.
428  */
429 static int
430 tcp_usr_listen(struct socket *so, int backlog, struct thread *td)
431 {
432 	int error = 0;
433 	struct inpcb *inp;
434 	struct tcpcb *tp = NULL;
435 
436 	TCPDEBUG0;
437 	inp = sotoinpcb(so);
438 	KASSERT(inp != NULL, ("tcp_usr_listen: inp == NULL"));
439 	INP_WLOCK(inp);
440 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
441 		error = EINVAL;
442 		goto out;
443 	}
444 	tp = intotcpcb(inp);
445 	TCPDEBUG1();
446 	SOCK_LOCK(so);
447 	error = solisten_proto_check(so);
448 	INP_HASH_WLOCK(&V_tcbinfo);
449 	if (error == 0 && inp->inp_lport == 0)
450 		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
451 	INP_HASH_WUNLOCK(&V_tcbinfo);
452 	if (error == 0) {
453 		tcp_state_change(tp, TCPS_LISTEN);
454 		solisten_proto(so, backlog);
455 #ifdef TCP_OFFLOAD
456 		if ((so->so_options & SO_NO_OFFLOAD) == 0)
457 			tcp_offload_listen_start(tp);
458 #endif
459 	}
460 	SOCK_UNLOCK(so);
461 
462 	if (IS_FASTOPEN(tp->t_flags))
463 		tp->t_tfo_pending = tcp_fastopen_alloc_counter();
464 
465 out:
466 	TCPDEBUG2(PRU_LISTEN);
467 	TCP_PROBE2(debug__user, tp, PRU_LISTEN);
468 	INP_WUNLOCK(inp);
469 	return (error);
470 }
471 #endif /* INET */
472 
473 #ifdef INET6
474 static int
475 tcp6_usr_listen(struct socket *so, int backlog, struct thread *td)
476 {
477 	int error = 0;
478 	struct inpcb *inp;
479 	struct tcpcb *tp = NULL;
480 	u_char vflagsav;
481 
482 	TCPDEBUG0;
483 	inp = sotoinpcb(so);
484 	KASSERT(inp != NULL, ("tcp6_usr_listen: inp == NULL"));
485 	INP_WLOCK(inp);
486 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
487 		error = EINVAL;
488 		goto out;
489 	}
490 	vflagsav = inp->inp_vflag;
491 	tp = intotcpcb(inp);
492 	TCPDEBUG1();
493 	SOCK_LOCK(so);
494 	error = solisten_proto_check(so);
495 	INP_HASH_WLOCK(&V_tcbinfo);
496 	if (error == 0 && inp->inp_lport == 0) {
497 		inp->inp_vflag &= ~INP_IPV4;
498 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
499 			inp->inp_vflag |= INP_IPV4;
500 		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
501 	}
502 	INP_HASH_WUNLOCK(&V_tcbinfo);
503 	if (error == 0) {
504 		tcp_state_change(tp, TCPS_LISTEN);
505 		solisten_proto(so, backlog);
506 #ifdef TCP_OFFLOAD
507 		if ((so->so_options & SO_NO_OFFLOAD) == 0)
508 			tcp_offload_listen_start(tp);
509 #endif
510 	}
511 	SOCK_UNLOCK(so);
512 
513 	if (IS_FASTOPEN(tp->t_flags))
514 		tp->t_tfo_pending = tcp_fastopen_alloc_counter();
515 
516 	if (error != 0)
517 		inp->inp_vflag = vflagsav;
518 
519 out:
520 	TCPDEBUG2(PRU_LISTEN);
521 	TCP_PROBE2(debug__user, tp, PRU_LISTEN);
522 	INP_WUNLOCK(inp);
523 	return (error);
524 }
525 #endif /* INET6 */
526 
527 #ifdef INET
528 /*
529  * Initiate connection to peer.
530  * Create a template for use in transmissions on this connection.
531  * Enter SYN_SENT state, and mark socket as connecting.
532  * Start keep-alive timer, and seed output sequence space.
533  * Send initial segment on connection.
534  */
535 static int
536 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
537 {
538 	struct epoch_tracker et;
539 	int error = 0;
540 	struct inpcb *inp;
541 	struct tcpcb *tp = NULL;
542 	struct sockaddr_in *sinp;
543 
544 	sinp = (struct sockaddr_in *)nam;
545 	if (nam->sa_len != sizeof (*sinp))
546 		return (EINVAL);
547 	/*
548 	 * Must disallow TCP ``connections'' to multicast addresses.
549 	 */
550 	if (sinp->sin_family == AF_INET
551 	    && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
552 		return (EAFNOSUPPORT);
553 	if ((sinp->sin_family == AF_INET) &&
554 	    (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST))
555 		return (EACCES);
556 	if ((error = prison_remote_ip4(td->td_ucred, &sinp->sin_addr)) != 0)
557 		return (error);
558 
559 	TCPDEBUG0;
560 	inp = sotoinpcb(so);
561 	KASSERT(inp != NULL, ("tcp_usr_connect: inp == NULL"));
562 	INP_WLOCK(inp);
563 	if (inp->inp_flags & INP_TIMEWAIT) {
564 		error = EADDRINUSE;
565 		goto out;
566 	}
567 	if (inp->inp_flags & INP_DROPPED) {
568 		error = ECONNREFUSED;
569 		goto out;
570 	}
571 	tp = intotcpcb(inp);
572 	TCPDEBUG1();
573 	NET_EPOCH_ENTER(et);
574 	if ((error = tcp_connect(tp, nam, td)) != 0)
575 		goto out_in_epoch;
576 #ifdef TCP_OFFLOAD
577 	if (registered_toedevs > 0 &&
578 	    (so->so_options & SO_NO_OFFLOAD) == 0 &&
579 	    (error = tcp_offload_connect(so, nam)) == 0)
580 		goto out_in_epoch;
581 #endif
582 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
583 	error = tp->t_fb->tfb_tcp_output(tp);
584 out_in_epoch:
585 	NET_EPOCH_EXIT(et);
586 out:
587 	TCPDEBUG2(PRU_CONNECT);
588 	TCP_PROBE2(debug__user, tp, PRU_CONNECT);
589 	INP_WUNLOCK(inp);
590 	return (error);
591 }
592 #endif /* INET */
593 
594 #ifdef INET6
595 static int
596 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
597 {
598 	struct epoch_tracker et;
599 	int error = 0;
600 	struct inpcb *inp;
601 	struct tcpcb *tp = NULL;
602 	struct sockaddr_in6 *sin6;
603 	u_int8_t incflagsav;
604 	u_char vflagsav;
605 
606 	TCPDEBUG0;
607 
608 	sin6 = (struct sockaddr_in6 *)nam;
609 	if (nam->sa_len != sizeof (*sin6))
610 		return (EINVAL);
611 	/*
612 	 * Must disallow TCP ``connections'' to multicast addresses.
613 	 */
614 	if (sin6->sin6_family == AF_INET6
615 	    && IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
616 		return (EAFNOSUPPORT);
617 
618 	inp = sotoinpcb(so);
619 	KASSERT(inp != NULL, ("tcp6_usr_connect: inp == NULL"));
620 	INP_WLOCK(inp);
621 	vflagsav = inp->inp_vflag;
622 	incflagsav = inp->inp_inc.inc_flags;
623 	if (inp->inp_flags & INP_TIMEWAIT) {
624 		error = EADDRINUSE;
625 		goto out;
626 	}
627 	if (inp->inp_flags & INP_DROPPED) {
628 		error = ECONNREFUSED;
629 		goto out;
630 	}
631 	tp = intotcpcb(inp);
632 	TCPDEBUG1();
633 #ifdef INET
634 	/*
635 	 * XXXRW: Some confusion: V4/V6 flags relate to binding, and
636 	 * therefore probably require the hash lock, which isn't held here.
637 	 * Is this a significant problem?
638 	 */
639 	if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
640 		struct sockaddr_in sin;
641 
642 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
643 			error = EINVAL;
644 			goto out;
645 		}
646 		if ((inp->inp_vflag & INP_IPV4) == 0) {
647 			error = EAFNOSUPPORT;
648 			goto out;
649 		}
650 
651 		in6_sin6_2_sin(&sin, sin6);
652 		if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
653 			error = EAFNOSUPPORT;
654 			goto out;
655 		}
656 		if (ntohl(sin.sin_addr.s_addr) == INADDR_BROADCAST) {
657 			error = EACCES;
658 			goto out;
659 		}
660 		if ((error = prison_remote_ip4(td->td_ucred,
661 		    &sin.sin_addr)) != 0)
662 			goto out;
663 		inp->inp_vflag |= INP_IPV4;
664 		inp->inp_vflag &= ~INP_IPV6;
665 		NET_EPOCH_ENTER(et);
666 		if ((error = tcp_connect(tp, (struct sockaddr *)&sin, td)) != 0)
667 			goto out_in_epoch;
668 #ifdef TCP_OFFLOAD
669 		if (registered_toedevs > 0 &&
670 		    (so->so_options & SO_NO_OFFLOAD) == 0 &&
671 		    (error = tcp_offload_connect(so, nam)) == 0)
672 			goto out_in_epoch;
673 #endif
674 		error = tp->t_fb->tfb_tcp_output(tp);
675 		goto out_in_epoch;
676 	} else {
677 		if ((inp->inp_vflag & INP_IPV6) == 0) {
678 			error = EAFNOSUPPORT;
679 			goto out;
680 		}
681 	}
682 #endif
683 	if ((error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr)) != 0)
684 		goto out;
685 	inp->inp_vflag &= ~INP_IPV4;
686 	inp->inp_vflag |= INP_IPV6;
687 	inp->inp_inc.inc_flags |= INC_ISIPV6;
688 	if ((error = tcp6_connect(tp, nam, td)) != 0)
689 		goto out;
690 #ifdef TCP_OFFLOAD
691 	if (registered_toedevs > 0 &&
692 	    (so->so_options & SO_NO_OFFLOAD) == 0 &&
693 	    (error = tcp_offload_connect(so, nam)) == 0)
694 		goto out;
695 #endif
696 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
697 	NET_EPOCH_ENTER(et);
698 	error = tp->t_fb->tfb_tcp_output(tp);
699 #ifdef INET
700 out_in_epoch:
701 #endif
702 	NET_EPOCH_EXIT(et);
703 out:
704 	/*
705 	 * If the implicit bind in the connect call fails, restore
706 	 * the flags we modified.
707 	 */
708 	if (error != 0 && inp->inp_lport == 0) {
709 		inp->inp_vflag = vflagsav;
710 		inp->inp_inc.inc_flags = incflagsav;
711 	}
712 
713 	TCPDEBUG2(PRU_CONNECT);
714 	TCP_PROBE2(debug__user, tp, PRU_CONNECT);
715 	INP_WUNLOCK(inp);
716 	return (error);
717 }
718 #endif /* INET6 */
719 
720 /*
721  * Initiate disconnect from peer.
722  * If connection never passed embryonic stage, just drop;
723  * else if don't need to let data drain, then can just drop anyways,
724  * else have to begin TCP shutdown process: mark socket disconnecting,
725  * drain unread data, state switch to reflect user close, and
726  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
727  * when peer sends FIN and acks ours.
728  *
729  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
730  */
731 static int
732 tcp_usr_disconnect(struct socket *so)
733 {
734 	struct inpcb *inp;
735 	struct tcpcb *tp = NULL;
736 	struct epoch_tracker et;
737 	int error = 0;
738 
739 	TCPDEBUG0;
740 	NET_EPOCH_ENTER(et);
741 	inp = sotoinpcb(so);
742 	KASSERT(inp != NULL, ("tcp_usr_disconnect: inp == NULL"));
743 	INP_WLOCK(inp);
744 	if (inp->inp_flags & INP_TIMEWAIT)
745 		goto out;
746 	if (inp->inp_flags & INP_DROPPED) {
747 		error = ECONNRESET;
748 		goto out;
749 	}
750 	tp = intotcpcb(inp);
751 	TCPDEBUG1();
752 	tcp_disconnect(tp);
753 out:
754 	TCPDEBUG2(PRU_DISCONNECT);
755 	TCP_PROBE2(debug__user, tp, PRU_DISCONNECT);
756 	INP_WUNLOCK(inp);
757 	NET_EPOCH_EXIT(et);
758 	return (error);
759 }
760 
761 #ifdef INET
762 /*
763  * Accept a connection.  Essentially all the work is done at higher levels;
764  * just return the address of the peer, storing through addr.
765  */
766 static int
767 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
768 {
769 	int error = 0;
770 	struct inpcb *inp = NULL;
771 	struct tcpcb *tp = NULL;
772 	struct in_addr addr;
773 	in_port_t port = 0;
774 	TCPDEBUG0;
775 
776 	if (so->so_state & SS_ISDISCONNECTED)
777 		return (ECONNABORTED);
778 
779 	inp = sotoinpcb(so);
780 	KASSERT(inp != NULL, ("tcp_usr_accept: inp == NULL"));
781 	INP_WLOCK(inp);
782 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
783 		error = ECONNABORTED;
784 		goto out;
785 	}
786 	tp = intotcpcb(inp);
787 	TCPDEBUG1();
788 
789 	/*
790 	 * We inline in_getpeeraddr and COMMON_END here, so that we can
791 	 * copy the data of interest and defer the malloc until after we
792 	 * release the lock.
793 	 */
794 	port = inp->inp_fport;
795 	addr = inp->inp_faddr;
796 
797 out:
798 	TCPDEBUG2(PRU_ACCEPT);
799 	TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
800 	INP_WUNLOCK(inp);
801 	if (error == 0)
802 		*nam = in_sockaddr(port, &addr);
803 	return error;
804 }
805 #endif /* INET */
806 
807 #ifdef INET6
808 static int
809 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
810 {
811 	struct inpcb *inp = NULL;
812 	int error = 0;
813 	struct tcpcb *tp = NULL;
814 	struct in_addr addr;
815 	struct in6_addr addr6;
816 	struct epoch_tracker et;
817 	in_port_t port = 0;
818 	int v4 = 0;
819 	TCPDEBUG0;
820 
821 	if (so->so_state & SS_ISDISCONNECTED)
822 		return (ECONNABORTED);
823 
824 	inp = sotoinpcb(so);
825 	KASSERT(inp != NULL, ("tcp6_usr_accept: inp == NULL"));
826 	NET_EPOCH_ENTER(et);
827 	INP_WLOCK(inp);
828 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
829 		error = ECONNABORTED;
830 		goto out;
831 	}
832 	tp = intotcpcb(inp);
833 	TCPDEBUG1();
834 
835 	/*
836 	 * We inline in6_mapped_peeraddr and COMMON_END here, so that we can
837 	 * copy the data of interest and defer the malloc until after we
838 	 * release the lock.
839 	 */
840 	if (inp->inp_vflag & INP_IPV4) {
841 		v4 = 1;
842 		port = inp->inp_fport;
843 		addr = inp->inp_faddr;
844 	} else {
845 		port = inp->inp_fport;
846 		addr6 = inp->in6p_faddr;
847 	}
848 
849 out:
850 	TCPDEBUG2(PRU_ACCEPT);
851 	TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
852 	INP_WUNLOCK(inp);
853 	NET_EPOCH_EXIT(et);
854 	if (error == 0) {
855 		if (v4)
856 			*nam = in6_v4mapsin6_sockaddr(port, &addr);
857 		else
858 			*nam = in6_sockaddr(port, &addr6);
859 	}
860 	return error;
861 }
862 #endif /* INET6 */
863 
864 /*
865  * Mark the connection as being incapable of further output.
866  */
867 static int
868 tcp_usr_shutdown(struct socket *so)
869 {
870 	int error = 0;
871 	struct inpcb *inp;
872 	struct tcpcb *tp = NULL;
873 	struct epoch_tracker et;
874 
875 	TCPDEBUG0;
876 	NET_EPOCH_ENTER(et);
877 	inp = sotoinpcb(so);
878 	KASSERT(inp != NULL, ("inp == NULL"));
879 	INP_WLOCK(inp);
880 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
881 		error = ECONNRESET;
882 		goto out;
883 	}
884 	tp = intotcpcb(inp);
885 	TCPDEBUG1();
886 	socantsendmore(so);
887 	tcp_usrclosed(tp);
888 	if (!(inp->inp_flags & INP_DROPPED))
889 		error = tp->t_fb->tfb_tcp_output(tp);
890 
891 out:
892 	TCPDEBUG2(PRU_SHUTDOWN);
893 	TCP_PROBE2(debug__user, tp, PRU_SHUTDOWN);
894 	INP_WUNLOCK(inp);
895 	NET_EPOCH_EXIT(et);
896 
897 	return (error);
898 }
899 
900 /*
901  * After a receive, possibly send window update to peer.
902  */
903 static int
904 tcp_usr_rcvd(struct socket *so, int flags)
905 {
906 	struct epoch_tracker et;
907 	struct inpcb *inp;
908 	struct tcpcb *tp = NULL;
909 	int error = 0;
910 
911 	TCPDEBUG0;
912 	inp = sotoinpcb(so);
913 	KASSERT(inp != NULL, ("tcp_usr_rcvd: inp == NULL"));
914 	INP_WLOCK(inp);
915 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
916 		error = ECONNRESET;
917 		goto out;
918 	}
919 	tp = intotcpcb(inp);
920 	TCPDEBUG1();
921 	/*
922 	 * For passively-created TFO connections, don't attempt a window
923 	 * update while still in SYN_RECEIVED as this may trigger an early
924 	 * SYN|ACK.  It is preferable to have the SYN|ACK be sent along with
925 	 * application response data, or failing that, when the DELACK timer
926 	 * expires.
927 	 */
928 	if (IS_FASTOPEN(tp->t_flags) &&
929 	    (tp->t_state == TCPS_SYN_RECEIVED))
930 		goto out;
931 	NET_EPOCH_ENTER(et);
932 #ifdef TCP_OFFLOAD
933 	if (tp->t_flags & TF_TOE)
934 		tcp_offload_rcvd(tp);
935 	else
936 #endif
937 	tp->t_fb->tfb_tcp_output(tp);
938 	NET_EPOCH_EXIT(et);
939 out:
940 	TCPDEBUG2(PRU_RCVD);
941 	TCP_PROBE2(debug__user, tp, PRU_RCVD);
942 	INP_WUNLOCK(inp);
943 	return (error);
944 }
945 
946 /*
947  * Do a send by putting data in output queue and updating urgent
948  * marker if URG set.  Possibly send more data.  Unlike the other
949  * pru_*() routines, the mbuf chains are our responsibility.  We
950  * must either enqueue them or free them.  The other pru_* routines
951  * generally are caller-frees.
952  */
953 static int
954 tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
955     struct sockaddr *nam, struct mbuf *control, struct thread *td)
956 {
957 	struct epoch_tracker et;
958 	int error = 0;
959 	struct inpcb *inp;
960 	struct tcpcb *tp = NULL;
961 #ifdef INET
962 #ifdef INET6
963 	struct sockaddr_in sin;
964 #endif
965 	struct sockaddr_in *sinp;
966 #endif
967 #ifdef INET6
968 	int isipv6;
969 #endif
970 	u_int8_t incflagsav;
971 	u_char vflagsav;
972 	bool restoreflags;
973 	TCPDEBUG0;
974 
975 	/*
976 	 * We require the pcbinfo "read lock" if we will close the socket
977 	 * as part of this call.
978 	 */
979 	NET_EPOCH_ENTER(et);
980 	inp = sotoinpcb(so);
981 	KASSERT(inp != NULL, ("tcp_usr_send: inp == NULL"));
982 	INP_WLOCK(inp);
983 	vflagsav = inp->inp_vflag;
984 	incflagsav = inp->inp_inc.inc_flags;
985 	restoreflags = false;
986 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
987 		if (control)
988 			m_freem(control);
989 		/*
990 		 * In case of PRUS_NOTREADY, tcp_usr_ready() is responsible
991 		 * for freeing memory.
992 		 */
993 		if (m && (flags & PRUS_NOTREADY) == 0)
994 			m_freem(m);
995 		error = ECONNRESET;
996 		goto out;
997 	}
998 	tp = intotcpcb(inp);
999 	if (flags & PRUS_OOB) {
1000 		if ((error = tcp_pru_options_support(tp, PRUS_OOB)) != 0) {
1001 			if (control)
1002 				m_freem(control);
1003 			if (m && (flags & PRUS_NOTREADY) == 0)
1004 				m_freem(m);
1005 			goto out;
1006 		}
1007 	}
1008 	TCPDEBUG1();
1009 	if (nam != NULL && tp->t_state < TCPS_SYN_SENT) {
1010 		switch (nam->sa_family) {
1011 #ifdef INET
1012 		case AF_INET:
1013 			sinp = (struct sockaddr_in *)nam;
1014 			if (sinp->sin_len != sizeof(struct sockaddr_in)) {
1015 				if (m)
1016 					m_freem(m);
1017 				error = EINVAL;
1018 				goto out;
1019 			}
1020 			if ((inp->inp_vflag & INP_IPV6) != 0) {
1021 				if (m)
1022 					m_freem(m);
1023 				error = EAFNOSUPPORT;
1024 				goto out;
1025 			}
1026 			if (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
1027 				if (m)
1028 					m_freem(m);
1029 				error = EAFNOSUPPORT;
1030 				goto out;
1031 			}
1032 			if (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST) {
1033 				if (m)
1034 					m_freem(m);
1035 				error = EACCES;
1036 				goto out;
1037 			}
1038 			if ((error = prison_remote_ip4(td->td_ucred,
1039 			    &sinp->sin_addr))) {
1040 				if (m)
1041 					m_freem(m);
1042 				goto out;
1043 			}
1044 #ifdef INET6
1045 			isipv6 = 0;
1046 #endif
1047 			break;
1048 #endif /* INET */
1049 #ifdef INET6
1050 		case AF_INET6:
1051 		{
1052 			struct sockaddr_in6 *sin6;
1053 
1054 			sin6 = (struct sockaddr_in6 *)nam;
1055 			if (sin6->sin6_len != sizeof(*sin6)) {
1056 				if (m)
1057 					m_freem(m);
1058 				error = EINVAL;
1059 				goto out;
1060 			}
1061 			if ((inp->inp_vflag & INP_IPV6PROTO) == 0) {
1062 				if (m != NULL)
1063 					m_freem(m);
1064 				error = EAFNOSUPPORT;
1065 				goto out;
1066 			}
1067 			if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
1068 				if (m)
1069 					m_freem(m);
1070 				error = EAFNOSUPPORT;
1071 				goto out;
1072 			}
1073 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1074 #ifdef INET
1075 				if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
1076 					error = EINVAL;
1077 					if (m)
1078 						m_freem(m);
1079 					goto out;
1080 				}
1081 				if ((inp->inp_vflag & INP_IPV4) == 0) {
1082 					error = EAFNOSUPPORT;
1083 					if (m)
1084 						m_freem(m);
1085 					goto out;
1086 				}
1087 				restoreflags = true;
1088 				inp->inp_vflag &= ~INP_IPV6;
1089 				sinp = &sin;
1090 				in6_sin6_2_sin(sinp, sin6);
1091 				if (IN_MULTICAST(
1092 				    ntohl(sinp->sin_addr.s_addr))) {
1093 					error = EAFNOSUPPORT;
1094 					if (m)
1095 						m_freem(m);
1096 					goto out;
1097 				}
1098 				if ((error = prison_remote_ip4(td->td_ucred,
1099 				    &sinp->sin_addr))) {
1100 					if (m)
1101 						m_freem(m);
1102 					goto out;
1103 				}
1104 				isipv6 = 0;
1105 #else /* !INET */
1106 				error = EAFNOSUPPORT;
1107 				if (m)
1108 					m_freem(m);
1109 				goto out;
1110 #endif /* INET */
1111 			} else {
1112 				if ((inp->inp_vflag & INP_IPV6) == 0) {
1113 					if (m)
1114 						m_freem(m);
1115 					error = EAFNOSUPPORT;
1116 					goto out;
1117 				}
1118 				restoreflags = true;
1119 				inp->inp_vflag &= ~INP_IPV4;
1120 				inp->inp_inc.inc_flags |= INC_ISIPV6;
1121 				if ((error = prison_remote_ip6(td->td_ucred,
1122 				    &sin6->sin6_addr))) {
1123 					if (m)
1124 						m_freem(m);
1125 					goto out;
1126 				}
1127 				isipv6 = 1;
1128 			}
1129 			break;
1130 		}
1131 #endif /* INET6 */
1132 		default:
1133 			if (m)
1134 				m_freem(m);
1135 			error = EAFNOSUPPORT;
1136 			goto out;
1137 		}
1138 	}
1139 	if (control) {
1140 		/* TCP doesn't do control messages (rights, creds, etc) */
1141 		if (control->m_len) {
1142 			m_freem(control);
1143 			if (m)
1144 				m_freem(m);
1145 			error = EINVAL;
1146 			goto out;
1147 		}
1148 		m_freem(control);	/* empty control, just free it */
1149 	}
1150 	if (!(flags & PRUS_OOB)) {
1151 		sbappendstream(&so->so_snd, m, flags);
1152 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1153 			/*
1154 			 * Do implied connect if not yet connected,
1155 			 * initialize window to default value, and
1156 			 * initialize maxseg using peer's cached MSS.
1157 			 */
1158 #ifdef INET6
1159 			if (isipv6)
1160 				error = tcp6_connect(tp, nam, td);
1161 #endif /* INET6 */
1162 #if defined(INET6) && defined(INET)
1163 			else
1164 #endif
1165 #ifdef INET
1166 				error = tcp_connect(tp,
1167 				    (struct sockaddr *)sinp, td);
1168 #endif
1169 			/*
1170 			 * The bind operation in tcp_connect succeeded. We
1171 			 * no longer want to restore the flags if later
1172 			 * operations fail.
1173 			 */
1174 			if (error == 0 || inp->inp_lport != 0)
1175 				restoreflags = false;
1176 
1177 			if (error)
1178 				goto out;
1179 			if (IS_FASTOPEN(tp->t_flags))
1180 				tcp_fastopen_connect(tp);
1181 			else {
1182 				tp->snd_wnd = TTCP_CLIENT_SND_WND;
1183 				tcp_mss(tp, -1);
1184 			}
1185 		}
1186 		if (flags & PRUS_EOF) {
1187 			/*
1188 			 * Close the send side of the connection after
1189 			 * the data is sent.
1190 			 */
1191 			socantsendmore(so);
1192 			tcp_usrclosed(tp);
1193 		}
1194 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1195 		    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
1196 		    (tp->t_fbyte_out == 0) &&
1197 		    (so->so_snd.sb_ccc > 0)) {
1198 			tp->t_fbyte_out = ticks;
1199 			if (tp->t_fbyte_out == 0)
1200 				tp->t_fbyte_out = 1;
1201 			if (tp->t_fbyte_out && tp->t_fbyte_in)
1202 				tp->t_flags2 |= TF2_FBYTES_COMPLETE;
1203 		}
1204 		if (!(inp->inp_flags & INP_DROPPED) &&
1205 		    !(flags & PRUS_NOTREADY)) {
1206 			if (flags & PRUS_MORETOCOME)
1207 				tp->t_flags |= TF_MORETOCOME;
1208 			error = tp->t_fb->tfb_tcp_output(tp);
1209 			if (flags & PRUS_MORETOCOME)
1210 				tp->t_flags &= ~TF_MORETOCOME;
1211 		}
1212 	} else {
1213 		/*
1214 		 * XXXRW: PRUS_EOF not implemented with PRUS_OOB?
1215 		 */
1216 		SOCKBUF_LOCK(&so->so_snd);
1217 		if (sbspace(&so->so_snd) < -512) {
1218 			SOCKBUF_UNLOCK(&so->so_snd);
1219 			m_freem(m);
1220 			error = ENOBUFS;
1221 			goto out;
1222 		}
1223 		/*
1224 		 * According to RFC961 (Assigned Protocols),
1225 		 * the urgent pointer points to the last octet
1226 		 * of urgent data.  We continue, however,
1227 		 * to consider it to indicate the first octet
1228 		 * of data past the urgent section.
1229 		 * Otherwise, snd_up should be one lower.
1230 		 */
1231 		sbappendstream_locked(&so->so_snd, m, flags);
1232 		SOCKBUF_UNLOCK(&so->so_snd);
1233 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1234 			/*
1235 			 * Do implied connect if not yet connected,
1236 			 * initialize window to default value, and
1237 			 * initialize maxseg using peer's cached MSS.
1238 			 */
1239 
1240 			/*
1241 			 * Not going to contemplate SYN|URG
1242 			 */
1243 			if (IS_FASTOPEN(tp->t_flags))
1244 				tp->t_flags &= ~TF_FASTOPEN;
1245 #ifdef INET6
1246 			if (isipv6)
1247 				error = tcp6_connect(tp, nam, td);
1248 #endif /* INET6 */
1249 #if defined(INET6) && defined(INET)
1250 			else
1251 #endif
1252 #ifdef INET
1253 				error = tcp_connect(tp,
1254 				    (struct sockaddr *)sinp, td);
1255 #endif
1256 			/*
1257 			 * The bind operation in tcp_connect succeeded. We
1258 			 * no longer want to restore the flags if later
1259 			 * operations fail.
1260 			 */
1261 			if (error == 0 || inp->inp_lport != 0)
1262 				restoreflags = false;
1263 
1264 			if (error)
1265 				goto out;
1266 			tp->snd_wnd = TTCP_CLIENT_SND_WND;
1267 			tcp_mss(tp, -1);
1268 		}
1269 		tp->snd_up = tp->snd_una + sbavail(&so->so_snd);
1270 		if (!(flags & PRUS_NOTREADY)) {
1271 			tp->t_flags |= TF_FORCEDATA;
1272 			error = tp->t_fb->tfb_tcp_output(tp);
1273 			tp->t_flags &= ~TF_FORCEDATA;
1274 		}
1275 	}
1276 	TCP_LOG_EVENT(tp, NULL,
1277 	    &inp->inp_socket->so_rcv,
1278 	    &inp->inp_socket->so_snd,
1279 	    TCP_LOG_USERSEND, error,
1280 	    0, NULL, false);
1281 out:
1282 	/*
1283 	 * If the request was unsuccessful and we changed flags,
1284 	 * restore the original flags.
1285 	 */
1286 	if (error != 0 && restoreflags) {
1287 		inp->inp_vflag = vflagsav;
1288 		inp->inp_inc.inc_flags = incflagsav;
1289 	}
1290 	TCPDEBUG2((flags & PRUS_OOB) ? PRU_SENDOOB :
1291 		  ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1292 	TCP_PROBE2(debug__user, tp, (flags & PRUS_OOB) ? PRU_SENDOOB :
1293 		   ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1294 	INP_WUNLOCK(inp);
1295 	NET_EPOCH_EXIT(et);
1296 	return (error);
1297 }
1298 
1299 static int
1300 tcp_usr_ready(struct socket *so, struct mbuf *m, int count)
1301 {
1302 	struct epoch_tracker et;
1303 	struct inpcb *inp;
1304 	struct tcpcb *tp;
1305 	int error;
1306 
1307 	inp = sotoinpcb(so);
1308 	INP_WLOCK(inp);
1309 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1310 		INP_WUNLOCK(inp);
1311 		mb_free_notready(m, count);
1312 		return (ECONNRESET);
1313 	}
1314 	tp = intotcpcb(inp);
1315 
1316 	SOCKBUF_LOCK(&so->so_snd);
1317 	error = sbready(&so->so_snd, m, count);
1318 	SOCKBUF_UNLOCK(&so->so_snd);
1319 	if (error == 0) {
1320 		NET_EPOCH_ENTER(et);
1321 		error = tp->t_fb->tfb_tcp_output(tp);
1322 		NET_EPOCH_EXIT(et);
1323 	}
1324 	INP_WUNLOCK(inp);
1325 
1326 	return (error);
1327 }
1328 
1329 /*
1330  * Abort the TCP.  Drop the connection abruptly.
1331  */
1332 static void
1333 tcp_usr_abort(struct socket *so)
1334 {
1335 	struct inpcb *inp;
1336 	struct tcpcb *tp = NULL;
1337 	struct epoch_tracker et;
1338 	TCPDEBUG0;
1339 
1340 	inp = sotoinpcb(so);
1341 	KASSERT(inp != NULL, ("tcp_usr_abort: inp == NULL"));
1342 
1343 	NET_EPOCH_ENTER(et);
1344 	INP_WLOCK(inp);
1345 	KASSERT(inp->inp_socket != NULL,
1346 	    ("tcp_usr_abort: inp_socket == NULL"));
1347 
1348 	/*
1349 	 * If we still have full TCP state, and we're not dropped, drop.
1350 	 */
1351 	if (!(inp->inp_flags & INP_TIMEWAIT) &&
1352 	    !(inp->inp_flags & INP_DROPPED)) {
1353 		tp = intotcpcb(inp);
1354 		TCPDEBUG1();
1355 		tp = tcp_drop(tp, ECONNABORTED);
1356 		if (tp == NULL)
1357 			goto dropped;
1358 		TCPDEBUG2(PRU_ABORT);
1359 		TCP_PROBE2(debug__user, tp, PRU_ABORT);
1360 	}
1361 	if (!(inp->inp_flags & INP_DROPPED)) {
1362 		SOCK_LOCK(so);
1363 		so->so_state |= SS_PROTOREF;
1364 		SOCK_UNLOCK(so);
1365 		inp->inp_flags |= INP_SOCKREF;
1366 	}
1367 	INP_WUNLOCK(inp);
1368 dropped:
1369 	NET_EPOCH_EXIT(et);
1370 }
1371 
1372 /*
1373  * TCP socket is closed.  Start friendly disconnect.
1374  */
1375 static void
1376 tcp_usr_close(struct socket *so)
1377 {
1378 	struct inpcb *inp;
1379 	struct tcpcb *tp = NULL;
1380 	struct epoch_tracker et;
1381 	TCPDEBUG0;
1382 
1383 	inp = sotoinpcb(so);
1384 	KASSERT(inp != NULL, ("tcp_usr_close: inp == NULL"));
1385 
1386 	NET_EPOCH_ENTER(et);
1387 	INP_WLOCK(inp);
1388 	KASSERT(inp->inp_socket != NULL,
1389 	    ("tcp_usr_close: inp_socket == NULL"));
1390 
1391 	/*
1392 	 * If we still have full TCP state, and we're not dropped, initiate
1393 	 * a disconnect.
1394 	 */
1395 	if (!(inp->inp_flags & INP_TIMEWAIT) &&
1396 	    !(inp->inp_flags & INP_DROPPED)) {
1397 		tp = intotcpcb(inp);
1398 		TCPDEBUG1();
1399 		tcp_disconnect(tp);
1400 		TCPDEBUG2(PRU_CLOSE);
1401 		TCP_PROBE2(debug__user, tp, PRU_CLOSE);
1402 	}
1403 	if (!(inp->inp_flags & INP_DROPPED)) {
1404 		SOCK_LOCK(so);
1405 		so->so_state |= SS_PROTOREF;
1406 		SOCK_UNLOCK(so);
1407 		inp->inp_flags |= INP_SOCKREF;
1408 	}
1409 	INP_WUNLOCK(inp);
1410 	NET_EPOCH_EXIT(et);
1411 }
1412 
1413 static int
1414 tcp_pru_options_support(struct tcpcb *tp, int flags)
1415 {
1416 	/*
1417 	 * If the specific TCP stack has a pru_options
1418 	 * specified then it does not always support
1419 	 * all the PRU_XX options and we must ask it.
1420 	 * If the function is not specified then all
1421 	 * of the PRU_XX options are supported.
1422 	 */
1423 	int ret = 0;
1424 
1425 	if (tp->t_fb->tfb_pru_options) {
1426 		ret = (*tp->t_fb->tfb_pru_options)(tp, flags);
1427 	}
1428 	return (ret);
1429 }
1430 
1431 /*
1432  * Receive out-of-band data.
1433  */
1434 static int
1435 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1436 {
1437 	int error = 0;
1438 	struct inpcb *inp;
1439 	struct tcpcb *tp = NULL;
1440 
1441 	TCPDEBUG0;
1442 	inp = sotoinpcb(so);
1443 	KASSERT(inp != NULL, ("tcp_usr_rcvoob: inp == NULL"));
1444 	INP_WLOCK(inp);
1445 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1446 		error = ECONNRESET;
1447 		goto out;
1448 	}
1449 	tp = intotcpcb(inp);
1450 	error = tcp_pru_options_support(tp, PRUS_OOB);
1451 	if (error) {
1452 		goto out;
1453 	}
1454 	TCPDEBUG1();
1455 	if ((so->so_oobmark == 0 &&
1456 	     (so->so_rcv.sb_state & SBS_RCVATMARK) == 0) ||
1457 	    so->so_options & SO_OOBINLINE ||
1458 	    tp->t_oobflags & TCPOOB_HADDATA) {
1459 		error = EINVAL;
1460 		goto out;
1461 	}
1462 	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1463 		error = EWOULDBLOCK;
1464 		goto out;
1465 	}
1466 	m->m_len = 1;
1467 	*mtod(m, caddr_t) = tp->t_iobc;
1468 	if ((flags & MSG_PEEK) == 0)
1469 		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1470 
1471 out:
1472 	TCPDEBUG2(PRU_RCVOOB);
1473 	TCP_PROBE2(debug__user, tp, PRU_RCVOOB);
1474 	INP_WUNLOCK(inp);
1475 	return (error);
1476 }
1477 
1478 #ifdef INET
1479 struct pr_usrreqs tcp_usrreqs = {
1480 	.pru_abort =		tcp_usr_abort,
1481 	.pru_accept =		tcp_usr_accept,
1482 	.pru_attach =		tcp_usr_attach,
1483 	.pru_bind =		tcp_usr_bind,
1484 	.pru_connect =		tcp_usr_connect,
1485 	.pru_control =		in_control,
1486 	.pru_detach =		tcp_usr_detach,
1487 	.pru_disconnect =	tcp_usr_disconnect,
1488 	.pru_listen =		tcp_usr_listen,
1489 	.pru_peeraddr =		in_getpeeraddr,
1490 	.pru_rcvd =		tcp_usr_rcvd,
1491 	.pru_rcvoob =		tcp_usr_rcvoob,
1492 	.pru_send =		tcp_usr_send,
1493 	.pru_ready =		tcp_usr_ready,
1494 	.pru_shutdown =		tcp_usr_shutdown,
1495 	.pru_sockaddr =		in_getsockaddr,
1496 	.pru_sosetlabel =	in_pcbsosetlabel,
1497 	.pru_close =		tcp_usr_close,
1498 };
1499 #endif /* INET */
1500 
1501 #ifdef INET6
1502 struct pr_usrreqs tcp6_usrreqs = {
1503 	.pru_abort =		tcp_usr_abort,
1504 	.pru_accept =		tcp6_usr_accept,
1505 	.pru_attach =		tcp_usr_attach,
1506 	.pru_bind =		tcp6_usr_bind,
1507 	.pru_connect =		tcp6_usr_connect,
1508 	.pru_control =		in6_control,
1509 	.pru_detach =		tcp_usr_detach,
1510 	.pru_disconnect =	tcp_usr_disconnect,
1511 	.pru_listen =		tcp6_usr_listen,
1512 	.pru_peeraddr =		in6_mapped_peeraddr,
1513 	.pru_rcvd =		tcp_usr_rcvd,
1514 	.pru_rcvoob =		tcp_usr_rcvoob,
1515 	.pru_send =		tcp_usr_send,
1516 	.pru_ready =		tcp_usr_ready,
1517 	.pru_shutdown =		tcp_usr_shutdown,
1518 	.pru_sockaddr =		in6_mapped_sockaddr,
1519 	.pru_sosetlabel =	in_pcbsosetlabel,
1520 	.pru_close =		tcp_usr_close,
1521 };
1522 #endif /* INET6 */
1523 
1524 #ifdef INET
1525 /*
1526  * Common subroutine to open a TCP connection to remote host specified
1527  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1528  * port number if needed.  Call in_pcbconnect_setup to do the routing and
1529  * to choose a local host address (interface).  If there is an existing
1530  * incarnation of the same connection in TIME-WAIT state and if the remote
1531  * host was sending CC options and if the connection duration was < MSL, then
1532  * truncate the previous TIME-WAIT state and proceed.
1533  * Initialize connection parameters and enter SYN-SENT state.
1534  */
1535 static int
1536 tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1537 {
1538 	struct inpcb *inp = tp->t_inpcb, *oinp;
1539 	struct socket *so = inp->inp_socket;
1540 	struct in_addr laddr;
1541 	u_short lport;
1542 	int error;
1543 
1544 	NET_EPOCH_ASSERT();
1545 	INP_WLOCK_ASSERT(inp);
1546 	INP_HASH_WLOCK(&V_tcbinfo);
1547 
1548 	if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1549 		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1550 		if (error)
1551 			goto out;
1552 	}
1553 
1554 	/*
1555 	 * Cannot simply call in_pcbconnect, because there might be an
1556 	 * earlier incarnation of this same connection still in
1557 	 * TIME_WAIT state, creating an ADDRINUSE error.
1558 	 */
1559 	laddr = inp->inp_laddr;
1560 	lport = inp->inp_lport;
1561 	error = in_pcbconnect_setup(inp, nam, &laddr.s_addr, &lport,
1562 	    &inp->inp_faddr.s_addr, &inp->inp_fport, &oinp, td->td_ucred);
1563 	if (error && oinp == NULL)
1564 		goto out;
1565 	if (oinp) {
1566 		error = EADDRINUSE;
1567 		goto out;
1568 	}
1569 	/* Handle initial bind if it hadn't been done in advance. */
1570 	if (inp->inp_lport == 0) {
1571 		inp->inp_lport = lport;
1572 		if (in_pcbinshash(inp) != 0) {
1573 			inp->inp_lport = 0;
1574 			error = EAGAIN;
1575 			goto out;
1576 		}
1577 	}
1578 	inp->inp_laddr = laddr;
1579 	in_pcbrehash(inp);
1580 	INP_HASH_WUNLOCK(&V_tcbinfo);
1581 
1582 	/*
1583 	 * Compute window scaling to request:
1584 	 * Scale to fit into sweet spot.  See tcp_syncache.c.
1585 	 * XXX: This should move to tcp_output().
1586 	 */
1587 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1588 	    (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1589 		tp->request_r_scale++;
1590 
1591 	soisconnecting(so);
1592 	TCPSTAT_INC(tcps_connattempt);
1593 	tcp_state_change(tp, TCPS_SYN_SENT);
1594 	tp->iss = tcp_new_isn(&inp->inp_inc);
1595 	if (tp->t_flags & TF_REQ_TSTMP)
1596 		tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1597 	tcp_sendseqinit(tp);
1598 
1599 	return 0;
1600 
1601 out:
1602 	INP_HASH_WUNLOCK(&V_tcbinfo);
1603 	return (error);
1604 }
1605 #endif /* INET */
1606 
1607 #ifdef INET6
1608 static int
1609 tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1610 {
1611 	struct inpcb *inp = tp->t_inpcb;
1612 	int error;
1613 
1614 	INP_WLOCK_ASSERT(inp);
1615 	INP_HASH_WLOCK(&V_tcbinfo);
1616 
1617 	if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1618 		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1619 		if (error)
1620 			goto out;
1621 	}
1622 	error = in6_pcbconnect(inp, nam, td->td_ucred);
1623 	if (error != 0)
1624 		goto out;
1625 	INP_HASH_WUNLOCK(&V_tcbinfo);
1626 
1627 	/* Compute window scaling to request.  */
1628 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1629 	    (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1630 		tp->request_r_scale++;
1631 
1632 	soisconnecting(inp->inp_socket);
1633 	TCPSTAT_INC(tcps_connattempt);
1634 	tcp_state_change(tp, TCPS_SYN_SENT);
1635 	tp->iss = tcp_new_isn(&inp->inp_inc);
1636 	if (tp->t_flags & TF_REQ_TSTMP)
1637 		tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1638 	tcp_sendseqinit(tp);
1639 
1640 	return 0;
1641 
1642 out:
1643 	INP_HASH_WUNLOCK(&V_tcbinfo);
1644 	return error;
1645 }
1646 #endif /* INET6 */
1647 
1648 /*
1649  * Export TCP internal state information via a struct tcp_info, based on the
1650  * Linux 2.6 API.  Not ABI compatible as our constants are mapped differently
1651  * (TCP state machine, etc).  We export all information using FreeBSD-native
1652  * constants -- for example, the numeric values for tcpi_state will differ
1653  * from Linux.
1654  */
1655 static void
1656 tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
1657 {
1658 
1659 	INP_WLOCK_ASSERT(tp->t_inpcb);
1660 	bzero(ti, sizeof(*ti));
1661 
1662 	ti->tcpi_state = tp->t_state;
1663 	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
1664 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1665 	if (tp->t_flags & TF_SACK_PERMIT)
1666 		ti->tcpi_options |= TCPI_OPT_SACK;
1667 	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
1668 		ti->tcpi_options |= TCPI_OPT_WSCALE;
1669 		ti->tcpi_snd_wscale = tp->snd_scale;
1670 		ti->tcpi_rcv_wscale = tp->rcv_scale;
1671 	}
1672 	if (tp->t_flags2 & TF2_ECN_PERMIT)
1673 		ti->tcpi_options |= TCPI_OPT_ECN;
1674 
1675 	ti->tcpi_rto = tp->t_rxtcur * tick;
1676 	ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
1677 	ti->tcpi_rtt = ((u_int64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
1678 	ti->tcpi_rttvar = ((u_int64_t)tp->t_rttvar * tick) >> TCP_RTTVAR_SHIFT;
1679 
1680 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1681 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
1682 
1683 	/*
1684 	 * FreeBSD-specific extension fields for tcp_info.
1685 	 */
1686 	ti->tcpi_rcv_space = tp->rcv_wnd;
1687 	ti->tcpi_rcv_nxt = tp->rcv_nxt;
1688 	ti->tcpi_snd_wnd = tp->snd_wnd;
1689 	ti->tcpi_snd_bwnd = 0;		/* Unused, kept for compat. */
1690 	ti->tcpi_snd_nxt = tp->snd_nxt;
1691 	ti->tcpi_snd_mss = tp->t_maxseg;
1692 	ti->tcpi_rcv_mss = tp->t_maxseg;
1693 	ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
1694 	ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
1695 	ti->tcpi_snd_zerowin = tp->t_sndzerowin;
1696 #ifdef TCP_OFFLOAD
1697 	if (tp->t_flags & TF_TOE) {
1698 		ti->tcpi_options |= TCPI_OPT_TOE;
1699 		tcp_offload_tcp_info(tp, ti);
1700 	}
1701 #endif
1702 }
1703 
1704 /*
1705  * tcp_ctloutput() must drop the inpcb lock before performing copyin on
1706  * socket option arguments.  When it re-acquires the lock after the copy, it
1707  * has to revalidate that the connection is still valid for the socket
1708  * option.
1709  */
1710 #define INP_WLOCK_RECHECK_CLEANUP(inp, cleanup) do {			\
1711 	INP_WLOCK(inp);							\
1712 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {		\
1713 		INP_WUNLOCK(inp);					\
1714 		cleanup;						\
1715 		return (ECONNRESET);					\
1716 	}								\
1717 	tp = intotcpcb(inp);						\
1718 } while(0)
1719 #define INP_WLOCK_RECHECK(inp) INP_WLOCK_RECHECK_CLEANUP((inp), /* noop */)
1720 
1721 int
1722 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
1723 {
1724 	int	error;
1725 	struct	inpcb *inp;
1726 	struct	tcpcb *tp;
1727 	struct tcp_function_block *blk;
1728 	struct tcp_function_set fsn;
1729 
1730 	error = 0;
1731 	inp = sotoinpcb(so);
1732 	KASSERT(inp != NULL, ("tcp_ctloutput: inp == NULL"));
1733 	if (sopt->sopt_level != IPPROTO_TCP) {
1734 #ifdef INET6
1735 		if (inp->inp_vflag & INP_IPV6PROTO) {
1736 			error = ip6_ctloutput(so, sopt);
1737 			/*
1738 			 * In case of the IPV6_USE_MIN_MTU socket option,
1739 			 * the INC_IPV6MINMTU flag to announce a corresponding
1740 			 * MSS during the initial handshake.
1741 			 * If the TCP connection is not in the front states,
1742 			 * just reduce the MSS being used.
1743 			 * This avoids the sending of TCP segments which will
1744 			 * be fragmented at the IPv6 layer.
1745 			 */
1746 			if ((error == 0) &&
1747 			    (sopt->sopt_dir == SOPT_SET) &&
1748 			    (sopt->sopt_level == IPPROTO_IPV6) &&
1749 			    (sopt->sopt_name == IPV6_USE_MIN_MTU)) {
1750 				INP_WLOCK(inp);
1751 				if ((inp->inp_flags &
1752 				    (INP_TIMEWAIT | INP_DROPPED))) {
1753 					INP_WUNLOCK(inp);
1754 					return (ECONNRESET);
1755 				}
1756 				inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
1757 				tp = intotcpcb(inp);
1758 				if ((tp->t_state >= TCPS_SYN_SENT) &&
1759 				    (inp->inp_inc.inc_flags & INC_ISIPV6)) {
1760 					struct ip6_pktopts *opt;
1761 
1762 					opt = inp->in6p_outputopts;
1763 					if ((opt != NULL) &&
1764 					    (opt->ip6po_minmtu ==
1765 					    IP6PO_MINMTU_ALL)) {
1766 						if (tp->t_maxseg > TCP6_MSS) {
1767 							tp->t_maxseg = TCP6_MSS;
1768 						}
1769 					}
1770 				}
1771 				INP_WUNLOCK(inp);
1772 			}
1773 		}
1774 #endif /* INET6 */
1775 #if defined(INET6) && defined(INET)
1776 		else
1777 #endif
1778 #ifdef INET
1779 		{
1780 			error = ip_ctloutput(so, sopt);
1781 		}
1782 #endif
1783 		return (error);
1784 	}
1785 	INP_WLOCK(inp);
1786 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1787 		INP_WUNLOCK(inp);
1788 		return (ECONNRESET);
1789 	}
1790 	tp = intotcpcb(inp);
1791 	/*
1792 	 * Protect the TCP option TCP_FUNCTION_BLK so
1793 	 * that a sub-function can *never* overwrite this.
1794 	 */
1795 	if ((sopt->sopt_dir == SOPT_SET) &&
1796 	    (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1797 		INP_WUNLOCK(inp);
1798 		error = sooptcopyin(sopt, &fsn, sizeof fsn,
1799 		    sizeof fsn);
1800 		if (error)
1801 			return (error);
1802 		INP_WLOCK_RECHECK(inp);
1803 		blk = find_and_ref_tcp_functions(&fsn);
1804 		if (blk == NULL) {
1805 			INP_WUNLOCK(inp);
1806 			return (ENOENT);
1807 		}
1808 		if (tp->t_fb == blk) {
1809 			/* You already have this */
1810 			refcount_release(&blk->tfb_refcnt);
1811 			INP_WUNLOCK(inp);
1812 			return (0);
1813 		}
1814 		if (tp->t_state != TCPS_CLOSED) {
1815 			/*
1816 			 * The user has advanced the state
1817 			 * past the initial point, we may not
1818 			 * be able to switch.
1819 			 */
1820 			if (blk->tfb_tcp_handoff_ok != NULL) {
1821 				/*
1822 				 * Does the stack provide a
1823 				 * query mechanism, if so it may
1824 				 * still be possible?
1825 				 */
1826 				error = (*blk->tfb_tcp_handoff_ok)(tp);
1827 			} else
1828 				error = EINVAL;
1829 			if (error) {
1830 				refcount_release(&blk->tfb_refcnt);
1831 				INP_WUNLOCK(inp);
1832 				return(error);
1833 			}
1834 		}
1835 		if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1836 			refcount_release(&blk->tfb_refcnt);
1837 			INP_WUNLOCK(inp);
1838 			return (ENOENT);
1839 		}
1840 		/*
1841 		 * Release the old refcnt, the
1842 		 * lookup acquired a ref on the
1843 		 * new one already.
1844 		 */
1845 		if (tp->t_fb->tfb_tcp_fb_fini) {
1846 			/*
1847 			 * Tell the stack to cleanup with 0 i.e.
1848 			 * the tcb is not going away.
1849 			 */
1850 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
1851 		}
1852 #ifdef TCPHPTS
1853 		/* Assure that we are not on any hpts */
1854 		tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_ALL);
1855 #endif
1856 		if (blk->tfb_tcp_fb_init) {
1857 			error = (*blk->tfb_tcp_fb_init)(tp);
1858 			if (error) {
1859 				refcount_release(&blk->tfb_refcnt);
1860 				if (tp->t_fb->tfb_tcp_fb_init) {
1861 					if((*tp->t_fb->tfb_tcp_fb_init)(tp) != 0)  {
1862 						/* Fall back failed, drop the connection */
1863 						INP_WUNLOCK(inp);
1864 						soabort(so);
1865 						return(error);
1866 					}
1867 				}
1868 				goto err_out;
1869 			}
1870 		}
1871 		refcount_release(&tp->t_fb->tfb_refcnt);
1872 		tp->t_fb = blk;
1873 #ifdef TCP_OFFLOAD
1874 		if (tp->t_flags & TF_TOE) {
1875 			tcp_offload_ctloutput(tp, sopt->sopt_dir,
1876 			     sopt->sopt_name);
1877 		}
1878 #endif
1879 err_out:
1880 		INP_WUNLOCK(inp);
1881 		return (error);
1882 	} else if ((sopt->sopt_dir == SOPT_GET) &&
1883 	    (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1884 		strncpy(fsn.function_set_name, tp->t_fb->tfb_tcp_block_name,
1885 		    TCP_FUNCTION_NAME_LEN_MAX);
1886 		fsn.function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
1887 		fsn.pcbcnt = tp->t_fb->tfb_refcnt;
1888 		INP_WUNLOCK(inp);
1889 		error = sooptcopyout(sopt, &fsn, sizeof fsn);
1890 		return (error);
1891 	}
1892 	/* Pass in the INP locked, called must unlock it */
1893 	return (tp->t_fb->tfb_tcp_ctloutput(so, sopt, inp, tp));
1894 }
1895 
1896 /*
1897  * If this assert becomes untrue, we need to change the size of the buf
1898  * variable in tcp_default_ctloutput().
1899  */
1900 #ifdef CTASSERT
1901 CTASSERT(TCP_CA_NAME_MAX <= TCP_LOG_ID_LEN);
1902 CTASSERT(TCP_LOG_REASON_LEN <= TCP_LOG_ID_LEN);
1903 #endif
1904 
1905 #ifdef KERN_TLS
1906 static int
1907 copyin_tls_enable(struct sockopt *sopt, struct tls_enable *tls)
1908 {
1909 	struct tls_enable_v0 tls_v0;
1910 	int error;
1911 
1912 	if (sopt->sopt_valsize == sizeof(tls_v0)) {
1913 		error = sooptcopyin(sopt, &tls_v0, sizeof(tls_v0),
1914 		    sizeof(tls_v0));
1915 		if (error)
1916 			return (error);
1917 		memset(tls, 0, sizeof(*tls));
1918 		tls->cipher_key = tls_v0.cipher_key;
1919 		tls->iv = tls_v0.iv;
1920 		tls->auth_key = tls_v0.auth_key;
1921 		tls->cipher_algorithm = tls_v0.cipher_algorithm;
1922 		tls->cipher_key_len = tls_v0.cipher_key_len;
1923 		tls->iv_len = tls_v0.iv_len;
1924 		tls->auth_algorithm = tls_v0.auth_algorithm;
1925 		tls->auth_key_len = tls_v0.auth_key_len;
1926 		tls->flags = tls_v0.flags;
1927 		tls->tls_vmajor = tls_v0.tls_vmajor;
1928 		tls->tls_vminor = tls_v0.tls_vminor;
1929 		return (0);
1930 	}
1931 
1932 	return (sooptcopyin(sopt, tls, sizeof(*tls), sizeof(*tls)));
1933 }
1934 #endif
1935 
1936 int
1937 tcp_default_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
1938 {
1939 	int	error, opt, optval;
1940 	u_int	ui;
1941 	struct	tcp_info ti;
1942 #ifdef KERN_TLS
1943 	struct tls_enable tls;
1944 #endif
1945 	struct cc_algo *algo;
1946 	char	*pbuf, buf[TCP_LOG_ID_LEN];
1947 #ifdef STATS
1948 	struct statsblob *sbp;
1949 #endif
1950 	size_t	len;
1951 
1952 	/*
1953 	 * For TCP_CCALGOOPT forward the control to CC module, for both
1954 	 * SOPT_SET and SOPT_GET.
1955 	 */
1956 	switch (sopt->sopt_name) {
1957 	case TCP_CCALGOOPT:
1958 		INP_WUNLOCK(inp);
1959 		if (sopt->sopt_valsize > CC_ALGOOPT_LIMIT)
1960 			return (EINVAL);
1961 		pbuf = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK | M_ZERO);
1962 		error = sooptcopyin(sopt, pbuf, sopt->sopt_valsize,
1963 		    sopt->sopt_valsize);
1964 		if (error) {
1965 			free(pbuf, M_TEMP);
1966 			return (error);
1967 		}
1968 		INP_WLOCK_RECHECK_CLEANUP(inp, free(pbuf, M_TEMP));
1969 		if (CC_ALGO(tp)->ctl_output != NULL)
1970 			error = CC_ALGO(tp)->ctl_output(tp->ccv, sopt, pbuf);
1971 		else
1972 			error = ENOENT;
1973 		INP_WUNLOCK(inp);
1974 		if (error == 0 && sopt->sopt_dir == SOPT_GET)
1975 			error = sooptcopyout(sopt, pbuf, sopt->sopt_valsize);
1976 		free(pbuf, M_TEMP);
1977 		return (error);
1978 	}
1979 
1980 	switch (sopt->sopt_dir) {
1981 	case SOPT_SET:
1982 		switch (sopt->sopt_name) {
1983 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1984 		case TCP_MD5SIG:
1985 			if (!TCPMD5_ENABLED()) {
1986 				INP_WUNLOCK(inp);
1987 				return (ENOPROTOOPT);
1988 			}
1989 			error = TCPMD5_PCBCTL(inp, sopt);
1990 			if (error)
1991 				return (error);
1992 			goto unlock_and_done;
1993 #endif /* IPSEC */
1994 
1995 		case TCP_NODELAY:
1996 		case TCP_NOOPT:
1997 			INP_WUNLOCK(inp);
1998 			error = sooptcopyin(sopt, &optval, sizeof optval,
1999 			    sizeof optval);
2000 			if (error)
2001 				return (error);
2002 
2003 			INP_WLOCK_RECHECK(inp);
2004 			switch (sopt->sopt_name) {
2005 			case TCP_NODELAY:
2006 				opt = TF_NODELAY;
2007 				break;
2008 			case TCP_NOOPT:
2009 				opt = TF_NOOPT;
2010 				break;
2011 			default:
2012 				opt = 0; /* dead code to fool gcc */
2013 				break;
2014 			}
2015 
2016 			if (optval)
2017 				tp->t_flags |= opt;
2018 			else
2019 				tp->t_flags &= ~opt;
2020 unlock_and_done:
2021 #ifdef TCP_OFFLOAD
2022 			if (tp->t_flags & TF_TOE) {
2023 				tcp_offload_ctloutput(tp, sopt->sopt_dir,
2024 				    sopt->sopt_name);
2025 			}
2026 #endif
2027 			INP_WUNLOCK(inp);
2028 			break;
2029 
2030 		case TCP_NOPUSH:
2031 			INP_WUNLOCK(inp);
2032 			error = sooptcopyin(sopt, &optval, sizeof optval,
2033 			    sizeof optval);
2034 			if (error)
2035 				return (error);
2036 
2037 			INP_WLOCK_RECHECK(inp);
2038 			if (optval)
2039 				tp->t_flags |= TF_NOPUSH;
2040 			else if (tp->t_flags & TF_NOPUSH) {
2041 				tp->t_flags &= ~TF_NOPUSH;
2042 				if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2043 					struct epoch_tracker et;
2044 
2045 					NET_EPOCH_ENTER(et);
2046 					error = tp->t_fb->tfb_tcp_output(tp);
2047 					NET_EPOCH_EXIT(et);
2048 				}
2049 			}
2050 			goto unlock_and_done;
2051 
2052 		case TCP_MAXSEG:
2053 			INP_WUNLOCK(inp);
2054 			error = sooptcopyin(sopt, &optval, sizeof optval,
2055 			    sizeof optval);
2056 			if (error)
2057 				return (error);
2058 
2059 			INP_WLOCK_RECHECK(inp);
2060 			if (optval > 0 && optval <= tp->t_maxseg &&
2061 			    optval + 40 >= V_tcp_minmss)
2062 				tp->t_maxseg = optval;
2063 			else
2064 				error = EINVAL;
2065 			goto unlock_and_done;
2066 
2067 		case TCP_INFO:
2068 			INP_WUNLOCK(inp);
2069 			error = EINVAL;
2070 			break;
2071 
2072 		case TCP_STATS:
2073 			INP_WUNLOCK(inp);
2074 #ifdef STATS
2075 			error = sooptcopyin(sopt, &optval, sizeof optval,
2076 			    sizeof optval);
2077 			if (error)
2078 				return (error);
2079 
2080 			if (optval > 0)
2081 				sbp = stats_blob_alloc(
2082 				    V_tcp_perconn_stats_dflt_tpl, 0);
2083 			else
2084 				sbp = NULL;
2085 
2086 			INP_WLOCK_RECHECK(inp);
2087 			if ((tp->t_stats != NULL && sbp == NULL) ||
2088 			    (tp->t_stats == NULL && sbp != NULL)) {
2089 				struct statsblob *t = tp->t_stats;
2090 				tp->t_stats = sbp;
2091 				sbp = t;
2092 			}
2093 			INP_WUNLOCK(inp);
2094 
2095 			stats_blob_destroy(sbp);
2096 #else
2097 			return (EOPNOTSUPP);
2098 #endif /* !STATS */
2099 			break;
2100 
2101 		case TCP_CONGESTION:
2102 			INP_WUNLOCK(inp);
2103 			error = sooptcopyin(sopt, buf, TCP_CA_NAME_MAX - 1, 1);
2104 			if (error)
2105 				break;
2106 			buf[sopt->sopt_valsize] = '\0';
2107 			INP_WLOCK_RECHECK(inp);
2108 			CC_LIST_RLOCK();
2109 			STAILQ_FOREACH(algo, &cc_list, entries)
2110 				if (strncmp(buf, algo->name,
2111 				    TCP_CA_NAME_MAX) == 0)
2112 					break;
2113 			CC_LIST_RUNLOCK();
2114 			if (algo == NULL) {
2115 				INP_WUNLOCK(inp);
2116 				error = EINVAL;
2117 				break;
2118 			}
2119 			/*
2120 			 * We hold a write lock over the tcb so it's safe to
2121 			 * do these things without ordering concerns.
2122 			 */
2123 			if (CC_ALGO(tp)->cb_destroy != NULL)
2124 				CC_ALGO(tp)->cb_destroy(tp->ccv);
2125 			CC_DATA(tp) = NULL;
2126 			CC_ALGO(tp) = algo;
2127 			/*
2128 			 * If something goes pear shaped initialising the new
2129 			 * algo, fall back to newreno (which does not
2130 			 * require initialisation).
2131 			 */
2132 			if (algo->cb_init != NULL &&
2133 			    algo->cb_init(tp->ccv) != 0) {
2134 				CC_ALGO(tp) = &newreno_cc_algo;
2135 				/*
2136 				 * The only reason init should fail is
2137 				 * because of malloc.
2138 				 */
2139 				error = ENOMEM;
2140 			}
2141 			INP_WUNLOCK(inp);
2142 			break;
2143 
2144 		case TCP_REUSPORT_LB_NUMA:
2145 			INP_WUNLOCK(inp);
2146 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2147 			    sizeof(optval));
2148 			INP_WLOCK_RECHECK(inp);
2149 			if (!error)
2150 				error = in_pcblbgroup_numa(inp, optval);
2151 			INP_WUNLOCK(inp);
2152 			break;
2153 
2154 #ifdef KERN_TLS
2155 		case TCP_TXTLS_ENABLE:
2156 			INP_WUNLOCK(inp);
2157 			error = copyin_tls_enable(sopt, &tls);
2158 			if (error)
2159 				break;
2160 			error = ktls_enable_tx(so, &tls);
2161 			break;
2162 		case TCP_TXTLS_MODE:
2163 			INP_WUNLOCK(inp);
2164 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2165 			if (error)
2166 				return (error);
2167 
2168 			INP_WLOCK_RECHECK(inp);
2169 			error = ktls_set_tx_mode(so, ui);
2170 			INP_WUNLOCK(inp);
2171 			break;
2172 		case TCP_RXTLS_ENABLE:
2173 			INP_WUNLOCK(inp);
2174 			error = sooptcopyin(sopt, &tls, sizeof(tls),
2175 			    sizeof(tls));
2176 			if (error)
2177 				break;
2178 			error = ktls_enable_rx(so, &tls);
2179 			break;
2180 #endif
2181 
2182 		case TCP_KEEPIDLE:
2183 		case TCP_KEEPINTVL:
2184 		case TCP_KEEPINIT:
2185 			INP_WUNLOCK(inp);
2186 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2187 			if (error)
2188 				return (error);
2189 
2190 			if (ui > (UINT_MAX / hz)) {
2191 				error = EINVAL;
2192 				break;
2193 			}
2194 			ui *= hz;
2195 
2196 			INP_WLOCK_RECHECK(inp);
2197 			switch (sopt->sopt_name) {
2198 			case TCP_KEEPIDLE:
2199 				tp->t_keepidle = ui;
2200 				/*
2201 				 * XXX: better check current remaining
2202 				 * timeout and "merge" it with new value.
2203 				 */
2204 				if ((tp->t_state > TCPS_LISTEN) &&
2205 				    (tp->t_state <= TCPS_CLOSING))
2206 					tcp_timer_activate(tp, TT_KEEP,
2207 					    TP_KEEPIDLE(tp));
2208 				break;
2209 			case TCP_KEEPINTVL:
2210 				tp->t_keepintvl = ui;
2211 				if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2212 				    (TP_MAXIDLE(tp) > 0))
2213 					tcp_timer_activate(tp, TT_2MSL,
2214 					    TP_MAXIDLE(tp));
2215 				break;
2216 			case TCP_KEEPINIT:
2217 				tp->t_keepinit = ui;
2218 				if (tp->t_state == TCPS_SYN_RECEIVED ||
2219 				    tp->t_state == TCPS_SYN_SENT)
2220 					tcp_timer_activate(tp, TT_KEEP,
2221 					    TP_KEEPINIT(tp));
2222 				break;
2223 			}
2224 			goto unlock_and_done;
2225 
2226 		case TCP_KEEPCNT:
2227 			INP_WUNLOCK(inp);
2228 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2229 			if (error)
2230 				return (error);
2231 
2232 			INP_WLOCK_RECHECK(inp);
2233 			tp->t_keepcnt = ui;
2234 			if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2235 			    (TP_MAXIDLE(tp) > 0))
2236 				tcp_timer_activate(tp, TT_2MSL,
2237 				    TP_MAXIDLE(tp));
2238 			goto unlock_and_done;
2239 
2240 #ifdef TCPPCAP
2241 		case TCP_PCAP_OUT:
2242 		case TCP_PCAP_IN:
2243 			INP_WUNLOCK(inp);
2244 			error = sooptcopyin(sopt, &optval, sizeof optval,
2245 			    sizeof optval);
2246 			if (error)
2247 				return (error);
2248 
2249 			INP_WLOCK_RECHECK(inp);
2250 			if (optval >= 0)
2251 				tcp_pcap_set_sock_max(TCP_PCAP_OUT ?
2252 					&(tp->t_outpkts) : &(tp->t_inpkts),
2253 					optval);
2254 			else
2255 				error = EINVAL;
2256 			goto unlock_and_done;
2257 #endif
2258 
2259 		case TCP_FASTOPEN: {
2260 			struct tcp_fastopen tfo_optval;
2261 
2262 			INP_WUNLOCK(inp);
2263 			if (!V_tcp_fastopen_client_enable &&
2264 			    !V_tcp_fastopen_server_enable)
2265 				return (EPERM);
2266 
2267 			error = sooptcopyin(sopt, &tfo_optval,
2268 				    sizeof(tfo_optval), sizeof(int));
2269 			if (error)
2270 				return (error);
2271 
2272 			INP_WLOCK_RECHECK(inp);
2273 			if ((tp->t_state != TCPS_CLOSED) &&
2274 			    (tp->t_state != TCPS_LISTEN)) {
2275 				error = EINVAL;
2276 				goto unlock_and_done;
2277 			}
2278 			if (tfo_optval.enable) {
2279 				if (tp->t_state == TCPS_LISTEN) {
2280 					if (!V_tcp_fastopen_server_enable) {
2281 						error = EPERM;
2282 						goto unlock_and_done;
2283 					}
2284 
2285 					if (tp->t_tfo_pending == NULL)
2286 						tp->t_tfo_pending =
2287 						    tcp_fastopen_alloc_counter();
2288 				} else {
2289 					/*
2290 					 * If a pre-shared key was provided,
2291 					 * stash it in the client cookie
2292 					 * field of the tcpcb for use during
2293 					 * connect.
2294 					 */
2295 					if (sopt->sopt_valsize ==
2296 					    sizeof(tfo_optval)) {
2297 						memcpy(tp->t_tfo_cookie.client,
2298 						       tfo_optval.psk,
2299 						       TCP_FASTOPEN_PSK_LEN);
2300 						tp->t_tfo_client_cookie_len =
2301 						    TCP_FASTOPEN_PSK_LEN;
2302 					}
2303 				}
2304 				tp->t_flags |= TF_FASTOPEN;
2305 			} else
2306 				tp->t_flags &= ~TF_FASTOPEN;
2307 			goto unlock_and_done;
2308 		}
2309 
2310 #ifdef TCP_BLACKBOX
2311 		case TCP_LOG:
2312 			INP_WUNLOCK(inp);
2313 			error = sooptcopyin(sopt, &optval, sizeof optval,
2314 			    sizeof optval);
2315 			if (error)
2316 				return (error);
2317 
2318 			INP_WLOCK_RECHECK(inp);
2319 			error = tcp_log_state_change(tp, optval);
2320 			goto unlock_and_done;
2321 
2322 		case TCP_LOGBUF:
2323 			INP_WUNLOCK(inp);
2324 			error = EINVAL;
2325 			break;
2326 
2327 		case TCP_LOGID:
2328 			INP_WUNLOCK(inp);
2329 			error = sooptcopyin(sopt, buf, TCP_LOG_ID_LEN - 1, 0);
2330 			if (error)
2331 				break;
2332 			buf[sopt->sopt_valsize] = '\0';
2333 			INP_WLOCK_RECHECK(inp);
2334 			error = tcp_log_set_id(tp, buf);
2335 			/* tcp_log_set_id() unlocks the INP. */
2336 			break;
2337 
2338 		case TCP_LOGDUMP:
2339 		case TCP_LOGDUMPID:
2340 			INP_WUNLOCK(inp);
2341 			error =
2342 			    sooptcopyin(sopt, buf, TCP_LOG_REASON_LEN - 1, 0);
2343 			if (error)
2344 				break;
2345 			buf[sopt->sopt_valsize] = '\0';
2346 			INP_WLOCK_RECHECK(inp);
2347 			if (sopt->sopt_name == TCP_LOGDUMP) {
2348 				error = tcp_log_dump_tp_logbuf(tp, buf,
2349 				    M_WAITOK, true);
2350 				INP_WUNLOCK(inp);
2351 			} else {
2352 				tcp_log_dump_tp_bucket_logbufs(tp, buf);
2353 				/*
2354 				 * tcp_log_dump_tp_bucket_logbufs() drops the
2355 				 * INP lock.
2356 				 */
2357 			}
2358 			break;
2359 #endif
2360 
2361 		default:
2362 			INP_WUNLOCK(inp);
2363 			error = ENOPROTOOPT;
2364 			break;
2365 		}
2366 		break;
2367 
2368 	case SOPT_GET:
2369 		tp = intotcpcb(inp);
2370 		switch (sopt->sopt_name) {
2371 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2372 		case TCP_MD5SIG:
2373 			if (!TCPMD5_ENABLED()) {
2374 				INP_WUNLOCK(inp);
2375 				return (ENOPROTOOPT);
2376 			}
2377 			error = TCPMD5_PCBCTL(inp, sopt);
2378 			break;
2379 #endif
2380 
2381 		case TCP_NODELAY:
2382 			optval = tp->t_flags & TF_NODELAY;
2383 			INP_WUNLOCK(inp);
2384 			error = sooptcopyout(sopt, &optval, sizeof optval);
2385 			break;
2386 		case TCP_MAXSEG:
2387 			optval = tp->t_maxseg;
2388 			INP_WUNLOCK(inp);
2389 			error = sooptcopyout(sopt, &optval, sizeof optval);
2390 			break;
2391 		case TCP_NOOPT:
2392 			optval = tp->t_flags & TF_NOOPT;
2393 			INP_WUNLOCK(inp);
2394 			error = sooptcopyout(sopt, &optval, sizeof optval);
2395 			break;
2396 		case TCP_NOPUSH:
2397 			optval = tp->t_flags & TF_NOPUSH;
2398 			INP_WUNLOCK(inp);
2399 			error = sooptcopyout(sopt, &optval, sizeof optval);
2400 			break;
2401 		case TCP_INFO:
2402 			tcp_fill_info(tp, &ti);
2403 			INP_WUNLOCK(inp);
2404 			error = sooptcopyout(sopt, &ti, sizeof ti);
2405 			break;
2406 		case TCP_STATS:
2407 			{
2408 #ifdef STATS
2409 			int nheld;
2410 			TYPEOF_MEMBER(struct statsblob, flags) sbflags = 0;
2411 
2412 			error = 0;
2413 			socklen_t outsbsz = sopt->sopt_valsize;
2414 			if (tp->t_stats == NULL)
2415 				error = ENOENT;
2416 			else if (outsbsz >= tp->t_stats->cursz)
2417 				outsbsz = tp->t_stats->cursz;
2418 			else if (outsbsz >= sizeof(struct statsblob))
2419 				outsbsz = sizeof(struct statsblob);
2420 			else
2421 				error = EINVAL;
2422 			INP_WUNLOCK(inp);
2423 			if (error)
2424 				break;
2425 
2426 			sbp = sopt->sopt_val;
2427 			nheld = atop(round_page(((vm_offset_t)sbp) +
2428 			    (vm_size_t)outsbsz) - trunc_page((vm_offset_t)sbp));
2429 			vm_page_t ma[nheld];
2430 			if (vm_fault_quick_hold_pages(
2431 			    &curproc->p_vmspace->vm_map, (vm_offset_t)sbp,
2432 			    outsbsz, VM_PROT_READ | VM_PROT_WRITE, ma,
2433 			    nheld) < 0) {
2434 				error = EFAULT;
2435 				break;
2436 			}
2437 
2438 			if ((error = copyin_nofault(&(sbp->flags), &sbflags,
2439 			    SIZEOF_MEMBER(struct statsblob, flags))))
2440 				goto unhold;
2441 
2442 			INP_WLOCK_RECHECK(inp);
2443 			error = stats_blob_snapshot(&sbp, outsbsz, tp->t_stats,
2444 			    sbflags | SB_CLONE_USRDSTNOFAULT);
2445 			INP_WUNLOCK(inp);
2446 			sopt->sopt_valsize = outsbsz;
2447 unhold:
2448 			vm_page_unhold_pages(ma, nheld);
2449 #else
2450 			INP_WUNLOCK(inp);
2451 			error = EOPNOTSUPP;
2452 #endif /* !STATS */
2453 			break;
2454 			}
2455 		case TCP_CONGESTION:
2456 			len = strlcpy(buf, CC_ALGO(tp)->name, TCP_CA_NAME_MAX);
2457 			INP_WUNLOCK(inp);
2458 			error = sooptcopyout(sopt, buf, len + 1);
2459 			break;
2460 		case TCP_KEEPIDLE:
2461 		case TCP_KEEPINTVL:
2462 		case TCP_KEEPINIT:
2463 		case TCP_KEEPCNT:
2464 			switch (sopt->sopt_name) {
2465 			case TCP_KEEPIDLE:
2466 				ui = TP_KEEPIDLE(tp) / hz;
2467 				break;
2468 			case TCP_KEEPINTVL:
2469 				ui = TP_KEEPINTVL(tp) / hz;
2470 				break;
2471 			case TCP_KEEPINIT:
2472 				ui = TP_KEEPINIT(tp) / hz;
2473 				break;
2474 			case TCP_KEEPCNT:
2475 				ui = TP_KEEPCNT(tp);
2476 				break;
2477 			}
2478 			INP_WUNLOCK(inp);
2479 			error = sooptcopyout(sopt, &ui, sizeof(ui));
2480 			break;
2481 #ifdef TCPPCAP
2482 		case TCP_PCAP_OUT:
2483 		case TCP_PCAP_IN:
2484 			optval = tcp_pcap_get_sock_max(TCP_PCAP_OUT ?
2485 					&(tp->t_outpkts) : &(tp->t_inpkts));
2486 			INP_WUNLOCK(inp);
2487 			error = sooptcopyout(sopt, &optval, sizeof optval);
2488 			break;
2489 #endif
2490 		case TCP_FASTOPEN:
2491 			optval = tp->t_flags & TF_FASTOPEN;
2492 			INP_WUNLOCK(inp);
2493 			error = sooptcopyout(sopt, &optval, sizeof optval);
2494 			break;
2495 #ifdef TCP_BLACKBOX
2496 		case TCP_LOG:
2497 			optval = tp->t_logstate;
2498 			INP_WUNLOCK(inp);
2499 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2500 			break;
2501 		case TCP_LOGBUF:
2502 			/* tcp_log_getlogbuf() does INP_WUNLOCK(inp) */
2503 			error = tcp_log_getlogbuf(sopt, tp);
2504 			break;
2505 		case TCP_LOGID:
2506 			len = tcp_log_get_id(tp, buf);
2507 			INP_WUNLOCK(inp);
2508 			error = sooptcopyout(sopt, buf, len + 1);
2509 			break;
2510 		case TCP_LOGDUMP:
2511 		case TCP_LOGDUMPID:
2512 			INP_WUNLOCK(inp);
2513 			error = EINVAL;
2514 			break;
2515 #endif
2516 #ifdef KERN_TLS
2517 		case TCP_TXTLS_MODE:
2518 			optval = ktls_get_tx_mode(so);
2519 			INP_WUNLOCK(inp);
2520 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2521 			break;
2522 		case TCP_RXTLS_MODE:
2523 			optval = ktls_get_rx_mode(so);
2524 			INP_WUNLOCK(inp);
2525 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2526 			break;
2527 #endif
2528 		default:
2529 			INP_WUNLOCK(inp);
2530 			error = ENOPROTOOPT;
2531 			break;
2532 		}
2533 		break;
2534 	}
2535 	return (error);
2536 }
2537 #undef INP_WLOCK_RECHECK
2538 #undef INP_WLOCK_RECHECK_CLEANUP
2539 
2540 /*
2541  * Initiate (or continue) disconnect.
2542  * If embryonic state, just send reset (once).
2543  * If in ``let data drain'' option and linger null, just drop.
2544  * Otherwise (hard), mark socket disconnecting and drop
2545  * current input data; switch states based on user close, and
2546  * send segment to peer (with FIN).
2547  */
2548 static void
2549 tcp_disconnect(struct tcpcb *tp)
2550 {
2551 	struct inpcb *inp = tp->t_inpcb;
2552 	struct socket *so = inp->inp_socket;
2553 
2554 	NET_EPOCH_ASSERT();
2555 	INP_WLOCK_ASSERT(inp);
2556 
2557 	/*
2558 	 * Neither tcp_close() nor tcp_drop() should return NULL, as the
2559 	 * socket is still open.
2560 	 */
2561 	if (tp->t_state < TCPS_ESTABLISHED &&
2562 	    !(tp->t_state > TCPS_LISTEN && IS_FASTOPEN(tp->t_flags))) {
2563 		tp = tcp_close(tp);
2564 		KASSERT(tp != NULL,
2565 		    ("tcp_disconnect: tcp_close() returned NULL"));
2566 	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
2567 		tp = tcp_drop(tp, 0);
2568 		KASSERT(tp != NULL,
2569 		    ("tcp_disconnect: tcp_drop() returned NULL"));
2570 	} else {
2571 		soisdisconnecting(so);
2572 		sbflush(&so->so_rcv);
2573 		tcp_usrclosed(tp);
2574 		if (!(inp->inp_flags & INP_DROPPED))
2575 			tp->t_fb->tfb_tcp_output(tp);
2576 	}
2577 }
2578 
2579 /*
2580  * User issued close, and wish to trail through shutdown states:
2581  * if never received SYN, just forget it.  If got a SYN from peer,
2582  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
2583  * If already got a FIN from peer, then almost done; go to LAST_ACK
2584  * state.  In all other cases, have already sent FIN to peer (e.g.
2585  * after PRU_SHUTDOWN), and just have to play tedious game waiting
2586  * for peer to send FIN or not respond to keep-alives, etc.
2587  * We can let the user exit from the close as soon as the FIN is acked.
2588  */
2589 static void
2590 tcp_usrclosed(struct tcpcb *tp)
2591 {
2592 
2593 	NET_EPOCH_ASSERT();
2594 	INP_WLOCK_ASSERT(tp->t_inpcb);
2595 
2596 	switch (tp->t_state) {
2597 	case TCPS_LISTEN:
2598 #ifdef TCP_OFFLOAD
2599 		tcp_offload_listen_stop(tp);
2600 #endif
2601 		tcp_state_change(tp, TCPS_CLOSED);
2602 		/* FALLTHROUGH */
2603 	case TCPS_CLOSED:
2604 		tp = tcp_close(tp);
2605 		/*
2606 		 * tcp_close() should never return NULL here as the socket is
2607 		 * still open.
2608 		 */
2609 		KASSERT(tp != NULL,
2610 		    ("tcp_usrclosed: tcp_close() returned NULL"));
2611 		break;
2612 
2613 	case TCPS_SYN_SENT:
2614 	case TCPS_SYN_RECEIVED:
2615 		tp->t_flags |= TF_NEEDFIN;
2616 		break;
2617 
2618 	case TCPS_ESTABLISHED:
2619 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
2620 		break;
2621 
2622 	case TCPS_CLOSE_WAIT:
2623 		tcp_state_change(tp, TCPS_LAST_ACK);
2624 		break;
2625 	}
2626 	if (tp->t_state >= TCPS_FIN_WAIT_2) {
2627 		soisdisconnected(tp->t_inpcb->inp_socket);
2628 		/* Prevent the connection hanging in FIN_WAIT_2 forever. */
2629 		if (tp->t_state == TCPS_FIN_WAIT_2) {
2630 			int timeout;
2631 
2632 			timeout = (tcp_fast_finwait2_recycle) ?
2633 			    tcp_finwait2_timeout : TP_MAXIDLE(tp);
2634 			tcp_timer_activate(tp, TT_2MSL, timeout);
2635 		}
2636 	}
2637 }
2638 
2639 #ifdef DDB
2640 static void
2641 db_print_indent(int indent)
2642 {
2643 	int i;
2644 
2645 	for (i = 0; i < indent; i++)
2646 		db_printf(" ");
2647 }
2648 
2649 static void
2650 db_print_tstate(int t_state)
2651 {
2652 
2653 	switch (t_state) {
2654 	case TCPS_CLOSED:
2655 		db_printf("TCPS_CLOSED");
2656 		return;
2657 
2658 	case TCPS_LISTEN:
2659 		db_printf("TCPS_LISTEN");
2660 		return;
2661 
2662 	case TCPS_SYN_SENT:
2663 		db_printf("TCPS_SYN_SENT");
2664 		return;
2665 
2666 	case TCPS_SYN_RECEIVED:
2667 		db_printf("TCPS_SYN_RECEIVED");
2668 		return;
2669 
2670 	case TCPS_ESTABLISHED:
2671 		db_printf("TCPS_ESTABLISHED");
2672 		return;
2673 
2674 	case TCPS_CLOSE_WAIT:
2675 		db_printf("TCPS_CLOSE_WAIT");
2676 		return;
2677 
2678 	case TCPS_FIN_WAIT_1:
2679 		db_printf("TCPS_FIN_WAIT_1");
2680 		return;
2681 
2682 	case TCPS_CLOSING:
2683 		db_printf("TCPS_CLOSING");
2684 		return;
2685 
2686 	case TCPS_LAST_ACK:
2687 		db_printf("TCPS_LAST_ACK");
2688 		return;
2689 
2690 	case TCPS_FIN_WAIT_2:
2691 		db_printf("TCPS_FIN_WAIT_2");
2692 		return;
2693 
2694 	case TCPS_TIME_WAIT:
2695 		db_printf("TCPS_TIME_WAIT");
2696 		return;
2697 
2698 	default:
2699 		db_printf("unknown");
2700 		return;
2701 	}
2702 }
2703 
2704 static void
2705 db_print_tflags(u_int t_flags)
2706 {
2707 	int comma;
2708 
2709 	comma = 0;
2710 	if (t_flags & TF_ACKNOW) {
2711 		db_printf("%sTF_ACKNOW", comma ? ", " : "");
2712 		comma = 1;
2713 	}
2714 	if (t_flags & TF_DELACK) {
2715 		db_printf("%sTF_DELACK", comma ? ", " : "");
2716 		comma = 1;
2717 	}
2718 	if (t_flags & TF_NODELAY) {
2719 		db_printf("%sTF_NODELAY", comma ? ", " : "");
2720 		comma = 1;
2721 	}
2722 	if (t_flags & TF_NOOPT) {
2723 		db_printf("%sTF_NOOPT", comma ? ", " : "");
2724 		comma = 1;
2725 	}
2726 	if (t_flags & TF_SENTFIN) {
2727 		db_printf("%sTF_SENTFIN", comma ? ", " : "");
2728 		comma = 1;
2729 	}
2730 	if (t_flags & TF_REQ_SCALE) {
2731 		db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
2732 		comma = 1;
2733 	}
2734 	if (t_flags & TF_RCVD_SCALE) {
2735 		db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
2736 		comma = 1;
2737 	}
2738 	if (t_flags & TF_REQ_TSTMP) {
2739 		db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
2740 		comma = 1;
2741 	}
2742 	if (t_flags & TF_RCVD_TSTMP) {
2743 		db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
2744 		comma = 1;
2745 	}
2746 	if (t_flags & TF_SACK_PERMIT) {
2747 		db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
2748 		comma = 1;
2749 	}
2750 	if (t_flags & TF_NEEDSYN) {
2751 		db_printf("%sTF_NEEDSYN", comma ? ", " : "");
2752 		comma = 1;
2753 	}
2754 	if (t_flags & TF_NEEDFIN) {
2755 		db_printf("%sTF_NEEDFIN", comma ? ", " : "");
2756 		comma = 1;
2757 	}
2758 	if (t_flags & TF_NOPUSH) {
2759 		db_printf("%sTF_NOPUSH", comma ? ", " : "");
2760 		comma = 1;
2761 	}
2762 	if (t_flags & TF_MORETOCOME) {
2763 		db_printf("%sTF_MORETOCOME", comma ? ", " : "");
2764 		comma = 1;
2765 	}
2766 	if (t_flags & TF_LQ_OVERFLOW) {
2767 		db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
2768 		comma = 1;
2769 	}
2770 	if (t_flags & TF_LASTIDLE) {
2771 		db_printf("%sTF_LASTIDLE", comma ? ", " : "");
2772 		comma = 1;
2773 	}
2774 	if (t_flags & TF_RXWIN0SENT) {
2775 		db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
2776 		comma = 1;
2777 	}
2778 	if (t_flags & TF_FASTRECOVERY) {
2779 		db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
2780 		comma = 1;
2781 	}
2782 	if (t_flags & TF_CONGRECOVERY) {
2783 		db_printf("%sTF_CONGRECOVERY", comma ? ", " : "");
2784 		comma = 1;
2785 	}
2786 	if (t_flags & TF_WASFRECOVERY) {
2787 		db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
2788 		comma = 1;
2789 	}
2790 	if (t_flags & TF_SIGNATURE) {
2791 		db_printf("%sTF_SIGNATURE", comma ? ", " : "");
2792 		comma = 1;
2793 	}
2794 	if (t_flags & TF_FORCEDATA) {
2795 		db_printf("%sTF_FORCEDATA", comma ? ", " : "");
2796 		comma = 1;
2797 	}
2798 	if (t_flags & TF_TSO) {
2799 		db_printf("%sTF_TSO", comma ? ", " : "");
2800 		comma = 1;
2801 	}
2802 	if (t_flags & TF_FASTOPEN) {
2803 		db_printf("%sTF_FASTOPEN", comma ? ", " : "");
2804 		comma = 1;
2805 	}
2806 }
2807 
2808 static void
2809 db_print_tflags2(u_int t_flags2)
2810 {
2811 	int comma;
2812 
2813 	comma = 0;
2814 	if (t_flags2 & TF2_ECN_PERMIT) {
2815 		db_printf("%sTF2_ECN_PERMIT", comma ? ", " : "");
2816 		comma = 1;
2817 	}
2818 }
2819 
2820 static void
2821 db_print_toobflags(char t_oobflags)
2822 {
2823 	int comma;
2824 
2825 	comma = 0;
2826 	if (t_oobflags & TCPOOB_HAVEDATA) {
2827 		db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
2828 		comma = 1;
2829 	}
2830 	if (t_oobflags & TCPOOB_HADDATA) {
2831 		db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
2832 		comma = 1;
2833 	}
2834 }
2835 
2836 static void
2837 db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
2838 {
2839 
2840 	db_print_indent(indent);
2841 	db_printf("%s at %p\n", name, tp);
2842 
2843 	indent += 2;
2844 
2845 	db_print_indent(indent);
2846 	db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
2847 	   TAILQ_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
2848 
2849 	db_print_indent(indent);
2850 	db_printf("tt_rexmt: %p   tt_persist: %p   tt_keep: %p\n",
2851 	    &tp->t_timers->tt_rexmt, &tp->t_timers->tt_persist, &tp->t_timers->tt_keep);
2852 
2853 	db_print_indent(indent);
2854 	db_printf("tt_2msl: %p   tt_delack: %p   t_inpcb: %p\n", &tp->t_timers->tt_2msl,
2855 	    &tp->t_timers->tt_delack, tp->t_inpcb);
2856 
2857 	db_print_indent(indent);
2858 	db_printf("t_state: %d (", tp->t_state);
2859 	db_print_tstate(tp->t_state);
2860 	db_printf(")\n");
2861 
2862 	db_print_indent(indent);
2863 	db_printf("t_flags: 0x%x (", tp->t_flags);
2864 	db_print_tflags(tp->t_flags);
2865 	db_printf(")\n");
2866 
2867 	db_print_indent(indent);
2868 	db_printf("t_flags2: 0x%x (", tp->t_flags2);
2869 	db_print_tflags2(tp->t_flags2);
2870 	db_printf(")\n");
2871 
2872 	db_print_indent(indent);
2873 	db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
2874 	    tp->snd_una, tp->snd_max, tp->snd_nxt);
2875 
2876 	db_print_indent(indent);
2877 	db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
2878 	   tp->snd_up, tp->snd_wl1, tp->snd_wl2);
2879 
2880 	db_print_indent(indent);
2881 	db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
2882 	    tp->iss, tp->irs, tp->rcv_nxt);
2883 
2884 	db_print_indent(indent);
2885 	db_printf("rcv_adv: 0x%08x   rcv_wnd: %u   rcv_up: 0x%08x\n",
2886 	    tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
2887 
2888 	db_print_indent(indent);
2889 	db_printf("snd_wnd: %u   snd_cwnd: %u\n",
2890 	   tp->snd_wnd, tp->snd_cwnd);
2891 
2892 	db_print_indent(indent);
2893 	db_printf("snd_ssthresh: %u   snd_recover: "
2894 	    "0x%08x\n", tp->snd_ssthresh, tp->snd_recover);
2895 
2896 	db_print_indent(indent);
2897 	db_printf("t_rcvtime: %u   t_startime: %u\n",
2898 	    tp->t_rcvtime, tp->t_starttime);
2899 
2900 	db_print_indent(indent);
2901 	db_printf("t_rttime: %u   t_rtsq: 0x%08x\n",
2902 	    tp->t_rtttime, tp->t_rtseq);
2903 
2904 	db_print_indent(indent);
2905 	db_printf("t_rxtcur: %d   t_maxseg: %u   t_srtt: %d\n",
2906 	    tp->t_rxtcur, tp->t_maxseg, tp->t_srtt);
2907 
2908 	db_print_indent(indent);
2909 	db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u   "
2910 	    "t_rttbest: %u\n", tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin,
2911 	    tp->t_rttbest);
2912 
2913 	db_print_indent(indent);
2914 	db_printf("t_rttupdated: %lu   max_sndwnd: %u   t_softerror: %d\n",
2915 	    tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
2916 
2917 	db_print_indent(indent);
2918 	db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
2919 	db_print_toobflags(tp->t_oobflags);
2920 	db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
2921 
2922 	db_print_indent(indent);
2923 	db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
2924 	    tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
2925 
2926 	db_print_indent(indent);
2927 	db_printf("ts_recent: %u   ts_recent_age: %u\n",
2928 	    tp->ts_recent, tp->ts_recent_age);
2929 
2930 	db_print_indent(indent);
2931 	db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
2932 	    "%u\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
2933 
2934 	db_print_indent(indent);
2935 	db_printf("snd_ssthresh_prev: %u   snd_recover_prev: 0x%08x   "
2936 	    "t_badrxtwin: %u\n", tp->snd_ssthresh_prev,
2937 	    tp->snd_recover_prev, tp->t_badrxtwin);
2938 
2939 	db_print_indent(indent);
2940 	db_printf("snd_numholes: %d  snd_holes first: %p\n",
2941 	    tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
2942 
2943 	db_print_indent(indent);
2944 	db_printf("snd_fack: 0x%08x   rcv_numsacks: %d\n",
2945 	    tp->snd_fack, tp->rcv_numsacks);
2946 
2947 	/* Skip sackblks, sackhint. */
2948 
2949 	db_print_indent(indent);
2950 	db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
2951 	    tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
2952 }
2953 
2954 DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
2955 {
2956 	struct tcpcb *tp;
2957 
2958 	if (!have_addr) {
2959 		db_printf("usage: show tcpcb <addr>\n");
2960 		return;
2961 	}
2962 	tp = (struct tcpcb *)addr;
2963 
2964 	db_print_tcpcb(tp, "tcpcb", 0);
2965 }
2966 #endif
2967