]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/frag6.c
MFC r346535 (by hselasky):
[FreeBSD/FreeBSD.git] / sys / netinet6 / frag6.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  * Copyright (c) 2019 Netflix, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      $KAME: frag6.c,v 1.33 2002/01/07 11:34:48 kjc Exp $
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_rss.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/domain.h>
43 #include <sys/eventhandler.h>
44 #include <sys/hash.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/kernel.h>
49 #include <sys/protosw.h>
50 #include <sys/queue.h>
51 #include <sys/socket.h>
52 #include <sys/sysctl.h>
53 #include <sys/syslog.h>
54
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/netisr.h>
58 #include <net/route.h>
59 #include <net/vnet.h>
60
61 #include <netinet/in.h>
62 #include <netinet/in_var.h>
63 #include <netinet/ip6.h>
64 #include <netinet6/ip6_var.h>
65 #include <netinet/icmp6.h>
66 #include <netinet/in_systm.h>   /* For ECN definitions. */
67 #include <netinet/ip.h>         /* For ECN definitions. */
68
69 #ifdef MAC
70 #include <security/mac/mac_framework.h>
71 #endif
72
73 /*
74  * A "big picture" of how IPv6 fragment queues are all linked together.
75  *
76  * struct ip6qbucket ip6qb[...];                        hashed buckets
77  * ||||||||
78  * |
79  * +--- TAILQ(struct ip6q, packets) *q6;                tailq entries holding
80  *      ||||||||                                        fragmented packets
81  *      |                                               (1 per original packet)
82  *      |
83  *      +--- TAILQ(struct ip6asfrag, ip6q_frags) *af6;  tailq entries of IPv6
84  *           |                                   *ip6af;fragment packets
85  *           |                                          for one original packet
86  *           + *mbuf
87  */
88
89 /* Reassembly headers are stored in hash buckets. */
90 #define IP6REASS_NHASH_LOG2     10
91 #define IP6REASS_NHASH          (1 << IP6REASS_NHASH_LOG2)
92 #define IP6REASS_HMASK          (IP6REASS_NHASH - 1)
93
94 TAILQ_HEAD(ip6qhead, ip6q);
95 struct ip6qbucket {
96         struct ip6qhead packets;
97         struct mtx      lock;
98         int             count;
99 };
100
101 struct ip6asfrag {
102         TAILQ_ENTRY(ip6asfrag) ip6af_tq;
103         struct mbuf     *ip6af_m;
104         int             ip6af_offset;   /* Offset in ip6af_m to next header. */
105         int             ip6af_frglen;   /* Fragmentable part length. */
106         int             ip6af_off;      /* Fragment offset. */
107         bool            ip6af_mff;      /* More fragment bit in frag off. */
108 };
109
110 static MALLOC_DEFINE(M_FRAG6, "frag6", "IPv6 fragment reassembly header");
111
112 #ifdef VIMAGE
113 /* A flag to indicate if IPv6 fragmentation is initialized. */
114 VNET_DEFINE_STATIC(bool,                frag6_on);
115 #define V_frag6_on                      VNET(frag6_on)
116 #endif
117
118 /* System wide (global) maximum and count of packets in reassembly queues. */
119 static int ip6_maxfrags;
120 static volatile u_int frag6_nfrags = 0;
121
122 /* Maximum and current packets in per-VNET reassembly queue. */
123 VNET_DEFINE_STATIC(int,                 ip6_maxfragpackets);
124 VNET_DEFINE_STATIC(volatile u_int,      frag6_nfragpackets);
125 #define V_ip6_maxfragpackets            VNET(ip6_maxfragpackets)
126 #define V_frag6_nfragpackets            VNET(frag6_nfragpackets)
127
128 /* Maximum per-VNET reassembly queues per bucket and fragments per packet. */
129 VNET_DEFINE_STATIC(int,                 ip6_maxfragbucketsize);
130 VNET_DEFINE_STATIC(int,                 ip6_maxfragsperpacket);
131 #define V_ip6_maxfragbucketsize         VNET(ip6_maxfragbucketsize)
132 #define V_ip6_maxfragsperpacket         VNET(ip6_maxfragsperpacket)
133
134 /* Per-VNET reassembly queue buckets. */
135 VNET_DEFINE_STATIC(struct ip6qbucket,   ip6qb[IP6REASS_NHASH]);
136 VNET_DEFINE_STATIC(uint32_t,            ip6qb_hashseed);
137 #define V_ip6qb                         VNET(ip6qb)
138 #define V_ip6qb_hashseed                VNET(ip6qb_hashseed)
139
140 #define IP6QB_LOCK(_b)          mtx_lock(&V_ip6qb[(_b)].lock)
141 #define IP6QB_TRYLOCK(_b)       mtx_trylock(&V_ip6qb[(_b)].lock)
142 #define IP6QB_LOCK_ASSERT(_b)   mtx_assert(&V_ip6qb[(_b)].lock, MA_OWNED)
143 #define IP6QB_UNLOCK(_b)        mtx_unlock(&V_ip6qb[(_b)].lock)
144 #define IP6QB_HEAD(_b)          (&V_ip6qb[(_b)].packets)
145
146 /*
147  * By default, limit the number of IP6 fragments across all reassembly
148  * queues to  1/32 of the total number of mbuf clusters.
149  *
150  * Limit the total number of reassembly queues per VNET to the
151  * IP6 fragment limit, but ensure the limit will not allow any bucket
152  * to grow above 100 items. (The bucket limit is
153  * IP_MAXFRAGPACKETS / (IPREASS_NHASH / 2), so the 50 is the correct
154  * multiplier to reach a 100-item limit.)
155  * The 100-item limit was chosen as brief testing seems to show that
156  * this produces "reasonable" performance on some subset of systems
157  * under DoS attack.
158  */
159 #define IP6_MAXFRAGS            (nmbclusters / 32)
160 #define IP6_MAXFRAGPACKETS      (imin(IP6_MAXFRAGS, IP6REASS_NHASH * 50))
161
162
163 /*
164  * Sysctls and helper function.
165  */
166 SYSCTL_DECL(_net_inet6_ip6);
167
168 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfrags,
169         CTLFLAG_RD, __DEVOLATILE(u_int *, &frag6_nfrags), 0,
170         "Global number of IPv6 fragments across all reassembly queues.");
171
172 static void
173 frag6_set_bucketsize(void)
174 {
175         int i;
176
177         if ((i = V_ip6_maxfragpackets) > 0)
178                 V_ip6_maxfragbucketsize = imax(i / (IP6REASS_NHASH / 2), 1);
179 }
180
181 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGS, maxfrags,
182         CTLFLAG_RW, &ip6_maxfrags, 0,
183         "Maximum allowed number of outstanding IPv6 packet fragments. "
184         "A value of 0 means no fragmented packets will be accepted, while a "
185         "a value of -1 means no limit");
186
187 static int
188 sysctl_ip6_maxfragpackets(SYSCTL_HANDLER_ARGS)
189 {
190         int error, val;
191
192         val = V_ip6_maxfragpackets;
193         error = sysctl_handle_int(oidp, &val, 0, req);
194         if (error != 0 || !req->newptr)
195                 return (error);
196         V_ip6_maxfragpackets = val;
197         frag6_set_bucketsize();
198         return (0);
199 }
200 SYSCTL_PROC(_net_inet6_ip6, IPV6CTL_MAXFRAGPACKETS, maxfragpackets,
201         CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
202         sysctl_ip6_maxfragpackets, "I",
203         "Default maximum number of outstanding fragmented IPv6 packets. "
204         "A value of 0 means no fragmented packets will be accepted, while a "
205         "a value of -1 means no limit");
206 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfragpackets,
207         CTLFLAG_VNET | CTLFLAG_RD,
208         __DEVOLATILE(u_int *, &VNET_NAME(frag6_nfragpackets)), 0,
209         "Per-VNET number of IPv6 fragments across all reassembly queues.");
210 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGSPERPACKET, maxfragsperpacket,
211         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragsperpacket), 0,
212         "Maximum allowed number of fragments per packet");
213 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGBUCKETSIZE, maxfragbucketsize,
214         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragbucketsize), 0,
215         "Maximum number of reassembly queues per hash bucket");
216
217
218 /*
219  * Remove the IPv6 fragmentation header from the mbuf.
220  */
221 int
222 ip6_deletefraghdr(struct mbuf *m, int offset, int wait)
223 {
224         struct ip6_hdr *ip6;
225         struct mbuf *t;
226
227         /* Delete frag6 header. */
228         if (m->m_len >= offset + sizeof(struct ip6_frag)) {
229
230                 /* This is the only possible case with !PULLDOWN_TEST. */
231                 ip6 = mtod(m, struct ip6_hdr *);
232                 bcopy(ip6, (char *)ip6 + sizeof(struct ip6_frag),
233                     offset);
234                 m->m_data += sizeof(struct ip6_frag);
235                 m->m_len -= sizeof(struct ip6_frag);
236         } else {
237
238                 /* This comes with no copy if the boundary is on cluster. */
239                 if ((t = m_split(m, offset, wait)) == NULL)
240                         return (ENOMEM);
241                 m_adj(t, sizeof(struct ip6_frag));
242                 m_cat(m, t);
243         }
244
245         m->m_flags |= M_FRAGMENTED;
246         return (0);
247 }
248
249 /*
250  * Free a fragment reassembly header and all associated datagrams.
251  */
252 static void
253 frag6_freef(struct ip6q *q6, uint32_t bucket)
254 {
255         struct ip6_hdr *ip6;
256         struct ip6asfrag *af6;
257         struct mbuf *m;
258
259         IP6QB_LOCK_ASSERT(bucket);
260
261         while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
262
263                 m = af6->ip6af_m;
264                 TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
265
266                 /*
267                  * Return ICMP time exceeded error for the 1st fragment.
268                  * Just free other fragments.
269                  */
270                 if (af6->ip6af_off == 0 && m->m_pkthdr.rcvif != NULL) {
271
272                         /* Adjust pointer. */
273                         ip6 = mtod(m, struct ip6_hdr *);
274
275                         /* Restore source and destination addresses. */
276                         ip6->ip6_src = q6->ip6q_src;
277                         ip6->ip6_dst = q6->ip6q_dst;
278
279                         icmp6_error(m, ICMP6_TIME_EXCEEDED,
280                             ICMP6_TIME_EXCEED_REASSEMBLY, 0);
281                 } else
282                         m_freem(m);
283
284                 free(af6, M_FRAG6);
285         }
286
287         TAILQ_REMOVE(IP6QB_HEAD(bucket), q6, ip6q_tq);
288         V_ip6qb[bucket].count--;
289         atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
290 #ifdef MAC
291         mac_ip6q_destroy(q6);
292 #endif
293         free(q6, M_FRAG6);
294         atomic_subtract_int(&V_frag6_nfragpackets, 1);
295 }
296
297 /*
298  * Drain off all datagram fragments belonging to
299  * the given network interface.
300  */
301 static void
302 frag6_cleanup(void *arg __unused, struct ifnet *ifp)
303 {
304         struct ip6qhead *head;
305         struct ip6q *q6;
306         struct ip6asfrag *af6;
307         uint32_t bucket;
308
309         KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
310
311         CURVNET_SET_QUIET(ifp->if_vnet);
312 #ifdef VIMAGE
313         /*
314          * Skip processing if IPv6 reassembly is not initialised or
315          * torn down by frag6_destroy().
316          */
317         if (!V_frag6_on) {
318                 CURVNET_RESTORE();
319                 return;
320         }
321 #endif
322
323         for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
324                 IP6QB_LOCK(bucket);
325                 head = IP6QB_HEAD(bucket);
326                 /* Scan fragment list. */
327                 TAILQ_FOREACH(q6, head, ip6q_tq) {
328                         TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
329
330                                 /* Clear no longer valid rcvif pointer. */
331                                 if (af6->ip6af_m->m_pkthdr.rcvif == ifp)
332                                         af6->ip6af_m->m_pkthdr.rcvif = NULL;
333                         }
334                 }
335                 IP6QB_UNLOCK(bucket);
336         }
337         CURVNET_RESTORE();
338 }
339 EVENTHANDLER_DEFINE(ifnet_departure_event, frag6_cleanup, NULL, 0);
340
341 /*
342  * Like in RFC2460, in RFC8200, fragment and reassembly rules do not agree with
343  * each other, in terms of next header field handling in fragment header.
344  * While the sender will use the same value for all of the fragmented packets,
345  * receiver is suggested not to check for consistency.
346  *
347  * Fragment rules (p18,p19):
348  *      (2)  A Fragment header containing:
349  *      The Next Header value that identifies the first header
350  *      after the Per-Fragment headers of the original packet.
351  *              -> next header field is same for all fragments
352  *
353  * Reassembly rule (p20):
354  *      The Next Header field of the last header of the Per-Fragment
355  *      headers is obtained from the Next Header field of the first
356  *      fragment's Fragment header.
357  *              -> should grab it from the first fragment only
358  *
359  * The following note also contradicts with fragment rule - no one is going to
360  * send different fragment with different next header field.
361  *
362  * Additional note (p22) [not an error]:
363  *      The Next Header values in the Fragment headers of different
364  *      fragments of the same original packet may differ.  Only the value
365  *      from the Offset zero fragment packet is used for reassembly.
366  *              -> should grab it from the first fragment only
367  *
368  * There is no explicit reason given in the RFC.  Historical reason maybe?
369  */
370 /*
371  * Fragment input.
372  */
373 int
374 frag6_input(struct mbuf **mp, int *offp, int proto)
375 {
376         struct mbuf *m, *t;
377         struct ip6_hdr *ip6;
378         struct ip6_frag *ip6f;
379         struct ip6qhead *head;
380         struct ip6q *q6;
381         struct ip6asfrag *af6, *ip6af, *af6tmp;
382         struct in6_ifaddr *ia6;
383         struct ifnet *dstifp, *srcifp;
384         uint32_t hashkey[(sizeof(struct in6_addr) * 2 +
385                     sizeof(ip6f->ip6f_ident)) / sizeof(uint32_t)];
386         uint32_t bucket, *hashkeyp;
387         int fragoff, frgpartlen;        /* Must be larger than uint16_t. */
388         int nxt, offset, plen;
389         uint8_t ecn, ecn0;
390         bool only_frag;
391 #ifdef RSS
392         struct ip6_direct_ctx *ip6dc;
393         struct m_tag *mtag;
394 #endif
395
396         m = *mp;
397         offset = *offp;
398
399         ip6 = mtod(m, struct ip6_hdr *);
400 #ifndef PULLDOWN_TEST
401         IP6_EXTHDR_CHECK(m, offset, sizeof(struct ip6_frag), IPPROTO_DONE);
402         ip6f = (struct ip6_frag *)((caddr_t)ip6 + offset);
403 #else
404         IP6_EXTHDR_GET(ip6f, struct ip6_frag *, m, offset, sizeof(*ip6f));
405         if (ip6f == NULL)
406                 return (IPPROTO_DONE);
407 #endif
408
409         dstifp = NULL;
410         /* Find the destination interface of the packet. */
411         ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
412         if (ia6 != NULL) {
413                 dstifp = ia6->ia_ifp;
414                 ifa_free(&ia6->ia_ifa);
415         }
416
417         /* Jumbo payload cannot contain a fragment header. */
418         if (ip6->ip6_plen == 0) {
419                 icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER, offset);
420                 in6_ifstat_inc(dstifp, ifs6_reass_fail);
421                 return (IPPROTO_DONE);
422         }
423
424         /*
425          * Check whether fragment packet's fragment length is a
426          * multiple of 8 octets (unless it is the last one).
427          * sizeof(struct ip6_frag) == 8
428          * sizeof(struct ip6_hdr) = 40
429          */
430         if ((ip6f->ip6f_offlg & IP6F_MORE_FRAG) &&
431             (((ntohs(ip6->ip6_plen) - offset) & 0x7) != 0)) {
432                 icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
433                     offsetof(struct ip6_hdr, ip6_plen));
434                 in6_ifstat_inc(dstifp, ifs6_reass_fail);
435                 return (IPPROTO_DONE);
436         }
437
438         IP6STAT_INC(ip6s_fragments);
439         in6_ifstat_inc(dstifp, ifs6_reass_reqd);
440
441         /* Offset now points to data portion. */
442         offset += sizeof(struct ip6_frag);
443
444         /*
445          * Handle "atomic" fragments (offset and m bit set to 0) upfront,
446          * unrelated to any reassembly.  Still need to remove the frag hdr.
447          * See RFC 6946 and section 4.5 of RFC 8200.
448          */
449         if ((ip6f->ip6f_offlg & ~IP6F_RESERVED_MASK) == 0) {
450                 /* XXX-BZ we want dedicated counters for this. */
451                 IP6STAT_INC(ip6s_reassembled);
452                 /* XXX-BZ handle correctly. */
453                 in6_ifstat_inc(dstifp, ifs6_reass_ok);
454                 *offp = offset;
455                 m->m_flags |= M_FRAGMENTED;
456                 return (ip6f->ip6f_nxt);
457         }
458
459         /* Get fragment length and discard 0-byte fragments. */
460         frgpartlen = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - offset;
461         if (frgpartlen == 0) {
462                 icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
463                     offsetof(struct ip6_hdr, ip6_plen));
464                 in6_ifstat_inc(dstifp, ifs6_reass_fail);
465                 IP6STAT_INC(ip6s_fragdropped);
466                 return (IPPROTO_DONE);
467         }
468
469         /*
470          * Enforce upper bound on number of fragments for the entire system.
471          * If maxfrag is 0, never accept fragments.
472          * If maxfrag is -1, accept all fragments without limitation.
473          */
474         if (ip6_maxfrags < 0)
475                 ;
476         else if (atomic_load_int(&frag6_nfrags) >= (u_int)ip6_maxfrags)
477                 goto dropfrag2;
478
479         /*
480          * Validate that a full header chain to the ULP is present in the
481          * packet containing the first fragment as per RFC RFC7112 and
482          * RFC 8200 pages 18,19:
483          * The first fragment packet is composed of:
484          * (3)  Extension headers, if any, and the Upper-Layer header.  These
485          *      headers must be in the first fragment.  ...
486          */
487         fragoff = ntohs(ip6f->ip6f_offlg & IP6F_OFF_MASK);
488         /* XXX TODO.  thj has D16851 open for this. */
489         /* Send ICMPv6 4,3 in case of violation. */
490
491         /* Store receive network interface pointer for later. */
492         srcifp = m->m_pkthdr.rcvif;
493
494         /* Generate a hash value for fragment bucket selection. */
495         hashkeyp = hashkey;
496         memcpy(hashkeyp, &ip6->ip6_src, sizeof(struct in6_addr));
497         hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
498         memcpy(hashkeyp, &ip6->ip6_dst, sizeof(struct in6_addr));
499         hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
500         *hashkeyp = ip6f->ip6f_ident;
501         bucket = jenkins_hash32(hashkey, nitems(hashkey), V_ip6qb_hashseed);
502         bucket &= IP6REASS_HMASK;
503         IP6QB_LOCK(bucket);
504         head = IP6QB_HEAD(bucket);
505
506         TAILQ_FOREACH(q6, head, ip6q_tq)
507                 if (ip6f->ip6f_ident == q6->ip6q_ident &&
508                     IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &q6->ip6q_src) &&
509                     IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &q6->ip6q_dst)
510 #ifdef MAC
511                     && mac_ip6q_match(m, q6)
512 #endif
513                     )
514                         break;
515
516         only_frag = false;
517         if (q6 == NULL) {
518
519                 /* A first fragment to arrive creates a reassembly queue. */
520                 only_frag = true;
521
522                 /*
523                  * Enforce upper bound on number of fragmented packets
524                  * for which we attempt reassembly;
525                  * If maxfragpackets is 0, never accept fragments.
526                  * If maxfragpackets is -1, accept all fragments without
527                  * limitation.
528                  */
529                 if (V_ip6_maxfragpackets < 0)
530                         ;
531                 else if (V_ip6qb[bucket].count >= V_ip6_maxfragbucketsize ||
532                     atomic_load_int(&V_frag6_nfragpackets) >=
533                     (u_int)V_ip6_maxfragpackets)
534                         goto dropfrag;
535
536                 /* Allocate IPv6 fragement packet queue entry. */
537                 q6 = (struct ip6q *)malloc(sizeof(struct ip6q), M_FRAG6,
538                     M_NOWAIT | M_ZERO);
539                 if (q6 == NULL)
540                         goto dropfrag;
541 #ifdef MAC
542                 if (mac_ip6q_init(q6, M_NOWAIT) != 0) {
543                         free(q6, M_FRAG6);
544                         goto dropfrag;
545                 }
546                 mac_ip6q_create(m, q6);
547 #endif
548                 atomic_add_int(&V_frag6_nfragpackets, 1);
549
550                 /* ip6q_nxt will be filled afterwards, from 1st fragment. */
551                 TAILQ_INIT(&q6->ip6q_frags);
552                 q6->ip6q_ident  = ip6f->ip6f_ident;
553                 q6->ip6q_ttl    = IPV6_FRAGTTL;
554                 q6->ip6q_src    = ip6->ip6_src;
555                 q6->ip6q_dst    = ip6->ip6_dst;
556                 q6->ip6q_ecn    =
557                     (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
558                 q6->ip6q_unfrglen = -1; /* The 1st fragment has not arrived. */
559
560                 /* Add the fragemented packet to the bucket. */
561                 TAILQ_INSERT_HEAD(head, q6, ip6q_tq);
562                 V_ip6qb[bucket].count++;
563         }
564
565         /*
566          * If it is the 1st fragment, record the length of the
567          * unfragmentable part and the next header of the fragment header.
568          * Assume the first 1st fragement to arrive will be correct.
569          * We do not have any duplicate checks here yet so another packet
570          * with fragoff == 0 could come and overwrite the ip6q_unfrglen
571          * and worse, the next header, at any time.
572          */
573         if (fragoff == 0 && q6->ip6q_unfrglen == -1) {
574                 q6->ip6q_unfrglen = offset - sizeof(struct ip6_hdr) -
575                     sizeof(struct ip6_frag);
576                 q6->ip6q_nxt = ip6f->ip6f_nxt;
577                 /* XXX ECN? */
578         }
579
580         /*
581          * Check that the reassembled packet would not exceed 65535 bytes
582          * in size.
583          * If it would exceed, discard the fragment and return an ICMP error.
584          */
585         if (q6->ip6q_unfrglen >= 0) {
586                 /* The 1st fragment has already arrived. */
587                 if (q6->ip6q_unfrglen + fragoff + frgpartlen > IPV6_MAXPACKET) {
588                         if (only_frag) {
589                                 TAILQ_REMOVE(head, q6, ip6q_tq);
590                                 V_ip6qb[bucket].count--;
591                                 atomic_subtract_int(&V_frag6_nfragpackets, 1);
592 #ifdef MAC
593                                 mac_ip6q_destroy(q6);
594 #endif
595                                 free(q6, M_FRAG6);
596                         }
597                         IP6QB_UNLOCK(bucket);
598                         icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
599                             offset - sizeof(struct ip6_frag) +
600                             offsetof(struct ip6_frag, ip6f_offlg));
601                         return (IPPROTO_DONE);
602                 }
603         } else if (fragoff + frgpartlen > IPV6_MAXPACKET) {
604                 if (only_frag) {
605                         TAILQ_REMOVE(head, q6, ip6q_tq);
606                         V_ip6qb[bucket].count--;
607                         atomic_subtract_int(&V_frag6_nfragpackets, 1);
608 #ifdef MAC
609                         mac_ip6q_destroy(q6);
610 #endif
611                         free(q6, M_FRAG6);
612                 }
613                 IP6QB_UNLOCK(bucket);
614                 icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
615                     offset - sizeof(struct ip6_frag) +
616                     offsetof(struct ip6_frag, ip6f_offlg));
617                 return (IPPROTO_DONE);
618         }
619
620         /*
621          * If it is the first fragment, do the above check for each
622          * fragment already stored in the reassembly queue.
623          */
624         if (fragoff == 0 && !only_frag) {
625                 TAILQ_FOREACH_SAFE(af6, &q6->ip6q_frags, ip6af_tq, af6tmp) {
626
627                         if (q6->ip6q_unfrglen + af6->ip6af_off +
628                             af6->ip6af_frglen > IPV6_MAXPACKET) {
629                                 struct ip6_hdr *ip6err;
630                                 struct mbuf *merr;
631                                 int erroff;
632
633                                 merr = af6->ip6af_m;
634                                 erroff = af6->ip6af_offset;
635
636                                 /* Dequeue the fragment. */
637                                 TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
638                                 q6->ip6q_nfrag--;
639                                 atomic_subtract_int(&frag6_nfrags, 1);
640                                 free(af6, M_FRAG6);
641
642                                 /* Set a valid receive interface pointer. */
643                                 merr->m_pkthdr.rcvif = srcifp;
644
645                                 /* Adjust pointer. */
646                                 ip6err = mtod(merr, struct ip6_hdr *);
647
648                                 /*
649                                  * Restore source and destination addresses
650                                  * in the erroneous IPv6 header.
651                                  */
652                                 ip6err->ip6_src = q6->ip6q_src;
653                                 ip6err->ip6_dst = q6->ip6q_dst;
654
655                                 icmp6_error(merr, ICMP6_PARAM_PROB,
656                                     ICMP6_PARAMPROB_HEADER,
657                                     erroff - sizeof(struct ip6_frag) +
658                                     offsetof(struct ip6_frag, ip6f_offlg));
659                         }
660                 }
661         }
662
663         /* Allocate an IPv6 fragement queue entry for this fragmented part. */
664         ip6af = (struct ip6asfrag *)malloc(sizeof(struct ip6asfrag), M_FRAG6,
665             M_NOWAIT | M_ZERO);
666         if (ip6af == NULL)
667                 goto dropfrag;
668         ip6af->ip6af_mff = (ip6f->ip6f_offlg & IP6F_MORE_FRAG) ? true : false;
669         ip6af->ip6af_off = fragoff;
670         ip6af->ip6af_frglen = frgpartlen;
671         ip6af->ip6af_offset = offset;
672         ip6af->ip6af_m = m;
673
674         if (only_frag) {
675                 /*
676                  * Do a manual insert rather than a hard-to-understand cast
677                  * to a different type relying on data structure order to work.
678                  */
679                 TAILQ_INSERT_HEAD(&q6->ip6q_frags, ip6af, ip6af_tq);
680                 goto postinsert;
681         }
682
683         /* Do duplicate, condition, and boundry checks. */
684         /*
685          * Handle ECN by comparing this segment with the first one;
686          * if CE is set, do not lose CE.
687          * Drop if CE and not-ECT are mixed for the same packet.
688          */
689         ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
690         ecn0 = q6->ip6q_ecn;
691         if (ecn == IPTOS_ECN_CE) {
692                 if (ecn0 == IPTOS_ECN_NOTECT) {
693                         free(ip6af, M_FRAG6);
694                         goto dropfrag;
695                 }
696                 if (ecn0 != IPTOS_ECN_CE)
697                         q6->ip6q_ecn = IPTOS_ECN_CE;
698         }
699         if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
700                 free(ip6af, M_FRAG6);
701                 goto dropfrag;
702         }
703
704         /* Find a fragmented part which begins after this one does. */
705         TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq)
706                 if (af6->ip6af_off > ip6af->ip6af_off)
707                         break;
708
709         /*
710          * If the incoming framgent overlaps some existing fragments in
711          * the reassembly queue, drop both the new fragment and the
712          * entire reassembly queue.  However, if the new fragment
713          * is an exact duplicate of an existing fragment, only silently
714          * drop the existing fragment and leave the fragmentation queue
715          * unchanged, as allowed by the RFC.  (RFC 8200, 4.5)
716          */
717         if (af6 != NULL)
718                 af6tmp = TAILQ_PREV(af6, ip6fraghead, ip6af_tq);
719         else
720                 af6tmp = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
721         if (af6tmp != NULL) {
722                 if (af6tmp->ip6af_off + af6tmp->ip6af_frglen -
723                     ip6af->ip6af_off > 0) {
724                         if (af6tmp->ip6af_off != ip6af->ip6af_off ||
725                             af6tmp->ip6af_frglen != ip6af->ip6af_frglen)
726                                 frag6_freef(q6, bucket);
727                         free(ip6af, M_FRAG6);
728                         goto dropfrag;
729                 }
730         }
731         if (af6 != NULL) {
732                 if (ip6af->ip6af_off + ip6af->ip6af_frglen -
733                     af6->ip6af_off > 0) {
734                         if (af6->ip6af_off != ip6af->ip6af_off ||
735                             af6->ip6af_frglen != ip6af->ip6af_frglen)
736                                 frag6_freef(q6, bucket);
737                         free(ip6af, M_FRAG6);
738                         goto dropfrag;
739                 }
740         }
741
742 #ifdef MAC
743         mac_ip6q_update(m, q6);
744 #endif
745
746         /*
747          * Stick new segment in its place; check for complete reassembly.
748          * If not complete, check fragment limit.  Move to front of packet
749          * queue, as we are the most recently active fragmented packet.
750          */
751         if (af6 != NULL)
752                 TAILQ_INSERT_BEFORE(af6, ip6af, ip6af_tq);
753         else
754                 TAILQ_INSERT_TAIL(&q6->ip6q_frags, ip6af, ip6af_tq);
755 postinsert:
756         atomic_add_int(&frag6_nfrags, 1);
757         q6->ip6q_nfrag++;
758
759         plen = 0;
760         TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
761                 if (af6->ip6af_off != plen) {
762                         if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
763                                 IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
764                                 frag6_freef(q6, bucket);
765                         }
766                         IP6QB_UNLOCK(bucket);
767                         return (IPPROTO_DONE);
768                 }
769                 plen += af6->ip6af_frglen;
770         }
771         af6 = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
772         if (af6->ip6af_mff) {
773                 if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
774                         IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
775                         frag6_freef(q6, bucket);
776                 }
777                 IP6QB_UNLOCK(bucket);
778                 return (IPPROTO_DONE);
779         }
780
781         /* Reassembly is complete; concatenate fragments. */
782         ip6af = TAILQ_FIRST(&q6->ip6q_frags);
783         t = m = ip6af->ip6af_m;
784         TAILQ_REMOVE(&q6->ip6q_frags, ip6af, ip6af_tq);
785         while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
786                 m->m_pkthdr.csum_flags &=
787                     af6->ip6af_m->m_pkthdr.csum_flags;
788                 m->m_pkthdr.csum_data +=
789                     af6->ip6af_m->m_pkthdr.csum_data;
790
791                 TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
792                 t = m_last(t);
793                 m_adj(af6->ip6af_m, af6->ip6af_offset);
794                 m_demote_pkthdr(af6->ip6af_m);
795                 m_cat(t, af6->ip6af_m);
796                 free(af6, M_FRAG6);
797         }
798
799         while (m->m_pkthdr.csum_data & 0xffff0000)
800                 m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
801                     (m->m_pkthdr.csum_data >> 16);
802
803         /* Adjust offset to point where the original next header starts. */
804         offset = ip6af->ip6af_offset - sizeof(struct ip6_frag);
805         free(ip6af, M_FRAG6);
806         ip6 = mtod(m, struct ip6_hdr *);
807         ip6->ip6_plen = htons((u_short)plen + offset - sizeof(struct ip6_hdr));
808         if (q6->ip6q_ecn == IPTOS_ECN_CE)
809                 ip6->ip6_flow |= htonl(IPTOS_ECN_CE << 20);
810         nxt = q6->ip6q_nxt;
811
812         TAILQ_REMOVE(head, q6, ip6q_tq);
813         V_ip6qb[bucket].count--;
814         atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
815
816         if (ip6_deletefraghdr(m, offset, M_NOWAIT) != 0) {
817 #ifdef MAC
818                 mac_ip6q_destroy(q6);
819 #endif
820                 free(q6, M_FRAG6);
821                 atomic_subtract_int(&V_frag6_nfragpackets, 1);
822
823                 goto dropfrag;
824         }
825
826         /* Set nxt(-hdr field value) to the original value. */
827         m_copyback(m, ip6_get_prevhdr(m, offset), sizeof(uint8_t),
828             (caddr_t)&nxt);
829
830 #ifdef MAC
831         mac_ip6q_reassemble(q6, m);
832         mac_ip6q_destroy(q6);
833 #endif
834         free(q6, M_FRAG6);
835         atomic_subtract_int(&V_frag6_nfragpackets, 1);
836
837         if (m->m_flags & M_PKTHDR) { /* Isn't it always true? */
838
839                 plen = 0;
840                 for (t = m; t; t = t->m_next)
841                         plen += t->m_len;
842                 m->m_pkthdr.len = plen;
843                 /* Set a valid receive interface pointer. */
844                 m->m_pkthdr.rcvif = srcifp;
845         }
846
847 #ifdef RSS
848         mtag = m_tag_alloc(MTAG_ABI_IPV6, IPV6_TAG_DIRECT, sizeof(*ip6dc),
849             M_NOWAIT);
850         if (mtag == NULL)
851                 goto dropfrag;
852
853         ip6dc = (struct ip6_direct_ctx *)(mtag + 1);
854         ip6dc->ip6dc_nxt = nxt;
855         ip6dc->ip6dc_off = offset;
856
857         m_tag_prepend(m, mtag);
858 #endif
859
860         IP6QB_UNLOCK(bucket);
861         IP6STAT_INC(ip6s_reassembled);
862         in6_ifstat_inc(dstifp, ifs6_reass_ok);
863
864 #ifdef RSS
865         /* Queue/dispatch for reprocessing. */
866         netisr_dispatch(NETISR_IPV6_DIRECT, m);
867         return (IPPROTO_DONE);
868 #endif
869
870         /* Tell launch routine the next header. */
871         *mp = m;
872         *offp = offset;
873
874         return (nxt);
875
876 dropfrag:
877         IP6QB_UNLOCK(bucket);
878 dropfrag2:
879         in6_ifstat_inc(dstifp, ifs6_reass_fail);
880         IP6STAT_INC(ip6s_fragdropped);
881         m_freem(m);
882         return (IPPROTO_DONE);
883 }
884
885 /*
886  * IPv6 reassembling timer processing;
887  * if a timer expires on a reassembly queue, discard it.
888  */
889 void
890 frag6_slowtimo(void)
891 {
892         VNET_ITERATOR_DECL(vnet_iter);
893         struct ip6qhead *head;
894         struct ip6q *q6, *q6tmp;
895         uint32_t bucket;
896
897         VNET_LIST_RLOCK_NOSLEEP();
898         VNET_FOREACH(vnet_iter) {
899                 CURVNET_SET(vnet_iter);
900                 for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
901                         IP6QB_LOCK(bucket);
902                         head = IP6QB_HEAD(bucket);
903                         TAILQ_FOREACH_SAFE(q6, head, ip6q_tq, q6tmp)
904                                 if (--q6->ip6q_ttl == 0) {
905                                         IP6STAT_ADD(ip6s_fragtimeout,
906                                                 q6->ip6q_nfrag);
907                                         /* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
908                                         frag6_freef(q6, bucket);
909                                 }
910                         /*
911                          * If we are over the maximum number of fragments
912                          * (due to the limit being lowered), drain off
913                          * enough to get down to the new limit.
914                          * Note that we drain all reassembly queues if
915                          * maxfragpackets is 0 (fragmentation is disabled),
916                          * and do not enforce a limit when maxfragpackets
917                          * is negative.
918                          */
919                         while ((V_ip6_maxfragpackets == 0 ||
920                             (V_ip6_maxfragpackets > 0 &&
921                             V_ip6qb[bucket].count > V_ip6_maxfragbucketsize)) &&
922                             (q6 = TAILQ_LAST(head, ip6qhead)) != NULL) {
923                                 IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
924                                 /* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
925                                 frag6_freef(q6, bucket);
926                         }
927                         IP6QB_UNLOCK(bucket);
928                 }
929                 /*
930                  * If we are still over the maximum number of fragmented
931                  * packets, drain off enough to get down to the new limit.
932                  */
933                 bucket = 0;
934                 while (V_ip6_maxfragpackets >= 0 &&
935                     atomic_load_int(&V_frag6_nfragpackets) >
936                     (u_int)V_ip6_maxfragpackets) {
937                         IP6QB_LOCK(bucket);
938                         q6 = TAILQ_LAST(IP6QB_HEAD(bucket), ip6qhead);
939                         if (q6 != NULL) {
940                                 IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
941                                 /* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
942                                 frag6_freef(q6, bucket);
943                         }
944                         IP6QB_UNLOCK(bucket);
945                         bucket = (bucket + 1) % IP6REASS_NHASH;
946                 }
947                 CURVNET_RESTORE();
948         }
949         VNET_LIST_RUNLOCK_NOSLEEP();
950 }
951
952 /*
953  * Eventhandler to adjust limits in case nmbclusters change.
954  */
955 static void
956 frag6_change(void *tag)
957 {
958         VNET_ITERATOR_DECL(vnet_iter);
959
960         ip6_maxfrags = IP6_MAXFRAGS;
961         VNET_LIST_RLOCK_NOSLEEP();
962         VNET_FOREACH(vnet_iter) {
963                 CURVNET_SET(vnet_iter);
964                 V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
965                 frag6_set_bucketsize();
966                 CURVNET_RESTORE();
967         }
968         VNET_LIST_RUNLOCK_NOSLEEP();
969 }
970
971 /*
972  * Initialise reassembly queue and fragment identifier.
973  */
974 void
975 frag6_init(void)
976 {
977         uint32_t bucket;
978
979         V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
980         frag6_set_bucketsize();
981         for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
982                 TAILQ_INIT(IP6QB_HEAD(bucket));
983                 mtx_init(&V_ip6qb[bucket].lock, "ip6qb", NULL, MTX_DEF);
984                 V_ip6qb[bucket].count = 0;
985         }
986         V_ip6qb_hashseed = arc4random();
987         V_ip6_maxfragsperpacket = 64;
988 #ifdef VIMAGE
989         V_frag6_on = true;
990 #endif
991         if (!IS_DEFAULT_VNET(curvnet))
992                 return;
993
994         ip6_maxfrags = IP6_MAXFRAGS;
995         EVENTHANDLER_REGISTER(nmbclusters_change,
996             frag6_change, NULL, EVENTHANDLER_PRI_ANY);
997 }
998
999 /*
1000  * Drain off all datagram fragments.
1001  */
1002 static void
1003 frag6_drain_one(void)
1004 {
1005         struct ip6q *q6;
1006         uint32_t bucket;
1007
1008         for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1009                 IP6QB_LOCK(bucket);
1010                 while ((q6 = TAILQ_FIRST(IP6QB_HEAD(bucket))) != NULL) {
1011                         IP6STAT_INC(ip6s_fragdropped);
1012                         /* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
1013                         frag6_freef(q6, bucket);
1014                 }
1015                 IP6QB_UNLOCK(bucket);
1016         }
1017 }
1018
1019 void
1020 frag6_drain(void)
1021 {
1022         VNET_ITERATOR_DECL(vnet_iter);
1023
1024         VNET_LIST_RLOCK_NOSLEEP();
1025         VNET_FOREACH(vnet_iter) {
1026                 CURVNET_SET(vnet_iter);
1027                 frag6_drain_one();
1028                 CURVNET_RESTORE();
1029         }
1030         VNET_LIST_RUNLOCK_NOSLEEP();
1031 }
1032
1033 #ifdef VIMAGE
1034 /*
1035  * Clear up IPv6 reassembly structures.
1036  */
1037 void
1038 frag6_destroy(void)
1039 {
1040         uint32_t bucket;
1041
1042         frag6_drain_one();
1043         V_frag6_on = false;
1044         for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1045                 KASSERT(V_ip6qb[bucket].count == 0,
1046                     ("%s: V_ip6qb[%d] (%p) count not 0 (%d)", __func__,
1047                     bucket, &V_ip6qb[bucket], V_ip6qb[bucket].count));
1048                 mtx_destroy(&V_ip6qb[bucket].lock);
1049         }
1050 }
1051 #endif