xref: /freebsd/sys/netinet/tcp_usrreq.c (revision ac099daf6742ead81ea7ea86351a8ef4e783041b)
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_REMOTE_UDP_ENCAPS_PORT:
2053 			INP_WUNLOCK(inp);
2054 			error = sooptcopyin(sopt, &optval, sizeof optval,
2055 			    sizeof optval);
2056 			if (error)
2057 				return (error);
2058 			if ((optval < TCP_TUNNELING_PORT_MIN) ||
2059 			    (optval > TCP_TUNNELING_PORT_MAX)) {
2060 				/* Its got to be in range */
2061 				return (EINVAL);
2062 			}
2063 			if ((V_tcp_udp_tunneling_port == 0) && (optval != 0)) {
2064 				/* You have to have enabled a UDP tunneling port first */
2065 				return (EINVAL);
2066 			}
2067 			INP_WLOCK_RECHECK(inp);
2068 			if (tp->t_state != TCPS_CLOSED) {
2069 				/* You can't change after you are connected */
2070 				error = EINVAL;
2071 			} else {
2072 				/* Ok we are all good set the port */
2073 				tp->t_port = htons(optval);
2074 			}
2075 			goto unlock_and_done;
2076 
2077 		case TCP_MAXSEG:
2078 			INP_WUNLOCK(inp);
2079 			error = sooptcopyin(sopt, &optval, sizeof optval,
2080 			    sizeof optval);
2081 			if (error)
2082 				return (error);
2083 
2084 			INP_WLOCK_RECHECK(inp);
2085 			if (optval > 0 && optval <= tp->t_maxseg &&
2086 			    optval + 40 >= V_tcp_minmss)
2087 				tp->t_maxseg = optval;
2088 			else
2089 				error = EINVAL;
2090 			goto unlock_and_done;
2091 
2092 		case TCP_INFO:
2093 			INP_WUNLOCK(inp);
2094 			error = EINVAL;
2095 			break;
2096 
2097 		case TCP_STATS:
2098 			INP_WUNLOCK(inp);
2099 #ifdef STATS
2100 			error = sooptcopyin(sopt, &optval, sizeof optval,
2101 			    sizeof optval);
2102 			if (error)
2103 				return (error);
2104 
2105 			if (optval > 0)
2106 				sbp = stats_blob_alloc(
2107 				    V_tcp_perconn_stats_dflt_tpl, 0);
2108 			else
2109 				sbp = NULL;
2110 
2111 			INP_WLOCK_RECHECK(inp);
2112 			if ((tp->t_stats != NULL && sbp == NULL) ||
2113 			    (tp->t_stats == NULL && sbp != NULL)) {
2114 				struct statsblob *t = tp->t_stats;
2115 				tp->t_stats = sbp;
2116 				sbp = t;
2117 			}
2118 			INP_WUNLOCK(inp);
2119 
2120 			stats_blob_destroy(sbp);
2121 #else
2122 			return (EOPNOTSUPP);
2123 #endif /* !STATS */
2124 			break;
2125 
2126 		case TCP_CONGESTION:
2127 			INP_WUNLOCK(inp);
2128 			error = sooptcopyin(sopt, buf, TCP_CA_NAME_MAX - 1, 1);
2129 			if (error)
2130 				break;
2131 			buf[sopt->sopt_valsize] = '\0';
2132 			INP_WLOCK_RECHECK(inp);
2133 			CC_LIST_RLOCK();
2134 			STAILQ_FOREACH(algo, &cc_list, entries)
2135 				if (strncmp(buf, algo->name,
2136 				    TCP_CA_NAME_MAX) == 0)
2137 					break;
2138 			CC_LIST_RUNLOCK();
2139 			if (algo == NULL) {
2140 				INP_WUNLOCK(inp);
2141 				error = EINVAL;
2142 				break;
2143 			}
2144 			/*
2145 			 * We hold a write lock over the tcb so it's safe to
2146 			 * do these things without ordering concerns.
2147 			 */
2148 			if (CC_ALGO(tp)->cb_destroy != NULL)
2149 				CC_ALGO(tp)->cb_destroy(tp->ccv);
2150 			CC_DATA(tp) = NULL;
2151 			CC_ALGO(tp) = algo;
2152 			/*
2153 			 * If something goes pear shaped initialising the new
2154 			 * algo, fall back to newreno (which does not
2155 			 * require initialisation).
2156 			 */
2157 			if (algo->cb_init != NULL &&
2158 			    algo->cb_init(tp->ccv) != 0) {
2159 				CC_ALGO(tp) = &newreno_cc_algo;
2160 				/*
2161 				 * The only reason init should fail is
2162 				 * because of malloc.
2163 				 */
2164 				error = ENOMEM;
2165 			}
2166 			INP_WUNLOCK(inp);
2167 			break;
2168 
2169 		case TCP_REUSPORT_LB_NUMA:
2170 			INP_WUNLOCK(inp);
2171 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2172 			    sizeof(optval));
2173 			INP_WLOCK_RECHECK(inp);
2174 			if (!error)
2175 				error = in_pcblbgroup_numa(inp, optval);
2176 			INP_WUNLOCK(inp);
2177 			break;
2178 
2179 #ifdef KERN_TLS
2180 		case TCP_TXTLS_ENABLE:
2181 			INP_WUNLOCK(inp);
2182 			error = copyin_tls_enable(sopt, &tls);
2183 			if (error)
2184 				break;
2185 			error = ktls_enable_tx(so, &tls);
2186 			break;
2187 		case TCP_TXTLS_MODE:
2188 			INP_WUNLOCK(inp);
2189 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2190 			if (error)
2191 				return (error);
2192 
2193 			INP_WLOCK_RECHECK(inp);
2194 			error = ktls_set_tx_mode(so, ui);
2195 			INP_WUNLOCK(inp);
2196 			break;
2197 		case TCP_RXTLS_ENABLE:
2198 			INP_WUNLOCK(inp);
2199 			error = sooptcopyin(sopt, &tls, sizeof(tls),
2200 			    sizeof(tls));
2201 			if (error)
2202 				break;
2203 			error = ktls_enable_rx(so, &tls);
2204 			break;
2205 #endif
2206 
2207 		case TCP_KEEPIDLE:
2208 		case TCP_KEEPINTVL:
2209 		case TCP_KEEPINIT:
2210 			INP_WUNLOCK(inp);
2211 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2212 			if (error)
2213 				return (error);
2214 
2215 			if (ui > (UINT_MAX / hz)) {
2216 				error = EINVAL;
2217 				break;
2218 			}
2219 			ui *= hz;
2220 
2221 			INP_WLOCK_RECHECK(inp);
2222 			switch (sopt->sopt_name) {
2223 			case TCP_KEEPIDLE:
2224 				tp->t_keepidle = ui;
2225 				/*
2226 				 * XXX: better check current remaining
2227 				 * timeout and "merge" it with new value.
2228 				 */
2229 				if ((tp->t_state > TCPS_LISTEN) &&
2230 				    (tp->t_state <= TCPS_CLOSING))
2231 					tcp_timer_activate(tp, TT_KEEP,
2232 					    TP_KEEPIDLE(tp));
2233 				break;
2234 			case TCP_KEEPINTVL:
2235 				tp->t_keepintvl = ui;
2236 				if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2237 				    (TP_MAXIDLE(tp) > 0))
2238 					tcp_timer_activate(tp, TT_2MSL,
2239 					    TP_MAXIDLE(tp));
2240 				break;
2241 			case TCP_KEEPINIT:
2242 				tp->t_keepinit = ui;
2243 				if (tp->t_state == TCPS_SYN_RECEIVED ||
2244 				    tp->t_state == TCPS_SYN_SENT)
2245 					tcp_timer_activate(tp, TT_KEEP,
2246 					    TP_KEEPINIT(tp));
2247 				break;
2248 			}
2249 			goto unlock_and_done;
2250 
2251 		case TCP_KEEPCNT:
2252 			INP_WUNLOCK(inp);
2253 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2254 			if (error)
2255 				return (error);
2256 
2257 			INP_WLOCK_RECHECK(inp);
2258 			tp->t_keepcnt = ui;
2259 			if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2260 			    (TP_MAXIDLE(tp) > 0))
2261 				tcp_timer_activate(tp, TT_2MSL,
2262 				    TP_MAXIDLE(tp));
2263 			goto unlock_and_done;
2264 
2265 #ifdef TCPPCAP
2266 		case TCP_PCAP_OUT:
2267 		case TCP_PCAP_IN:
2268 			INP_WUNLOCK(inp);
2269 			error = sooptcopyin(sopt, &optval, sizeof optval,
2270 			    sizeof optval);
2271 			if (error)
2272 				return (error);
2273 
2274 			INP_WLOCK_RECHECK(inp);
2275 			if (optval >= 0)
2276 				tcp_pcap_set_sock_max(TCP_PCAP_OUT ?
2277 					&(tp->t_outpkts) : &(tp->t_inpkts),
2278 					optval);
2279 			else
2280 				error = EINVAL;
2281 			goto unlock_and_done;
2282 #endif
2283 
2284 		case TCP_FASTOPEN: {
2285 			struct tcp_fastopen tfo_optval;
2286 
2287 			INP_WUNLOCK(inp);
2288 			if (!V_tcp_fastopen_client_enable &&
2289 			    !V_tcp_fastopen_server_enable)
2290 				return (EPERM);
2291 
2292 			error = sooptcopyin(sopt, &tfo_optval,
2293 				    sizeof(tfo_optval), sizeof(int));
2294 			if (error)
2295 				return (error);
2296 
2297 			INP_WLOCK_RECHECK(inp);
2298 			if ((tp->t_state != TCPS_CLOSED) &&
2299 			    (tp->t_state != TCPS_LISTEN)) {
2300 				error = EINVAL;
2301 				goto unlock_and_done;
2302 			}
2303 			if (tfo_optval.enable) {
2304 				if (tp->t_state == TCPS_LISTEN) {
2305 					if (!V_tcp_fastopen_server_enable) {
2306 						error = EPERM;
2307 						goto unlock_and_done;
2308 					}
2309 
2310 					if (tp->t_tfo_pending == NULL)
2311 						tp->t_tfo_pending =
2312 						    tcp_fastopen_alloc_counter();
2313 				} else {
2314 					/*
2315 					 * If a pre-shared key was provided,
2316 					 * stash it in the client cookie
2317 					 * field of the tcpcb for use during
2318 					 * connect.
2319 					 */
2320 					if (sopt->sopt_valsize ==
2321 					    sizeof(tfo_optval)) {
2322 						memcpy(tp->t_tfo_cookie.client,
2323 						       tfo_optval.psk,
2324 						       TCP_FASTOPEN_PSK_LEN);
2325 						tp->t_tfo_client_cookie_len =
2326 						    TCP_FASTOPEN_PSK_LEN;
2327 					}
2328 				}
2329 				tp->t_flags |= TF_FASTOPEN;
2330 			} else
2331 				tp->t_flags &= ~TF_FASTOPEN;
2332 			goto unlock_and_done;
2333 		}
2334 
2335 #ifdef TCP_BLACKBOX
2336 		case TCP_LOG:
2337 			INP_WUNLOCK(inp);
2338 			error = sooptcopyin(sopt, &optval, sizeof optval,
2339 			    sizeof optval);
2340 			if (error)
2341 				return (error);
2342 
2343 			INP_WLOCK_RECHECK(inp);
2344 			error = tcp_log_state_change(tp, optval);
2345 			goto unlock_and_done;
2346 
2347 		case TCP_LOGBUF:
2348 			INP_WUNLOCK(inp);
2349 			error = EINVAL;
2350 			break;
2351 
2352 		case TCP_LOGID:
2353 			INP_WUNLOCK(inp);
2354 			error = sooptcopyin(sopt, buf, TCP_LOG_ID_LEN - 1, 0);
2355 			if (error)
2356 				break;
2357 			buf[sopt->sopt_valsize] = '\0';
2358 			INP_WLOCK_RECHECK(inp);
2359 			error = tcp_log_set_id(tp, buf);
2360 			/* tcp_log_set_id() unlocks the INP. */
2361 			break;
2362 
2363 		case TCP_LOGDUMP:
2364 		case TCP_LOGDUMPID:
2365 			INP_WUNLOCK(inp);
2366 			error =
2367 			    sooptcopyin(sopt, buf, TCP_LOG_REASON_LEN - 1, 0);
2368 			if (error)
2369 				break;
2370 			buf[sopt->sopt_valsize] = '\0';
2371 			INP_WLOCK_RECHECK(inp);
2372 			if (sopt->sopt_name == TCP_LOGDUMP) {
2373 				error = tcp_log_dump_tp_logbuf(tp, buf,
2374 				    M_WAITOK, true);
2375 				INP_WUNLOCK(inp);
2376 			} else {
2377 				tcp_log_dump_tp_bucket_logbufs(tp, buf);
2378 				/*
2379 				 * tcp_log_dump_tp_bucket_logbufs() drops the
2380 				 * INP lock.
2381 				 */
2382 			}
2383 			break;
2384 #endif
2385 
2386 		default:
2387 			INP_WUNLOCK(inp);
2388 			error = ENOPROTOOPT;
2389 			break;
2390 		}
2391 		break;
2392 
2393 	case SOPT_GET:
2394 		tp = intotcpcb(inp);
2395 		switch (sopt->sopt_name) {
2396 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2397 		case TCP_MD5SIG:
2398 			if (!TCPMD5_ENABLED()) {
2399 				INP_WUNLOCK(inp);
2400 				return (ENOPROTOOPT);
2401 			}
2402 			error = TCPMD5_PCBCTL(inp, sopt);
2403 			break;
2404 #endif
2405 
2406 		case TCP_NODELAY:
2407 			optval = tp->t_flags & TF_NODELAY;
2408 			INP_WUNLOCK(inp);
2409 			error = sooptcopyout(sopt, &optval, sizeof optval);
2410 			break;
2411 		case TCP_MAXSEG:
2412 			optval = tp->t_maxseg;
2413 			INP_WUNLOCK(inp);
2414 			error = sooptcopyout(sopt, &optval, sizeof optval);
2415 			break;
2416 		case TCP_REMOTE_UDP_ENCAPS_PORT:
2417 			optval = ntohs(tp->t_port);
2418 			INP_WUNLOCK(inp);
2419 			error = sooptcopyout(sopt, &optval, sizeof optval);
2420 			break;
2421 		case TCP_NOOPT:
2422 			optval = tp->t_flags & TF_NOOPT;
2423 			INP_WUNLOCK(inp);
2424 			error = sooptcopyout(sopt, &optval, sizeof optval);
2425 			break;
2426 		case TCP_NOPUSH:
2427 			optval = tp->t_flags & TF_NOPUSH;
2428 			INP_WUNLOCK(inp);
2429 			error = sooptcopyout(sopt, &optval, sizeof optval);
2430 			break;
2431 		case TCP_INFO:
2432 			tcp_fill_info(tp, &ti);
2433 			INP_WUNLOCK(inp);
2434 			error = sooptcopyout(sopt, &ti, sizeof ti);
2435 			break;
2436 		case TCP_STATS:
2437 			{
2438 #ifdef STATS
2439 			int nheld;
2440 			TYPEOF_MEMBER(struct statsblob, flags) sbflags = 0;
2441 
2442 			error = 0;
2443 			socklen_t outsbsz = sopt->sopt_valsize;
2444 			if (tp->t_stats == NULL)
2445 				error = ENOENT;
2446 			else if (outsbsz >= tp->t_stats->cursz)
2447 				outsbsz = tp->t_stats->cursz;
2448 			else if (outsbsz >= sizeof(struct statsblob))
2449 				outsbsz = sizeof(struct statsblob);
2450 			else
2451 				error = EINVAL;
2452 			INP_WUNLOCK(inp);
2453 			if (error)
2454 				break;
2455 
2456 			sbp = sopt->sopt_val;
2457 			nheld = atop(round_page(((vm_offset_t)sbp) +
2458 			    (vm_size_t)outsbsz) - trunc_page((vm_offset_t)sbp));
2459 			vm_page_t ma[nheld];
2460 			if (vm_fault_quick_hold_pages(
2461 			    &curproc->p_vmspace->vm_map, (vm_offset_t)sbp,
2462 			    outsbsz, VM_PROT_READ | VM_PROT_WRITE, ma,
2463 			    nheld) < 0) {
2464 				error = EFAULT;
2465 				break;
2466 			}
2467 
2468 			if ((error = copyin_nofault(&(sbp->flags), &sbflags,
2469 			    SIZEOF_MEMBER(struct statsblob, flags))))
2470 				goto unhold;
2471 
2472 			INP_WLOCK_RECHECK(inp);
2473 			error = stats_blob_snapshot(&sbp, outsbsz, tp->t_stats,
2474 			    sbflags | SB_CLONE_USRDSTNOFAULT);
2475 			INP_WUNLOCK(inp);
2476 			sopt->sopt_valsize = outsbsz;
2477 unhold:
2478 			vm_page_unhold_pages(ma, nheld);
2479 #else
2480 			INP_WUNLOCK(inp);
2481 			error = EOPNOTSUPP;
2482 #endif /* !STATS */
2483 			break;
2484 			}
2485 		case TCP_CONGESTION:
2486 			len = strlcpy(buf, CC_ALGO(tp)->name, TCP_CA_NAME_MAX);
2487 			INP_WUNLOCK(inp);
2488 			error = sooptcopyout(sopt, buf, len + 1);
2489 			break;
2490 		case TCP_KEEPIDLE:
2491 		case TCP_KEEPINTVL:
2492 		case TCP_KEEPINIT:
2493 		case TCP_KEEPCNT:
2494 			switch (sopt->sopt_name) {
2495 			case TCP_KEEPIDLE:
2496 				ui = TP_KEEPIDLE(tp) / hz;
2497 				break;
2498 			case TCP_KEEPINTVL:
2499 				ui = TP_KEEPINTVL(tp) / hz;
2500 				break;
2501 			case TCP_KEEPINIT:
2502 				ui = TP_KEEPINIT(tp) / hz;
2503 				break;
2504 			case TCP_KEEPCNT:
2505 				ui = TP_KEEPCNT(tp);
2506 				break;
2507 			}
2508 			INP_WUNLOCK(inp);
2509 			error = sooptcopyout(sopt, &ui, sizeof(ui));
2510 			break;
2511 #ifdef TCPPCAP
2512 		case TCP_PCAP_OUT:
2513 		case TCP_PCAP_IN:
2514 			optval = tcp_pcap_get_sock_max(TCP_PCAP_OUT ?
2515 					&(tp->t_outpkts) : &(tp->t_inpkts));
2516 			INP_WUNLOCK(inp);
2517 			error = sooptcopyout(sopt, &optval, sizeof optval);
2518 			break;
2519 #endif
2520 		case TCP_FASTOPEN:
2521 			optval = tp->t_flags & TF_FASTOPEN;
2522 			INP_WUNLOCK(inp);
2523 			error = sooptcopyout(sopt, &optval, sizeof optval);
2524 			break;
2525 #ifdef TCP_BLACKBOX
2526 		case TCP_LOG:
2527 			optval = tp->t_logstate;
2528 			INP_WUNLOCK(inp);
2529 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2530 			break;
2531 		case TCP_LOGBUF:
2532 			/* tcp_log_getlogbuf() does INP_WUNLOCK(inp) */
2533 			error = tcp_log_getlogbuf(sopt, tp);
2534 			break;
2535 		case TCP_LOGID:
2536 			len = tcp_log_get_id(tp, buf);
2537 			INP_WUNLOCK(inp);
2538 			error = sooptcopyout(sopt, buf, len + 1);
2539 			break;
2540 		case TCP_LOGDUMP:
2541 		case TCP_LOGDUMPID:
2542 			INP_WUNLOCK(inp);
2543 			error = EINVAL;
2544 			break;
2545 #endif
2546 #ifdef KERN_TLS
2547 		case TCP_TXTLS_MODE:
2548 			optval = ktls_get_tx_mode(so);
2549 			INP_WUNLOCK(inp);
2550 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2551 			break;
2552 		case TCP_RXTLS_MODE:
2553 			optval = ktls_get_rx_mode(so);
2554 			INP_WUNLOCK(inp);
2555 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2556 			break;
2557 #endif
2558 		default:
2559 			INP_WUNLOCK(inp);
2560 			error = ENOPROTOOPT;
2561 			break;
2562 		}
2563 		break;
2564 	}
2565 	return (error);
2566 }
2567 #undef INP_WLOCK_RECHECK
2568 #undef INP_WLOCK_RECHECK_CLEANUP
2569 
2570 /*
2571  * Initiate (or continue) disconnect.
2572  * If embryonic state, just send reset (once).
2573  * If in ``let data drain'' option and linger null, just drop.
2574  * Otherwise (hard), mark socket disconnecting and drop
2575  * current input data; switch states based on user close, and
2576  * send segment to peer (with FIN).
2577  */
2578 static void
2579 tcp_disconnect(struct tcpcb *tp)
2580 {
2581 	struct inpcb *inp = tp->t_inpcb;
2582 	struct socket *so = inp->inp_socket;
2583 
2584 	NET_EPOCH_ASSERT();
2585 	INP_WLOCK_ASSERT(inp);
2586 
2587 	/*
2588 	 * Neither tcp_close() nor tcp_drop() should return NULL, as the
2589 	 * socket is still open.
2590 	 */
2591 	if (tp->t_state < TCPS_ESTABLISHED &&
2592 	    !(tp->t_state > TCPS_LISTEN && IS_FASTOPEN(tp->t_flags))) {
2593 		tp = tcp_close(tp);
2594 		KASSERT(tp != NULL,
2595 		    ("tcp_disconnect: tcp_close() returned NULL"));
2596 	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
2597 		tp = tcp_drop(tp, 0);
2598 		KASSERT(tp != NULL,
2599 		    ("tcp_disconnect: tcp_drop() returned NULL"));
2600 	} else {
2601 		soisdisconnecting(so);
2602 		sbflush(&so->so_rcv);
2603 		tcp_usrclosed(tp);
2604 		if (!(inp->inp_flags & INP_DROPPED))
2605 			tp->t_fb->tfb_tcp_output(tp);
2606 	}
2607 }
2608 
2609 /*
2610  * User issued close, and wish to trail through shutdown states:
2611  * if never received SYN, just forget it.  If got a SYN from peer,
2612  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
2613  * If already got a FIN from peer, then almost done; go to LAST_ACK
2614  * state.  In all other cases, have already sent FIN to peer (e.g.
2615  * after PRU_SHUTDOWN), and just have to play tedious game waiting
2616  * for peer to send FIN or not respond to keep-alives, etc.
2617  * We can let the user exit from the close as soon as the FIN is acked.
2618  */
2619 static void
2620 tcp_usrclosed(struct tcpcb *tp)
2621 {
2622 
2623 	NET_EPOCH_ASSERT();
2624 	INP_WLOCK_ASSERT(tp->t_inpcb);
2625 
2626 	switch (tp->t_state) {
2627 	case TCPS_LISTEN:
2628 #ifdef TCP_OFFLOAD
2629 		tcp_offload_listen_stop(tp);
2630 #endif
2631 		tcp_state_change(tp, TCPS_CLOSED);
2632 		/* FALLTHROUGH */
2633 	case TCPS_CLOSED:
2634 		tp = tcp_close(tp);
2635 		/*
2636 		 * tcp_close() should never return NULL here as the socket is
2637 		 * still open.
2638 		 */
2639 		KASSERT(tp != NULL,
2640 		    ("tcp_usrclosed: tcp_close() returned NULL"));
2641 		break;
2642 
2643 	case TCPS_SYN_SENT:
2644 	case TCPS_SYN_RECEIVED:
2645 		tp->t_flags |= TF_NEEDFIN;
2646 		break;
2647 
2648 	case TCPS_ESTABLISHED:
2649 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
2650 		break;
2651 
2652 	case TCPS_CLOSE_WAIT:
2653 		tcp_state_change(tp, TCPS_LAST_ACK);
2654 		break;
2655 	}
2656 	if (tp->t_state >= TCPS_FIN_WAIT_2) {
2657 		soisdisconnected(tp->t_inpcb->inp_socket);
2658 		/* Prevent the connection hanging in FIN_WAIT_2 forever. */
2659 		if (tp->t_state == TCPS_FIN_WAIT_2) {
2660 			int timeout;
2661 
2662 			timeout = (tcp_fast_finwait2_recycle) ?
2663 			    tcp_finwait2_timeout : TP_MAXIDLE(tp);
2664 			tcp_timer_activate(tp, TT_2MSL, timeout);
2665 		}
2666 	}
2667 }
2668 
2669 #ifdef DDB
2670 static void
2671 db_print_indent(int indent)
2672 {
2673 	int i;
2674 
2675 	for (i = 0; i < indent; i++)
2676 		db_printf(" ");
2677 }
2678 
2679 static void
2680 db_print_tstate(int t_state)
2681 {
2682 
2683 	switch (t_state) {
2684 	case TCPS_CLOSED:
2685 		db_printf("TCPS_CLOSED");
2686 		return;
2687 
2688 	case TCPS_LISTEN:
2689 		db_printf("TCPS_LISTEN");
2690 		return;
2691 
2692 	case TCPS_SYN_SENT:
2693 		db_printf("TCPS_SYN_SENT");
2694 		return;
2695 
2696 	case TCPS_SYN_RECEIVED:
2697 		db_printf("TCPS_SYN_RECEIVED");
2698 		return;
2699 
2700 	case TCPS_ESTABLISHED:
2701 		db_printf("TCPS_ESTABLISHED");
2702 		return;
2703 
2704 	case TCPS_CLOSE_WAIT:
2705 		db_printf("TCPS_CLOSE_WAIT");
2706 		return;
2707 
2708 	case TCPS_FIN_WAIT_1:
2709 		db_printf("TCPS_FIN_WAIT_1");
2710 		return;
2711 
2712 	case TCPS_CLOSING:
2713 		db_printf("TCPS_CLOSING");
2714 		return;
2715 
2716 	case TCPS_LAST_ACK:
2717 		db_printf("TCPS_LAST_ACK");
2718 		return;
2719 
2720 	case TCPS_FIN_WAIT_2:
2721 		db_printf("TCPS_FIN_WAIT_2");
2722 		return;
2723 
2724 	case TCPS_TIME_WAIT:
2725 		db_printf("TCPS_TIME_WAIT");
2726 		return;
2727 
2728 	default:
2729 		db_printf("unknown");
2730 		return;
2731 	}
2732 }
2733 
2734 static void
2735 db_print_tflags(u_int t_flags)
2736 {
2737 	int comma;
2738 
2739 	comma = 0;
2740 	if (t_flags & TF_ACKNOW) {
2741 		db_printf("%sTF_ACKNOW", comma ? ", " : "");
2742 		comma = 1;
2743 	}
2744 	if (t_flags & TF_DELACK) {
2745 		db_printf("%sTF_DELACK", comma ? ", " : "");
2746 		comma = 1;
2747 	}
2748 	if (t_flags & TF_NODELAY) {
2749 		db_printf("%sTF_NODELAY", comma ? ", " : "");
2750 		comma = 1;
2751 	}
2752 	if (t_flags & TF_NOOPT) {
2753 		db_printf("%sTF_NOOPT", comma ? ", " : "");
2754 		comma = 1;
2755 	}
2756 	if (t_flags & TF_SENTFIN) {
2757 		db_printf("%sTF_SENTFIN", comma ? ", " : "");
2758 		comma = 1;
2759 	}
2760 	if (t_flags & TF_REQ_SCALE) {
2761 		db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
2762 		comma = 1;
2763 	}
2764 	if (t_flags & TF_RCVD_SCALE) {
2765 		db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
2766 		comma = 1;
2767 	}
2768 	if (t_flags & TF_REQ_TSTMP) {
2769 		db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
2770 		comma = 1;
2771 	}
2772 	if (t_flags & TF_RCVD_TSTMP) {
2773 		db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
2774 		comma = 1;
2775 	}
2776 	if (t_flags & TF_SACK_PERMIT) {
2777 		db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
2778 		comma = 1;
2779 	}
2780 	if (t_flags & TF_NEEDSYN) {
2781 		db_printf("%sTF_NEEDSYN", comma ? ", " : "");
2782 		comma = 1;
2783 	}
2784 	if (t_flags & TF_NEEDFIN) {
2785 		db_printf("%sTF_NEEDFIN", comma ? ", " : "");
2786 		comma = 1;
2787 	}
2788 	if (t_flags & TF_NOPUSH) {
2789 		db_printf("%sTF_NOPUSH", comma ? ", " : "");
2790 		comma = 1;
2791 	}
2792 	if (t_flags & TF_MORETOCOME) {
2793 		db_printf("%sTF_MORETOCOME", comma ? ", " : "");
2794 		comma = 1;
2795 	}
2796 	if (t_flags & TF_LQ_OVERFLOW) {
2797 		db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
2798 		comma = 1;
2799 	}
2800 	if (t_flags & TF_LASTIDLE) {
2801 		db_printf("%sTF_LASTIDLE", comma ? ", " : "");
2802 		comma = 1;
2803 	}
2804 	if (t_flags & TF_RXWIN0SENT) {
2805 		db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
2806 		comma = 1;
2807 	}
2808 	if (t_flags & TF_FASTRECOVERY) {
2809 		db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
2810 		comma = 1;
2811 	}
2812 	if (t_flags & TF_CONGRECOVERY) {
2813 		db_printf("%sTF_CONGRECOVERY", comma ? ", " : "");
2814 		comma = 1;
2815 	}
2816 	if (t_flags & TF_WASFRECOVERY) {
2817 		db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
2818 		comma = 1;
2819 	}
2820 	if (t_flags & TF_SIGNATURE) {
2821 		db_printf("%sTF_SIGNATURE", comma ? ", " : "");
2822 		comma = 1;
2823 	}
2824 	if (t_flags & TF_FORCEDATA) {
2825 		db_printf("%sTF_FORCEDATA", comma ? ", " : "");
2826 		comma = 1;
2827 	}
2828 	if (t_flags & TF_TSO) {
2829 		db_printf("%sTF_TSO", comma ? ", " : "");
2830 		comma = 1;
2831 	}
2832 	if (t_flags & TF_FASTOPEN) {
2833 		db_printf("%sTF_FASTOPEN", comma ? ", " : "");
2834 		comma = 1;
2835 	}
2836 }
2837 
2838 static void
2839 db_print_tflags2(u_int t_flags2)
2840 {
2841 	int comma;
2842 
2843 	comma = 0;
2844 	if (t_flags2 & TF2_ECN_PERMIT) {
2845 		db_printf("%sTF2_ECN_PERMIT", comma ? ", " : "");
2846 		comma = 1;
2847 	}
2848 }
2849 
2850 static void
2851 db_print_toobflags(char t_oobflags)
2852 {
2853 	int comma;
2854 
2855 	comma = 0;
2856 	if (t_oobflags & TCPOOB_HAVEDATA) {
2857 		db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
2858 		comma = 1;
2859 	}
2860 	if (t_oobflags & TCPOOB_HADDATA) {
2861 		db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
2862 		comma = 1;
2863 	}
2864 }
2865 
2866 static void
2867 db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
2868 {
2869 
2870 	db_print_indent(indent);
2871 	db_printf("%s at %p\n", name, tp);
2872 
2873 	indent += 2;
2874 
2875 	db_print_indent(indent);
2876 	db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
2877 	   TAILQ_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
2878 
2879 	db_print_indent(indent);
2880 	db_printf("tt_rexmt: %p   tt_persist: %p   tt_keep: %p\n",
2881 	    &tp->t_timers->tt_rexmt, &tp->t_timers->tt_persist, &tp->t_timers->tt_keep);
2882 
2883 	db_print_indent(indent);
2884 	db_printf("tt_2msl: %p   tt_delack: %p   t_inpcb: %p\n", &tp->t_timers->tt_2msl,
2885 	    &tp->t_timers->tt_delack, tp->t_inpcb);
2886 
2887 	db_print_indent(indent);
2888 	db_printf("t_state: %d (", tp->t_state);
2889 	db_print_tstate(tp->t_state);
2890 	db_printf(")\n");
2891 
2892 	db_print_indent(indent);
2893 	db_printf("t_flags: 0x%x (", tp->t_flags);
2894 	db_print_tflags(tp->t_flags);
2895 	db_printf(")\n");
2896 
2897 	db_print_indent(indent);
2898 	db_printf("t_flags2: 0x%x (", tp->t_flags2);
2899 	db_print_tflags2(tp->t_flags2);
2900 	db_printf(")\n");
2901 
2902 	db_print_indent(indent);
2903 	db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
2904 	    tp->snd_una, tp->snd_max, tp->snd_nxt);
2905 
2906 	db_print_indent(indent);
2907 	db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
2908 	   tp->snd_up, tp->snd_wl1, tp->snd_wl2);
2909 
2910 	db_print_indent(indent);
2911 	db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
2912 	    tp->iss, tp->irs, tp->rcv_nxt);
2913 
2914 	db_print_indent(indent);
2915 	db_printf("rcv_adv: 0x%08x   rcv_wnd: %u   rcv_up: 0x%08x\n",
2916 	    tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
2917 
2918 	db_print_indent(indent);
2919 	db_printf("snd_wnd: %u   snd_cwnd: %u\n",
2920 	   tp->snd_wnd, tp->snd_cwnd);
2921 
2922 	db_print_indent(indent);
2923 	db_printf("snd_ssthresh: %u   snd_recover: "
2924 	    "0x%08x\n", tp->snd_ssthresh, tp->snd_recover);
2925 
2926 	db_print_indent(indent);
2927 	db_printf("t_rcvtime: %u   t_startime: %u\n",
2928 	    tp->t_rcvtime, tp->t_starttime);
2929 
2930 	db_print_indent(indent);
2931 	db_printf("t_rttime: %u   t_rtsq: 0x%08x\n",
2932 	    tp->t_rtttime, tp->t_rtseq);
2933 
2934 	db_print_indent(indent);
2935 	db_printf("t_rxtcur: %d   t_maxseg: %u   t_srtt: %d\n",
2936 	    tp->t_rxtcur, tp->t_maxseg, tp->t_srtt);
2937 
2938 	db_print_indent(indent);
2939 	db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u   "
2940 	    "t_rttbest: %u\n", tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin,
2941 	    tp->t_rttbest);
2942 
2943 	db_print_indent(indent);
2944 	db_printf("t_rttupdated: %lu   max_sndwnd: %u   t_softerror: %d\n",
2945 	    tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
2946 
2947 	db_print_indent(indent);
2948 	db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
2949 	db_print_toobflags(tp->t_oobflags);
2950 	db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
2951 
2952 	db_print_indent(indent);
2953 	db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
2954 	    tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
2955 
2956 	db_print_indent(indent);
2957 	db_printf("ts_recent: %u   ts_recent_age: %u\n",
2958 	    tp->ts_recent, tp->ts_recent_age);
2959 
2960 	db_print_indent(indent);
2961 	db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
2962 	    "%u\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
2963 
2964 	db_print_indent(indent);
2965 	db_printf("snd_ssthresh_prev: %u   snd_recover_prev: 0x%08x   "
2966 	    "t_badrxtwin: %u\n", tp->snd_ssthresh_prev,
2967 	    tp->snd_recover_prev, tp->t_badrxtwin);
2968 
2969 	db_print_indent(indent);
2970 	db_printf("snd_numholes: %d  snd_holes first: %p\n",
2971 	    tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
2972 
2973 	db_print_indent(indent);
2974 	db_printf("snd_fack: 0x%08x   rcv_numsacks: %d\n",
2975 	    tp->snd_fack, tp->rcv_numsacks);
2976 
2977 	/* Skip sackblks, sackhint. */
2978 
2979 	db_print_indent(indent);
2980 	db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
2981 	    tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
2982 }
2983 
2984 DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
2985 {
2986 	struct tcpcb *tp;
2987 
2988 	if (!have_addr) {
2989 		db_printf("usage: show tcpcb <addr>\n");
2990 		return;
2991 	}
2992 	tp = (struct tcpcb *)addr;
2993 
2994 	db_print_tcpcb(tp, "tcpcb", 0);
2995 }
2996 #endif
2997