OSDN Git Service

Merge tag 'vfio-v5.0-rc4' of git://github.com/awilliam/linux-vfio
[uclinux-h8/linux.git] / net / ipv4 / ip_fragment.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * INET         An implementation of the TCP/IP protocol suite for the LINUX
4  *              operating system.  INET is implemented using the  BSD Socket
5  *              interface as the means of communication with the user level.
6  *
7  *              The IP fragmentation functionality.
8  *
9  * Authors:     Fred N. van Kempen <waltje@uWalt.NL.Mugnet.ORG>
10  *              Alan Cox <alan@lxorguk.ukuu.org.uk>
11  *
12  * Fixes:
13  *              Alan Cox        :       Split from ip.c , see ip_input.c for history.
14  *              David S. Miller :       Begin massive cleanup...
15  *              Andi Kleen      :       Add sysctls.
16  *              xxxx            :       Overlapfrag bug.
17  *              Ultima          :       ip_expire() kernel panic.
18  *              Bill Hawes      :       Frag accounting and evictor fixes.
19  *              John McDonald   :       0 length frag bug.
20  *              Alexey Kuznetsov:       SMP races, threading, cleanup.
21  *              Patrick McHardy :       LRU queue of frag heads for evictor.
22  */
23
24 #define pr_fmt(fmt) "IPv4: " fmt
25
26 #include <linux/compiler.h>
27 #include <linux/module.h>
28 #include <linux/types.h>
29 #include <linux/mm.h>
30 #include <linux/jiffies.h>
31 #include <linux/skbuff.h>
32 #include <linux/list.h>
33 #include <linux/ip.h>
34 #include <linux/icmp.h>
35 #include <linux/netdevice.h>
36 #include <linux/jhash.h>
37 #include <linux/random.h>
38 #include <linux/slab.h>
39 #include <net/route.h>
40 #include <net/dst.h>
41 #include <net/sock.h>
42 #include <net/ip.h>
43 #include <net/icmp.h>
44 #include <net/checksum.h>
45 #include <net/inetpeer.h>
46 #include <net/inet_frag.h>
47 #include <linux/tcp.h>
48 #include <linux/udp.h>
49 #include <linux/inet.h>
50 #include <linux/netfilter_ipv4.h>
51 #include <net/inet_ecn.h>
52 #include <net/l3mdev.h>
53
54 /* NOTE. Logic of IP defragmentation is parallel to corresponding IPv6
55  * code now. If you change something here, _PLEASE_ update ipv6/reassembly.c
56  * as well. Or notify me, at least. --ANK
57  */
58 static const char ip_frag_cache_name[] = "ip4-frags";
59
60 /* Use skb->cb to track consecutive/adjacent fragments coming at
61  * the end of the queue. Nodes in the rb-tree queue will
62  * contain "runs" of one or more adjacent fragments.
63  *
64  * Invariants:
65  * - next_frag is NULL at the tail of a "run";
66  * - the head of a "run" has the sum of all fragment lengths in frag_run_len.
67  */
68 struct ipfrag_skb_cb {
69         struct inet_skb_parm    h;
70         struct sk_buff          *next_frag;
71         int                     frag_run_len;
72 };
73
74 #define FRAG_CB(skb)            ((struct ipfrag_skb_cb *)((skb)->cb))
75
76 static void ip4_frag_init_run(struct sk_buff *skb)
77 {
78         BUILD_BUG_ON(sizeof(struct ipfrag_skb_cb) > sizeof(skb->cb));
79
80         FRAG_CB(skb)->next_frag = NULL;
81         FRAG_CB(skb)->frag_run_len = skb->len;
82 }
83
84 /* Append skb to the last "run". */
85 static void ip4_frag_append_to_last_run(struct inet_frag_queue *q,
86                                         struct sk_buff *skb)
87 {
88         RB_CLEAR_NODE(&skb->rbnode);
89         FRAG_CB(skb)->next_frag = NULL;
90
91         FRAG_CB(q->last_run_head)->frag_run_len += skb->len;
92         FRAG_CB(q->fragments_tail)->next_frag = skb;
93         q->fragments_tail = skb;
94 }
95
96 /* Create a new "run" with the skb. */
97 static void ip4_frag_create_run(struct inet_frag_queue *q, struct sk_buff *skb)
98 {
99         if (q->last_run_head)
100                 rb_link_node(&skb->rbnode, &q->last_run_head->rbnode,
101                              &q->last_run_head->rbnode.rb_right);
102         else
103                 rb_link_node(&skb->rbnode, NULL, &q->rb_fragments.rb_node);
104         rb_insert_color(&skb->rbnode, &q->rb_fragments);
105
106         ip4_frag_init_run(skb);
107         q->fragments_tail = skb;
108         q->last_run_head = skb;
109 }
110
111 /* Describe an entry in the "incomplete datagrams" queue. */
112 struct ipq {
113         struct inet_frag_queue q;
114
115         u8              ecn; /* RFC3168 support */
116         u16             max_df_size; /* largest frag with DF set seen */
117         int             iif;
118         unsigned int    rid;
119         struct inet_peer *peer;
120 };
121
122 static u8 ip4_frag_ecn(u8 tos)
123 {
124         return 1 << (tos & INET_ECN_MASK);
125 }
126
127 static struct inet_frags ip4_frags;
128
129 static int ip_frag_reasm(struct ipq *qp, struct sk_buff *skb,
130                          struct sk_buff *prev_tail, struct net_device *dev);
131
132
133 static void ip4_frag_init(struct inet_frag_queue *q, const void *a)
134 {
135         struct ipq *qp = container_of(q, struct ipq, q);
136         struct netns_ipv4 *ipv4 = container_of(q->net, struct netns_ipv4,
137                                                frags);
138         struct net *net = container_of(ipv4, struct net, ipv4);
139
140         const struct frag_v4_compare_key *key = a;
141
142         q->key.v4 = *key;
143         qp->ecn = 0;
144         qp->peer = q->net->max_dist ?
145                 inet_getpeer_v4(net->ipv4.peers, key->saddr, key->vif, 1) :
146                 NULL;
147 }
148
149 static void ip4_frag_free(struct inet_frag_queue *q)
150 {
151         struct ipq *qp;
152
153         qp = container_of(q, struct ipq, q);
154         if (qp->peer)
155                 inet_putpeer(qp->peer);
156 }
157
158
159 /* Destruction primitives. */
160
161 static void ipq_put(struct ipq *ipq)
162 {
163         inet_frag_put(&ipq->q);
164 }
165
166 /* Kill ipq entry. It is not destroyed immediately,
167  * because caller (and someone more) holds reference count.
168  */
169 static void ipq_kill(struct ipq *ipq)
170 {
171         inet_frag_kill(&ipq->q);
172 }
173
174 static bool frag_expire_skip_icmp(u32 user)
175 {
176         return user == IP_DEFRAG_AF_PACKET ||
177                ip_defrag_user_in_between(user, IP_DEFRAG_CONNTRACK_IN,
178                                          __IP_DEFRAG_CONNTRACK_IN_END) ||
179                ip_defrag_user_in_between(user, IP_DEFRAG_CONNTRACK_BRIDGE_IN,
180                                          __IP_DEFRAG_CONNTRACK_BRIDGE_IN);
181 }
182
183 /*
184  * Oops, a fragment queue timed out.  Kill it and send an ICMP reply.
185  */
186 static void ip_expire(struct timer_list *t)
187 {
188         struct inet_frag_queue *frag = from_timer(frag, t, timer);
189         const struct iphdr *iph;
190         struct sk_buff *head = NULL;
191         struct net *net;
192         struct ipq *qp;
193         int err;
194
195         qp = container_of(frag, struct ipq, q);
196         net = container_of(qp->q.net, struct net, ipv4.frags);
197
198         rcu_read_lock();
199         spin_lock(&qp->q.lock);
200
201         if (qp->q.flags & INET_FRAG_COMPLETE)
202                 goto out;
203
204         ipq_kill(qp);
205         __IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS);
206         __IP_INC_STATS(net, IPSTATS_MIB_REASMTIMEOUT);
207
208         if (!(qp->q.flags & INET_FRAG_FIRST_IN))
209                 goto out;
210
211         /* sk_buff::dev and sk_buff::rbnode are unionized. So we
212          * pull the head out of the tree in order to be able to
213          * deal with head->dev.
214          */
215         if (qp->q.fragments) {
216                 head = qp->q.fragments;
217                 qp->q.fragments = head->next;
218         } else {
219                 head = skb_rb_first(&qp->q.rb_fragments);
220                 if (!head)
221                         goto out;
222                 if (FRAG_CB(head)->next_frag)
223                         rb_replace_node(&head->rbnode,
224                                         &FRAG_CB(head)->next_frag->rbnode,
225                                         &qp->q.rb_fragments);
226                 else
227                         rb_erase(&head->rbnode, &qp->q.rb_fragments);
228                 memset(&head->rbnode, 0, sizeof(head->rbnode));
229                 barrier();
230         }
231         if (head == qp->q.fragments_tail)
232                 qp->q.fragments_tail = NULL;
233
234         sub_frag_mem_limit(qp->q.net, head->truesize);
235
236         head->dev = dev_get_by_index_rcu(net, qp->iif);
237         if (!head->dev)
238                 goto out;
239
240
241         /* skb has no dst, perform route lookup again */
242         iph = ip_hdr(head);
243         err = ip_route_input_noref(head, iph->daddr, iph->saddr,
244                                            iph->tos, head->dev);
245         if (err)
246                 goto out;
247
248         /* Only an end host needs to send an ICMP
249          * "Fragment Reassembly Timeout" message, per RFC792.
250          */
251         if (frag_expire_skip_icmp(qp->q.key.v4.user) &&
252             (skb_rtable(head)->rt_type != RTN_LOCAL))
253                 goto out;
254
255         spin_unlock(&qp->q.lock);
256         icmp_send(head, ICMP_TIME_EXCEEDED, ICMP_EXC_FRAGTIME, 0);
257         goto out_rcu_unlock;
258
259 out:
260         spin_unlock(&qp->q.lock);
261 out_rcu_unlock:
262         rcu_read_unlock();
263         kfree_skb(head);
264         ipq_put(qp);
265 }
266
267 /* Find the correct entry in the "incomplete datagrams" queue for
268  * this IP datagram, and create new one, if nothing is found.
269  */
270 static struct ipq *ip_find(struct net *net, struct iphdr *iph,
271                            u32 user, int vif)
272 {
273         struct frag_v4_compare_key key = {
274                 .saddr = iph->saddr,
275                 .daddr = iph->daddr,
276                 .user = user,
277                 .vif = vif,
278                 .id = iph->id,
279                 .protocol = iph->protocol,
280         };
281         struct inet_frag_queue *q;
282
283         q = inet_frag_find(&net->ipv4.frags, &key);
284         if (!q)
285                 return NULL;
286
287         return container_of(q, struct ipq, q);
288 }
289
290 /* Is the fragment too far ahead to be part of ipq? */
291 static int ip_frag_too_far(struct ipq *qp)
292 {
293         struct inet_peer *peer = qp->peer;
294         unsigned int max = qp->q.net->max_dist;
295         unsigned int start, end;
296
297         int rc;
298
299         if (!peer || !max)
300                 return 0;
301
302         start = qp->rid;
303         end = atomic_inc_return(&peer->rid);
304         qp->rid = end;
305
306         rc = qp->q.fragments_tail && (end - start) > max;
307
308         if (rc) {
309                 struct net *net;
310
311                 net = container_of(qp->q.net, struct net, ipv4.frags);
312                 __IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS);
313         }
314
315         return rc;
316 }
317
318 static int ip_frag_reinit(struct ipq *qp)
319 {
320         unsigned int sum_truesize = 0;
321
322         if (!mod_timer(&qp->q.timer, jiffies + qp->q.net->timeout)) {
323                 refcount_inc(&qp->q.refcnt);
324                 return -ETIMEDOUT;
325         }
326
327         sum_truesize = inet_frag_rbtree_purge(&qp->q.rb_fragments);
328         sub_frag_mem_limit(qp->q.net, sum_truesize);
329
330         qp->q.flags = 0;
331         qp->q.len = 0;
332         qp->q.meat = 0;
333         qp->q.fragments = NULL;
334         qp->q.rb_fragments = RB_ROOT;
335         qp->q.fragments_tail = NULL;
336         qp->q.last_run_head = NULL;
337         qp->iif = 0;
338         qp->ecn = 0;
339
340         return 0;
341 }
342
343 /* Add new segment to existing queue. */
344 static int ip_frag_queue(struct ipq *qp, struct sk_buff *skb)
345 {
346         struct net *net = container_of(qp->q.net, struct net, ipv4.frags);
347         struct rb_node **rbn, *parent;
348         struct sk_buff *skb1, *prev_tail;
349         int ihl, end, skb1_run_end;
350         struct net_device *dev;
351         unsigned int fragsize;
352         int flags, offset;
353         int err = -ENOENT;
354         u8 ecn;
355
356         if (qp->q.flags & INET_FRAG_COMPLETE)
357                 goto err;
358
359         if (!(IPCB(skb)->flags & IPSKB_FRAG_COMPLETE) &&
360             unlikely(ip_frag_too_far(qp)) &&
361             unlikely(err = ip_frag_reinit(qp))) {
362                 ipq_kill(qp);
363                 goto err;
364         }
365
366         ecn = ip4_frag_ecn(ip_hdr(skb)->tos);
367         offset = ntohs(ip_hdr(skb)->frag_off);
368         flags = offset & ~IP_OFFSET;
369         offset &= IP_OFFSET;
370         offset <<= 3;           /* offset is in 8-byte chunks */
371         ihl = ip_hdrlen(skb);
372
373         /* Determine the position of this fragment. */
374         end = offset + skb->len - skb_network_offset(skb) - ihl;
375         err = -EINVAL;
376
377         /* Is this the final fragment? */
378         if ((flags & IP_MF) == 0) {
379                 /* If we already have some bits beyond end
380                  * or have different end, the segment is corrupted.
381                  */
382                 if (end < qp->q.len ||
383                     ((qp->q.flags & INET_FRAG_LAST_IN) && end != qp->q.len))
384                         goto discard_qp;
385                 qp->q.flags |= INET_FRAG_LAST_IN;
386                 qp->q.len = end;
387         } else {
388                 if (end&7) {
389                         end &= ~7;
390                         if (skb->ip_summed != CHECKSUM_UNNECESSARY)
391                                 skb->ip_summed = CHECKSUM_NONE;
392                 }
393                 if (end > qp->q.len) {
394                         /* Some bits beyond end -> corruption. */
395                         if (qp->q.flags & INET_FRAG_LAST_IN)
396                                 goto discard_qp;
397                         qp->q.len = end;
398                 }
399         }
400         if (end == offset)
401                 goto discard_qp;
402
403         err = -ENOMEM;
404         if (!pskb_pull(skb, skb_network_offset(skb) + ihl))
405                 goto discard_qp;
406
407         err = pskb_trim_rcsum(skb, end - offset);
408         if (err)
409                 goto discard_qp;
410
411         /* Note : skb->rbnode and skb->dev share the same location. */
412         dev = skb->dev;
413         /* Makes sure compiler wont do silly aliasing games */
414         barrier();
415
416         /* RFC5722, Section 4, amended by Errata ID : 3089
417          *                          When reassembling an IPv6 datagram, if
418          *   one or more its constituent fragments is determined to be an
419          *   overlapping fragment, the entire datagram (and any constituent
420          *   fragments) MUST be silently discarded.
421          *
422          * We do the same here for IPv4 (and increment an snmp counter) but
423          * we do not want to drop the whole queue in response to a duplicate
424          * fragment.
425          */
426
427         err = -EINVAL;
428         /* Find out where to put this fragment.  */
429         prev_tail = qp->q.fragments_tail;
430         if (!prev_tail)
431                 ip4_frag_create_run(&qp->q, skb);  /* First fragment. */
432         else if (prev_tail->ip_defrag_offset + prev_tail->len < end) {
433                 /* This is the common case: skb goes to the end. */
434                 /* Detect and discard overlaps. */
435                 if (offset < prev_tail->ip_defrag_offset + prev_tail->len)
436                         goto overlap;
437                 if (offset == prev_tail->ip_defrag_offset + prev_tail->len)
438                         ip4_frag_append_to_last_run(&qp->q, skb);
439                 else
440                         ip4_frag_create_run(&qp->q, skb);
441         } else {
442                 /* Binary search. Note that skb can become the first fragment,
443                  * but not the last (covered above).
444                  */
445                 rbn = &qp->q.rb_fragments.rb_node;
446                 do {
447                         parent = *rbn;
448                         skb1 = rb_to_skb(parent);
449                         skb1_run_end = skb1->ip_defrag_offset +
450                                        FRAG_CB(skb1)->frag_run_len;
451                         if (end <= skb1->ip_defrag_offset)
452                                 rbn = &parent->rb_left;
453                         else if (offset >= skb1_run_end)
454                                 rbn = &parent->rb_right;
455                         else if (offset >= skb1->ip_defrag_offset &&
456                                  end <= skb1_run_end)
457                                 goto err; /* No new data, potential duplicate */
458                         else
459                                 goto overlap; /* Found an overlap */
460                 } while (*rbn);
461                 /* Here we have parent properly set, and rbn pointing to
462                  * one of its NULL left/right children. Insert skb.
463                  */
464                 ip4_frag_init_run(skb);
465                 rb_link_node(&skb->rbnode, parent, rbn);
466                 rb_insert_color(&skb->rbnode, &qp->q.rb_fragments);
467         }
468
469         if (dev)
470                 qp->iif = dev->ifindex;
471         skb->ip_defrag_offset = offset;
472
473         qp->q.stamp = skb->tstamp;
474         qp->q.meat += skb->len;
475         qp->ecn |= ecn;
476         add_frag_mem_limit(qp->q.net, skb->truesize);
477         if (offset == 0)
478                 qp->q.flags |= INET_FRAG_FIRST_IN;
479
480         fragsize = skb->len + ihl;
481
482         if (fragsize > qp->q.max_size)
483                 qp->q.max_size = fragsize;
484
485         if (ip_hdr(skb)->frag_off & htons(IP_DF) &&
486             fragsize > qp->max_df_size)
487                 qp->max_df_size = fragsize;
488
489         if (qp->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
490             qp->q.meat == qp->q.len) {
491                 unsigned long orefdst = skb->_skb_refdst;
492
493                 skb->_skb_refdst = 0UL;
494                 err = ip_frag_reasm(qp, skb, prev_tail, dev);
495                 skb->_skb_refdst = orefdst;
496                 if (err)
497                         inet_frag_kill(&qp->q);
498                 return err;
499         }
500
501         skb_dst_drop(skb);
502         return -EINPROGRESS;
503
504 overlap:
505         __IP_INC_STATS(net, IPSTATS_MIB_REASM_OVERLAPS);
506 discard_qp:
507         inet_frag_kill(&qp->q);
508 err:
509         kfree_skb(skb);
510         return err;
511 }
512
513 /* Build a new IP datagram from all its fragments. */
514 static int ip_frag_reasm(struct ipq *qp, struct sk_buff *skb,
515                          struct sk_buff *prev_tail, struct net_device *dev)
516 {
517         struct net *net = container_of(qp->q.net, struct net, ipv4.frags);
518         struct iphdr *iph;
519         struct sk_buff *fp, *head = skb_rb_first(&qp->q.rb_fragments);
520         struct sk_buff **nextp; /* To build frag_list. */
521         struct rb_node *rbn;
522         int len;
523         int ihlen;
524         int delta;
525         int err;
526         u8 ecn;
527
528         ipq_kill(qp);
529
530         ecn = ip_frag_ecn_table[qp->ecn];
531         if (unlikely(ecn == 0xff)) {
532                 err = -EINVAL;
533                 goto out_fail;
534         }
535         /* Make the one we just received the head. */
536         if (head != skb) {
537                 fp = skb_clone(skb, GFP_ATOMIC);
538                 if (!fp)
539                         goto out_nomem;
540                 FRAG_CB(fp)->next_frag = FRAG_CB(skb)->next_frag;
541                 if (RB_EMPTY_NODE(&skb->rbnode))
542                         FRAG_CB(prev_tail)->next_frag = fp;
543                 else
544                         rb_replace_node(&skb->rbnode, &fp->rbnode,
545                                         &qp->q.rb_fragments);
546                 if (qp->q.fragments_tail == skb)
547                         qp->q.fragments_tail = fp;
548                 skb_morph(skb, head);
549                 FRAG_CB(skb)->next_frag = FRAG_CB(head)->next_frag;
550                 rb_replace_node(&head->rbnode, &skb->rbnode,
551                                 &qp->q.rb_fragments);
552                 consume_skb(head);
553                 head = skb;
554         }
555
556         WARN_ON(head->ip_defrag_offset != 0);
557
558         /* Allocate a new buffer for the datagram. */
559         ihlen = ip_hdrlen(head);
560         len = ihlen + qp->q.len;
561
562         err = -E2BIG;
563         if (len > 65535)
564                 goto out_oversize;
565
566         delta = - head->truesize;
567
568         /* Head of list must not be cloned. */
569         if (skb_unclone(head, GFP_ATOMIC))
570                 goto out_nomem;
571
572         delta += head->truesize;
573         if (delta)
574                 add_frag_mem_limit(qp->q.net, delta);
575
576         /* If the first fragment is fragmented itself, we split
577          * it to two chunks: the first with data and paged part
578          * and the second, holding only fragments. */
579         if (skb_has_frag_list(head)) {
580                 struct sk_buff *clone;
581                 int i, plen = 0;
582
583                 clone = alloc_skb(0, GFP_ATOMIC);
584                 if (!clone)
585                         goto out_nomem;
586                 skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
587                 skb_frag_list_init(head);
588                 for (i = 0; i < skb_shinfo(head)->nr_frags; i++)
589                         plen += skb_frag_size(&skb_shinfo(head)->frags[i]);
590                 clone->len = clone->data_len = head->data_len - plen;
591                 head->truesize += clone->truesize;
592                 clone->csum = 0;
593                 clone->ip_summed = head->ip_summed;
594                 add_frag_mem_limit(qp->q.net, clone->truesize);
595                 skb_shinfo(head)->frag_list = clone;
596                 nextp = &clone->next;
597         } else {
598                 nextp = &skb_shinfo(head)->frag_list;
599         }
600
601         skb_push(head, head->data - skb_network_header(head));
602
603         /* Traverse the tree in order, to build frag_list. */
604         fp = FRAG_CB(head)->next_frag;
605         rbn = rb_next(&head->rbnode);
606         rb_erase(&head->rbnode, &qp->q.rb_fragments);
607         while (rbn || fp) {
608                 /* fp points to the next sk_buff in the current run;
609                  * rbn points to the next run.
610                  */
611                 /* Go through the current run. */
612                 while (fp) {
613                         *nextp = fp;
614                         nextp = &fp->next;
615                         fp->prev = NULL;
616                         memset(&fp->rbnode, 0, sizeof(fp->rbnode));
617                         fp->sk = NULL;
618                         head->data_len += fp->len;
619                         head->len += fp->len;
620                         if (head->ip_summed != fp->ip_summed)
621                                 head->ip_summed = CHECKSUM_NONE;
622                         else if (head->ip_summed == CHECKSUM_COMPLETE)
623                                 head->csum = csum_add(head->csum, fp->csum);
624                         head->truesize += fp->truesize;
625                         fp = FRAG_CB(fp)->next_frag;
626                 }
627                 /* Move to the next run. */
628                 if (rbn) {
629                         struct rb_node *rbnext = rb_next(rbn);
630
631                         fp = rb_to_skb(rbn);
632                         rb_erase(rbn, &qp->q.rb_fragments);
633                         rbn = rbnext;
634                 }
635         }
636         sub_frag_mem_limit(qp->q.net, head->truesize);
637
638         *nextp = NULL;
639         skb_mark_not_on_list(head);
640         head->prev = NULL;
641         head->dev = dev;
642         head->tstamp = qp->q.stamp;
643         IPCB(head)->frag_max_size = max(qp->max_df_size, qp->q.max_size);
644
645         iph = ip_hdr(head);
646         iph->tot_len = htons(len);
647         iph->tos |= ecn;
648
649         /* When we set IP_DF on a refragmented skb we must also force a
650          * call to ip_fragment to avoid forwarding a DF-skb of size s while
651          * original sender only sent fragments of size f (where f < s).
652          *
653          * We only set DF/IPSKB_FRAG_PMTU if such DF fragment was the largest
654          * frag seen to avoid sending tiny DF-fragments in case skb was built
655          * from one very small df-fragment and one large non-df frag.
656          */
657         if (qp->max_df_size == qp->q.max_size) {
658                 IPCB(head)->flags |= IPSKB_FRAG_PMTU;
659                 iph->frag_off = htons(IP_DF);
660         } else {
661                 iph->frag_off = 0;
662         }
663
664         ip_send_check(iph);
665
666         __IP_INC_STATS(net, IPSTATS_MIB_REASMOKS);
667         qp->q.fragments = NULL;
668         qp->q.rb_fragments = RB_ROOT;
669         qp->q.fragments_tail = NULL;
670         qp->q.last_run_head = NULL;
671         return 0;
672
673 out_nomem:
674         net_dbg_ratelimited("queue_glue: no memory for gluing queue %p\n", qp);
675         err = -ENOMEM;
676         goto out_fail;
677 out_oversize:
678         net_info_ratelimited("Oversized IP packet from %pI4\n", &qp->q.key.v4.saddr);
679 out_fail:
680         __IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS);
681         return err;
682 }
683
684 /* Process an incoming IP datagram fragment. */
685 int ip_defrag(struct net *net, struct sk_buff *skb, u32 user)
686 {
687         struct net_device *dev = skb->dev ? : skb_dst(skb)->dev;
688         int vif = l3mdev_master_ifindex_rcu(dev);
689         struct ipq *qp;
690
691         __IP_INC_STATS(net, IPSTATS_MIB_REASMREQDS);
692         skb_orphan(skb);
693
694         /* Lookup (or create) queue header */
695         qp = ip_find(net, ip_hdr(skb), user, vif);
696         if (qp) {
697                 int ret;
698
699                 spin_lock(&qp->q.lock);
700
701                 ret = ip_frag_queue(qp, skb);
702
703                 spin_unlock(&qp->q.lock);
704                 ipq_put(qp);
705                 return ret;
706         }
707
708         __IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS);
709         kfree_skb(skb);
710         return -ENOMEM;
711 }
712 EXPORT_SYMBOL(ip_defrag);
713
714 struct sk_buff *ip_check_defrag(struct net *net, struct sk_buff *skb, u32 user)
715 {
716         struct iphdr iph;
717         int netoff;
718         u32 len;
719
720         if (skb->protocol != htons(ETH_P_IP))
721                 return skb;
722
723         netoff = skb_network_offset(skb);
724
725         if (skb_copy_bits(skb, netoff, &iph, sizeof(iph)) < 0)
726                 return skb;
727
728         if (iph.ihl < 5 || iph.version != 4)
729                 return skb;
730
731         len = ntohs(iph.tot_len);
732         if (skb->len < netoff + len || len < (iph.ihl * 4))
733                 return skb;
734
735         if (ip_is_fragment(&iph)) {
736                 skb = skb_share_check(skb, GFP_ATOMIC);
737                 if (skb) {
738                         if (!pskb_may_pull(skb, netoff + iph.ihl * 4)) {
739                                 kfree_skb(skb);
740                                 return NULL;
741                         }
742                         if (pskb_trim_rcsum(skb, netoff + len)) {
743                                 kfree_skb(skb);
744                                 return NULL;
745                         }
746                         memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
747                         if (ip_defrag(net, skb, user))
748                                 return NULL;
749                         skb_clear_hash(skb);
750                 }
751         }
752         return skb;
753 }
754 EXPORT_SYMBOL(ip_check_defrag);
755
756 unsigned int inet_frag_rbtree_purge(struct rb_root *root)
757 {
758         struct rb_node *p = rb_first(root);
759         unsigned int sum = 0;
760
761         while (p) {
762                 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
763
764                 p = rb_next(p);
765                 rb_erase(&skb->rbnode, root);
766                 while (skb) {
767                         struct sk_buff *next = FRAG_CB(skb)->next_frag;
768
769                         sum += skb->truesize;
770                         kfree_skb(skb);
771                         skb = next;
772                 }
773         }
774         return sum;
775 }
776 EXPORT_SYMBOL(inet_frag_rbtree_purge);
777
778 #ifdef CONFIG_SYSCTL
779 static int dist_min;
780
781 static struct ctl_table ip4_frags_ns_ctl_table[] = {
782         {
783                 .procname       = "ipfrag_high_thresh",
784                 .data           = &init_net.ipv4.frags.high_thresh,
785                 .maxlen         = sizeof(unsigned long),
786                 .mode           = 0644,
787                 .proc_handler   = proc_doulongvec_minmax,
788                 .extra1         = &init_net.ipv4.frags.low_thresh
789         },
790         {
791                 .procname       = "ipfrag_low_thresh",
792                 .data           = &init_net.ipv4.frags.low_thresh,
793                 .maxlen         = sizeof(unsigned long),
794                 .mode           = 0644,
795                 .proc_handler   = proc_doulongvec_minmax,
796                 .extra2         = &init_net.ipv4.frags.high_thresh
797         },
798         {
799                 .procname       = "ipfrag_time",
800                 .data           = &init_net.ipv4.frags.timeout,
801                 .maxlen         = sizeof(int),
802                 .mode           = 0644,
803                 .proc_handler   = proc_dointvec_jiffies,
804         },
805         {
806                 .procname       = "ipfrag_max_dist",
807                 .data           = &init_net.ipv4.frags.max_dist,
808                 .maxlen         = sizeof(int),
809                 .mode           = 0644,
810                 .proc_handler   = proc_dointvec_minmax,
811                 .extra1         = &dist_min,
812         },
813         { }
814 };
815
816 /* secret interval has been deprecated */
817 static int ip4_frags_secret_interval_unused;
818 static struct ctl_table ip4_frags_ctl_table[] = {
819         {
820                 .procname       = "ipfrag_secret_interval",
821                 .data           = &ip4_frags_secret_interval_unused,
822                 .maxlen         = sizeof(int),
823                 .mode           = 0644,
824                 .proc_handler   = proc_dointvec_jiffies,
825         },
826         { }
827 };
828
829 static int __net_init ip4_frags_ns_ctl_register(struct net *net)
830 {
831         struct ctl_table *table;
832         struct ctl_table_header *hdr;
833
834         table = ip4_frags_ns_ctl_table;
835         if (!net_eq(net, &init_net)) {
836                 table = kmemdup(table, sizeof(ip4_frags_ns_ctl_table), GFP_KERNEL);
837                 if (!table)
838                         goto err_alloc;
839
840                 table[0].data = &net->ipv4.frags.high_thresh;
841                 table[0].extra1 = &net->ipv4.frags.low_thresh;
842                 table[1].data = &net->ipv4.frags.low_thresh;
843                 table[1].extra2 = &net->ipv4.frags.high_thresh;
844                 table[2].data = &net->ipv4.frags.timeout;
845                 table[3].data = &net->ipv4.frags.max_dist;
846         }
847
848         hdr = register_net_sysctl(net, "net/ipv4", table);
849         if (!hdr)
850                 goto err_reg;
851
852         net->ipv4.frags_hdr = hdr;
853         return 0;
854
855 err_reg:
856         if (!net_eq(net, &init_net))
857                 kfree(table);
858 err_alloc:
859         return -ENOMEM;
860 }
861
862 static void __net_exit ip4_frags_ns_ctl_unregister(struct net *net)
863 {
864         struct ctl_table *table;
865
866         table = net->ipv4.frags_hdr->ctl_table_arg;
867         unregister_net_sysctl_table(net->ipv4.frags_hdr);
868         kfree(table);
869 }
870
871 static void __init ip4_frags_ctl_register(void)
872 {
873         register_net_sysctl(&init_net, "net/ipv4", ip4_frags_ctl_table);
874 }
875 #else
876 static int ip4_frags_ns_ctl_register(struct net *net)
877 {
878         return 0;
879 }
880
881 static void ip4_frags_ns_ctl_unregister(struct net *net)
882 {
883 }
884
885 static void __init ip4_frags_ctl_register(void)
886 {
887 }
888 #endif
889
890 static int __net_init ipv4_frags_init_net(struct net *net)
891 {
892         int res;
893
894         /* Fragment cache limits.
895          *
896          * The fragment memory accounting code, (tries to) account for
897          * the real memory usage, by measuring both the size of frag
898          * queue struct (inet_frag_queue (ipv4:ipq/ipv6:frag_queue))
899          * and the SKB's truesize.
900          *
901          * A 64K fragment consumes 129736 bytes (44*2944)+200
902          * (1500 truesize == 2944, sizeof(struct ipq) == 200)
903          *
904          * We will commit 4MB at one time. Should we cross that limit
905          * we will prune down to 3MB, making room for approx 8 big 64K
906          * fragments 8x128k.
907          */
908         net->ipv4.frags.high_thresh = 4 * 1024 * 1024;
909         net->ipv4.frags.low_thresh  = 3 * 1024 * 1024;
910         /*
911          * Important NOTE! Fragment queue must be destroyed before MSL expires.
912          * RFC791 is wrong proposing to prolongate timer each fragment arrival
913          * by TTL.
914          */
915         net->ipv4.frags.timeout = IP_FRAG_TIME;
916
917         net->ipv4.frags.max_dist = 64;
918         net->ipv4.frags.f = &ip4_frags;
919
920         res = inet_frags_init_net(&net->ipv4.frags);
921         if (res < 0)
922                 return res;
923         res = ip4_frags_ns_ctl_register(net);
924         if (res < 0)
925                 inet_frags_exit_net(&net->ipv4.frags);
926         return res;
927 }
928
929 static void __net_exit ipv4_frags_exit_net(struct net *net)
930 {
931         ip4_frags_ns_ctl_unregister(net);
932         inet_frags_exit_net(&net->ipv4.frags);
933 }
934
935 static struct pernet_operations ip4_frags_ops = {
936         .init = ipv4_frags_init_net,
937         .exit = ipv4_frags_exit_net,
938 };
939
940
941 static u32 ip4_key_hashfn(const void *data, u32 len, u32 seed)
942 {
943         return jhash2(data,
944                       sizeof(struct frag_v4_compare_key) / sizeof(u32), seed);
945 }
946
947 static u32 ip4_obj_hashfn(const void *data, u32 len, u32 seed)
948 {
949         const struct inet_frag_queue *fq = data;
950
951         return jhash2((const u32 *)&fq->key.v4,
952                       sizeof(struct frag_v4_compare_key) / sizeof(u32), seed);
953 }
954
955 static int ip4_obj_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr)
956 {
957         const struct frag_v4_compare_key *key = arg->key;
958         const struct inet_frag_queue *fq = ptr;
959
960         return !!memcmp(&fq->key, key, sizeof(*key));
961 }
962
963 static const struct rhashtable_params ip4_rhash_params = {
964         .head_offset            = offsetof(struct inet_frag_queue, node),
965         .key_offset             = offsetof(struct inet_frag_queue, key),
966         .key_len                = sizeof(struct frag_v4_compare_key),
967         .hashfn                 = ip4_key_hashfn,
968         .obj_hashfn             = ip4_obj_hashfn,
969         .obj_cmpfn              = ip4_obj_cmpfn,
970         .automatic_shrinking    = true,
971 };
972
973 void __init ipfrag_init(void)
974 {
975         ip4_frags.constructor = ip4_frag_init;
976         ip4_frags.destructor = ip4_frag_free;
977         ip4_frags.qsize = sizeof(struct ipq);
978         ip4_frags.frag_expire = ip_expire;
979         ip4_frags.frags_cache_name = ip_frag_cache_name;
980         ip4_frags.rhash_params = ip4_rhash_params;
981         if (inet_frags_init(&ip4_frags))
982                 panic("IP: failed to allocate ip4_frags cache\n");
983         ip4_frags_ctl_register();
984         register_pernet_subsys(&ip4_frags_ops);
985 }