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