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