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