Merge tag 'lkdtm-next' of https://git.kernel.org/pub/scm/linux/kernel/git/kees/linux...
[linux-2.6-microblaze.git] / drivers / net / vxlan.c
1 /*
2  * VXLAN: Virtual eXtensible Local Area Network
3  *
4  * Copyright (c) 2012-2013 Vyatta Inc.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/errno.h>
16 #include <linux/slab.h>
17 #include <linux/udp.h>
18 #include <linux/igmp.h>
19 #include <linux/if_ether.h>
20 #include <linux/ethtool.h>
21 #include <net/arp.h>
22 #include <net/ndisc.h>
23 #include <net/ipv6_stubs.h>
24 #include <net/ip.h>
25 #include <net/icmp.h>
26 #include <net/rtnetlink.h>
27 #include <net/inet_ecn.h>
28 #include <net/net_namespace.h>
29 #include <net/netns/generic.h>
30 #include <net/tun_proto.h>
31 #include <net/vxlan.h>
32
33 #if IS_ENABLED(CONFIG_IPV6)
34 #include <net/ip6_tunnel.h>
35 #include <net/ip6_checksum.h>
36 #endif
37
38 #define VXLAN_VERSION   "0.1"
39
40 #define PORT_HASH_BITS  8
41 #define PORT_HASH_SIZE  (1<<PORT_HASH_BITS)
42 #define FDB_AGE_DEFAULT 300 /* 5 min */
43 #define FDB_AGE_INTERVAL (10 * HZ)      /* rescan interval */
44
45 /* UDP port for VXLAN traffic.
46  * The IANA assigned port is 4789, but the Linux default is 8472
47  * for compatibility with early adopters.
48  */
49 static unsigned short vxlan_port __read_mostly = 8472;
50 module_param_named(udp_port, vxlan_port, ushort, 0444);
51 MODULE_PARM_DESC(udp_port, "Destination UDP port");
52
53 static bool log_ecn_error = true;
54 module_param(log_ecn_error, bool, 0644);
55 MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN");
56
57 static unsigned int vxlan_net_id;
58 static struct rtnl_link_ops vxlan_link_ops;
59
60 static const u8 all_zeros_mac[ETH_ALEN + 2];
61
62 static int vxlan_sock_add(struct vxlan_dev *vxlan);
63
64 static void vxlan_vs_del_dev(struct vxlan_dev *vxlan);
65
66 /* per-network namespace private data for this module */
67 struct vxlan_net {
68         struct list_head  vxlan_list;
69         struct hlist_head sock_list[PORT_HASH_SIZE];
70         spinlock_t        sock_lock;
71 };
72
73 /* Forwarding table entry */
74 struct vxlan_fdb {
75         struct hlist_node hlist;        /* linked list of entries */
76         struct rcu_head   rcu;
77         unsigned long     updated;      /* jiffies */
78         unsigned long     used;
79         struct list_head  remotes;
80         u8                eth_addr[ETH_ALEN];
81         u16               state;        /* see ndm_state */
82         __be32            vni;
83         u16               flags;        /* see ndm_flags and below */
84 };
85
86 #define NTF_VXLAN_ADDED_BY_USER 0x100
87
88 /* salt for hash table */
89 static u32 vxlan_salt __read_mostly;
90
91 static inline bool vxlan_collect_metadata(struct vxlan_sock *vs)
92 {
93         return vs->flags & VXLAN_F_COLLECT_METADATA ||
94                ip_tunnel_collect_metadata();
95 }
96
97 #if IS_ENABLED(CONFIG_IPV6)
98 static inline
99 bool vxlan_addr_equal(const union vxlan_addr *a, const union vxlan_addr *b)
100 {
101         if (a->sa.sa_family != b->sa.sa_family)
102                 return false;
103         if (a->sa.sa_family == AF_INET6)
104                 return ipv6_addr_equal(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
105         else
106                 return a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr;
107 }
108
109 static int vxlan_nla_get_addr(union vxlan_addr *ip, struct nlattr *nla)
110 {
111         if (nla_len(nla) >= sizeof(struct in6_addr)) {
112                 ip->sin6.sin6_addr = nla_get_in6_addr(nla);
113                 ip->sa.sa_family = AF_INET6;
114                 return 0;
115         } else if (nla_len(nla) >= sizeof(__be32)) {
116                 ip->sin.sin_addr.s_addr = nla_get_in_addr(nla);
117                 ip->sa.sa_family = AF_INET;
118                 return 0;
119         } else {
120                 return -EAFNOSUPPORT;
121         }
122 }
123
124 static int vxlan_nla_put_addr(struct sk_buff *skb, int attr,
125                               const union vxlan_addr *ip)
126 {
127         if (ip->sa.sa_family == AF_INET6)
128                 return nla_put_in6_addr(skb, attr, &ip->sin6.sin6_addr);
129         else
130                 return nla_put_in_addr(skb, attr, ip->sin.sin_addr.s_addr);
131 }
132
133 #else /* !CONFIG_IPV6 */
134
135 static inline
136 bool vxlan_addr_equal(const union vxlan_addr *a, const union vxlan_addr *b)
137 {
138         return a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr;
139 }
140
141 static int vxlan_nla_get_addr(union vxlan_addr *ip, struct nlattr *nla)
142 {
143         if (nla_len(nla) >= sizeof(struct in6_addr)) {
144                 return -EAFNOSUPPORT;
145         } else if (nla_len(nla) >= sizeof(__be32)) {
146                 ip->sin.sin_addr.s_addr = nla_get_in_addr(nla);
147                 ip->sa.sa_family = AF_INET;
148                 return 0;
149         } else {
150                 return -EAFNOSUPPORT;
151         }
152 }
153
154 static int vxlan_nla_put_addr(struct sk_buff *skb, int attr,
155                               const union vxlan_addr *ip)
156 {
157         return nla_put_in_addr(skb, attr, ip->sin.sin_addr.s_addr);
158 }
159 #endif
160
161 /* Virtual Network hash table head */
162 static inline struct hlist_head *vni_head(struct vxlan_sock *vs, __be32 vni)
163 {
164         return &vs->vni_list[hash_32((__force u32)vni, VNI_HASH_BITS)];
165 }
166
167 /* Socket hash table head */
168 static inline struct hlist_head *vs_head(struct net *net, __be16 port)
169 {
170         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
171
172         return &vn->sock_list[hash_32(ntohs(port), PORT_HASH_BITS)];
173 }
174
175 /* First remote destination for a forwarding entry.
176  * Guaranteed to be non-NULL because remotes are never deleted.
177  */
178 static inline struct vxlan_rdst *first_remote_rcu(struct vxlan_fdb *fdb)
179 {
180         return list_entry_rcu(fdb->remotes.next, struct vxlan_rdst, list);
181 }
182
183 static inline struct vxlan_rdst *first_remote_rtnl(struct vxlan_fdb *fdb)
184 {
185         return list_first_entry(&fdb->remotes, struct vxlan_rdst, list);
186 }
187
188 /* Find VXLAN socket based on network namespace, address family and UDP port
189  * and enabled unshareable flags.
190  */
191 static struct vxlan_sock *vxlan_find_sock(struct net *net, sa_family_t family,
192                                           __be16 port, u32 flags, int ifindex)
193 {
194         struct vxlan_sock *vs;
195
196         flags &= VXLAN_F_RCV_FLAGS;
197
198         hlist_for_each_entry_rcu(vs, vs_head(net, port), hlist) {
199                 if (inet_sk(vs->sock->sk)->inet_sport == port &&
200                     vxlan_get_sk_family(vs) == family &&
201                     vs->flags == flags &&
202                     vs->sock->sk->sk_bound_dev_if == ifindex)
203                         return vs;
204         }
205         return NULL;
206 }
207
208 static struct vxlan_dev *vxlan_vs_find_vni(struct vxlan_sock *vs, int ifindex,
209                                            __be32 vni)
210 {
211         struct vxlan_dev_node *node;
212
213         /* For flow based devices, map all packets to VNI 0 */
214         if (vs->flags & VXLAN_F_COLLECT_METADATA)
215                 vni = 0;
216
217         hlist_for_each_entry_rcu(node, vni_head(vs, vni), hlist) {
218                 if (node->vxlan->default_dst.remote_vni != vni)
219                         continue;
220
221                 if (IS_ENABLED(CONFIG_IPV6)) {
222                         const struct vxlan_config *cfg = &node->vxlan->cfg;
223
224                         if ((cfg->flags & VXLAN_F_IPV6_LINKLOCAL) &&
225                             cfg->remote_ifindex != ifindex)
226                                 continue;
227                 }
228
229                 return node->vxlan;
230         }
231
232         return NULL;
233 }
234
235 /* Look up VNI in a per net namespace table */
236 static struct vxlan_dev *vxlan_find_vni(struct net *net, int ifindex,
237                                         __be32 vni, sa_family_t family,
238                                         __be16 port, u32 flags)
239 {
240         struct vxlan_sock *vs;
241
242         vs = vxlan_find_sock(net, family, port, flags, ifindex);
243         if (!vs)
244                 return NULL;
245
246         return vxlan_vs_find_vni(vs, ifindex, vni);
247 }
248
249 /* Fill in neighbour message in skbuff. */
250 static int vxlan_fdb_info(struct sk_buff *skb, struct vxlan_dev *vxlan,
251                           const struct vxlan_fdb *fdb,
252                           u32 portid, u32 seq, int type, unsigned int flags,
253                           const struct vxlan_rdst *rdst)
254 {
255         unsigned long now = jiffies;
256         struct nda_cacheinfo ci;
257         struct nlmsghdr *nlh;
258         struct ndmsg *ndm;
259         bool send_ip, send_eth;
260
261         nlh = nlmsg_put(skb, portid, seq, type, sizeof(*ndm), flags);
262         if (nlh == NULL)
263                 return -EMSGSIZE;
264
265         ndm = nlmsg_data(nlh);
266         memset(ndm, 0, sizeof(*ndm));
267
268         send_eth = send_ip = true;
269
270         if (type == RTM_GETNEIGH) {
271                 send_ip = !vxlan_addr_any(&rdst->remote_ip);
272                 send_eth = !is_zero_ether_addr(fdb->eth_addr);
273                 ndm->ndm_family = send_ip ? rdst->remote_ip.sa.sa_family : AF_INET;
274         } else
275                 ndm->ndm_family = AF_BRIDGE;
276         ndm->ndm_state = fdb->state;
277         ndm->ndm_ifindex = vxlan->dev->ifindex;
278         ndm->ndm_flags = fdb->flags;
279         if (rdst->offloaded)
280                 ndm->ndm_flags |= NTF_OFFLOADED;
281         ndm->ndm_type = RTN_UNICAST;
282
283         if (!net_eq(dev_net(vxlan->dev), vxlan->net) &&
284             nla_put_s32(skb, NDA_LINK_NETNSID,
285                         peernet2id(dev_net(vxlan->dev), vxlan->net)))
286                 goto nla_put_failure;
287
288         if (send_eth && nla_put(skb, NDA_LLADDR, ETH_ALEN, &fdb->eth_addr))
289                 goto nla_put_failure;
290
291         if (send_ip && vxlan_nla_put_addr(skb, NDA_DST, &rdst->remote_ip))
292                 goto nla_put_failure;
293
294         if (rdst->remote_port && rdst->remote_port != vxlan->cfg.dst_port &&
295             nla_put_be16(skb, NDA_PORT, rdst->remote_port))
296                 goto nla_put_failure;
297         if (rdst->remote_vni != vxlan->default_dst.remote_vni &&
298             nla_put_u32(skb, NDA_VNI, be32_to_cpu(rdst->remote_vni)))
299                 goto nla_put_failure;
300         if ((vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA) && fdb->vni &&
301             nla_put_u32(skb, NDA_SRC_VNI,
302                         be32_to_cpu(fdb->vni)))
303                 goto nla_put_failure;
304         if (rdst->remote_ifindex &&
305             nla_put_u32(skb, NDA_IFINDEX, rdst->remote_ifindex))
306                 goto nla_put_failure;
307
308         ci.ndm_used      = jiffies_to_clock_t(now - fdb->used);
309         ci.ndm_confirmed = 0;
310         ci.ndm_updated   = jiffies_to_clock_t(now - fdb->updated);
311         ci.ndm_refcnt    = 0;
312
313         if (nla_put(skb, NDA_CACHEINFO, sizeof(ci), &ci))
314                 goto nla_put_failure;
315
316         nlmsg_end(skb, nlh);
317         return 0;
318
319 nla_put_failure:
320         nlmsg_cancel(skb, nlh);
321         return -EMSGSIZE;
322 }
323
324 static inline size_t vxlan_nlmsg_size(void)
325 {
326         return NLMSG_ALIGN(sizeof(struct ndmsg))
327                 + nla_total_size(ETH_ALEN) /* NDA_LLADDR */
328                 + nla_total_size(sizeof(struct in6_addr)) /* NDA_DST */
329                 + nla_total_size(sizeof(__be16)) /* NDA_PORT */
330                 + nla_total_size(sizeof(__be32)) /* NDA_VNI */
331                 + nla_total_size(sizeof(__u32)) /* NDA_IFINDEX */
332                 + nla_total_size(sizeof(__s32)) /* NDA_LINK_NETNSID */
333                 + nla_total_size(sizeof(struct nda_cacheinfo));
334 }
335
336 static void __vxlan_fdb_notify(struct vxlan_dev *vxlan, struct vxlan_fdb *fdb,
337                                struct vxlan_rdst *rd, int type)
338 {
339         struct net *net = dev_net(vxlan->dev);
340         struct sk_buff *skb;
341         int err = -ENOBUFS;
342
343         skb = nlmsg_new(vxlan_nlmsg_size(), GFP_ATOMIC);
344         if (skb == NULL)
345                 goto errout;
346
347         err = vxlan_fdb_info(skb, vxlan, fdb, 0, 0, type, 0, rd);
348         if (err < 0) {
349                 /* -EMSGSIZE implies BUG in vxlan_nlmsg_size() */
350                 WARN_ON(err == -EMSGSIZE);
351                 kfree_skb(skb);
352                 goto errout;
353         }
354
355         rtnl_notify(skb, net, 0, RTNLGRP_NEIGH, NULL, GFP_ATOMIC);
356         return;
357 errout:
358         if (err < 0)
359                 rtnl_set_sk_err(net, RTNLGRP_NEIGH, err);
360 }
361
362 static void vxlan_fdb_switchdev_notifier_info(const struct vxlan_dev *vxlan,
363                             const struct vxlan_fdb *fdb,
364                             const struct vxlan_rdst *rd,
365                             struct netlink_ext_ack *extack,
366                             struct switchdev_notifier_vxlan_fdb_info *fdb_info)
367 {
368         fdb_info->info.dev = vxlan->dev;
369         fdb_info->info.extack = extack;
370         fdb_info->remote_ip = rd->remote_ip;
371         fdb_info->remote_port = rd->remote_port;
372         fdb_info->remote_vni = rd->remote_vni;
373         fdb_info->remote_ifindex = rd->remote_ifindex;
374         memcpy(fdb_info->eth_addr, fdb->eth_addr, ETH_ALEN);
375         fdb_info->vni = fdb->vni;
376         fdb_info->offloaded = rd->offloaded;
377         fdb_info->added_by_user = fdb->flags & NTF_VXLAN_ADDED_BY_USER;
378 }
379
380 static int vxlan_fdb_switchdev_call_notifiers(struct vxlan_dev *vxlan,
381                                               struct vxlan_fdb *fdb,
382                                               struct vxlan_rdst *rd,
383                                               bool adding,
384                                               struct netlink_ext_ack *extack)
385 {
386         struct switchdev_notifier_vxlan_fdb_info info;
387         enum switchdev_notifier_type notifier_type;
388         int ret;
389
390         if (WARN_ON(!rd))
391                 return 0;
392
393         notifier_type = adding ? SWITCHDEV_VXLAN_FDB_ADD_TO_DEVICE
394                                : SWITCHDEV_VXLAN_FDB_DEL_TO_DEVICE;
395         vxlan_fdb_switchdev_notifier_info(vxlan, fdb, rd, NULL, &info);
396         ret = call_switchdev_notifiers(notifier_type, vxlan->dev,
397                                        &info.info, extack);
398         return notifier_to_errno(ret);
399 }
400
401 static int vxlan_fdb_notify(struct vxlan_dev *vxlan, struct vxlan_fdb *fdb,
402                             struct vxlan_rdst *rd, int type, bool swdev_notify,
403                             struct netlink_ext_ack *extack)
404 {
405         int err;
406
407         if (swdev_notify) {
408                 switch (type) {
409                 case RTM_NEWNEIGH:
410                         err = vxlan_fdb_switchdev_call_notifiers(vxlan, fdb, rd,
411                                                                  true, extack);
412                         if (err)
413                                 return err;
414                         break;
415                 case RTM_DELNEIGH:
416                         vxlan_fdb_switchdev_call_notifiers(vxlan, fdb, rd,
417                                                            false, extack);
418                         break;
419                 }
420         }
421
422         __vxlan_fdb_notify(vxlan, fdb, rd, type);
423         return 0;
424 }
425
426 static void vxlan_ip_miss(struct net_device *dev, union vxlan_addr *ipa)
427 {
428         struct vxlan_dev *vxlan = netdev_priv(dev);
429         struct vxlan_fdb f = {
430                 .state = NUD_STALE,
431         };
432         struct vxlan_rdst remote = {
433                 .remote_ip = *ipa, /* goes to NDA_DST */
434                 .remote_vni = cpu_to_be32(VXLAN_N_VID),
435         };
436
437         vxlan_fdb_notify(vxlan, &f, &remote, RTM_GETNEIGH, true, NULL);
438 }
439
440 static void vxlan_fdb_miss(struct vxlan_dev *vxlan, const u8 eth_addr[ETH_ALEN])
441 {
442         struct vxlan_fdb f = {
443                 .state = NUD_STALE,
444         };
445         struct vxlan_rdst remote = { };
446
447         memcpy(f.eth_addr, eth_addr, ETH_ALEN);
448
449         vxlan_fdb_notify(vxlan, &f, &remote, RTM_GETNEIGH, true, NULL);
450 }
451
452 /* Hash Ethernet address */
453 static u32 eth_hash(const unsigned char *addr)
454 {
455         u64 value = get_unaligned((u64 *)addr);
456
457         /* only want 6 bytes */
458 #ifdef __BIG_ENDIAN
459         value >>= 16;
460 #else
461         value <<= 16;
462 #endif
463         return hash_64(value, FDB_HASH_BITS);
464 }
465
466 static u32 eth_vni_hash(const unsigned char *addr, __be32 vni)
467 {
468         /* use 1 byte of OUI and 3 bytes of NIC */
469         u32 key = get_unaligned((u32 *)(addr + 2));
470
471         return jhash_2words(key, vni, vxlan_salt) & (FDB_HASH_SIZE - 1);
472 }
473
474 /* Hash chain to use given mac address */
475 static inline struct hlist_head *vxlan_fdb_head(struct vxlan_dev *vxlan,
476                                                 const u8 *mac, __be32 vni)
477 {
478         if (vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA)
479                 return &vxlan->fdb_head[eth_vni_hash(mac, vni)];
480         else
481                 return &vxlan->fdb_head[eth_hash(mac)];
482 }
483
484 /* Look up Ethernet address in forwarding table */
485 static struct vxlan_fdb *__vxlan_find_mac(struct vxlan_dev *vxlan,
486                                           const u8 *mac, __be32 vni)
487 {
488         struct hlist_head *head = vxlan_fdb_head(vxlan, mac, vni);
489         struct vxlan_fdb *f;
490
491         hlist_for_each_entry_rcu(f, head, hlist) {
492                 if (ether_addr_equal(mac, f->eth_addr)) {
493                         if (vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA) {
494                                 if (vni == f->vni)
495                                         return f;
496                         } else {
497                                 return f;
498                         }
499                 }
500         }
501
502         return NULL;
503 }
504
505 static struct vxlan_fdb *vxlan_find_mac(struct vxlan_dev *vxlan,
506                                         const u8 *mac, __be32 vni)
507 {
508         struct vxlan_fdb *f;
509
510         f = __vxlan_find_mac(vxlan, mac, vni);
511         if (f && f->used != jiffies)
512                 f->used = jiffies;
513
514         return f;
515 }
516
517 /* caller should hold vxlan->hash_lock */
518 static struct vxlan_rdst *vxlan_fdb_find_rdst(struct vxlan_fdb *f,
519                                               union vxlan_addr *ip, __be16 port,
520                                               __be32 vni, __u32 ifindex)
521 {
522         struct vxlan_rdst *rd;
523
524         list_for_each_entry(rd, &f->remotes, list) {
525                 if (vxlan_addr_equal(&rd->remote_ip, ip) &&
526                     rd->remote_port == port &&
527                     rd->remote_vni == vni &&
528                     rd->remote_ifindex == ifindex)
529                         return rd;
530         }
531
532         return NULL;
533 }
534
535 int vxlan_fdb_find_uc(struct net_device *dev, const u8 *mac, __be32 vni,
536                       struct switchdev_notifier_vxlan_fdb_info *fdb_info)
537 {
538         struct vxlan_dev *vxlan = netdev_priv(dev);
539         u8 eth_addr[ETH_ALEN + 2] = { 0 };
540         struct vxlan_rdst *rdst;
541         struct vxlan_fdb *f;
542         int rc = 0;
543
544         if (is_multicast_ether_addr(mac) ||
545             is_zero_ether_addr(mac))
546                 return -EINVAL;
547
548         ether_addr_copy(eth_addr, mac);
549
550         rcu_read_lock();
551
552         f = __vxlan_find_mac(vxlan, eth_addr, vni);
553         if (!f) {
554                 rc = -ENOENT;
555                 goto out;
556         }
557
558         rdst = first_remote_rcu(f);
559         vxlan_fdb_switchdev_notifier_info(vxlan, f, rdst, NULL, fdb_info);
560
561 out:
562         rcu_read_unlock();
563         return rc;
564 }
565 EXPORT_SYMBOL_GPL(vxlan_fdb_find_uc);
566
567 static int vxlan_fdb_notify_one(struct notifier_block *nb,
568                                 const struct vxlan_dev *vxlan,
569                                 const struct vxlan_fdb *f,
570                                 const struct vxlan_rdst *rdst,
571                                 struct netlink_ext_ack *extack)
572 {
573         struct switchdev_notifier_vxlan_fdb_info fdb_info;
574         int rc;
575
576         vxlan_fdb_switchdev_notifier_info(vxlan, f, rdst, extack, &fdb_info);
577         rc = nb->notifier_call(nb, SWITCHDEV_VXLAN_FDB_ADD_TO_DEVICE,
578                                &fdb_info);
579         return notifier_to_errno(rc);
580 }
581
582 int vxlan_fdb_replay(const struct net_device *dev, __be32 vni,
583                      struct notifier_block *nb,
584                      struct netlink_ext_ack *extack)
585 {
586         struct vxlan_dev *vxlan;
587         struct vxlan_rdst *rdst;
588         struct vxlan_fdb *f;
589         unsigned int h;
590         int rc = 0;
591
592         if (!netif_is_vxlan(dev))
593                 return -EINVAL;
594         vxlan = netdev_priv(dev);
595
596         spin_lock_bh(&vxlan->hash_lock);
597         for (h = 0; h < FDB_HASH_SIZE; ++h) {
598                 hlist_for_each_entry(f, &vxlan->fdb_head[h], hlist) {
599                         if (f->vni == vni) {
600                                 list_for_each_entry(rdst, &f->remotes, list) {
601                                         rc = vxlan_fdb_notify_one(nb, vxlan,
602                                                                   f, rdst,
603                                                                   extack);
604                                         if (rc)
605                                                 goto out;
606                                 }
607                         }
608                 }
609         }
610
611 out:
612         spin_unlock_bh(&vxlan->hash_lock);
613         return rc;
614 }
615 EXPORT_SYMBOL_GPL(vxlan_fdb_replay);
616
617 void vxlan_fdb_clear_offload(const struct net_device *dev, __be32 vni)
618 {
619         struct vxlan_dev *vxlan;
620         struct vxlan_rdst *rdst;
621         struct vxlan_fdb *f;
622         unsigned int h;
623
624         if (!netif_is_vxlan(dev))
625                 return;
626         vxlan = netdev_priv(dev);
627
628         spin_lock_bh(&vxlan->hash_lock);
629         for (h = 0; h < FDB_HASH_SIZE; ++h) {
630                 hlist_for_each_entry(f, &vxlan->fdb_head[h], hlist)
631                         if (f->vni == vni)
632                                 list_for_each_entry(rdst, &f->remotes, list)
633                                         rdst->offloaded = false;
634         }
635         spin_unlock_bh(&vxlan->hash_lock);
636 }
637 EXPORT_SYMBOL_GPL(vxlan_fdb_clear_offload);
638
639 /* Replace destination of unicast mac */
640 static int vxlan_fdb_replace(struct vxlan_fdb *f,
641                              union vxlan_addr *ip, __be16 port, __be32 vni,
642                              __u32 ifindex, struct vxlan_rdst *oldrd)
643 {
644         struct vxlan_rdst *rd;
645
646         rd = vxlan_fdb_find_rdst(f, ip, port, vni, ifindex);
647         if (rd)
648                 return 0;
649
650         rd = list_first_entry_or_null(&f->remotes, struct vxlan_rdst, list);
651         if (!rd)
652                 return 0;
653
654         *oldrd = *rd;
655         dst_cache_reset(&rd->dst_cache);
656         rd->remote_ip = *ip;
657         rd->remote_port = port;
658         rd->remote_vni = vni;
659         rd->remote_ifindex = ifindex;
660         rd->offloaded = false;
661         return 1;
662 }
663
664 /* Add/update destinations for multicast */
665 static int vxlan_fdb_append(struct vxlan_fdb *f,
666                             union vxlan_addr *ip, __be16 port, __be32 vni,
667                             __u32 ifindex, struct vxlan_rdst **rdp)
668 {
669         struct vxlan_rdst *rd;
670
671         rd = vxlan_fdb_find_rdst(f, ip, port, vni, ifindex);
672         if (rd)
673                 return 0;
674
675         rd = kmalloc(sizeof(*rd), GFP_ATOMIC);
676         if (rd == NULL)
677                 return -ENOBUFS;
678
679         if (dst_cache_init(&rd->dst_cache, GFP_ATOMIC)) {
680                 kfree(rd);
681                 return -ENOBUFS;
682         }
683
684         rd->remote_ip = *ip;
685         rd->remote_port = port;
686         rd->offloaded = false;
687         rd->remote_vni = vni;
688         rd->remote_ifindex = ifindex;
689
690         list_add_tail_rcu(&rd->list, &f->remotes);
691
692         *rdp = rd;
693         return 1;
694 }
695
696 static struct vxlanhdr *vxlan_gro_remcsum(struct sk_buff *skb,
697                                           unsigned int off,
698                                           struct vxlanhdr *vh, size_t hdrlen,
699                                           __be32 vni_field,
700                                           struct gro_remcsum *grc,
701                                           bool nopartial)
702 {
703         size_t start, offset;
704
705         if (skb->remcsum_offload)
706                 return vh;
707
708         if (!NAPI_GRO_CB(skb)->csum_valid)
709                 return NULL;
710
711         start = vxlan_rco_start(vni_field);
712         offset = start + vxlan_rco_offset(vni_field);
713
714         vh = skb_gro_remcsum_process(skb, (void *)vh, off, hdrlen,
715                                      start, offset, grc, nopartial);
716
717         skb->remcsum_offload = 1;
718
719         return vh;
720 }
721
722 static struct sk_buff *vxlan_gro_receive(struct sock *sk,
723                                          struct list_head *head,
724                                          struct sk_buff *skb)
725 {
726         struct sk_buff *pp = NULL;
727         struct sk_buff *p;
728         struct vxlanhdr *vh, *vh2;
729         unsigned int hlen, off_vx;
730         int flush = 1;
731         struct vxlan_sock *vs = rcu_dereference_sk_user_data(sk);
732         __be32 flags;
733         struct gro_remcsum grc;
734
735         skb_gro_remcsum_init(&grc);
736
737         off_vx = skb_gro_offset(skb);
738         hlen = off_vx + sizeof(*vh);
739         vh   = skb_gro_header_fast(skb, off_vx);
740         if (skb_gro_header_hard(skb, hlen)) {
741                 vh = skb_gro_header_slow(skb, hlen, off_vx);
742                 if (unlikely(!vh))
743                         goto out;
744         }
745
746         skb_gro_postpull_rcsum(skb, vh, sizeof(struct vxlanhdr));
747
748         flags = vh->vx_flags;
749
750         if ((flags & VXLAN_HF_RCO) && (vs->flags & VXLAN_F_REMCSUM_RX)) {
751                 vh = vxlan_gro_remcsum(skb, off_vx, vh, sizeof(struct vxlanhdr),
752                                        vh->vx_vni, &grc,
753                                        !!(vs->flags &
754                                           VXLAN_F_REMCSUM_NOPARTIAL));
755
756                 if (!vh)
757                         goto out;
758         }
759
760         skb_gro_pull(skb, sizeof(struct vxlanhdr)); /* pull vxlan header */
761
762         list_for_each_entry(p, head, list) {
763                 if (!NAPI_GRO_CB(p)->same_flow)
764                         continue;
765
766                 vh2 = (struct vxlanhdr *)(p->data + off_vx);
767                 if (vh->vx_flags != vh2->vx_flags ||
768                     vh->vx_vni != vh2->vx_vni) {
769                         NAPI_GRO_CB(p)->same_flow = 0;
770                         continue;
771                 }
772         }
773
774         pp = call_gro_receive(eth_gro_receive, head, skb);
775         flush = 0;
776
777 out:
778         skb_gro_flush_final_remcsum(skb, pp, flush, &grc);
779
780         return pp;
781 }
782
783 static int vxlan_gro_complete(struct sock *sk, struct sk_buff *skb, int nhoff)
784 {
785         /* Sets 'skb->inner_mac_header' since we are always called with
786          * 'skb->encapsulation' set.
787          */
788         return eth_gro_complete(skb, nhoff + sizeof(struct vxlanhdr));
789 }
790
791 static struct vxlan_fdb *vxlan_fdb_alloc(struct vxlan_dev *vxlan,
792                                          const u8 *mac, __u16 state,
793                                          __be32 src_vni, __u16 ndm_flags)
794 {
795         struct vxlan_fdb *f;
796
797         f = kmalloc(sizeof(*f), GFP_ATOMIC);
798         if (!f)
799                 return NULL;
800         f->state = state;
801         f->flags = ndm_flags;
802         f->updated = f->used = jiffies;
803         f->vni = src_vni;
804         INIT_LIST_HEAD(&f->remotes);
805         memcpy(f->eth_addr, mac, ETH_ALEN);
806
807         return f;
808 }
809
810 static int vxlan_fdb_create(struct vxlan_dev *vxlan,
811                             const u8 *mac, union vxlan_addr *ip,
812                             __u16 state, __be16 port, __be32 src_vni,
813                             __be32 vni, __u32 ifindex, __u16 ndm_flags,
814                             struct vxlan_fdb **fdb)
815 {
816         struct vxlan_rdst *rd = NULL;
817         struct vxlan_fdb *f;
818         int rc;
819
820         if (vxlan->cfg.addrmax &&
821             vxlan->addrcnt >= vxlan->cfg.addrmax)
822                 return -ENOSPC;
823
824         netdev_dbg(vxlan->dev, "add %pM -> %pIS\n", mac, ip);
825         f = vxlan_fdb_alloc(vxlan, mac, state, src_vni, ndm_flags);
826         if (!f)
827                 return -ENOMEM;
828
829         rc = vxlan_fdb_append(f, ip, port, vni, ifindex, &rd);
830         if (rc < 0) {
831                 kfree(f);
832                 return rc;
833         }
834
835         ++vxlan->addrcnt;
836         hlist_add_head_rcu(&f->hlist,
837                            vxlan_fdb_head(vxlan, mac, src_vni));
838
839         *fdb = f;
840
841         return 0;
842 }
843
844 static void vxlan_fdb_free(struct rcu_head *head)
845 {
846         struct vxlan_fdb *f = container_of(head, struct vxlan_fdb, rcu);
847         struct vxlan_rdst *rd, *nd;
848
849         list_for_each_entry_safe(rd, nd, &f->remotes, list) {
850                 dst_cache_destroy(&rd->dst_cache);
851                 kfree(rd);
852         }
853         kfree(f);
854 }
855
856 static void vxlan_fdb_destroy(struct vxlan_dev *vxlan, struct vxlan_fdb *f,
857                               bool do_notify, bool swdev_notify)
858 {
859         struct vxlan_rdst *rd;
860
861         netdev_dbg(vxlan->dev, "delete %pM\n", f->eth_addr);
862
863         --vxlan->addrcnt;
864         if (do_notify)
865                 list_for_each_entry(rd, &f->remotes, list)
866                         vxlan_fdb_notify(vxlan, f, rd, RTM_DELNEIGH,
867                                          swdev_notify, NULL);
868
869         hlist_del_rcu(&f->hlist);
870         call_rcu(&f->rcu, vxlan_fdb_free);
871 }
872
873 static void vxlan_dst_free(struct rcu_head *head)
874 {
875         struct vxlan_rdst *rd = container_of(head, struct vxlan_rdst, rcu);
876
877         dst_cache_destroy(&rd->dst_cache);
878         kfree(rd);
879 }
880
881 static int vxlan_fdb_update_existing(struct vxlan_dev *vxlan,
882                                      union vxlan_addr *ip,
883                                      __u16 state, __u16 flags,
884                                      __be16 port, __be32 vni,
885                                      __u32 ifindex, __u16 ndm_flags,
886                                      struct vxlan_fdb *f,
887                                      bool swdev_notify,
888                                      struct netlink_ext_ack *extack)
889 {
890         __u16 fdb_flags = (ndm_flags & ~NTF_USE);
891         struct vxlan_rdst *rd = NULL;
892         struct vxlan_rdst oldrd;
893         int notify = 0;
894         int rc = 0;
895         int err;
896
897         /* Do not allow an externally learned entry to take over an entry added
898          * by the user.
899          */
900         if (!(fdb_flags & NTF_EXT_LEARNED) ||
901             !(f->flags & NTF_VXLAN_ADDED_BY_USER)) {
902                 if (f->state != state) {
903                         f->state = state;
904                         f->updated = jiffies;
905                         notify = 1;
906                 }
907                 if (f->flags != fdb_flags) {
908                         f->flags = fdb_flags;
909                         f->updated = jiffies;
910                         notify = 1;
911                 }
912         }
913
914         if ((flags & NLM_F_REPLACE)) {
915                 /* Only change unicasts */
916                 if (!(is_multicast_ether_addr(f->eth_addr) ||
917                       is_zero_ether_addr(f->eth_addr))) {
918                         rc = vxlan_fdb_replace(f, ip, port, vni,
919                                                ifindex, &oldrd);
920                         notify |= rc;
921                 } else {
922                         return -EOPNOTSUPP;
923                 }
924         }
925         if ((flags & NLM_F_APPEND) &&
926             (is_multicast_ether_addr(f->eth_addr) ||
927              is_zero_ether_addr(f->eth_addr))) {
928                 rc = vxlan_fdb_append(f, ip, port, vni, ifindex, &rd);
929
930                 if (rc < 0)
931                         return rc;
932                 notify |= rc;
933         }
934
935         if (ndm_flags & NTF_USE)
936                 f->used = jiffies;
937
938         if (notify) {
939                 if (rd == NULL)
940                         rd = first_remote_rtnl(f);
941
942                 err = vxlan_fdb_notify(vxlan, f, rd, RTM_NEWNEIGH,
943                                        swdev_notify, extack);
944                 if (err)
945                         goto err_notify;
946         }
947
948         return 0;
949
950 err_notify:
951         if ((flags & NLM_F_REPLACE) && rc)
952                 *rd = oldrd;
953         else if ((flags & NLM_F_APPEND) && rc) {
954                 list_del_rcu(&rd->list);
955                 call_rcu(&rd->rcu, vxlan_dst_free);
956         }
957         return err;
958 }
959
960 static int vxlan_fdb_update_create(struct vxlan_dev *vxlan,
961                                    const u8 *mac, union vxlan_addr *ip,
962                                    __u16 state, __u16 flags,
963                                    __be16 port, __be32 src_vni, __be32 vni,
964                                    __u32 ifindex, __u16 ndm_flags,
965                                    bool swdev_notify,
966                                    struct netlink_ext_ack *extack)
967 {
968         __u16 fdb_flags = (ndm_flags & ~NTF_USE);
969         struct vxlan_fdb *f;
970         int rc;
971
972         /* Disallow replace to add a multicast entry */
973         if ((flags & NLM_F_REPLACE) &&
974             (is_multicast_ether_addr(mac) || is_zero_ether_addr(mac)))
975                 return -EOPNOTSUPP;
976
977         netdev_dbg(vxlan->dev, "add %pM -> %pIS\n", mac, ip);
978         rc = vxlan_fdb_create(vxlan, mac, ip, state, port, src_vni,
979                               vni, ifindex, fdb_flags, &f);
980         if (rc < 0)
981                 return rc;
982
983         rc = vxlan_fdb_notify(vxlan, f, first_remote_rtnl(f), RTM_NEWNEIGH,
984                               swdev_notify, extack);
985         if (rc)
986                 goto err_notify;
987
988         return 0;
989
990 err_notify:
991         vxlan_fdb_destroy(vxlan, f, false, false);
992         return rc;
993 }
994
995 /* Add new entry to forwarding table -- assumes lock held */
996 static int vxlan_fdb_update(struct vxlan_dev *vxlan,
997                             const u8 *mac, union vxlan_addr *ip,
998                             __u16 state, __u16 flags,
999                             __be16 port, __be32 src_vni, __be32 vni,
1000                             __u32 ifindex, __u16 ndm_flags,
1001                             bool swdev_notify,
1002                             struct netlink_ext_ack *extack)
1003 {
1004         struct vxlan_fdb *f;
1005
1006         f = __vxlan_find_mac(vxlan, mac, src_vni);
1007         if (f) {
1008                 if (flags & NLM_F_EXCL) {
1009                         netdev_dbg(vxlan->dev,
1010                                    "lost race to create %pM\n", mac);
1011                         return -EEXIST;
1012                 }
1013
1014                 return vxlan_fdb_update_existing(vxlan, ip, state, flags, port,
1015                                                  vni, ifindex, ndm_flags, f,
1016                                                  swdev_notify, extack);
1017         } else {
1018                 if (!(flags & NLM_F_CREATE))
1019                         return -ENOENT;
1020
1021                 return vxlan_fdb_update_create(vxlan, mac, ip, state, flags,
1022                                                port, src_vni, vni, ifindex,
1023                                                ndm_flags, swdev_notify, extack);
1024         }
1025 }
1026
1027 static void vxlan_fdb_dst_destroy(struct vxlan_dev *vxlan, struct vxlan_fdb *f,
1028                                   struct vxlan_rdst *rd, bool swdev_notify)
1029 {
1030         list_del_rcu(&rd->list);
1031         vxlan_fdb_notify(vxlan, f, rd, RTM_DELNEIGH, swdev_notify, NULL);
1032         call_rcu(&rd->rcu, vxlan_dst_free);
1033 }
1034
1035 static int vxlan_fdb_parse(struct nlattr *tb[], struct vxlan_dev *vxlan,
1036                            union vxlan_addr *ip, __be16 *port, __be32 *src_vni,
1037                            __be32 *vni, u32 *ifindex)
1038 {
1039         struct net *net = dev_net(vxlan->dev);
1040         int err;
1041
1042         if (tb[NDA_DST]) {
1043                 err = vxlan_nla_get_addr(ip, tb[NDA_DST]);
1044                 if (err)
1045                         return err;
1046         } else {
1047                 union vxlan_addr *remote = &vxlan->default_dst.remote_ip;
1048                 if (remote->sa.sa_family == AF_INET) {
1049                         ip->sin.sin_addr.s_addr = htonl(INADDR_ANY);
1050                         ip->sa.sa_family = AF_INET;
1051 #if IS_ENABLED(CONFIG_IPV6)
1052                 } else {
1053                         ip->sin6.sin6_addr = in6addr_any;
1054                         ip->sa.sa_family = AF_INET6;
1055 #endif
1056                 }
1057         }
1058
1059         if (tb[NDA_PORT]) {
1060                 if (nla_len(tb[NDA_PORT]) != sizeof(__be16))
1061                         return -EINVAL;
1062                 *port = nla_get_be16(tb[NDA_PORT]);
1063         } else {
1064                 *port = vxlan->cfg.dst_port;
1065         }
1066
1067         if (tb[NDA_VNI]) {
1068                 if (nla_len(tb[NDA_VNI]) != sizeof(u32))
1069                         return -EINVAL;
1070                 *vni = cpu_to_be32(nla_get_u32(tb[NDA_VNI]));
1071         } else {
1072                 *vni = vxlan->default_dst.remote_vni;
1073         }
1074
1075         if (tb[NDA_SRC_VNI]) {
1076                 if (nla_len(tb[NDA_SRC_VNI]) != sizeof(u32))
1077                         return -EINVAL;
1078                 *src_vni = cpu_to_be32(nla_get_u32(tb[NDA_SRC_VNI]));
1079         } else {
1080                 *src_vni = vxlan->default_dst.remote_vni;
1081         }
1082
1083         if (tb[NDA_IFINDEX]) {
1084                 struct net_device *tdev;
1085
1086                 if (nla_len(tb[NDA_IFINDEX]) != sizeof(u32))
1087                         return -EINVAL;
1088                 *ifindex = nla_get_u32(tb[NDA_IFINDEX]);
1089                 tdev = __dev_get_by_index(net, *ifindex);
1090                 if (!tdev)
1091                         return -EADDRNOTAVAIL;
1092         } else {
1093                 *ifindex = 0;
1094         }
1095
1096         return 0;
1097 }
1098
1099 /* Add static entry (via netlink) */
1100 static int vxlan_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
1101                          struct net_device *dev,
1102                          const unsigned char *addr, u16 vid, u16 flags,
1103                          struct netlink_ext_ack *extack)
1104 {
1105         struct vxlan_dev *vxlan = netdev_priv(dev);
1106         /* struct net *net = dev_net(vxlan->dev); */
1107         union vxlan_addr ip;
1108         __be16 port;
1109         __be32 src_vni, vni;
1110         u32 ifindex;
1111         int err;
1112
1113         if (!(ndm->ndm_state & (NUD_PERMANENT|NUD_REACHABLE))) {
1114                 pr_info("RTM_NEWNEIGH with invalid state %#x\n",
1115                         ndm->ndm_state);
1116                 return -EINVAL;
1117         }
1118
1119         if (tb[NDA_DST] == NULL)
1120                 return -EINVAL;
1121
1122         err = vxlan_fdb_parse(tb, vxlan, &ip, &port, &src_vni, &vni, &ifindex);
1123         if (err)
1124                 return err;
1125
1126         if (vxlan->default_dst.remote_ip.sa.sa_family != ip.sa.sa_family)
1127                 return -EAFNOSUPPORT;
1128
1129         spin_lock_bh(&vxlan->hash_lock);
1130         err = vxlan_fdb_update(vxlan, addr, &ip, ndm->ndm_state, flags,
1131                                port, src_vni, vni, ifindex,
1132                                ndm->ndm_flags | NTF_VXLAN_ADDED_BY_USER,
1133                                true, extack);
1134         spin_unlock_bh(&vxlan->hash_lock);
1135
1136         return err;
1137 }
1138
1139 static int __vxlan_fdb_delete(struct vxlan_dev *vxlan,
1140                               const unsigned char *addr, union vxlan_addr ip,
1141                               __be16 port, __be32 src_vni, __be32 vni,
1142                               u32 ifindex, bool swdev_notify)
1143 {
1144         struct vxlan_fdb *f;
1145         struct vxlan_rdst *rd = NULL;
1146         int err = -ENOENT;
1147
1148         f = vxlan_find_mac(vxlan, addr, src_vni);
1149         if (!f)
1150                 return err;
1151
1152         if (!vxlan_addr_any(&ip)) {
1153                 rd = vxlan_fdb_find_rdst(f, &ip, port, vni, ifindex);
1154                 if (!rd)
1155                         goto out;
1156         }
1157
1158         /* remove a destination if it's not the only one on the list,
1159          * otherwise destroy the fdb entry
1160          */
1161         if (rd && !list_is_singular(&f->remotes)) {
1162                 vxlan_fdb_dst_destroy(vxlan, f, rd, swdev_notify);
1163                 goto out;
1164         }
1165
1166         vxlan_fdb_destroy(vxlan, f, true, swdev_notify);
1167
1168 out:
1169         return 0;
1170 }
1171
1172 /* Delete entry (via netlink) */
1173 static int vxlan_fdb_delete(struct ndmsg *ndm, struct nlattr *tb[],
1174                             struct net_device *dev,
1175                             const unsigned char *addr, u16 vid)
1176 {
1177         struct vxlan_dev *vxlan = netdev_priv(dev);
1178         union vxlan_addr ip;
1179         __be32 src_vni, vni;
1180         __be16 port;
1181         u32 ifindex;
1182         int err;
1183
1184         err = vxlan_fdb_parse(tb, vxlan, &ip, &port, &src_vni, &vni, &ifindex);
1185         if (err)
1186                 return err;
1187
1188         spin_lock_bh(&vxlan->hash_lock);
1189         err = __vxlan_fdb_delete(vxlan, addr, ip, port, src_vni, vni, ifindex,
1190                                  true);
1191         spin_unlock_bh(&vxlan->hash_lock);
1192
1193         return err;
1194 }
1195
1196 /* Dump forwarding table */
1197 static int vxlan_fdb_dump(struct sk_buff *skb, struct netlink_callback *cb,
1198                           struct net_device *dev,
1199                           struct net_device *filter_dev, int *idx)
1200 {
1201         struct vxlan_dev *vxlan = netdev_priv(dev);
1202         unsigned int h;
1203         int err = 0;
1204
1205         for (h = 0; h < FDB_HASH_SIZE; ++h) {
1206                 struct vxlan_fdb *f;
1207
1208                 hlist_for_each_entry_rcu(f, &vxlan->fdb_head[h], hlist) {
1209                         struct vxlan_rdst *rd;
1210
1211                         list_for_each_entry_rcu(rd, &f->remotes, list) {
1212                                 if (*idx < cb->args[2])
1213                                         goto skip;
1214
1215                                 err = vxlan_fdb_info(skb, vxlan, f,
1216                                                      NETLINK_CB(cb->skb).portid,
1217                                                      cb->nlh->nlmsg_seq,
1218                                                      RTM_NEWNEIGH,
1219                                                      NLM_F_MULTI, rd);
1220                                 if (err < 0)
1221                                         goto out;
1222 skip:
1223                                 *idx += 1;
1224                         }
1225                 }
1226         }
1227 out:
1228         return err;
1229 }
1230
1231 static int vxlan_fdb_get(struct sk_buff *skb,
1232                          struct nlattr *tb[],
1233                          struct net_device *dev,
1234                          const unsigned char *addr,
1235                          u16 vid, u32 portid, u32 seq,
1236                          struct netlink_ext_ack *extack)
1237 {
1238         struct vxlan_dev *vxlan = netdev_priv(dev);
1239         struct vxlan_fdb *f;
1240         __be32 vni;
1241         int err;
1242
1243         if (tb[NDA_VNI])
1244                 vni = cpu_to_be32(nla_get_u32(tb[NDA_VNI]));
1245         else
1246                 vni = vxlan->default_dst.remote_vni;
1247
1248         rcu_read_lock();
1249
1250         f = __vxlan_find_mac(vxlan, addr, vni);
1251         if (!f) {
1252                 NL_SET_ERR_MSG(extack, "Fdb entry not found");
1253                 err = -ENOENT;
1254                 goto errout;
1255         }
1256
1257         err = vxlan_fdb_info(skb, vxlan, f, portid, seq,
1258                              RTM_NEWNEIGH, 0, first_remote_rcu(f));
1259 errout:
1260         rcu_read_unlock();
1261         return err;
1262 }
1263
1264 /* Watch incoming packets to learn mapping between Ethernet address
1265  * and Tunnel endpoint.
1266  * Return true if packet is bogus and should be dropped.
1267  */
1268 static bool vxlan_snoop(struct net_device *dev,
1269                         union vxlan_addr *src_ip, const u8 *src_mac,
1270                         u32 src_ifindex, __be32 vni)
1271 {
1272         struct vxlan_dev *vxlan = netdev_priv(dev);
1273         struct vxlan_fdb *f;
1274         u32 ifindex = 0;
1275
1276 #if IS_ENABLED(CONFIG_IPV6)
1277         if (src_ip->sa.sa_family == AF_INET6 &&
1278             (ipv6_addr_type(&src_ip->sin6.sin6_addr) & IPV6_ADDR_LINKLOCAL))
1279                 ifindex = src_ifindex;
1280 #endif
1281
1282         f = vxlan_find_mac(vxlan, src_mac, vni);
1283         if (likely(f)) {
1284                 struct vxlan_rdst *rdst = first_remote_rcu(f);
1285
1286                 if (likely(vxlan_addr_equal(&rdst->remote_ip, src_ip) &&
1287                            rdst->remote_ifindex == ifindex))
1288                         return false;
1289
1290                 /* Don't migrate static entries, drop packets */
1291                 if (f->state & (NUD_PERMANENT | NUD_NOARP))
1292                         return true;
1293
1294                 if (net_ratelimit())
1295                         netdev_info(dev,
1296                                     "%pM migrated from %pIS to %pIS\n",
1297                                     src_mac, &rdst->remote_ip.sa, &src_ip->sa);
1298
1299                 rdst->remote_ip = *src_ip;
1300                 f->updated = jiffies;
1301                 vxlan_fdb_notify(vxlan, f, rdst, RTM_NEWNEIGH, true, NULL);
1302         } else {
1303                 /* learned new entry */
1304                 spin_lock(&vxlan->hash_lock);
1305
1306                 /* close off race between vxlan_flush and incoming packets */
1307                 if (netif_running(dev))
1308                         vxlan_fdb_update(vxlan, src_mac, src_ip,
1309                                          NUD_REACHABLE,
1310                                          NLM_F_EXCL|NLM_F_CREATE,
1311                                          vxlan->cfg.dst_port,
1312                                          vni,
1313                                          vxlan->default_dst.remote_vni,
1314                                          ifindex, NTF_SELF, true, NULL);
1315                 spin_unlock(&vxlan->hash_lock);
1316         }
1317
1318         return false;
1319 }
1320
1321 /* See if multicast group is already in use by other ID */
1322 static bool vxlan_group_used(struct vxlan_net *vn, struct vxlan_dev *dev)
1323 {
1324         struct vxlan_dev *vxlan;
1325         struct vxlan_sock *sock4;
1326 #if IS_ENABLED(CONFIG_IPV6)
1327         struct vxlan_sock *sock6;
1328 #endif
1329         unsigned short family = dev->default_dst.remote_ip.sa.sa_family;
1330
1331         sock4 = rtnl_dereference(dev->vn4_sock);
1332
1333         /* The vxlan_sock is only used by dev, leaving group has
1334          * no effect on other vxlan devices.
1335          */
1336         if (family == AF_INET && sock4 && refcount_read(&sock4->refcnt) == 1)
1337                 return false;
1338 #if IS_ENABLED(CONFIG_IPV6)
1339         sock6 = rtnl_dereference(dev->vn6_sock);
1340         if (family == AF_INET6 && sock6 && refcount_read(&sock6->refcnt) == 1)
1341                 return false;
1342 #endif
1343
1344         list_for_each_entry(vxlan, &vn->vxlan_list, next) {
1345                 if (!netif_running(vxlan->dev) || vxlan == dev)
1346                         continue;
1347
1348                 if (family == AF_INET &&
1349                     rtnl_dereference(vxlan->vn4_sock) != sock4)
1350                         continue;
1351 #if IS_ENABLED(CONFIG_IPV6)
1352                 if (family == AF_INET6 &&
1353                     rtnl_dereference(vxlan->vn6_sock) != sock6)
1354                         continue;
1355 #endif
1356
1357                 if (!vxlan_addr_equal(&vxlan->default_dst.remote_ip,
1358                                       &dev->default_dst.remote_ip))
1359                         continue;
1360
1361                 if (vxlan->default_dst.remote_ifindex !=
1362                     dev->default_dst.remote_ifindex)
1363                         continue;
1364
1365                 return true;
1366         }
1367
1368         return false;
1369 }
1370
1371 static bool __vxlan_sock_release_prep(struct vxlan_sock *vs)
1372 {
1373         struct vxlan_net *vn;
1374
1375         if (!vs)
1376                 return false;
1377         if (!refcount_dec_and_test(&vs->refcnt))
1378                 return false;
1379
1380         vn = net_generic(sock_net(vs->sock->sk), vxlan_net_id);
1381         spin_lock(&vn->sock_lock);
1382         hlist_del_rcu(&vs->hlist);
1383         udp_tunnel_notify_del_rx_port(vs->sock,
1384                                       (vs->flags & VXLAN_F_GPE) ?
1385                                       UDP_TUNNEL_TYPE_VXLAN_GPE :
1386                                       UDP_TUNNEL_TYPE_VXLAN);
1387         spin_unlock(&vn->sock_lock);
1388
1389         return true;
1390 }
1391
1392 static void vxlan_sock_release(struct vxlan_dev *vxlan)
1393 {
1394         struct vxlan_sock *sock4 = rtnl_dereference(vxlan->vn4_sock);
1395 #if IS_ENABLED(CONFIG_IPV6)
1396         struct vxlan_sock *sock6 = rtnl_dereference(vxlan->vn6_sock);
1397
1398         RCU_INIT_POINTER(vxlan->vn6_sock, NULL);
1399 #endif
1400
1401         RCU_INIT_POINTER(vxlan->vn4_sock, NULL);
1402         synchronize_net();
1403
1404         vxlan_vs_del_dev(vxlan);
1405
1406         if (__vxlan_sock_release_prep(sock4)) {
1407                 udp_tunnel_sock_release(sock4->sock);
1408                 kfree(sock4);
1409         }
1410
1411 #if IS_ENABLED(CONFIG_IPV6)
1412         if (__vxlan_sock_release_prep(sock6)) {
1413                 udp_tunnel_sock_release(sock6->sock);
1414                 kfree(sock6);
1415         }
1416 #endif
1417 }
1418
1419 /* Update multicast group membership when first VNI on
1420  * multicast address is brought up
1421  */
1422 static int vxlan_igmp_join(struct vxlan_dev *vxlan)
1423 {
1424         struct sock *sk;
1425         union vxlan_addr *ip = &vxlan->default_dst.remote_ip;
1426         int ifindex = vxlan->default_dst.remote_ifindex;
1427         int ret = -EINVAL;
1428
1429         if (ip->sa.sa_family == AF_INET) {
1430                 struct vxlan_sock *sock4 = rtnl_dereference(vxlan->vn4_sock);
1431                 struct ip_mreqn mreq = {
1432                         .imr_multiaddr.s_addr   = ip->sin.sin_addr.s_addr,
1433                         .imr_ifindex            = ifindex,
1434                 };
1435
1436                 sk = sock4->sock->sk;
1437                 lock_sock(sk);
1438                 ret = ip_mc_join_group(sk, &mreq);
1439                 release_sock(sk);
1440 #if IS_ENABLED(CONFIG_IPV6)
1441         } else {
1442                 struct vxlan_sock *sock6 = rtnl_dereference(vxlan->vn6_sock);
1443
1444                 sk = sock6->sock->sk;
1445                 lock_sock(sk);
1446                 ret = ipv6_stub->ipv6_sock_mc_join(sk, ifindex,
1447                                                    &ip->sin6.sin6_addr);
1448                 release_sock(sk);
1449 #endif
1450         }
1451
1452         return ret;
1453 }
1454
1455 /* Inverse of vxlan_igmp_join when last VNI is brought down */
1456 static int vxlan_igmp_leave(struct vxlan_dev *vxlan)
1457 {
1458         struct sock *sk;
1459         union vxlan_addr *ip = &vxlan->default_dst.remote_ip;
1460         int ifindex = vxlan->default_dst.remote_ifindex;
1461         int ret = -EINVAL;
1462
1463         if (ip->sa.sa_family == AF_INET) {
1464                 struct vxlan_sock *sock4 = rtnl_dereference(vxlan->vn4_sock);
1465                 struct ip_mreqn mreq = {
1466                         .imr_multiaddr.s_addr   = ip->sin.sin_addr.s_addr,
1467                         .imr_ifindex            = ifindex,
1468                 };
1469
1470                 sk = sock4->sock->sk;
1471                 lock_sock(sk);
1472                 ret = ip_mc_leave_group(sk, &mreq);
1473                 release_sock(sk);
1474 #if IS_ENABLED(CONFIG_IPV6)
1475         } else {
1476                 struct vxlan_sock *sock6 = rtnl_dereference(vxlan->vn6_sock);
1477
1478                 sk = sock6->sock->sk;
1479                 lock_sock(sk);
1480                 ret = ipv6_stub->ipv6_sock_mc_drop(sk, ifindex,
1481                                                    &ip->sin6.sin6_addr);
1482                 release_sock(sk);
1483 #endif
1484         }
1485
1486         return ret;
1487 }
1488
1489 static bool vxlan_remcsum(struct vxlanhdr *unparsed,
1490                           struct sk_buff *skb, u32 vxflags)
1491 {
1492         size_t start, offset;
1493
1494         if (!(unparsed->vx_flags & VXLAN_HF_RCO) || skb->remcsum_offload)
1495                 goto out;
1496
1497         start = vxlan_rco_start(unparsed->vx_vni);
1498         offset = start + vxlan_rco_offset(unparsed->vx_vni);
1499
1500         if (!pskb_may_pull(skb, offset + sizeof(u16)))
1501                 return false;
1502
1503         skb_remcsum_process(skb, (void *)(vxlan_hdr(skb) + 1), start, offset,
1504                             !!(vxflags & VXLAN_F_REMCSUM_NOPARTIAL));
1505 out:
1506         unparsed->vx_flags &= ~VXLAN_HF_RCO;
1507         unparsed->vx_vni &= VXLAN_VNI_MASK;
1508         return true;
1509 }
1510
1511 static void vxlan_parse_gbp_hdr(struct vxlanhdr *unparsed,
1512                                 struct sk_buff *skb, u32 vxflags,
1513                                 struct vxlan_metadata *md)
1514 {
1515         struct vxlanhdr_gbp *gbp = (struct vxlanhdr_gbp *)unparsed;
1516         struct metadata_dst *tun_dst;
1517
1518         if (!(unparsed->vx_flags & VXLAN_HF_GBP))
1519                 goto out;
1520
1521         md->gbp = ntohs(gbp->policy_id);
1522
1523         tun_dst = (struct metadata_dst *)skb_dst(skb);
1524         if (tun_dst) {
1525                 tun_dst->u.tun_info.key.tun_flags |= TUNNEL_VXLAN_OPT;
1526                 tun_dst->u.tun_info.options_len = sizeof(*md);
1527         }
1528         if (gbp->dont_learn)
1529                 md->gbp |= VXLAN_GBP_DONT_LEARN;
1530
1531         if (gbp->policy_applied)
1532                 md->gbp |= VXLAN_GBP_POLICY_APPLIED;
1533
1534         /* In flow-based mode, GBP is carried in dst_metadata */
1535         if (!(vxflags & VXLAN_F_COLLECT_METADATA))
1536                 skb->mark = md->gbp;
1537 out:
1538         unparsed->vx_flags &= ~VXLAN_GBP_USED_BITS;
1539 }
1540
1541 static bool vxlan_parse_gpe_hdr(struct vxlanhdr *unparsed,
1542                                 __be16 *protocol,
1543                                 struct sk_buff *skb, u32 vxflags)
1544 {
1545         struct vxlanhdr_gpe *gpe = (struct vxlanhdr_gpe *)unparsed;
1546
1547         /* Need to have Next Protocol set for interfaces in GPE mode. */
1548         if (!gpe->np_applied)
1549                 return false;
1550         /* "The initial version is 0. If a receiver does not support the
1551          * version indicated it MUST drop the packet.
1552          */
1553         if (gpe->version != 0)
1554                 return false;
1555         /* "When the O bit is set to 1, the packet is an OAM packet and OAM
1556          * processing MUST occur." However, we don't implement OAM
1557          * processing, thus drop the packet.
1558          */
1559         if (gpe->oam_flag)
1560                 return false;
1561
1562         *protocol = tun_p_to_eth_p(gpe->next_protocol);
1563         if (!*protocol)
1564                 return false;
1565
1566         unparsed->vx_flags &= ~VXLAN_GPE_USED_BITS;
1567         return true;
1568 }
1569
1570 static bool vxlan_set_mac(struct vxlan_dev *vxlan,
1571                           struct vxlan_sock *vs,
1572                           struct sk_buff *skb, __be32 vni)
1573 {
1574         union vxlan_addr saddr;
1575         u32 ifindex = skb->dev->ifindex;
1576
1577         skb_reset_mac_header(skb);
1578         skb->protocol = eth_type_trans(skb, vxlan->dev);
1579         skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
1580
1581         /* Ignore packet loops (and multicast echo) */
1582         if (ether_addr_equal(eth_hdr(skb)->h_source, vxlan->dev->dev_addr))
1583                 return false;
1584
1585         /* Get address from the outer IP header */
1586         if (vxlan_get_sk_family(vs) == AF_INET) {
1587                 saddr.sin.sin_addr.s_addr = ip_hdr(skb)->saddr;
1588                 saddr.sa.sa_family = AF_INET;
1589 #if IS_ENABLED(CONFIG_IPV6)
1590         } else {
1591                 saddr.sin6.sin6_addr = ipv6_hdr(skb)->saddr;
1592                 saddr.sa.sa_family = AF_INET6;
1593 #endif
1594         }
1595
1596         if ((vxlan->cfg.flags & VXLAN_F_LEARN) &&
1597             vxlan_snoop(skb->dev, &saddr, eth_hdr(skb)->h_source, ifindex, vni))
1598                 return false;
1599
1600         return true;
1601 }
1602
1603 static bool vxlan_ecn_decapsulate(struct vxlan_sock *vs, void *oiph,
1604                                   struct sk_buff *skb)
1605 {
1606         int err = 0;
1607
1608         if (vxlan_get_sk_family(vs) == AF_INET)
1609                 err = IP_ECN_decapsulate(oiph, skb);
1610 #if IS_ENABLED(CONFIG_IPV6)
1611         else
1612                 err = IP6_ECN_decapsulate(oiph, skb);
1613 #endif
1614
1615         if (unlikely(err) && log_ecn_error) {
1616                 if (vxlan_get_sk_family(vs) == AF_INET)
1617                         net_info_ratelimited("non-ECT from %pI4 with TOS=%#x\n",
1618                                              &((struct iphdr *)oiph)->saddr,
1619                                              ((struct iphdr *)oiph)->tos);
1620                 else
1621                         net_info_ratelimited("non-ECT from %pI6\n",
1622                                              &((struct ipv6hdr *)oiph)->saddr);
1623         }
1624         return err <= 1;
1625 }
1626
1627 /* Callback from net/ipv4/udp.c to receive packets */
1628 static int vxlan_rcv(struct sock *sk, struct sk_buff *skb)
1629 {
1630         struct pcpu_sw_netstats *stats;
1631         struct vxlan_dev *vxlan;
1632         struct vxlan_sock *vs;
1633         struct vxlanhdr unparsed;
1634         struct vxlan_metadata _md;
1635         struct vxlan_metadata *md = &_md;
1636         __be16 protocol = htons(ETH_P_TEB);
1637         bool raw_proto = false;
1638         void *oiph;
1639         __be32 vni = 0;
1640
1641         /* Need UDP and VXLAN header to be present */
1642         if (!pskb_may_pull(skb, VXLAN_HLEN))
1643                 goto drop;
1644
1645         unparsed = *vxlan_hdr(skb);
1646         /* VNI flag always required to be set */
1647         if (!(unparsed.vx_flags & VXLAN_HF_VNI)) {
1648                 netdev_dbg(skb->dev, "invalid vxlan flags=%#x vni=%#x\n",
1649                            ntohl(vxlan_hdr(skb)->vx_flags),
1650                            ntohl(vxlan_hdr(skb)->vx_vni));
1651                 /* Return non vxlan pkt */
1652                 goto drop;
1653         }
1654         unparsed.vx_flags &= ~VXLAN_HF_VNI;
1655         unparsed.vx_vni &= ~VXLAN_VNI_MASK;
1656
1657         vs = rcu_dereference_sk_user_data(sk);
1658         if (!vs)
1659                 goto drop;
1660
1661         vni = vxlan_vni(vxlan_hdr(skb)->vx_vni);
1662
1663         vxlan = vxlan_vs_find_vni(vs, skb->dev->ifindex, vni);
1664         if (!vxlan)
1665                 goto drop;
1666
1667         /* For backwards compatibility, only allow reserved fields to be
1668          * used by VXLAN extensions if explicitly requested.
1669          */
1670         if (vs->flags & VXLAN_F_GPE) {
1671                 if (!vxlan_parse_gpe_hdr(&unparsed, &protocol, skb, vs->flags))
1672                         goto drop;
1673                 raw_proto = true;
1674         }
1675
1676         if (__iptunnel_pull_header(skb, VXLAN_HLEN, protocol, raw_proto,
1677                                    !net_eq(vxlan->net, dev_net(vxlan->dev))))
1678                         goto drop;
1679
1680         if (vxlan_collect_metadata(vs)) {
1681                 struct metadata_dst *tun_dst;
1682
1683                 tun_dst = udp_tun_rx_dst(skb, vxlan_get_sk_family(vs), TUNNEL_KEY,
1684                                          key32_to_tunnel_id(vni), sizeof(*md));
1685
1686                 if (!tun_dst)
1687                         goto drop;
1688
1689                 md = ip_tunnel_info_opts(&tun_dst->u.tun_info);
1690
1691                 skb_dst_set(skb, (struct dst_entry *)tun_dst);
1692         } else {
1693                 memset(md, 0, sizeof(*md));
1694         }
1695
1696         if (vs->flags & VXLAN_F_REMCSUM_RX)
1697                 if (!vxlan_remcsum(&unparsed, skb, vs->flags))
1698                         goto drop;
1699         if (vs->flags & VXLAN_F_GBP)
1700                 vxlan_parse_gbp_hdr(&unparsed, skb, vs->flags, md);
1701         /* Note that GBP and GPE can never be active together. This is
1702          * ensured in vxlan_dev_configure.
1703          */
1704
1705         if (unparsed.vx_flags || unparsed.vx_vni) {
1706                 /* If there are any unprocessed flags remaining treat
1707                  * this as a malformed packet. This behavior diverges from
1708                  * VXLAN RFC (RFC7348) which stipulates that bits in reserved
1709                  * in reserved fields are to be ignored. The approach here
1710                  * maintains compatibility with previous stack code, and also
1711                  * is more robust and provides a little more security in
1712                  * adding extensions to VXLAN.
1713                  */
1714                 goto drop;
1715         }
1716
1717         if (!raw_proto) {
1718                 if (!vxlan_set_mac(vxlan, vs, skb, vni))
1719                         goto drop;
1720         } else {
1721                 skb_reset_mac_header(skb);
1722                 skb->dev = vxlan->dev;
1723                 skb->pkt_type = PACKET_HOST;
1724         }
1725
1726         oiph = skb_network_header(skb);
1727         skb_reset_network_header(skb);
1728
1729         if (!vxlan_ecn_decapsulate(vs, oiph, skb)) {
1730                 ++vxlan->dev->stats.rx_frame_errors;
1731                 ++vxlan->dev->stats.rx_errors;
1732                 goto drop;
1733         }
1734
1735         rcu_read_lock();
1736
1737         if (unlikely(!(vxlan->dev->flags & IFF_UP))) {
1738                 rcu_read_unlock();
1739                 atomic_long_inc(&vxlan->dev->rx_dropped);
1740                 goto drop;
1741         }
1742
1743         stats = this_cpu_ptr(vxlan->dev->tstats);
1744         u64_stats_update_begin(&stats->syncp);
1745         stats->rx_packets++;
1746         stats->rx_bytes += skb->len;
1747         u64_stats_update_end(&stats->syncp);
1748
1749         gro_cells_receive(&vxlan->gro_cells, skb);
1750
1751         rcu_read_unlock();
1752
1753         return 0;
1754
1755 drop:
1756         /* Consume bad packet */
1757         kfree_skb(skb);
1758         return 0;
1759 }
1760
1761 /* Callback from net/ipv{4,6}/udp.c to check that we have a VNI for errors */
1762 static int vxlan_err_lookup(struct sock *sk, struct sk_buff *skb)
1763 {
1764         struct vxlan_dev *vxlan;
1765         struct vxlan_sock *vs;
1766         struct vxlanhdr *hdr;
1767         __be32 vni;
1768
1769         if (skb->len < VXLAN_HLEN)
1770                 return -EINVAL;
1771
1772         hdr = vxlan_hdr(skb);
1773
1774         if (!(hdr->vx_flags & VXLAN_HF_VNI))
1775                 return -EINVAL;
1776
1777         vs = rcu_dereference_sk_user_data(sk);
1778         if (!vs)
1779                 return -ENOENT;
1780
1781         vni = vxlan_vni(hdr->vx_vni);
1782         vxlan = vxlan_vs_find_vni(vs, skb->dev->ifindex, vni);
1783         if (!vxlan)
1784                 return -ENOENT;
1785
1786         return 0;
1787 }
1788
1789 static int arp_reduce(struct net_device *dev, struct sk_buff *skb, __be32 vni)
1790 {
1791         struct vxlan_dev *vxlan = netdev_priv(dev);
1792         struct arphdr *parp;
1793         u8 *arpptr, *sha;
1794         __be32 sip, tip;
1795         struct neighbour *n;
1796
1797         if (dev->flags & IFF_NOARP)
1798                 goto out;
1799
1800         if (!pskb_may_pull(skb, arp_hdr_len(dev))) {
1801                 dev->stats.tx_dropped++;
1802                 goto out;
1803         }
1804         parp = arp_hdr(skb);
1805
1806         if ((parp->ar_hrd != htons(ARPHRD_ETHER) &&
1807              parp->ar_hrd != htons(ARPHRD_IEEE802)) ||
1808             parp->ar_pro != htons(ETH_P_IP) ||
1809             parp->ar_op != htons(ARPOP_REQUEST) ||
1810             parp->ar_hln != dev->addr_len ||
1811             parp->ar_pln != 4)
1812                 goto out;
1813         arpptr = (u8 *)parp + sizeof(struct arphdr);
1814         sha = arpptr;
1815         arpptr += dev->addr_len;        /* sha */
1816         memcpy(&sip, arpptr, sizeof(sip));
1817         arpptr += sizeof(sip);
1818         arpptr += dev->addr_len;        /* tha */
1819         memcpy(&tip, arpptr, sizeof(tip));
1820
1821         if (ipv4_is_loopback(tip) ||
1822             ipv4_is_multicast(tip))
1823                 goto out;
1824
1825         n = neigh_lookup(&arp_tbl, &tip, dev);
1826
1827         if (n) {
1828                 struct vxlan_fdb *f;
1829                 struct sk_buff  *reply;
1830
1831                 if (!(n->nud_state & NUD_CONNECTED)) {
1832                         neigh_release(n);
1833                         goto out;
1834                 }
1835
1836                 f = vxlan_find_mac(vxlan, n->ha, vni);
1837                 if (f && vxlan_addr_any(&(first_remote_rcu(f)->remote_ip))) {
1838                         /* bridge-local neighbor */
1839                         neigh_release(n);
1840                         goto out;
1841                 }
1842
1843                 reply = arp_create(ARPOP_REPLY, ETH_P_ARP, sip, dev, tip, sha,
1844                                 n->ha, sha);
1845
1846                 neigh_release(n);
1847
1848                 if (reply == NULL)
1849                         goto out;
1850
1851                 skb_reset_mac_header(reply);
1852                 __skb_pull(reply, skb_network_offset(reply));
1853                 reply->ip_summed = CHECKSUM_UNNECESSARY;
1854                 reply->pkt_type = PACKET_HOST;
1855
1856                 if (netif_rx_ni(reply) == NET_RX_DROP)
1857                         dev->stats.rx_dropped++;
1858         } else if (vxlan->cfg.flags & VXLAN_F_L3MISS) {
1859                 union vxlan_addr ipa = {
1860                         .sin.sin_addr.s_addr = tip,
1861                         .sin.sin_family = AF_INET,
1862                 };
1863
1864                 vxlan_ip_miss(dev, &ipa);
1865         }
1866 out:
1867         consume_skb(skb);
1868         return NETDEV_TX_OK;
1869 }
1870
1871 #if IS_ENABLED(CONFIG_IPV6)
1872 static struct sk_buff *vxlan_na_create(struct sk_buff *request,
1873         struct neighbour *n, bool isrouter)
1874 {
1875         struct net_device *dev = request->dev;
1876         struct sk_buff *reply;
1877         struct nd_msg *ns, *na;
1878         struct ipv6hdr *pip6;
1879         u8 *daddr;
1880         int na_olen = 8; /* opt hdr + ETH_ALEN for target */
1881         int ns_olen;
1882         int i, len;
1883
1884         if (dev == NULL || !pskb_may_pull(request, request->len))
1885                 return NULL;
1886
1887         len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) +
1888                 sizeof(*na) + na_olen + dev->needed_tailroom;
1889         reply = alloc_skb(len, GFP_ATOMIC);
1890         if (reply == NULL)
1891                 return NULL;
1892
1893         reply->protocol = htons(ETH_P_IPV6);
1894         reply->dev = dev;
1895         skb_reserve(reply, LL_RESERVED_SPACE(request->dev));
1896         skb_push(reply, sizeof(struct ethhdr));
1897         skb_reset_mac_header(reply);
1898
1899         ns = (struct nd_msg *)(ipv6_hdr(request) + 1);
1900
1901         daddr = eth_hdr(request)->h_source;
1902         ns_olen = request->len - skb_network_offset(request) -
1903                 sizeof(struct ipv6hdr) - sizeof(*ns);
1904         for (i = 0; i < ns_olen-1; i += (ns->opt[i+1]<<3)) {
1905                 if (ns->opt[i] == ND_OPT_SOURCE_LL_ADDR) {
1906                         daddr = ns->opt + i + sizeof(struct nd_opt_hdr);
1907                         break;
1908                 }
1909         }
1910
1911         /* Ethernet header */
1912         ether_addr_copy(eth_hdr(reply)->h_dest, daddr);
1913         ether_addr_copy(eth_hdr(reply)->h_source, n->ha);
1914         eth_hdr(reply)->h_proto = htons(ETH_P_IPV6);
1915         reply->protocol = htons(ETH_P_IPV6);
1916
1917         skb_pull(reply, sizeof(struct ethhdr));
1918         skb_reset_network_header(reply);
1919         skb_put(reply, sizeof(struct ipv6hdr));
1920
1921         /* IPv6 header */
1922
1923         pip6 = ipv6_hdr(reply);
1924         memset(pip6, 0, sizeof(struct ipv6hdr));
1925         pip6->version = 6;
1926         pip6->priority = ipv6_hdr(request)->priority;
1927         pip6->nexthdr = IPPROTO_ICMPV6;
1928         pip6->hop_limit = 255;
1929         pip6->daddr = ipv6_hdr(request)->saddr;
1930         pip6->saddr = *(struct in6_addr *)n->primary_key;
1931
1932         skb_pull(reply, sizeof(struct ipv6hdr));
1933         skb_reset_transport_header(reply);
1934
1935         /* Neighbor Advertisement */
1936         na = skb_put_zero(reply, sizeof(*na) + na_olen);
1937         na->icmph.icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT;
1938         na->icmph.icmp6_router = isrouter;
1939         na->icmph.icmp6_override = 1;
1940         na->icmph.icmp6_solicited = 1;
1941         na->target = ns->target;
1942         ether_addr_copy(&na->opt[2], n->ha);
1943         na->opt[0] = ND_OPT_TARGET_LL_ADDR;
1944         na->opt[1] = na_olen >> 3;
1945
1946         na->icmph.icmp6_cksum = csum_ipv6_magic(&pip6->saddr,
1947                 &pip6->daddr, sizeof(*na)+na_olen, IPPROTO_ICMPV6,
1948                 csum_partial(na, sizeof(*na)+na_olen, 0));
1949
1950         pip6->payload_len = htons(sizeof(*na)+na_olen);
1951
1952         skb_push(reply, sizeof(struct ipv6hdr));
1953
1954         reply->ip_summed = CHECKSUM_UNNECESSARY;
1955
1956         return reply;
1957 }
1958
1959 static int neigh_reduce(struct net_device *dev, struct sk_buff *skb, __be32 vni)
1960 {
1961         struct vxlan_dev *vxlan = netdev_priv(dev);
1962         const struct in6_addr *daddr;
1963         const struct ipv6hdr *iphdr;
1964         struct inet6_dev *in6_dev;
1965         struct neighbour *n;
1966         struct nd_msg *msg;
1967
1968         in6_dev = __in6_dev_get(dev);
1969         if (!in6_dev)
1970                 goto out;
1971
1972         iphdr = ipv6_hdr(skb);
1973         daddr = &iphdr->daddr;
1974         msg = (struct nd_msg *)(iphdr + 1);
1975
1976         if (ipv6_addr_loopback(daddr) ||
1977             ipv6_addr_is_multicast(&msg->target))
1978                 goto out;
1979
1980         n = neigh_lookup(ipv6_stub->nd_tbl, &msg->target, dev);
1981
1982         if (n) {
1983                 struct vxlan_fdb *f;
1984                 struct sk_buff *reply;
1985
1986                 if (!(n->nud_state & NUD_CONNECTED)) {
1987                         neigh_release(n);
1988                         goto out;
1989                 }
1990
1991                 f = vxlan_find_mac(vxlan, n->ha, vni);
1992                 if (f && vxlan_addr_any(&(first_remote_rcu(f)->remote_ip))) {
1993                         /* bridge-local neighbor */
1994                         neigh_release(n);
1995                         goto out;
1996                 }
1997
1998                 reply = vxlan_na_create(skb, n,
1999                                         !!(f ? f->flags & NTF_ROUTER : 0));
2000
2001                 neigh_release(n);
2002
2003                 if (reply == NULL)
2004                         goto out;
2005
2006                 if (netif_rx_ni(reply) == NET_RX_DROP)
2007                         dev->stats.rx_dropped++;
2008
2009         } else if (vxlan->cfg.flags & VXLAN_F_L3MISS) {
2010                 union vxlan_addr ipa = {
2011                         .sin6.sin6_addr = msg->target,
2012                         .sin6.sin6_family = AF_INET6,
2013                 };
2014
2015                 vxlan_ip_miss(dev, &ipa);
2016         }
2017
2018 out:
2019         consume_skb(skb);
2020         return NETDEV_TX_OK;
2021 }
2022 #endif
2023
2024 static bool route_shortcircuit(struct net_device *dev, struct sk_buff *skb)
2025 {
2026         struct vxlan_dev *vxlan = netdev_priv(dev);
2027         struct neighbour *n;
2028
2029         if (is_multicast_ether_addr(eth_hdr(skb)->h_dest))
2030                 return false;
2031
2032         n = NULL;
2033         switch (ntohs(eth_hdr(skb)->h_proto)) {
2034         case ETH_P_IP:
2035         {
2036                 struct iphdr *pip;
2037
2038                 if (!pskb_may_pull(skb, sizeof(struct iphdr)))
2039                         return false;
2040                 pip = ip_hdr(skb);
2041                 n = neigh_lookup(&arp_tbl, &pip->daddr, dev);
2042                 if (!n && (vxlan->cfg.flags & VXLAN_F_L3MISS)) {
2043                         union vxlan_addr ipa = {
2044                                 .sin.sin_addr.s_addr = pip->daddr,
2045                                 .sin.sin_family = AF_INET,
2046                         };
2047
2048                         vxlan_ip_miss(dev, &ipa);
2049                         return false;
2050                 }
2051
2052                 break;
2053         }
2054 #if IS_ENABLED(CONFIG_IPV6)
2055         case ETH_P_IPV6:
2056         {
2057                 struct ipv6hdr *pip6;
2058
2059                 if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
2060                         return false;
2061                 pip6 = ipv6_hdr(skb);
2062                 n = neigh_lookup(ipv6_stub->nd_tbl, &pip6->daddr, dev);
2063                 if (!n && (vxlan->cfg.flags & VXLAN_F_L3MISS)) {
2064                         union vxlan_addr ipa = {
2065                                 .sin6.sin6_addr = pip6->daddr,
2066                                 .sin6.sin6_family = AF_INET6,
2067                         };
2068
2069                         vxlan_ip_miss(dev, &ipa);
2070                         return false;
2071                 }
2072
2073                 break;
2074         }
2075 #endif
2076         default:
2077                 return false;
2078         }
2079
2080         if (n) {
2081                 bool diff;
2082
2083                 diff = !ether_addr_equal(eth_hdr(skb)->h_dest, n->ha);
2084                 if (diff) {
2085                         memcpy(eth_hdr(skb)->h_source, eth_hdr(skb)->h_dest,
2086                                 dev->addr_len);
2087                         memcpy(eth_hdr(skb)->h_dest, n->ha, dev->addr_len);
2088                 }
2089                 neigh_release(n);
2090                 return diff;
2091         }
2092
2093         return false;
2094 }
2095
2096 static void vxlan_build_gbp_hdr(struct vxlanhdr *vxh, u32 vxflags,
2097                                 struct vxlan_metadata *md)
2098 {
2099         struct vxlanhdr_gbp *gbp;
2100
2101         if (!md->gbp)
2102                 return;
2103
2104         gbp = (struct vxlanhdr_gbp *)vxh;
2105         vxh->vx_flags |= VXLAN_HF_GBP;
2106
2107         if (md->gbp & VXLAN_GBP_DONT_LEARN)
2108                 gbp->dont_learn = 1;
2109
2110         if (md->gbp & VXLAN_GBP_POLICY_APPLIED)
2111                 gbp->policy_applied = 1;
2112
2113         gbp->policy_id = htons(md->gbp & VXLAN_GBP_ID_MASK);
2114 }
2115
2116 static int vxlan_build_gpe_hdr(struct vxlanhdr *vxh, u32 vxflags,
2117                                __be16 protocol)
2118 {
2119         struct vxlanhdr_gpe *gpe = (struct vxlanhdr_gpe *)vxh;
2120
2121         gpe->np_applied = 1;
2122         gpe->next_protocol = tun_p_from_eth_p(protocol);
2123         if (!gpe->next_protocol)
2124                 return -EPFNOSUPPORT;
2125         return 0;
2126 }
2127
2128 static int vxlan_build_skb(struct sk_buff *skb, struct dst_entry *dst,
2129                            int iphdr_len, __be32 vni,
2130                            struct vxlan_metadata *md, u32 vxflags,
2131                            bool udp_sum)
2132 {
2133         struct vxlanhdr *vxh;
2134         int min_headroom;
2135         int err;
2136         int type = udp_sum ? SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL;
2137         __be16 inner_protocol = htons(ETH_P_TEB);
2138
2139         if ((vxflags & VXLAN_F_REMCSUM_TX) &&
2140             skb->ip_summed == CHECKSUM_PARTIAL) {
2141                 int csum_start = skb_checksum_start_offset(skb);
2142
2143                 if (csum_start <= VXLAN_MAX_REMCSUM_START &&
2144                     !(csum_start & VXLAN_RCO_SHIFT_MASK) &&
2145                     (skb->csum_offset == offsetof(struct udphdr, check) ||
2146                      skb->csum_offset == offsetof(struct tcphdr, check)))
2147                         type |= SKB_GSO_TUNNEL_REMCSUM;
2148         }
2149
2150         min_headroom = LL_RESERVED_SPACE(dst->dev) + dst->header_len
2151                         + VXLAN_HLEN + iphdr_len;
2152
2153         /* Need space for new headers (invalidates iph ptr) */
2154         err = skb_cow_head(skb, min_headroom);
2155         if (unlikely(err))
2156                 return err;
2157
2158         err = iptunnel_handle_offloads(skb, type);
2159         if (err)
2160                 return err;
2161
2162         vxh = __skb_push(skb, sizeof(*vxh));
2163         vxh->vx_flags = VXLAN_HF_VNI;
2164         vxh->vx_vni = vxlan_vni_field(vni);
2165
2166         if (type & SKB_GSO_TUNNEL_REMCSUM) {
2167                 unsigned int start;
2168
2169                 start = skb_checksum_start_offset(skb) - sizeof(struct vxlanhdr);
2170                 vxh->vx_vni |= vxlan_compute_rco(start, skb->csum_offset);
2171                 vxh->vx_flags |= VXLAN_HF_RCO;
2172
2173                 if (!skb_is_gso(skb)) {
2174                         skb->ip_summed = CHECKSUM_NONE;
2175                         skb->encapsulation = 0;
2176                 }
2177         }
2178
2179         if (vxflags & VXLAN_F_GBP)
2180                 vxlan_build_gbp_hdr(vxh, vxflags, md);
2181         if (vxflags & VXLAN_F_GPE) {
2182                 err = vxlan_build_gpe_hdr(vxh, vxflags, skb->protocol);
2183                 if (err < 0)
2184                         return err;
2185                 inner_protocol = skb->protocol;
2186         }
2187
2188         skb_set_inner_protocol(skb, inner_protocol);
2189         return 0;
2190 }
2191
2192 static struct rtable *vxlan_get_route(struct vxlan_dev *vxlan, struct net_device *dev,
2193                                       struct vxlan_sock *sock4,
2194                                       struct sk_buff *skb, int oif, u8 tos,
2195                                       __be32 daddr, __be32 *saddr, __be16 dport, __be16 sport,
2196                                       struct dst_cache *dst_cache,
2197                                       const struct ip_tunnel_info *info)
2198 {
2199         bool use_cache = ip_tunnel_dst_cache_usable(skb, info);
2200         struct rtable *rt = NULL;
2201         struct flowi4 fl4;
2202
2203         if (!sock4)
2204                 return ERR_PTR(-EIO);
2205
2206         if (tos && !info)
2207                 use_cache = false;
2208         if (use_cache) {
2209                 rt = dst_cache_get_ip4(dst_cache, saddr);
2210                 if (rt)
2211                         return rt;
2212         }
2213
2214         memset(&fl4, 0, sizeof(fl4));
2215         fl4.flowi4_oif = oif;
2216         fl4.flowi4_tos = RT_TOS(tos);
2217         fl4.flowi4_mark = skb->mark;
2218         fl4.flowi4_proto = IPPROTO_UDP;
2219         fl4.daddr = daddr;
2220         fl4.saddr = *saddr;
2221         fl4.fl4_dport = dport;
2222         fl4.fl4_sport = sport;
2223
2224         rt = ip_route_output_key(vxlan->net, &fl4);
2225         if (likely(!IS_ERR(rt))) {
2226                 if (rt->dst.dev == dev) {
2227                         netdev_dbg(dev, "circular route to %pI4\n", &daddr);
2228                         ip_rt_put(rt);
2229                         return ERR_PTR(-ELOOP);
2230                 }
2231
2232                 *saddr = fl4.saddr;
2233                 if (use_cache)
2234                         dst_cache_set_ip4(dst_cache, &rt->dst, fl4.saddr);
2235         } else {
2236                 netdev_dbg(dev, "no route to %pI4\n", &daddr);
2237                 return ERR_PTR(-ENETUNREACH);
2238         }
2239         return rt;
2240 }
2241
2242 #if IS_ENABLED(CONFIG_IPV6)
2243 static struct dst_entry *vxlan6_get_route(struct vxlan_dev *vxlan,
2244                                           struct net_device *dev,
2245                                           struct vxlan_sock *sock6,
2246                                           struct sk_buff *skb, int oif, u8 tos,
2247                                           __be32 label,
2248                                           const struct in6_addr *daddr,
2249                                           struct in6_addr *saddr,
2250                                           __be16 dport, __be16 sport,
2251                                           struct dst_cache *dst_cache,
2252                                           const struct ip_tunnel_info *info)
2253 {
2254         bool use_cache = ip_tunnel_dst_cache_usable(skb, info);
2255         struct dst_entry *ndst;
2256         struct flowi6 fl6;
2257         int err;
2258
2259         if (!sock6)
2260                 return ERR_PTR(-EIO);
2261
2262         if (tos && !info)
2263                 use_cache = false;
2264         if (use_cache) {
2265                 ndst = dst_cache_get_ip6(dst_cache, saddr);
2266                 if (ndst)
2267                         return ndst;
2268         }
2269
2270         memset(&fl6, 0, sizeof(fl6));
2271         fl6.flowi6_oif = oif;
2272         fl6.daddr = *daddr;
2273         fl6.saddr = *saddr;
2274         fl6.flowlabel = ip6_make_flowinfo(RT_TOS(tos), label);
2275         fl6.flowi6_mark = skb->mark;
2276         fl6.flowi6_proto = IPPROTO_UDP;
2277         fl6.fl6_dport = dport;
2278         fl6.fl6_sport = sport;
2279
2280         err = ipv6_stub->ipv6_dst_lookup(vxlan->net,
2281                                          sock6->sock->sk,
2282                                          &ndst, &fl6);
2283         if (unlikely(err < 0)) {
2284                 netdev_dbg(dev, "no route to %pI6\n", daddr);
2285                 return ERR_PTR(-ENETUNREACH);
2286         }
2287
2288         if (unlikely(ndst->dev == dev)) {
2289                 netdev_dbg(dev, "circular route to %pI6\n", daddr);
2290                 dst_release(ndst);
2291                 return ERR_PTR(-ELOOP);
2292         }
2293
2294         *saddr = fl6.saddr;
2295         if (use_cache)
2296                 dst_cache_set_ip6(dst_cache, ndst, saddr);
2297         return ndst;
2298 }
2299 #endif
2300
2301 /* Bypass encapsulation if the destination is local */
2302 static void vxlan_encap_bypass(struct sk_buff *skb, struct vxlan_dev *src_vxlan,
2303                                struct vxlan_dev *dst_vxlan, __be32 vni)
2304 {
2305         struct pcpu_sw_netstats *tx_stats, *rx_stats;
2306         union vxlan_addr loopback;
2307         union vxlan_addr *remote_ip = &dst_vxlan->default_dst.remote_ip;
2308         struct net_device *dev;
2309         int len = skb->len;
2310
2311         tx_stats = this_cpu_ptr(src_vxlan->dev->tstats);
2312         rx_stats = this_cpu_ptr(dst_vxlan->dev->tstats);
2313         skb->pkt_type = PACKET_HOST;
2314         skb->encapsulation = 0;
2315         skb->dev = dst_vxlan->dev;
2316         __skb_pull(skb, skb_network_offset(skb));
2317
2318         if (remote_ip->sa.sa_family == AF_INET) {
2319                 loopback.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2320                 loopback.sa.sa_family =  AF_INET;
2321 #if IS_ENABLED(CONFIG_IPV6)
2322         } else {
2323                 loopback.sin6.sin6_addr = in6addr_loopback;
2324                 loopback.sa.sa_family =  AF_INET6;
2325 #endif
2326         }
2327
2328         rcu_read_lock();
2329         dev = skb->dev;
2330         if (unlikely(!(dev->flags & IFF_UP))) {
2331                 kfree_skb(skb);
2332                 goto drop;
2333         }
2334
2335         if (dst_vxlan->cfg.flags & VXLAN_F_LEARN)
2336                 vxlan_snoop(dev, &loopback, eth_hdr(skb)->h_source, 0, vni);
2337
2338         u64_stats_update_begin(&tx_stats->syncp);
2339         tx_stats->tx_packets++;
2340         tx_stats->tx_bytes += len;
2341         u64_stats_update_end(&tx_stats->syncp);
2342
2343         if (netif_rx(skb) == NET_RX_SUCCESS) {
2344                 u64_stats_update_begin(&rx_stats->syncp);
2345                 rx_stats->rx_packets++;
2346                 rx_stats->rx_bytes += len;
2347                 u64_stats_update_end(&rx_stats->syncp);
2348         } else {
2349 drop:
2350                 dev->stats.rx_dropped++;
2351         }
2352         rcu_read_unlock();
2353 }
2354
2355 static int encap_bypass_if_local(struct sk_buff *skb, struct net_device *dev,
2356                                  struct vxlan_dev *vxlan,
2357                                  union vxlan_addr *daddr,
2358                                  __be16 dst_port, int dst_ifindex, __be32 vni,
2359                                  struct dst_entry *dst,
2360                                  u32 rt_flags)
2361 {
2362 #if IS_ENABLED(CONFIG_IPV6)
2363         /* IPv6 rt-flags are checked against RTF_LOCAL, but the value of
2364          * RTF_LOCAL is equal to RTCF_LOCAL. So to keep code simple
2365          * we can use RTCF_LOCAL which works for ipv4 and ipv6 route entry.
2366          */
2367         BUILD_BUG_ON(RTCF_LOCAL != RTF_LOCAL);
2368 #endif
2369         /* Bypass encapsulation if the destination is local */
2370         if (rt_flags & RTCF_LOCAL &&
2371             !(rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))) {
2372                 struct vxlan_dev *dst_vxlan;
2373
2374                 dst_release(dst);
2375                 dst_vxlan = vxlan_find_vni(vxlan->net, dst_ifindex, vni,
2376                                            daddr->sa.sa_family, dst_port,
2377                                            vxlan->cfg.flags);
2378                 if (!dst_vxlan) {
2379                         dev->stats.tx_errors++;
2380                         kfree_skb(skb);
2381
2382                         return -ENOENT;
2383                 }
2384                 vxlan_encap_bypass(skb, vxlan, dst_vxlan, vni);
2385                 return 1;
2386         }
2387
2388         return 0;
2389 }
2390
2391 static void vxlan_xmit_one(struct sk_buff *skb, struct net_device *dev,
2392                            __be32 default_vni, struct vxlan_rdst *rdst,
2393                            bool did_rsc)
2394 {
2395         struct dst_cache *dst_cache;
2396         struct ip_tunnel_info *info;
2397         struct vxlan_dev *vxlan = netdev_priv(dev);
2398         const struct iphdr *old_iph = ip_hdr(skb);
2399         union vxlan_addr *dst;
2400         union vxlan_addr remote_ip, local_ip;
2401         struct vxlan_metadata _md;
2402         struct vxlan_metadata *md = &_md;
2403         __be16 src_port = 0, dst_port;
2404         struct dst_entry *ndst = NULL;
2405         __be32 vni, label;
2406         __u8 tos, ttl;
2407         int ifindex;
2408         int err;
2409         u32 flags = vxlan->cfg.flags;
2410         bool udp_sum = false;
2411         bool xnet = !net_eq(vxlan->net, dev_net(vxlan->dev));
2412
2413         info = skb_tunnel_info(skb);
2414
2415         if (rdst) {
2416                 dst = &rdst->remote_ip;
2417                 if (vxlan_addr_any(dst)) {
2418                         if (did_rsc) {
2419                                 /* short-circuited back to local bridge */
2420                                 vxlan_encap_bypass(skb, vxlan, vxlan, default_vni);
2421                                 return;
2422                         }
2423                         goto drop;
2424                 }
2425
2426                 dst_port = rdst->remote_port ? rdst->remote_port : vxlan->cfg.dst_port;
2427                 vni = (rdst->remote_vni) ? : default_vni;
2428                 ifindex = rdst->remote_ifindex;
2429                 local_ip = vxlan->cfg.saddr;
2430                 dst_cache = &rdst->dst_cache;
2431                 md->gbp = skb->mark;
2432                 if (flags & VXLAN_F_TTL_INHERIT) {
2433                         ttl = ip_tunnel_get_ttl(old_iph, skb);
2434                 } else {
2435                         ttl = vxlan->cfg.ttl;
2436                         if (!ttl && vxlan_addr_multicast(dst))
2437                                 ttl = 1;
2438                 }
2439
2440                 tos = vxlan->cfg.tos;
2441                 if (tos == 1)
2442                         tos = ip_tunnel_get_dsfield(old_iph, skb);
2443
2444                 if (dst->sa.sa_family == AF_INET)
2445                         udp_sum = !(flags & VXLAN_F_UDP_ZERO_CSUM_TX);
2446                 else
2447                         udp_sum = !(flags & VXLAN_F_UDP_ZERO_CSUM6_TX);
2448                 label = vxlan->cfg.label;
2449         } else {
2450                 if (!info) {
2451                         WARN_ONCE(1, "%s: Missing encapsulation instructions\n",
2452                                   dev->name);
2453                         goto drop;
2454                 }
2455                 remote_ip.sa.sa_family = ip_tunnel_info_af(info);
2456                 if (remote_ip.sa.sa_family == AF_INET) {
2457                         remote_ip.sin.sin_addr.s_addr = info->key.u.ipv4.dst;
2458                         local_ip.sin.sin_addr.s_addr = info->key.u.ipv4.src;
2459                 } else {
2460                         remote_ip.sin6.sin6_addr = info->key.u.ipv6.dst;
2461                         local_ip.sin6.sin6_addr = info->key.u.ipv6.src;
2462                 }
2463                 dst = &remote_ip;
2464                 dst_port = info->key.tp_dst ? : vxlan->cfg.dst_port;
2465                 vni = tunnel_id_to_key32(info->key.tun_id);
2466                 ifindex = 0;
2467                 dst_cache = &info->dst_cache;
2468                 if (info->options_len &&
2469                     info->key.tun_flags & TUNNEL_VXLAN_OPT)
2470                         md = ip_tunnel_info_opts(info);
2471                 ttl = info->key.ttl;
2472                 tos = info->key.tos;
2473                 label = info->key.label;
2474                 udp_sum = !!(info->key.tun_flags & TUNNEL_CSUM);
2475         }
2476         src_port = udp_flow_src_port(dev_net(dev), skb, vxlan->cfg.port_min,
2477                                      vxlan->cfg.port_max, true);
2478
2479         rcu_read_lock();
2480         if (dst->sa.sa_family == AF_INET) {
2481                 struct vxlan_sock *sock4 = rcu_dereference(vxlan->vn4_sock);
2482                 struct rtable *rt;
2483                 __be16 df = 0;
2484
2485                 if (!ifindex)
2486                         ifindex = sock4->sock->sk->sk_bound_dev_if;
2487
2488                 rt = vxlan_get_route(vxlan, dev, sock4, skb, ifindex, tos,
2489                                      dst->sin.sin_addr.s_addr,
2490                                      &local_ip.sin.sin_addr.s_addr,
2491                                      dst_port, src_port,
2492                                      dst_cache, info);
2493                 if (IS_ERR(rt)) {
2494                         err = PTR_ERR(rt);
2495                         goto tx_error;
2496                 }
2497
2498                 if (!info) {
2499                         /* Bypass encapsulation if the destination is local */
2500                         err = encap_bypass_if_local(skb, dev, vxlan, dst,
2501                                                     dst_port, ifindex, vni,
2502                                                     &rt->dst, rt->rt_flags);
2503                         if (err)
2504                                 goto out_unlock;
2505
2506                         if (vxlan->cfg.df == VXLAN_DF_SET) {
2507                                 df = htons(IP_DF);
2508                         } else if (vxlan->cfg.df == VXLAN_DF_INHERIT) {
2509                                 struct ethhdr *eth = eth_hdr(skb);
2510
2511                                 if (ntohs(eth->h_proto) == ETH_P_IPV6 ||
2512                                     (ntohs(eth->h_proto) == ETH_P_IP &&
2513                                      old_iph->frag_off & htons(IP_DF)))
2514                                         df = htons(IP_DF);
2515                         }
2516                 } else if (info->key.tun_flags & TUNNEL_DONT_FRAGMENT) {
2517                         df = htons(IP_DF);
2518                 }
2519
2520                 ndst = &rt->dst;
2521                 skb_tunnel_check_pmtu(skb, ndst, VXLAN_HEADROOM);
2522
2523                 tos = ip_tunnel_ecn_encap(tos, old_iph, skb);
2524                 ttl = ttl ? : ip4_dst_hoplimit(&rt->dst);
2525                 err = vxlan_build_skb(skb, ndst, sizeof(struct iphdr),
2526                                       vni, md, flags, udp_sum);
2527                 if (err < 0)
2528                         goto tx_error;
2529
2530                 udp_tunnel_xmit_skb(rt, sock4->sock->sk, skb, local_ip.sin.sin_addr.s_addr,
2531                                     dst->sin.sin_addr.s_addr, tos, ttl, df,
2532                                     src_port, dst_port, xnet, !udp_sum);
2533 #if IS_ENABLED(CONFIG_IPV6)
2534         } else {
2535                 struct vxlan_sock *sock6 = rcu_dereference(vxlan->vn6_sock);
2536
2537                 if (!ifindex)
2538                         ifindex = sock6->sock->sk->sk_bound_dev_if;
2539
2540                 ndst = vxlan6_get_route(vxlan, dev, sock6, skb, ifindex, tos,
2541                                         label, &dst->sin6.sin6_addr,
2542                                         &local_ip.sin6.sin6_addr,
2543                                         dst_port, src_port,
2544                                         dst_cache, info);
2545                 if (IS_ERR(ndst)) {
2546                         err = PTR_ERR(ndst);
2547                         ndst = NULL;
2548                         goto tx_error;
2549                 }
2550
2551                 if (!info) {
2552                         u32 rt6i_flags = ((struct rt6_info *)ndst)->rt6i_flags;
2553
2554                         err = encap_bypass_if_local(skb, dev, vxlan, dst,
2555                                                     dst_port, ifindex, vni,
2556                                                     ndst, rt6i_flags);
2557                         if (err)
2558                                 goto out_unlock;
2559                 }
2560
2561                 skb_tunnel_check_pmtu(skb, ndst, VXLAN6_HEADROOM);
2562
2563                 tos = ip_tunnel_ecn_encap(tos, old_iph, skb);
2564                 ttl = ttl ? : ip6_dst_hoplimit(ndst);
2565                 skb_scrub_packet(skb, xnet);
2566                 err = vxlan_build_skb(skb, ndst, sizeof(struct ipv6hdr),
2567                                       vni, md, flags, udp_sum);
2568                 if (err < 0)
2569                         goto tx_error;
2570
2571                 udp_tunnel6_xmit_skb(ndst, sock6->sock->sk, skb, dev,
2572                                      &local_ip.sin6.sin6_addr,
2573                                      &dst->sin6.sin6_addr, tos, ttl,
2574                                      label, src_port, dst_port, !udp_sum);
2575 #endif
2576         }
2577 out_unlock:
2578         rcu_read_unlock();
2579         return;
2580
2581 drop:
2582         dev->stats.tx_dropped++;
2583         dev_kfree_skb(skb);
2584         return;
2585
2586 tx_error:
2587         rcu_read_unlock();
2588         if (err == -ELOOP)
2589                 dev->stats.collisions++;
2590         else if (err == -ENETUNREACH)
2591                 dev->stats.tx_carrier_errors++;
2592         dst_release(ndst);
2593         dev->stats.tx_errors++;
2594         kfree_skb(skb);
2595 }
2596
2597 /* Transmit local packets over Vxlan
2598  *
2599  * Outer IP header inherits ECN and DF from inner header.
2600  * Outer UDP destination is the VXLAN assigned port.
2601  *           source port is based on hash of flow
2602  */
2603 static netdev_tx_t vxlan_xmit(struct sk_buff *skb, struct net_device *dev)
2604 {
2605         struct vxlan_dev *vxlan = netdev_priv(dev);
2606         struct vxlan_rdst *rdst, *fdst = NULL;
2607         const struct ip_tunnel_info *info;
2608         bool did_rsc = false;
2609         struct vxlan_fdb *f;
2610         struct ethhdr *eth;
2611         __be32 vni = 0;
2612
2613         info = skb_tunnel_info(skb);
2614
2615         skb_reset_mac_header(skb);
2616
2617         if (vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA) {
2618                 if (info && info->mode & IP_TUNNEL_INFO_BRIDGE &&
2619                     info->mode & IP_TUNNEL_INFO_TX) {
2620                         vni = tunnel_id_to_key32(info->key.tun_id);
2621                 } else {
2622                         if (info && info->mode & IP_TUNNEL_INFO_TX)
2623                                 vxlan_xmit_one(skb, dev, vni, NULL, false);
2624                         else
2625                                 kfree_skb(skb);
2626                         return NETDEV_TX_OK;
2627                 }
2628         }
2629
2630         if (vxlan->cfg.flags & VXLAN_F_PROXY) {
2631                 eth = eth_hdr(skb);
2632                 if (ntohs(eth->h_proto) == ETH_P_ARP)
2633                         return arp_reduce(dev, skb, vni);
2634 #if IS_ENABLED(CONFIG_IPV6)
2635                 else if (ntohs(eth->h_proto) == ETH_P_IPV6 &&
2636                          pskb_may_pull(skb, sizeof(struct ipv6hdr) +
2637                                             sizeof(struct nd_msg)) &&
2638                          ipv6_hdr(skb)->nexthdr == IPPROTO_ICMPV6) {
2639                         struct nd_msg *m = (struct nd_msg *)(ipv6_hdr(skb) + 1);
2640
2641                         if (m->icmph.icmp6_code == 0 &&
2642                             m->icmph.icmp6_type == NDISC_NEIGHBOUR_SOLICITATION)
2643                                 return neigh_reduce(dev, skb, vni);
2644                 }
2645 #endif
2646         }
2647
2648         eth = eth_hdr(skb);
2649         f = vxlan_find_mac(vxlan, eth->h_dest, vni);
2650         did_rsc = false;
2651
2652         if (f && (f->flags & NTF_ROUTER) && (vxlan->cfg.flags & VXLAN_F_RSC) &&
2653             (ntohs(eth->h_proto) == ETH_P_IP ||
2654              ntohs(eth->h_proto) == ETH_P_IPV6)) {
2655                 did_rsc = route_shortcircuit(dev, skb);
2656                 if (did_rsc)
2657                         f = vxlan_find_mac(vxlan, eth->h_dest, vni);
2658         }
2659
2660         if (f == NULL) {
2661                 f = vxlan_find_mac(vxlan, all_zeros_mac, vni);
2662                 if (f == NULL) {
2663                         if ((vxlan->cfg.flags & VXLAN_F_L2MISS) &&
2664                             !is_multicast_ether_addr(eth->h_dest))
2665                                 vxlan_fdb_miss(vxlan, eth->h_dest);
2666
2667                         dev->stats.tx_dropped++;
2668                         kfree_skb(skb);
2669                         return NETDEV_TX_OK;
2670                 }
2671         }
2672
2673         list_for_each_entry_rcu(rdst, &f->remotes, list) {
2674                 struct sk_buff *skb1;
2675
2676                 if (!fdst) {
2677                         fdst = rdst;
2678                         continue;
2679                 }
2680                 skb1 = skb_clone(skb, GFP_ATOMIC);
2681                 if (skb1)
2682                         vxlan_xmit_one(skb1, dev, vni, rdst, did_rsc);
2683         }
2684
2685         if (fdst)
2686                 vxlan_xmit_one(skb, dev, vni, fdst, did_rsc);
2687         else
2688                 kfree_skb(skb);
2689         return NETDEV_TX_OK;
2690 }
2691
2692 /* Walk the forwarding table and purge stale entries */
2693 static void vxlan_cleanup(struct timer_list *t)
2694 {
2695         struct vxlan_dev *vxlan = from_timer(vxlan, t, age_timer);
2696         unsigned long next_timer = jiffies + FDB_AGE_INTERVAL;
2697         unsigned int h;
2698
2699         if (!netif_running(vxlan->dev))
2700                 return;
2701
2702         for (h = 0; h < FDB_HASH_SIZE; ++h) {
2703                 struct hlist_node *p, *n;
2704
2705                 spin_lock(&vxlan->hash_lock);
2706                 hlist_for_each_safe(p, n, &vxlan->fdb_head[h]) {
2707                         struct vxlan_fdb *f
2708                                 = container_of(p, struct vxlan_fdb, hlist);
2709                         unsigned long timeout;
2710
2711                         if (f->state & (NUD_PERMANENT | NUD_NOARP))
2712                                 continue;
2713
2714                         if (f->flags & NTF_EXT_LEARNED)
2715                                 continue;
2716
2717                         timeout = f->used + vxlan->cfg.age_interval * HZ;
2718                         if (time_before_eq(timeout, jiffies)) {
2719                                 netdev_dbg(vxlan->dev,
2720                                            "garbage collect %pM\n",
2721                                            f->eth_addr);
2722                                 f->state = NUD_STALE;
2723                                 vxlan_fdb_destroy(vxlan, f, true, true);
2724                         } else if (time_before(timeout, next_timer))
2725                                 next_timer = timeout;
2726                 }
2727                 spin_unlock(&vxlan->hash_lock);
2728         }
2729
2730         mod_timer(&vxlan->age_timer, next_timer);
2731 }
2732
2733 static void vxlan_vs_del_dev(struct vxlan_dev *vxlan)
2734 {
2735         struct vxlan_net *vn = net_generic(vxlan->net, vxlan_net_id);
2736
2737         spin_lock(&vn->sock_lock);
2738         hlist_del_init_rcu(&vxlan->hlist4.hlist);
2739 #if IS_ENABLED(CONFIG_IPV6)
2740         hlist_del_init_rcu(&vxlan->hlist6.hlist);
2741 #endif
2742         spin_unlock(&vn->sock_lock);
2743 }
2744
2745 static void vxlan_vs_add_dev(struct vxlan_sock *vs, struct vxlan_dev *vxlan,
2746                              struct vxlan_dev_node *node)
2747 {
2748         struct vxlan_net *vn = net_generic(vxlan->net, vxlan_net_id);
2749         __be32 vni = vxlan->default_dst.remote_vni;
2750
2751         node->vxlan = vxlan;
2752         spin_lock(&vn->sock_lock);
2753         hlist_add_head_rcu(&node->hlist, vni_head(vs, vni));
2754         spin_unlock(&vn->sock_lock);
2755 }
2756
2757 /* Setup stats when device is created */
2758 static int vxlan_init(struct net_device *dev)
2759 {
2760         dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
2761         if (!dev->tstats)
2762                 return -ENOMEM;
2763
2764         return 0;
2765 }
2766
2767 static void vxlan_fdb_delete_default(struct vxlan_dev *vxlan, __be32 vni)
2768 {
2769         struct vxlan_fdb *f;
2770
2771         spin_lock_bh(&vxlan->hash_lock);
2772         f = __vxlan_find_mac(vxlan, all_zeros_mac, vni);
2773         if (f)
2774                 vxlan_fdb_destroy(vxlan, f, true, true);
2775         spin_unlock_bh(&vxlan->hash_lock);
2776 }
2777
2778 static void vxlan_uninit(struct net_device *dev)
2779 {
2780         struct vxlan_dev *vxlan = netdev_priv(dev);
2781
2782         gro_cells_destroy(&vxlan->gro_cells);
2783
2784         vxlan_fdb_delete_default(vxlan, vxlan->cfg.vni);
2785
2786         free_percpu(dev->tstats);
2787 }
2788
2789 /* Start ageing timer and join group when device is brought up */
2790 static int vxlan_open(struct net_device *dev)
2791 {
2792         struct vxlan_dev *vxlan = netdev_priv(dev);
2793         int ret;
2794
2795         ret = vxlan_sock_add(vxlan);
2796         if (ret < 0)
2797                 return ret;
2798
2799         if (vxlan_addr_multicast(&vxlan->default_dst.remote_ip)) {
2800                 ret = vxlan_igmp_join(vxlan);
2801                 if (ret == -EADDRINUSE)
2802                         ret = 0;
2803                 if (ret) {
2804                         vxlan_sock_release(vxlan);
2805                         return ret;
2806                 }
2807         }
2808
2809         if (vxlan->cfg.age_interval)
2810                 mod_timer(&vxlan->age_timer, jiffies + FDB_AGE_INTERVAL);
2811
2812         return ret;
2813 }
2814
2815 /* Purge the forwarding table */
2816 static void vxlan_flush(struct vxlan_dev *vxlan, bool do_all)
2817 {
2818         unsigned int h;
2819
2820         spin_lock_bh(&vxlan->hash_lock);
2821         for (h = 0; h < FDB_HASH_SIZE; ++h) {
2822                 struct hlist_node *p, *n;
2823                 hlist_for_each_safe(p, n, &vxlan->fdb_head[h]) {
2824                         struct vxlan_fdb *f
2825                                 = container_of(p, struct vxlan_fdb, hlist);
2826                         if (!do_all && (f->state & (NUD_PERMANENT | NUD_NOARP)))
2827                                 continue;
2828                         /* the all_zeros_mac entry is deleted at vxlan_uninit */
2829                         if (!is_zero_ether_addr(f->eth_addr))
2830                                 vxlan_fdb_destroy(vxlan, f, true, true);
2831                 }
2832         }
2833         spin_unlock_bh(&vxlan->hash_lock);
2834 }
2835
2836 /* Cleanup timer and forwarding table on shutdown */
2837 static int vxlan_stop(struct net_device *dev)
2838 {
2839         struct vxlan_dev *vxlan = netdev_priv(dev);
2840         struct vxlan_net *vn = net_generic(vxlan->net, vxlan_net_id);
2841         int ret = 0;
2842
2843         if (vxlan_addr_multicast(&vxlan->default_dst.remote_ip) &&
2844             !vxlan_group_used(vn, vxlan))
2845                 ret = vxlan_igmp_leave(vxlan);
2846
2847         del_timer_sync(&vxlan->age_timer);
2848
2849         vxlan_flush(vxlan, false);
2850         vxlan_sock_release(vxlan);
2851
2852         return ret;
2853 }
2854
2855 /* Stub, nothing needs to be done. */
2856 static void vxlan_set_multicast_list(struct net_device *dev)
2857 {
2858 }
2859
2860 static int vxlan_change_mtu(struct net_device *dev, int new_mtu)
2861 {
2862         struct vxlan_dev *vxlan = netdev_priv(dev);
2863         struct vxlan_rdst *dst = &vxlan->default_dst;
2864         struct net_device *lowerdev = __dev_get_by_index(vxlan->net,
2865                                                          dst->remote_ifindex);
2866         bool use_ipv6 = !!(vxlan->cfg.flags & VXLAN_F_IPV6);
2867
2868         /* This check is different than dev->max_mtu, because it looks at
2869          * the lowerdev->mtu, rather than the static dev->max_mtu
2870          */
2871         if (lowerdev) {
2872                 int max_mtu = lowerdev->mtu -
2873                               (use_ipv6 ? VXLAN6_HEADROOM : VXLAN_HEADROOM);
2874                 if (new_mtu > max_mtu)
2875                         return -EINVAL;
2876         }
2877
2878         dev->mtu = new_mtu;
2879         return 0;
2880 }
2881
2882 static int vxlan_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
2883 {
2884         struct vxlan_dev *vxlan = netdev_priv(dev);
2885         struct ip_tunnel_info *info = skb_tunnel_info(skb);
2886         __be16 sport, dport;
2887
2888         sport = udp_flow_src_port(dev_net(dev), skb, vxlan->cfg.port_min,
2889                                   vxlan->cfg.port_max, true);
2890         dport = info->key.tp_dst ? : vxlan->cfg.dst_port;
2891
2892         if (ip_tunnel_info_af(info) == AF_INET) {
2893                 struct vxlan_sock *sock4 = rcu_dereference(vxlan->vn4_sock);
2894                 struct rtable *rt;
2895
2896                 rt = vxlan_get_route(vxlan, dev, sock4, skb, 0, info->key.tos,
2897                                      info->key.u.ipv4.dst,
2898                                      &info->key.u.ipv4.src, dport, sport,
2899                                      &info->dst_cache, info);
2900                 if (IS_ERR(rt))
2901                         return PTR_ERR(rt);
2902                 ip_rt_put(rt);
2903         } else {
2904 #if IS_ENABLED(CONFIG_IPV6)
2905                 struct vxlan_sock *sock6 = rcu_dereference(vxlan->vn6_sock);
2906                 struct dst_entry *ndst;
2907
2908                 ndst = vxlan6_get_route(vxlan, dev, sock6, skb, 0, info->key.tos,
2909                                         info->key.label, &info->key.u.ipv6.dst,
2910                                         &info->key.u.ipv6.src, dport, sport,
2911                                         &info->dst_cache, info);
2912                 if (IS_ERR(ndst))
2913                         return PTR_ERR(ndst);
2914                 dst_release(ndst);
2915 #else /* !CONFIG_IPV6 */
2916                 return -EPFNOSUPPORT;
2917 #endif
2918         }
2919         info->key.tp_src = sport;
2920         info->key.tp_dst = dport;
2921         return 0;
2922 }
2923
2924 static const struct net_device_ops vxlan_netdev_ether_ops = {
2925         .ndo_init               = vxlan_init,
2926         .ndo_uninit             = vxlan_uninit,
2927         .ndo_open               = vxlan_open,
2928         .ndo_stop               = vxlan_stop,
2929         .ndo_start_xmit         = vxlan_xmit,
2930         .ndo_get_stats64        = ip_tunnel_get_stats64,
2931         .ndo_set_rx_mode        = vxlan_set_multicast_list,
2932         .ndo_change_mtu         = vxlan_change_mtu,
2933         .ndo_validate_addr      = eth_validate_addr,
2934         .ndo_set_mac_address    = eth_mac_addr,
2935         .ndo_fdb_add            = vxlan_fdb_add,
2936         .ndo_fdb_del            = vxlan_fdb_delete,
2937         .ndo_fdb_dump           = vxlan_fdb_dump,
2938         .ndo_fdb_get            = vxlan_fdb_get,
2939         .ndo_fill_metadata_dst  = vxlan_fill_metadata_dst,
2940         .ndo_change_proto_down  = dev_change_proto_down_generic,
2941 };
2942
2943 static const struct net_device_ops vxlan_netdev_raw_ops = {
2944         .ndo_init               = vxlan_init,
2945         .ndo_uninit             = vxlan_uninit,
2946         .ndo_open               = vxlan_open,
2947         .ndo_stop               = vxlan_stop,
2948         .ndo_start_xmit         = vxlan_xmit,
2949         .ndo_get_stats64        = ip_tunnel_get_stats64,
2950         .ndo_change_mtu         = vxlan_change_mtu,
2951         .ndo_fill_metadata_dst  = vxlan_fill_metadata_dst,
2952 };
2953
2954 /* Info for udev, that this is a virtual tunnel endpoint */
2955 static struct device_type vxlan_type = {
2956         .name = "vxlan",
2957 };
2958
2959 /* Calls the ndo_udp_tunnel_add of the caller in order to
2960  * supply the listening VXLAN udp ports. Callers are expected
2961  * to implement the ndo_udp_tunnel_add.
2962  */
2963 static void vxlan_offload_rx_ports(struct net_device *dev, bool push)
2964 {
2965         struct vxlan_sock *vs;
2966         struct net *net = dev_net(dev);
2967         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2968         unsigned int i;
2969
2970         spin_lock(&vn->sock_lock);
2971         for (i = 0; i < PORT_HASH_SIZE; ++i) {
2972                 hlist_for_each_entry_rcu(vs, &vn->sock_list[i], hlist) {
2973                         unsigned short type;
2974
2975                         if (vs->flags & VXLAN_F_GPE)
2976                                 type = UDP_TUNNEL_TYPE_VXLAN_GPE;
2977                         else
2978                                 type = UDP_TUNNEL_TYPE_VXLAN;
2979
2980                         if (push)
2981                                 udp_tunnel_push_rx_port(dev, vs->sock, type);
2982                         else
2983                                 udp_tunnel_drop_rx_port(dev, vs->sock, type);
2984                 }
2985         }
2986         spin_unlock(&vn->sock_lock);
2987 }
2988
2989 /* Initialize the device structure. */
2990 static void vxlan_setup(struct net_device *dev)
2991 {
2992         struct vxlan_dev *vxlan = netdev_priv(dev);
2993         unsigned int h;
2994
2995         eth_hw_addr_random(dev);
2996         ether_setup(dev);
2997
2998         dev->needs_free_netdev = true;
2999         SET_NETDEV_DEVTYPE(dev, &vxlan_type);
3000
3001         dev->features   |= NETIF_F_LLTX;
3002         dev->features   |= NETIF_F_SG | NETIF_F_HW_CSUM;
3003         dev->features   |= NETIF_F_RXCSUM;
3004         dev->features   |= NETIF_F_GSO_SOFTWARE;
3005
3006         dev->vlan_features = dev->features;
3007         dev->hw_features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_RXCSUM;
3008         dev->hw_features |= NETIF_F_GSO_SOFTWARE;
3009         netif_keep_dst(dev);
3010         dev->priv_flags |= IFF_NO_QUEUE;
3011
3012         /* MTU range: 68 - 65535 */
3013         dev->min_mtu = ETH_MIN_MTU;
3014         dev->max_mtu = ETH_MAX_MTU;
3015
3016         INIT_LIST_HEAD(&vxlan->next);
3017         spin_lock_init(&vxlan->hash_lock);
3018
3019         timer_setup(&vxlan->age_timer, vxlan_cleanup, TIMER_DEFERRABLE);
3020
3021         vxlan->dev = dev;
3022
3023         gro_cells_init(&vxlan->gro_cells, dev);
3024
3025         for (h = 0; h < FDB_HASH_SIZE; ++h)
3026                 INIT_HLIST_HEAD(&vxlan->fdb_head[h]);
3027 }
3028
3029 static void vxlan_ether_setup(struct net_device *dev)
3030 {
3031         dev->priv_flags &= ~IFF_TX_SKB_SHARING;
3032         dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
3033         dev->netdev_ops = &vxlan_netdev_ether_ops;
3034 }
3035
3036 static void vxlan_raw_setup(struct net_device *dev)
3037 {
3038         dev->header_ops = NULL;
3039         dev->type = ARPHRD_NONE;
3040         dev->hard_header_len = 0;
3041         dev->addr_len = 0;
3042         dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
3043         dev->netdev_ops = &vxlan_netdev_raw_ops;
3044 }
3045
3046 static const struct nla_policy vxlan_policy[IFLA_VXLAN_MAX + 1] = {
3047         [IFLA_VXLAN_ID]         = { .type = NLA_U32 },
3048         [IFLA_VXLAN_GROUP]      = { .len = FIELD_SIZEOF(struct iphdr, daddr) },
3049         [IFLA_VXLAN_GROUP6]     = { .len = sizeof(struct in6_addr) },
3050         [IFLA_VXLAN_LINK]       = { .type = NLA_U32 },
3051         [IFLA_VXLAN_LOCAL]      = { .len = FIELD_SIZEOF(struct iphdr, saddr) },
3052         [IFLA_VXLAN_LOCAL6]     = { .len = sizeof(struct in6_addr) },
3053         [IFLA_VXLAN_TOS]        = { .type = NLA_U8 },
3054         [IFLA_VXLAN_TTL]        = { .type = NLA_U8 },
3055         [IFLA_VXLAN_LABEL]      = { .type = NLA_U32 },
3056         [IFLA_VXLAN_LEARNING]   = { .type = NLA_U8 },
3057         [IFLA_VXLAN_AGEING]     = { .type = NLA_U32 },
3058         [IFLA_VXLAN_LIMIT]      = { .type = NLA_U32 },
3059         [IFLA_VXLAN_PORT_RANGE] = { .len  = sizeof(struct ifla_vxlan_port_range) },
3060         [IFLA_VXLAN_PROXY]      = { .type = NLA_U8 },
3061         [IFLA_VXLAN_RSC]        = { .type = NLA_U8 },
3062         [IFLA_VXLAN_L2MISS]     = { .type = NLA_U8 },
3063         [IFLA_VXLAN_L3MISS]     = { .type = NLA_U8 },
3064         [IFLA_VXLAN_COLLECT_METADATA]   = { .type = NLA_U8 },
3065         [IFLA_VXLAN_PORT]       = { .type = NLA_U16 },
3066         [IFLA_VXLAN_UDP_CSUM]   = { .type = NLA_U8 },
3067         [IFLA_VXLAN_UDP_ZERO_CSUM6_TX]  = { .type = NLA_U8 },
3068         [IFLA_VXLAN_UDP_ZERO_CSUM6_RX]  = { .type = NLA_U8 },
3069         [IFLA_VXLAN_REMCSUM_TX] = { .type = NLA_U8 },
3070         [IFLA_VXLAN_REMCSUM_RX] = { .type = NLA_U8 },
3071         [IFLA_VXLAN_GBP]        = { .type = NLA_FLAG, },
3072         [IFLA_VXLAN_GPE]        = { .type = NLA_FLAG, },
3073         [IFLA_VXLAN_REMCSUM_NOPARTIAL]  = { .type = NLA_FLAG },
3074         [IFLA_VXLAN_TTL_INHERIT]        = { .type = NLA_FLAG },
3075         [IFLA_VXLAN_DF]         = { .type = NLA_U8 },
3076 };
3077
3078 static int vxlan_validate(struct nlattr *tb[], struct nlattr *data[],
3079                           struct netlink_ext_ack *extack)
3080 {
3081         if (tb[IFLA_ADDRESS]) {
3082                 if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN) {
3083                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_ADDRESS],
3084                                             "Provided link layer address is not Ethernet");
3085                         return -EINVAL;
3086                 }
3087
3088                 if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS]))) {
3089                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_ADDRESS],
3090                                             "Provided Ethernet address is not unicast");
3091                         return -EADDRNOTAVAIL;
3092                 }
3093         }
3094
3095         if (tb[IFLA_MTU]) {
3096                 u32 mtu = nla_get_u32(tb[IFLA_MTU]);
3097
3098                 if (mtu < ETH_MIN_MTU || mtu > ETH_MAX_MTU) {
3099                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_MTU],
3100                                             "MTU must be between 68 and 65535");
3101                         return -EINVAL;
3102                 }
3103         }
3104
3105         if (!data) {
3106                 NL_SET_ERR_MSG(extack,
3107                                "Required attributes not provided to perform the operation");
3108                 return -EINVAL;
3109         }
3110
3111         if (data[IFLA_VXLAN_ID]) {
3112                 u32 id = nla_get_u32(data[IFLA_VXLAN_ID]);
3113
3114                 if (id >= VXLAN_N_VID) {
3115                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_ID],
3116                                             "VXLAN ID must be lower than 16777216");
3117                         return -ERANGE;
3118                 }
3119         }
3120
3121         if (data[IFLA_VXLAN_PORT_RANGE]) {
3122                 const struct ifla_vxlan_port_range *p
3123                         = nla_data(data[IFLA_VXLAN_PORT_RANGE]);
3124
3125                 if (ntohs(p->high) < ntohs(p->low)) {
3126                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_PORT_RANGE],
3127                                             "Invalid source port range");
3128                         return -EINVAL;
3129                 }
3130         }
3131
3132         if (data[IFLA_VXLAN_DF]) {
3133                 enum ifla_vxlan_df df = nla_get_u8(data[IFLA_VXLAN_DF]);
3134
3135                 if (df < 0 || df > VXLAN_DF_MAX) {
3136                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_DF],
3137                                             "Invalid DF attribute");
3138                         return -EINVAL;
3139                 }
3140         }
3141
3142         return 0;
3143 }
3144
3145 static void vxlan_get_drvinfo(struct net_device *netdev,
3146                               struct ethtool_drvinfo *drvinfo)
3147 {
3148         strlcpy(drvinfo->version, VXLAN_VERSION, sizeof(drvinfo->version));
3149         strlcpy(drvinfo->driver, "vxlan", sizeof(drvinfo->driver));
3150 }
3151
3152 static const struct ethtool_ops vxlan_ethtool_ops = {
3153         .get_drvinfo    = vxlan_get_drvinfo,
3154         .get_link       = ethtool_op_get_link,
3155 };
3156
3157 static struct socket *vxlan_create_sock(struct net *net, bool ipv6,
3158                                         __be16 port, u32 flags, int ifindex)
3159 {
3160         struct socket *sock;
3161         struct udp_port_cfg udp_conf;
3162         int err;
3163
3164         memset(&udp_conf, 0, sizeof(udp_conf));
3165
3166         if (ipv6) {
3167                 udp_conf.family = AF_INET6;
3168                 udp_conf.use_udp6_rx_checksums =
3169                     !(flags & VXLAN_F_UDP_ZERO_CSUM6_RX);
3170                 udp_conf.ipv6_v6only = 1;
3171         } else {
3172                 udp_conf.family = AF_INET;
3173         }
3174
3175         udp_conf.local_udp_port = port;
3176         udp_conf.bind_ifindex = ifindex;
3177
3178         /* Open UDP socket */
3179         err = udp_sock_create(net, &udp_conf, &sock);
3180         if (err < 0)
3181                 return ERR_PTR(err);
3182
3183         return sock;
3184 }
3185
3186 /* Create new listen socket if needed */
3187 static struct vxlan_sock *vxlan_socket_create(struct net *net, bool ipv6,
3188                                               __be16 port, u32 flags,
3189                                               int ifindex)
3190 {
3191         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
3192         struct vxlan_sock *vs;
3193         struct socket *sock;
3194         unsigned int h;
3195         struct udp_tunnel_sock_cfg tunnel_cfg;
3196
3197         vs = kzalloc(sizeof(*vs), GFP_KERNEL);
3198         if (!vs)
3199                 return ERR_PTR(-ENOMEM);
3200
3201         for (h = 0; h < VNI_HASH_SIZE; ++h)
3202                 INIT_HLIST_HEAD(&vs->vni_list[h]);
3203
3204         sock = vxlan_create_sock(net, ipv6, port, flags, ifindex);
3205         if (IS_ERR(sock)) {
3206                 kfree(vs);
3207                 return ERR_CAST(sock);
3208         }
3209
3210         vs->sock = sock;
3211         refcount_set(&vs->refcnt, 1);
3212         vs->flags = (flags & VXLAN_F_RCV_FLAGS);
3213
3214         spin_lock(&vn->sock_lock);
3215         hlist_add_head_rcu(&vs->hlist, vs_head(net, port));
3216         udp_tunnel_notify_add_rx_port(sock,
3217                                       (vs->flags & VXLAN_F_GPE) ?
3218                                       UDP_TUNNEL_TYPE_VXLAN_GPE :
3219                                       UDP_TUNNEL_TYPE_VXLAN);
3220         spin_unlock(&vn->sock_lock);
3221
3222         /* Mark socket as an encapsulation socket. */
3223         memset(&tunnel_cfg, 0, sizeof(tunnel_cfg));
3224         tunnel_cfg.sk_user_data = vs;
3225         tunnel_cfg.encap_type = 1;
3226         tunnel_cfg.encap_rcv = vxlan_rcv;
3227         tunnel_cfg.encap_err_lookup = vxlan_err_lookup;
3228         tunnel_cfg.encap_destroy = NULL;
3229         tunnel_cfg.gro_receive = vxlan_gro_receive;
3230         tunnel_cfg.gro_complete = vxlan_gro_complete;
3231
3232         setup_udp_tunnel_sock(net, sock, &tunnel_cfg);
3233
3234         return vs;
3235 }
3236
3237 static int __vxlan_sock_add(struct vxlan_dev *vxlan, bool ipv6)
3238 {
3239         struct vxlan_net *vn = net_generic(vxlan->net, vxlan_net_id);
3240         struct vxlan_sock *vs = NULL;
3241         struct vxlan_dev_node *node;
3242         int l3mdev_index = 0;
3243
3244         if (vxlan->cfg.remote_ifindex)
3245                 l3mdev_index = l3mdev_master_upper_ifindex_by_index(
3246                         vxlan->net, vxlan->cfg.remote_ifindex);
3247
3248         if (!vxlan->cfg.no_share) {
3249                 spin_lock(&vn->sock_lock);
3250                 vs = vxlan_find_sock(vxlan->net, ipv6 ? AF_INET6 : AF_INET,
3251                                      vxlan->cfg.dst_port, vxlan->cfg.flags,
3252                                      l3mdev_index);
3253                 if (vs && !refcount_inc_not_zero(&vs->refcnt)) {
3254                         spin_unlock(&vn->sock_lock);
3255                         return -EBUSY;
3256                 }
3257                 spin_unlock(&vn->sock_lock);
3258         }
3259         if (!vs)
3260                 vs = vxlan_socket_create(vxlan->net, ipv6,
3261                                          vxlan->cfg.dst_port, vxlan->cfg.flags,
3262                                          l3mdev_index);
3263         if (IS_ERR(vs))
3264                 return PTR_ERR(vs);
3265 #if IS_ENABLED(CONFIG_IPV6)
3266         if (ipv6) {
3267                 rcu_assign_pointer(vxlan->vn6_sock, vs);
3268                 node = &vxlan->hlist6;
3269         } else
3270 #endif
3271         {
3272                 rcu_assign_pointer(vxlan->vn4_sock, vs);
3273                 node = &vxlan->hlist4;
3274         }
3275         vxlan_vs_add_dev(vs, vxlan, node);
3276         return 0;
3277 }
3278
3279 static int vxlan_sock_add(struct vxlan_dev *vxlan)
3280 {
3281         bool metadata = vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA;
3282         bool ipv6 = vxlan->cfg.flags & VXLAN_F_IPV6 || metadata;
3283         bool ipv4 = !ipv6 || metadata;
3284         int ret = 0;
3285
3286         RCU_INIT_POINTER(vxlan->vn4_sock, NULL);
3287 #if IS_ENABLED(CONFIG_IPV6)
3288         RCU_INIT_POINTER(vxlan->vn6_sock, NULL);
3289         if (ipv6) {
3290                 ret = __vxlan_sock_add(vxlan, true);
3291                 if (ret < 0 && ret != -EAFNOSUPPORT)
3292                         ipv4 = false;
3293         }
3294 #endif
3295         if (ipv4)
3296                 ret = __vxlan_sock_add(vxlan, false);
3297         if (ret < 0)
3298                 vxlan_sock_release(vxlan);
3299         return ret;
3300 }
3301
3302 static int vxlan_config_validate(struct net *src_net, struct vxlan_config *conf,
3303                                  struct net_device **lower,
3304                                  struct vxlan_dev *old,
3305                                  struct netlink_ext_ack *extack)
3306 {
3307         struct vxlan_net *vn = net_generic(src_net, vxlan_net_id);
3308         struct vxlan_dev *tmp;
3309         bool use_ipv6 = false;
3310
3311         if (conf->flags & VXLAN_F_GPE) {
3312                 /* For now, allow GPE only together with
3313                  * COLLECT_METADATA. This can be relaxed later; in such
3314                  * case, the other side of the PtP link will have to be
3315                  * provided.
3316                  */
3317                 if ((conf->flags & ~VXLAN_F_ALLOWED_GPE) ||
3318                     !(conf->flags & VXLAN_F_COLLECT_METADATA)) {
3319                         NL_SET_ERR_MSG(extack,
3320                                        "VXLAN GPE does not support this combination of attributes");
3321                         return -EINVAL;
3322                 }
3323         }
3324
3325         if (!conf->remote_ip.sa.sa_family && !conf->saddr.sa.sa_family) {
3326                 /* Unless IPv6 is explicitly requested, assume IPv4 */
3327                 conf->remote_ip.sa.sa_family = AF_INET;
3328                 conf->saddr.sa.sa_family = AF_INET;
3329         } else if (!conf->remote_ip.sa.sa_family) {
3330                 conf->remote_ip.sa.sa_family = conf->saddr.sa.sa_family;
3331         } else if (!conf->saddr.sa.sa_family) {
3332                 conf->saddr.sa.sa_family = conf->remote_ip.sa.sa_family;
3333         }
3334
3335         if (conf->saddr.sa.sa_family != conf->remote_ip.sa.sa_family) {
3336                 NL_SET_ERR_MSG(extack,
3337                                "Local and remote address must be from the same family");
3338                 return -EINVAL;
3339         }
3340
3341         if (vxlan_addr_multicast(&conf->saddr)) {
3342                 NL_SET_ERR_MSG(extack, "Local address cannot be multicast");
3343                 return -EINVAL;
3344         }
3345
3346         if (conf->saddr.sa.sa_family == AF_INET6) {
3347                 if (!IS_ENABLED(CONFIG_IPV6)) {
3348                         NL_SET_ERR_MSG(extack,
3349                                        "IPv6 support not enabled in the kernel");
3350                         return -EPFNOSUPPORT;
3351                 }
3352                 use_ipv6 = true;
3353                 conf->flags |= VXLAN_F_IPV6;
3354
3355                 if (!(conf->flags & VXLAN_F_COLLECT_METADATA)) {
3356                         int local_type =
3357                                 ipv6_addr_type(&conf->saddr.sin6.sin6_addr);
3358                         int remote_type =
3359                                 ipv6_addr_type(&conf->remote_ip.sin6.sin6_addr);
3360
3361                         if (local_type & IPV6_ADDR_LINKLOCAL) {
3362                                 if (!(remote_type & IPV6_ADDR_LINKLOCAL) &&
3363                                     (remote_type != IPV6_ADDR_ANY)) {
3364                                         NL_SET_ERR_MSG(extack,
3365                                                        "Invalid combination of local and remote address scopes");
3366                                         return -EINVAL;
3367                                 }
3368
3369                                 conf->flags |= VXLAN_F_IPV6_LINKLOCAL;
3370                         } else {
3371                                 if (remote_type ==
3372                                     (IPV6_ADDR_UNICAST | IPV6_ADDR_LINKLOCAL)) {
3373                                         NL_SET_ERR_MSG(extack,
3374                                                        "Invalid combination of local and remote address scopes");
3375                                         return -EINVAL;
3376                                 }
3377
3378                                 conf->flags &= ~VXLAN_F_IPV6_LINKLOCAL;
3379                         }
3380                 }
3381         }
3382
3383         if (conf->label && !use_ipv6) {
3384                 NL_SET_ERR_MSG(extack,
3385                                "Label attribute only applies to IPv6 VXLAN devices");
3386                 return -EINVAL;
3387         }
3388
3389         if (conf->remote_ifindex) {
3390                 struct net_device *lowerdev;
3391
3392                 lowerdev = __dev_get_by_index(src_net, conf->remote_ifindex);
3393                 if (!lowerdev) {
3394                         NL_SET_ERR_MSG(extack,
3395                                        "Invalid local interface, device not found");
3396                         return -ENODEV;
3397                 }
3398
3399 #if IS_ENABLED(CONFIG_IPV6)
3400                 if (use_ipv6) {
3401                         struct inet6_dev *idev = __in6_dev_get(lowerdev);
3402                         if (idev && idev->cnf.disable_ipv6) {
3403                                 NL_SET_ERR_MSG(extack,
3404                                                "IPv6 support disabled by administrator");
3405                                 return -EPERM;
3406                         }
3407                 }
3408 #endif
3409
3410                 *lower = lowerdev;
3411         } else {
3412                 if (vxlan_addr_multicast(&conf->remote_ip)) {
3413                         NL_SET_ERR_MSG(extack,
3414                                        "Local interface required for multicast remote destination");
3415
3416                         return -EINVAL;
3417                 }
3418
3419 #if IS_ENABLED(CONFIG_IPV6)
3420                 if (conf->flags & VXLAN_F_IPV6_LINKLOCAL) {
3421                         NL_SET_ERR_MSG(extack,
3422                                        "Local interface required for link-local local/remote addresses");
3423                         return -EINVAL;
3424                 }
3425 #endif
3426
3427                 *lower = NULL;
3428         }
3429
3430         if (!conf->dst_port) {
3431                 if (conf->flags & VXLAN_F_GPE)
3432                         conf->dst_port = htons(4790); /* IANA VXLAN-GPE port */
3433                 else
3434                         conf->dst_port = htons(vxlan_port);
3435         }
3436
3437         if (!conf->age_interval)
3438                 conf->age_interval = FDB_AGE_DEFAULT;
3439
3440         list_for_each_entry(tmp, &vn->vxlan_list, next) {
3441                 if (tmp == old)
3442                         continue;
3443
3444                 if (tmp->cfg.vni != conf->vni)
3445                         continue;
3446                 if (tmp->cfg.dst_port != conf->dst_port)
3447                         continue;
3448                 if ((tmp->cfg.flags & (VXLAN_F_RCV_FLAGS | VXLAN_F_IPV6)) !=
3449                     (conf->flags & (VXLAN_F_RCV_FLAGS | VXLAN_F_IPV6)))
3450                         continue;
3451
3452                 if ((conf->flags & VXLAN_F_IPV6_LINKLOCAL) &&
3453                     tmp->cfg.remote_ifindex != conf->remote_ifindex)
3454                         continue;
3455
3456                 NL_SET_ERR_MSG(extack,
3457                                "A VXLAN device with the specified VNI already exists");
3458                 return -EEXIST;
3459         }
3460
3461         return 0;
3462 }
3463
3464 static void vxlan_config_apply(struct net_device *dev,
3465                                struct vxlan_config *conf,
3466                                struct net_device *lowerdev,
3467                                struct net *src_net,
3468                                bool changelink)
3469 {
3470         struct vxlan_dev *vxlan = netdev_priv(dev);
3471         struct vxlan_rdst *dst = &vxlan->default_dst;
3472         unsigned short needed_headroom = ETH_HLEN;
3473         bool use_ipv6 = !!(conf->flags & VXLAN_F_IPV6);
3474         int max_mtu = ETH_MAX_MTU;
3475
3476         if (!changelink) {
3477                 if (conf->flags & VXLAN_F_GPE)
3478                         vxlan_raw_setup(dev);
3479                 else
3480                         vxlan_ether_setup(dev);
3481
3482                 if (conf->mtu)
3483                         dev->mtu = conf->mtu;
3484
3485                 vxlan->net = src_net;
3486         }
3487
3488         dst->remote_vni = conf->vni;
3489
3490         memcpy(&dst->remote_ip, &conf->remote_ip, sizeof(conf->remote_ip));
3491
3492         if (lowerdev) {
3493                 dst->remote_ifindex = conf->remote_ifindex;
3494
3495                 dev->gso_max_size = lowerdev->gso_max_size;
3496                 dev->gso_max_segs = lowerdev->gso_max_segs;
3497
3498                 needed_headroom = lowerdev->hard_header_len;
3499
3500                 max_mtu = lowerdev->mtu - (use_ipv6 ? VXLAN6_HEADROOM :
3501                                            VXLAN_HEADROOM);
3502                 if (max_mtu < ETH_MIN_MTU)
3503                         max_mtu = ETH_MIN_MTU;
3504
3505                 if (!changelink && !conf->mtu)
3506                         dev->mtu = max_mtu;
3507         }
3508
3509         if (dev->mtu > max_mtu)
3510                 dev->mtu = max_mtu;
3511
3512         if (use_ipv6 || conf->flags & VXLAN_F_COLLECT_METADATA)
3513                 needed_headroom += VXLAN6_HEADROOM;
3514         else
3515                 needed_headroom += VXLAN_HEADROOM;
3516         dev->needed_headroom = needed_headroom;
3517
3518         memcpy(&vxlan->cfg, conf, sizeof(*conf));
3519 }
3520
3521 static int vxlan_dev_configure(struct net *src_net, struct net_device *dev,
3522                                struct vxlan_config *conf, bool changelink,
3523                                struct netlink_ext_ack *extack)
3524 {
3525         struct vxlan_dev *vxlan = netdev_priv(dev);
3526         struct net_device *lowerdev;
3527         int ret;
3528
3529         ret = vxlan_config_validate(src_net, conf, &lowerdev, vxlan, extack);
3530         if (ret)
3531                 return ret;
3532
3533         vxlan_config_apply(dev, conf, lowerdev, src_net, changelink);
3534
3535         return 0;
3536 }
3537
3538 static int __vxlan_dev_create(struct net *net, struct net_device *dev,
3539                               struct vxlan_config *conf,
3540                               struct netlink_ext_ack *extack)
3541 {
3542         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
3543         struct vxlan_dev *vxlan = netdev_priv(dev);
3544         struct vxlan_fdb *f = NULL;
3545         bool unregister = false;
3546         int err;
3547
3548         err = vxlan_dev_configure(net, dev, conf, false, extack);
3549         if (err)
3550                 return err;
3551
3552         dev->ethtool_ops = &vxlan_ethtool_ops;
3553
3554         /* create an fdb entry for a valid default destination */
3555         if (!vxlan_addr_any(&vxlan->default_dst.remote_ip)) {
3556                 err = vxlan_fdb_create(vxlan, all_zeros_mac,
3557                                        &vxlan->default_dst.remote_ip,
3558                                        NUD_REACHABLE | NUD_PERMANENT,
3559                                        vxlan->cfg.dst_port,
3560                                        vxlan->default_dst.remote_vni,
3561                                        vxlan->default_dst.remote_vni,
3562                                        vxlan->default_dst.remote_ifindex,
3563                                        NTF_SELF, &f);
3564                 if (err)
3565                         return err;
3566         }
3567
3568         err = register_netdevice(dev);
3569         if (err)
3570                 goto errout;
3571         unregister = true;
3572
3573         err = rtnl_configure_link(dev, NULL);
3574         if (err)
3575                 goto errout;
3576
3577         /* notify default fdb entry */
3578         if (f) {
3579                 err = vxlan_fdb_notify(vxlan, f, first_remote_rtnl(f),
3580                                        RTM_NEWNEIGH, true, extack);
3581                 if (err)
3582                         goto errout;
3583         }
3584
3585         list_add(&vxlan->next, &vn->vxlan_list);
3586         return 0;
3587
3588 errout:
3589         /* unregister_netdevice() destroys the default FDB entry with deletion
3590          * notification. But the addition notification was not sent yet, so
3591          * destroy the entry by hand here.
3592          */
3593         if (f)
3594                 vxlan_fdb_destroy(vxlan, f, false, false);
3595         if (unregister)
3596                 unregister_netdevice(dev);
3597         return err;
3598 }
3599
3600 /* Set/clear flags based on attribute */
3601 static int vxlan_nl2flag(struct vxlan_config *conf, struct nlattr *tb[],
3602                           int attrtype, unsigned long mask, bool changelink,
3603                           bool changelink_supported,
3604                           struct netlink_ext_ack *extack)
3605 {
3606         unsigned long flags;
3607
3608         if (!tb[attrtype])
3609                 return 0;
3610
3611         if (changelink && !changelink_supported) {
3612                 vxlan_flag_attr_error(attrtype, extack);
3613                 return -EOPNOTSUPP;
3614         }
3615
3616         if (vxlan_policy[attrtype].type == NLA_FLAG)
3617                 flags = conf->flags | mask;
3618         else if (nla_get_u8(tb[attrtype]))
3619                 flags = conf->flags | mask;
3620         else
3621                 flags = conf->flags & ~mask;
3622
3623         conf->flags = flags;
3624
3625         return 0;
3626 }
3627
3628 static int vxlan_nl2conf(struct nlattr *tb[], struct nlattr *data[],
3629                          struct net_device *dev, struct vxlan_config *conf,
3630                          bool changelink, struct netlink_ext_ack *extack)
3631 {
3632         struct vxlan_dev *vxlan = netdev_priv(dev);
3633         int err = 0;
3634
3635         memset(conf, 0, sizeof(*conf));
3636
3637         /* if changelink operation, start with old existing cfg */
3638         if (changelink)
3639                 memcpy(conf, &vxlan->cfg, sizeof(*conf));
3640
3641         if (data[IFLA_VXLAN_ID]) {
3642                 __be32 vni = cpu_to_be32(nla_get_u32(data[IFLA_VXLAN_ID]));
3643
3644                 if (changelink && (vni != conf->vni)) {
3645                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_ID], "Cannot change VNI");
3646                         return -EOPNOTSUPP;
3647                 }
3648                 conf->vni = cpu_to_be32(nla_get_u32(data[IFLA_VXLAN_ID]));
3649         }
3650
3651         if (data[IFLA_VXLAN_GROUP]) {
3652                 if (changelink && (conf->remote_ip.sa.sa_family != AF_INET)) {
3653                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_GROUP], "New group address family does not match old group");
3654                         return -EOPNOTSUPP;
3655                 }
3656
3657                 conf->remote_ip.sin.sin_addr.s_addr = nla_get_in_addr(data[IFLA_VXLAN_GROUP]);
3658                 conf->remote_ip.sa.sa_family = AF_INET;
3659         } else if (data[IFLA_VXLAN_GROUP6]) {
3660                 if (!IS_ENABLED(CONFIG_IPV6)) {
3661                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_GROUP6], "IPv6 support not enabled in the kernel");
3662                         return -EPFNOSUPPORT;
3663                 }
3664
3665                 if (changelink && (conf->remote_ip.sa.sa_family != AF_INET6)) {
3666                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_GROUP6], "New group address family does not match old group");
3667                         return -EOPNOTSUPP;
3668                 }
3669
3670                 conf->remote_ip.sin6.sin6_addr = nla_get_in6_addr(data[IFLA_VXLAN_GROUP6]);
3671                 conf->remote_ip.sa.sa_family = AF_INET6;
3672         }
3673
3674         if (data[IFLA_VXLAN_LOCAL]) {
3675                 if (changelink && (conf->saddr.sa.sa_family != AF_INET)) {
3676                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_LOCAL], "New local address family does not match old");
3677                         return -EOPNOTSUPP;
3678                 }
3679
3680                 conf->saddr.sin.sin_addr.s_addr = nla_get_in_addr(data[IFLA_VXLAN_LOCAL]);
3681                 conf->saddr.sa.sa_family = AF_INET;
3682         } else if (data[IFLA_VXLAN_LOCAL6]) {
3683                 if (!IS_ENABLED(CONFIG_IPV6)) {
3684                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_LOCAL6], "IPv6 support not enabled in the kernel");
3685                         return -EPFNOSUPPORT;
3686                 }
3687
3688                 if (changelink && (conf->saddr.sa.sa_family != AF_INET6)) {
3689                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_LOCAL6], "New local address family does not match old");
3690                         return -EOPNOTSUPP;
3691                 }
3692
3693                 /* TODO: respect scope id */
3694                 conf->saddr.sin6.sin6_addr = nla_get_in6_addr(data[IFLA_VXLAN_LOCAL6]);
3695                 conf->saddr.sa.sa_family = AF_INET6;
3696         }
3697
3698         if (data[IFLA_VXLAN_LINK])
3699                 conf->remote_ifindex = nla_get_u32(data[IFLA_VXLAN_LINK]);
3700
3701         if (data[IFLA_VXLAN_TOS])
3702                 conf->tos  = nla_get_u8(data[IFLA_VXLAN_TOS]);
3703
3704         if (data[IFLA_VXLAN_TTL])
3705                 conf->ttl = nla_get_u8(data[IFLA_VXLAN_TTL]);
3706
3707         if (data[IFLA_VXLAN_TTL_INHERIT]) {
3708                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_TTL_INHERIT,
3709                                     VXLAN_F_TTL_INHERIT, changelink, false,
3710                                     extack);
3711                 if (err)
3712                         return err;
3713
3714         }
3715
3716         if (data[IFLA_VXLAN_LABEL])
3717                 conf->label = nla_get_be32(data[IFLA_VXLAN_LABEL]) &
3718                              IPV6_FLOWLABEL_MASK;
3719
3720         if (data[IFLA_VXLAN_LEARNING]) {
3721                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_LEARNING,
3722                                     VXLAN_F_LEARN, changelink, true,
3723                                     extack);
3724                 if (err)
3725                         return err;
3726         } else if (!changelink) {
3727                 /* default to learn on a new device */
3728                 conf->flags |= VXLAN_F_LEARN;
3729         }
3730
3731         if (data[IFLA_VXLAN_AGEING])
3732                 conf->age_interval = nla_get_u32(data[IFLA_VXLAN_AGEING]);
3733
3734         if (data[IFLA_VXLAN_PROXY]) {
3735                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_PROXY,
3736                                     VXLAN_F_PROXY, changelink, false,
3737                                     extack);
3738                 if (err)
3739                         return err;
3740         }
3741
3742         if (data[IFLA_VXLAN_RSC]) {
3743                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_RSC,
3744                                     VXLAN_F_RSC, changelink, false,
3745                                     extack);
3746                 if (err)
3747                         return err;
3748         }
3749
3750         if (data[IFLA_VXLAN_L2MISS]) {
3751                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_L2MISS,
3752                                     VXLAN_F_L2MISS, changelink, false,
3753                                     extack);
3754                 if (err)
3755                         return err;
3756         }
3757
3758         if (data[IFLA_VXLAN_L3MISS]) {
3759                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_L3MISS,
3760                                     VXLAN_F_L3MISS, changelink, false,
3761                                     extack);
3762                 if (err)
3763                         return err;
3764         }
3765
3766         if (data[IFLA_VXLAN_LIMIT]) {
3767                 if (changelink) {
3768                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_LIMIT],
3769                                             "Cannot change limit");
3770                         return -EOPNOTSUPP;
3771                 }
3772                 conf->addrmax = nla_get_u32(data[IFLA_VXLAN_LIMIT]);
3773         }
3774
3775         if (data[IFLA_VXLAN_COLLECT_METADATA]) {
3776                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_COLLECT_METADATA,
3777                                     VXLAN_F_COLLECT_METADATA, changelink, false,
3778                                     extack);
3779                 if (err)
3780                         return err;
3781         }
3782
3783         if (data[IFLA_VXLAN_PORT_RANGE]) {
3784                 if (!changelink) {
3785                         const struct ifla_vxlan_port_range *p
3786                                 = nla_data(data[IFLA_VXLAN_PORT_RANGE]);
3787                         conf->port_min = ntohs(p->low);
3788                         conf->port_max = ntohs(p->high);
3789                 } else {
3790                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_PORT_RANGE],
3791                                             "Cannot change port range");
3792                         return -EOPNOTSUPP;
3793                 }
3794         }
3795
3796         if (data[IFLA_VXLAN_PORT]) {
3797                 if (changelink) {
3798                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_PORT],
3799                                             "Cannot change port");
3800                         return -EOPNOTSUPP;
3801                 }
3802                 conf->dst_port = nla_get_be16(data[IFLA_VXLAN_PORT]);
3803         }
3804
3805         if (data[IFLA_VXLAN_UDP_CSUM]) {
3806                 if (changelink) {
3807                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_VXLAN_UDP_CSUM],
3808                                             "Cannot change UDP_CSUM flag");
3809                         return -EOPNOTSUPP;
3810                 }
3811                 if (!nla_get_u8(data[IFLA_VXLAN_UDP_CSUM]))
3812                         conf->flags |= VXLAN_F_UDP_ZERO_CSUM_TX;
3813         }
3814
3815         if (data[IFLA_VXLAN_UDP_ZERO_CSUM6_TX]) {
3816                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_UDP_ZERO_CSUM6_TX,
3817                                     VXLAN_F_UDP_ZERO_CSUM6_TX, changelink,
3818                                     false, extack);
3819                 if (err)
3820                         return err;
3821         }
3822
3823         if (data[IFLA_VXLAN_UDP_ZERO_CSUM6_RX]) {
3824                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_UDP_ZERO_CSUM6_RX,
3825                                     VXLAN_F_UDP_ZERO_CSUM6_RX, changelink,
3826                                     false, extack);
3827                 if (err)
3828                         return err;
3829         }
3830
3831         if (data[IFLA_VXLAN_REMCSUM_TX]) {
3832                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_REMCSUM_TX,
3833                                     VXLAN_F_REMCSUM_TX, changelink, false,
3834                                     extack);
3835                 if (err)
3836                         return err;
3837         }
3838
3839         if (data[IFLA_VXLAN_REMCSUM_RX]) {
3840                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_REMCSUM_RX,
3841                                     VXLAN_F_REMCSUM_RX, changelink, false,
3842                                     extack);
3843                 if (err)
3844                         return err;
3845         }
3846
3847         if (data[IFLA_VXLAN_GBP]) {
3848                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_GBP,
3849                                     VXLAN_F_GBP, changelink, false, extack);
3850                 if (err)
3851                         return err;
3852         }
3853
3854         if (data[IFLA_VXLAN_GPE]) {
3855                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_GPE,
3856                                     VXLAN_F_GPE, changelink, false,
3857                                     extack);
3858                 if (err)
3859                         return err;
3860         }
3861
3862         if (data[IFLA_VXLAN_REMCSUM_NOPARTIAL]) {
3863                 err = vxlan_nl2flag(conf, data, IFLA_VXLAN_REMCSUM_NOPARTIAL,
3864                                     VXLAN_F_REMCSUM_NOPARTIAL, changelink,
3865                                     false, extack);
3866                 if (err)
3867                         return err;
3868         }
3869
3870         if (tb[IFLA_MTU]) {
3871                 if (changelink) {
3872                         NL_SET_ERR_MSG_ATTR(extack, tb[IFLA_MTU],
3873                                             "Cannot change mtu");
3874                         return -EOPNOTSUPP;
3875                 }
3876                 conf->mtu = nla_get_u32(tb[IFLA_MTU]);
3877         }
3878
3879         if (data[IFLA_VXLAN_DF])
3880                 conf->df = nla_get_u8(data[IFLA_VXLAN_DF]);
3881
3882         return 0;
3883 }
3884
3885 static int vxlan_newlink(struct net *src_net, struct net_device *dev,
3886                          struct nlattr *tb[], struct nlattr *data[],
3887                          struct netlink_ext_ack *extack)
3888 {
3889         struct vxlan_config conf;
3890         int err;
3891
3892         err = vxlan_nl2conf(tb, data, dev, &conf, false, extack);
3893         if (err)
3894                 return err;
3895
3896         return __vxlan_dev_create(src_net, dev, &conf, extack);
3897 }
3898
3899 static int vxlan_changelink(struct net_device *dev, struct nlattr *tb[],
3900                             struct nlattr *data[],
3901                             struct netlink_ext_ack *extack)
3902 {
3903         struct vxlan_dev *vxlan = netdev_priv(dev);
3904         struct vxlan_rdst *dst = &vxlan->default_dst;
3905         struct net_device *lowerdev;
3906         struct vxlan_config conf;
3907         int err;
3908
3909         err = vxlan_nl2conf(tb, data, dev, &conf, true, extack);
3910         if (err)
3911                 return err;
3912
3913         err = vxlan_config_validate(vxlan->net, &conf, &lowerdev,
3914                                     vxlan, extack);
3915         if (err)
3916                 return err;
3917
3918         /* handle default dst entry */
3919         if (!vxlan_addr_equal(&conf.remote_ip, &dst->remote_ip)) {
3920                 spin_lock_bh(&vxlan->hash_lock);
3921                 if (!vxlan_addr_any(&conf.remote_ip)) {
3922                         err = vxlan_fdb_update(vxlan, all_zeros_mac,
3923                                                &conf.remote_ip,
3924                                                NUD_REACHABLE | NUD_PERMANENT,
3925                                                NLM_F_APPEND | NLM_F_CREATE,
3926                                                vxlan->cfg.dst_port,
3927                                                conf.vni, conf.vni,
3928                                                conf.remote_ifindex,
3929                                                NTF_SELF, true, extack);
3930                         if (err) {
3931                                 spin_unlock_bh(&vxlan->hash_lock);
3932                                 return err;
3933                         }
3934                 }
3935                 if (!vxlan_addr_any(&dst->remote_ip))
3936                         __vxlan_fdb_delete(vxlan, all_zeros_mac,
3937                                            dst->remote_ip,
3938                                            vxlan->cfg.dst_port,
3939                                            dst->remote_vni,
3940                                            dst->remote_vni,
3941                                            dst->remote_ifindex,
3942                                            true);
3943                 spin_unlock_bh(&vxlan->hash_lock);
3944         }
3945
3946         if (conf.age_interval != vxlan->cfg.age_interval)
3947                 mod_timer(&vxlan->age_timer, jiffies);
3948
3949         vxlan_config_apply(dev, &conf, lowerdev, vxlan->net, true);
3950         return 0;
3951 }
3952
3953 static void vxlan_dellink(struct net_device *dev, struct list_head *head)
3954 {
3955         struct vxlan_dev *vxlan = netdev_priv(dev);
3956
3957         vxlan_flush(vxlan, true);
3958
3959         list_del(&vxlan->next);
3960         unregister_netdevice_queue(dev, head);
3961 }
3962
3963 static size_t vxlan_get_size(const struct net_device *dev)
3964 {
3965
3966         return nla_total_size(sizeof(__u32)) +  /* IFLA_VXLAN_ID */
3967                 nla_total_size(sizeof(struct in6_addr)) + /* IFLA_VXLAN_GROUP{6} */
3968                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_LINK */
3969                 nla_total_size(sizeof(struct in6_addr)) + /* IFLA_VXLAN_LOCAL{6} */
3970                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_TTL */
3971                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_TTL_INHERIT */
3972                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_TOS */
3973                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_DF */
3974                 nla_total_size(sizeof(__be32)) + /* IFLA_VXLAN_LABEL */
3975                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_LEARNING */
3976                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_PROXY */
3977                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_RSC */
3978                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_L2MISS */
3979                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_L3MISS */
3980                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_COLLECT_METADATA */
3981                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_AGEING */
3982                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_LIMIT */
3983                 nla_total_size(sizeof(struct ifla_vxlan_port_range)) +
3984                 nla_total_size(sizeof(__be16)) + /* IFLA_VXLAN_PORT */
3985                 nla_total_size(sizeof(__u8)) + /* IFLA_VXLAN_UDP_CSUM */
3986                 nla_total_size(sizeof(__u8)) + /* IFLA_VXLAN_UDP_ZERO_CSUM6_TX */
3987                 nla_total_size(sizeof(__u8)) + /* IFLA_VXLAN_UDP_ZERO_CSUM6_RX */
3988                 nla_total_size(sizeof(__u8)) + /* IFLA_VXLAN_REMCSUM_TX */
3989                 nla_total_size(sizeof(__u8)) + /* IFLA_VXLAN_REMCSUM_RX */
3990                 0;
3991 }
3992
3993 static int vxlan_fill_info(struct sk_buff *skb, const struct net_device *dev)
3994 {
3995         const struct vxlan_dev *vxlan = netdev_priv(dev);
3996         const struct vxlan_rdst *dst = &vxlan->default_dst;
3997         struct ifla_vxlan_port_range ports = {
3998                 .low =  htons(vxlan->cfg.port_min),
3999                 .high = htons(vxlan->cfg.port_max),
4000         };
4001
4002         if (nla_put_u32(skb, IFLA_VXLAN_ID, be32_to_cpu(dst->remote_vni)))
4003                 goto nla_put_failure;
4004
4005         if (!vxlan_addr_any(&dst->remote_ip)) {
4006                 if (dst->remote_ip.sa.sa_family == AF_INET) {
4007                         if (nla_put_in_addr(skb, IFLA_VXLAN_GROUP,
4008                                             dst->remote_ip.sin.sin_addr.s_addr))
4009                                 goto nla_put_failure;
4010 #if IS_ENABLED(CONFIG_IPV6)
4011                 } else {
4012                         if (nla_put_in6_addr(skb, IFLA_VXLAN_GROUP6,
4013                                              &dst->remote_ip.sin6.sin6_addr))
4014                                 goto nla_put_failure;
4015 #endif
4016                 }
4017         }
4018
4019         if (dst->remote_ifindex && nla_put_u32(skb, IFLA_VXLAN_LINK, dst->remote_ifindex))
4020                 goto nla_put_failure;
4021
4022         if (!vxlan_addr_any(&vxlan->cfg.saddr)) {
4023                 if (vxlan->cfg.saddr.sa.sa_family == AF_INET) {
4024                         if (nla_put_in_addr(skb, IFLA_VXLAN_LOCAL,
4025                                             vxlan->cfg.saddr.sin.sin_addr.s_addr))
4026                                 goto nla_put_failure;
4027 #if IS_ENABLED(CONFIG_IPV6)
4028                 } else {
4029                         if (nla_put_in6_addr(skb, IFLA_VXLAN_LOCAL6,
4030                                              &vxlan->cfg.saddr.sin6.sin6_addr))
4031                                 goto nla_put_failure;
4032 #endif
4033                 }
4034         }
4035
4036         if (nla_put_u8(skb, IFLA_VXLAN_TTL, vxlan->cfg.ttl) ||
4037             nla_put_u8(skb, IFLA_VXLAN_TTL_INHERIT,
4038                        !!(vxlan->cfg.flags & VXLAN_F_TTL_INHERIT)) ||
4039             nla_put_u8(skb, IFLA_VXLAN_TOS, vxlan->cfg.tos) ||
4040             nla_put_u8(skb, IFLA_VXLAN_DF, vxlan->cfg.df) ||
4041             nla_put_be32(skb, IFLA_VXLAN_LABEL, vxlan->cfg.label) ||
4042             nla_put_u8(skb, IFLA_VXLAN_LEARNING,
4043                         !!(vxlan->cfg.flags & VXLAN_F_LEARN)) ||
4044             nla_put_u8(skb, IFLA_VXLAN_PROXY,
4045                         !!(vxlan->cfg.flags & VXLAN_F_PROXY)) ||
4046             nla_put_u8(skb, IFLA_VXLAN_RSC,
4047                        !!(vxlan->cfg.flags & VXLAN_F_RSC)) ||
4048             nla_put_u8(skb, IFLA_VXLAN_L2MISS,
4049                         !!(vxlan->cfg.flags & VXLAN_F_L2MISS)) ||
4050             nla_put_u8(skb, IFLA_VXLAN_L3MISS,
4051                         !!(vxlan->cfg.flags & VXLAN_F_L3MISS)) ||
4052             nla_put_u8(skb, IFLA_VXLAN_COLLECT_METADATA,
4053                        !!(vxlan->cfg.flags & VXLAN_F_COLLECT_METADATA)) ||
4054             nla_put_u32(skb, IFLA_VXLAN_AGEING, vxlan->cfg.age_interval) ||
4055             nla_put_u32(skb, IFLA_VXLAN_LIMIT, vxlan->cfg.addrmax) ||
4056             nla_put_be16(skb, IFLA_VXLAN_PORT, vxlan->cfg.dst_port) ||
4057             nla_put_u8(skb, IFLA_VXLAN_UDP_CSUM,
4058                         !(vxlan->cfg.flags & VXLAN_F_UDP_ZERO_CSUM_TX)) ||
4059             nla_put_u8(skb, IFLA_VXLAN_UDP_ZERO_CSUM6_TX,
4060                         !!(vxlan->cfg.flags & VXLAN_F_UDP_ZERO_CSUM6_TX)) ||
4061             nla_put_u8(skb, IFLA_VXLAN_UDP_ZERO_CSUM6_RX,
4062                         !!(vxlan->cfg.flags & VXLAN_F_UDP_ZERO_CSUM6_RX)) ||
4063             nla_put_u8(skb, IFLA_VXLAN_REMCSUM_TX,
4064                         !!(vxlan->cfg.flags & VXLAN_F_REMCSUM_TX)) ||
4065             nla_put_u8(skb, IFLA_VXLAN_REMCSUM_RX,
4066                         !!(vxlan->cfg.flags & VXLAN_F_REMCSUM_RX)))
4067                 goto nla_put_failure;
4068
4069         if (nla_put(skb, IFLA_VXLAN_PORT_RANGE, sizeof(ports), &ports))
4070                 goto nla_put_failure;
4071
4072         if (vxlan->cfg.flags & VXLAN_F_GBP &&
4073             nla_put_flag(skb, IFLA_VXLAN_GBP))
4074                 goto nla_put_failure;
4075
4076         if (vxlan->cfg.flags & VXLAN_F_GPE &&
4077             nla_put_flag(skb, IFLA_VXLAN_GPE))
4078                 goto nla_put_failure;
4079
4080         if (vxlan->cfg.flags & VXLAN_F_REMCSUM_NOPARTIAL &&
4081             nla_put_flag(skb, IFLA_VXLAN_REMCSUM_NOPARTIAL))
4082                 goto nla_put_failure;
4083
4084         return 0;
4085
4086 nla_put_failure:
4087         return -EMSGSIZE;
4088 }
4089
4090 static struct net *vxlan_get_link_net(const struct net_device *dev)
4091 {
4092         struct vxlan_dev *vxlan = netdev_priv(dev);
4093
4094         return vxlan->net;
4095 }
4096
4097 static struct rtnl_link_ops vxlan_link_ops __read_mostly = {
4098         .kind           = "vxlan",
4099         .maxtype        = IFLA_VXLAN_MAX,
4100         .policy         = vxlan_policy,
4101         .priv_size      = sizeof(struct vxlan_dev),
4102         .setup          = vxlan_setup,
4103         .validate       = vxlan_validate,
4104         .newlink        = vxlan_newlink,
4105         .changelink     = vxlan_changelink,
4106         .dellink        = vxlan_dellink,
4107         .get_size       = vxlan_get_size,
4108         .fill_info      = vxlan_fill_info,
4109         .get_link_net   = vxlan_get_link_net,
4110 };
4111
4112 struct net_device *vxlan_dev_create(struct net *net, const char *name,
4113                                     u8 name_assign_type,
4114                                     struct vxlan_config *conf)
4115 {
4116         struct nlattr *tb[IFLA_MAX + 1];
4117         struct net_device *dev;
4118         int err;
4119
4120         memset(&tb, 0, sizeof(tb));
4121
4122         dev = rtnl_create_link(net, name, name_assign_type,
4123                                &vxlan_link_ops, tb, NULL);
4124         if (IS_ERR(dev))
4125                 return dev;
4126
4127         err = __vxlan_dev_create(net, dev, conf, NULL);
4128         if (err < 0) {
4129                 free_netdev(dev);
4130                 return ERR_PTR(err);
4131         }
4132
4133         err = rtnl_configure_link(dev, NULL);
4134         if (err < 0) {
4135                 LIST_HEAD(list_kill);
4136
4137                 vxlan_dellink(dev, &list_kill);
4138                 unregister_netdevice_many(&list_kill);
4139                 return ERR_PTR(err);
4140         }
4141
4142         return dev;
4143 }
4144 EXPORT_SYMBOL_GPL(vxlan_dev_create);
4145
4146 static void vxlan_handle_lowerdev_unregister(struct vxlan_net *vn,
4147                                              struct net_device *dev)
4148 {
4149         struct vxlan_dev *vxlan, *next;
4150         LIST_HEAD(list_kill);
4151
4152         list_for_each_entry_safe(vxlan, next, &vn->vxlan_list, next) {
4153                 struct vxlan_rdst *dst = &vxlan->default_dst;
4154
4155                 /* In case we created vxlan device with carrier
4156                  * and we loose the carrier due to module unload
4157                  * we also need to remove vxlan device. In other
4158                  * cases, it's not necessary and remote_ifindex
4159                  * is 0 here, so no matches.
4160                  */
4161                 if (dst->remote_ifindex == dev->ifindex)
4162                         vxlan_dellink(vxlan->dev, &list_kill);
4163         }
4164
4165         unregister_netdevice_many(&list_kill);
4166 }
4167
4168 static int vxlan_netdevice_event(struct notifier_block *unused,
4169                                  unsigned long event, void *ptr)
4170 {
4171         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
4172         struct vxlan_net *vn = net_generic(dev_net(dev), vxlan_net_id);
4173
4174         if (event == NETDEV_UNREGISTER) {
4175                 vxlan_offload_rx_ports(dev, false);
4176                 vxlan_handle_lowerdev_unregister(vn, dev);
4177         } else if (event == NETDEV_REGISTER) {
4178                 vxlan_offload_rx_ports(dev, true);
4179         } else if (event == NETDEV_UDP_TUNNEL_PUSH_INFO ||
4180                    event == NETDEV_UDP_TUNNEL_DROP_INFO) {
4181                 vxlan_offload_rx_ports(dev, event == NETDEV_UDP_TUNNEL_PUSH_INFO);
4182         }
4183
4184         return NOTIFY_DONE;
4185 }
4186
4187 static struct notifier_block vxlan_notifier_block __read_mostly = {
4188         .notifier_call = vxlan_netdevice_event,
4189 };
4190
4191 static void
4192 vxlan_fdb_offloaded_set(struct net_device *dev,
4193                         struct switchdev_notifier_vxlan_fdb_info *fdb_info)
4194 {
4195         struct vxlan_dev *vxlan = netdev_priv(dev);
4196         struct vxlan_rdst *rdst;
4197         struct vxlan_fdb *f;
4198
4199         spin_lock_bh(&vxlan->hash_lock);
4200
4201         f = vxlan_find_mac(vxlan, fdb_info->eth_addr, fdb_info->vni);
4202         if (!f)
4203                 goto out;
4204
4205         rdst = vxlan_fdb_find_rdst(f, &fdb_info->remote_ip,
4206                                    fdb_info->remote_port,
4207                                    fdb_info->remote_vni,
4208                                    fdb_info->remote_ifindex);
4209         if (!rdst)
4210                 goto out;
4211
4212         rdst->offloaded = fdb_info->offloaded;
4213
4214 out:
4215         spin_unlock_bh(&vxlan->hash_lock);
4216 }
4217
4218 static int
4219 vxlan_fdb_external_learn_add(struct net_device *dev,
4220                              struct switchdev_notifier_vxlan_fdb_info *fdb_info)
4221 {
4222         struct vxlan_dev *vxlan = netdev_priv(dev);
4223         struct netlink_ext_ack *extack;
4224         int err;
4225
4226         extack = switchdev_notifier_info_to_extack(&fdb_info->info);
4227
4228         spin_lock_bh(&vxlan->hash_lock);
4229         err = vxlan_fdb_update(vxlan, fdb_info->eth_addr, &fdb_info->remote_ip,
4230                                NUD_REACHABLE,
4231                                NLM_F_CREATE | NLM_F_REPLACE,
4232                                fdb_info->remote_port,
4233                                fdb_info->vni,
4234                                fdb_info->remote_vni,
4235                                fdb_info->remote_ifindex,
4236                                NTF_USE | NTF_SELF | NTF_EXT_LEARNED,
4237                                false, extack);
4238         spin_unlock_bh(&vxlan->hash_lock);
4239
4240         return err;
4241 }
4242
4243 static int
4244 vxlan_fdb_external_learn_del(struct net_device *dev,
4245                              struct switchdev_notifier_vxlan_fdb_info *fdb_info)
4246 {
4247         struct vxlan_dev *vxlan = netdev_priv(dev);
4248         struct vxlan_fdb *f;
4249         int err = 0;
4250
4251         spin_lock_bh(&vxlan->hash_lock);
4252
4253         f = vxlan_find_mac(vxlan, fdb_info->eth_addr, fdb_info->vni);
4254         if (!f)
4255                 err = -ENOENT;
4256         else if (f->flags & NTF_EXT_LEARNED)
4257                 err = __vxlan_fdb_delete(vxlan, fdb_info->eth_addr,
4258                                          fdb_info->remote_ip,
4259                                          fdb_info->remote_port,
4260                                          fdb_info->vni,
4261                                          fdb_info->remote_vni,
4262                                          fdb_info->remote_ifindex,
4263                                          false);
4264
4265         spin_unlock_bh(&vxlan->hash_lock);
4266
4267         return err;
4268 }
4269
4270 static int vxlan_switchdev_event(struct notifier_block *unused,
4271                                  unsigned long event, void *ptr)
4272 {
4273         struct net_device *dev = switchdev_notifier_info_to_dev(ptr);
4274         struct switchdev_notifier_vxlan_fdb_info *fdb_info;
4275         int err = 0;
4276
4277         switch (event) {
4278         case SWITCHDEV_VXLAN_FDB_OFFLOADED:
4279                 vxlan_fdb_offloaded_set(dev, ptr);
4280                 break;
4281         case SWITCHDEV_VXLAN_FDB_ADD_TO_BRIDGE:
4282                 fdb_info = ptr;
4283                 err = vxlan_fdb_external_learn_add(dev, fdb_info);
4284                 if (err) {
4285                         err = notifier_from_errno(err);
4286                         break;
4287                 }
4288                 fdb_info->offloaded = true;
4289                 vxlan_fdb_offloaded_set(dev, fdb_info);
4290                 break;
4291         case SWITCHDEV_VXLAN_FDB_DEL_TO_BRIDGE:
4292                 fdb_info = ptr;
4293                 err = vxlan_fdb_external_learn_del(dev, fdb_info);
4294                 if (err) {
4295                         err = notifier_from_errno(err);
4296                         break;
4297                 }
4298                 fdb_info->offloaded = false;
4299                 vxlan_fdb_offloaded_set(dev, fdb_info);
4300                 break;
4301         }
4302
4303         return err;
4304 }
4305
4306 static struct notifier_block vxlan_switchdev_notifier_block __read_mostly = {
4307         .notifier_call = vxlan_switchdev_event,
4308 };
4309
4310 static __net_init int vxlan_init_net(struct net *net)
4311 {
4312         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
4313         unsigned int h;
4314
4315         INIT_LIST_HEAD(&vn->vxlan_list);
4316         spin_lock_init(&vn->sock_lock);
4317
4318         for (h = 0; h < PORT_HASH_SIZE; ++h)
4319                 INIT_HLIST_HEAD(&vn->sock_list[h]);
4320
4321         return 0;
4322 }
4323
4324 static void vxlan_destroy_tunnels(struct net *net, struct list_head *head)
4325 {
4326         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
4327         struct vxlan_dev *vxlan, *next;
4328         struct net_device *dev, *aux;
4329         unsigned int h;
4330
4331         for_each_netdev_safe(net, dev, aux)
4332                 if (dev->rtnl_link_ops == &vxlan_link_ops)
4333                         unregister_netdevice_queue(dev, head);
4334
4335         list_for_each_entry_safe(vxlan, next, &vn->vxlan_list, next) {
4336                 /* If vxlan->dev is in the same netns, it has already been added
4337                  * to the list by the previous loop.
4338                  */
4339                 if (!net_eq(dev_net(vxlan->dev), net))
4340                         unregister_netdevice_queue(vxlan->dev, head);
4341         }
4342
4343         for (h = 0; h < PORT_HASH_SIZE; ++h)
4344                 WARN_ON_ONCE(!hlist_empty(&vn->sock_list[h]));
4345 }
4346
4347 static void __net_exit vxlan_exit_batch_net(struct list_head *net_list)
4348 {
4349         struct net *net;
4350         LIST_HEAD(list);
4351
4352         rtnl_lock();
4353         list_for_each_entry(net, net_list, exit_list)
4354                 vxlan_destroy_tunnels(net, &list);
4355
4356         unregister_netdevice_many(&list);
4357         rtnl_unlock();
4358 }
4359
4360 static struct pernet_operations vxlan_net_ops = {
4361         .init = vxlan_init_net,
4362         .exit_batch = vxlan_exit_batch_net,
4363         .id   = &vxlan_net_id,
4364         .size = sizeof(struct vxlan_net),
4365 };
4366
4367 static int __init vxlan_init_module(void)
4368 {
4369         int rc;
4370
4371         get_random_bytes(&vxlan_salt, sizeof(vxlan_salt));
4372
4373         rc = register_pernet_subsys(&vxlan_net_ops);
4374         if (rc)
4375                 goto out1;
4376
4377         rc = register_netdevice_notifier(&vxlan_notifier_block);
4378         if (rc)
4379                 goto out2;
4380
4381         rc = register_switchdev_notifier(&vxlan_switchdev_notifier_block);
4382         if (rc)
4383                 goto out3;
4384
4385         rc = rtnl_link_register(&vxlan_link_ops);
4386         if (rc)
4387                 goto out4;
4388
4389         return 0;
4390 out4:
4391         unregister_switchdev_notifier(&vxlan_switchdev_notifier_block);
4392 out3:
4393         unregister_netdevice_notifier(&vxlan_notifier_block);
4394 out2:
4395         unregister_pernet_subsys(&vxlan_net_ops);
4396 out1:
4397         return rc;
4398 }
4399 late_initcall(vxlan_init_module);
4400
4401 static void __exit vxlan_cleanup_module(void)
4402 {
4403         rtnl_link_unregister(&vxlan_link_ops);
4404         unregister_switchdev_notifier(&vxlan_switchdev_notifier_block);
4405         unregister_netdevice_notifier(&vxlan_notifier_block);
4406         unregister_pernet_subsys(&vxlan_net_ops);
4407         /* rcu_barrier() is called by netns */
4408 }
4409 module_exit(vxlan_cleanup_module);
4410
4411 MODULE_LICENSE("GPL");
4412 MODULE_VERSION(VXLAN_VERSION);
4413 MODULE_AUTHOR("Stephen Hemminger <stephen@networkplumber.org>");
4414 MODULE_DESCRIPTION("Driver for VXLAN encapsulated traffic");
4415 MODULE_ALIAS_RTNL_LINK("vxlan");