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