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