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