xref: /freebsd/sys/netinet6/in6_pcb.c (revision 6f63e88c0166ed3e5f2805a9e667c7d24d304cf1)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
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 project 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 PROJECT 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 PROJECT 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  *	$KAME: in6_pcb.c,v 1.31 2001/05/21 05:45:10 jinmei Exp $
36  */
37 
38 /*-
39  * Copyright (c) 1982, 1986, 1991, 1993
40  *	The Regents of the University of California.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
67  */
68 
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71 
72 #include "opt_inet.h"
73 #include "opt_inet6.h"
74 #include "opt_ipsec.h"
75 #include "opt_pcbgroup.h"
76 #include "opt_rss.h"
77 
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/malloc.h>
81 #include <sys/mbuf.h>
82 #include <sys/domain.h>
83 #include <sys/protosw.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/sockio.h>
87 #include <sys/errno.h>
88 #include <sys/time.h>
89 #include <sys/priv.h>
90 #include <sys/proc.h>
91 #include <sys/jail.h>
92 
93 #include <vm/uma.h>
94 
95 #include <net/if.h>
96 #include <net/if_var.h>
97 #include <net/if_llatbl.h>
98 #include <net/if_types.h>
99 #include <net/route.h>
100 #include <net/route/nhop.h>
101 
102 #include <netinet/in.h>
103 #include <netinet/in_var.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/tcp_var.h>
106 #include <netinet/ip6.h>
107 #include <netinet/ip_var.h>
108 
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/nd6.h>
111 #include <netinet/in_pcb.h>
112 #include <netinet6/in6_pcb.h>
113 #include <netinet6/in6_fib.h>
114 #include <netinet6/scope6_var.h>
115 
116 static struct inpcb *in6_pcblookup_hash_locked(struct inpcbinfo *,
117     struct in6_addr *, u_int, struct in6_addr *, u_int, int, struct ifnet *);
118 
119 int
120 in6_pcbbind(struct inpcb *inp, struct sockaddr *nam,
121     struct ucred *cred)
122 {
123 	struct socket *so = inp->inp_socket;
124 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)NULL;
125 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
126 	u_short	lport = 0;
127 	int error, lookupflags = 0;
128 	int reuseport = (so->so_options & SO_REUSEPORT);
129 
130 	/*
131 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
132 	 * so that we don't have to add to the (already messy) code below.
133 	 */
134 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
135 
136 	INP_WLOCK_ASSERT(inp);
137 	INP_HASH_WLOCK_ASSERT(pcbinfo);
138 
139 	if (CK_STAILQ_EMPTY(&V_in6_ifaddrhead))	/* XXX broken! */
140 		return (EADDRNOTAVAIL);
141 	if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
142 		return (EINVAL);
143 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
144 		lookupflags = INPLOOKUP_WILDCARD;
145 	if (nam == NULL) {
146 		if ((error = prison_local_ip6(cred, &inp->in6p_laddr,
147 		    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
148 			return (error);
149 	} else {
150 		sin6 = (struct sockaddr_in6 *)nam;
151 		if (nam->sa_len != sizeof(*sin6))
152 			return (EINVAL);
153 		/*
154 		 * family check.
155 		 */
156 		if (nam->sa_family != AF_INET6)
157 			return (EAFNOSUPPORT);
158 
159 		if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
160 			return(error);
161 
162 		if ((error = prison_local_ip6(cred, &sin6->sin6_addr,
163 		    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
164 			return (error);
165 
166 		lport = sin6->sin6_port;
167 		if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
168 			/*
169 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
170 			 * allow compepte duplication of binding if
171 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
172 			 * and a multicast address is bound on both
173 			 * new and duplicated sockets.
174 			 */
175 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
176 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
177 			/*
178 			 * XXX: How to deal with SO_REUSEPORT_LB here?
179 			 * Treat same as SO_REUSEPORT for now.
180 			 */
181 			if ((so->so_options &
182 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
183 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
184 		} else if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
185 			struct epoch_tracker et;
186 			struct ifaddr *ifa;
187 
188 			sin6->sin6_port = 0;		/* yech... */
189 			NET_EPOCH_ENTER(et);
190 			if ((ifa = ifa_ifwithaddr((struct sockaddr *)sin6)) ==
191 			    NULL &&
192 			    (inp->inp_flags & INP_BINDANY) == 0) {
193 				NET_EPOCH_EXIT(et);
194 				return (EADDRNOTAVAIL);
195 			}
196 
197 			/*
198 			 * XXX: bind to an anycast address might accidentally
199 			 * cause sending a packet with anycast source address.
200 			 * We should allow to bind to a deprecated address, since
201 			 * the application dares to use it.
202 			 */
203 			if (ifa != NULL &&
204 			    ((struct in6_ifaddr *)ifa)->ia6_flags &
205 			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY|IN6_IFF_DETACHED)) {
206 				NET_EPOCH_EXIT(et);
207 				return (EADDRNOTAVAIL);
208 			}
209 			NET_EPOCH_EXIT(et);
210 		}
211 		if (lport) {
212 			struct inpcb *t;
213 			struct tcptw *tw;
214 
215 			/* GROSS */
216 			if (ntohs(lport) <= V_ipport_reservedhigh &&
217 			    ntohs(lport) >= V_ipport_reservedlow &&
218 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
219 				return (EACCES);
220 			if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) &&
221 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
222 				t = in6_pcblookup_local(pcbinfo,
223 				    &sin6->sin6_addr, lport,
224 				    INPLOOKUP_WILDCARD, cred);
225 				if (t &&
226 				    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
227 				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
228 				    (so->so_type != SOCK_STREAM ||
229 				     IN6_IS_ADDR_UNSPECIFIED(&t->in6p_faddr)) &&
230 				    (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
231 				     !IN6_IS_ADDR_UNSPECIFIED(&t->in6p_laddr) ||
232 				     (t->inp_flags2 & INP_REUSEPORT) ||
233 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
234 				    (inp->inp_cred->cr_uid !=
235 				     t->inp_cred->cr_uid))
236 					return (EADDRINUSE);
237 
238 				/*
239 				 * If the socket is a BINDMULTI socket, then
240 				 * the credentials need to match and the
241 				 * original socket also has to have been bound
242 				 * with BINDMULTI.
243 				 */
244 				if (t && (! in_pcbbind_check_bindmulti(inp, t)))
245 					return (EADDRINUSE);
246 
247 #ifdef INET
248 				if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
249 				    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
250 					struct sockaddr_in sin;
251 
252 					in6_sin6_2_sin(&sin, sin6);
253 					t = in_pcblookup_local(pcbinfo,
254 					    sin.sin_addr, lport,
255 					    INPLOOKUP_WILDCARD, cred);
256 					if (t &&
257 					    ((inp->inp_flags2 & INP_BINDMULTI) == 0) &&
258 					    ((t->inp_flags &
259 					      INP_TIMEWAIT) == 0) &&
260 					    (so->so_type != SOCK_STREAM ||
261 					     ntohl(t->inp_faddr.s_addr) ==
262 					      INADDR_ANY) &&
263 					    (inp->inp_cred->cr_uid !=
264 					     t->inp_cred->cr_uid))
265 						return (EADDRINUSE);
266 
267 					if (t && (! in_pcbbind_check_bindmulti(inp, t)))
268 						return (EADDRINUSE);
269 				}
270 #endif
271 			}
272 			t = in6_pcblookup_local(pcbinfo, &sin6->sin6_addr,
273 			    lport, lookupflags, cred);
274 			if (t && (t->inp_flags & INP_TIMEWAIT)) {
275 				/*
276 				 * XXXRW: If an incpb has had its timewait
277 				 * state recycled, we treat the address as
278 				 * being in use (for now).  This is better
279 				 * than a panic, but not desirable.
280 				 */
281 				tw = intotw(t);
282 				if (tw == NULL ||
283 				    ((reuseport & tw->tw_so_options) == 0 &&
284 					 (reuseport_lb & tw->tw_so_options) == 0))
285 					return (EADDRINUSE);
286 			} else if (t && (reuseport & inp_so_options(t)) == 0 &&
287 					   (reuseport_lb & inp_so_options(t)) == 0) {
288 				return (EADDRINUSE);
289 			}
290 #ifdef INET
291 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
292 			    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
293 				struct sockaddr_in sin;
294 
295 				in6_sin6_2_sin(&sin, sin6);
296 				t = in_pcblookup_local(pcbinfo, sin.sin_addr,
297 				   lport, lookupflags, cred);
298 				if (t && t->inp_flags & INP_TIMEWAIT) {
299 					tw = intotw(t);
300 					if (tw == NULL)
301 						return (EADDRINUSE);
302 					if ((reuseport & tw->tw_so_options) == 0
303 					    && (reuseport_lb & tw->tw_so_options) == 0
304 					    && (ntohl(t->inp_laddr.s_addr) !=
305 					        INADDR_ANY || ((inp->inp_vflag &
306 					                INP_IPV6PROTO) ==
307 					            (t->inp_vflag & INP_IPV6PROTO))))
308 						return (EADDRINUSE);
309 				} else if (t &&
310 				    (reuseport & inp_so_options(t)) == 0 &&
311 				    (reuseport_lb & inp_so_options(t)) == 0 &&
312 				    (ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
313 				        (t->inp_vflag & INP_IPV6PROTO) != 0)) {
314 					return (EADDRINUSE);
315 				}
316 			}
317 #endif
318 		}
319 		inp->in6p_laddr = sin6->sin6_addr;
320 	}
321 	if (lport == 0) {
322 		if ((error = in6_pcbsetport(&inp->in6p_laddr, inp, cred)) != 0) {
323 			/* Undo an address bind that may have occurred. */
324 			inp->in6p_laddr = in6addr_any;
325 			return (error);
326 		}
327 	} else {
328 		inp->inp_lport = lport;
329 		if (in_pcbinshash(inp) != 0) {
330 			inp->in6p_laddr = in6addr_any;
331 			inp->inp_lport = 0;
332 			return (EAGAIN);
333 		}
334 	}
335 	return (0);
336 }
337 
338 /*
339  *   Transform old in6_pcbconnect() into an inner subroutine for new
340  *   in6_pcbconnect(): Do some validity-checking on the remote
341  *   address (in mbuf 'nam') and then determine local host address
342  *   (i.e., which interface) to use to access that remote host.
343  *
344  *   This preserves definition of in6_pcbconnect(), while supporting a
345  *   slightly different version for T/TCP.  (This is more than
346  *   a bit of a kludge, but cleaning up the internal interfaces would
347  *   have forced minor changes in every protocol).
348  */
349 static int
350 in6_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
351     struct in6_addr *plocal_addr6)
352 {
353 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
354 	int error = 0;
355 	int scope_ambiguous = 0;
356 	struct in6_addr in6a;
357 
358 	INP_WLOCK_ASSERT(inp);
359 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);	/* XXXRW: why? */
360 
361 	if (nam->sa_len != sizeof (*sin6))
362 		return (EINVAL);
363 	if (sin6->sin6_family != AF_INET6)
364 		return (EAFNOSUPPORT);
365 	if (sin6->sin6_port == 0)
366 		return (EADDRNOTAVAIL);
367 
368 	if (sin6->sin6_scope_id == 0 && !V_ip6_use_defzone)
369 		scope_ambiguous = 1;
370 	if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
371 		return(error);
372 
373 	if (!CK_STAILQ_EMPTY(&V_in6_ifaddrhead)) {
374 		/*
375 		 * If the destination address is UNSPECIFIED addr,
376 		 * use the loopback addr, e.g ::1.
377 		 */
378 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
379 			sin6->sin6_addr = in6addr_loopback;
380 	}
381 	if ((error = prison_remote_ip6(inp->inp_cred, &sin6->sin6_addr)) != 0)
382 		return (error);
383 
384 	error = in6_selectsrc_socket(sin6, inp->in6p_outputopts,
385 	    inp, inp->inp_cred, scope_ambiguous, &in6a, NULL);
386 	if (error)
387 		return (error);
388 
389 	/*
390 	 * Do not update this earlier, in case we return with an error.
391 	 *
392 	 * XXX: this in6_selectsrc_socket result might replace the bound local
393 	 * address with the address specified by setsockopt(IPV6_PKTINFO).
394 	 * Is it the intended behavior?
395 	 */
396 	*plocal_addr6 = in6a;
397 
398 	/*
399 	 * Don't do pcblookup call here; return interface in
400 	 * plocal_addr6
401 	 * and exit to caller, that will do the lookup.
402 	 */
403 
404 	return (0);
405 }
406 
407 /*
408  * Outer subroutine:
409  * Connect from a socket to a specified address.
410  * Both address and port must be specified in argument sin.
411  * If don't have a local address for this socket yet,
412  * then pick one.
413  */
414 int
415 in6_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
416     struct ucred *cred, struct mbuf *m, bool rehash)
417 {
418 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
419 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)nam;
420 	struct in6_addr addr6;
421 	int error;
422 
423 	INP_WLOCK_ASSERT(inp);
424 	INP_HASH_WLOCK_ASSERT(pcbinfo);
425 
426 	/*
427 	 * Call inner routine, to assign local interface address.
428 	 * in6_pcbladdr() may automatically fill in sin6_scope_id.
429 	 */
430 	if ((error = in6_pcbladdr(inp, nam, &addr6)) != 0)
431 		return (error);
432 
433 	if (in6_pcblookup_hash_locked(pcbinfo, &sin6->sin6_addr,
434 			       sin6->sin6_port,
435 			      IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)
436 			      ? &addr6 : &inp->in6p_laddr,
437 			      inp->inp_lport, 0, NULL) != NULL) {
438 		return (EADDRINUSE);
439 	}
440 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
441 		if (inp->inp_lport == 0) {
442 			KASSERT(rehash == true,
443 			    ("Rehashing required for unbound inps"));
444 			error = in6_pcbbind(inp, (struct sockaddr *)0, cred);
445 			if (error)
446 				return (error);
447 		}
448 		inp->in6p_laddr = addr6;
449 	}
450 	inp->in6p_faddr = sin6->sin6_addr;
451 	inp->inp_fport = sin6->sin6_port;
452 	/* update flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
453 	inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
454 	if (inp->inp_flags & IN6P_AUTOFLOWLABEL)
455 		inp->inp_flow |=
456 		    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
457 
458 	if (rehash) {
459 		in_pcbrehash_mbuf(inp, m);
460 	} else {
461 		in_pcbinshash_mbuf(inp, m);
462 	}
463 
464 	return (0);
465 }
466 
467 int
468 in6_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
469 {
470 
471 	return (in6_pcbconnect_mbuf(inp, nam, cred, NULL, true));
472 }
473 
474 void
475 in6_pcbdisconnect(struct inpcb *inp)
476 {
477 
478 	INP_WLOCK_ASSERT(inp);
479 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
480 
481 	bzero((caddr_t)&inp->in6p_faddr, sizeof(inp->in6p_faddr));
482 	inp->inp_fport = 0;
483 	/* clear flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
484 	inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
485 	in_pcbrehash(inp);
486 }
487 
488 struct sockaddr *
489 in6_sockaddr(in_port_t port, struct in6_addr *addr_p)
490 {
491 	struct sockaddr_in6 *sin6;
492 
493 	sin6 = malloc(sizeof *sin6, M_SONAME, M_WAITOK);
494 	bzero(sin6, sizeof *sin6);
495 	sin6->sin6_family = AF_INET6;
496 	sin6->sin6_len = sizeof(*sin6);
497 	sin6->sin6_port = port;
498 	sin6->sin6_addr = *addr_p;
499 	(void)sa6_recoverscope(sin6); /* XXX: should catch errors */
500 
501 	return (struct sockaddr *)sin6;
502 }
503 
504 struct sockaddr *
505 in6_v4mapsin6_sockaddr(in_port_t port, struct in_addr *addr_p)
506 {
507 	struct sockaddr_in sin;
508 	struct sockaddr_in6 *sin6_p;
509 
510 	bzero(&sin, sizeof sin);
511 	sin.sin_family = AF_INET;
512 	sin.sin_len = sizeof(sin);
513 	sin.sin_port = port;
514 	sin.sin_addr = *addr_p;
515 
516 	sin6_p = malloc(sizeof *sin6_p, M_SONAME,
517 		M_WAITOK);
518 	in6_sin_2_v4mapsin6(&sin, sin6_p);
519 
520 	return (struct sockaddr *)sin6_p;
521 }
522 
523 int
524 in6_getsockaddr(struct socket *so, struct sockaddr **nam)
525 {
526 	struct inpcb *inp;
527 	struct in6_addr addr;
528 	in_port_t port;
529 
530 	inp = sotoinpcb(so);
531 	KASSERT(inp != NULL, ("in6_getsockaddr: inp == NULL"));
532 
533 	INP_RLOCK(inp);
534 	port = inp->inp_lport;
535 	addr = inp->in6p_laddr;
536 	INP_RUNLOCK(inp);
537 
538 	*nam = in6_sockaddr(port, &addr);
539 	return 0;
540 }
541 
542 int
543 in6_getpeeraddr(struct socket *so, struct sockaddr **nam)
544 {
545 	struct inpcb *inp;
546 	struct in6_addr addr;
547 	in_port_t port;
548 
549 	inp = sotoinpcb(so);
550 	KASSERT(inp != NULL, ("in6_getpeeraddr: inp == NULL"));
551 
552 	INP_RLOCK(inp);
553 	port = inp->inp_fport;
554 	addr = inp->in6p_faddr;
555 	INP_RUNLOCK(inp);
556 
557 	*nam = in6_sockaddr(port, &addr);
558 	return 0;
559 }
560 
561 int
562 in6_mapped_sockaddr(struct socket *so, struct sockaddr **nam)
563 {
564 	struct	inpcb *inp;
565 	int	error;
566 
567 	inp = sotoinpcb(so);
568 	KASSERT(inp != NULL, ("in6_mapped_sockaddr: inp == NULL"));
569 
570 #ifdef INET
571 	if ((inp->inp_vflag & (INP_IPV4 | INP_IPV6)) == INP_IPV4) {
572 		error = in_getsockaddr(so, nam);
573 		if (error == 0)
574 			in6_sin_2_v4mapsin6_in_sock(nam);
575 	} else
576 #endif
577 	{
578 		/* scope issues will be handled in in6_getsockaddr(). */
579 		error = in6_getsockaddr(so, nam);
580 	}
581 
582 	return error;
583 }
584 
585 int
586 in6_mapped_peeraddr(struct socket *so, struct sockaddr **nam)
587 {
588 	struct	inpcb *inp;
589 	int	error;
590 
591 	inp = sotoinpcb(so);
592 	KASSERT(inp != NULL, ("in6_mapped_peeraddr: inp == NULL"));
593 
594 #ifdef INET
595 	if ((inp->inp_vflag & (INP_IPV4 | INP_IPV6)) == INP_IPV4) {
596 		error = in_getpeeraddr(so, nam);
597 		if (error == 0)
598 			in6_sin_2_v4mapsin6_in_sock(nam);
599 	} else
600 #endif
601 	/* scope issues will be handled in in6_getpeeraddr(). */
602 	error = in6_getpeeraddr(so, nam);
603 
604 	return error;
605 }
606 
607 /*
608  * Pass some notification to all connections of a protocol
609  * associated with address dst.  The local address and/or port numbers
610  * may be specified to limit the search.  The "usual action" will be
611  * taken, depending on the ctlinput cmd.  The caller must filter any
612  * cmds that are uninteresting (e.g., no error in the map).
613  * Call the protocol specific routine (if any) to report
614  * any errors for each matching socket.
615  */
616 void
617 in6_pcbnotify(struct inpcbinfo *pcbinfo, struct sockaddr *dst,
618     u_int fport_arg, const struct sockaddr *src, u_int lport_arg,
619     int cmd, void *cmdarg,
620     struct inpcb *(*notify)(struct inpcb *, int))
621 {
622 	struct inpcb *inp, *inp_temp;
623 	struct sockaddr_in6 sa6_src, *sa6_dst;
624 	u_short	fport = fport_arg, lport = lport_arg;
625 	u_int32_t flowinfo;
626 	int errno;
627 
628 	if ((unsigned)cmd >= PRC_NCMDS || dst->sa_family != AF_INET6)
629 		return;
630 
631 	sa6_dst = (struct sockaddr_in6 *)dst;
632 	if (IN6_IS_ADDR_UNSPECIFIED(&sa6_dst->sin6_addr))
633 		return;
634 
635 	/*
636 	 * note that src can be NULL when we get notify by local fragmentation.
637 	 */
638 	sa6_src = (src == NULL) ? sa6_any : *(const struct sockaddr_in6 *)src;
639 	flowinfo = sa6_src.sin6_flowinfo;
640 
641 	/*
642 	 * Redirects go to all references to the destination,
643 	 * and use in6_rtchange to invalidate the route cache.
644 	 * Dead host indications: also use in6_rtchange to invalidate
645 	 * the cache, and deliver the error to all the sockets.
646 	 * Otherwise, if we have knowledge of the local port and address,
647 	 * deliver only to that socket.
648 	 */
649 	if (PRC_IS_REDIRECT(cmd) || cmd == PRC_HOSTDEAD) {
650 		fport = 0;
651 		lport = 0;
652 		bzero((caddr_t)&sa6_src.sin6_addr, sizeof(sa6_src.sin6_addr));
653 
654 		if (cmd != PRC_HOSTDEAD)
655 			notify = in6_rtchange;
656 	}
657 	errno = inet6ctlerrmap[cmd];
658 	INP_INFO_WLOCK(pcbinfo);
659 	CK_LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
660 		INP_WLOCK(inp);
661 		if ((inp->inp_vflag & INP_IPV6) == 0) {
662 			INP_WUNLOCK(inp);
663 			continue;
664 		}
665 
666 		/*
667 		 * If the error designates a new path MTU for a destination
668 		 * and the application (associated with this socket) wanted to
669 		 * know the value, notify.
670 		 * XXX: should we avoid to notify the value to TCP sockets?
671 		 */
672 		if (cmd == PRC_MSGSIZE && cmdarg != NULL)
673 			ip6_notify_pmtu(inp, (struct sockaddr_in6 *)dst,
674 					*(u_int32_t *)cmdarg);
675 
676 		/*
677 		 * Detect if we should notify the error. If no source and
678 		 * destination ports are specifed, but non-zero flowinfo and
679 		 * local address match, notify the error. This is the case
680 		 * when the error is delivered with an encrypted buffer
681 		 * by ESP. Otherwise, just compare addresses and ports
682 		 * as usual.
683 		 */
684 		if (lport == 0 && fport == 0 && flowinfo &&
685 		    inp->inp_socket != NULL &&
686 		    flowinfo == (inp->inp_flow & IPV6_FLOWLABEL_MASK) &&
687 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &sa6_src.sin6_addr))
688 			goto do_notify;
689 		else if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr,
690 					     &sa6_dst->sin6_addr) ||
691 			 inp->inp_socket == 0 ||
692 			 (lport && inp->inp_lport != lport) ||
693 			 (!IN6_IS_ADDR_UNSPECIFIED(&sa6_src.sin6_addr) &&
694 			  !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
695 					      &sa6_src.sin6_addr)) ||
696 			 (fport && inp->inp_fport != fport)) {
697 			INP_WUNLOCK(inp);
698 			continue;
699 		}
700 
701 	  do_notify:
702 		if (notify) {
703 			if ((*notify)(inp, errno))
704 				INP_WUNLOCK(inp);
705 		} else
706 			INP_WUNLOCK(inp);
707 	}
708 	INP_INFO_WUNLOCK(pcbinfo);
709 }
710 
711 /*
712  * Lookup a PCB based on the local address and port.  Caller must hold the
713  * hash lock.  No inpcb locks or references are acquired.
714  */
715 struct inpcb *
716 in6_pcblookup_local(struct inpcbinfo *pcbinfo, struct in6_addr *laddr,
717     u_short lport, int lookupflags, struct ucred *cred)
718 {
719 	struct inpcb *inp;
720 	int matchwild = 3, wildcard;
721 
722 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
723 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
724 
725 	INP_HASH_LOCK_ASSERT(pcbinfo);
726 
727 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
728 		struct inpcbhead *head;
729 		/*
730 		 * Look for an unconnected (wildcard foreign addr) PCB that
731 		 * matches the local address and port we're looking for.
732 		 */
733 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(
734 		    INP6_PCBHASHKEY(&in6addr_any), lport, 0,
735 		    pcbinfo->ipi_hashmask)];
736 		CK_LIST_FOREACH(inp, head, inp_hash) {
737 			/* XXX inp locking */
738 			if ((inp->inp_vflag & INP_IPV6) == 0)
739 				continue;
740 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
741 			    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
742 			    inp->inp_lport == lport) {
743 				/* Found. */
744 				if (cred == NULL ||
745 				    prison_equal_ip6(cred->cr_prison,
746 					inp->inp_cred->cr_prison))
747 					return (inp);
748 			}
749 		}
750 		/*
751 		 * Not found.
752 		 */
753 		return (NULL);
754 	} else {
755 		struct inpcbporthead *porthash;
756 		struct inpcbport *phd;
757 		struct inpcb *match = NULL;
758 		/*
759 		 * Best fit PCB lookup.
760 		 *
761 		 * First see if this local port is in use by looking on the
762 		 * port hash list.
763 		 */
764 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
765 		    pcbinfo->ipi_porthashmask)];
766 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
767 			if (phd->phd_port == lport)
768 				break;
769 		}
770 		if (phd != NULL) {
771 			/*
772 			 * Port is in use by one or more PCBs. Look for best
773 			 * fit.
774 			 */
775 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
776 				wildcard = 0;
777 				if (cred != NULL &&
778 				    !prison_equal_ip6(cred->cr_prison,
779 					inp->inp_cred->cr_prison))
780 					continue;
781 				/* XXX inp locking */
782 				if ((inp->inp_vflag & INP_IPV6) == 0)
783 					continue;
784 				if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
785 					wildcard++;
786 				if (!IN6_IS_ADDR_UNSPECIFIED(
787 					&inp->in6p_laddr)) {
788 					if (IN6_IS_ADDR_UNSPECIFIED(laddr))
789 						wildcard++;
790 					else if (!IN6_ARE_ADDR_EQUAL(
791 					    &inp->in6p_laddr, laddr))
792 						continue;
793 				} else {
794 					if (!IN6_IS_ADDR_UNSPECIFIED(laddr))
795 						wildcard++;
796 				}
797 				if (wildcard < matchwild) {
798 					match = inp;
799 					matchwild = wildcard;
800 					if (matchwild == 0)
801 						break;
802 				}
803 			}
804 		}
805 		return (match);
806 	}
807 }
808 
809 void
810 in6_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
811 {
812 	struct inpcb *inp;
813 	struct in6_multi *inm;
814 	struct in6_mfilter *imf;
815 	struct ip6_moptions *im6o;
816 
817 	INP_INFO_WLOCK(pcbinfo);
818 	CK_LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
819 		INP_WLOCK(inp);
820 		if (__predict_false(inp->inp_flags2 & INP_FREED)) {
821 			INP_WUNLOCK(inp);
822 			continue;
823 		}
824 		im6o = inp->in6p_moptions;
825 		if ((inp->inp_vflag & INP_IPV6) && im6o != NULL) {
826 			/*
827 			 * Unselect the outgoing ifp for multicast if it
828 			 * is being detached.
829 			 */
830 			if (im6o->im6o_multicast_ifp == ifp)
831 				im6o->im6o_multicast_ifp = NULL;
832 			/*
833 			 * Drop multicast group membership if we joined
834 			 * through the interface being detached.
835 			 */
836 restart:
837 			IP6_MFILTER_FOREACH(imf, &im6o->im6o_head) {
838 				if ((inm = imf->im6f_in6m) == NULL)
839 					continue;
840 				if (inm->in6m_ifp != ifp)
841 					continue;
842 				ip6_mfilter_remove(&im6o->im6o_head, imf);
843 				IN6_MULTI_LOCK_ASSERT();
844 				in6_leavegroup_locked(inm, NULL);
845 				ip6_mfilter_free(imf);
846 				goto restart;
847 			}
848 		}
849 		INP_WUNLOCK(inp);
850 	}
851 	INP_INFO_WUNLOCK(pcbinfo);
852 }
853 
854 /*
855  * Check for alternatives when higher level complains
856  * about service problems.  For now, invalidate cached
857  * routing information.  If the route was created dynamically
858  * (by a redirect), time to try a default gateway again.
859  */
860 void
861 in6_losing(struct inpcb *inp)
862 {
863 
864 	RO_INVALIDATE_CACHE(&inp->inp_route6);
865 }
866 
867 /*
868  * After a routing change, flush old routing
869  * and allocate a (hopefully) better one.
870  */
871 struct inpcb *
872 in6_rtchange(struct inpcb *inp, int errno __unused)
873 {
874 
875 	RO_INVALIDATE_CACHE(&inp->inp_route6);
876 	return inp;
877 }
878 
879 static struct inpcb *
880 in6_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
881     const struct in6_addr *laddr, uint16_t lport, const struct in6_addr *faddr,
882     uint16_t fport, int lookupflags)
883 {
884 	struct inpcb *local_wild;
885 	const struct inpcblbgrouphead *hdr;
886 	struct inpcblbgroup *grp;
887 	uint32_t idx;
888 
889 	INP_HASH_LOCK_ASSERT(pcbinfo);
890 
891 	hdr = &pcbinfo->ipi_lbgrouphashbase[
892 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
893 
894 	/*
895 	 * Order of socket selection:
896 	 * 1. non-wild.
897 	 * 2. wild (if lookupflags contains INPLOOKUP_WILDCARD).
898 	 *
899 	 * NOTE:
900 	 * - Load balanced group does not contain jailed sockets.
901 	 * - Load balanced does not contain IPv4 mapped INET6 wild sockets.
902 	 */
903 	local_wild = NULL;
904 	CK_LIST_FOREACH(grp, hdr, il_list) {
905 #ifdef INET
906 		if (!(grp->il_vflag & INP_IPV6))
907 			continue;
908 #endif
909 		if (grp->il_lport != lport)
910 			continue;
911 
912 		idx = INP_PCBLBGROUP_PKTHASH(INP6_PCBHASHKEY(faddr), lport,
913 		    fport) % grp->il_inpcnt;
914 		if (IN6_ARE_ADDR_EQUAL(&grp->il6_laddr, laddr))
915 			return (grp->il_inp[idx]);
916 		if (IN6_IS_ADDR_UNSPECIFIED(&grp->il6_laddr) &&
917 		    (lookupflags & INPLOOKUP_WILDCARD) != 0)
918 			local_wild = grp->il_inp[idx];
919 	}
920 	return (local_wild);
921 }
922 
923 #ifdef PCBGROUP
924 /*
925  * Lookup PCB in hash list, using pcbgroup tables.
926  */
927 static struct inpcb *
928 in6_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
929     struct in6_addr *faddr, u_int fport_arg, struct in6_addr *laddr,
930     u_int lport_arg, int lookupflags, struct ifnet *ifp)
931 {
932 	struct inpcbhead *head;
933 	struct inpcb *inp, *tmpinp;
934 	u_short fport = fport_arg, lport = lport_arg;
935 	bool locked;
936 
937 	/*
938 	 * First look for an exact match.
939 	 */
940 	tmpinp = NULL;
941 	INP_GROUP_LOCK(pcbgroup);
942 	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(
943 	    INP6_PCBHASHKEY(faddr), lport, fport, pcbgroup->ipg_hashmask)];
944 	CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
945 		/* XXX inp locking */
946 		if ((inp->inp_vflag & INP_IPV6) == 0)
947 			continue;
948 		if (IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, faddr) &&
949 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
950 		    inp->inp_fport == fport &&
951 		    inp->inp_lport == lport) {
952 			/*
953 			 * XXX We should be able to directly return
954 			 * the inp here, without any checks.
955 			 * Well unless both bound with SO_REUSEPORT?
956 			 */
957 			if (prison_flag(inp->inp_cred, PR_IP6))
958 				goto found;
959 			if (tmpinp == NULL)
960 				tmpinp = inp;
961 		}
962 	}
963 	if (tmpinp != NULL) {
964 		inp = tmpinp;
965 		goto found;
966 	}
967 
968 	/*
969 	 * Then look for a wildcard match in the pcbgroup.
970 	 */
971 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
972 		struct inpcb *local_wild = NULL, *local_exact = NULL;
973 		struct inpcb *jail_wild = NULL;
974 		int injail;
975 
976 		/*
977 		 * Order of socket selection - we always prefer jails.
978 		 *      1. jailed, non-wild.
979 		 *      2. jailed, wild.
980 		 *      3. non-jailed, non-wild.
981 		 *      4. non-jailed, wild.
982 		 */
983 		head = &pcbgroup->ipg_hashbase[
984 		    INP_PCBHASH(INADDR_ANY, lport, 0, pcbgroup->ipg_hashmask)];
985 		CK_LIST_FOREACH(inp, head, inp_pcbgrouphash) {
986 			/* XXX inp locking */
987 			if ((inp->inp_vflag & INP_IPV6) == 0)
988 				continue;
989 
990 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
991 			    inp->inp_lport != lport) {
992 				continue;
993 			}
994 
995 			injail = prison_flag(inp->inp_cred, PR_IP6);
996 			if (injail) {
997 				if (prison_check_ip6(inp->inp_cred,
998 				    laddr) != 0)
999 					continue;
1000 			} else {
1001 				if (local_exact != NULL)
1002 					continue;
1003 			}
1004 
1005 			if (IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr)) {
1006 				if (injail)
1007 					goto found;
1008 				else
1009 					local_exact = inp;
1010 			} else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1011 				if (injail)
1012 					jail_wild = inp;
1013 				else
1014 					local_wild = inp;
1015 			}
1016 		} /* LIST_FOREACH */
1017 
1018 		inp = jail_wild;
1019 		if (inp == NULL)
1020 			inp = jail_wild;
1021 		if (inp == NULL)
1022 			inp = local_exact;
1023 		if (inp == NULL)
1024 			inp = local_wild;
1025 		if (inp != NULL)
1026 			goto found;
1027 	}
1028 
1029 	/*
1030 	 * Then look for a wildcard match, if requested.
1031 	 */
1032 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1033 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1034 		struct inpcb *jail_wild = NULL;
1035 		int injail;
1036 
1037 		/*
1038 		 * Order of socket selection - we always prefer jails.
1039 		 *      1. jailed, non-wild.
1040 		 *      2. jailed, wild.
1041 		 *      3. non-jailed, non-wild.
1042 		 *      4. non-jailed, wild.
1043 		 */
1044 		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(
1045 		    INP6_PCBHASHKEY(&in6addr_any), lport, 0,
1046 		    pcbinfo->ipi_wildmask)];
1047 		CK_LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1048 			/* XXX inp locking */
1049 			if ((inp->inp_vflag & INP_IPV6) == 0)
1050 				continue;
1051 
1052 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
1053 			    inp->inp_lport != lport) {
1054 				continue;
1055 			}
1056 
1057 			injail = prison_flag(inp->inp_cred, PR_IP6);
1058 			if (injail) {
1059 				if (prison_check_ip6(inp->inp_cred,
1060 				    laddr) != 0)
1061 					continue;
1062 			} else {
1063 				if (local_exact != NULL)
1064 					continue;
1065 			}
1066 
1067 			if (IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr)) {
1068 				if (injail)
1069 					goto found;
1070 				else
1071 					local_exact = inp;
1072 			} else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1073 				if (injail)
1074 					jail_wild = inp;
1075 				else
1076 					local_wild = inp;
1077 			}
1078 		} /* LIST_FOREACH */
1079 
1080 		inp = jail_wild;
1081 		if (inp == NULL)
1082 			inp = jail_wild;
1083 		if (inp == NULL)
1084 			inp = local_exact;
1085 		if (inp == NULL)
1086 			inp = local_wild;
1087 		if (inp != NULL)
1088 			goto found;
1089 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1090 	INP_GROUP_UNLOCK(pcbgroup);
1091 	return (NULL);
1092 
1093 found:
1094 	if (lookupflags & INPLOOKUP_WLOCKPCB)
1095 		locked = INP_TRY_WLOCK(inp);
1096 	else if (lookupflags & INPLOOKUP_RLOCKPCB)
1097 		locked = INP_TRY_RLOCK(inp);
1098 	else
1099 		panic("%s: locking buf", __func__);
1100 	if (!locked)
1101 		in_pcbref(inp);
1102 	INP_GROUP_UNLOCK(pcbgroup);
1103 	if (!locked) {
1104 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
1105 			INP_WLOCK(inp);
1106 			if (in_pcbrele_wlocked(inp))
1107 				return (NULL);
1108 		} else {
1109 			INP_RLOCK(inp);
1110 			if (in_pcbrele_rlocked(inp))
1111 				return (NULL);
1112 		}
1113 	}
1114 #ifdef INVARIANTS
1115 	if (lookupflags & INPLOOKUP_WLOCKPCB)
1116 		INP_WLOCK_ASSERT(inp);
1117 	else
1118 		INP_RLOCK_ASSERT(inp);
1119 #endif
1120 	return (inp);
1121 }
1122 #endif /* PCBGROUP */
1123 
1124 /*
1125  * Lookup PCB in hash list.
1126  */
1127 static struct inpcb *
1128 in6_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1129     u_int fport_arg, struct in6_addr *laddr, u_int lport_arg,
1130     int lookupflags, struct ifnet *ifp)
1131 {
1132 	struct inpcbhead *head;
1133 	struct inpcb *inp, *tmpinp;
1134 	u_short fport = fport_arg, lport = lport_arg;
1135 
1136 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1137 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1138 
1139 	INP_HASH_LOCK_ASSERT(pcbinfo);
1140 
1141 	/*
1142 	 * First look for an exact match.
1143 	 */
1144 	tmpinp = NULL;
1145 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(
1146 	    INP6_PCBHASHKEY(faddr), lport, fport, pcbinfo->ipi_hashmask)];
1147 	CK_LIST_FOREACH(inp, head, inp_hash) {
1148 		/* XXX inp locking */
1149 		if ((inp->inp_vflag & INP_IPV6) == 0)
1150 			continue;
1151 		if (IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, faddr) &&
1152 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
1153 		    inp->inp_fport == fport &&
1154 		    inp->inp_lport == lport) {
1155 			/*
1156 			 * XXX We should be able to directly return
1157 			 * the inp here, without any checks.
1158 			 * Well unless both bound with SO_REUSEPORT?
1159 			 */
1160 			if (prison_flag(inp->inp_cred, PR_IP6))
1161 				return (inp);
1162 			if (tmpinp == NULL)
1163 				tmpinp = inp;
1164 		}
1165 	}
1166 	if (tmpinp != NULL)
1167 		return (tmpinp);
1168 
1169 	/*
1170 	 * Then look in lb group (for wildcard match).
1171 	 */
1172 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1173 		inp = in6_pcblookup_lbgroup(pcbinfo, laddr, lport, faddr,
1174 		    fport, lookupflags);
1175 		if (inp != NULL)
1176 			return (inp);
1177 	}
1178 
1179 	/*
1180 	 * Then look for a wildcard match, if requested.
1181 	 */
1182 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1183 		struct inpcb *local_wild = NULL, *local_exact = NULL;
1184 		struct inpcb *jail_wild = NULL;
1185 		int injail;
1186 
1187 		/*
1188 		 * Order of socket selection - we always prefer jails.
1189 		 *      1. jailed, non-wild.
1190 		 *      2. jailed, wild.
1191 		 *      3. non-jailed, non-wild.
1192 		 *      4. non-jailed, wild.
1193 		 */
1194 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(
1195 		    INP6_PCBHASHKEY(&in6addr_any), lport, 0,
1196 		    pcbinfo->ipi_hashmask)];
1197 		CK_LIST_FOREACH(inp, head, inp_hash) {
1198 			/* XXX inp locking */
1199 			if ((inp->inp_vflag & INP_IPV6) == 0)
1200 				continue;
1201 
1202 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
1203 			    inp->inp_lport != lport) {
1204 				continue;
1205 			}
1206 
1207 			injail = prison_flag(inp->inp_cred, PR_IP6);
1208 			if (injail) {
1209 				if (prison_check_ip6(inp->inp_cred,
1210 				    laddr) != 0)
1211 					continue;
1212 			} else {
1213 				if (local_exact != NULL)
1214 					continue;
1215 			}
1216 
1217 			if (IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr)) {
1218 				if (injail)
1219 					return (inp);
1220 				else
1221 					local_exact = inp;
1222 			} else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1223 				if (injail)
1224 					jail_wild = inp;
1225 				else
1226 					local_wild = inp;
1227 			}
1228 		} /* LIST_FOREACH */
1229 
1230 		if (jail_wild != NULL)
1231 			return (jail_wild);
1232 		if (local_exact != NULL)
1233 			return (local_exact);
1234 		if (local_wild != NULL)
1235 			return (local_wild);
1236 	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1237 
1238 	/*
1239 	 * Not found.
1240 	 */
1241 	return (NULL);
1242 }
1243 
1244 /*
1245  * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
1246  * hash list lock, and will return the inpcb locked (i.e., requires
1247  * INPLOOKUP_LOCKPCB).
1248  */
1249 static struct inpcb *
1250 in6_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1251     u_int fport, struct in6_addr *laddr, u_int lport, int lookupflags,
1252     struct ifnet *ifp)
1253 {
1254 	struct inpcb *inp;
1255 
1256 	inp = in6_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1257 	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
1258 	if (inp != NULL) {
1259 		if (lookupflags & INPLOOKUP_WLOCKPCB) {
1260 			INP_WLOCK(inp);
1261 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
1262 				INP_WUNLOCK(inp);
1263 				inp = NULL;
1264 			}
1265 		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1266 			INP_RLOCK(inp);
1267 			if (__predict_false(inp->inp_flags2 & INP_FREED)) {
1268 				INP_RUNLOCK(inp);
1269 				inp = NULL;
1270 			}
1271 		} else
1272 			panic("%s: locking bug", __func__);
1273 #ifdef INVARIANTS
1274 		if (inp != NULL) {
1275 			if (lookupflags & INPLOOKUP_WLOCKPCB)
1276 				INP_WLOCK_ASSERT(inp);
1277 			else
1278 				INP_RLOCK_ASSERT(inp);
1279 		}
1280 #endif
1281 	}
1282 	return (inp);
1283 }
1284 
1285 /*
1286  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1287  * from which a pre-calculated hash value may be extracted.
1288  *
1289  * Possibly more of this logic should be in in6_pcbgroup.c.
1290  */
1291 struct inpcb *
1292 in6_pcblookup(struct inpcbinfo *pcbinfo, struct in6_addr *faddr, u_int fport,
1293     struct in6_addr *laddr, u_int lport, int lookupflags, struct ifnet *ifp)
1294 {
1295 #if defined(PCBGROUP) && !defined(RSS)
1296 	struct inpcbgroup *pcbgroup;
1297 #endif
1298 
1299 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1300 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1301 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1302 	    ("%s: LOCKPCB not set", __func__));
1303 
1304 	/*
1305 	 * When not using RSS, use connection groups in preference to the
1306 	 * reservation table when looking up 4-tuples.  When using RSS, just
1307 	 * use the reservation table, due to the cost of the Toeplitz hash
1308 	 * in software.
1309 	 *
1310 	 * XXXRW: This policy belongs in the pcbgroup code, as in principle
1311 	 * we could be doing RSS with a non-Toeplitz hash that is affordable
1312 	 * in software.
1313 	 */
1314 #if defined(PCBGROUP) && !defined(RSS)
1315 	if (in_pcbgroup_enabled(pcbinfo)) {
1316 		pcbgroup = in6_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1317 		    fport);
1318 		return (in6_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1319 		    laddr, lport, lookupflags, ifp));
1320 	}
1321 #endif
1322 	return (in6_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1323 	    lookupflags, ifp));
1324 }
1325 
1326 struct inpcb *
1327 in6_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1328     u_int fport, struct in6_addr *laddr, u_int lport, int lookupflags,
1329     struct ifnet *ifp, struct mbuf *m)
1330 {
1331 #ifdef PCBGROUP
1332 	struct inpcbgroup *pcbgroup;
1333 #endif
1334 
1335 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1336 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1337 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1338 	    ("%s: LOCKPCB not set", __func__));
1339 
1340 #ifdef PCBGROUP
1341 	/*
1342 	 * If we can use a hardware-generated hash to look up the connection
1343 	 * group, use that connection group to find the inpcb.  Otherwise
1344 	 * fall back on a software hash -- or the reservation table if we're
1345 	 * using RSS.
1346 	 *
1347 	 * XXXRW: As above, that policy belongs in the pcbgroup code.
1348 	 */
1349 	if (in_pcbgroup_enabled(pcbinfo) &&
1350 	    M_HASHTYPE_TEST(m, M_HASHTYPE_NONE) == 0) {
1351 		pcbgroup = in6_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
1352 		    m->m_pkthdr.flowid);
1353 		if (pcbgroup != NULL)
1354 			return (in6_pcblookup_group(pcbinfo, pcbgroup, faddr,
1355 			    fport, laddr, lport, lookupflags, ifp));
1356 #ifndef RSS
1357 		pcbgroup = in6_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1358 		    fport);
1359 		return (in6_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1360 		    laddr, lport, lookupflags, ifp));
1361 #endif
1362 	}
1363 #endif
1364 	return (in6_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1365 	    lookupflags, ifp));
1366 }
1367 
1368 void
1369 init_sin6(struct sockaddr_in6 *sin6, struct mbuf *m, int srcordst)
1370 {
1371 	struct ip6_hdr *ip;
1372 
1373 	ip = mtod(m, struct ip6_hdr *);
1374 	bzero(sin6, sizeof(*sin6));
1375 	sin6->sin6_len = sizeof(*sin6);
1376 	sin6->sin6_family = AF_INET6;
1377 	sin6->sin6_addr = srcordst ? ip->ip6_dst : ip->ip6_src;
1378 
1379 	(void)sa6_recoverscope(sin6); /* XXX: should catch errors... */
1380 
1381 	return;
1382 }
1383