4c5c74d79c8171ed65316f691e1c4a1e24ac4e8a
[platform/kernel/linux-rpi.git] / drivers / net / amt.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* Copyright (c) 2021 Taehee Yoo <ap420073@gmail.com> */
3
4 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
5
6 #include <linux/module.h>
7 #include <linux/skbuff.h>
8 #include <linux/udp.h>
9 #include <linux/jhash.h>
10 #include <linux/if_tunnel.h>
11 #include <linux/net.h>
12 #include <linux/igmp.h>
13 #include <linux/workqueue.h>
14 #include <net/sch_generic.h>
15 #include <net/net_namespace.h>
16 #include <net/ip.h>
17 #include <net/udp.h>
18 #include <net/udp_tunnel.h>
19 #include <net/icmp.h>
20 #include <net/mld.h>
21 #include <net/amt.h>
22 #include <uapi/linux/amt.h>
23 #include <linux/security.h>
24 #include <net/gro_cells.h>
25 #include <net/ipv6.h>
26 #include <net/if_inet6.h>
27 #include <net/ndisc.h>
28 #include <net/addrconf.h>
29 #include <net/ip6_route.h>
30 #include <net/inet_common.h>
31 #include <net/ip6_checksum.h>
32
33 static struct workqueue_struct *amt_wq;
34
35 static HLIST_HEAD(source_gc_list);
36 /* Lock for source_gc_list */
37 static spinlock_t source_gc_lock;
38 static struct delayed_work source_gc_wq;
39 static char *status_str[] = {
40         "AMT_STATUS_INIT",
41         "AMT_STATUS_SENT_DISCOVERY",
42         "AMT_STATUS_RECEIVED_DISCOVERY",
43         "AMT_STATUS_SENT_ADVERTISEMENT",
44         "AMT_STATUS_RECEIVED_ADVERTISEMENT",
45         "AMT_STATUS_SENT_REQUEST",
46         "AMT_STATUS_RECEIVED_REQUEST",
47         "AMT_STATUS_SENT_QUERY",
48         "AMT_STATUS_RECEIVED_QUERY",
49         "AMT_STATUS_SENT_UPDATE",
50         "AMT_STATUS_RECEIVED_UPDATE",
51 };
52
53 static char *type_str[] = {
54         "", /* Type 0 is not defined */
55         "AMT_MSG_DISCOVERY",
56         "AMT_MSG_ADVERTISEMENT",
57         "AMT_MSG_REQUEST",
58         "AMT_MSG_MEMBERSHIP_QUERY",
59         "AMT_MSG_MEMBERSHIP_UPDATE",
60         "AMT_MSG_MULTICAST_DATA",
61         "AMT_MSG_TEARDOWN",
62 };
63
64 static char *action_str[] = {
65         "AMT_ACT_GMI",
66         "AMT_ACT_GMI_ZERO",
67         "AMT_ACT_GT",
68         "AMT_ACT_STATUS_FWD_NEW",
69         "AMT_ACT_STATUS_D_FWD_NEW",
70         "AMT_ACT_STATUS_NONE_NEW",
71 };
72
73 static struct igmpv3_grec igmpv3_zero_grec;
74
75 #if IS_ENABLED(CONFIG_IPV6)
76 #define MLD2_ALL_NODE_INIT { { { 0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01 } } }
77 static struct in6_addr mld2_all_node = MLD2_ALL_NODE_INIT;
78 static struct mld2_grec mldv2_zero_grec;
79 #endif
80
81 static struct amt_skb_cb *amt_skb_cb(struct sk_buff *skb)
82 {
83         BUILD_BUG_ON(sizeof(struct amt_skb_cb) + sizeof(struct qdisc_skb_cb) >
84                      sizeof_field(struct sk_buff, cb));
85
86         return (struct amt_skb_cb *)((void *)skb->cb +
87                 sizeof(struct qdisc_skb_cb));
88 }
89
90 static void __amt_source_gc_work(void)
91 {
92         struct amt_source_node *snode;
93         struct hlist_head gc_list;
94         struct hlist_node *t;
95
96         spin_lock_bh(&source_gc_lock);
97         hlist_move_list(&source_gc_list, &gc_list);
98         spin_unlock_bh(&source_gc_lock);
99
100         hlist_for_each_entry_safe(snode, t, &gc_list, node) {
101                 hlist_del_rcu(&snode->node);
102                 kfree_rcu(snode, rcu);
103         }
104 }
105
106 static void amt_source_gc_work(struct work_struct *work)
107 {
108         __amt_source_gc_work();
109
110         spin_lock_bh(&source_gc_lock);
111         mod_delayed_work(amt_wq, &source_gc_wq,
112                          msecs_to_jiffies(AMT_GC_INTERVAL));
113         spin_unlock_bh(&source_gc_lock);
114 }
115
116 static bool amt_addr_equal(union amt_addr *a, union amt_addr *b)
117 {
118         return !memcmp(a, b, sizeof(union amt_addr));
119 }
120
121 static u32 amt_source_hash(struct amt_tunnel_list *tunnel, union amt_addr *src)
122 {
123         u32 hash = jhash(src, sizeof(*src), tunnel->amt->hash_seed);
124
125         return reciprocal_scale(hash, tunnel->amt->hash_buckets);
126 }
127
128 static bool amt_status_filter(struct amt_source_node *snode,
129                               enum amt_filter filter)
130 {
131         bool rc = false;
132
133         switch (filter) {
134         case AMT_FILTER_FWD:
135                 if (snode->status == AMT_SOURCE_STATUS_FWD &&
136                     snode->flags == AMT_SOURCE_OLD)
137                         rc = true;
138                 break;
139         case AMT_FILTER_D_FWD:
140                 if (snode->status == AMT_SOURCE_STATUS_D_FWD &&
141                     snode->flags == AMT_SOURCE_OLD)
142                         rc = true;
143                 break;
144         case AMT_FILTER_FWD_NEW:
145                 if (snode->status == AMT_SOURCE_STATUS_FWD &&
146                     snode->flags == AMT_SOURCE_NEW)
147                         rc = true;
148                 break;
149         case AMT_FILTER_D_FWD_NEW:
150                 if (snode->status == AMT_SOURCE_STATUS_D_FWD &&
151                     snode->flags == AMT_SOURCE_NEW)
152                         rc = true;
153                 break;
154         case AMT_FILTER_ALL:
155                 rc = true;
156                 break;
157         case AMT_FILTER_NONE_NEW:
158                 if (snode->status == AMT_SOURCE_STATUS_NONE &&
159                     snode->flags == AMT_SOURCE_NEW)
160                         rc = true;
161                 break;
162         case AMT_FILTER_BOTH:
163                 if ((snode->status == AMT_SOURCE_STATUS_D_FWD ||
164                      snode->status == AMT_SOURCE_STATUS_FWD) &&
165                     snode->flags == AMT_SOURCE_OLD)
166                         rc = true;
167                 break;
168         case AMT_FILTER_BOTH_NEW:
169                 if ((snode->status == AMT_SOURCE_STATUS_D_FWD ||
170                      snode->status == AMT_SOURCE_STATUS_FWD) &&
171                     snode->flags == AMT_SOURCE_NEW)
172                         rc = true;
173                 break;
174         default:
175                 WARN_ON_ONCE(1);
176                 break;
177         }
178
179         return rc;
180 }
181
182 static struct amt_source_node *amt_lookup_src(struct amt_tunnel_list *tunnel,
183                                               struct amt_group_node *gnode,
184                                               enum amt_filter filter,
185                                               union amt_addr *src)
186 {
187         u32 hash = amt_source_hash(tunnel, src);
188         struct amt_source_node *snode;
189
190         hlist_for_each_entry_rcu(snode, &gnode->sources[hash], node)
191                 if (amt_status_filter(snode, filter) &&
192                     amt_addr_equal(&snode->source_addr, src))
193                         return snode;
194
195         return NULL;
196 }
197
198 static u32 amt_group_hash(struct amt_tunnel_list *tunnel, union amt_addr *group)
199 {
200         u32 hash = jhash(group, sizeof(*group), tunnel->amt->hash_seed);
201
202         return reciprocal_scale(hash, tunnel->amt->hash_buckets);
203 }
204
205 static struct amt_group_node *amt_lookup_group(struct amt_tunnel_list *tunnel,
206                                                union amt_addr *group,
207                                                union amt_addr *host,
208                                                bool v6)
209 {
210         u32 hash = amt_group_hash(tunnel, group);
211         struct amt_group_node *gnode;
212
213         hlist_for_each_entry_rcu(gnode, &tunnel->groups[hash], node) {
214                 if (amt_addr_equal(&gnode->group_addr, group) &&
215                     amt_addr_equal(&gnode->host_addr, host) &&
216                     gnode->v6 == v6)
217                         return gnode;
218         }
219
220         return NULL;
221 }
222
223 static void amt_destroy_source(struct amt_source_node *snode)
224 {
225         struct amt_group_node *gnode = snode->gnode;
226         struct amt_tunnel_list *tunnel;
227
228         tunnel = gnode->tunnel_list;
229
230         if (!gnode->v6) {
231                 netdev_dbg(snode->gnode->amt->dev,
232                            "Delete source %pI4 from %pI4\n",
233                            &snode->source_addr.ip4,
234                            &gnode->group_addr.ip4);
235 #if IS_ENABLED(CONFIG_IPV6)
236         } else {
237                 netdev_dbg(snode->gnode->amt->dev,
238                            "Delete source %pI6 from %pI6\n",
239                            &snode->source_addr.ip6,
240                            &gnode->group_addr.ip6);
241 #endif
242         }
243
244         cancel_delayed_work(&snode->source_timer);
245         hlist_del_init_rcu(&snode->node);
246         tunnel->nr_sources--;
247         gnode->nr_sources--;
248         spin_lock_bh(&source_gc_lock);
249         hlist_add_head_rcu(&snode->node, &source_gc_list);
250         spin_unlock_bh(&source_gc_lock);
251 }
252
253 static void amt_del_group(struct amt_dev *amt, struct amt_group_node *gnode)
254 {
255         struct amt_source_node *snode;
256         struct hlist_node *t;
257         int i;
258
259         if (cancel_delayed_work(&gnode->group_timer))
260                 dev_put(amt->dev);
261         hlist_del_rcu(&gnode->node);
262         gnode->tunnel_list->nr_groups--;
263
264         if (!gnode->v6)
265                 netdev_dbg(amt->dev, "Leave group %pI4\n",
266                            &gnode->group_addr.ip4);
267 #if IS_ENABLED(CONFIG_IPV6)
268         else
269                 netdev_dbg(amt->dev, "Leave group %pI6\n",
270                            &gnode->group_addr.ip6);
271 #endif
272         for (i = 0; i < amt->hash_buckets; i++)
273                 hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node)
274                         amt_destroy_source(snode);
275
276         /* tunnel->lock was acquired outside of amt_del_group()
277          * But rcu_read_lock() was acquired too so It's safe.
278          */
279         kfree_rcu(gnode, rcu);
280 }
281
282 /* If a source timer expires with a router filter-mode for the group of
283  * INCLUDE, the router concludes that traffic from this particular
284  * source is no longer desired on the attached network, and deletes the
285  * associated source record.
286  */
287 static void amt_source_work(struct work_struct *work)
288 {
289         struct amt_source_node *snode = container_of(to_delayed_work(work),
290                                                      struct amt_source_node,
291                                                      source_timer);
292         struct amt_group_node *gnode = snode->gnode;
293         struct amt_dev *amt = gnode->amt;
294         struct amt_tunnel_list *tunnel;
295
296         tunnel = gnode->tunnel_list;
297         spin_lock_bh(&tunnel->lock);
298         rcu_read_lock();
299         if (gnode->filter_mode == MCAST_INCLUDE) {
300                 amt_destroy_source(snode);
301                 if (!gnode->nr_sources)
302                         amt_del_group(amt, gnode);
303         } else {
304                 /* When a router filter-mode for a group is EXCLUDE,
305                  * source records are only deleted when the group timer expires
306                  */
307                 snode->status = AMT_SOURCE_STATUS_D_FWD;
308         }
309         rcu_read_unlock();
310         spin_unlock_bh(&tunnel->lock);
311 }
312
313 static void amt_act_src(struct amt_tunnel_list *tunnel,
314                         struct amt_group_node *gnode,
315                         struct amt_source_node *snode,
316                         enum amt_act act)
317 {
318         struct amt_dev *amt = tunnel->amt;
319
320         switch (act) {
321         case AMT_ACT_GMI:
322                 mod_delayed_work(amt_wq, &snode->source_timer,
323                                  msecs_to_jiffies(amt_gmi(amt)));
324                 break;
325         case AMT_ACT_GMI_ZERO:
326                 cancel_delayed_work(&snode->source_timer);
327                 break;
328         case AMT_ACT_GT:
329                 mod_delayed_work(amt_wq, &snode->source_timer,
330                                  gnode->group_timer.timer.expires);
331                 break;
332         case AMT_ACT_STATUS_FWD_NEW:
333                 snode->status = AMT_SOURCE_STATUS_FWD;
334                 snode->flags = AMT_SOURCE_NEW;
335                 break;
336         case AMT_ACT_STATUS_D_FWD_NEW:
337                 snode->status = AMT_SOURCE_STATUS_D_FWD;
338                 snode->flags = AMT_SOURCE_NEW;
339                 break;
340         case AMT_ACT_STATUS_NONE_NEW:
341                 cancel_delayed_work(&snode->source_timer);
342                 snode->status = AMT_SOURCE_STATUS_NONE;
343                 snode->flags = AMT_SOURCE_NEW;
344                 break;
345         default:
346                 WARN_ON_ONCE(1);
347                 return;
348         }
349
350         if (!gnode->v6)
351                 netdev_dbg(amt->dev, "Source %pI4 from %pI4 Acted %s\n",
352                            &snode->source_addr.ip4,
353                            &gnode->group_addr.ip4,
354                            action_str[act]);
355 #if IS_ENABLED(CONFIG_IPV6)
356         else
357                 netdev_dbg(amt->dev, "Source %pI6 from %pI6 Acted %s\n",
358                            &snode->source_addr.ip6,
359                            &gnode->group_addr.ip6,
360                            action_str[act]);
361 #endif
362 }
363
364 static struct amt_source_node *amt_alloc_snode(struct amt_group_node *gnode,
365                                                union amt_addr *src)
366 {
367         struct amt_source_node *snode;
368
369         snode = kzalloc(sizeof(*snode), GFP_ATOMIC);
370         if (!snode)
371                 return NULL;
372
373         memcpy(&snode->source_addr, src, sizeof(union amt_addr));
374         snode->gnode = gnode;
375         snode->status = AMT_SOURCE_STATUS_NONE;
376         snode->flags = AMT_SOURCE_NEW;
377         INIT_HLIST_NODE(&snode->node);
378         INIT_DELAYED_WORK(&snode->source_timer, amt_source_work);
379
380         return snode;
381 }
382
383 /* RFC 3810 - 7.2.2.  Definition of Filter Timers
384  *
385  *  Router Mode          Filter Timer         Actions/Comments
386  *  -----------       -----------------       ----------------
387  *
388  *    INCLUDE             Not Used            All listeners in
389  *                                            INCLUDE mode.
390  *
391  *    EXCLUDE             Timer > 0           At least one listener
392  *                                            in EXCLUDE mode.
393  *
394  *    EXCLUDE             Timer == 0          No more listeners in
395  *                                            EXCLUDE mode for the
396  *                                            multicast address.
397  *                                            If the Requested List
398  *                                            is empty, delete
399  *                                            Multicast Address
400  *                                            Record.  If not, switch
401  *                                            to INCLUDE filter mode;
402  *                                            the sources in the
403  *                                            Requested List are
404  *                                            moved to the Include
405  *                                            List, and the Exclude
406  *                                            List is deleted.
407  */
408 static void amt_group_work(struct work_struct *work)
409 {
410         struct amt_group_node *gnode = container_of(to_delayed_work(work),
411                                                     struct amt_group_node,
412                                                     group_timer);
413         struct amt_tunnel_list *tunnel = gnode->tunnel_list;
414         struct amt_dev *amt = gnode->amt;
415         struct amt_source_node *snode;
416         bool delete_group = true;
417         struct hlist_node *t;
418         int i, buckets;
419
420         buckets = amt->hash_buckets;
421
422         spin_lock_bh(&tunnel->lock);
423         if (gnode->filter_mode == MCAST_INCLUDE) {
424                 /* Not Used */
425                 spin_unlock_bh(&tunnel->lock);
426                 goto out;
427         }
428
429         rcu_read_lock();
430         for (i = 0; i < buckets; i++) {
431                 hlist_for_each_entry_safe(snode, t,
432                                           &gnode->sources[i], node) {
433                         if (!delayed_work_pending(&snode->source_timer) ||
434                             snode->status == AMT_SOURCE_STATUS_D_FWD) {
435                                 amt_destroy_source(snode);
436                         } else {
437                                 delete_group = false;
438                                 snode->status = AMT_SOURCE_STATUS_FWD;
439                         }
440                 }
441         }
442         if (delete_group)
443                 amt_del_group(amt, gnode);
444         else
445                 gnode->filter_mode = MCAST_INCLUDE;
446         rcu_read_unlock();
447         spin_unlock_bh(&tunnel->lock);
448 out:
449         dev_put(amt->dev);
450 }
451
452 /* Non-existant group is created as INCLUDE {empty}:
453  *
454  * RFC 3376 - 5.1. Action on Change of Interface State
455  *
456  * If no interface state existed for that multicast address before
457  * the change (i.e., the change consisted of creating a new
458  * per-interface record), or if no state exists after the change
459  * (i.e., the change consisted of deleting a per-interface record),
460  * then the "non-existent" state is considered to have a filter mode
461  * of INCLUDE and an empty source list.
462  */
463 static struct amt_group_node *amt_add_group(struct amt_dev *amt,
464                                             struct amt_tunnel_list *tunnel,
465                                             union amt_addr *group,
466                                             union amt_addr *host,
467                                             bool v6)
468 {
469         struct amt_group_node *gnode;
470         u32 hash;
471         int i;
472
473         if (tunnel->nr_groups >= amt->max_groups)
474                 return ERR_PTR(-ENOSPC);
475
476         gnode = kzalloc(sizeof(*gnode) +
477                         (sizeof(struct hlist_head) * amt->hash_buckets),
478                         GFP_ATOMIC);
479         if (unlikely(!gnode))
480                 return ERR_PTR(-ENOMEM);
481
482         gnode->amt = amt;
483         gnode->group_addr = *group;
484         gnode->host_addr = *host;
485         gnode->v6 = v6;
486         gnode->tunnel_list = tunnel;
487         gnode->filter_mode = MCAST_INCLUDE;
488         INIT_HLIST_NODE(&gnode->node);
489         INIT_DELAYED_WORK(&gnode->group_timer, amt_group_work);
490         for (i = 0; i < amt->hash_buckets; i++)
491                 INIT_HLIST_HEAD(&gnode->sources[i]);
492
493         hash = amt_group_hash(tunnel, group);
494         hlist_add_head_rcu(&gnode->node, &tunnel->groups[hash]);
495         tunnel->nr_groups++;
496
497         if (!gnode->v6)
498                 netdev_dbg(amt->dev, "Join group %pI4\n",
499                            &gnode->group_addr.ip4);
500 #if IS_ENABLED(CONFIG_IPV6)
501         else
502                 netdev_dbg(amt->dev, "Join group %pI6\n",
503                            &gnode->group_addr.ip6);
504 #endif
505
506         return gnode;
507 }
508
509 static struct sk_buff *amt_build_igmp_gq(struct amt_dev *amt)
510 {
511         u8 ra[AMT_IPHDR_OPTS] = { IPOPT_RA, 4, 0, 0 };
512         int hlen = LL_RESERVED_SPACE(amt->dev);
513         int tlen = amt->dev->needed_tailroom;
514         struct igmpv3_query *ihv3;
515         void *csum_start = NULL;
516         __sum16 *csum = NULL;
517         struct sk_buff *skb;
518         struct ethhdr *eth;
519         struct iphdr *iph;
520         unsigned int len;
521         int offset;
522
523         len = hlen + tlen + sizeof(*iph) + AMT_IPHDR_OPTS + sizeof(*ihv3);
524         skb = netdev_alloc_skb_ip_align(amt->dev, len);
525         if (!skb)
526                 return NULL;
527
528         skb_reserve(skb, hlen);
529         skb_push(skb, sizeof(*eth));
530         skb->protocol = htons(ETH_P_IP);
531         skb_reset_mac_header(skb);
532         skb->priority = TC_PRIO_CONTROL;
533         skb_put(skb, sizeof(*iph));
534         skb_put_data(skb, ra, sizeof(ra));
535         skb_put(skb, sizeof(*ihv3));
536         skb_pull(skb, sizeof(*eth));
537         skb_reset_network_header(skb);
538
539         iph             = ip_hdr(skb);
540         iph->version    = 4;
541         iph->ihl        = (sizeof(struct iphdr) + AMT_IPHDR_OPTS) >> 2;
542         iph->tos        = AMT_TOS;
543         iph->tot_len    = htons(sizeof(*iph) + AMT_IPHDR_OPTS + sizeof(*ihv3));
544         iph->frag_off   = htons(IP_DF);
545         iph->ttl        = 1;
546         iph->id         = 0;
547         iph->protocol   = IPPROTO_IGMP;
548         iph->daddr      = htonl(INADDR_ALLHOSTS_GROUP);
549         iph->saddr      = htonl(INADDR_ANY);
550         ip_send_check(iph);
551
552         eth = eth_hdr(skb);
553         ether_addr_copy(eth->h_source, amt->dev->dev_addr);
554         ip_eth_mc_map(htonl(INADDR_ALLHOSTS_GROUP), eth->h_dest);
555         eth->h_proto = htons(ETH_P_IP);
556
557         ihv3            = skb_pull(skb, sizeof(*iph) + AMT_IPHDR_OPTS);
558         skb_reset_transport_header(skb);
559         ihv3->type      = IGMP_HOST_MEMBERSHIP_QUERY;
560         ihv3->code      = 1;
561         ihv3->group     = 0;
562         ihv3->qqic      = amt->qi;
563         ihv3->nsrcs     = 0;
564         ihv3->resv      = 0;
565         ihv3->suppress  = false;
566         ihv3->qrv       = READ_ONCE(amt->net->ipv4.sysctl_igmp_qrv);
567         ihv3->csum      = 0;
568         csum            = &ihv3->csum;
569         csum_start      = (void *)ihv3;
570         *csum           = ip_compute_csum(csum_start, sizeof(*ihv3));
571         offset          = skb_transport_offset(skb);
572         skb->csum       = skb_checksum(skb, offset, skb->len - offset, 0);
573         skb->ip_summed  = CHECKSUM_NONE;
574
575         skb_push(skb, sizeof(*eth) + sizeof(*iph) + AMT_IPHDR_OPTS);
576
577         return skb;
578 }
579
580 static void amt_update_gw_status(struct amt_dev *amt, enum amt_status status,
581                                  bool validate)
582 {
583         if (validate && amt->status >= status)
584                 return;
585         netdev_dbg(amt->dev, "Update GW status %s -> %s",
586                    status_str[amt->status], status_str[status]);
587         WRITE_ONCE(amt->status, status);
588 }
589
590 static void __amt_update_relay_status(struct amt_tunnel_list *tunnel,
591                                       enum amt_status status,
592                                       bool validate)
593 {
594         if (validate && tunnel->status >= status)
595                 return;
596         netdev_dbg(tunnel->amt->dev,
597                    "Update Tunnel(IP = %pI4, PORT = %u) status %s -> %s",
598                    &tunnel->ip4, ntohs(tunnel->source_port),
599                    status_str[tunnel->status], status_str[status]);
600         tunnel->status = status;
601 }
602
603 static void amt_update_relay_status(struct amt_tunnel_list *tunnel,
604                                     enum amt_status status, bool validate)
605 {
606         spin_lock_bh(&tunnel->lock);
607         __amt_update_relay_status(tunnel, status, validate);
608         spin_unlock_bh(&tunnel->lock);
609 }
610
611 static void amt_send_discovery(struct amt_dev *amt)
612 {
613         struct amt_header_discovery *amtd;
614         int hlen, tlen, offset;
615         struct socket *sock;
616         struct udphdr *udph;
617         struct sk_buff *skb;
618         struct iphdr *iph;
619         struct rtable *rt;
620         struct flowi4 fl4;
621         u32 len;
622         int err;
623
624         rcu_read_lock();
625         sock = rcu_dereference(amt->sock);
626         if (!sock)
627                 goto out;
628
629         if (!netif_running(amt->stream_dev) || !netif_running(amt->dev))
630                 goto out;
631
632         rt = ip_route_output_ports(amt->net, &fl4, sock->sk,
633                                    amt->discovery_ip, amt->local_ip,
634                                    amt->gw_port, amt->relay_port,
635                                    IPPROTO_UDP, 0,
636                                    amt->stream_dev->ifindex);
637         if (IS_ERR(rt)) {
638                 amt->dev->stats.tx_errors++;
639                 goto out;
640         }
641
642         hlen = LL_RESERVED_SPACE(amt->dev);
643         tlen = amt->dev->needed_tailroom;
644         len = hlen + tlen + sizeof(*iph) + sizeof(*udph) + sizeof(*amtd);
645         skb = netdev_alloc_skb_ip_align(amt->dev, len);
646         if (!skb) {
647                 ip_rt_put(rt);
648                 amt->dev->stats.tx_errors++;
649                 goto out;
650         }
651
652         skb->priority = TC_PRIO_CONTROL;
653         skb_dst_set(skb, &rt->dst);
654
655         len = sizeof(*iph) + sizeof(*udph) + sizeof(*amtd);
656         skb_reset_network_header(skb);
657         skb_put(skb, len);
658         amtd = skb_pull(skb, sizeof(*iph) + sizeof(*udph));
659         amtd->version   = 0;
660         amtd->type      = AMT_MSG_DISCOVERY;
661         amtd->reserved  = 0;
662         amtd->nonce     = amt->nonce;
663         skb_push(skb, sizeof(*udph));
664         skb_reset_transport_header(skb);
665         udph            = udp_hdr(skb);
666         udph->source    = amt->gw_port;
667         udph->dest      = amt->relay_port;
668         udph->len       = htons(sizeof(*udph) + sizeof(*amtd));
669         udph->check     = 0;
670         offset = skb_transport_offset(skb);
671         skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
672         udph->check = csum_tcpudp_magic(amt->local_ip, amt->discovery_ip,
673                                         sizeof(*udph) + sizeof(*amtd),
674                                         IPPROTO_UDP, skb->csum);
675
676         skb_push(skb, sizeof(*iph));
677         iph             = ip_hdr(skb);
678         iph->version    = 4;
679         iph->ihl        = (sizeof(struct iphdr)) >> 2;
680         iph->tos        = AMT_TOS;
681         iph->frag_off   = 0;
682         iph->ttl        = ip4_dst_hoplimit(&rt->dst);
683         iph->daddr      = amt->discovery_ip;
684         iph->saddr      = amt->local_ip;
685         iph->protocol   = IPPROTO_UDP;
686         iph->tot_len    = htons(len);
687
688         skb->ip_summed = CHECKSUM_NONE;
689         ip_select_ident(amt->net, skb, NULL);
690         ip_send_check(iph);
691         err = ip_local_out(amt->net, sock->sk, skb);
692         if (unlikely(net_xmit_eval(err)))
693                 amt->dev->stats.tx_errors++;
694
695         amt_update_gw_status(amt, AMT_STATUS_SENT_DISCOVERY, true);
696 out:
697         rcu_read_unlock();
698 }
699
700 static void amt_send_request(struct amt_dev *amt, bool v6)
701 {
702         struct amt_header_request *amtrh;
703         int hlen, tlen, offset;
704         struct socket *sock;
705         struct udphdr *udph;
706         struct sk_buff *skb;
707         struct iphdr *iph;
708         struct rtable *rt;
709         struct flowi4 fl4;
710         u32 len;
711         int err;
712
713         rcu_read_lock();
714         sock = rcu_dereference(amt->sock);
715         if (!sock)
716                 goto out;
717
718         if (!netif_running(amt->stream_dev) || !netif_running(amt->dev))
719                 goto out;
720
721         rt = ip_route_output_ports(amt->net, &fl4, sock->sk,
722                                    amt->remote_ip, amt->local_ip,
723                                    amt->gw_port, amt->relay_port,
724                                    IPPROTO_UDP, 0,
725                                    amt->stream_dev->ifindex);
726         if (IS_ERR(rt)) {
727                 amt->dev->stats.tx_errors++;
728                 goto out;
729         }
730
731         hlen = LL_RESERVED_SPACE(amt->dev);
732         tlen = amt->dev->needed_tailroom;
733         len = hlen + tlen + sizeof(*iph) + sizeof(*udph) + sizeof(*amtrh);
734         skb = netdev_alloc_skb_ip_align(amt->dev, len);
735         if (!skb) {
736                 ip_rt_put(rt);
737                 amt->dev->stats.tx_errors++;
738                 goto out;
739         }
740
741         skb->priority = TC_PRIO_CONTROL;
742         skb_dst_set(skb, &rt->dst);
743
744         len = sizeof(*iph) + sizeof(*udph) + sizeof(*amtrh);
745         skb_reset_network_header(skb);
746         skb_put(skb, len);
747         amtrh = skb_pull(skb, sizeof(*iph) + sizeof(*udph));
748         amtrh->version   = 0;
749         amtrh->type      = AMT_MSG_REQUEST;
750         amtrh->reserved1 = 0;
751         amtrh->p         = v6;
752         amtrh->reserved2 = 0;
753         amtrh->nonce     = amt->nonce;
754         skb_push(skb, sizeof(*udph));
755         skb_reset_transport_header(skb);
756         udph            = udp_hdr(skb);
757         udph->source    = amt->gw_port;
758         udph->dest      = amt->relay_port;
759         udph->len       = htons(sizeof(*amtrh) + sizeof(*udph));
760         udph->check     = 0;
761         offset = skb_transport_offset(skb);
762         skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
763         udph->check = csum_tcpudp_magic(amt->local_ip, amt->remote_ip,
764                                         sizeof(*udph) + sizeof(*amtrh),
765                                         IPPROTO_UDP, skb->csum);
766
767         skb_push(skb, sizeof(*iph));
768         iph             = ip_hdr(skb);
769         iph->version    = 4;
770         iph->ihl        = (sizeof(struct iphdr)) >> 2;
771         iph->tos        = AMT_TOS;
772         iph->frag_off   = 0;
773         iph->ttl        = ip4_dst_hoplimit(&rt->dst);
774         iph->daddr      = amt->remote_ip;
775         iph->saddr      = amt->local_ip;
776         iph->protocol   = IPPROTO_UDP;
777         iph->tot_len    = htons(len);
778
779         skb->ip_summed = CHECKSUM_NONE;
780         ip_select_ident(amt->net, skb, NULL);
781         ip_send_check(iph);
782         err = ip_local_out(amt->net, sock->sk, skb);
783         if (unlikely(net_xmit_eval(err)))
784                 amt->dev->stats.tx_errors++;
785
786 out:
787         rcu_read_unlock();
788 }
789
790 static void amt_send_igmp_gq(struct amt_dev *amt,
791                              struct amt_tunnel_list *tunnel)
792 {
793         struct sk_buff *skb;
794
795         skb = amt_build_igmp_gq(amt);
796         if (!skb)
797                 return;
798
799         amt_skb_cb(skb)->tunnel = tunnel;
800         dev_queue_xmit(skb);
801 }
802
803 #if IS_ENABLED(CONFIG_IPV6)
804 static struct sk_buff *amt_build_mld_gq(struct amt_dev *amt)
805 {
806         u8 ra[AMT_IP6HDR_OPTS] = { IPPROTO_ICMPV6, 0, IPV6_TLV_ROUTERALERT,
807                                    2, 0, 0, IPV6_TLV_PAD1, IPV6_TLV_PAD1 };
808         int hlen = LL_RESERVED_SPACE(amt->dev);
809         int tlen = amt->dev->needed_tailroom;
810         struct mld2_query *mld2q;
811         void *csum_start = NULL;
812         struct ipv6hdr *ip6h;
813         struct sk_buff *skb;
814         struct ethhdr *eth;
815         u32 len;
816
817         len = hlen + tlen + sizeof(*ip6h) + sizeof(ra) + sizeof(*mld2q);
818         skb = netdev_alloc_skb_ip_align(amt->dev, len);
819         if (!skb)
820                 return NULL;
821
822         skb_reserve(skb, hlen);
823         skb_push(skb, sizeof(*eth));
824         skb_reset_mac_header(skb);
825         eth = eth_hdr(skb);
826         skb->priority = TC_PRIO_CONTROL;
827         skb->protocol = htons(ETH_P_IPV6);
828         skb_put_zero(skb, sizeof(*ip6h));
829         skb_put_data(skb, ra, sizeof(ra));
830         skb_put_zero(skb, sizeof(*mld2q));
831         skb_pull(skb, sizeof(*eth));
832         skb_reset_network_header(skb);
833         ip6h                    = ipv6_hdr(skb);
834         ip6h->payload_len       = htons(sizeof(ra) + sizeof(*mld2q));
835         ip6h->nexthdr           = NEXTHDR_HOP;
836         ip6h->hop_limit         = 1;
837         ip6h->daddr             = mld2_all_node;
838         ip6_flow_hdr(ip6h, 0, 0);
839
840         if (ipv6_dev_get_saddr(amt->net, amt->dev, &ip6h->daddr, 0,
841                                &ip6h->saddr)) {
842                 amt->dev->stats.tx_errors++;
843                 kfree_skb(skb);
844                 return NULL;
845         }
846
847         eth->h_proto = htons(ETH_P_IPV6);
848         ether_addr_copy(eth->h_source, amt->dev->dev_addr);
849         ipv6_eth_mc_map(&mld2_all_node, eth->h_dest);
850
851         skb_pull(skb, sizeof(*ip6h) + sizeof(ra));
852         skb_reset_transport_header(skb);
853         mld2q                   = (struct mld2_query *)icmp6_hdr(skb);
854         mld2q->mld2q_mrc        = htons(1);
855         mld2q->mld2q_type       = ICMPV6_MGM_QUERY;
856         mld2q->mld2q_code       = 0;
857         mld2q->mld2q_cksum      = 0;
858         mld2q->mld2q_resv1      = 0;
859         mld2q->mld2q_resv2      = 0;
860         mld2q->mld2q_suppress   = 0;
861         mld2q->mld2q_qrv        = amt->qrv;
862         mld2q->mld2q_nsrcs      = 0;
863         mld2q->mld2q_qqic       = amt->qi;
864         csum_start              = (void *)mld2q;
865         mld2q->mld2q_cksum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
866                                              sizeof(*mld2q),
867                                              IPPROTO_ICMPV6,
868                                              csum_partial(csum_start,
869                                                           sizeof(*mld2q), 0));
870
871         skb->ip_summed = CHECKSUM_NONE;
872         skb_push(skb, sizeof(*eth) + sizeof(*ip6h) + sizeof(ra));
873         return skb;
874 }
875
876 static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel)
877 {
878         struct sk_buff *skb;
879
880         skb = amt_build_mld_gq(amt);
881         if (!skb)
882                 return;
883
884         amt_skb_cb(skb)->tunnel = tunnel;
885         dev_queue_xmit(skb);
886 }
887 #else
888 static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel)
889 {
890 }
891 #endif
892
893 static bool amt_queue_event(struct amt_dev *amt, enum amt_event event,
894                             struct sk_buff *skb)
895 {
896         int index;
897
898         spin_lock_bh(&amt->lock);
899         if (amt->nr_events >= AMT_MAX_EVENTS) {
900                 spin_unlock_bh(&amt->lock);
901                 return 1;
902         }
903
904         index = (amt->event_idx + amt->nr_events) % AMT_MAX_EVENTS;
905         amt->events[index].event = event;
906         amt->events[index].skb = skb;
907         amt->nr_events++;
908         amt->event_idx %= AMT_MAX_EVENTS;
909         queue_work(amt_wq, &amt->event_wq);
910         spin_unlock_bh(&amt->lock);
911
912         return 0;
913 }
914
915 static void amt_secret_work(struct work_struct *work)
916 {
917         struct amt_dev *amt = container_of(to_delayed_work(work),
918                                            struct amt_dev,
919                                            secret_wq);
920
921         spin_lock_bh(&amt->lock);
922         get_random_bytes(&amt->key, sizeof(siphash_key_t));
923         spin_unlock_bh(&amt->lock);
924         mod_delayed_work(amt_wq, &amt->secret_wq,
925                          msecs_to_jiffies(AMT_SECRET_TIMEOUT));
926 }
927
928 static void amt_event_send_discovery(struct amt_dev *amt)
929 {
930         if (amt->status > AMT_STATUS_SENT_DISCOVERY)
931                 goto out;
932         get_random_bytes(&amt->nonce, sizeof(__be32));
933
934         amt_send_discovery(amt);
935 out:
936         mod_delayed_work(amt_wq, &amt->discovery_wq,
937                          msecs_to_jiffies(AMT_DISCOVERY_TIMEOUT));
938 }
939
940 static void amt_discovery_work(struct work_struct *work)
941 {
942         struct amt_dev *amt = container_of(to_delayed_work(work),
943                                            struct amt_dev,
944                                            discovery_wq);
945
946         if (amt_queue_event(amt, AMT_EVENT_SEND_DISCOVERY, NULL))
947                 mod_delayed_work(amt_wq, &amt->discovery_wq,
948                                  msecs_to_jiffies(AMT_DISCOVERY_TIMEOUT));
949 }
950
951 static void amt_event_send_request(struct amt_dev *amt)
952 {
953         u32 exp;
954
955         if (amt->status < AMT_STATUS_RECEIVED_ADVERTISEMENT)
956                 goto out;
957
958         if (amt->req_cnt > AMT_MAX_REQ_COUNT) {
959                 netdev_dbg(amt->dev, "Gateway is not ready");
960                 amt->qi = AMT_INIT_REQ_TIMEOUT;
961                 WRITE_ONCE(amt->ready4, false);
962                 WRITE_ONCE(amt->ready6, false);
963                 amt->remote_ip = 0;
964                 amt_update_gw_status(amt, AMT_STATUS_INIT, false);
965                 amt->req_cnt = 0;
966                 goto out;
967         }
968
969         amt_send_request(amt, false);
970         amt_send_request(amt, true);
971         amt_update_gw_status(amt, AMT_STATUS_SENT_REQUEST, true);
972         amt->req_cnt++;
973 out:
974         exp = min_t(u32, (1 * (1 << amt->req_cnt)), AMT_MAX_REQ_TIMEOUT);
975         mod_delayed_work(amt_wq, &amt->req_wq, msecs_to_jiffies(exp * 1000));
976 }
977
978 static void amt_req_work(struct work_struct *work)
979 {
980         struct amt_dev *amt = container_of(to_delayed_work(work),
981                                            struct amt_dev,
982                                            req_wq);
983
984         if (amt_queue_event(amt, AMT_EVENT_SEND_REQUEST, NULL))
985                 mod_delayed_work(amt_wq, &amt->req_wq,
986                                  msecs_to_jiffies(100));
987 }
988
989 static bool amt_send_membership_update(struct amt_dev *amt,
990                                        struct sk_buff *skb,
991                                        bool v6)
992 {
993         struct amt_header_membership_update *amtmu;
994         struct socket *sock;
995         struct iphdr *iph;
996         struct flowi4 fl4;
997         struct rtable *rt;
998         int err;
999
1000         sock = rcu_dereference_bh(amt->sock);
1001         if (!sock)
1002                 return true;
1003
1004         err = skb_cow_head(skb, LL_RESERVED_SPACE(amt->dev) + sizeof(*amtmu) +
1005                            sizeof(*iph) + sizeof(struct udphdr));
1006         if (err)
1007                 return true;
1008
1009         skb_reset_inner_headers(skb);
1010         memset(&fl4, 0, sizeof(struct flowi4));
1011         fl4.flowi4_oif         = amt->stream_dev->ifindex;
1012         fl4.daddr              = amt->remote_ip;
1013         fl4.saddr              = amt->local_ip;
1014         fl4.flowi4_tos         = AMT_TOS;
1015         fl4.flowi4_proto       = IPPROTO_UDP;
1016         rt = ip_route_output_key(amt->net, &fl4);
1017         if (IS_ERR(rt)) {
1018                 netdev_dbg(amt->dev, "no route to %pI4\n", &amt->remote_ip);
1019                 return true;
1020         }
1021
1022         amtmu                   = skb_push(skb, sizeof(*amtmu));
1023         amtmu->version          = 0;
1024         amtmu->type             = AMT_MSG_MEMBERSHIP_UPDATE;
1025         amtmu->reserved         = 0;
1026         amtmu->nonce            = amt->nonce;
1027         amtmu->response_mac     = amt->mac;
1028
1029         if (!v6)
1030                 skb_set_inner_protocol(skb, htons(ETH_P_IP));
1031         else
1032                 skb_set_inner_protocol(skb, htons(ETH_P_IPV6));
1033         udp_tunnel_xmit_skb(rt, sock->sk, skb,
1034                             fl4.saddr,
1035                             fl4.daddr,
1036                             AMT_TOS,
1037                             ip4_dst_hoplimit(&rt->dst),
1038                             0,
1039                             amt->gw_port,
1040                             amt->relay_port,
1041                             false,
1042                             false);
1043         amt_update_gw_status(amt, AMT_STATUS_SENT_UPDATE, true);
1044         return false;
1045 }
1046
1047 static void amt_send_multicast_data(struct amt_dev *amt,
1048                                     const struct sk_buff *oskb,
1049                                     struct amt_tunnel_list *tunnel,
1050                                     bool v6)
1051 {
1052         struct amt_header_mcast_data *amtmd;
1053         struct socket *sock;
1054         struct sk_buff *skb;
1055         struct iphdr *iph;
1056         struct flowi4 fl4;
1057         struct rtable *rt;
1058
1059         sock = rcu_dereference_bh(amt->sock);
1060         if (!sock)
1061                 return;
1062
1063         skb = skb_copy_expand(oskb, sizeof(*amtmd) + sizeof(*iph) +
1064                               sizeof(struct udphdr), 0, GFP_ATOMIC);
1065         if (!skb)
1066                 return;
1067
1068         skb_reset_inner_headers(skb);
1069         memset(&fl4, 0, sizeof(struct flowi4));
1070         fl4.flowi4_oif         = amt->stream_dev->ifindex;
1071         fl4.daddr              = tunnel->ip4;
1072         fl4.saddr              = amt->local_ip;
1073         fl4.flowi4_proto       = IPPROTO_UDP;
1074         rt = ip_route_output_key(amt->net, &fl4);
1075         if (IS_ERR(rt)) {
1076                 netdev_dbg(amt->dev, "no route to %pI4\n", &tunnel->ip4);
1077                 kfree_skb(skb);
1078                 return;
1079         }
1080
1081         amtmd = skb_push(skb, sizeof(*amtmd));
1082         amtmd->version = 0;
1083         amtmd->reserved = 0;
1084         amtmd->type = AMT_MSG_MULTICAST_DATA;
1085
1086         if (!v6)
1087                 skb_set_inner_protocol(skb, htons(ETH_P_IP));
1088         else
1089                 skb_set_inner_protocol(skb, htons(ETH_P_IPV6));
1090         udp_tunnel_xmit_skb(rt, sock->sk, skb,
1091                             fl4.saddr,
1092                             fl4.daddr,
1093                             AMT_TOS,
1094                             ip4_dst_hoplimit(&rt->dst),
1095                             0,
1096                             amt->relay_port,
1097                             tunnel->source_port,
1098                             false,
1099                             false);
1100 }
1101
1102 static bool amt_send_membership_query(struct amt_dev *amt,
1103                                       struct sk_buff *skb,
1104                                       struct amt_tunnel_list *tunnel,
1105                                       bool v6)
1106 {
1107         struct amt_header_membership_query *amtmq;
1108         struct socket *sock;
1109         struct rtable *rt;
1110         struct flowi4 fl4;
1111         int err;
1112
1113         sock = rcu_dereference_bh(amt->sock);
1114         if (!sock)
1115                 return true;
1116
1117         err = skb_cow_head(skb, LL_RESERVED_SPACE(amt->dev) + sizeof(*amtmq) +
1118                            sizeof(struct iphdr) + sizeof(struct udphdr));
1119         if (err)
1120                 return true;
1121
1122         skb_reset_inner_headers(skb);
1123         memset(&fl4, 0, sizeof(struct flowi4));
1124         fl4.flowi4_oif         = amt->stream_dev->ifindex;
1125         fl4.daddr              = tunnel->ip4;
1126         fl4.saddr              = amt->local_ip;
1127         fl4.flowi4_tos         = AMT_TOS;
1128         fl4.flowi4_proto       = IPPROTO_UDP;
1129         rt = ip_route_output_key(amt->net, &fl4);
1130         if (IS_ERR(rt)) {
1131                 netdev_dbg(amt->dev, "no route to %pI4\n", &tunnel->ip4);
1132                 return true;
1133         }
1134
1135         amtmq           = skb_push(skb, sizeof(*amtmq));
1136         amtmq->version  = 0;
1137         amtmq->type     = AMT_MSG_MEMBERSHIP_QUERY;
1138         amtmq->reserved = 0;
1139         amtmq->l        = 0;
1140         amtmq->g        = 0;
1141         amtmq->nonce    = tunnel->nonce;
1142         amtmq->response_mac = tunnel->mac;
1143
1144         if (!v6)
1145                 skb_set_inner_protocol(skb, htons(ETH_P_IP));
1146         else
1147                 skb_set_inner_protocol(skb, htons(ETH_P_IPV6));
1148         udp_tunnel_xmit_skb(rt, sock->sk, skb,
1149                             fl4.saddr,
1150                             fl4.daddr,
1151                             AMT_TOS,
1152                             ip4_dst_hoplimit(&rt->dst),
1153                             0,
1154                             amt->relay_port,
1155                             tunnel->source_port,
1156                             false,
1157                             false);
1158         amt_update_relay_status(tunnel, AMT_STATUS_SENT_QUERY, true);
1159         return false;
1160 }
1161
1162 static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev)
1163 {
1164         struct amt_dev *amt = netdev_priv(dev);
1165         struct amt_tunnel_list *tunnel;
1166         struct amt_group_node *gnode;
1167         union amt_addr group = {0,};
1168 #if IS_ENABLED(CONFIG_IPV6)
1169         struct ipv6hdr *ip6h;
1170         struct mld_msg *mld;
1171 #endif
1172         bool report = false;
1173         struct igmphdr *ih;
1174         bool query = false;
1175         struct iphdr *iph;
1176         bool data = false;
1177         bool v6 = false;
1178         u32 hash;
1179
1180         iph = ip_hdr(skb);
1181         if (iph->version == 4) {
1182                 if (!ipv4_is_multicast(iph->daddr))
1183                         goto free;
1184
1185                 if (!ip_mc_check_igmp(skb)) {
1186                         ih = igmp_hdr(skb);
1187                         switch (ih->type) {
1188                         case IGMPV3_HOST_MEMBERSHIP_REPORT:
1189                         case IGMP_HOST_MEMBERSHIP_REPORT:
1190                                 report = true;
1191                                 break;
1192                         case IGMP_HOST_MEMBERSHIP_QUERY:
1193                                 query = true;
1194                                 break;
1195                         default:
1196                                 goto free;
1197                         }
1198                 } else {
1199                         data = true;
1200                 }
1201                 v6 = false;
1202                 group.ip4 = iph->daddr;
1203 #if IS_ENABLED(CONFIG_IPV6)
1204         } else if (iph->version == 6) {
1205                 ip6h = ipv6_hdr(skb);
1206                 if (!ipv6_addr_is_multicast(&ip6h->daddr))
1207                         goto free;
1208
1209                 if (!ipv6_mc_check_mld(skb)) {
1210                         mld = (struct mld_msg *)skb_transport_header(skb);
1211                         switch (mld->mld_type) {
1212                         case ICMPV6_MGM_REPORT:
1213                         case ICMPV6_MLD2_REPORT:
1214                                 report = true;
1215                                 break;
1216                         case ICMPV6_MGM_QUERY:
1217                                 query = true;
1218                                 break;
1219                         default:
1220                                 goto free;
1221                         }
1222                 } else {
1223                         data = true;
1224                 }
1225                 v6 = true;
1226                 group.ip6 = ip6h->daddr;
1227 #endif
1228         } else {
1229                 dev->stats.tx_errors++;
1230                 goto free;
1231         }
1232
1233         if (!pskb_may_pull(skb, sizeof(struct ethhdr)))
1234                 goto free;
1235
1236         skb_pull(skb, sizeof(struct ethhdr));
1237
1238         if (amt->mode == AMT_MODE_GATEWAY) {
1239                 /* Gateway only passes IGMP/MLD packets */
1240                 if (!report)
1241                         goto free;
1242                 if ((!v6 && !READ_ONCE(amt->ready4)) ||
1243                     (v6 && !READ_ONCE(amt->ready6)))
1244                         goto free;
1245                 if (amt_send_membership_update(amt, skb,  v6))
1246                         goto free;
1247                 goto unlock;
1248         } else if (amt->mode == AMT_MODE_RELAY) {
1249                 if (query) {
1250                         tunnel = amt_skb_cb(skb)->tunnel;
1251                         if (!tunnel) {
1252                                 WARN_ON(1);
1253                                 goto free;
1254                         }
1255
1256                         /* Do not forward unexpected query */
1257                         if (amt_send_membership_query(amt, skb, tunnel, v6))
1258                                 goto free;
1259                         goto unlock;
1260                 }
1261
1262                 if (!data)
1263                         goto free;
1264                 list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) {
1265                         hash = amt_group_hash(tunnel, &group);
1266                         hlist_for_each_entry_rcu(gnode, &tunnel->groups[hash],
1267                                                  node) {
1268                                 if (!v6) {
1269                                         if (gnode->group_addr.ip4 == iph->daddr)
1270                                                 goto found;
1271 #if IS_ENABLED(CONFIG_IPV6)
1272                                 } else {
1273                                         if (ipv6_addr_equal(&gnode->group_addr.ip6,
1274                                                             &ip6h->daddr))
1275                                                 goto found;
1276 #endif
1277                                 }
1278                         }
1279                         continue;
1280 found:
1281                         amt_send_multicast_data(amt, skb, tunnel, v6);
1282                 }
1283         }
1284
1285         dev_kfree_skb(skb);
1286         return NETDEV_TX_OK;
1287 free:
1288         dev_kfree_skb(skb);
1289 unlock:
1290         dev->stats.tx_dropped++;
1291         return NETDEV_TX_OK;
1292 }
1293
1294 static int amt_parse_type(struct sk_buff *skb)
1295 {
1296         struct amt_header *amth;
1297
1298         if (!pskb_may_pull(skb, sizeof(struct udphdr) +
1299                            sizeof(struct amt_header)))
1300                 return -1;
1301
1302         amth = (struct amt_header *)(udp_hdr(skb) + 1);
1303
1304         if (amth->version != 0)
1305                 return -1;
1306
1307         if (amth->type >= __AMT_MSG_MAX || !amth->type)
1308                 return -1;
1309         return amth->type;
1310 }
1311
1312 static void amt_clear_groups(struct amt_tunnel_list *tunnel)
1313 {
1314         struct amt_dev *amt = tunnel->amt;
1315         struct amt_group_node *gnode;
1316         struct hlist_node *t;
1317         int i;
1318
1319         spin_lock_bh(&tunnel->lock);
1320         rcu_read_lock();
1321         for (i = 0; i < amt->hash_buckets; i++)
1322                 hlist_for_each_entry_safe(gnode, t, &tunnel->groups[i], node)
1323                         amt_del_group(amt, gnode);
1324         rcu_read_unlock();
1325         spin_unlock_bh(&tunnel->lock);
1326 }
1327
1328 static void amt_tunnel_expire(struct work_struct *work)
1329 {
1330         struct amt_tunnel_list *tunnel = container_of(to_delayed_work(work),
1331                                                       struct amt_tunnel_list,
1332                                                       gc_wq);
1333         struct amt_dev *amt = tunnel->amt;
1334
1335         spin_lock_bh(&amt->lock);
1336         rcu_read_lock();
1337         list_del_rcu(&tunnel->list);
1338         amt->nr_tunnels--;
1339         amt_clear_groups(tunnel);
1340         rcu_read_unlock();
1341         spin_unlock_bh(&amt->lock);
1342         kfree_rcu(tunnel, rcu);
1343 }
1344
1345 static void amt_cleanup_srcs(struct amt_dev *amt,
1346                              struct amt_tunnel_list *tunnel,
1347                              struct amt_group_node *gnode)
1348 {
1349         struct amt_source_node *snode;
1350         struct hlist_node *t;
1351         int i;
1352
1353         /* Delete old sources */
1354         for (i = 0; i < amt->hash_buckets; i++) {
1355                 hlist_for_each_entry_safe(snode, t, &gnode->sources[i], node) {
1356                         if (snode->flags == AMT_SOURCE_OLD)
1357                                 amt_destroy_source(snode);
1358                 }
1359         }
1360
1361         /* switch from new to old */
1362         for (i = 0; i < amt->hash_buckets; i++)  {
1363                 hlist_for_each_entry_rcu(snode, &gnode->sources[i], node) {
1364                         snode->flags = AMT_SOURCE_OLD;
1365                         if (!gnode->v6)
1366                                 netdev_dbg(snode->gnode->amt->dev,
1367                                            "Add source as OLD %pI4 from %pI4\n",
1368                                            &snode->source_addr.ip4,
1369                                            &gnode->group_addr.ip4);
1370 #if IS_ENABLED(CONFIG_IPV6)
1371                         else
1372                                 netdev_dbg(snode->gnode->amt->dev,
1373                                            "Add source as OLD %pI6 from %pI6\n",
1374                                            &snode->source_addr.ip6,
1375                                            &gnode->group_addr.ip6);
1376 #endif
1377                 }
1378         }
1379 }
1380
1381 static void amt_add_srcs(struct amt_dev *amt, struct amt_tunnel_list *tunnel,
1382                          struct amt_group_node *gnode, void *grec,
1383                          bool v6)
1384 {
1385         struct igmpv3_grec *igmp_grec;
1386         struct amt_source_node *snode;
1387 #if IS_ENABLED(CONFIG_IPV6)
1388         struct mld2_grec *mld_grec;
1389 #endif
1390         union amt_addr src = {0,};
1391         u16 nsrcs;
1392         u32 hash;
1393         int i;
1394
1395         if (!v6) {
1396                 igmp_grec = (struct igmpv3_grec *)grec;
1397                 nsrcs = ntohs(igmp_grec->grec_nsrcs);
1398         } else {
1399 #if IS_ENABLED(CONFIG_IPV6)
1400                 mld_grec = (struct mld2_grec *)grec;
1401                 nsrcs = ntohs(mld_grec->grec_nsrcs);
1402 #else
1403         return;
1404 #endif
1405         }
1406         for (i = 0; i < nsrcs; i++) {
1407                 if (tunnel->nr_sources >= amt->max_sources)
1408                         return;
1409                 if (!v6)
1410                         src.ip4 = igmp_grec->grec_src[i];
1411 #if IS_ENABLED(CONFIG_IPV6)
1412                 else
1413                         memcpy(&src.ip6, &mld_grec->grec_src[i],
1414                                sizeof(struct in6_addr));
1415 #endif
1416                 if (amt_lookup_src(tunnel, gnode, AMT_FILTER_ALL, &src))
1417                         continue;
1418
1419                 snode = amt_alloc_snode(gnode, &src);
1420                 if (snode) {
1421                         hash = amt_source_hash(tunnel, &snode->source_addr);
1422                         hlist_add_head_rcu(&snode->node, &gnode->sources[hash]);
1423                         tunnel->nr_sources++;
1424                         gnode->nr_sources++;
1425
1426                         if (!gnode->v6)
1427                                 netdev_dbg(snode->gnode->amt->dev,
1428                                            "Add source as NEW %pI4 from %pI4\n",
1429                                            &snode->source_addr.ip4,
1430                                            &gnode->group_addr.ip4);
1431 #if IS_ENABLED(CONFIG_IPV6)
1432                         else
1433                                 netdev_dbg(snode->gnode->amt->dev,
1434                                            "Add source as NEW %pI6 from %pI6\n",
1435                                            &snode->source_addr.ip6,
1436                                            &gnode->group_addr.ip6);
1437 #endif
1438                 }
1439         }
1440 }
1441
1442 /* Router State   Report Rec'd New Router State
1443  * ------------   ------------ ----------------
1444  * EXCLUDE (X,Y)  IS_IN (A)    EXCLUDE (X+A,Y-A)
1445  *
1446  * -----------+-----------+-----------+
1447  *            |    OLD    |    NEW    |
1448  * -----------+-----------+-----------+
1449  *    FWD     |     X     |    X+A    |
1450  * -----------+-----------+-----------+
1451  *    D_FWD   |     Y     |    Y-A    |
1452  * -----------+-----------+-----------+
1453  *    NONE    |           |     A     |
1454  * -----------+-----------+-----------+
1455  *
1456  * a) Received sources are NONE/NEW
1457  * b) All NONE will be deleted by amt_cleanup_srcs().
1458  * c) All OLD will be deleted by amt_cleanup_srcs().
1459  * d) After delete, NEW source will be switched to OLD.
1460  */
1461 static void amt_lookup_act_srcs(struct amt_tunnel_list *tunnel,
1462                                 struct amt_group_node *gnode,
1463                                 void *grec,
1464                                 enum amt_ops ops,
1465                                 enum amt_filter filter,
1466                                 enum amt_act act,
1467                                 bool v6)
1468 {
1469         struct amt_dev *amt = tunnel->amt;
1470         struct amt_source_node *snode;
1471         struct igmpv3_grec *igmp_grec;
1472 #if IS_ENABLED(CONFIG_IPV6)
1473         struct mld2_grec *mld_grec;
1474 #endif
1475         union amt_addr src = {0,};
1476         struct hlist_node *t;
1477         u16 nsrcs;
1478         int i, j;
1479
1480         if (!v6) {
1481                 igmp_grec = (struct igmpv3_grec *)grec;
1482                 nsrcs = ntohs(igmp_grec->grec_nsrcs);
1483         } else {
1484 #if IS_ENABLED(CONFIG_IPV6)
1485                 mld_grec = (struct mld2_grec *)grec;
1486                 nsrcs = ntohs(mld_grec->grec_nsrcs);
1487 #else
1488         return;
1489 #endif
1490         }
1491
1492         memset(&src, 0, sizeof(union amt_addr));
1493         switch (ops) {
1494         case AMT_OPS_INT:
1495                 /* A*B */
1496                 for (i = 0; i < nsrcs; i++) {
1497                         if (!v6)
1498                                 src.ip4 = igmp_grec->grec_src[i];
1499 #if IS_ENABLED(CONFIG_IPV6)
1500                         else
1501                                 memcpy(&src.ip6, &mld_grec->grec_src[i],
1502                                        sizeof(struct in6_addr));
1503 #endif
1504                         snode = amt_lookup_src(tunnel, gnode, filter, &src);
1505                         if (!snode)
1506                                 continue;
1507                         amt_act_src(tunnel, gnode, snode, act);
1508                 }
1509                 break;
1510         case AMT_OPS_UNI:
1511                 /* A+B */
1512                 for (i = 0; i < amt->hash_buckets; i++) {
1513                         hlist_for_each_entry_safe(snode, t, &gnode->sources[i],
1514                                                   node) {
1515                                 if (amt_status_filter(snode, filter))
1516                                         amt_act_src(tunnel, gnode, snode, act);
1517                         }
1518                 }
1519                 for (i = 0; i < nsrcs; i++) {
1520                         if (!v6)
1521                                 src.ip4 = igmp_grec->grec_src[i];
1522 #if IS_ENABLED(CONFIG_IPV6)
1523                         else
1524                                 memcpy(&src.ip6, &mld_grec->grec_src[i],
1525                                        sizeof(struct in6_addr));
1526 #endif
1527                         snode = amt_lookup_src(tunnel, gnode, filter, &src);
1528                         if (!snode)
1529                                 continue;
1530                         amt_act_src(tunnel, gnode, snode, act);
1531                 }
1532                 break;
1533         case AMT_OPS_SUB:
1534                 /* A-B */
1535                 for (i = 0; i < amt->hash_buckets; i++) {
1536                         hlist_for_each_entry_safe(snode, t, &gnode->sources[i],
1537                                                   node) {
1538                                 if (!amt_status_filter(snode, filter))
1539                                         continue;
1540                                 for (j = 0; j < nsrcs; j++) {
1541                                         if (!v6)
1542                                                 src.ip4 = igmp_grec->grec_src[j];
1543 #if IS_ENABLED(CONFIG_IPV6)
1544                                         else
1545                                                 memcpy(&src.ip6,
1546                                                        &mld_grec->grec_src[j],
1547                                                        sizeof(struct in6_addr));
1548 #endif
1549                                         if (amt_addr_equal(&snode->source_addr,
1550                                                            &src))
1551                                                 goto out_sub;
1552                                 }
1553                                 amt_act_src(tunnel, gnode, snode, act);
1554                                 continue;
1555 out_sub:;
1556                         }
1557                 }
1558                 break;
1559         case AMT_OPS_SUB_REV:
1560                 /* B-A */
1561                 for (i = 0; i < nsrcs; i++) {
1562                         if (!v6)
1563                                 src.ip4 = igmp_grec->grec_src[i];
1564 #if IS_ENABLED(CONFIG_IPV6)
1565                         else
1566                                 memcpy(&src.ip6, &mld_grec->grec_src[i],
1567                                        sizeof(struct in6_addr));
1568 #endif
1569                         snode = amt_lookup_src(tunnel, gnode, AMT_FILTER_ALL,
1570                                                &src);
1571                         if (!snode) {
1572                                 snode = amt_lookup_src(tunnel, gnode,
1573                                                        filter, &src);
1574                                 if (snode)
1575                                         amt_act_src(tunnel, gnode, snode, act);
1576                         }
1577                 }
1578                 break;
1579         default:
1580                 netdev_dbg(amt->dev, "Invalid type\n");
1581                 return;
1582         }
1583 }
1584
1585 static void amt_mcast_is_in_handler(struct amt_dev *amt,
1586                                     struct amt_tunnel_list *tunnel,
1587                                     struct amt_group_node *gnode,
1588                                     void *grec, void *zero_grec, bool v6)
1589 {
1590         if (gnode->filter_mode == MCAST_INCLUDE) {
1591 /* Router State   Report Rec'd New Router State        Actions
1592  * ------------   ------------ ----------------        -------
1593  * INCLUDE (A)    IS_IN (B)    INCLUDE (A+B)           (B)=GMI
1594  */
1595                 /* Update IS_IN (B) as FWD/NEW */
1596                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1597                                     AMT_FILTER_NONE_NEW,
1598                                     AMT_ACT_STATUS_FWD_NEW,
1599                                     v6);
1600                 /* Update INCLUDE (A) as NEW */
1601                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1602                                     AMT_FILTER_FWD,
1603                                     AMT_ACT_STATUS_FWD_NEW,
1604                                     v6);
1605                 /* (B)=GMI */
1606                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1607                                     AMT_FILTER_FWD_NEW,
1608                                     AMT_ACT_GMI,
1609                                     v6);
1610         } else {
1611 /* State        Actions
1612  * ------------   ------------ ----------------        -------
1613  * EXCLUDE (X,Y)  IS_IN (A)    EXCLUDE (X+A,Y-A)       (A)=GMI
1614  */
1615                 /* Update (A) in (X, Y) as NONE/NEW */
1616                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1617                                     AMT_FILTER_BOTH,
1618                                     AMT_ACT_STATUS_NONE_NEW,
1619                                     v6);
1620                 /* Update FWD/OLD as FWD/NEW */
1621                 amt_lookup_act_srcs(tunnel, gnode, zero_grec, AMT_OPS_UNI,
1622                                     AMT_FILTER_FWD,
1623                                     AMT_ACT_STATUS_FWD_NEW,
1624                                     v6);
1625                 /* Update IS_IN (A) as FWD/NEW */
1626                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1627                                     AMT_FILTER_NONE_NEW,
1628                                     AMT_ACT_STATUS_FWD_NEW,
1629                                     v6);
1630                 /* Update EXCLUDE (, Y-A) as D_FWD_NEW */
1631                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB,
1632                                     AMT_FILTER_D_FWD,
1633                                     AMT_ACT_STATUS_D_FWD_NEW,
1634                                     v6);
1635         }
1636 }
1637
1638 static void amt_mcast_is_ex_handler(struct amt_dev *amt,
1639                                     struct amt_tunnel_list *tunnel,
1640                                     struct amt_group_node *gnode,
1641                                     void *grec, void *zero_grec, bool v6)
1642 {
1643         if (gnode->filter_mode == MCAST_INCLUDE) {
1644 /* Router State   Report Rec'd  New Router State         Actions
1645  * ------------   ------------  ----------------         -------
1646  * INCLUDE (A)    IS_EX (B)     EXCLUDE (A*B,B-A)        (B-A)=0
1647  *                                                       Delete (A-B)
1648  *                                                       Group Timer=GMI
1649  */
1650                 /* EXCLUDE(A*B, ) */
1651                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1652                                     AMT_FILTER_FWD,
1653                                     AMT_ACT_STATUS_FWD_NEW,
1654                                     v6);
1655                 /* EXCLUDE(, B-A) */
1656                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1657                                     AMT_FILTER_FWD,
1658                                     AMT_ACT_STATUS_D_FWD_NEW,
1659                                     v6);
1660                 /* (B-A)=0 */
1661                 amt_lookup_act_srcs(tunnel, gnode, zero_grec, AMT_OPS_UNI,
1662                                     AMT_FILTER_D_FWD_NEW,
1663                                     AMT_ACT_GMI_ZERO,
1664                                     v6);
1665                 /* Group Timer=GMI */
1666                 if (!mod_delayed_work(amt_wq, &gnode->group_timer,
1667                                       msecs_to_jiffies(amt_gmi(amt))))
1668                         dev_hold(amt->dev);
1669                 gnode->filter_mode = MCAST_EXCLUDE;
1670                 /* Delete (A-B) will be worked by amt_cleanup_srcs(). */
1671         } else {
1672 /* Router State   Report Rec'd  New Router State        Actions
1673  * ------------   ------------  ----------------        -------
1674  * EXCLUDE (X,Y)  IS_EX (A)     EXCLUDE (A-Y,Y*A)       (A-X-Y)=GMI
1675  *                                                      Delete (X-A)
1676  *                                                      Delete (Y-A)
1677  *                                                      Group Timer=GMI
1678  */
1679                 /* EXCLUDE (A-Y, ) */
1680                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1681                                     AMT_FILTER_D_FWD,
1682                                     AMT_ACT_STATUS_FWD_NEW,
1683                                     v6);
1684                 /* EXCLUDE (, Y*A ) */
1685                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1686                                     AMT_FILTER_D_FWD,
1687                                     AMT_ACT_STATUS_D_FWD_NEW,
1688                                     v6);
1689                 /* (A-X-Y)=GMI */
1690                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1691                                     AMT_FILTER_BOTH_NEW,
1692                                     AMT_ACT_GMI,
1693                                     v6);
1694                 /* Group Timer=GMI */
1695                 if (!mod_delayed_work(amt_wq, &gnode->group_timer,
1696                                       msecs_to_jiffies(amt_gmi(amt))))
1697                         dev_hold(amt->dev);
1698                 /* Delete (X-A), (Y-A) will be worked by amt_cleanup_srcs(). */
1699         }
1700 }
1701
1702 static void amt_mcast_to_in_handler(struct amt_dev *amt,
1703                                     struct amt_tunnel_list *tunnel,
1704                                     struct amt_group_node *gnode,
1705                                     void *grec, void *zero_grec, bool v6)
1706 {
1707         if (gnode->filter_mode == MCAST_INCLUDE) {
1708 /* Router State   Report Rec'd New Router State        Actions
1709  * ------------   ------------ ----------------        -------
1710  * INCLUDE (A)    TO_IN (B)    INCLUDE (A+B)           (B)=GMI
1711  *                                                     Send Q(G,A-B)
1712  */
1713                 /* Update TO_IN (B) sources as FWD/NEW */
1714                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1715                                     AMT_FILTER_NONE_NEW,
1716                                     AMT_ACT_STATUS_FWD_NEW,
1717                                     v6);
1718                 /* Update INCLUDE (A) sources as NEW */
1719                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1720                                     AMT_FILTER_FWD,
1721                                     AMT_ACT_STATUS_FWD_NEW,
1722                                     v6);
1723                 /* (B)=GMI */
1724                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1725                                     AMT_FILTER_FWD_NEW,
1726                                     AMT_ACT_GMI,
1727                                     v6);
1728         } else {
1729 /* Router State   Report Rec'd New Router State        Actions
1730  * ------------   ------------ ----------------        -------
1731  * EXCLUDE (X,Y)  TO_IN (A)    EXCLUDE (X+A,Y-A)       (A)=GMI
1732  *                                                     Send Q(G,X-A)
1733  *                                                     Send Q(G)
1734  */
1735                 /* Update TO_IN (A) sources as FWD/NEW */
1736                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1737                                     AMT_FILTER_NONE_NEW,
1738                                     AMT_ACT_STATUS_FWD_NEW,
1739                                     v6);
1740                 /* Update EXCLUDE(X,) sources as FWD/NEW */
1741                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1742                                     AMT_FILTER_FWD,
1743                                     AMT_ACT_STATUS_FWD_NEW,
1744                                     v6);
1745                 /* EXCLUDE (, Y-A)
1746                  * (A) are already switched to FWD_NEW.
1747                  * So, D_FWD/OLD -> D_FWD/NEW is okay.
1748                  */
1749                 amt_lookup_act_srcs(tunnel, gnode, zero_grec, AMT_OPS_UNI,
1750                                     AMT_FILTER_D_FWD,
1751                                     AMT_ACT_STATUS_D_FWD_NEW,
1752                                     v6);
1753                 /* (A)=GMI
1754                  * Only FWD_NEW will have (A) sources.
1755                  */
1756                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1757                                     AMT_FILTER_FWD_NEW,
1758                                     AMT_ACT_GMI,
1759                                     v6);
1760         }
1761 }
1762
1763 static void amt_mcast_to_ex_handler(struct amt_dev *amt,
1764                                     struct amt_tunnel_list *tunnel,
1765                                     struct amt_group_node *gnode,
1766                                     void *grec, void *zero_grec, bool v6)
1767 {
1768         if (gnode->filter_mode == MCAST_INCLUDE) {
1769 /* Router State   Report Rec'd New Router State        Actions
1770  * ------------   ------------ ----------------        -------
1771  * INCLUDE (A)    TO_EX (B)    EXCLUDE (A*B,B-A)       (B-A)=0
1772  *                                                     Delete (A-B)
1773  *                                                     Send Q(G,A*B)
1774  *                                                     Group Timer=GMI
1775  */
1776                 /* EXCLUDE (A*B, ) */
1777                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1778                                     AMT_FILTER_FWD,
1779                                     AMT_ACT_STATUS_FWD_NEW,
1780                                     v6);
1781                 /* EXCLUDE (, B-A) */
1782                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1783                                     AMT_FILTER_FWD,
1784                                     AMT_ACT_STATUS_D_FWD_NEW,
1785                                     v6);
1786                 /* (B-A)=0 */
1787                 amt_lookup_act_srcs(tunnel, gnode, zero_grec, AMT_OPS_UNI,
1788                                     AMT_FILTER_D_FWD_NEW,
1789                                     AMT_ACT_GMI_ZERO,
1790                                     v6);
1791                 /* Group Timer=GMI */
1792                 if (!mod_delayed_work(amt_wq, &gnode->group_timer,
1793                                       msecs_to_jiffies(amt_gmi(amt))))
1794                         dev_hold(amt->dev);
1795                 gnode->filter_mode = MCAST_EXCLUDE;
1796                 /* Delete (A-B) will be worked by amt_cleanup_srcs(). */
1797         } else {
1798 /* Router State   Report Rec'd New Router State        Actions
1799  * ------------   ------------ ----------------        -------
1800  * EXCLUDE (X,Y)  TO_EX (A)    EXCLUDE (A-Y,Y*A)       (A-X-Y)=Group Timer
1801  *                                                     Delete (X-A)
1802  *                                                     Delete (Y-A)
1803  *                                                     Send Q(G,A-Y)
1804  *                                                     Group Timer=GMI
1805  */
1806                 /* Update (A-X-Y) as NONE/OLD */
1807                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1808                                     AMT_FILTER_BOTH,
1809                                     AMT_ACT_GT,
1810                                     v6);
1811                 /* EXCLUDE (A-Y, ) */
1812                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1813                                     AMT_FILTER_D_FWD,
1814                                     AMT_ACT_STATUS_FWD_NEW,
1815                                     v6);
1816                 /* EXCLUDE (, Y*A) */
1817                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1818                                     AMT_FILTER_D_FWD,
1819                                     AMT_ACT_STATUS_D_FWD_NEW,
1820                                     v6);
1821                 /* Group Timer=GMI */
1822                 if (!mod_delayed_work(amt_wq, &gnode->group_timer,
1823                                       msecs_to_jiffies(amt_gmi(amt))))
1824                         dev_hold(amt->dev);
1825                 /* Delete (X-A), (Y-A) will be worked by amt_cleanup_srcs(). */
1826         }
1827 }
1828
1829 static void amt_mcast_allow_handler(struct amt_dev *amt,
1830                                     struct amt_tunnel_list *tunnel,
1831                                     struct amt_group_node *gnode,
1832                                     void *grec, void *zero_grec, bool v6)
1833 {
1834         if (gnode->filter_mode == MCAST_INCLUDE) {
1835 /* Router State   Report Rec'd New Router State        Actions
1836  * ------------   ------------ ----------------        -------
1837  * INCLUDE (A)    ALLOW (B)    INCLUDE (A+B)           (B)=GMI
1838  */
1839                 /* INCLUDE (A+B) */
1840                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1841                                     AMT_FILTER_FWD,
1842                                     AMT_ACT_STATUS_FWD_NEW,
1843                                     v6);
1844                 /* (B)=GMI */
1845                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1846                                     AMT_FILTER_FWD_NEW,
1847                                     AMT_ACT_GMI,
1848                                     v6);
1849         } else {
1850 /* Router State   Report Rec'd New Router State        Actions
1851  * ------------   ------------ ----------------        -------
1852  * EXCLUDE (X,Y)  ALLOW (A)    EXCLUDE (X+A,Y-A)       (A)=GMI
1853  */
1854                 /* EXCLUDE (X+A, ) */
1855                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1856                                     AMT_FILTER_FWD,
1857                                     AMT_ACT_STATUS_FWD_NEW,
1858                                     v6);
1859                 /* EXCLUDE (, Y-A) */
1860                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB,
1861                                     AMT_FILTER_D_FWD,
1862                                     AMT_ACT_STATUS_D_FWD_NEW,
1863                                     v6);
1864                 /* (A)=GMI
1865                  * All (A) source are now FWD/NEW status.
1866                  */
1867                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_INT,
1868                                     AMT_FILTER_FWD_NEW,
1869                                     AMT_ACT_GMI,
1870                                     v6);
1871         }
1872 }
1873
1874 static void amt_mcast_block_handler(struct amt_dev *amt,
1875                                     struct amt_tunnel_list *tunnel,
1876                                     struct amt_group_node *gnode,
1877                                     void *grec, void *zero_grec, bool v6)
1878 {
1879         if (gnode->filter_mode == MCAST_INCLUDE) {
1880 /* Router State   Report Rec'd New Router State        Actions
1881  * ------------   ------------ ----------------        -------
1882  * INCLUDE (A)    BLOCK (B)    INCLUDE (A)             Send Q(G,A*B)
1883  */
1884                 /* INCLUDE (A) */
1885                 amt_lookup_act_srcs(tunnel, gnode, zero_grec, AMT_OPS_UNI,
1886                                     AMT_FILTER_FWD,
1887                                     AMT_ACT_STATUS_FWD_NEW,
1888                                     v6);
1889         } else {
1890 /* Router State   Report Rec'd New Router State        Actions
1891  * ------------   ------------ ----------------        -------
1892  * EXCLUDE (X,Y)  BLOCK (A)    EXCLUDE (X+(A-Y),Y)     (A-X-Y)=Group Timer
1893  *                                                     Send Q(G,A-Y)
1894  */
1895                 /* (A-X-Y)=Group Timer */
1896                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1897                                     AMT_FILTER_BOTH,
1898                                     AMT_ACT_GT,
1899                                     v6);
1900                 /* EXCLUDE (X, ) */
1901                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1902                                     AMT_FILTER_FWD,
1903                                     AMT_ACT_STATUS_FWD_NEW,
1904                                     v6);
1905                 /* EXCLUDE (X+(A-Y) */
1906                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_SUB_REV,
1907                                     AMT_FILTER_D_FWD,
1908                                     AMT_ACT_STATUS_FWD_NEW,
1909                                     v6);
1910                 /* EXCLUDE (, Y) */
1911                 amt_lookup_act_srcs(tunnel, gnode, grec, AMT_OPS_UNI,
1912                                     AMT_FILTER_D_FWD,
1913                                     AMT_ACT_STATUS_D_FWD_NEW,
1914                                     v6);
1915         }
1916 }
1917
1918 /* RFC 3376
1919  * 7.3.2. In the Presence of Older Version Group Members
1920  *
1921  * When Group Compatibility Mode is IGMPv2, a router internally
1922  * translates the following IGMPv2 messages for that group to their
1923  * IGMPv3 equivalents:
1924  *
1925  * IGMPv2 Message                IGMPv3 Equivalent
1926  * --------------                -----------------
1927  * Report                        IS_EX( {} )
1928  * Leave                         TO_IN( {} )
1929  */
1930 static void amt_igmpv2_report_handler(struct amt_dev *amt, struct sk_buff *skb,
1931                                       struct amt_tunnel_list *tunnel)
1932 {
1933         struct igmphdr *ih = igmp_hdr(skb);
1934         struct iphdr *iph = ip_hdr(skb);
1935         struct amt_group_node *gnode;
1936         union amt_addr group, host;
1937
1938         memset(&group, 0, sizeof(union amt_addr));
1939         group.ip4 = ih->group;
1940         memset(&host, 0, sizeof(union amt_addr));
1941         host.ip4 = iph->saddr;
1942
1943         gnode = amt_lookup_group(tunnel, &group, &host, false);
1944         if (!gnode) {
1945                 gnode = amt_add_group(amt, tunnel, &group, &host, false);
1946                 if (!IS_ERR(gnode)) {
1947                         gnode->filter_mode = MCAST_EXCLUDE;
1948                         if (!mod_delayed_work(amt_wq, &gnode->group_timer,
1949                                               msecs_to_jiffies(amt_gmi(amt))))
1950                                 dev_hold(amt->dev);
1951                 }
1952         }
1953 }
1954
1955 /* RFC 3376
1956  * 7.3.2. In the Presence of Older Version Group Members
1957  *
1958  * When Group Compatibility Mode is IGMPv2, a router internally
1959  * translates the following IGMPv2 messages for that group to their
1960  * IGMPv3 equivalents:
1961  *
1962  * IGMPv2 Message                IGMPv3 Equivalent
1963  * --------------                -----------------
1964  * Report                        IS_EX( {} )
1965  * Leave                         TO_IN( {} )
1966  */
1967 static void amt_igmpv2_leave_handler(struct amt_dev *amt, struct sk_buff *skb,
1968                                      struct amt_tunnel_list *tunnel)
1969 {
1970         struct igmphdr *ih = igmp_hdr(skb);
1971         struct iphdr *iph = ip_hdr(skb);
1972         struct amt_group_node *gnode;
1973         union amt_addr group, host;
1974
1975         memset(&group, 0, sizeof(union amt_addr));
1976         group.ip4 = ih->group;
1977         memset(&host, 0, sizeof(union amt_addr));
1978         host.ip4 = iph->saddr;
1979
1980         gnode = amt_lookup_group(tunnel, &group, &host, false);
1981         if (gnode)
1982                 amt_del_group(amt, gnode);
1983 }
1984
1985 static void amt_igmpv3_report_handler(struct amt_dev *amt, struct sk_buff *skb,
1986                                       struct amt_tunnel_list *tunnel)
1987 {
1988         struct igmpv3_report *ihrv3 = igmpv3_report_hdr(skb);
1989         int len = skb_transport_offset(skb) + sizeof(*ihrv3);
1990         void *zero_grec = (void *)&igmpv3_zero_grec;
1991         struct iphdr *iph = ip_hdr(skb);
1992         struct amt_group_node *gnode;
1993         union amt_addr group, host;
1994         struct igmpv3_grec *grec;
1995         u16 nsrcs;
1996         int i;
1997
1998         for (i = 0; i < ntohs(ihrv3->ngrec); i++) {
1999                 len += sizeof(*grec);
2000                 if (!ip_mc_may_pull(skb, len))
2001                         break;
2002
2003                 grec = (void *)(skb->data + len - sizeof(*grec));
2004                 nsrcs = ntohs(grec->grec_nsrcs);
2005
2006                 len += nsrcs * sizeof(__be32);
2007                 if (!ip_mc_may_pull(skb, len))
2008                         break;
2009
2010                 memset(&group, 0, sizeof(union amt_addr));
2011                 group.ip4 = grec->grec_mca;
2012                 memset(&host, 0, sizeof(union amt_addr));
2013                 host.ip4 = iph->saddr;
2014                 gnode = amt_lookup_group(tunnel, &group, &host, false);
2015                 if (!gnode) {
2016                         gnode = amt_add_group(amt, tunnel, &group, &host,
2017                                               false);
2018                         if (IS_ERR(gnode))
2019                                 continue;
2020                 }
2021
2022                 amt_add_srcs(amt, tunnel, gnode, grec, false);
2023                 switch (grec->grec_type) {
2024                 case IGMPV3_MODE_IS_INCLUDE:
2025                         amt_mcast_is_in_handler(amt, tunnel, gnode, grec,
2026                                                 zero_grec, false);
2027                         break;
2028                 case IGMPV3_MODE_IS_EXCLUDE:
2029                         amt_mcast_is_ex_handler(amt, tunnel, gnode, grec,
2030                                                 zero_grec, false);
2031                         break;
2032                 case IGMPV3_CHANGE_TO_INCLUDE:
2033                         amt_mcast_to_in_handler(amt, tunnel, gnode, grec,
2034                                                 zero_grec, false);
2035                         break;
2036                 case IGMPV3_CHANGE_TO_EXCLUDE:
2037                         amt_mcast_to_ex_handler(amt, tunnel, gnode, grec,
2038                                                 zero_grec, false);
2039                         break;
2040                 case IGMPV3_ALLOW_NEW_SOURCES:
2041                         amt_mcast_allow_handler(amt, tunnel, gnode, grec,
2042                                                 zero_grec, false);
2043                         break;
2044                 case IGMPV3_BLOCK_OLD_SOURCES:
2045                         amt_mcast_block_handler(amt, tunnel, gnode, grec,
2046                                                 zero_grec, false);
2047                         break;
2048                 default:
2049                         break;
2050                 }
2051                 amt_cleanup_srcs(amt, tunnel, gnode);
2052         }
2053 }
2054
2055 /* caller held tunnel->lock */
2056 static void amt_igmp_report_handler(struct amt_dev *amt, struct sk_buff *skb,
2057                                     struct amt_tunnel_list *tunnel)
2058 {
2059         struct igmphdr *ih = igmp_hdr(skb);
2060
2061         switch (ih->type) {
2062         case IGMPV3_HOST_MEMBERSHIP_REPORT:
2063                 amt_igmpv3_report_handler(amt, skb, tunnel);
2064                 break;
2065         case IGMPV2_HOST_MEMBERSHIP_REPORT:
2066                 amt_igmpv2_report_handler(amt, skb, tunnel);
2067                 break;
2068         case IGMP_HOST_LEAVE_MESSAGE:
2069                 amt_igmpv2_leave_handler(amt, skb, tunnel);
2070                 break;
2071         default:
2072                 break;
2073         }
2074 }
2075
2076 #if IS_ENABLED(CONFIG_IPV6)
2077 /* RFC 3810
2078  * 8.3.2. In the Presence of MLDv1 Multicast Address Listeners
2079  *
2080  * When Multicast Address Compatibility Mode is MLDv2, a router acts
2081  * using the MLDv2 protocol for that multicast address.  When Multicast
2082  * Address Compatibility Mode is MLDv1, a router internally translates
2083  * the following MLDv1 messages for that multicast address to their
2084  * MLDv2 equivalents:
2085  *
2086  * MLDv1 Message                 MLDv2 Equivalent
2087  * --------------                -----------------
2088  * Report                        IS_EX( {} )
2089  * Done                          TO_IN( {} )
2090  */
2091 static void amt_mldv1_report_handler(struct amt_dev *amt, struct sk_buff *skb,
2092                                      struct amt_tunnel_list *tunnel)
2093 {
2094         struct mld_msg *mld = (struct mld_msg *)icmp6_hdr(skb);
2095         struct ipv6hdr *ip6h = ipv6_hdr(skb);
2096         struct amt_group_node *gnode;
2097         union amt_addr group, host;
2098
2099         memcpy(&group.ip6, &mld->mld_mca, sizeof(struct in6_addr));
2100         memcpy(&host.ip6, &ip6h->saddr, sizeof(struct in6_addr));
2101
2102         gnode = amt_lookup_group(tunnel, &group, &host, true);
2103         if (!gnode) {
2104                 gnode = amt_add_group(amt, tunnel, &group, &host, true);
2105                 if (!IS_ERR(gnode)) {
2106                         gnode->filter_mode = MCAST_EXCLUDE;
2107                         if (!mod_delayed_work(amt_wq, &gnode->group_timer,
2108                                               msecs_to_jiffies(amt_gmi(amt))))
2109                                 dev_hold(amt->dev);
2110                 }
2111         }
2112 }
2113
2114 /* RFC 3810
2115  * 8.3.2. In the Presence of MLDv1 Multicast Address Listeners
2116  *
2117  * When Multicast Address Compatibility Mode is MLDv2, a router acts
2118  * using the MLDv2 protocol for that multicast address.  When Multicast
2119  * Address Compatibility Mode is MLDv1, a router internally translates
2120  * the following MLDv1 messages for that multicast address to their
2121  * MLDv2 equivalents:
2122  *
2123  * MLDv1 Message                 MLDv2 Equivalent
2124  * --------------                -----------------
2125  * Report                        IS_EX( {} )
2126  * Done                          TO_IN( {} )
2127  */
2128 static void amt_mldv1_leave_handler(struct amt_dev *amt, struct sk_buff *skb,
2129                                     struct amt_tunnel_list *tunnel)
2130 {
2131         struct mld_msg *mld = (struct mld_msg *)icmp6_hdr(skb);
2132         struct iphdr *iph = ip_hdr(skb);
2133         struct amt_group_node *gnode;
2134         union amt_addr group, host;
2135
2136         memcpy(&group.ip6, &mld->mld_mca, sizeof(struct in6_addr));
2137         memset(&host, 0, sizeof(union amt_addr));
2138         host.ip4 = iph->saddr;
2139
2140         gnode = amt_lookup_group(tunnel, &group, &host, true);
2141         if (gnode) {
2142                 amt_del_group(amt, gnode);
2143                 return;
2144         }
2145 }
2146
2147 static void amt_mldv2_report_handler(struct amt_dev *amt, struct sk_buff *skb,
2148                                      struct amt_tunnel_list *tunnel)
2149 {
2150         struct mld2_report *mld2r = (struct mld2_report *)icmp6_hdr(skb);
2151         int len = skb_transport_offset(skb) + sizeof(*mld2r);
2152         void *zero_grec = (void *)&mldv2_zero_grec;
2153         struct ipv6hdr *ip6h = ipv6_hdr(skb);
2154         struct amt_group_node *gnode;
2155         union amt_addr group, host;
2156         struct mld2_grec *grec;
2157         u16 nsrcs;
2158         int i;
2159
2160         for (i = 0; i < ntohs(mld2r->mld2r_ngrec); i++) {
2161                 len += sizeof(*grec);
2162                 if (!ipv6_mc_may_pull(skb, len))
2163                         break;
2164
2165                 grec = (void *)(skb->data + len - sizeof(*grec));
2166                 nsrcs = ntohs(grec->grec_nsrcs);
2167
2168                 len += nsrcs * sizeof(struct in6_addr);
2169                 if (!ipv6_mc_may_pull(skb, len))
2170                         break;
2171
2172                 memset(&group, 0, sizeof(union amt_addr));
2173                 group.ip6 = grec->grec_mca;
2174                 memset(&host, 0, sizeof(union amt_addr));
2175                 host.ip6 = ip6h->saddr;
2176                 gnode = amt_lookup_group(tunnel, &group, &host, true);
2177                 if (!gnode) {
2178                         gnode = amt_add_group(amt, tunnel, &group, &host,
2179                                               ETH_P_IPV6);
2180                         if (IS_ERR(gnode))
2181                                 continue;
2182                 }
2183
2184                 amt_add_srcs(amt, tunnel, gnode, grec, true);
2185                 switch (grec->grec_type) {
2186                 case MLD2_MODE_IS_INCLUDE:
2187                         amt_mcast_is_in_handler(amt, tunnel, gnode, grec,
2188                                                 zero_grec, true);
2189                         break;
2190                 case MLD2_MODE_IS_EXCLUDE:
2191                         amt_mcast_is_ex_handler(amt, tunnel, gnode, grec,
2192                                                 zero_grec, true);
2193                         break;
2194                 case MLD2_CHANGE_TO_INCLUDE:
2195                         amt_mcast_to_in_handler(amt, tunnel, gnode, grec,
2196                                                 zero_grec, true);
2197                         break;
2198                 case MLD2_CHANGE_TO_EXCLUDE:
2199                         amt_mcast_to_ex_handler(amt, tunnel, gnode, grec,
2200                                                 zero_grec, true);
2201                         break;
2202                 case MLD2_ALLOW_NEW_SOURCES:
2203                         amt_mcast_allow_handler(amt, tunnel, gnode, grec,
2204                                                 zero_grec, true);
2205                         break;
2206                 case MLD2_BLOCK_OLD_SOURCES:
2207                         amt_mcast_block_handler(amt, tunnel, gnode, grec,
2208                                                 zero_grec, true);
2209                         break;
2210                 default:
2211                         break;
2212                 }
2213                 amt_cleanup_srcs(amt, tunnel, gnode);
2214         }
2215 }
2216
2217 /* caller held tunnel->lock */
2218 static void amt_mld_report_handler(struct amt_dev *amt, struct sk_buff *skb,
2219                                    struct amt_tunnel_list *tunnel)
2220 {
2221         struct mld_msg *mld = (struct mld_msg *)icmp6_hdr(skb);
2222
2223         switch (mld->mld_type) {
2224         case ICMPV6_MGM_REPORT:
2225                 amt_mldv1_report_handler(amt, skb, tunnel);
2226                 break;
2227         case ICMPV6_MLD2_REPORT:
2228                 amt_mldv2_report_handler(amt, skb, tunnel);
2229                 break;
2230         case ICMPV6_MGM_REDUCTION:
2231                 amt_mldv1_leave_handler(amt, skb, tunnel);
2232                 break;
2233         default:
2234                 break;
2235         }
2236 }
2237 #endif
2238
2239 static bool amt_advertisement_handler(struct amt_dev *amt, struct sk_buff *skb)
2240 {
2241         struct amt_header_advertisement *amta;
2242         int hdr_size;
2243
2244         hdr_size = sizeof(*amta) + sizeof(struct udphdr);
2245         if (!pskb_may_pull(skb, hdr_size))
2246                 return true;
2247
2248         amta = (struct amt_header_advertisement *)(udp_hdr(skb) + 1);
2249         if (!amta->ip4)
2250                 return true;
2251
2252         if (amta->reserved || amta->version)
2253                 return true;
2254
2255         if (ipv4_is_loopback(amta->ip4) || ipv4_is_multicast(amta->ip4) ||
2256             ipv4_is_zeronet(amta->ip4))
2257                 return true;
2258
2259         amt->remote_ip = amta->ip4;
2260         netdev_dbg(amt->dev, "advertised remote ip = %pI4\n", &amt->remote_ip);
2261         mod_delayed_work(amt_wq, &amt->req_wq, 0);
2262
2263         amt_update_gw_status(amt, AMT_STATUS_RECEIVED_ADVERTISEMENT, true);
2264         return false;
2265 }
2266
2267 static bool amt_multicast_data_handler(struct amt_dev *amt, struct sk_buff *skb)
2268 {
2269         struct amt_header_mcast_data *amtmd;
2270         int hdr_size, len, err;
2271         struct ethhdr *eth;
2272         struct iphdr *iph;
2273
2274         hdr_size = sizeof(*amtmd) + sizeof(struct udphdr);
2275         if (!pskb_may_pull(skb, hdr_size))
2276                 return true;
2277
2278         amtmd = (struct amt_header_mcast_data *)(udp_hdr(skb) + 1);
2279         if (amtmd->reserved || amtmd->version)
2280                 return true;
2281
2282         if (iptunnel_pull_header(skb, hdr_size, htons(ETH_P_IP), false))
2283                 return true;
2284
2285         skb_reset_network_header(skb);
2286         skb_push(skb, sizeof(*eth));
2287         skb_reset_mac_header(skb);
2288         skb_pull(skb, sizeof(*eth));
2289         eth = eth_hdr(skb);
2290
2291         if (!pskb_may_pull(skb, sizeof(*iph)))
2292                 return true;
2293         iph = ip_hdr(skb);
2294
2295         if (iph->version == 4) {
2296                 if (!ipv4_is_multicast(iph->daddr))
2297                         return true;
2298                 skb->protocol = htons(ETH_P_IP);
2299                 eth->h_proto = htons(ETH_P_IP);
2300                 ip_eth_mc_map(iph->daddr, eth->h_dest);
2301 #if IS_ENABLED(CONFIG_IPV6)
2302         } else if (iph->version == 6) {
2303                 struct ipv6hdr *ip6h;
2304
2305                 if (!pskb_may_pull(skb, sizeof(*ip6h)))
2306                         return true;
2307
2308                 ip6h = ipv6_hdr(skb);
2309                 if (!ipv6_addr_is_multicast(&ip6h->daddr))
2310                         return true;
2311                 skb->protocol = htons(ETH_P_IPV6);
2312                 eth->h_proto = htons(ETH_P_IPV6);
2313                 ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
2314 #endif
2315         } else {
2316                 return true;
2317         }
2318
2319         skb->pkt_type = PACKET_MULTICAST;
2320         skb->ip_summed = CHECKSUM_NONE;
2321         len = skb->len;
2322         err = gro_cells_receive(&amt->gro_cells, skb);
2323         if (likely(err == NET_RX_SUCCESS))
2324                 dev_sw_netstats_rx_add(amt->dev, len);
2325         else
2326                 amt->dev->stats.rx_dropped++;
2327
2328         return false;
2329 }
2330
2331 static bool amt_membership_query_handler(struct amt_dev *amt,
2332                                          struct sk_buff *skb)
2333 {
2334         struct amt_header_membership_query *amtmq;
2335         struct igmpv3_query *ihv3;
2336         struct ethhdr *eth, *oeth;
2337         struct iphdr *iph;
2338         int hdr_size, len;
2339
2340         hdr_size = sizeof(*amtmq) + sizeof(struct udphdr);
2341         if (!pskb_may_pull(skb, hdr_size))
2342                 return true;
2343
2344         amtmq = (struct amt_header_membership_query *)(udp_hdr(skb) + 1);
2345         if (amtmq->reserved || amtmq->version)
2346                 return true;
2347
2348         hdr_size -= sizeof(*eth);
2349         if (iptunnel_pull_header(skb, hdr_size, htons(ETH_P_TEB), false))
2350                 return true;
2351
2352         oeth = eth_hdr(skb);
2353         skb_reset_mac_header(skb);
2354         skb_pull(skb, sizeof(*eth));
2355         skb_reset_network_header(skb);
2356         eth = eth_hdr(skb);
2357         if (!pskb_may_pull(skb, sizeof(*iph)))
2358                 return true;
2359
2360         iph = ip_hdr(skb);
2361         if (iph->version == 4) {
2362                 if (!pskb_may_pull(skb, sizeof(*iph) + AMT_IPHDR_OPTS +
2363                                    sizeof(*ihv3)))
2364                         return true;
2365
2366                 if (!ipv4_is_multicast(iph->daddr))
2367                         return true;
2368
2369                 ihv3 = skb_pull(skb, sizeof(*iph) + AMT_IPHDR_OPTS);
2370                 skb_reset_transport_header(skb);
2371                 skb_push(skb, sizeof(*iph) + AMT_IPHDR_OPTS);
2372                 WRITE_ONCE(amt->ready4, true);
2373                 amt->mac = amtmq->response_mac;
2374                 amt->req_cnt = 0;
2375                 amt->qi = ihv3->qqic;
2376                 skb->protocol = htons(ETH_P_IP);
2377                 eth->h_proto = htons(ETH_P_IP);
2378                 ip_eth_mc_map(iph->daddr, eth->h_dest);
2379 #if IS_ENABLED(CONFIG_IPV6)
2380         } else if (iph->version == 6) {
2381                 struct mld2_query *mld2q;
2382                 struct ipv6hdr *ip6h;
2383
2384                 if (!pskb_may_pull(skb, sizeof(*ip6h) + AMT_IP6HDR_OPTS +
2385                                    sizeof(*mld2q)))
2386                         return true;
2387
2388                 ip6h = ipv6_hdr(skb);
2389                 if (!ipv6_addr_is_multicast(&ip6h->daddr))
2390                         return true;
2391
2392                 mld2q = skb_pull(skb, sizeof(*ip6h) + AMT_IP6HDR_OPTS);
2393                 skb_reset_transport_header(skb);
2394                 skb_push(skb, sizeof(*ip6h) + AMT_IP6HDR_OPTS);
2395                 WRITE_ONCE(amt->ready6, true);
2396                 amt->mac = amtmq->response_mac;
2397                 amt->req_cnt = 0;
2398                 amt->qi = mld2q->mld2q_qqic;
2399                 skb->protocol = htons(ETH_P_IPV6);
2400                 eth->h_proto = htons(ETH_P_IPV6);
2401                 ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
2402 #endif
2403         } else {
2404                 return true;
2405         }
2406
2407         ether_addr_copy(eth->h_source, oeth->h_source);
2408         skb->pkt_type = PACKET_MULTICAST;
2409         skb->ip_summed = CHECKSUM_NONE;
2410         len = skb->len;
2411         local_bh_disable();
2412         if (__netif_rx(skb) == NET_RX_SUCCESS) {
2413                 amt_update_gw_status(amt, AMT_STATUS_RECEIVED_QUERY, true);
2414                 dev_sw_netstats_rx_add(amt->dev, len);
2415         } else {
2416                 amt->dev->stats.rx_dropped++;
2417         }
2418         local_bh_enable();
2419
2420         return false;
2421 }
2422
2423 static bool amt_update_handler(struct amt_dev *amt, struct sk_buff *skb)
2424 {
2425         struct amt_header_membership_update *amtmu;
2426         struct amt_tunnel_list *tunnel;
2427         struct ethhdr *eth;
2428         struct iphdr *iph;
2429         int len, hdr_size;
2430
2431         iph = ip_hdr(skb);
2432
2433         hdr_size = sizeof(*amtmu) + sizeof(struct udphdr);
2434         if (!pskb_may_pull(skb, hdr_size))
2435                 return true;
2436
2437         amtmu = (struct amt_header_membership_update *)(udp_hdr(skb) + 1);
2438         if (amtmu->reserved || amtmu->version)
2439                 return true;
2440
2441         if (iptunnel_pull_header(skb, hdr_size, skb->protocol, false))
2442                 return true;
2443
2444         skb_reset_network_header(skb);
2445
2446         list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) {
2447                 if (tunnel->ip4 == iph->saddr) {
2448                         if ((amtmu->nonce == tunnel->nonce &&
2449                              amtmu->response_mac == tunnel->mac)) {
2450                                 mod_delayed_work(amt_wq, &tunnel->gc_wq,
2451                                                  msecs_to_jiffies(amt_gmi(amt))
2452                                                                   * 3);
2453                                 goto report;
2454                         } else {
2455                                 netdev_dbg(amt->dev, "Invalid MAC\n");
2456                                 return true;
2457                         }
2458                 }
2459         }
2460
2461         return true;
2462
2463 report:
2464         if (!pskb_may_pull(skb, sizeof(*iph)))
2465                 return true;
2466
2467         iph = ip_hdr(skb);
2468         if (iph->version == 4) {
2469                 if (ip_mc_check_igmp(skb)) {
2470                         netdev_dbg(amt->dev, "Invalid IGMP\n");
2471                         return true;
2472                 }
2473
2474                 spin_lock_bh(&tunnel->lock);
2475                 amt_igmp_report_handler(amt, skb, tunnel);
2476                 spin_unlock_bh(&tunnel->lock);
2477
2478                 skb_push(skb, sizeof(struct ethhdr));
2479                 skb_reset_mac_header(skb);
2480                 eth = eth_hdr(skb);
2481                 skb->protocol = htons(ETH_P_IP);
2482                 eth->h_proto = htons(ETH_P_IP);
2483                 ip_eth_mc_map(iph->daddr, eth->h_dest);
2484 #if IS_ENABLED(CONFIG_IPV6)
2485         } else if (iph->version == 6) {
2486                 struct ipv6hdr *ip6h = ipv6_hdr(skb);
2487
2488                 if (ipv6_mc_check_mld(skb)) {
2489                         netdev_dbg(amt->dev, "Invalid MLD\n");
2490                         return true;
2491                 }
2492
2493                 spin_lock_bh(&tunnel->lock);
2494                 amt_mld_report_handler(amt, skb, tunnel);
2495                 spin_unlock_bh(&tunnel->lock);
2496
2497                 skb_push(skb, sizeof(struct ethhdr));
2498                 skb_reset_mac_header(skb);
2499                 eth = eth_hdr(skb);
2500                 skb->protocol = htons(ETH_P_IPV6);
2501                 eth->h_proto = htons(ETH_P_IPV6);
2502                 ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
2503 #endif
2504         } else {
2505                 netdev_dbg(amt->dev, "Unsupported Protocol\n");
2506                 return true;
2507         }
2508
2509         skb_pull(skb, sizeof(struct ethhdr));
2510         skb->pkt_type = PACKET_MULTICAST;
2511         skb->ip_summed = CHECKSUM_NONE;
2512         len = skb->len;
2513         if (__netif_rx(skb) == NET_RX_SUCCESS) {
2514                 amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_UPDATE,
2515                                         true);
2516                 dev_sw_netstats_rx_add(amt->dev, len);
2517         } else {
2518                 amt->dev->stats.rx_dropped++;
2519         }
2520
2521         return false;
2522 }
2523
2524 static void amt_send_advertisement(struct amt_dev *amt, __be32 nonce,
2525                                    __be32 daddr, __be16 dport)
2526 {
2527         struct amt_header_advertisement *amta;
2528         int hlen, tlen, offset;
2529         struct socket *sock;
2530         struct udphdr *udph;
2531         struct sk_buff *skb;
2532         struct iphdr *iph;
2533         struct rtable *rt;
2534         struct flowi4 fl4;
2535         u32 len;
2536         int err;
2537
2538         rcu_read_lock();
2539         sock = rcu_dereference(amt->sock);
2540         if (!sock)
2541                 goto out;
2542
2543         if (!netif_running(amt->stream_dev) || !netif_running(amt->dev))
2544                 goto out;
2545
2546         rt = ip_route_output_ports(amt->net, &fl4, sock->sk,
2547                                    daddr, amt->local_ip,
2548                                    dport, amt->relay_port,
2549                                    IPPROTO_UDP, 0,
2550                                    amt->stream_dev->ifindex);
2551         if (IS_ERR(rt)) {
2552                 amt->dev->stats.tx_errors++;
2553                 goto out;
2554         }
2555
2556         hlen = LL_RESERVED_SPACE(amt->dev);
2557         tlen = amt->dev->needed_tailroom;
2558         len = hlen + tlen + sizeof(*iph) + sizeof(*udph) + sizeof(*amta);
2559         skb = netdev_alloc_skb_ip_align(amt->dev, len);
2560         if (!skb) {
2561                 ip_rt_put(rt);
2562                 amt->dev->stats.tx_errors++;
2563                 goto out;
2564         }
2565
2566         skb->priority = TC_PRIO_CONTROL;
2567         skb_dst_set(skb, &rt->dst);
2568
2569         len = sizeof(*iph) + sizeof(*udph) + sizeof(*amta);
2570         skb_reset_network_header(skb);
2571         skb_put(skb, len);
2572         amta = skb_pull(skb, sizeof(*iph) + sizeof(*udph));
2573         amta->version   = 0;
2574         amta->type      = AMT_MSG_ADVERTISEMENT;
2575         amta->reserved  = 0;
2576         amta->nonce     = nonce;
2577         amta->ip4       = amt->local_ip;
2578         skb_push(skb, sizeof(*udph));
2579         skb_reset_transport_header(skb);
2580         udph            = udp_hdr(skb);
2581         udph->source    = amt->relay_port;
2582         udph->dest      = dport;
2583         udph->len       = htons(sizeof(*amta) + sizeof(*udph));
2584         udph->check     = 0;
2585         offset = skb_transport_offset(skb);
2586         skb->csum = skb_checksum(skb, offset, skb->len - offset, 0);
2587         udph->check = csum_tcpudp_magic(amt->local_ip, daddr,
2588                                         sizeof(*udph) + sizeof(*amta),
2589                                         IPPROTO_UDP, skb->csum);
2590
2591         skb_push(skb, sizeof(*iph));
2592         iph             = ip_hdr(skb);
2593         iph->version    = 4;
2594         iph->ihl        = (sizeof(struct iphdr)) >> 2;
2595         iph->tos        = AMT_TOS;
2596         iph->frag_off   = 0;
2597         iph->ttl        = ip4_dst_hoplimit(&rt->dst);
2598         iph->daddr      = daddr;
2599         iph->saddr      = amt->local_ip;
2600         iph->protocol   = IPPROTO_UDP;
2601         iph->tot_len    = htons(len);
2602
2603         skb->ip_summed = CHECKSUM_NONE;
2604         ip_select_ident(amt->net, skb, NULL);
2605         ip_send_check(iph);
2606         err = ip_local_out(amt->net, sock->sk, skb);
2607         if (unlikely(net_xmit_eval(err)))
2608                 amt->dev->stats.tx_errors++;
2609
2610 out:
2611         rcu_read_unlock();
2612 }
2613
2614 static bool amt_discovery_handler(struct amt_dev *amt, struct sk_buff *skb)
2615 {
2616         struct amt_header_discovery *amtd;
2617         struct udphdr *udph;
2618         struct iphdr *iph;
2619
2620         if (!pskb_may_pull(skb, sizeof(*udph) + sizeof(*amtd)))
2621                 return true;
2622
2623         iph = ip_hdr(skb);
2624         udph = udp_hdr(skb);
2625         amtd = (struct amt_header_discovery *)(udp_hdr(skb) + 1);
2626
2627         if (amtd->reserved || amtd->version)
2628                 return true;
2629
2630         amt_send_advertisement(amt, amtd->nonce, iph->saddr, udph->source);
2631
2632         return false;
2633 }
2634
2635 static bool amt_request_handler(struct amt_dev *amt, struct sk_buff *skb)
2636 {
2637         struct amt_header_request *amtrh;
2638         struct amt_tunnel_list *tunnel;
2639         unsigned long long key;
2640         struct udphdr *udph;
2641         struct iphdr *iph;
2642         u64 mac;
2643         int i;
2644
2645         if (!pskb_may_pull(skb, sizeof(*udph) + sizeof(*amtrh)))
2646                 return true;
2647
2648         iph = ip_hdr(skb);
2649         udph = udp_hdr(skb);
2650         amtrh = (struct amt_header_request *)(udp_hdr(skb) + 1);
2651
2652         if (amtrh->reserved1 || amtrh->reserved2 || amtrh->version)
2653                 return true;
2654
2655         list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list)
2656                 if (tunnel->ip4 == iph->saddr)
2657                         goto send;
2658
2659         if (amt->nr_tunnels >= amt->max_tunnels) {
2660                 icmp_ndo_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0);
2661                 return true;
2662         }
2663
2664         tunnel = kzalloc(sizeof(*tunnel) +
2665                          (sizeof(struct hlist_head) * amt->hash_buckets),
2666                          GFP_ATOMIC);
2667         if (!tunnel)
2668                 return true;
2669
2670         tunnel->source_port = udph->source;
2671         tunnel->ip4 = iph->saddr;
2672
2673         memcpy(&key, &tunnel->key, sizeof(unsigned long long));
2674         tunnel->amt = amt;
2675         spin_lock_init(&tunnel->lock);
2676         for (i = 0; i < amt->hash_buckets; i++)
2677                 INIT_HLIST_HEAD(&tunnel->groups[i]);
2678
2679         INIT_DELAYED_WORK(&tunnel->gc_wq, amt_tunnel_expire);
2680
2681         spin_lock_bh(&amt->lock);
2682         list_add_tail_rcu(&tunnel->list, &amt->tunnel_list);
2683         tunnel->key = amt->key;
2684         amt_update_relay_status(tunnel, AMT_STATUS_RECEIVED_REQUEST, true);
2685         amt->nr_tunnels++;
2686         mod_delayed_work(amt_wq, &tunnel->gc_wq,
2687                          msecs_to_jiffies(amt_gmi(amt)));
2688         spin_unlock_bh(&amt->lock);
2689
2690 send:
2691         tunnel->nonce = amtrh->nonce;
2692         mac = siphash_3u32((__force u32)tunnel->ip4,
2693                            (__force u32)tunnel->source_port,
2694                            (__force u32)tunnel->nonce,
2695                            &tunnel->key);
2696         tunnel->mac = mac >> 16;
2697
2698         if (!netif_running(amt->dev) || !netif_running(amt->stream_dev))
2699                 return true;
2700
2701         if (!amtrh->p)
2702                 amt_send_igmp_gq(amt, tunnel);
2703         else
2704                 amt_send_mld_gq(amt, tunnel);
2705
2706         return false;
2707 }
2708
2709 static void amt_gw_rcv(struct amt_dev *amt, struct sk_buff *skb)
2710 {
2711         int type = amt_parse_type(skb);
2712         int err = 1;
2713
2714         if (type == -1)
2715                 goto drop;
2716
2717         if (amt->mode == AMT_MODE_GATEWAY) {
2718                 switch (type) {
2719                 case AMT_MSG_ADVERTISEMENT:
2720                         err = amt_advertisement_handler(amt, skb);
2721                         break;
2722                 case AMT_MSG_MEMBERSHIP_QUERY:
2723                         err = amt_membership_query_handler(amt, skb);
2724                         if (!err)
2725                                 return;
2726                         break;
2727                 default:
2728                         netdev_dbg(amt->dev, "Invalid type of Gateway\n");
2729                         break;
2730                 }
2731         }
2732 drop:
2733         if (err) {
2734                 amt->dev->stats.rx_dropped++;
2735                 kfree_skb(skb);
2736         } else {
2737                 consume_skb(skb);
2738         }
2739 }
2740
2741 static int amt_rcv(struct sock *sk, struct sk_buff *skb)
2742 {
2743         struct amt_dev *amt;
2744         struct iphdr *iph;
2745         int type;
2746         bool err;
2747
2748         rcu_read_lock_bh();
2749         amt = rcu_dereference_sk_user_data(sk);
2750         if (!amt) {
2751                 err = true;
2752                 kfree_skb(skb);
2753                 goto out;
2754         }
2755
2756         skb->dev = amt->dev;
2757         iph = ip_hdr(skb);
2758         type = amt_parse_type(skb);
2759         if (type == -1) {
2760                 err = true;
2761                 goto drop;
2762         }
2763
2764         if (amt->mode == AMT_MODE_GATEWAY) {
2765                 switch (type) {
2766                 case AMT_MSG_ADVERTISEMENT:
2767                         if (iph->saddr != amt->discovery_ip) {
2768                                 netdev_dbg(amt->dev, "Invalid Relay IP\n");
2769                                 err = true;
2770                                 goto drop;
2771                         }
2772                         if (amt_queue_event(amt, AMT_EVENT_RECEIVE, skb)) {
2773                                 netdev_dbg(amt->dev, "AMT Event queue full\n");
2774                                 err = true;
2775                                 goto drop;
2776                         }
2777                         goto out;
2778                 case AMT_MSG_MULTICAST_DATA:
2779                         if (iph->saddr != amt->remote_ip) {
2780                                 netdev_dbg(amt->dev, "Invalid Relay IP\n");
2781                                 err = true;
2782                                 goto drop;
2783                         }
2784                         err = amt_multicast_data_handler(amt, skb);
2785                         if (err)
2786                                 goto drop;
2787                         else
2788                                 goto out;
2789                 case AMT_MSG_MEMBERSHIP_QUERY:
2790                         if (iph->saddr != amt->remote_ip) {
2791                                 netdev_dbg(amt->dev, "Invalid Relay IP\n");
2792                                 err = true;
2793                                 goto drop;
2794                         }
2795                         if (amt_queue_event(amt, AMT_EVENT_RECEIVE, skb)) {
2796                                 netdev_dbg(amt->dev, "AMT Event queue full\n");
2797                                 err = true;
2798                                 goto drop;
2799                         }
2800                         goto out;
2801                 default:
2802                         err = true;
2803                         netdev_dbg(amt->dev, "Invalid type of Gateway\n");
2804                         break;
2805                 }
2806         } else {
2807                 switch (type) {
2808                 case AMT_MSG_DISCOVERY:
2809                         err = amt_discovery_handler(amt, skb);
2810                         break;
2811                 case AMT_MSG_REQUEST:
2812                         err = amt_request_handler(amt, skb);
2813                         break;
2814                 case AMT_MSG_MEMBERSHIP_UPDATE:
2815                         err = amt_update_handler(amt, skb);
2816                         if (err)
2817                                 goto drop;
2818                         else
2819                                 goto out;
2820                 default:
2821                         err = true;
2822                         netdev_dbg(amt->dev, "Invalid type of relay\n");
2823                         break;
2824                 }
2825         }
2826 drop:
2827         if (err) {
2828                 amt->dev->stats.rx_dropped++;
2829                 kfree_skb(skb);
2830         } else {
2831                 consume_skb(skb);
2832         }
2833 out:
2834         rcu_read_unlock_bh();
2835         return 0;
2836 }
2837
2838 static void amt_event_work(struct work_struct *work)
2839 {
2840         struct amt_dev *amt = container_of(work, struct amt_dev, event_wq);
2841         struct sk_buff *skb;
2842         u8 event;
2843         int i;
2844
2845         for (i = 0; i < AMT_MAX_EVENTS; i++) {
2846                 spin_lock_bh(&amt->lock);
2847                 if (amt->nr_events == 0) {
2848                         spin_unlock_bh(&amt->lock);
2849                         return;
2850                 }
2851                 event = amt->events[amt->event_idx].event;
2852                 skb = amt->events[amt->event_idx].skb;
2853                 amt->events[amt->event_idx].event = AMT_EVENT_NONE;
2854                 amt->events[amt->event_idx].skb = NULL;
2855                 amt->nr_events--;
2856                 amt->event_idx++;
2857                 amt->event_idx %= AMT_MAX_EVENTS;
2858                 spin_unlock_bh(&amt->lock);
2859
2860                 switch (event) {
2861                 case AMT_EVENT_RECEIVE:
2862                         amt_gw_rcv(amt, skb);
2863                         break;
2864                 case AMT_EVENT_SEND_DISCOVERY:
2865                         amt_event_send_discovery(amt);
2866                         break;
2867                 case AMT_EVENT_SEND_REQUEST:
2868                         amt_event_send_request(amt);
2869                         break;
2870                 default:
2871                         if (skb)
2872                                 kfree_skb(skb);
2873                         break;
2874                 }
2875         }
2876 }
2877
2878 static int amt_err_lookup(struct sock *sk, struct sk_buff *skb)
2879 {
2880         struct amt_dev *amt;
2881         int type;
2882
2883         rcu_read_lock_bh();
2884         amt = rcu_dereference_sk_user_data(sk);
2885         if (!amt)
2886                 goto out;
2887
2888         if (amt->mode != AMT_MODE_GATEWAY)
2889                 goto drop;
2890
2891         type = amt_parse_type(skb);
2892         if (type == -1)
2893                 goto drop;
2894
2895         netdev_dbg(amt->dev, "Received IGMP Unreachable of %s\n",
2896                    type_str[type]);
2897         switch (type) {
2898         case AMT_MSG_DISCOVERY:
2899                 break;
2900         case AMT_MSG_REQUEST:
2901         case AMT_MSG_MEMBERSHIP_UPDATE:
2902                 if (READ_ONCE(amt->status) >= AMT_STATUS_RECEIVED_ADVERTISEMENT)
2903                         mod_delayed_work(amt_wq, &amt->req_wq, 0);
2904                 break;
2905         default:
2906                 goto drop;
2907         }
2908 out:
2909         rcu_read_unlock_bh();
2910         return 0;
2911 drop:
2912         rcu_read_unlock_bh();
2913         amt->dev->stats.rx_dropped++;
2914         return 0;
2915 }
2916
2917 static struct socket *amt_create_sock(struct net *net, __be16 port)
2918 {
2919         struct udp_port_cfg udp_conf;
2920         struct socket *sock;
2921         int err;
2922
2923         memset(&udp_conf, 0, sizeof(udp_conf));
2924         udp_conf.family = AF_INET;
2925         udp_conf.local_ip.s_addr = htonl(INADDR_ANY);
2926
2927         udp_conf.local_udp_port = port;
2928
2929         err = udp_sock_create(net, &udp_conf, &sock);
2930         if (err < 0)
2931                 return ERR_PTR(err);
2932
2933         return sock;
2934 }
2935
2936 static int amt_socket_create(struct amt_dev *amt)
2937 {
2938         struct udp_tunnel_sock_cfg tunnel_cfg;
2939         struct socket *sock;
2940
2941         sock = amt_create_sock(amt->net, amt->relay_port);
2942         if (IS_ERR(sock))
2943                 return PTR_ERR(sock);
2944
2945         /* Mark socket as an encapsulation socket */
2946         memset(&tunnel_cfg, 0, sizeof(tunnel_cfg));
2947         tunnel_cfg.sk_user_data = amt;
2948         tunnel_cfg.encap_type = 1;
2949         tunnel_cfg.encap_rcv = amt_rcv;
2950         tunnel_cfg.encap_err_lookup = amt_err_lookup;
2951         tunnel_cfg.encap_destroy = NULL;
2952         setup_udp_tunnel_sock(amt->net, sock, &tunnel_cfg);
2953
2954         rcu_assign_pointer(amt->sock, sock);
2955         return 0;
2956 }
2957
2958 static int amt_dev_open(struct net_device *dev)
2959 {
2960         struct amt_dev *amt = netdev_priv(dev);
2961         int err;
2962
2963         amt->ready4 = false;
2964         amt->ready6 = false;
2965         amt->event_idx = 0;
2966         amt->nr_events = 0;
2967
2968         err = amt_socket_create(amt);
2969         if (err)
2970                 return err;
2971
2972         amt->req_cnt = 0;
2973         amt->remote_ip = 0;
2974         get_random_bytes(&amt->key, sizeof(siphash_key_t));
2975
2976         amt->status = AMT_STATUS_INIT;
2977         if (amt->mode == AMT_MODE_GATEWAY) {
2978                 mod_delayed_work(amt_wq, &amt->discovery_wq, 0);
2979                 mod_delayed_work(amt_wq, &amt->req_wq, 0);
2980         } else if (amt->mode == AMT_MODE_RELAY) {
2981                 mod_delayed_work(amt_wq, &amt->secret_wq,
2982                                  msecs_to_jiffies(AMT_SECRET_TIMEOUT));
2983         }
2984         return err;
2985 }
2986
2987 static int amt_dev_stop(struct net_device *dev)
2988 {
2989         struct amt_dev *amt = netdev_priv(dev);
2990         struct amt_tunnel_list *tunnel, *tmp;
2991         struct socket *sock;
2992         struct sk_buff *skb;
2993         int i;
2994
2995         cancel_delayed_work_sync(&amt->req_wq);
2996         cancel_delayed_work_sync(&amt->discovery_wq);
2997         cancel_delayed_work_sync(&amt->secret_wq);
2998
2999         /* shutdown */
3000         sock = rtnl_dereference(amt->sock);
3001         RCU_INIT_POINTER(amt->sock, NULL);
3002         synchronize_net();
3003         if (sock)
3004                 udp_tunnel_sock_release(sock);
3005
3006         cancel_work_sync(&amt->event_wq);
3007         for (i = 0; i < AMT_MAX_EVENTS; i++) {
3008                 skb = amt->events[i].skb;
3009                 if (skb)
3010                         kfree_skb(skb);
3011                 amt->events[i].event = AMT_EVENT_NONE;
3012                 amt->events[i].skb = NULL;
3013         }
3014
3015         amt->ready4 = false;
3016         amt->ready6 = false;
3017         amt->req_cnt = 0;
3018         amt->remote_ip = 0;
3019
3020         list_for_each_entry_safe(tunnel, tmp, &amt->tunnel_list, list) {
3021                 list_del_rcu(&tunnel->list);
3022                 amt->nr_tunnels--;
3023                 cancel_delayed_work_sync(&tunnel->gc_wq);
3024                 amt_clear_groups(tunnel);
3025                 kfree_rcu(tunnel, rcu);
3026         }
3027
3028         return 0;
3029 }
3030
3031 static const struct device_type amt_type = {
3032         .name = "amt",
3033 };
3034
3035 static int amt_dev_init(struct net_device *dev)
3036 {
3037         struct amt_dev *amt = netdev_priv(dev);
3038         int err;
3039
3040         amt->dev = dev;
3041         dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
3042         if (!dev->tstats)
3043                 return -ENOMEM;
3044
3045         err = gro_cells_init(&amt->gro_cells, dev);
3046         if (err) {
3047                 free_percpu(dev->tstats);
3048                 return err;
3049         }
3050
3051         return 0;
3052 }
3053
3054 static void amt_dev_uninit(struct net_device *dev)
3055 {
3056         struct amt_dev *amt = netdev_priv(dev);
3057
3058         gro_cells_destroy(&amt->gro_cells);
3059         free_percpu(dev->tstats);
3060 }
3061
3062 static const struct net_device_ops amt_netdev_ops = {
3063         .ndo_init               = amt_dev_init,
3064         .ndo_uninit             = amt_dev_uninit,
3065         .ndo_open               = amt_dev_open,
3066         .ndo_stop               = amt_dev_stop,
3067         .ndo_start_xmit         = amt_dev_xmit,
3068         .ndo_get_stats64        = dev_get_tstats64,
3069 };
3070
3071 static void amt_link_setup(struct net_device *dev)
3072 {
3073         dev->netdev_ops         = &amt_netdev_ops;
3074         dev->needs_free_netdev  = true;
3075         SET_NETDEV_DEVTYPE(dev, &amt_type);
3076         dev->min_mtu            = ETH_MIN_MTU;
3077         dev->max_mtu            = ETH_MAX_MTU;
3078         dev->type               = ARPHRD_NONE;
3079         dev->flags              = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
3080         dev->hard_header_len    = 0;
3081         dev->addr_len           = 0;
3082         dev->priv_flags         |= IFF_NO_QUEUE;
3083         dev->features           |= NETIF_F_LLTX;
3084         dev->features           |= NETIF_F_GSO_SOFTWARE;
3085         dev->features           |= NETIF_F_NETNS_LOCAL;
3086         dev->hw_features        |= NETIF_F_SG | NETIF_F_HW_CSUM;
3087         dev->hw_features        |= NETIF_F_FRAGLIST | NETIF_F_RXCSUM;
3088         dev->hw_features        |= NETIF_F_GSO_SOFTWARE;
3089         eth_hw_addr_random(dev);
3090         eth_zero_addr(dev->broadcast);
3091         ether_setup(dev);
3092 }
3093
3094 static const struct nla_policy amt_policy[IFLA_AMT_MAX + 1] = {
3095         [IFLA_AMT_MODE]         = { .type = NLA_U32 },
3096         [IFLA_AMT_RELAY_PORT]   = { .type = NLA_U16 },
3097         [IFLA_AMT_GATEWAY_PORT] = { .type = NLA_U16 },
3098         [IFLA_AMT_LINK]         = { .type = NLA_U32 },
3099         [IFLA_AMT_LOCAL_IP]     = { .len = sizeof_field(struct iphdr, daddr) },
3100         [IFLA_AMT_REMOTE_IP]    = { .len = sizeof_field(struct iphdr, daddr) },
3101         [IFLA_AMT_DISCOVERY_IP] = { .len = sizeof_field(struct iphdr, daddr) },
3102         [IFLA_AMT_MAX_TUNNELS]  = { .type = NLA_U32 },
3103 };
3104
3105 static int amt_validate(struct nlattr *tb[], struct nlattr *data[],
3106                         struct netlink_ext_ack *extack)
3107 {
3108         if (!data)
3109                 return -EINVAL;
3110
3111         if (!data[IFLA_AMT_LINK]) {
3112                 NL_SET_ERR_MSG_ATTR(extack, data[IFLA_AMT_LINK],
3113                                     "Link attribute is required");
3114                 return -EINVAL;
3115         }
3116
3117         if (!data[IFLA_AMT_MODE]) {
3118                 NL_SET_ERR_MSG_ATTR(extack, data[IFLA_AMT_MODE],
3119                                     "Mode attribute is required");
3120                 return -EINVAL;
3121         }
3122
3123         if (nla_get_u32(data[IFLA_AMT_MODE]) > AMT_MODE_MAX) {
3124                 NL_SET_ERR_MSG_ATTR(extack, data[IFLA_AMT_MODE],
3125                                     "Mode attribute is not valid");
3126                 return -EINVAL;
3127         }
3128
3129         if (!data[IFLA_AMT_LOCAL_IP]) {
3130                 NL_SET_ERR_MSG_ATTR(extack, data[IFLA_AMT_DISCOVERY_IP],
3131                                     "Local attribute is required");
3132                 return -EINVAL;
3133         }
3134
3135         if (!data[IFLA_AMT_DISCOVERY_IP] &&
3136             nla_get_u32(data[IFLA_AMT_MODE]) == AMT_MODE_GATEWAY) {
3137                 NL_SET_ERR_MSG_ATTR(extack, data[IFLA_AMT_LOCAL_IP],
3138                                     "Discovery attribute is required");
3139                 return -EINVAL;
3140         }
3141
3142         return 0;
3143 }
3144
3145 static int amt_newlink(struct net *net, struct net_device *dev,
3146                        struct nlattr *tb[], struct nlattr *data[],
3147                        struct netlink_ext_ack *extack)
3148 {
3149         struct amt_dev *amt = netdev_priv(dev);
3150         int err = -EINVAL;
3151
3152         amt->net = net;
3153         amt->mode = nla_get_u32(data[IFLA_AMT_MODE]);
3154
3155         if (data[IFLA_AMT_MAX_TUNNELS] &&
3156             nla_get_u32(data[IFLA_AMT_MAX_TUNNELS]))
3157                 amt->max_tunnels = nla_get_u32(data[IFLA_AMT_MAX_TUNNELS]);
3158         else
3159                 amt->max_tunnels = AMT_MAX_TUNNELS;
3160
3161         spin_lock_init(&amt->lock);
3162         amt->max_groups = AMT_MAX_GROUP;
3163         amt->max_sources = AMT_MAX_SOURCE;
3164         amt->hash_buckets = AMT_HSIZE;
3165         amt->nr_tunnels = 0;
3166         get_random_bytes(&amt->hash_seed, sizeof(amt->hash_seed));
3167         amt->stream_dev = dev_get_by_index(net,
3168                                            nla_get_u32(data[IFLA_AMT_LINK]));
3169         if (!amt->stream_dev) {
3170                 NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_LINK],
3171                                     "Can't find stream device");
3172                 return -ENODEV;
3173         }
3174
3175         if (amt->stream_dev->type != ARPHRD_ETHER) {
3176                 NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_LINK],
3177                                     "Invalid stream device type");
3178                 goto err;
3179         }
3180
3181         amt->local_ip = nla_get_in_addr(data[IFLA_AMT_LOCAL_IP]);
3182         if (ipv4_is_loopback(amt->local_ip) ||
3183             ipv4_is_zeronet(amt->local_ip) ||
3184             ipv4_is_multicast(amt->local_ip)) {
3185                 NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_LOCAL_IP],
3186                                     "Invalid Local address");
3187                 goto err;
3188         }
3189
3190         if (data[IFLA_AMT_RELAY_PORT])
3191                 amt->relay_port = nla_get_be16(data[IFLA_AMT_RELAY_PORT]);
3192         else
3193                 amt->relay_port = htons(IANA_AMT_UDP_PORT);
3194
3195         if (data[IFLA_AMT_GATEWAY_PORT])
3196                 amt->gw_port = nla_get_be16(data[IFLA_AMT_GATEWAY_PORT]);
3197         else
3198                 amt->gw_port = htons(IANA_AMT_UDP_PORT);
3199
3200         if (!amt->relay_port) {
3201                 NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_DISCOVERY_IP],
3202                                     "relay port must not be 0");
3203                 goto err;
3204         }
3205         if (amt->mode == AMT_MODE_RELAY) {
3206                 amt->qrv = READ_ONCE(amt->net->ipv4.sysctl_igmp_qrv);
3207                 amt->qri = 10;
3208                 dev->needed_headroom = amt->stream_dev->needed_headroom +
3209                                        AMT_RELAY_HLEN;
3210                 dev->mtu = amt->stream_dev->mtu - AMT_RELAY_HLEN;
3211                 dev->max_mtu = dev->mtu;
3212                 dev->min_mtu = ETH_MIN_MTU + AMT_RELAY_HLEN;
3213         } else {
3214                 if (!data[IFLA_AMT_DISCOVERY_IP]) {
3215                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_DISCOVERY_IP],
3216                                             "discovery must be set in gateway mode");
3217                         goto err;
3218                 }
3219                 if (!amt->gw_port) {
3220                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_DISCOVERY_IP],
3221                                             "gateway port must not be 0");
3222                         goto err;
3223                 }
3224                 amt->remote_ip = 0;
3225                 amt->discovery_ip = nla_get_in_addr(data[IFLA_AMT_DISCOVERY_IP]);
3226                 if (ipv4_is_loopback(amt->discovery_ip) ||
3227                     ipv4_is_zeronet(amt->discovery_ip) ||
3228                     ipv4_is_multicast(amt->discovery_ip)) {
3229                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_AMT_DISCOVERY_IP],
3230                                             "discovery must be unicast");
3231                         goto err;
3232                 }
3233
3234                 dev->needed_headroom = amt->stream_dev->needed_headroom +
3235                                        AMT_GW_HLEN;
3236                 dev->mtu = amt->stream_dev->mtu - AMT_GW_HLEN;
3237                 dev->max_mtu = dev->mtu;
3238                 dev->min_mtu = ETH_MIN_MTU + AMT_GW_HLEN;
3239         }
3240         amt->qi = AMT_INIT_QUERY_INTERVAL;
3241
3242         err = register_netdevice(dev);
3243         if (err < 0) {
3244                 netdev_dbg(dev, "failed to register new netdev %d\n", err);
3245                 goto err;
3246         }
3247
3248         err = netdev_upper_dev_link(amt->stream_dev, dev, extack);
3249         if (err < 0) {
3250                 unregister_netdevice(dev);
3251                 goto err;
3252         }
3253
3254         INIT_DELAYED_WORK(&amt->discovery_wq, amt_discovery_work);
3255         INIT_DELAYED_WORK(&amt->req_wq, amt_req_work);
3256         INIT_DELAYED_WORK(&amt->secret_wq, amt_secret_work);
3257         INIT_WORK(&amt->event_wq, amt_event_work);
3258         INIT_LIST_HEAD(&amt->tunnel_list);
3259         return 0;
3260 err:
3261         dev_put(amt->stream_dev);
3262         return err;
3263 }
3264
3265 static void amt_dellink(struct net_device *dev, struct list_head *head)
3266 {
3267         struct amt_dev *amt = netdev_priv(dev);
3268
3269         unregister_netdevice_queue(dev, head);
3270         netdev_upper_dev_unlink(amt->stream_dev, dev);
3271         dev_put(amt->stream_dev);
3272 }
3273
3274 static size_t amt_get_size(const struct net_device *dev)
3275 {
3276         return nla_total_size(sizeof(__u32)) + /* IFLA_AMT_MODE */
3277                nla_total_size(sizeof(__u16)) + /* IFLA_AMT_RELAY_PORT */
3278                nla_total_size(sizeof(__u16)) + /* IFLA_AMT_GATEWAY_PORT */
3279                nla_total_size(sizeof(__u32)) + /* IFLA_AMT_LINK */
3280                nla_total_size(sizeof(__u32)) + /* IFLA_MAX_TUNNELS */
3281                nla_total_size(sizeof(struct iphdr)) + /* IFLA_AMT_DISCOVERY_IP */
3282                nla_total_size(sizeof(struct iphdr)) + /* IFLA_AMT_REMOTE_IP */
3283                nla_total_size(sizeof(struct iphdr)); /* IFLA_AMT_LOCAL_IP */
3284 }
3285
3286 static int amt_fill_info(struct sk_buff *skb, const struct net_device *dev)
3287 {
3288         struct amt_dev *amt = netdev_priv(dev);
3289
3290         if (nla_put_u32(skb, IFLA_AMT_MODE, amt->mode))
3291                 goto nla_put_failure;
3292         if (nla_put_be16(skb, IFLA_AMT_RELAY_PORT, amt->relay_port))
3293                 goto nla_put_failure;
3294         if (nla_put_be16(skb, IFLA_AMT_GATEWAY_PORT, amt->gw_port))
3295                 goto nla_put_failure;
3296         if (nla_put_u32(skb, IFLA_AMT_LINK, amt->stream_dev->ifindex))
3297                 goto nla_put_failure;
3298         if (nla_put_in_addr(skb, IFLA_AMT_LOCAL_IP, amt->local_ip))
3299                 goto nla_put_failure;
3300         if (nla_put_in_addr(skb, IFLA_AMT_DISCOVERY_IP, amt->discovery_ip))
3301                 goto nla_put_failure;
3302         if (amt->remote_ip)
3303                 if (nla_put_in_addr(skb, IFLA_AMT_REMOTE_IP, amt->remote_ip))
3304                         goto nla_put_failure;
3305         if (nla_put_u32(skb, IFLA_AMT_MAX_TUNNELS, amt->max_tunnels))
3306                 goto nla_put_failure;
3307
3308         return 0;
3309
3310 nla_put_failure:
3311         return -EMSGSIZE;
3312 }
3313
3314 static struct rtnl_link_ops amt_link_ops __read_mostly = {
3315         .kind           = "amt",
3316         .maxtype        = IFLA_AMT_MAX,
3317         .policy         = amt_policy,
3318         .priv_size      = sizeof(struct amt_dev),
3319         .setup          = amt_link_setup,
3320         .validate       = amt_validate,
3321         .newlink        = amt_newlink,
3322         .dellink        = amt_dellink,
3323         .get_size       = amt_get_size,
3324         .fill_info      = amt_fill_info,
3325 };
3326
3327 static struct net_device *amt_lookup_upper_dev(struct net_device *dev)
3328 {
3329         struct net_device *upper_dev;
3330         struct amt_dev *amt;
3331
3332         for_each_netdev(dev_net(dev), upper_dev) {
3333                 if (netif_is_amt(upper_dev)) {
3334                         amt = netdev_priv(upper_dev);
3335                         if (amt->stream_dev == dev)
3336                                 return upper_dev;
3337                 }
3338         }
3339
3340         return NULL;
3341 }
3342
3343 static int amt_device_event(struct notifier_block *unused,
3344                             unsigned long event, void *ptr)
3345 {
3346         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3347         struct net_device *upper_dev;
3348         struct amt_dev *amt;
3349         LIST_HEAD(list);
3350         int new_mtu;
3351
3352         upper_dev = amt_lookup_upper_dev(dev);
3353         if (!upper_dev)
3354                 return NOTIFY_DONE;
3355         amt = netdev_priv(upper_dev);
3356
3357         switch (event) {
3358         case NETDEV_UNREGISTER:
3359                 amt_dellink(amt->dev, &list);
3360                 unregister_netdevice_many(&list);
3361                 break;
3362         case NETDEV_CHANGEMTU:
3363                 if (amt->mode == AMT_MODE_RELAY)
3364                         new_mtu = dev->mtu - AMT_RELAY_HLEN;
3365                 else
3366                         new_mtu = dev->mtu - AMT_GW_HLEN;
3367
3368                 dev_set_mtu(amt->dev, new_mtu);
3369                 break;
3370         }
3371
3372         return NOTIFY_DONE;
3373 }
3374
3375 static struct notifier_block amt_notifier_block __read_mostly = {
3376         .notifier_call = amt_device_event,
3377 };
3378
3379 static int __init amt_init(void)
3380 {
3381         int err;
3382
3383         err = register_netdevice_notifier(&amt_notifier_block);
3384         if (err < 0)
3385                 goto err;
3386
3387         err = rtnl_link_register(&amt_link_ops);
3388         if (err < 0)
3389                 goto unregister_notifier;
3390
3391         amt_wq = alloc_workqueue("amt", WQ_UNBOUND, 0);
3392         if (!amt_wq) {
3393                 err = -ENOMEM;
3394                 goto rtnl_unregister;
3395         }
3396
3397         spin_lock_init(&source_gc_lock);
3398         spin_lock_bh(&source_gc_lock);
3399         INIT_DELAYED_WORK(&source_gc_wq, amt_source_gc_work);
3400         mod_delayed_work(amt_wq, &source_gc_wq,
3401                          msecs_to_jiffies(AMT_GC_INTERVAL));
3402         spin_unlock_bh(&source_gc_lock);
3403
3404         return 0;
3405
3406 rtnl_unregister:
3407         rtnl_link_unregister(&amt_link_ops);
3408 unregister_notifier:
3409         unregister_netdevice_notifier(&amt_notifier_block);
3410 err:
3411         pr_err("error loading AMT module loaded\n");
3412         return err;
3413 }
3414 late_initcall(amt_init);
3415
3416 static void __exit amt_fini(void)
3417 {
3418         rtnl_link_unregister(&amt_link_ops);
3419         unregister_netdevice_notifier(&amt_notifier_block);
3420         cancel_delayed_work_sync(&source_gc_wq);
3421         __amt_source_gc_work();
3422         destroy_workqueue(amt_wq);
3423 }
3424 module_exit(amt_fini);
3425
3426 MODULE_LICENSE("GPL");
3427 MODULE_AUTHOR("Taehee Yoo <ap420073@gmail.com>");
3428 MODULE_ALIAS_RTNL_LINK("amt");