xref: /freebsd/sys/netinet6/ip6_output.c (revision 206b73d0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "opt_inet.h"
69 #include "opt_inet6.h"
70 #include "opt_ipsec.h"
71 #include "opt_ratelimit.h"
72 #include "opt_route.h"
73 #include "opt_rss.h"
74 #include "opt_sctp.h"
75 
76 #include <sys/param.h>
77 #include <sys/kernel.h>
78 #include <sys/malloc.h>
79 #include <sys/mbuf.h>
80 #include <sys/errno.h>
81 #include <sys/priv.h>
82 #include <sys/proc.h>
83 #include <sys/protosw.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/syslog.h>
87 #include <sys/ucred.h>
88 
89 #include <machine/in_cksum.h>
90 
91 #include <net/if.h>
92 #include <net/if_var.h>
93 #include <net/if_llatbl.h>
94 #include <net/netisr.h>
95 #include <net/route.h>
96 #include <net/pfil.h>
97 #include <net/rss_config.h>
98 #include <net/vnet.h>
99 
100 #include <netinet/in.h>
101 #include <netinet/in_var.h>
102 #include <netinet/ip_var.h>
103 #include <netinet6/in6_fib.h>
104 #include <netinet6/in6_var.h>
105 #include <netinet/ip6.h>
106 #include <netinet/icmp6.h>
107 #include <netinet6/ip6_var.h>
108 #include <netinet/in_pcb.h>
109 #include <netinet/tcp_var.h>
110 #include <netinet6/nd6.h>
111 #include <netinet6/in6_rss.h>
112 
113 #include <netipsec/ipsec_support.h>
114 #ifdef SCTP
115 #include <netinet/sctp.h>
116 #include <netinet/sctp_crc32.h>
117 #endif
118 
119 #include <netinet6/ip6protosw.h>
120 #include <netinet6/scope6_var.h>
121 
122 extern int in6_mcast_loop;
123 
124 struct ip6_exthdrs {
125 	struct mbuf *ip6e_ip6;
126 	struct mbuf *ip6e_hbh;
127 	struct mbuf *ip6e_dest1;
128 	struct mbuf *ip6e_rthdr;
129 	struct mbuf *ip6e_dest2;
130 };
131 
132 static MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
133 
134 static int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **,
135 			   struct ucred *, int);
136 static int ip6_pcbopts(struct ip6_pktopts **, struct mbuf *,
137 	struct socket *, struct sockopt *);
138 static int ip6_getpcbopt(struct inpcb *, int, struct sockopt *);
139 static int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *,
140 	struct ucred *, int, int, int);
141 
142 static int ip6_copyexthdr(struct mbuf **, caddr_t, int);
143 static int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
144 	struct ip6_frag **);
145 static int ip6_insert_jumboopt(struct ip6_exthdrs *, u_int32_t);
146 static int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
147 static int ip6_getpmtu(struct route_in6 *, int,
148 	struct ifnet *, const struct in6_addr *, u_long *, int *, u_int,
149 	u_int);
150 static int ip6_calcmtu(struct ifnet *, const struct in6_addr *, u_long,
151 	u_long *, int *, u_int);
152 static int ip6_getpmtu_ctl(u_int, const struct in6_addr *, u_long *);
153 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, int);
154 
155 
156 /*
157  * Make an extension header from option data.  hp is the source, and
158  * mp is the destination.
159  */
160 #define MAKE_EXTHDR(hp, mp)						\
161     do {								\
162 	if (hp) {							\
163 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
164 		error = ip6_copyexthdr((mp), (caddr_t)(hp),		\
165 		    ((eh)->ip6e_len + 1) << 3);				\
166 		if (error)						\
167 			goto freehdrs;					\
168 	}								\
169     } while (/*CONSTCOND*/ 0)
170 
171 /*
172  * Form a chain of extension headers.
173  * m is the extension header mbuf
174  * mp is the previous mbuf in the chain
175  * p is the next header
176  * i is the type of option.
177  */
178 #define MAKE_CHAIN(m, mp, p, i)\
179     do {\
180 	if (m) {\
181 		if (!hdrsplit) \
182 			panic("assumption failed: hdr not split"); \
183 		*mtod((m), u_char *) = *(p);\
184 		*(p) = (i);\
185 		p = mtod((m), u_char *);\
186 		(m)->m_next = (mp)->m_next;\
187 		(mp)->m_next = (m);\
188 		(mp) = (m);\
189 	}\
190     } while (/*CONSTCOND*/ 0)
191 
192 void
193 in6_delayed_cksum(struct mbuf *m, uint32_t plen, u_short offset)
194 {
195 	u_short csum;
196 
197 	csum = in_cksum_skip(m, offset + plen, offset);
198 	if (m->m_pkthdr.csum_flags & CSUM_UDP_IPV6 && csum == 0)
199 		csum = 0xffff;
200 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
201 
202 	if (offset + sizeof(csum) > m->m_len)
203 		m_copyback(m, offset, sizeof(csum), (caddr_t)&csum);
204 	else
205 		*(u_short *)mtodo(m, offset) = csum;
206 }
207 
208 int
209 ip6_fragment(struct ifnet *ifp, struct mbuf *m0, int hlen, u_char nextproto,
210     int fraglen , uint32_t id)
211 {
212 	struct mbuf *m, **mnext, *m_frgpart;
213 	struct ip6_hdr *ip6, *mhip6;
214 	struct ip6_frag *ip6f;
215 	int off;
216 	int error;
217 	int tlen = m0->m_pkthdr.len;
218 
219 	KASSERT((fraglen % 8 == 0), ("Fragment length must be a multiple of 8"));
220 
221 	m = m0;
222 	ip6 = mtod(m, struct ip6_hdr *);
223 	mnext = &m->m_nextpkt;
224 
225 	for (off = hlen; off < tlen; off += fraglen) {
226 		m = m_gethdr(M_NOWAIT, MT_DATA);
227 		if (!m) {
228 			IP6STAT_INC(ip6s_odropped);
229 			return (ENOBUFS);
230 		}
231 
232 		/*
233 		 * Make sure the complete packet header gets copied
234 		 * from the originating mbuf to the newly created
235 		 * mbuf. This also ensures that existing firewall
236 		 * classification(s), VLAN tags and so on get copied
237 		 * to the resulting fragmented packet(s):
238 		 */
239 		if (m_dup_pkthdr(m, m0, M_NOWAIT) == 0) {
240 			m_free(m);
241 			IP6STAT_INC(ip6s_odropped);
242 			return (ENOBUFS);
243 		}
244 
245 		*mnext = m;
246 		mnext = &m->m_nextpkt;
247 		m->m_data += max_linkhdr;
248 		mhip6 = mtod(m, struct ip6_hdr *);
249 		*mhip6 = *ip6;
250 		m->m_len = sizeof(*mhip6);
251 		error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
252 		if (error) {
253 			IP6STAT_INC(ip6s_odropped);
254 			return (error);
255 		}
256 		ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
257 		if (off + fraglen >= tlen)
258 			fraglen = tlen - off;
259 		else
260 			ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
261 		mhip6->ip6_plen = htons((u_short)(fraglen + hlen +
262 		    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
263 		if ((m_frgpart = m_copym(m0, off, fraglen, M_NOWAIT)) == NULL) {
264 			IP6STAT_INC(ip6s_odropped);
265 			return (ENOBUFS);
266 		}
267 		m_cat(m, m_frgpart);
268 		m->m_pkthdr.len = fraglen + hlen + sizeof(*ip6f);
269 		ip6f->ip6f_reserved = 0;
270 		ip6f->ip6f_ident = id;
271 		ip6f->ip6f_nxt = nextproto;
272 		IP6STAT_INC(ip6s_ofragments);
273 		in6_ifstat_inc(ifp, ifs6_out_fragcreat);
274 	}
275 
276 	return (0);
277 }
278 
279 static int
280 ip6_output_send(struct inpcb *inp, struct ifnet *ifp, struct ifnet *origifp,
281     struct mbuf *m, struct sockaddr_in6 *dst, struct route_in6 *ro)
282 {
283 	struct m_snd_tag *mst;
284 	int error;
285 
286 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
287 	mst = NULL;
288 
289 #ifdef RATELIMIT
290 	if (inp != NULL) {
291 		if ((inp->inp_flags2 & INP_RATE_LIMIT_CHANGED) != 0 ||
292 		    (inp->inp_snd_tag != NULL &&
293 		    inp->inp_snd_tag->ifp != ifp))
294 			in_pcboutput_txrtlmt(inp, ifp, m);
295 
296 		if (inp->inp_snd_tag != NULL)
297 			mst = inp->inp_snd_tag;
298 	}
299 #endif
300 	if (mst != NULL) {
301 		KASSERT(m->m_pkthdr.rcvif == NULL,
302 		    ("trying to add a send tag to a forwarded packet"));
303 		if (mst->ifp != ifp) {
304 			error = EAGAIN;
305 			goto done;
306 		}
307 
308 		/* stamp send tag on mbuf */
309 		m->m_pkthdr.snd_tag = m_snd_tag_ref(mst);
310 		m->m_pkthdr.csum_flags |= CSUM_SND_TAG;
311 	}
312 
313 	error = nd6_output_ifp(ifp, origifp, m, dst, (struct route *)ro);
314 
315 done:
316 	/* Check for route change invalidating send tags. */
317 #ifdef RATELIMIT
318 	if (error == EAGAIN)
319 		in_pcboutput_eagain(inp);
320 #endif
321 	return (error);
322 }
323 
324 /*
325  * IP6 output. The packet in mbuf chain m contains a skeletal IP6
326  * header (with pri, len, nxt, hlim, src, dst).
327  * This function may modify ver and hlim only.
328  * The mbuf chain containing the packet will be freed.
329  * The mbuf opt, if present, will not be freed.
330  * If route_in6 ro is present and has ro_rt initialized, route lookup would be
331  * skipped and ro->ro_rt would be used. If ro is present but ro->ro_rt is NULL,
332  * then result of route lookup is stored in ro->ro_rt.
333  *
334  * type of "mtu": rt_mtu is u_long, ifnet.ifr_mtu is int, and
335  * nd_ifinfo.linkmtu is u_int32_t.  so we use u_long to hold largest one,
336  * which is rt_mtu.
337  *
338  * ifpp - XXX: just for statistics
339  */
340 /*
341  * XXX TODO: no flowid is assigned for outbound flows?
342  */
343 int
344 ip6_output(struct mbuf *m0, struct ip6_pktopts *opt,
345     struct route_in6 *ro, int flags, struct ip6_moptions *im6o,
346     struct ifnet **ifpp, struct inpcb *inp)
347 {
348 	struct ip6_hdr *ip6;
349 	struct ifnet *ifp, *origifp;
350 	struct mbuf *m = m0;
351 	struct mbuf *mprev = NULL;
352 	int hlen, tlen, len;
353 	struct route_in6 ip6route;
354 	struct rtentry *rt = NULL;
355 	struct sockaddr_in6 *dst, src_sa, dst_sa;
356 	struct in6_addr odst;
357 	int error = 0;
358 	struct in6_ifaddr *ia = NULL;
359 	u_long mtu;
360 	int alwaysfrag, dontfrag;
361 	u_int32_t optlen = 0, plen = 0, unfragpartlen = 0;
362 	struct ip6_exthdrs exthdrs;
363 	struct in6_addr src0, dst0;
364 	u_int32_t zone;
365 	struct route_in6 *ro_pmtu = NULL;
366 	int hdrsplit = 0;
367 	int sw_csum, tso;
368 	int needfiblookup;
369 	uint32_t fibnum;
370 	struct m_tag *fwd_tag = NULL;
371 	uint32_t id;
372 
373 	if (inp != NULL) {
374 		INP_LOCK_ASSERT(inp);
375 		M_SETFIB(m, inp->inp_inc.inc_fibnum);
376 		if ((flags & IP_NODEFAULTFLOWID) == 0) {
377 			/* unconditionally set flowid */
378 			m->m_pkthdr.flowid = inp->inp_flowid;
379 			M_HASHTYPE_SET(m, inp->inp_flowtype);
380 		}
381 #ifdef NUMA
382 		m->m_pkthdr.numa_domain = inp->inp_numa_domain;
383 #endif
384 	}
385 
386 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
387 	/*
388 	 * IPSec checking which handles several cases.
389 	 * FAST IPSEC: We re-injected the packet.
390 	 * XXX: need scope argument.
391 	 */
392 	if (IPSEC_ENABLED(ipv6)) {
393 		if ((error = IPSEC_OUTPUT(ipv6, m, inp)) != 0) {
394 			if (error == EINPROGRESS)
395 				error = 0;
396 			goto done;
397 		}
398 	}
399 #endif /* IPSEC */
400 
401 	bzero(&exthdrs, sizeof(exthdrs));
402 	if (opt) {
403 		/* Hop-by-Hop options header */
404 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh);
405 		/* Destination options header(1st part) */
406 		if (opt->ip6po_rthdr) {
407 			/*
408 			 * Destination options header(1st part)
409 			 * This only makes sense with a routing header.
410 			 * See Section 9.2 of RFC 3542.
411 			 * Disabling this part just for MIP6 convenience is
412 			 * a bad idea.  We need to think carefully about a
413 			 * way to make the advanced API coexist with MIP6
414 			 * options, which might automatically be inserted in
415 			 * the kernel.
416 			 */
417 			MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1);
418 		}
419 		/* Routing header */
420 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr);
421 		/* Destination options header(2nd part) */
422 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2);
423 	}
424 
425 	/*
426 	 * Calculate the total length of the extension header chain.
427 	 * Keep the length of the unfragmentable part for fragmentation.
428 	 */
429 	optlen = 0;
430 	if (exthdrs.ip6e_hbh)
431 		optlen += exthdrs.ip6e_hbh->m_len;
432 	if (exthdrs.ip6e_dest1)
433 		optlen += exthdrs.ip6e_dest1->m_len;
434 	if (exthdrs.ip6e_rthdr)
435 		optlen += exthdrs.ip6e_rthdr->m_len;
436 	unfragpartlen = optlen + sizeof(struct ip6_hdr);
437 
438 	/* NOTE: we don't add AH/ESP length here (done in ip6_ipsec_output) */
439 	if (exthdrs.ip6e_dest2)
440 		optlen += exthdrs.ip6e_dest2->m_len;
441 
442 	/*
443 	 * If there is at least one extension header,
444 	 * separate IP6 header from the payload.
445 	 */
446 	if (optlen && !hdrsplit) {
447 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
448 			m = NULL;
449 			goto freehdrs;
450 		}
451 		m = exthdrs.ip6e_ip6;
452 		hdrsplit++;
453 	}
454 
455 	ip6 = mtod(m, struct ip6_hdr *);
456 
457 	/* adjust mbuf packet header length */
458 	m->m_pkthdr.len += optlen;
459 	plen = m->m_pkthdr.len - sizeof(*ip6);
460 
461 	/* If this is a jumbo payload, insert a jumbo payload option. */
462 	if (plen > IPV6_MAXPACKET) {
463 		if (!hdrsplit) {
464 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
465 				m = NULL;
466 				goto freehdrs;
467 			}
468 			m = exthdrs.ip6e_ip6;
469 			hdrsplit++;
470 		}
471 		/* adjust pointer */
472 		ip6 = mtod(m, struct ip6_hdr *);
473 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
474 			goto freehdrs;
475 		ip6->ip6_plen = 0;
476 	} else
477 		ip6->ip6_plen = htons(plen);
478 
479 	/*
480 	 * Concatenate headers and fill in next header fields.
481 	 * Here we have, on "m"
482 	 *	IPv6 payload
483 	 * and we insert headers accordingly.  Finally, we should be getting:
484 	 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload]
485 	 *
486 	 * during the header composing process, "m" points to IPv6 header.
487 	 * "mprev" points to an extension header prior to esp.
488 	 */
489 	u_char *nexthdrp = &ip6->ip6_nxt;
490 	mprev = m;
491 
492 	/*
493 	 * we treat dest2 specially.  this makes IPsec processing
494 	 * much easier.  the goal here is to make mprev point the
495 	 * mbuf prior to dest2.
496 	 *
497 	 * result: IPv6 dest2 payload
498 	 * m and mprev will point to IPv6 header.
499 	 */
500 	if (exthdrs.ip6e_dest2) {
501 		if (!hdrsplit)
502 			panic("assumption failed: hdr not split");
503 		exthdrs.ip6e_dest2->m_next = m->m_next;
504 		m->m_next = exthdrs.ip6e_dest2;
505 		*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
506 		ip6->ip6_nxt = IPPROTO_DSTOPTS;
507 	}
508 
509 	/*
510 	 * result: IPv6 hbh dest1 rthdr dest2 payload
511 	 * m will point to IPv6 header.  mprev will point to the
512 	 * extension header prior to dest2 (rthdr in the above case).
513 	 */
514 	MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
515 	MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
516 		   IPPROTO_DSTOPTS);
517 	MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
518 		   IPPROTO_ROUTING);
519 
520 	/*
521 	 * If there is a routing header, discard the packet.
522 	 */
523 	if (exthdrs.ip6e_rthdr) {
524 		 error = EINVAL;
525 		 goto bad;
526 	}
527 
528 	/* Source address validation */
529 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
530 	    (flags & IPV6_UNSPECSRC) == 0) {
531 		error = EOPNOTSUPP;
532 		IP6STAT_INC(ip6s_badscope);
533 		goto bad;
534 	}
535 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
536 		error = EOPNOTSUPP;
537 		IP6STAT_INC(ip6s_badscope);
538 		goto bad;
539 	}
540 
541 	IP6STAT_INC(ip6s_localout);
542 
543 	/*
544 	 * Route packet.
545 	 */
546 	if (ro == NULL) {
547 		ro = &ip6route;
548 		bzero((caddr_t)ro, sizeof(*ro));
549 	}
550 	ro_pmtu = ro;
551 	if (opt && opt->ip6po_rthdr)
552 		ro = &opt->ip6po_route;
553 	dst = (struct sockaddr_in6 *)&ro->ro_dst;
554 	fibnum = (inp != NULL) ? inp->inp_inc.inc_fibnum : M_GETFIB(m);
555 again:
556 	/*
557 	 * if specified, try to fill in the traffic class field.
558 	 * do not override if a non-zero value is already set.
559 	 * we check the diffserv field and the ecn field separately.
560 	 */
561 	if (opt && opt->ip6po_tclass >= 0) {
562 		int mask = 0;
563 
564 		if ((ip6->ip6_flow & htonl(0xfc << 20)) == 0)
565 			mask |= 0xfc;
566 		if ((ip6->ip6_flow & htonl(0x03 << 20)) == 0)
567 			mask |= 0x03;
568 		if (mask != 0)
569 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
570 	}
571 
572 	/* fill in or override the hop limit field, if necessary. */
573 	if (opt && opt->ip6po_hlim != -1)
574 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
575 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
576 		if (im6o != NULL)
577 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
578 		else
579 			ip6->ip6_hlim = V_ip6_defmcasthlim;
580 	}
581 	/*
582 	 * Validate route against routing table additions;
583 	 * a better/more specific route might have been added.
584 	 * Make sure address family is set in route.
585 	 */
586 	if (inp) {
587 		ro->ro_dst.sin6_family = AF_INET6;
588 		RT_VALIDATE((struct route *)ro, &inp->inp_rt_cookie, fibnum);
589 	}
590 	if (ro->ro_rt && fwd_tag == NULL && (ro->ro_rt->rt_flags & RTF_UP) &&
591 	    ro->ro_dst.sin6_family == AF_INET6 &&
592 	    IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &ip6->ip6_dst)) {
593 		rt = ro->ro_rt;
594 		ifp = ro->ro_rt->rt_ifp;
595 	} else {
596 		if (ro->ro_lle)
597 			LLE_FREE(ro->ro_lle);	/* zeros ro_lle */
598 		ro->ro_lle = NULL;
599 		if (fwd_tag == NULL) {
600 			bzero(&dst_sa, sizeof(dst_sa));
601 			dst_sa.sin6_family = AF_INET6;
602 			dst_sa.sin6_len = sizeof(dst_sa);
603 			dst_sa.sin6_addr = ip6->ip6_dst;
604 		}
605 		error = in6_selectroute_fib(&dst_sa, opt, im6o, ro, &ifp,
606 		    &rt, fibnum);
607 		if (error != 0) {
608 			if (ifp != NULL)
609 				in6_ifstat_inc(ifp, ifs6_out_discard);
610 			goto bad;
611 		}
612 	}
613 	if (rt == NULL) {
614 		/*
615 		 * If in6_selectroute() does not return a route entry,
616 		 * dst may not have been updated.
617 		 */
618 		*dst = dst_sa;	/* XXX */
619 	}
620 
621 	/*
622 	 * then rt (for unicast) and ifp must be non-NULL valid values.
623 	 */
624 	if ((flags & IPV6_FORWARDING) == 0) {
625 		/* XXX: the FORWARDING flag can be set for mrouting. */
626 		in6_ifstat_inc(ifp, ifs6_out_request);
627 	}
628 	if (rt != NULL) {
629 		ia = (struct in6_ifaddr *)(rt->rt_ifa);
630 		counter_u64_add(rt->rt_pksent, 1);
631 	}
632 
633 	/* Setup data structures for scope ID checks. */
634 	src0 = ip6->ip6_src;
635 	bzero(&src_sa, sizeof(src_sa));
636 	src_sa.sin6_family = AF_INET6;
637 	src_sa.sin6_len = sizeof(src_sa);
638 	src_sa.sin6_addr = ip6->ip6_src;
639 
640 	dst0 = ip6->ip6_dst;
641 	/* re-initialize to be sure */
642 	bzero(&dst_sa, sizeof(dst_sa));
643 	dst_sa.sin6_family = AF_INET6;
644 	dst_sa.sin6_len = sizeof(dst_sa);
645 	dst_sa.sin6_addr = ip6->ip6_dst;
646 
647 	/* Check for valid scope ID. */
648 	if (in6_setscope(&src0, ifp, &zone) == 0 &&
649 	    sa6_recoverscope(&src_sa) == 0 && zone == src_sa.sin6_scope_id &&
650 	    in6_setscope(&dst0, ifp, &zone) == 0 &&
651 	    sa6_recoverscope(&dst_sa) == 0 && zone == dst_sa.sin6_scope_id) {
652 		/*
653 		 * The outgoing interface is in the zone of the source
654 		 * and destination addresses.
655 		 *
656 		 * Because the loopback interface cannot receive
657 		 * packets with a different scope ID than its own,
658 		 * there is a trick is to pretend the outgoing packet
659 		 * was received by the real network interface, by
660 		 * setting "origifp" different from "ifp". This is
661 		 * only allowed when "ifp" is a loopback network
662 		 * interface. Refer to code in nd6_output_ifp() for
663 		 * more details.
664 		 */
665 		origifp = ifp;
666 
667 		/*
668 		 * We should use ia_ifp to support the case of sending
669 		 * packets to an address of our own.
670 		 */
671 		if (ia != NULL && ia->ia_ifp)
672 			ifp = ia->ia_ifp;
673 
674 	} else if ((ifp->if_flags & IFF_LOOPBACK) == 0 ||
675 	    sa6_recoverscope(&src_sa) != 0 ||
676 	    sa6_recoverscope(&dst_sa) != 0 ||
677 	    dst_sa.sin6_scope_id == 0 ||
678 	    (src_sa.sin6_scope_id != 0 &&
679 	    src_sa.sin6_scope_id != dst_sa.sin6_scope_id) ||
680 	    (origifp = ifnet_byindex(dst_sa.sin6_scope_id)) == NULL) {
681 		/*
682 		 * If the destination network interface is not a
683 		 * loopback interface, or the destination network
684 		 * address has no scope ID, or the source address has
685 		 * a scope ID set which is different from the
686 		 * destination address one, or there is no network
687 		 * interface representing this scope ID, the address
688 		 * pair is considered invalid.
689 		 */
690 		IP6STAT_INC(ip6s_badscope);
691 		in6_ifstat_inc(ifp, ifs6_out_discard);
692 		if (error == 0)
693 			error = EHOSTUNREACH; /* XXX */
694 		goto bad;
695 	}
696 
697 	/* All scope ID checks are successful. */
698 
699 	if (rt && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
700 		if (opt && opt->ip6po_nextroute.ro_rt) {
701 			/*
702 			 * The nexthop is explicitly specified by the
703 			 * application.  We assume the next hop is an IPv6
704 			 * address.
705 			 */
706 			dst = (struct sockaddr_in6 *)opt->ip6po_nexthop;
707 		}
708 		else if ((rt->rt_flags & RTF_GATEWAY))
709 			dst = (struct sockaddr_in6 *)rt->rt_gateway;
710 	}
711 
712 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
713 		m->m_flags &= ~(M_BCAST | M_MCAST); /* just in case */
714 	} else {
715 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
716 		in6_ifstat_inc(ifp, ifs6_out_mcast);
717 		/*
718 		 * Confirm that the outgoing interface supports multicast.
719 		 */
720 		if (!(ifp->if_flags & IFF_MULTICAST)) {
721 			IP6STAT_INC(ip6s_noroute);
722 			in6_ifstat_inc(ifp, ifs6_out_discard);
723 			error = ENETUNREACH;
724 			goto bad;
725 		}
726 		if ((im6o == NULL && in6_mcast_loop) ||
727 		    (im6o && im6o->im6o_multicast_loop)) {
728 			/*
729 			 * Loop back multicast datagram if not expressly
730 			 * forbidden to do so, even if we have not joined
731 			 * the address; protocols will filter it later,
732 			 * thus deferring a hash lookup and lock acquisition
733 			 * at the expense of an m_copym().
734 			 */
735 			ip6_mloopback(ifp, m);
736 		} else {
737 			/*
738 			 * If we are acting as a multicast router, perform
739 			 * multicast forwarding as if the packet had just
740 			 * arrived on the interface to which we are about
741 			 * to send.  The multicast forwarding function
742 			 * recursively calls this function, using the
743 			 * IPV6_FORWARDING flag to prevent infinite recursion.
744 			 *
745 			 * Multicasts that are looped back by ip6_mloopback(),
746 			 * above, will be forwarded by the ip6_input() routine,
747 			 * if necessary.
748 			 */
749 			if (V_ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
750 				/*
751 				 * XXX: ip6_mforward expects that rcvif is NULL
752 				 * when it is called from the originating path.
753 				 * However, it may not always be the case.
754 				 */
755 				m->m_pkthdr.rcvif = NULL;
756 				if (ip6_mforward(ip6, ifp, m) != 0) {
757 					m_freem(m);
758 					goto done;
759 				}
760 			}
761 		}
762 		/*
763 		 * Multicasts with a hoplimit of zero may be looped back,
764 		 * above, but must not be transmitted on a network.
765 		 * Also, multicasts addressed to the loopback interface
766 		 * are not sent -- the above call to ip6_mloopback() will
767 		 * loop back a copy if this host actually belongs to the
768 		 * destination group on the loopback interface.
769 		 */
770 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
771 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
772 			m_freem(m);
773 			goto done;
774 		}
775 	}
776 
777 	/*
778 	 * Fill the outgoing inteface to tell the upper layer
779 	 * to increment per-interface statistics.
780 	 */
781 	if (ifpp)
782 		*ifpp = ifp;
783 
784 	/* Determine path MTU. */
785 	if ((error = ip6_getpmtu(ro_pmtu, ro != ro_pmtu, ifp, &ip6->ip6_dst,
786 		    &mtu, &alwaysfrag, fibnum, *nexthdrp)) != 0)
787 		goto bad;
788 
789 	/*
790 	 * The caller of this function may specify to use the minimum MTU
791 	 * in some cases.
792 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
793 	 * setting.  The logic is a bit complicated; by default, unicast
794 	 * packets will follow path MTU while multicast packets will be sent at
795 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
796 	 * including unicast ones will be sent at the minimum MTU.  Multicast
797 	 * packets will always be sent at the minimum MTU unless
798 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
799 	 * See RFC 3542 for more details.
800 	 */
801 	if (mtu > IPV6_MMTU) {
802 		if ((flags & IPV6_MINMTU))
803 			mtu = IPV6_MMTU;
804 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
805 			mtu = IPV6_MMTU;
806 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
807 			 (opt == NULL ||
808 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
809 			mtu = IPV6_MMTU;
810 		}
811 	}
812 
813 	/*
814 	 * clear embedded scope identifiers if necessary.
815 	 * in6_clearscope will touch the addresses only when necessary.
816 	 */
817 	in6_clearscope(&ip6->ip6_src);
818 	in6_clearscope(&ip6->ip6_dst);
819 
820 	/*
821 	 * If the outgoing packet contains a hop-by-hop options header,
822 	 * it must be examined and processed even by the source node.
823 	 * (RFC 2460, section 4.)
824 	 */
825 	if (exthdrs.ip6e_hbh) {
826 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
827 		u_int32_t dummy; /* XXX unused */
828 		u_int32_t plen = 0; /* XXX: ip6_process will check the value */
829 
830 #ifdef DIAGNOSTIC
831 		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
832 			panic("ip6e_hbh is not contiguous");
833 #endif
834 		/*
835 		 *  XXX: if we have to send an ICMPv6 error to the sender,
836 		 *       we need the M_LOOP flag since icmp6_error() expects
837 		 *       the IPv6 and the hop-by-hop options header are
838 		 *       contiguous unless the flag is set.
839 		 */
840 		m->m_flags |= M_LOOP;
841 		m->m_pkthdr.rcvif = ifp;
842 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
843 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
844 		    &dummy, &plen) < 0) {
845 			/* m was already freed at this point */
846 			error = EINVAL;/* better error? */
847 			goto done;
848 		}
849 		m->m_flags &= ~M_LOOP; /* XXX */
850 		m->m_pkthdr.rcvif = NULL;
851 	}
852 
853 	/* Jump over all PFIL processing if hooks are not active. */
854 	if (!PFIL_HOOKED_OUT(V_inet6_pfil_head))
855 		goto passout;
856 
857 	odst = ip6->ip6_dst;
858 	/* Run through list of hooks for output packets. */
859 	switch (pfil_run_hooks(V_inet6_pfil_head, &m, ifp, PFIL_OUT, inp)) {
860 	case PFIL_PASS:
861 		ip6 = mtod(m, struct ip6_hdr *);
862 		break;
863 	case PFIL_DROPPED:
864 		error = EPERM;
865 		/* FALLTHROUGH */
866 	case PFIL_CONSUMED:
867 		goto done;
868 	}
869 
870 	needfiblookup = 0;
871 	/* See if destination IP address was changed by packet filter. */
872 	if (!IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst)) {
873 		m->m_flags |= M_SKIP_FIREWALL;
874 		/* If destination is now ourself drop to ip6_input(). */
875 		if (in6_localip(&ip6->ip6_dst)) {
876 			m->m_flags |= M_FASTFWD_OURS;
877 			if (m->m_pkthdr.rcvif == NULL)
878 				m->m_pkthdr.rcvif = V_loif;
879 			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
880 				m->m_pkthdr.csum_flags |=
881 				    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
882 				m->m_pkthdr.csum_data = 0xffff;
883 			}
884 #ifdef SCTP
885 			if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
886 				m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
887 #endif
888 			error = netisr_queue(NETISR_IPV6, m);
889 			goto done;
890 		} else {
891 			RO_INVALIDATE_CACHE(ro);
892 			needfiblookup = 1; /* Redo the routing table lookup. */
893 		}
894 	}
895 	/* See if fib was changed by packet filter. */
896 	if (fibnum != M_GETFIB(m)) {
897 		m->m_flags |= M_SKIP_FIREWALL;
898 		fibnum = M_GETFIB(m);
899 		RO_INVALIDATE_CACHE(ro);
900 		needfiblookup = 1;
901 	}
902 	if (needfiblookup)
903 		goto again;
904 
905 	/* See if local, if yes, send it to netisr. */
906 	if (m->m_flags & M_FASTFWD_OURS) {
907 		if (m->m_pkthdr.rcvif == NULL)
908 			m->m_pkthdr.rcvif = V_loif;
909 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
910 			m->m_pkthdr.csum_flags |=
911 			    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
912 			m->m_pkthdr.csum_data = 0xffff;
913 		}
914 #ifdef SCTP
915 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
916 			m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
917 #endif
918 		error = netisr_queue(NETISR_IPV6, m);
919 		goto done;
920 	}
921 	/* Or forward to some other address? */
922 	if ((m->m_flags & M_IP6_NEXTHOP) &&
923 	    (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
924 		dst = (struct sockaddr_in6 *)&ro->ro_dst;
925 		bcopy((fwd_tag+1), &dst_sa, sizeof(struct sockaddr_in6));
926 		m->m_flags |= M_SKIP_FIREWALL;
927 		m->m_flags &= ~M_IP6_NEXTHOP;
928 		m_tag_delete(m, fwd_tag);
929 		goto again;
930 	}
931 
932 passout:
933 	/*
934 	 * Send the packet to the outgoing interface.
935 	 * If necessary, do IPv6 fragmentation before sending.
936 	 *
937 	 * the logic here is rather complex:
938 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
939 	 * 1-a:	send as is if tlen <= path mtu
940 	 * 1-b:	fragment if tlen > path mtu
941 	 *
942 	 * 2: if user asks us not to fragment (dontfrag == 1)
943 	 * 2-a:	send as is if tlen <= interface mtu
944 	 * 2-b:	error if tlen > interface mtu
945 	 *
946 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
947 	 *	always fragment
948 	 *
949 	 * 4: if dontfrag == 1 && alwaysfrag == 1
950 	 *	error, as we cannot handle this conflicting request
951 	 */
952 	sw_csum = m->m_pkthdr.csum_flags;
953 	if (!hdrsplit) {
954 		tso = ((sw_csum & ifp->if_hwassist & CSUM_TSO) != 0) ? 1 : 0;
955 		sw_csum &= ~ifp->if_hwassist;
956 	} else
957 		tso = 0;
958 	/*
959 	 * If we added extension headers, we will not do TSO and calculate the
960 	 * checksums ourselves for now.
961 	 * XXX-BZ  Need a framework to know when the NIC can handle it, even
962 	 * with ext. hdrs.
963 	 */
964 	if (sw_csum & CSUM_DELAY_DATA_IPV6) {
965 		sw_csum &= ~CSUM_DELAY_DATA_IPV6;
966 		m = mb_unmapped_to_ext(m);
967 		if (m == NULL) {
968 			error = ENOBUFS;
969 			IP6STAT_INC(ip6s_odropped);
970 			goto bad;
971 		}
972 		in6_delayed_cksum(m, plen, sizeof(struct ip6_hdr));
973 	} else if ((ifp->if_capenable & IFCAP_NOMAP) == 0) {
974 		m = mb_unmapped_to_ext(m);
975 		if (m == NULL) {
976 			error = ENOBUFS;
977 			IP6STAT_INC(ip6s_odropped);
978 			goto bad;
979 		}
980 	}
981 #ifdef SCTP
982 	if (sw_csum & CSUM_SCTP_IPV6) {
983 		sw_csum &= ~CSUM_SCTP_IPV6;
984 		m = mb_unmapped_to_ext(m);
985 		if (m == NULL) {
986 			error = ENOBUFS;
987 			IP6STAT_INC(ip6s_odropped);
988 			goto bad;
989 		}
990 		sctp_delayed_cksum(m, sizeof(struct ip6_hdr));
991 	}
992 #endif
993 	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
994 	tlen = m->m_pkthdr.len;
995 
996 	if ((opt && (opt->ip6po_flags & IP6PO_DONTFRAG)) || tso)
997 		dontfrag = 1;
998 	else
999 		dontfrag = 0;
1000 	if (dontfrag && alwaysfrag) {	/* case 4 */
1001 		/* conflicting request - can't transmit */
1002 		error = EMSGSIZE;
1003 		goto bad;
1004 	}
1005 	if (dontfrag && tlen > IN6_LINKMTU(ifp) && !tso) {	/* case 2-b */
1006 		/*
1007 		 * Even if the DONTFRAG option is specified, we cannot send the
1008 		 * packet when the data length is larger than the MTU of the
1009 		 * outgoing interface.
1010 		 * Notify the error by sending IPV6_PATHMTU ancillary data if
1011 		 * application wanted to know the MTU value. Also return an
1012 		 * error code (this is not described in the API spec).
1013 		 */
1014 		if (inp != NULL)
1015 			ip6_notify_pmtu(inp, &dst_sa, (u_int32_t)mtu);
1016 		error = EMSGSIZE;
1017 		goto bad;
1018 	}
1019 
1020 	/*
1021 	 * transmit packet without fragmentation
1022 	 */
1023 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* case 1-a and 2-a */
1024 		struct in6_ifaddr *ia6;
1025 
1026 		ip6 = mtod(m, struct ip6_hdr *);
1027 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
1028 		if (ia6) {
1029 			/* Record statistics for this interface address. */
1030 			counter_u64_add(ia6->ia_ifa.ifa_opackets, 1);
1031 			counter_u64_add(ia6->ia_ifa.ifa_obytes,
1032 			    m->m_pkthdr.len);
1033 			ifa_free(&ia6->ia_ifa);
1034 		}
1035 		error = ip6_output_send(inp, ifp, origifp, m, dst, ro);
1036 		goto done;
1037 	}
1038 
1039 	/*
1040 	 * try to fragment the packet.  case 1-b and 3
1041 	 */
1042 	if (mtu < IPV6_MMTU) {
1043 		/* path MTU cannot be less than IPV6_MMTU */
1044 		error = EMSGSIZE;
1045 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1046 		goto bad;
1047 	} else if (ip6->ip6_plen == 0) {
1048 		/* jumbo payload cannot be fragmented */
1049 		error = EMSGSIZE;
1050 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1051 		goto bad;
1052 	} else {
1053 		u_char nextproto;
1054 
1055 		/*
1056 		 * Too large for the destination or interface;
1057 		 * fragment if possible.
1058 		 * Must be able to put at least 8 bytes per fragment.
1059 		 */
1060 		hlen = unfragpartlen;
1061 		if (mtu > IPV6_MAXPACKET)
1062 			mtu = IPV6_MAXPACKET;
1063 
1064 		len = (mtu - hlen - sizeof(struct ip6_frag)) & ~7;
1065 		if (len < 8) {
1066 			error = EMSGSIZE;
1067 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
1068 			goto bad;
1069 		}
1070 
1071 		/*
1072 		 * If the interface will not calculate checksums on
1073 		 * fragmented packets, then do it here.
1074 		 * XXX-BZ handle the hw offloading case.  Need flags.
1075 		 */
1076 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
1077 			m = mb_unmapped_to_ext(m);
1078 			if (m == NULL) {
1079 				in6_ifstat_inc(ifp, ifs6_out_fragfail);
1080 				error = ENOBUFS;
1081 				goto bad;
1082 			}
1083 			in6_delayed_cksum(m, plen, hlen);
1084 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
1085 		}
1086 #ifdef SCTP
1087 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6) {
1088 			m = mb_unmapped_to_ext(m);
1089 			if (m == NULL) {
1090 				in6_ifstat_inc(ifp, ifs6_out_fragfail);
1091 				error = ENOBUFS;
1092 				goto bad;
1093 			}
1094 			sctp_delayed_cksum(m, hlen);
1095 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
1096 		}
1097 #endif
1098 		/*
1099 		 * Change the next header field of the last header in the
1100 		 * unfragmentable part.
1101 		 */
1102 		if (exthdrs.ip6e_rthdr) {
1103 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
1104 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
1105 		} else if (exthdrs.ip6e_dest1) {
1106 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
1107 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
1108 		} else if (exthdrs.ip6e_hbh) {
1109 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
1110 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
1111 		} else {
1112 			nextproto = ip6->ip6_nxt;
1113 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1114 		}
1115 
1116 		/*
1117 		 * Loop through length of segment after first fragment,
1118 		 * make new header and copy data of each part and link onto
1119 		 * chain.
1120 		 */
1121 		m0 = m;
1122 		id = htonl(ip6_randomid());
1123 		if ((error = ip6_fragment(ifp, m, hlen, nextproto, len, id)))
1124 			goto sendorfree;
1125 
1126 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1127 	}
1128 
1129 	/*
1130 	 * Remove leading garbages.
1131 	 */
1132 sendorfree:
1133 	m = m0->m_nextpkt;
1134 	m0->m_nextpkt = 0;
1135 	m_freem(m0);
1136 	for (; m; m = m0) {
1137 		m0 = m->m_nextpkt;
1138 		m->m_nextpkt = 0;
1139 		if (error == 0) {
1140 			/* Record statistics for this interface address. */
1141 			if (ia) {
1142 				counter_u64_add(ia->ia_ifa.ifa_opackets, 1);
1143 				counter_u64_add(ia->ia_ifa.ifa_obytes,
1144 				    m->m_pkthdr.len);
1145 			}
1146 			error = ip6_output_send(inp, ifp, origifp, m, dst, ro);
1147 		} else
1148 			m_freem(m);
1149 	}
1150 
1151 	if (error == 0)
1152 		IP6STAT_INC(ip6s_fragmented);
1153 
1154 done:
1155 	if (ro == &ip6route)
1156 		RO_RTFREE(ro);
1157 	return (error);
1158 
1159 freehdrs:
1160 	m_freem(exthdrs.ip6e_hbh);	/* m_freem will check if mbuf is 0 */
1161 	m_freem(exthdrs.ip6e_dest1);
1162 	m_freem(exthdrs.ip6e_rthdr);
1163 	m_freem(exthdrs.ip6e_dest2);
1164 	/* FALLTHROUGH */
1165 bad:
1166 	if (m)
1167 		m_freem(m);
1168 	goto done;
1169 }
1170 
1171 static int
1172 ip6_copyexthdr(struct mbuf **mp, caddr_t hdr, int hlen)
1173 {
1174 	struct mbuf *m;
1175 
1176 	if (hlen > MCLBYTES)
1177 		return (ENOBUFS); /* XXX */
1178 
1179 	if (hlen > MLEN)
1180 		m = m_getcl(M_NOWAIT, MT_DATA, 0);
1181 	else
1182 		m = m_get(M_NOWAIT, MT_DATA);
1183 	if (m == NULL)
1184 		return (ENOBUFS);
1185 	m->m_len = hlen;
1186 	if (hdr)
1187 		bcopy(hdr, mtod(m, caddr_t), hlen);
1188 
1189 	*mp = m;
1190 	return (0);
1191 }
1192 
1193 /*
1194  * Insert jumbo payload option.
1195  */
1196 static int
1197 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
1198 {
1199 	struct mbuf *mopt;
1200 	u_char *optbuf;
1201 	u_int32_t v;
1202 
1203 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1204 
1205 	/*
1206 	 * If there is no hop-by-hop options header, allocate new one.
1207 	 * If there is one but it doesn't have enough space to store the
1208 	 * jumbo payload option, allocate a cluster to store the whole options.
1209 	 * Otherwise, use it to store the options.
1210 	 */
1211 	if (exthdrs->ip6e_hbh == NULL) {
1212 		mopt = m_get(M_NOWAIT, MT_DATA);
1213 		if (mopt == NULL)
1214 			return (ENOBUFS);
1215 		mopt->m_len = JUMBOOPTLEN;
1216 		optbuf = mtod(mopt, u_char *);
1217 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1218 		exthdrs->ip6e_hbh = mopt;
1219 	} else {
1220 		struct ip6_hbh *hbh;
1221 
1222 		mopt = exthdrs->ip6e_hbh;
1223 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1224 			/*
1225 			 * XXX assumption:
1226 			 * - exthdrs->ip6e_hbh is not referenced from places
1227 			 *   other than exthdrs.
1228 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1229 			 */
1230 			int oldoptlen = mopt->m_len;
1231 			struct mbuf *n;
1232 
1233 			/*
1234 			 * XXX: give up if the whole (new) hbh header does
1235 			 * not fit even in an mbuf cluster.
1236 			 */
1237 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1238 				return (ENOBUFS);
1239 
1240 			/*
1241 			 * As a consequence, we must always prepare a cluster
1242 			 * at this point.
1243 			 */
1244 			n = m_getcl(M_NOWAIT, MT_DATA, 0);
1245 			if (n == NULL)
1246 				return (ENOBUFS);
1247 			n->m_len = oldoptlen + JUMBOOPTLEN;
1248 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1249 			    oldoptlen);
1250 			optbuf = mtod(n, caddr_t) + oldoptlen;
1251 			m_freem(mopt);
1252 			mopt = exthdrs->ip6e_hbh = n;
1253 		} else {
1254 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1255 			mopt->m_len += JUMBOOPTLEN;
1256 		}
1257 		optbuf[0] = IP6OPT_PADN;
1258 		optbuf[1] = 1;
1259 
1260 		/*
1261 		 * Adjust the header length according to the pad and
1262 		 * the jumbo payload option.
1263 		 */
1264 		hbh = mtod(mopt, struct ip6_hbh *);
1265 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1266 	}
1267 
1268 	/* fill in the option. */
1269 	optbuf[2] = IP6OPT_JUMBO;
1270 	optbuf[3] = 4;
1271 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1272 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1273 
1274 	/* finally, adjust the packet header length */
1275 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1276 
1277 	return (0);
1278 #undef JUMBOOPTLEN
1279 }
1280 
1281 /*
1282  * Insert fragment header and copy unfragmentable header portions.
1283  */
1284 static int
1285 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
1286     struct ip6_frag **frghdrp)
1287 {
1288 	struct mbuf *n, *mlast;
1289 
1290 	if (hlen > sizeof(struct ip6_hdr)) {
1291 		n = m_copym(m0, sizeof(struct ip6_hdr),
1292 		    hlen - sizeof(struct ip6_hdr), M_NOWAIT);
1293 		if (n == NULL)
1294 			return (ENOBUFS);
1295 		m->m_next = n;
1296 	} else
1297 		n = m;
1298 
1299 	/* Search for the last mbuf of unfragmentable part. */
1300 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1301 		;
1302 
1303 	if (M_WRITABLE(mlast) &&
1304 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1305 		/* use the trailing space of the last mbuf for the fragment hdr */
1306 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1307 		    mlast->m_len);
1308 		mlast->m_len += sizeof(struct ip6_frag);
1309 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1310 	} else {
1311 		/* allocate a new mbuf for the fragment header */
1312 		struct mbuf *mfrg;
1313 
1314 		mfrg = m_get(M_NOWAIT, MT_DATA);
1315 		if (mfrg == NULL)
1316 			return (ENOBUFS);
1317 		mfrg->m_len = sizeof(struct ip6_frag);
1318 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1319 		mlast->m_next = mfrg;
1320 	}
1321 
1322 	return (0);
1323 }
1324 
1325 /*
1326  * Calculates IPv6 path mtu for destination @dst.
1327  * Resulting MTU is stored in @mtup.
1328  *
1329  * Returns 0 on success.
1330  */
1331 static int
1332 ip6_getpmtu_ctl(u_int fibnum, const struct in6_addr *dst, u_long *mtup)
1333 {
1334 	struct nhop6_extended nh6;
1335 	struct in6_addr kdst;
1336 	uint32_t scopeid;
1337 	struct ifnet *ifp;
1338 	u_long mtu;
1339 	int error;
1340 
1341 	in6_splitscope(dst, &kdst, &scopeid);
1342 	if (fib6_lookup_nh_ext(fibnum, &kdst, scopeid, NHR_REF, 0, &nh6) != 0)
1343 		return (EHOSTUNREACH);
1344 
1345 	ifp = nh6.nh_ifp;
1346 	mtu = nh6.nh_mtu;
1347 
1348 	error = ip6_calcmtu(ifp, dst, mtu, mtup, NULL, 0);
1349 	fib6_free_nh_ext(fibnum, &nh6);
1350 
1351 	return (error);
1352 }
1353 
1354 /*
1355  * Calculates IPv6 path MTU for @dst based on transmit @ifp,
1356  * and cached data in @ro_pmtu.
1357  * MTU from (successful) route lookup is saved (along with dst)
1358  * inside @ro_pmtu to avoid subsequent route lookups after packet
1359  * filter processing.
1360  *
1361  * Stores mtu and always-frag value into @mtup and @alwaysfragp.
1362  * Returns 0 on success.
1363  */
1364 static int
1365 ip6_getpmtu(struct route_in6 *ro_pmtu, int do_lookup,
1366     struct ifnet *ifp, const struct in6_addr *dst, u_long *mtup,
1367     int *alwaysfragp, u_int fibnum, u_int proto)
1368 {
1369 	struct nhop6_basic nh6;
1370 	struct in6_addr kdst;
1371 	uint32_t scopeid;
1372 	struct sockaddr_in6 *sa6_dst;
1373 	u_long mtu;
1374 
1375 	mtu = 0;
1376 	if (do_lookup) {
1377 
1378 		/*
1379 		 * Here ro_pmtu has final destination address, while
1380 		 * ro might represent immediate destination.
1381 		 * Use ro_pmtu destination since mtu might differ.
1382 		 */
1383 		sa6_dst = (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1384 		if (!IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))
1385 			ro_pmtu->ro_mtu = 0;
1386 
1387 		if (ro_pmtu->ro_mtu == 0) {
1388 			bzero(sa6_dst, sizeof(*sa6_dst));
1389 			sa6_dst->sin6_family = AF_INET6;
1390 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1391 			sa6_dst->sin6_addr = *dst;
1392 
1393 			in6_splitscope(dst, &kdst, &scopeid);
1394 			if (fib6_lookup_nh_basic(fibnum, &kdst, scopeid, 0, 0,
1395 			    &nh6) == 0)
1396 				ro_pmtu->ro_mtu = nh6.nh_mtu;
1397 		}
1398 
1399 		mtu = ro_pmtu->ro_mtu;
1400 	}
1401 
1402 	if (ro_pmtu->ro_rt)
1403 		mtu = ro_pmtu->ro_rt->rt_mtu;
1404 
1405 	return (ip6_calcmtu(ifp, dst, mtu, mtup, alwaysfragp, proto));
1406 }
1407 
1408 /*
1409  * Calculate MTU based on transmit @ifp, route mtu @rt_mtu and
1410  * hostcache data for @dst.
1411  * Stores mtu and always-frag value into @mtup and @alwaysfragp.
1412  *
1413  * Returns 0 on success.
1414  */
1415 static int
1416 ip6_calcmtu(struct ifnet *ifp, const struct in6_addr *dst, u_long rt_mtu,
1417     u_long *mtup, int *alwaysfragp, u_int proto)
1418 {
1419 	u_long mtu = 0;
1420 	int alwaysfrag = 0;
1421 	int error = 0;
1422 
1423 	if (rt_mtu > 0) {
1424 		u_int32_t ifmtu;
1425 		struct in_conninfo inc;
1426 
1427 		bzero(&inc, sizeof(inc));
1428 		inc.inc_flags |= INC_ISIPV6;
1429 		inc.inc6_faddr = *dst;
1430 
1431 		ifmtu = IN6_LINKMTU(ifp);
1432 
1433 		/* TCP is known to react to pmtu changes so skip hc */
1434 		if (proto != IPPROTO_TCP)
1435 			mtu = tcp_hc_getmtu(&inc);
1436 
1437 		if (mtu)
1438 			mtu = min(mtu, rt_mtu);
1439 		else
1440 			mtu = rt_mtu;
1441 		if (mtu == 0)
1442 			mtu = ifmtu;
1443 		else if (mtu < IPV6_MMTU) {
1444 			/*
1445 			 * RFC2460 section 5, last paragraph:
1446 			 * if we record ICMPv6 too big message with
1447 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
1448 			 * or smaller, with framgent header attached.
1449 			 * (fragment header is needed regardless from the
1450 			 * packet size, for translators to identify packets)
1451 			 */
1452 			alwaysfrag = 1;
1453 			mtu = IPV6_MMTU;
1454 		}
1455 	} else if (ifp) {
1456 		mtu = IN6_LINKMTU(ifp);
1457 	} else
1458 		error = EHOSTUNREACH; /* XXX */
1459 
1460 	*mtup = mtu;
1461 	if (alwaysfragp)
1462 		*alwaysfragp = alwaysfrag;
1463 	return (error);
1464 }
1465 
1466 /*
1467  * IP6 socket option processing.
1468  */
1469 int
1470 ip6_ctloutput(struct socket *so, struct sockopt *sopt)
1471 {
1472 	int optdatalen, uproto;
1473 	void *optdata;
1474 	struct inpcb *inp = sotoinpcb(so);
1475 	int error, optval;
1476 	int level, op, optname;
1477 	int optlen;
1478 	struct thread *td;
1479 #ifdef	RSS
1480 	uint32_t rss_bucket;
1481 	int retval;
1482 #endif
1483 
1484 /*
1485  * Don't use more than a quarter of mbuf clusters.  N.B.:
1486  * nmbclusters is an int, but nmbclusters * MCLBYTES may overflow
1487  * on LP64 architectures, so cast to u_long to avoid undefined
1488  * behavior.  ILP32 architectures cannot have nmbclusters
1489  * large enough to overflow for other reasons.
1490  */
1491 #define IPV6_PKTOPTIONS_MBUF_LIMIT	((u_long)nmbclusters * MCLBYTES / 4)
1492 
1493 	level = sopt->sopt_level;
1494 	op = sopt->sopt_dir;
1495 	optname = sopt->sopt_name;
1496 	optlen = sopt->sopt_valsize;
1497 	td = sopt->sopt_td;
1498 	error = 0;
1499 	optval = 0;
1500 	uproto = (int)so->so_proto->pr_protocol;
1501 
1502 	if (level != IPPROTO_IPV6) {
1503 		error = EINVAL;
1504 
1505 		if (sopt->sopt_level == SOL_SOCKET &&
1506 		    sopt->sopt_dir == SOPT_SET) {
1507 			switch (sopt->sopt_name) {
1508 			case SO_REUSEADDR:
1509 				INP_WLOCK(inp);
1510 				if ((so->so_options & SO_REUSEADDR) != 0)
1511 					inp->inp_flags2 |= INP_REUSEADDR;
1512 				else
1513 					inp->inp_flags2 &= ~INP_REUSEADDR;
1514 				INP_WUNLOCK(inp);
1515 				error = 0;
1516 				break;
1517 			case SO_REUSEPORT:
1518 				INP_WLOCK(inp);
1519 				if ((so->so_options & SO_REUSEPORT) != 0)
1520 					inp->inp_flags2 |= INP_REUSEPORT;
1521 				else
1522 					inp->inp_flags2 &= ~INP_REUSEPORT;
1523 				INP_WUNLOCK(inp);
1524 				error = 0;
1525 				break;
1526 			case SO_REUSEPORT_LB:
1527 				INP_WLOCK(inp);
1528 				if ((so->so_options & SO_REUSEPORT_LB) != 0)
1529 					inp->inp_flags2 |= INP_REUSEPORT_LB;
1530 				else
1531 					inp->inp_flags2 &= ~INP_REUSEPORT_LB;
1532 				INP_WUNLOCK(inp);
1533 				error = 0;
1534 				break;
1535 			case SO_SETFIB:
1536 				INP_WLOCK(inp);
1537 				inp->inp_inc.inc_fibnum = so->so_fibnum;
1538 				INP_WUNLOCK(inp);
1539 				error = 0;
1540 				break;
1541 			case SO_MAX_PACING_RATE:
1542 #ifdef RATELIMIT
1543 				INP_WLOCK(inp);
1544 				inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
1545 				INP_WUNLOCK(inp);
1546 				error = 0;
1547 #else
1548 				error = EOPNOTSUPP;
1549 #endif
1550 				break;
1551 			default:
1552 				break;
1553 			}
1554 		}
1555 	} else {		/* level == IPPROTO_IPV6 */
1556 		switch (op) {
1557 
1558 		case SOPT_SET:
1559 			switch (optname) {
1560 			case IPV6_2292PKTOPTIONS:
1561 #ifdef IPV6_PKTOPTIONS
1562 			case IPV6_PKTOPTIONS:
1563 #endif
1564 			{
1565 				struct mbuf *m;
1566 
1567 				if (optlen > IPV6_PKTOPTIONS_MBUF_LIMIT) {
1568 					printf("ip6_ctloutput: mbuf limit hit\n");
1569 					error = ENOBUFS;
1570 					break;
1571 				}
1572 
1573 				error = soopt_getm(sopt, &m); /* XXX */
1574 				if (error != 0)
1575 					break;
1576 				error = soopt_mcopyin(sopt, m); /* XXX */
1577 				if (error != 0)
1578 					break;
1579 				error = ip6_pcbopts(&inp->in6p_outputopts,
1580 						    m, so, sopt);
1581 				m_freem(m); /* XXX */
1582 				break;
1583 			}
1584 
1585 			/*
1586 			 * Use of some Hop-by-Hop options or some
1587 			 * Destination options, might require special
1588 			 * privilege.  That is, normal applications
1589 			 * (without special privilege) might be forbidden
1590 			 * from setting certain options in outgoing packets,
1591 			 * and might never see certain options in received
1592 			 * packets. [RFC 2292 Section 6]
1593 			 * KAME specific note:
1594 			 *  KAME prevents non-privileged users from sending or
1595 			 *  receiving ANY hbh/dst options in order to avoid
1596 			 *  overhead of parsing options in the kernel.
1597 			 */
1598 			case IPV6_RECVHOPOPTS:
1599 			case IPV6_RECVDSTOPTS:
1600 			case IPV6_RECVRTHDRDSTOPTS:
1601 				if (td != NULL) {
1602 					error = priv_check(td,
1603 					    PRIV_NETINET_SETHDROPTS);
1604 					if (error)
1605 						break;
1606 				}
1607 				/* FALLTHROUGH */
1608 			case IPV6_UNICAST_HOPS:
1609 			case IPV6_HOPLIMIT:
1610 
1611 			case IPV6_RECVPKTINFO:
1612 			case IPV6_RECVHOPLIMIT:
1613 			case IPV6_RECVRTHDR:
1614 			case IPV6_RECVPATHMTU:
1615 			case IPV6_RECVTCLASS:
1616 			case IPV6_RECVFLOWID:
1617 #ifdef	RSS
1618 			case IPV6_RECVRSSBUCKETID:
1619 #endif
1620 			case IPV6_V6ONLY:
1621 			case IPV6_AUTOFLOWLABEL:
1622 			case IPV6_ORIGDSTADDR:
1623 			case IPV6_BINDANY:
1624 			case IPV6_BINDMULTI:
1625 #ifdef	RSS
1626 			case IPV6_RSS_LISTEN_BUCKET:
1627 #endif
1628 				if (optname == IPV6_BINDANY && td != NULL) {
1629 					error = priv_check(td,
1630 					    PRIV_NETINET_BINDANY);
1631 					if (error)
1632 						break;
1633 				}
1634 
1635 				if (optlen != sizeof(int)) {
1636 					error = EINVAL;
1637 					break;
1638 				}
1639 				error = sooptcopyin(sopt, &optval,
1640 					sizeof optval, sizeof optval);
1641 				if (error)
1642 					break;
1643 				switch (optname) {
1644 
1645 				case IPV6_UNICAST_HOPS:
1646 					if (optval < -1 || optval >= 256)
1647 						error = EINVAL;
1648 					else {
1649 						/* -1 = kernel default */
1650 						inp->in6p_hops = optval;
1651 						if ((inp->inp_vflag &
1652 						     INP_IPV4) != 0)
1653 							inp->inp_ip_ttl = optval;
1654 					}
1655 					break;
1656 #define OPTSET(bit) \
1657 do { \
1658 	INP_WLOCK(inp); \
1659 	if (optval) \
1660 		inp->inp_flags |= (bit); \
1661 	else \
1662 		inp->inp_flags &= ~(bit); \
1663 	INP_WUNLOCK(inp); \
1664 } while (/*CONSTCOND*/ 0)
1665 #define OPTSET2292(bit) \
1666 do { \
1667 	INP_WLOCK(inp); \
1668 	inp->inp_flags |= IN6P_RFC2292; \
1669 	if (optval) \
1670 		inp->inp_flags |= (bit); \
1671 	else \
1672 		inp->inp_flags &= ~(bit); \
1673 	INP_WUNLOCK(inp); \
1674 } while (/*CONSTCOND*/ 0)
1675 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
1676 
1677 #define OPTSET2_N(bit, val) do {					\
1678 	if (val)							\
1679 		inp->inp_flags2 |= bit;					\
1680 	else								\
1681 		inp->inp_flags2 &= ~bit;				\
1682 } while (0)
1683 #define OPTSET2(bit, val) do {						\
1684 	INP_WLOCK(inp);							\
1685 	OPTSET2_N(bit, val);						\
1686 	INP_WUNLOCK(inp);						\
1687 } while (0)
1688 #define OPTBIT2(bit) (inp->inp_flags2 & (bit) ? 1 : 0)
1689 #define OPTSET2292_EXCLUSIVE(bit)					\
1690 do {									\
1691 	INP_WLOCK(inp);							\
1692 	if (OPTBIT(IN6P_RFC2292)) {					\
1693 		error = EINVAL;						\
1694 	} else {							\
1695 		if (optval)						\
1696 			inp->inp_flags |= (bit);			\
1697 		else							\
1698 			inp->inp_flags &= ~(bit);			\
1699 	}								\
1700 	INP_WUNLOCK(inp);						\
1701 } while (/*CONSTCOND*/ 0)
1702 
1703 				case IPV6_RECVPKTINFO:
1704 					OPTSET2292_EXCLUSIVE(IN6P_PKTINFO);
1705 					break;
1706 
1707 				case IPV6_HOPLIMIT:
1708 				{
1709 					struct ip6_pktopts **optp;
1710 
1711 					/* cannot mix with RFC2292 */
1712 					if (OPTBIT(IN6P_RFC2292)) {
1713 						error = EINVAL;
1714 						break;
1715 					}
1716 					INP_WLOCK(inp);
1717 					if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1718 						INP_WUNLOCK(inp);
1719 						return (ECONNRESET);
1720 					}
1721 					optp = &inp->in6p_outputopts;
1722 					error = ip6_pcbopt(IPV6_HOPLIMIT,
1723 					    (u_char *)&optval, sizeof(optval),
1724 					    optp, (td != NULL) ? td->td_ucred :
1725 					    NULL, uproto);
1726 					INP_WUNLOCK(inp);
1727 					break;
1728 				}
1729 
1730 				case IPV6_RECVHOPLIMIT:
1731 					OPTSET2292_EXCLUSIVE(IN6P_HOPLIMIT);
1732 					break;
1733 
1734 				case IPV6_RECVHOPOPTS:
1735 					OPTSET2292_EXCLUSIVE(IN6P_HOPOPTS);
1736 					break;
1737 
1738 				case IPV6_RECVDSTOPTS:
1739 					OPTSET2292_EXCLUSIVE(IN6P_DSTOPTS);
1740 					break;
1741 
1742 				case IPV6_RECVRTHDRDSTOPTS:
1743 					OPTSET2292_EXCLUSIVE(IN6P_RTHDRDSTOPTS);
1744 					break;
1745 
1746 				case IPV6_RECVRTHDR:
1747 					OPTSET2292_EXCLUSIVE(IN6P_RTHDR);
1748 					break;
1749 
1750 				case IPV6_RECVPATHMTU:
1751 					/*
1752 					 * We ignore this option for TCP
1753 					 * sockets.
1754 					 * (RFC3542 leaves this case
1755 					 * unspecified.)
1756 					 */
1757 					if (uproto != IPPROTO_TCP)
1758 						OPTSET(IN6P_MTU);
1759 					break;
1760 
1761 				case IPV6_RECVFLOWID:
1762 					OPTSET2(INP_RECVFLOWID, optval);
1763 					break;
1764 
1765 #ifdef	RSS
1766 				case IPV6_RECVRSSBUCKETID:
1767 					OPTSET2(INP_RECVRSSBUCKETID, optval);
1768 					break;
1769 #endif
1770 
1771 				case IPV6_V6ONLY:
1772 					/*
1773 					 * make setsockopt(IPV6_V6ONLY)
1774 					 * available only prior to bind(2).
1775 					 * see ipng mailing list, Jun 22 2001.
1776 					 */
1777 					if (inp->inp_lport ||
1778 					    !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1779 						error = EINVAL;
1780 						break;
1781 					}
1782 					OPTSET(IN6P_IPV6_V6ONLY);
1783 					if (optval)
1784 						inp->inp_vflag &= ~INP_IPV4;
1785 					else
1786 						inp->inp_vflag |= INP_IPV4;
1787 					break;
1788 				case IPV6_RECVTCLASS:
1789 					/* cannot mix with RFC2292 XXX */
1790 					OPTSET2292_EXCLUSIVE(IN6P_TCLASS);
1791 					break;
1792 				case IPV6_AUTOFLOWLABEL:
1793 					OPTSET(IN6P_AUTOFLOWLABEL);
1794 					break;
1795 
1796 				case IPV6_ORIGDSTADDR:
1797 					OPTSET2(INP_ORIGDSTADDR, optval);
1798 					break;
1799 				case IPV6_BINDANY:
1800 					OPTSET(INP_BINDANY);
1801 					break;
1802 
1803 				case IPV6_BINDMULTI:
1804 					OPTSET2(INP_BINDMULTI, optval);
1805 					break;
1806 #ifdef	RSS
1807 				case IPV6_RSS_LISTEN_BUCKET:
1808 					if ((optval >= 0) &&
1809 					    (optval < rss_getnumbuckets())) {
1810 						INP_WLOCK(inp);
1811 						inp->inp_rss_listen_bucket = optval;
1812 						OPTSET2_N(INP_RSS_BUCKET_SET, 1);
1813 						INP_WUNLOCK(inp);
1814 					} else {
1815 						error = EINVAL;
1816 					}
1817 					break;
1818 #endif
1819 				}
1820 				break;
1821 
1822 			case IPV6_TCLASS:
1823 			case IPV6_DONTFRAG:
1824 			case IPV6_USE_MIN_MTU:
1825 			case IPV6_PREFER_TEMPADDR:
1826 				if (optlen != sizeof(optval)) {
1827 					error = EINVAL;
1828 					break;
1829 				}
1830 				error = sooptcopyin(sopt, &optval,
1831 					sizeof optval, sizeof optval);
1832 				if (error)
1833 					break;
1834 				{
1835 					struct ip6_pktopts **optp;
1836 					INP_WLOCK(inp);
1837 					if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1838 						INP_WUNLOCK(inp);
1839 						return (ECONNRESET);
1840 					}
1841 					optp = &inp->in6p_outputopts;
1842 					error = ip6_pcbopt(optname,
1843 					    (u_char *)&optval, sizeof(optval),
1844 					    optp, (td != NULL) ? td->td_ucred :
1845 					    NULL, uproto);
1846 					INP_WUNLOCK(inp);
1847 					break;
1848 				}
1849 
1850 			case IPV6_2292PKTINFO:
1851 			case IPV6_2292HOPLIMIT:
1852 			case IPV6_2292HOPOPTS:
1853 			case IPV6_2292DSTOPTS:
1854 			case IPV6_2292RTHDR:
1855 				/* RFC 2292 */
1856 				if (optlen != sizeof(int)) {
1857 					error = EINVAL;
1858 					break;
1859 				}
1860 				error = sooptcopyin(sopt, &optval,
1861 					sizeof optval, sizeof optval);
1862 				if (error)
1863 					break;
1864 				switch (optname) {
1865 				case IPV6_2292PKTINFO:
1866 					OPTSET2292(IN6P_PKTINFO);
1867 					break;
1868 				case IPV6_2292HOPLIMIT:
1869 					OPTSET2292(IN6P_HOPLIMIT);
1870 					break;
1871 				case IPV6_2292HOPOPTS:
1872 					/*
1873 					 * Check super-user privilege.
1874 					 * See comments for IPV6_RECVHOPOPTS.
1875 					 */
1876 					if (td != NULL) {
1877 						error = priv_check(td,
1878 						    PRIV_NETINET_SETHDROPTS);
1879 						if (error)
1880 							return (error);
1881 					}
1882 					OPTSET2292(IN6P_HOPOPTS);
1883 					break;
1884 				case IPV6_2292DSTOPTS:
1885 					if (td != NULL) {
1886 						error = priv_check(td,
1887 						    PRIV_NETINET_SETHDROPTS);
1888 						if (error)
1889 							return (error);
1890 					}
1891 					OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
1892 					break;
1893 				case IPV6_2292RTHDR:
1894 					OPTSET2292(IN6P_RTHDR);
1895 					break;
1896 				}
1897 				break;
1898 			case IPV6_PKTINFO:
1899 			case IPV6_HOPOPTS:
1900 			case IPV6_RTHDR:
1901 			case IPV6_DSTOPTS:
1902 			case IPV6_RTHDRDSTOPTS:
1903 			case IPV6_NEXTHOP:
1904 			{
1905 				/* new advanced API (RFC3542) */
1906 				u_char *optbuf;
1907 				u_char optbuf_storage[MCLBYTES];
1908 				int optlen;
1909 				struct ip6_pktopts **optp;
1910 
1911 				/* cannot mix with RFC2292 */
1912 				if (OPTBIT(IN6P_RFC2292)) {
1913 					error = EINVAL;
1914 					break;
1915 				}
1916 
1917 				/*
1918 				 * We only ensure valsize is not too large
1919 				 * here.  Further validation will be done
1920 				 * later.
1921 				 */
1922 				error = sooptcopyin(sopt, optbuf_storage,
1923 				    sizeof(optbuf_storage), 0);
1924 				if (error)
1925 					break;
1926 				optlen = sopt->sopt_valsize;
1927 				optbuf = optbuf_storage;
1928 				INP_WLOCK(inp);
1929 				if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1930 					INP_WUNLOCK(inp);
1931 					return (ECONNRESET);
1932 				}
1933 				optp = &inp->in6p_outputopts;
1934 				error = ip6_pcbopt(optname, optbuf, optlen,
1935 				    optp, (td != NULL) ? td->td_ucred : NULL,
1936 				    uproto);
1937 				INP_WUNLOCK(inp);
1938 				break;
1939 			}
1940 #undef OPTSET
1941 
1942 			case IPV6_MULTICAST_IF:
1943 			case IPV6_MULTICAST_HOPS:
1944 			case IPV6_MULTICAST_LOOP:
1945 			case IPV6_JOIN_GROUP:
1946 			case IPV6_LEAVE_GROUP:
1947 			case IPV6_MSFILTER:
1948 			case MCAST_BLOCK_SOURCE:
1949 			case MCAST_UNBLOCK_SOURCE:
1950 			case MCAST_JOIN_GROUP:
1951 			case MCAST_LEAVE_GROUP:
1952 			case MCAST_JOIN_SOURCE_GROUP:
1953 			case MCAST_LEAVE_SOURCE_GROUP:
1954 				error = ip6_setmoptions(inp, sopt);
1955 				break;
1956 
1957 			case IPV6_PORTRANGE:
1958 				error = sooptcopyin(sopt, &optval,
1959 				    sizeof optval, sizeof optval);
1960 				if (error)
1961 					break;
1962 
1963 				INP_WLOCK(inp);
1964 				switch (optval) {
1965 				case IPV6_PORTRANGE_DEFAULT:
1966 					inp->inp_flags &= ~(INP_LOWPORT);
1967 					inp->inp_flags &= ~(INP_HIGHPORT);
1968 					break;
1969 
1970 				case IPV6_PORTRANGE_HIGH:
1971 					inp->inp_flags &= ~(INP_LOWPORT);
1972 					inp->inp_flags |= INP_HIGHPORT;
1973 					break;
1974 
1975 				case IPV6_PORTRANGE_LOW:
1976 					inp->inp_flags &= ~(INP_HIGHPORT);
1977 					inp->inp_flags |= INP_LOWPORT;
1978 					break;
1979 
1980 				default:
1981 					error = EINVAL;
1982 					break;
1983 				}
1984 				INP_WUNLOCK(inp);
1985 				break;
1986 
1987 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1988 			case IPV6_IPSEC_POLICY:
1989 				if (IPSEC_ENABLED(ipv6)) {
1990 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
1991 					break;
1992 				}
1993 				/* FALLTHROUGH */
1994 #endif /* IPSEC */
1995 
1996 			default:
1997 				error = ENOPROTOOPT;
1998 				break;
1999 			}
2000 			break;
2001 
2002 		case SOPT_GET:
2003 			switch (optname) {
2004 
2005 			case IPV6_2292PKTOPTIONS:
2006 #ifdef IPV6_PKTOPTIONS
2007 			case IPV6_PKTOPTIONS:
2008 #endif
2009 				/*
2010 				 * RFC3542 (effectively) deprecated the
2011 				 * semantics of the 2292-style pktoptions.
2012 				 * Since it was not reliable in nature (i.e.,
2013 				 * applications had to expect the lack of some
2014 				 * information after all), it would make sense
2015 				 * to simplify this part by always returning
2016 				 * empty data.
2017 				 */
2018 				sopt->sopt_valsize = 0;
2019 				break;
2020 
2021 			case IPV6_RECVHOPOPTS:
2022 			case IPV6_RECVDSTOPTS:
2023 			case IPV6_RECVRTHDRDSTOPTS:
2024 			case IPV6_UNICAST_HOPS:
2025 			case IPV6_RECVPKTINFO:
2026 			case IPV6_RECVHOPLIMIT:
2027 			case IPV6_RECVRTHDR:
2028 			case IPV6_RECVPATHMTU:
2029 
2030 			case IPV6_V6ONLY:
2031 			case IPV6_PORTRANGE:
2032 			case IPV6_RECVTCLASS:
2033 			case IPV6_AUTOFLOWLABEL:
2034 			case IPV6_BINDANY:
2035 			case IPV6_FLOWID:
2036 			case IPV6_FLOWTYPE:
2037 			case IPV6_RECVFLOWID:
2038 #ifdef	RSS
2039 			case IPV6_RSSBUCKETID:
2040 			case IPV6_RECVRSSBUCKETID:
2041 #endif
2042 			case IPV6_BINDMULTI:
2043 				switch (optname) {
2044 
2045 				case IPV6_RECVHOPOPTS:
2046 					optval = OPTBIT(IN6P_HOPOPTS);
2047 					break;
2048 
2049 				case IPV6_RECVDSTOPTS:
2050 					optval = OPTBIT(IN6P_DSTOPTS);
2051 					break;
2052 
2053 				case IPV6_RECVRTHDRDSTOPTS:
2054 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
2055 					break;
2056 
2057 				case IPV6_UNICAST_HOPS:
2058 					optval = inp->in6p_hops;
2059 					break;
2060 
2061 				case IPV6_RECVPKTINFO:
2062 					optval = OPTBIT(IN6P_PKTINFO);
2063 					break;
2064 
2065 				case IPV6_RECVHOPLIMIT:
2066 					optval = OPTBIT(IN6P_HOPLIMIT);
2067 					break;
2068 
2069 				case IPV6_RECVRTHDR:
2070 					optval = OPTBIT(IN6P_RTHDR);
2071 					break;
2072 
2073 				case IPV6_RECVPATHMTU:
2074 					optval = OPTBIT(IN6P_MTU);
2075 					break;
2076 
2077 				case IPV6_V6ONLY:
2078 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
2079 					break;
2080 
2081 				case IPV6_PORTRANGE:
2082 				    {
2083 					int flags;
2084 					flags = inp->inp_flags;
2085 					if (flags & INP_HIGHPORT)
2086 						optval = IPV6_PORTRANGE_HIGH;
2087 					else if (flags & INP_LOWPORT)
2088 						optval = IPV6_PORTRANGE_LOW;
2089 					else
2090 						optval = 0;
2091 					break;
2092 				    }
2093 				case IPV6_RECVTCLASS:
2094 					optval = OPTBIT(IN6P_TCLASS);
2095 					break;
2096 
2097 				case IPV6_AUTOFLOWLABEL:
2098 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
2099 					break;
2100 
2101 				case IPV6_ORIGDSTADDR:
2102 					optval = OPTBIT2(INP_ORIGDSTADDR);
2103 					break;
2104 
2105 				case IPV6_BINDANY:
2106 					optval = OPTBIT(INP_BINDANY);
2107 					break;
2108 
2109 				case IPV6_FLOWID:
2110 					optval = inp->inp_flowid;
2111 					break;
2112 
2113 				case IPV6_FLOWTYPE:
2114 					optval = inp->inp_flowtype;
2115 					break;
2116 
2117 				case IPV6_RECVFLOWID:
2118 					optval = OPTBIT2(INP_RECVFLOWID);
2119 					break;
2120 #ifdef	RSS
2121 				case IPV6_RSSBUCKETID:
2122 					retval =
2123 					    rss_hash2bucket(inp->inp_flowid,
2124 					    inp->inp_flowtype,
2125 					    &rss_bucket);
2126 					if (retval == 0)
2127 						optval = rss_bucket;
2128 					else
2129 						error = EINVAL;
2130 					break;
2131 
2132 				case IPV6_RECVRSSBUCKETID:
2133 					optval = OPTBIT2(INP_RECVRSSBUCKETID);
2134 					break;
2135 #endif
2136 
2137 				case IPV6_BINDMULTI:
2138 					optval = OPTBIT2(INP_BINDMULTI);
2139 					break;
2140 
2141 				}
2142 				if (error)
2143 					break;
2144 				error = sooptcopyout(sopt, &optval,
2145 					sizeof optval);
2146 				break;
2147 
2148 			case IPV6_PATHMTU:
2149 			{
2150 				u_long pmtu = 0;
2151 				struct ip6_mtuinfo mtuinfo;
2152 				struct in6_addr addr;
2153 
2154 				if (!(so->so_state & SS_ISCONNECTED))
2155 					return (ENOTCONN);
2156 				/*
2157 				 * XXX: we dot not consider the case of source
2158 				 * routing, or optional information to specify
2159 				 * the outgoing interface.
2160 				 * Copy faddr out of inp to avoid holding lock
2161 				 * on inp during route lookup.
2162 				 */
2163 				INP_RLOCK(inp);
2164 				bcopy(&inp->in6p_faddr, &addr, sizeof(addr));
2165 				INP_RUNLOCK(inp);
2166 				error = ip6_getpmtu_ctl(so->so_fibnum,
2167 				    &addr, &pmtu);
2168 				if (error)
2169 					break;
2170 				if (pmtu > IPV6_MAXPACKET)
2171 					pmtu = IPV6_MAXPACKET;
2172 
2173 				bzero(&mtuinfo, sizeof(mtuinfo));
2174 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
2175 				optdata = (void *)&mtuinfo;
2176 				optdatalen = sizeof(mtuinfo);
2177 				error = sooptcopyout(sopt, optdata,
2178 				    optdatalen);
2179 				break;
2180 			}
2181 
2182 			case IPV6_2292PKTINFO:
2183 			case IPV6_2292HOPLIMIT:
2184 			case IPV6_2292HOPOPTS:
2185 			case IPV6_2292RTHDR:
2186 			case IPV6_2292DSTOPTS:
2187 				switch (optname) {
2188 				case IPV6_2292PKTINFO:
2189 					optval = OPTBIT(IN6P_PKTINFO);
2190 					break;
2191 				case IPV6_2292HOPLIMIT:
2192 					optval = OPTBIT(IN6P_HOPLIMIT);
2193 					break;
2194 				case IPV6_2292HOPOPTS:
2195 					optval = OPTBIT(IN6P_HOPOPTS);
2196 					break;
2197 				case IPV6_2292RTHDR:
2198 					optval = OPTBIT(IN6P_RTHDR);
2199 					break;
2200 				case IPV6_2292DSTOPTS:
2201 					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
2202 					break;
2203 				}
2204 				error = sooptcopyout(sopt, &optval,
2205 				    sizeof optval);
2206 				break;
2207 			case IPV6_PKTINFO:
2208 			case IPV6_HOPOPTS:
2209 			case IPV6_RTHDR:
2210 			case IPV6_DSTOPTS:
2211 			case IPV6_RTHDRDSTOPTS:
2212 			case IPV6_NEXTHOP:
2213 			case IPV6_TCLASS:
2214 			case IPV6_DONTFRAG:
2215 			case IPV6_USE_MIN_MTU:
2216 			case IPV6_PREFER_TEMPADDR:
2217 				error = ip6_getpcbopt(inp, optname, sopt);
2218 				break;
2219 
2220 			case IPV6_MULTICAST_IF:
2221 			case IPV6_MULTICAST_HOPS:
2222 			case IPV6_MULTICAST_LOOP:
2223 			case IPV6_MSFILTER:
2224 				error = ip6_getmoptions(inp, sopt);
2225 				break;
2226 
2227 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
2228 			case IPV6_IPSEC_POLICY:
2229 				if (IPSEC_ENABLED(ipv6)) {
2230 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
2231 					break;
2232 				}
2233 				/* FALLTHROUGH */
2234 #endif /* IPSEC */
2235 			default:
2236 				error = ENOPROTOOPT;
2237 				break;
2238 			}
2239 			break;
2240 		}
2241 	}
2242 	return (error);
2243 }
2244 
2245 int
2246 ip6_raw_ctloutput(struct socket *so, struct sockopt *sopt)
2247 {
2248 	int error = 0, optval, optlen;
2249 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
2250 	struct inpcb *inp = sotoinpcb(so);
2251 	int level, op, optname;
2252 
2253 	level = sopt->sopt_level;
2254 	op = sopt->sopt_dir;
2255 	optname = sopt->sopt_name;
2256 	optlen = sopt->sopt_valsize;
2257 
2258 	if (level != IPPROTO_IPV6) {
2259 		return (EINVAL);
2260 	}
2261 
2262 	switch (optname) {
2263 	case IPV6_CHECKSUM:
2264 		/*
2265 		 * For ICMPv6 sockets, no modification allowed for checksum
2266 		 * offset, permit "no change" values to help existing apps.
2267 		 *
2268 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
2269 		 * for an ICMPv6 socket will fail."
2270 		 * The current behavior does not meet RFC3542.
2271 		 */
2272 		switch (op) {
2273 		case SOPT_SET:
2274 			if (optlen != sizeof(int)) {
2275 				error = EINVAL;
2276 				break;
2277 			}
2278 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2279 					    sizeof(optval));
2280 			if (error)
2281 				break;
2282 			if (optval < -1 || (optval % 2) != 0) {
2283 				/*
2284 				 * The API assumes non-negative even offset
2285 				 * values or -1 as a special value.
2286 				 */
2287 				error = EINVAL;
2288 			} else if (so->so_proto->pr_protocol ==
2289 			    IPPROTO_ICMPV6) {
2290 				if (optval != icmp6off)
2291 					error = EINVAL;
2292 			} else
2293 				inp->in6p_cksum = optval;
2294 			break;
2295 
2296 		case SOPT_GET:
2297 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
2298 				optval = icmp6off;
2299 			else
2300 				optval = inp->in6p_cksum;
2301 
2302 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2303 			break;
2304 
2305 		default:
2306 			error = EINVAL;
2307 			break;
2308 		}
2309 		break;
2310 
2311 	default:
2312 		error = ENOPROTOOPT;
2313 		break;
2314 	}
2315 
2316 	return (error);
2317 }
2318 
2319 /*
2320  * Set up IP6 options in pcb for insertion in output packets or
2321  * specifying behavior of outgoing packets.
2322  */
2323 static int
2324 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m,
2325     struct socket *so, struct sockopt *sopt)
2326 {
2327 	struct ip6_pktopts *opt = *pktopt;
2328 	int error = 0;
2329 	struct thread *td = sopt->sopt_td;
2330 
2331 	/* turn off any old options. */
2332 	if (opt) {
2333 #ifdef DIAGNOSTIC
2334 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
2335 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
2336 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
2337 			printf("ip6_pcbopts: all specified options are cleared.\n");
2338 #endif
2339 		ip6_clearpktopts(opt, -1);
2340 	} else
2341 		opt = malloc(sizeof(*opt), M_IP6OPT, M_WAITOK);
2342 	*pktopt = NULL;
2343 
2344 	if (!m || m->m_len == 0) {
2345 		/*
2346 		 * Only turning off any previous options, regardless of
2347 		 * whether the opt is just created or given.
2348 		 */
2349 		free(opt, M_IP6OPT);
2350 		return (0);
2351 	}
2352 
2353 	/*  set options specified by user. */
2354 	if ((error = ip6_setpktopts(m, opt, NULL, (td != NULL) ?
2355 	    td->td_ucred : NULL, so->so_proto->pr_protocol)) != 0) {
2356 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
2357 		free(opt, M_IP6OPT);
2358 		return (error);
2359 	}
2360 	*pktopt = opt;
2361 	return (0);
2362 }
2363 
2364 /*
2365  * initialize ip6_pktopts.  beware that there are non-zero default values in
2366  * the struct.
2367  */
2368 void
2369 ip6_initpktopts(struct ip6_pktopts *opt)
2370 {
2371 
2372 	bzero(opt, sizeof(*opt));
2373 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2374 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2375 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2376 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
2377 }
2378 
2379 static int
2380 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
2381     struct ucred *cred, int uproto)
2382 {
2383 	struct ip6_pktopts *opt;
2384 
2385 	if (*pktopt == NULL) {
2386 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
2387 		    M_NOWAIT);
2388 		if (*pktopt == NULL)
2389 			return (ENOBUFS);
2390 		ip6_initpktopts(*pktopt);
2391 	}
2392 	opt = *pktopt;
2393 
2394 	return (ip6_setpktopt(optname, buf, len, opt, cred, 1, 0, uproto));
2395 }
2396 
2397 #define GET_PKTOPT_VAR(field, lenexpr) do {					\
2398 	if (pktopt && pktopt->field) {						\
2399 		INP_RUNLOCK(inp);						\
2400 		optdata = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK);		\
2401 		malloc_optdata = true;						\
2402 		INP_RLOCK(inp);							\
2403 		if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {		\
2404 			INP_RUNLOCK(inp);					\
2405 			free(optdata, M_TEMP);					\
2406 			return (ECONNRESET);					\
2407 		}								\
2408 		pktopt = inp->in6p_outputopts;					\
2409 		if (pktopt && pktopt->field) {					\
2410 			optdatalen = min(lenexpr, sopt->sopt_valsize);		\
2411 			bcopy(&pktopt->field, optdata, optdatalen);		\
2412 		} else {							\
2413 			free(optdata, M_TEMP);					\
2414 			optdata = NULL;						\
2415 			malloc_optdata = false;					\
2416 		}								\
2417 	}									\
2418 } while(0)
2419 
2420 #define GET_PKTOPT_EXT_HDR(field) GET_PKTOPT_VAR(field,				\
2421 	(((struct ip6_ext *)pktopt->field)->ip6e_len + 1) << 3)
2422 
2423 #define GET_PKTOPT_SOCKADDR(field) GET_PKTOPT_VAR(field,			\
2424 	pktopt->field->sa_len)
2425 
2426 static int
2427 ip6_getpcbopt(struct inpcb *inp, int optname, struct sockopt *sopt)
2428 {
2429 	void *optdata = NULL;
2430 	bool malloc_optdata = false;
2431 	int optdatalen = 0;
2432 	int error = 0;
2433 	struct in6_pktinfo null_pktinfo;
2434 	int deftclass = 0, on;
2435 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2436 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
2437 	struct ip6_pktopts *pktopt;
2438 
2439 	INP_RLOCK(inp);
2440 	pktopt = inp->in6p_outputopts;
2441 
2442 	switch (optname) {
2443 	case IPV6_PKTINFO:
2444 		optdata = (void *)&null_pktinfo;
2445 		if (pktopt && pktopt->ip6po_pktinfo) {
2446 			bcopy(pktopt->ip6po_pktinfo, &null_pktinfo,
2447 			    sizeof(null_pktinfo));
2448 			in6_clearscope(&null_pktinfo.ipi6_addr);
2449 		} else {
2450 			/* XXX: we don't have to do this every time... */
2451 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2452 		}
2453 		optdatalen = sizeof(struct in6_pktinfo);
2454 		break;
2455 	case IPV6_TCLASS:
2456 		if (pktopt && pktopt->ip6po_tclass >= 0)
2457 			deftclass = pktopt->ip6po_tclass;
2458 		optdata = (void *)&deftclass;
2459 		optdatalen = sizeof(int);
2460 		break;
2461 	case IPV6_HOPOPTS:
2462 		GET_PKTOPT_EXT_HDR(ip6po_hbh);
2463 		break;
2464 	case IPV6_RTHDR:
2465 		GET_PKTOPT_EXT_HDR(ip6po_rthdr);
2466 		break;
2467 	case IPV6_RTHDRDSTOPTS:
2468 		GET_PKTOPT_EXT_HDR(ip6po_dest1);
2469 		break;
2470 	case IPV6_DSTOPTS:
2471 		GET_PKTOPT_EXT_HDR(ip6po_dest2);
2472 		break;
2473 	case IPV6_NEXTHOP:
2474 		GET_PKTOPT_SOCKADDR(ip6po_nexthop);
2475 		break;
2476 	case IPV6_USE_MIN_MTU:
2477 		if (pktopt)
2478 			defminmtu = pktopt->ip6po_minmtu;
2479 		optdata = (void *)&defminmtu;
2480 		optdatalen = sizeof(int);
2481 		break;
2482 	case IPV6_DONTFRAG:
2483 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2484 			on = 1;
2485 		else
2486 			on = 0;
2487 		optdata = (void *)&on;
2488 		optdatalen = sizeof(on);
2489 		break;
2490 	case IPV6_PREFER_TEMPADDR:
2491 		if (pktopt)
2492 			defpreftemp = pktopt->ip6po_prefer_tempaddr;
2493 		optdata = (void *)&defpreftemp;
2494 		optdatalen = sizeof(int);
2495 		break;
2496 	default:		/* should not happen */
2497 #ifdef DIAGNOSTIC
2498 		panic("ip6_getpcbopt: unexpected option\n");
2499 #endif
2500 		INP_RUNLOCK(inp);
2501 		return (ENOPROTOOPT);
2502 	}
2503 	INP_RUNLOCK(inp);
2504 
2505 	error = sooptcopyout(sopt, optdata, optdatalen);
2506 	if (malloc_optdata)
2507 		free(optdata, M_TEMP);
2508 
2509 	return (error);
2510 }
2511 
2512 void
2513 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
2514 {
2515 	if (pktopt == NULL)
2516 		return;
2517 
2518 	if (optname == -1 || optname == IPV6_PKTINFO) {
2519 		if (pktopt->ip6po_pktinfo)
2520 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
2521 		pktopt->ip6po_pktinfo = NULL;
2522 	}
2523 	if (optname == -1 || optname == IPV6_HOPLIMIT)
2524 		pktopt->ip6po_hlim = -1;
2525 	if (optname == -1 || optname == IPV6_TCLASS)
2526 		pktopt->ip6po_tclass = -1;
2527 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2528 		if (pktopt->ip6po_nextroute.ro_rt) {
2529 			RTFREE(pktopt->ip6po_nextroute.ro_rt);
2530 			pktopt->ip6po_nextroute.ro_rt = NULL;
2531 		}
2532 		if (pktopt->ip6po_nexthop)
2533 			free(pktopt->ip6po_nexthop, M_IP6OPT);
2534 		pktopt->ip6po_nexthop = NULL;
2535 	}
2536 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2537 		if (pktopt->ip6po_hbh)
2538 			free(pktopt->ip6po_hbh, M_IP6OPT);
2539 		pktopt->ip6po_hbh = NULL;
2540 	}
2541 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2542 		if (pktopt->ip6po_dest1)
2543 			free(pktopt->ip6po_dest1, M_IP6OPT);
2544 		pktopt->ip6po_dest1 = NULL;
2545 	}
2546 	if (optname == -1 || optname == IPV6_RTHDR) {
2547 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2548 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2549 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2550 		if (pktopt->ip6po_route.ro_rt) {
2551 			RTFREE(pktopt->ip6po_route.ro_rt);
2552 			pktopt->ip6po_route.ro_rt = NULL;
2553 		}
2554 	}
2555 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2556 		if (pktopt->ip6po_dest2)
2557 			free(pktopt->ip6po_dest2, M_IP6OPT);
2558 		pktopt->ip6po_dest2 = NULL;
2559 	}
2560 }
2561 
2562 #define PKTOPT_EXTHDRCPY(type) \
2563 do {\
2564 	if (src->type) {\
2565 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2566 		dst->type = malloc(hlen, M_IP6OPT, canwait);\
2567 		if (dst->type == NULL)\
2568 			goto bad;\
2569 		bcopy(src->type, dst->type, hlen);\
2570 	}\
2571 } while (/*CONSTCOND*/ 0)
2572 
2573 static int
2574 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
2575 {
2576 	if (dst == NULL || src == NULL)  {
2577 		printf("ip6_clearpktopts: invalid argument\n");
2578 		return (EINVAL);
2579 	}
2580 
2581 	dst->ip6po_hlim = src->ip6po_hlim;
2582 	dst->ip6po_tclass = src->ip6po_tclass;
2583 	dst->ip6po_flags = src->ip6po_flags;
2584 	dst->ip6po_minmtu = src->ip6po_minmtu;
2585 	dst->ip6po_prefer_tempaddr = src->ip6po_prefer_tempaddr;
2586 	if (src->ip6po_pktinfo) {
2587 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
2588 		    M_IP6OPT, canwait);
2589 		if (dst->ip6po_pktinfo == NULL)
2590 			goto bad;
2591 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2592 	}
2593 	if (src->ip6po_nexthop) {
2594 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
2595 		    M_IP6OPT, canwait);
2596 		if (dst->ip6po_nexthop == NULL)
2597 			goto bad;
2598 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2599 		    src->ip6po_nexthop->sa_len);
2600 	}
2601 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2602 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2603 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2604 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2605 	return (0);
2606 
2607   bad:
2608 	ip6_clearpktopts(dst, -1);
2609 	return (ENOBUFS);
2610 }
2611 #undef PKTOPT_EXTHDRCPY
2612 
2613 struct ip6_pktopts *
2614 ip6_copypktopts(struct ip6_pktopts *src, int canwait)
2615 {
2616 	int error;
2617 	struct ip6_pktopts *dst;
2618 
2619 	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
2620 	if (dst == NULL)
2621 		return (NULL);
2622 	ip6_initpktopts(dst);
2623 
2624 	if ((error = copypktopts(dst, src, canwait)) != 0) {
2625 		free(dst, M_IP6OPT);
2626 		return (NULL);
2627 	}
2628 
2629 	return (dst);
2630 }
2631 
2632 void
2633 ip6_freepcbopts(struct ip6_pktopts *pktopt)
2634 {
2635 	if (pktopt == NULL)
2636 		return;
2637 
2638 	ip6_clearpktopts(pktopt, -1);
2639 
2640 	free(pktopt, M_IP6OPT);
2641 }
2642 
2643 /*
2644  * Set IPv6 outgoing packet options based on advanced API.
2645  */
2646 int
2647 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2648     struct ip6_pktopts *stickyopt, struct ucred *cred, int uproto)
2649 {
2650 	struct cmsghdr *cm = NULL;
2651 
2652 	if (control == NULL || opt == NULL)
2653 		return (EINVAL);
2654 
2655 	ip6_initpktopts(opt);
2656 	if (stickyopt) {
2657 		int error;
2658 
2659 		/*
2660 		 * If stickyopt is provided, make a local copy of the options
2661 		 * for this particular packet, then override them by ancillary
2662 		 * objects.
2663 		 * XXX: copypktopts() does not copy the cached route to a next
2664 		 * hop (if any).  This is not very good in terms of efficiency,
2665 		 * but we can allow this since this option should be rarely
2666 		 * used.
2667 		 */
2668 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
2669 			return (error);
2670 	}
2671 
2672 	/*
2673 	 * XXX: Currently, we assume all the optional information is stored
2674 	 * in a single mbuf.
2675 	 */
2676 	if (control->m_next)
2677 		return (EINVAL);
2678 
2679 	for (; control->m_len > 0; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2680 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2681 		int error;
2682 
2683 		if (control->m_len < CMSG_LEN(0))
2684 			return (EINVAL);
2685 
2686 		cm = mtod(control, struct cmsghdr *);
2687 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2688 			return (EINVAL);
2689 		if (cm->cmsg_level != IPPROTO_IPV6)
2690 			continue;
2691 
2692 		error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2693 		    cm->cmsg_len - CMSG_LEN(0), opt, cred, 0, 1, uproto);
2694 		if (error)
2695 			return (error);
2696 	}
2697 
2698 	return (0);
2699 }
2700 
2701 /*
2702  * Set a particular packet option, as a sticky option or an ancillary data
2703  * item.  "len" can be 0 only when it's a sticky option.
2704  * We have 4 cases of combination of "sticky" and "cmsg":
2705  * "sticky=0, cmsg=0": impossible
2706  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
2707  * "sticky=1, cmsg=0": RFC3542 socket option
2708  * "sticky=1, cmsg=1": RFC2292 socket option
2709  */
2710 static int
2711 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2712     struct ucred *cred, int sticky, int cmsg, int uproto)
2713 {
2714 	int minmtupolicy, preftemp;
2715 	int error;
2716 
2717 	if (!sticky && !cmsg) {
2718 #ifdef DIAGNOSTIC
2719 		printf("ip6_setpktopt: impossible case\n");
2720 #endif
2721 		return (EINVAL);
2722 	}
2723 
2724 	/*
2725 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
2726 	 * not be specified in the context of RFC3542.  Conversely,
2727 	 * RFC3542 types should not be specified in the context of RFC2292.
2728 	 */
2729 	if (!cmsg) {
2730 		switch (optname) {
2731 		case IPV6_2292PKTINFO:
2732 		case IPV6_2292HOPLIMIT:
2733 		case IPV6_2292NEXTHOP:
2734 		case IPV6_2292HOPOPTS:
2735 		case IPV6_2292DSTOPTS:
2736 		case IPV6_2292RTHDR:
2737 		case IPV6_2292PKTOPTIONS:
2738 			return (ENOPROTOOPT);
2739 		}
2740 	}
2741 	if (sticky && cmsg) {
2742 		switch (optname) {
2743 		case IPV6_PKTINFO:
2744 		case IPV6_HOPLIMIT:
2745 		case IPV6_NEXTHOP:
2746 		case IPV6_HOPOPTS:
2747 		case IPV6_DSTOPTS:
2748 		case IPV6_RTHDRDSTOPTS:
2749 		case IPV6_RTHDR:
2750 		case IPV6_USE_MIN_MTU:
2751 		case IPV6_DONTFRAG:
2752 		case IPV6_TCLASS:
2753 		case IPV6_PREFER_TEMPADDR: /* XXX: not an RFC3542 option */
2754 			return (ENOPROTOOPT);
2755 		}
2756 	}
2757 
2758 	switch (optname) {
2759 	case IPV6_2292PKTINFO:
2760 	case IPV6_PKTINFO:
2761 	{
2762 		struct ifnet *ifp = NULL;
2763 		struct in6_pktinfo *pktinfo;
2764 
2765 		if (len != sizeof(struct in6_pktinfo))
2766 			return (EINVAL);
2767 
2768 		pktinfo = (struct in6_pktinfo *)buf;
2769 
2770 		/*
2771 		 * An application can clear any sticky IPV6_PKTINFO option by
2772 		 * doing a "regular" setsockopt with ipi6_addr being
2773 		 * in6addr_any and ipi6_ifindex being zero.
2774 		 * [RFC 3542, Section 6]
2775 		 */
2776 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
2777 		    pktinfo->ipi6_ifindex == 0 &&
2778 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2779 			ip6_clearpktopts(opt, optname);
2780 			break;
2781 		}
2782 
2783 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
2784 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2785 			return (EINVAL);
2786 		}
2787 		if (IN6_IS_ADDR_MULTICAST(&pktinfo->ipi6_addr))
2788 			return (EINVAL);
2789 		/* validate the interface index if specified. */
2790 		if (pktinfo->ipi6_ifindex > V_if_index)
2791 			 return (ENXIO);
2792 		if (pktinfo->ipi6_ifindex) {
2793 			ifp = ifnet_byindex(pktinfo->ipi6_ifindex);
2794 			if (ifp == NULL)
2795 				return (ENXIO);
2796 		}
2797 		if (ifp != NULL && (ifp->if_afdata[AF_INET6] == NULL ||
2798 		    (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) != 0))
2799 			return (ENETDOWN);
2800 
2801 		if (ifp != NULL &&
2802 		    !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2803 			struct in6_ifaddr *ia;
2804 
2805 			in6_setscope(&pktinfo->ipi6_addr, ifp, NULL);
2806 			ia = in6ifa_ifpwithaddr(ifp, &pktinfo->ipi6_addr);
2807 			if (ia == NULL)
2808 				return (EADDRNOTAVAIL);
2809 			ifa_free(&ia->ia_ifa);
2810 		}
2811 		/*
2812 		 * We store the address anyway, and let in6_selectsrc()
2813 		 * validate the specified address.  This is because ipi6_addr
2814 		 * may not have enough information about its scope zone, and
2815 		 * we may need additional information (such as outgoing
2816 		 * interface or the scope zone of a destination address) to
2817 		 * disambiguate the scope.
2818 		 * XXX: the delay of the validation may confuse the
2819 		 * application when it is used as a sticky option.
2820 		 */
2821 		if (opt->ip6po_pktinfo == NULL) {
2822 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2823 			    M_IP6OPT, M_NOWAIT);
2824 			if (opt->ip6po_pktinfo == NULL)
2825 				return (ENOBUFS);
2826 		}
2827 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
2828 		break;
2829 	}
2830 
2831 	case IPV6_2292HOPLIMIT:
2832 	case IPV6_HOPLIMIT:
2833 	{
2834 		int *hlimp;
2835 
2836 		/*
2837 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
2838 		 * to simplify the ordering among hoplimit options.
2839 		 */
2840 		if (optname == IPV6_HOPLIMIT && sticky)
2841 			return (ENOPROTOOPT);
2842 
2843 		if (len != sizeof(int))
2844 			return (EINVAL);
2845 		hlimp = (int *)buf;
2846 		if (*hlimp < -1 || *hlimp > 255)
2847 			return (EINVAL);
2848 
2849 		opt->ip6po_hlim = *hlimp;
2850 		break;
2851 	}
2852 
2853 	case IPV6_TCLASS:
2854 	{
2855 		int tclass;
2856 
2857 		if (len != sizeof(int))
2858 			return (EINVAL);
2859 		tclass = *(int *)buf;
2860 		if (tclass < -1 || tclass > 255)
2861 			return (EINVAL);
2862 
2863 		opt->ip6po_tclass = tclass;
2864 		break;
2865 	}
2866 
2867 	case IPV6_2292NEXTHOP:
2868 	case IPV6_NEXTHOP:
2869 		if (cred != NULL) {
2870 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2871 			if (error)
2872 				return (error);
2873 		}
2874 
2875 		if (len == 0) {	/* just remove the option */
2876 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
2877 			break;
2878 		}
2879 
2880 		/* check if cmsg_len is large enough for sa_len */
2881 		if (len < sizeof(struct sockaddr) || len < *buf)
2882 			return (EINVAL);
2883 
2884 		switch (((struct sockaddr *)buf)->sa_family) {
2885 		case AF_INET6:
2886 		{
2887 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
2888 			int error;
2889 
2890 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
2891 				return (EINVAL);
2892 
2893 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
2894 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
2895 				return (EINVAL);
2896 			}
2897 			if ((error = sa6_embedscope(sa6, V_ip6_use_defzone))
2898 			    != 0) {
2899 				return (error);
2900 			}
2901 			break;
2902 		}
2903 		case AF_LINK:	/* should eventually be supported */
2904 		default:
2905 			return (EAFNOSUPPORT);
2906 		}
2907 
2908 		/* turn off the previous option, then set the new option. */
2909 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
2910 		opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_NOWAIT);
2911 		if (opt->ip6po_nexthop == NULL)
2912 			return (ENOBUFS);
2913 		bcopy(buf, opt->ip6po_nexthop, *buf);
2914 		break;
2915 
2916 	case IPV6_2292HOPOPTS:
2917 	case IPV6_HOPOPTS:
2918 	{
2919 		struct ip6_hbh *hbh;
2920 		int hbhlen;
2921 
2922 		/*
2923 		 * XXX: We don't allow a non-privileged user to set ANY HbH
2924 		 * options, since per-option restriction has too much
2925 		 * overhead.
2926 		 */
2927 		if (cred != NULL) {
2928 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2929 			if (error)
2930 				return (error);
2931 		}
2932 
2933 		if (len == 0) {
2934 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
2935 			break;	/* just remove the option */
2936 		}
2937 
2938 		/* message length validation */
2939 		if (len < sizeof(struct ip6_hbh))
2940 			return (EINVAL);
2941 		hbh = (struct ip6_hbh *)buf;
2942 		hbhlen = (hbh->ip6h_len + 1) << 3;
2943 		if (len != hbhlen)
2944 			return (EINVAL);
2945 
2946 		/* turn off the previous option, then set the new option. */
2947 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
2948 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
2949 		if (opt->ip6po_hbh == NULL)
2950 			return (ENOBUFS);
2951 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
2952 
2953 		break;
2954 	}
2955 
2956 	case IPV6_2292DSTOPTS:
2957 	case IPV6_DSTOPTS:
2958 	case IPV6_RTHDRDSTOPTS:
2959 	{
2960 		struct ip6_dest *dest, **newdest = NULL;
2961 		int destlen;
2962 
2963 		if (cred != NULL) { /* XXX: see the comment for IPV6_HOPOPTS */
2964 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
2965 			if (error)
2966 				return (error);
2967 		}
2968 
2969 		if (len == 0) {
2970 			ip6_clearpktopts(opt, optname);
2971 			break;	/* just remove the option */
2972 		}
2973 
2974 		/* message length validation */
2975 		if (len < sizeof(struct ip6_dest))
2976 			return (EINVAL);
2977 		dest = (struct ip6_dest *)buf;
2978 		destlen = (dest->ip6d_len + 1) << 3;
2979 		if (len != destlen)
2980 			return (EINVAL);
2981 
2982 		/*
2983 		 * Determine the position that the destination options header
2984 		 * should be inserted; before or after the routing header.
2985 		 */
2986 		switch (optname) {
2987 		case IPV6_2292DSTOPTS:
2988 			/*
2989 			 * The old advacned API is ambiguous on this point.
2990 			 * Our approach is to determine the position based
2991 			 * according to the existence of a routing header.
2992 			 * Note, however, that this depends on the order of the
2993 			 * extension headers in the ancillary data; the 1st
2994 			 * part of the destination options header must appear
2995 			 * before the routing header in the ancillary data,
2996 			 * too.
2997 			 * RFC3542 solved the ambiguity by introducing
2998 			 * separate ancillary data or option types.
2999 			 */
3000 			if (opt->ip6po_rthdr == NULL)
3001 				newdest = &opt->ip6po_dest1;
3002 			else
3003 				newdest = &opt->ip6po_dest2;
3004 			break;
3005 		case IPV6_RTHDRDSTOPTS:
3006 			newdest = &opt->ip6po_dest1;
3007 			break;
3008 		case IPV6_DSTOPTS:
3009 			newdest = &opt->ip6po_dest2;
3010 			break;
3011 		}
3012 
3013 		/* turn off the previous option, then set the new option. */
3014 		ip6_clearpktopts(opt, optname);
3015 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
3016 		if (*newdest == NULL)
3017 			return (ENOBUFS);
3018 		bcopy(dest, *newdest, destlen);
3019 
3020 		break;
3021 	}
3022 
3023 	case IPV6_2292RTHDR:
3024 	case IPV6_RTHDR:
3025 	{
3026 		struct ip6_rthdr *rth;
3027 		int rthlen;
3028 
3029 		if (len == 0) {
3030 			ip6_clearpktopts(opt, IPV6_RTHDR);
3031 			break;	/* just remove the option */
3032 		}
3033 
3034 		/* message length validation */
3035 		if (len < sizeof(struct ip6_rthdr))
3036 			return (EINVAL);
3037 		rth = (struct ip6_rthdr *)buf;
3038 		rthlen = (rth->ip6r_len + 1) << 3;
3039 		if (len != rthlen)
3040 			return (EINVAL);
3041 
3042 		switch (rth->ip6r_type) {
3043 		case IPV6_RTHDR_TYPE_0:
3044 			if (rth->ip6r_len == 0)	/* must contain one addr */
3045 				return (EINVAL);
3046 			if (rth->ip6r_len % 2) /* length must be even */
3047 				return (EINVAL);
3048 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
3049 				return (EINVAL);
3050 			break;
3051 		default:
3052 			return (EINVAL);	/* not supported */
3053 		}
3054 
3055 		/* turn off the previous option */
3056 		ip6_clearpktopts(opt, IPV6_RTHDR);
3057 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
3058 		if (opt->ip6po_rthdr == NULL)
3059 			return (ENOBUFS);
3060 		bcopy(rth, opt->ip6po_rthdr, rthlen);
3061 
3062 		break;
3063 	}
3064 
3065 	case IPV6_USE_MIN_MTU:
3066 		if (len != sizeof(int))
3067 			return (EINVAL);
3068 		minmtupolicy = *(int *)buf;
3069 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3070 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3071 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3072 			return (EINVAL);
3073 		}
3074 		opt->ip6po_minmtu = minmtupolicy;
3075 		break;
3076 
3077 	case IPV6_DONTFRAG:
3078 		if (len != sizeof(int))
3079 			return (EINVAL);
3080 
3081 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3082 			/*
3083 			 * we ignore this option for TCP sockets.
3084 			 * (RFC3542 leaves this case unspecified.)
3085 			 */
3086 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3087 		} else
3088 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3089 		break;
3090 
3091 	case IPV6_PREFER_TEMPADDR:
3092 		if (len != sizeof(int))
3093 			return (EINVAL);
3094 		preftemp = *(int *)buf;
3095 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
3096 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
3097 		    preftemp != IP6PO_TEMPADDR_PREFER) {
3098 			return (EINVAL);
3099 		}
3100 		opt->ip6po_prefer_tempaddr = preftemp;
3101 		break;
3102 
3103 	default:
3104 		return (ENOPROTOOPT);
3105 	} /* end of switch */
3106 
3107 	return (0);
3108 }
3109 
3110 /*
3111  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3112  * packet to the input queue of a specified interface.  Note that this
3113  * calls the output routine of the loopback "driver", but with an interface
3114  * pointer that might NOT be &loif -- easier than replicating that code here.
3115  */
3116 void
3117 ip6_mloopback(struct ifnet *ifp, struct mbuf *m)
3118 {
3119 	struct mbuf *copym;
3120 	struct ip6_hdr *ip6;
3121 
3122 	copym = m_copym(m, 0, M_COPYALL, M_NOWAIT);
3123 	if (copym == NULL)
3124 		return;
3125 
3126 	/*
3127 	 * Make sure to deep-copy IPv6 header portion in case the data
3128 	 * is in an mbuf cluster, so that we can safely override the IPv6
3129 	 * header portion later.
3130 	 */
3131 	if (!M_WRITABLE(copym) ||
3132 	    copym->m_len < sizeof(struct ip6_hdr)) {
3133 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3134 		if (copym == NULL)
3135 			return;
3136 	}
3137 	ip6 = mtod(copym, struct ip6_hdr *);
3138 	/*
3139 	 * clear embedded scope identifiers if necessary.
3140 	 * in6_clearscope will touch the addresses only when necessary.
3141 	 */
3142 	in6_clearscope(&ip6->ip6_src);
3143 	in6_clearscope(&ip6->ip6_dst);
3144 	if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
3145 		copym->m_pkthdr.csum_flags |= CSUM_DATA_VALID_IPV6 |
3146 		    CSUM_PSEUDO_HDR;
3147 		copym->m_pkthdr.csum_data = 0xffff;
3148 	}
3149 	if_simloop(ifp, copym, AF_INET6, 0);
3150 }
3151 
3152 /*
3153  * Chop IPv6 header off from the payload.
3154  */
3155 static int
3156 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
3157 {
3158 	struct mbuf *mh;
3159 	struct ip6_hdr *ip6;
3160 
3161 	ip6 = mtod(m, struct ip6_hdr *);
3162 	if (m->m_len > sizeof(*ip6)) {
3163 		mh = m_gethdr(M_NOWAIT, MT_DATA);
3164 		if (mh == NULL) {
3165 			m_freem(m);
3166 			return ENOBUFS;
3167 		}
3168 		m_move_pkthdr(mh, m);
3169 		M_ALIGN(mh, sizeof(*ip6));
3170 		m->m_len -= sizeof(*ip6);
3171 		m->m_data += sizeof(*ip6);
3172 		mh->m_next = m;
3173 		m = mh;
3174 		m->m_len = sizeof(*ip6);
3175 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
3176 	}
3177 	exthdrs->ip6e_ip6 = m;
3178 	return 0;
3179 }
3180 
3181 /*
3182  * Compute IPv6 extension header length.
3183  */
3184 int
3185 ip6_optlen(struct inpcb *inp)
3186 {
3187 	int len;
3188 
3189 	if (!inp->in6p_outputopts)
3190 		return 0;
3191 
3192 	len = 0;
3193 #define elen(x) \
3194     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3195 
3196 	len += elen(inp->in6p_outputopts->ip6po_hbh);
3197 	if (inp->in6p_outputopts->ip6po_rthdr)
3198 		/* dest1 is valid with rthdr only */
3199 		len += elen(inp->in6p_outputopts->ip6po_dest1);
3200 	len += elen(inp->in6p_outputopts->ip6po_rthdr);
3201 	len += elen(inp->in6p_outputopts->ip6po_dest2);
3202 	return len;
3203 #undef elen
3204 }
3205