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