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