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