Merge tag 'backport/v3.14.24-ltsi-rc1/phy-rcar-gen2-usb-to-v3.15' into backport/v3...
[platform/adaptation/renesas_rcar/renesas_kernel.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/types.h>
15 #include <linux/module.h>
16 #include <linux/errno.h>
17 #include <linux/slab.h>
18 #include <linux/skbuff.h>
19 #include <linux/rculist.h>
20 #include <linux/netdevice.h>
21 #include <linux/in.h>
22 #include <linux/ip.h>
23 #include <linux/udp.h>
24 #include <linux/igmp.h>
25 #include <linux/etherdevice.h>
26 #include <linux/if_ether.h>
27 #include <linux/if_vlan.h>
28 #include <linux/hash.h>
29 #include <linux/ethtool.h>
30 #include <net/arp.h>
31 #include <net/ndisc.h>
32 #include <net/ip.h>
33 #include <net/ip_tunnels.h>
34 #include <net/icmp.h>
35 #include <net/udp.h>
36 #include <net/rtnetlink.h>
37 #include <net/route.h>
38 #include <net/dsfield.h>
39 #include <net/inet_ecn.h>
40 #include <net/net_namespace.h>
41 #include <net/netns/generic.h>
42 #include <net/vxlan.h>
43 #include <net/protocol.h>
44 #if IS_ENABLED(CONFIG_IPV6)
45 #include <net/ipv6.h>
46 #include <net/addrconf.h>
47 #include <net/ip6_tunnel.h>
48 #include <net/ip6_checksum.h>
49 #endif
50
51 #define VXLAN_VERSION   "0.1"
52
53 #define PORT_HASH_BITS  8
54 #define PORT_HASH_SIZE  (1<<PORT_HASH_BITS)
55 #define VNI_HASH_BITS   10
56 #define VNI_HASH_SIZE   (1<<VNI_HASH_BITS)
57 #define FDB_HASH_BITS   8
58 #define FDB_HASH_SIZE   (1<<FDB_HASH_BITS)
59 #define FDB_AGE_DEFAULT 300 /* 5 min */
60 #define FDB_AGE_INTERVAL (10 * HZ)      /* rescan interval */
61
62 #define VXLAN_N_VID     (1u << 24)
63 #define VXLAN_VID_MASK  (VXLAN_N_VID - 1)
64 #define VXLAN_HLEN (sizeof(struct udphdr) + sizeof(struct vxlanhdr))
65
66 #define VXLAN_FLAGS 0x08000000  /* struct vxlanhdr.vx_flags required value. */
67
68 /* VXLAN protocol header */
69 struct vxlanhdr {
70         __be32 vx_flags;
71         __be32 vx_vni;
72 };
73
74 /* UDP port for VXLAN traffic.
75  * The IANA assigned port is 4789, but the Linux default is 8472
76  * for compatibility with early adopters.
77  */
78 static unsigned short vxlan_port __read_mostly = 8472;
79 module_param_named(udp_port, vxlan_port, ushort, 0444);
80 MODULE_PARM_DESC(udp_port, "Destination UDP port");
81
82 static bool log_ecn_error = true;
83 module_param(log_ecn_error, bool, 0644);
84 MODULE_PARM_DESC(log_ecn_error, "Log packets received with corrupted ECN");
85
86 static int vxlan_net_id;
87
88 static const u8 all_zeros_mac[ETH_ALEN];
89
90 /* per-network namespace private data for this module */
91 struct vxlan_net {
92         struct list_head  vxlan_list;
93         struct hlist_head sock_list[PORT_HASH_SIZE];
94         spinlock_t        sock_lock;
95 };
96
97 union vxlan_addr {
98         struct sockaddr_in sin;
99         struct sockaddr_in6 sin6;
100         struct sockaddr sa;
101 };
102
103 struct vxlan_rdst {
104         union vxlan_addr         remote_ip;
105         __be16                   remote_port;
106         u32                      remote_vni;
107         u32                      remote_ifindex;
108         struct list_head         list;
109         struct rcu_head          rcu;
110 };
111
112 /* Forwarding table entry */
113 struct vxlan_fdb {
114         struct hlist_node hlist;        /* linked list of entries */
115         struct rcu_head   rcu;
116         unsigned long     updated;      /* jiffies */
117         unsigned long     used;
118         struct list_head  remotes;
119         u16               state;        /* see ndm_state */
120         u8                flags;        /* see ndm_flags */
121         u8                eth_addr[ETH_ALEN];
122 };
123
124 /* Pseudo network device */
125 struct vxlan_dev {
126         struct hlist_node hlist;        /* vni hash table */
127         struct list_head  next;         /* vxlan's per namespace list */
128         struct vxlan_sock *vn_sock;     /* listening socket */
129         struct net_device *dev;
130         struct vxlan_rdst default_dst;  /* default destination */
131         union vxlan_addr  saddr;        /* source address */
132         __be16            dst_port;
133         __u16             port_min;     /* source port range */
134         __u16             port_max;
135         __u8              tos;          /* TOS override */
136         __u8              ttl;
137         u32               flags;        /* VXLAN_F_* below */
138
139         struct work_struct sock_work;
140         struct work_struct igmp_join;
141         struct work_struct igmp_leave;
142
143         unsigned long     age_interval;
144         struct timer_list age_timer;
145         spinlock_t        hash_lock;
146         unsigned int      addrcnt;
147         unsigned int      addrmax;
148
149         struct hlist_head fdb_head[FDB_HASH_SIZE];
150 };
151
152 #define VXLAN_F_LEARN   0x01
153 #define VXLAN_F_PROXY   0x02
154 #define VXLAN_F_RSC     0x04
155 #define VXLAN_F_L2MISS  0x08
156 #define VXLAN_F_L3MISS  0x10
157 #define VXLAN_F_IPV6    0x20 /* internal flag */
158
159 /* salt for hash table */
160 static u32 vxlan_salt __read_mostly;
161 static struct workqueue_struct *vxlan_wq;
162
163 static void vxlan_sock_work(struct work_struct *work);
164
165 #if IS_ENABLED(CONFIG_IPV6)
166 static inline
167 bool vxlan_addr_equal(const union vxlan_addr *a, const union vxlan_addr *b)
168 {
169        if (a->sa.sa_family != b->sa.sa_family)
170                return false;
171        if (a->sa.sa_family == AF_INET6)
172                return ipv6_addr_equal(&a->sin6.sin6_addr, &b->sin6.sin6_addr);
173        else
174                return a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr;
175 }
176
177 static inline bool vxlan_addr_any(const union vxlan_addr *ipa)
178 {
179        if (ipa->sa.sa_family == AF_INET6)
180                return ipv6_addr_any(&ipa->sin6.sin6_addr);
181        else
182                return ipa->sin.sin_addr.s_addr == htonl(INADDR_ANY);
183 }
184
185 static inline bool vxlan_addr_multicast(const union vxlan_addr *ipa)
186 {
187        if (ipa->sa.sa_family == AF_INET6)
188                return ipv6_addr_is_multicast(&ipa->sin6.sin6_addr);
189        else
190                return IN_MULTICAST(ntohl(ipa->sin.sin_addr.s_addr));
191 }
192
193 static int vxlan_nla_get_addr(union vxlan_addr *ip, struct nlattr *nla)
194 {
195        if (nla_len(nla) >= sizeof(struct in6_addr)) {
196                nla_memcpy(&ip->sin6.sin6_addr, nla, sizeof(struct in6_addr));
197                ip->sa.sa_family = AF_INET6;
198                return 0;
199        } else if (nla_len(nla) >= sizeof(__be32)) {
200                ip->sin.sin_addr.s_addr = nla_get_be32(nla);
201                ip->sa.sa_family = AF_INET;
202                return 0;
203        } else {
204                return -EAFNOSUPPORT;
205        }
206 }
207
208 static int vxlan_nla_put_addr(struct sk_buff *skb, int attr,
209                              const union vxlan_addr *ip)
210 {
211        if (ip->sa.sa_family == AF_INET6)
212                return nla_put(skb, attr, sizeof(struct in6_addr), &ip->sin6.sin6_addr);
213        else
214                return nla_put_be32(skb, attr, ip->sin.sin_addr.s_addr);
215 }
216
217 #else /* !CONFIG_IPV6 */
218
219 static inline
220 bool vxlan_addr_equal(const union vxlan_addr *a, const union vxlan_addr *b)
221 {
222        return a->sin.sin_addr.s_addr == b->sin.sin_addr.s_addr;
223 }
224
225 static inline bool vxlan_addr_any(const union vxlan_addr *ipa)
226 {
227        return ipa->sin.sin_addr.s_addr == htonl(INADDR_ANY);
228 }
229
230 static inline bool vxlan_addr_multicast(const union vxlan_addr *ipa)
231 {
232        return IN_MULTICAST(ntohl(ipa->sin.sin_addr.s_addr));
233 }
234
235 static int vxlan_nla_get_addr(union vxlan_addr *ip, struct nlattr *nla)
236 {
237        if (nla_len(nla) >= sizeof(struct in6_addr)) {
238                return -EAFNOSUPPORT;
239        } else if (nla_len(nla) >= sizeof(__be32)) {
240                ip->sin.sin_addr.s_addr = nla_get_be32(nla);
241                ip->sa.sa_family = AF_INET;
242                return 0;
243        } else {
244                return -EAFNOSUPPORT;
245        }
246 }
247
248 static int vxlan_nla_put_addr(struct sk_buff *skb, int attr,
249                              const union vxlan_addr *ip)
250 {
251        return nla_put_be32(skb, attr, ip->sin.sin_addr.s_addr);
252 }
253 #endif
254
255 /* Virtual Network hash table head */
256 static inline struct hlist_head *vni_head(struct vxlan_sock *vs, u32 id)
257 {
258         return &vs->vni_list[hash_32(id, VNI_HASH_BITS)];
259 }
260
261 /* Socket hash table head */
262 static inline struct hlist_head *vs_head(struct net *net, __be16 port)
263 {
264         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
265
266         return &vn->sock_list[hash_32(ntohs(port), PORT_HASH_BITS)];
267 }
268
269 /* First remote destination for a forwarding entry.
270  * Guaranteed to be non-NULL because remotes are never deleted.
271  */
272 static inline struct vxlan_rdst *first_remote_rcu(struct vxlan_fdb *fdb)
273 {
274         return list_entry_rcu(fdb->remotes.next, struct vxlan_rdst, list);
275 }
276
277 static inline struct vxlan_rdst *first_remote_rtnl(struct vxlan_fdb *fdb)
278 {
279         return list_first_entry(&fdb->remotes, struct vxlan_rdst, list);
280 }
281
282 /* Find VXLAN socket based on network namespace, address family and UDP port */
283 static struct vxlan_sock *vxlan_find_sock(struct net *net,
284                                           sa_family_t family, __be16 port)
285 {
286         struct vxlan_sock *vs;
287
288         hlist_for_each_entry_rcu(vs, vs_head(net, port), hlist) {
289                 if (inet_sk(vs->sock->sk)->inet_sport == port &&
290                     inet_sk(vs->sock->sk)->sk.sk_family == family)
291                         return vs;
292         }
293         return NULL;
294 }
295
296 static struct vxlan_dev *vxlan_vs_find_vni(struct vxlan_sock *vs, u32 id)
297 {
298         struct vxlan_dev *vxlan;
299
300         hlist_for_each_entry_rcu(vxlan, vni_head(vs, id), hlist) {
301                 if (vxlan->default_dst.remote_vni == id)
302                         return vxlan;
303         }
304
305         return NULL;
306 }
307
308 /* Look up VNI in a per net namespace table */
309 static struct vxlan_dev *vxlan_find_vni(struct net *net, u32 id,
310                                         sa_family_t family, __be16 port)
311 {
312         struct vxlan_sock *vs;
313
314         vs = vxlan_find_sock(net, family, port);
315         if (!vs)
316                 return NULL;
317
318         return vxlan_vs_find_vni(vs, id);
319 }
320
321 /* Fill in neighbour message in skbuff. */
322 static int vxlan_fdb_info(struct sk_buff *skb, struct vxlan_dev *vxlan,
323                           const struct vxlan_fdb *fdb,
324                           u32 portid, u32 seq, int type, unsigned int flags,
325                           const struct vxlan_rdst *rdst)
326 {
327         unsigned long now = jiffies;
328         struct nda_cacheinfo ci;
329         struct nlmsghdr *nlh;
330         struct ndmsg *ndm;
331         bool send_ip, send_eth;
332
333         nlh = nlmsg_put(skb, portid, seq, type, sizeof(*ndm), flags);
334         if (nlh == NULL)
335                 return -EMSGSIZE;
336
337         ndm = nlmsg_data(nlh);
338         memset(ndm, 0, sizeof(*ndm));
339
340         send_eth = send_ip = true;
341
342         if (type == RTM_GETNEIGH) {
343                 ndm->ndm_family = AF_INET;
344                 send_ip = !vxlan_addr_any(&rdst->remote_ip);
345                 send_eth = !is_zero_ether_addr(fdb->eth_addr);
346         } else
347                 ndm->ndm_family = AF_BRIDGE;
348         ndm->ndm_state = fdb->state;
349         ndm->ndm_ifindex = vxlan->dev->ifindex;
350         ndm->ndm_flags = fdb->flags;
351         ndm->ndm_type = NDA_DST;
352
353         if (send_eth && nla_put(skb, NDA_LLADDR, ETH_ALEN, &fdb->eth_addr))
354                 goto nla_put_failure;
355
356         if (send_ip && vxlan_nla_put_addr(skb, NDA_DST, &rdst->remote_ip))
357                 goto nla_put_failure;
358
359         if (rdst->remote_port && rdst->remote_port != vxlan->dst_port &&
360             nla_put_be16(skb, NDA_PORT, rdst->remote_port))
361                 goto nla_put_failure;
362         if (rdst->remote_vni != vxlan->default_dst.remote_vni &&
363             nla_put_u32(skb, NDA_VNI, rdst->remote_vni))
364                 goto nla_put_failure;
365         if (rdst->remote_ifindex &&
366             nla_put_u32(skb, NDA_IFINDEX, rdst->remote_ifindex))
367                 goto nla_put_failure;
368
369         ci.ndm_used      = jiffies_to_clock_t(now - fdb->used);
370         ci.ndm_confirmed = 0;
371         ci.ndm_updated   = jiffies_to_clock_t(now - fdb->updated);
372         ci.ndm_refcnt    = 0;
373
374         if (nla_put(skb, NDA_CACHEINFO, sizeof(ci), &ci))
375                 goto nla_put_failure;
376
377         return nlmsg_end(skb, nlh);
378
379 nla_put_failure:
380         nlmsg_cancel(skb, nlh);
381         return -EMSGSIZE;
382 }
383
384 static inline size_t vxlan_nlmsg_size(void)
385 {
386         return NLMSG_ALIGN(sizeof(struct ndmsg))
387                 + nla_total_size(ETH_ALEN) /* NDA_LLADDR */
388                 + nla_total_size(sizeof(struct in6_addr)) /* NDA_DST */
389                 + nla_total_size(sizeof(__be16)) /* NDA_PORT */
390                 + nla_total_size(sizeof(__be32)) /* NDA_VNI */
391                 + nla_total_size(sizeof(__u32)) /* NDA_IFINDEX */
392                 + nla_total_size(sizeof(struct nda_cacheinfo));
393 }
394
395 static void vxlan_fdb_notify(struct vxlan_dev *vxlan,
396                              struct vxlan_fdb *fdb, int type)
397 {
398         struct net *net = dev_net(vxlan->dev);
399         struct sk_buff *skb;
400         int err = -ENOBUFS;
401
402         skb = nlmsg_new(vxlan_nlmsg_size(), GFP_ATOMIC);
403         if (skb == NULL)
404                 goto errout;
405
406         err = vxlan_fdb_info(skb, vxlan, fdb, 0, 0, type, 0,
407                              first_remote_rtnl(fdb));
408         if (err < 0) {
409                 /* -EMSGSIZE implies BUG in vxlan_nlmsg_size() */
410                 WARN_ON(err == -EMSGSIZE);
411                 kfree_skb(skb);
412                 goto errout;
413         }
414
415         rtnl_notify(skb, net, 0, RTNLGRP_NEIGH, NULL, GFP_ATOMIC);
416         return;
417 errout:
418         if (err < 0)
419                 rtnl_set_sk_err(net, RTNLGRP_NEIGH, err);
420 }
421
422 static void vxlan_ip_miss(struct net_device *dev, union vxlan_addr *ipa)
423 {
424         struct vxlan_dev *vxlan = netdev_priv(dev);
425         struct vxlan_fdb f = {
426                 .state = NUD_STALE,
427         };
428         struct vxlan_rdst remote = {
429                 .remote_ip = *ipa, /* goes to NDA_DST */
430                 .remote_vni = VXLAN_N_VID,
431         };
432
433         INIT_LIST_HEAD(&f.remotes);
434         list_add_rcu(&remote.list, &f.remotes);
435
436         vxlan_fdb_notify(vxlan, &f, RTM_GETNEIGH);
437 }
438
439 static void vxlan_fdb_miss(struct vxlan_dev *vxlan, const u8 eth_addr[ETH_ALEN])
440 {
441         struct vxlan_fdb f = {
442                 .state = NUD_STALE,
443         };
444
445         INIT_LIST_HEAD(&f.remotes);
446         memcpy(f.eth_addr, eth_addr, ETH_ALEN);
447
448         vxlan_fdb_notify(vxlan, &f, RTM_GETNEIGH);
449 }
450
451 /* Hash Ethernet address */
452 static u32 eth_hash(const unsigned char *addr)
453 {
454         u64 value = get_unaligned((u64 *)addr);
455
456         /* only want 6 bytes */
457 #ifdef __BIG_ENDIAN
458         value >>= 16;
459 #else
460         value <<= 16;
461 #endif
462         return hash_64(value, FDB_HASH_BITS);
463 }
464
465 /* Hash chain to use given mac address */
466 static inline struct hlist_head *vxlan_fdb_head(struct vxlan_dev *vxlan,
467                                                 const u8 *mac)
468 {
469         return &vxlan->fdb_head[eth_hash(mac)];
470 }
471
472 /* Look up Ethernet address in forwarding table */
473 static struct vxlan_fdb *__vxlan_find_mac(struct vxlan_dev *vxlan,
474                                         const u8 *mac)
475 {
476         struct hlist_head *head = vxlan_fdb_head(vxlan, mac);
477         struct vxlan_fdb *f;
478
479         hlist_for_each_entry_rcu(f, head, hlist) {
480                 if (ether_addr_equal(mac, f->eth_addr))
481                         return f;
482         }
483
484         return NULL;
485 }
486
487 static struct vxlan_fdb *vxlan_find_mac(struct vxlan_dev *vxlan,
488                                         const u8 *mac)
489 {
490         struct vxlan_fdb *f;
491
492         f = __vxlan_find_mac(vxlan, mac);
493         if (f)
494                 f->used = jiffies;
495
496         return f;
497 }
498
499 /* caller should hold vxlan->hash_lock */
500 static struct vxlan_rdst *vxlan_fdb_find_rdst(struct vxlan_fdb *f,
501                                               union vxlan_addr *ip, __be16 port,
502                                               __u32 vni, __u32 ifindex)
503 {
504         struct vxlan_rdst *rd;
505
506         list_for_each_entry(rd, &f->remotes, list) {
507                 if (vxlan_addr_equal(&rd->remote_ip, ip) &&
508                     rd->remote_port == port &&
509                     rd->remote_vni == vni &&
510                     rd->remote_ifindex == ifindex)
511                         return rd;
512         }
513
514         return NULL;
515 }
516
517 /* Replace destination of unicast mac */
518 static int vxlan_fdb_replace(struct vxlan_fdb *f,
519                              union vxlan_addr *ip, __be16 port, __u32 vni, __u32 ifindex)
520 {
521         struct vxlan_rdst *rd;
522
523         rd = vxlan_fdb_find_rdst(f, ip, port, vni, ifindex);
524         if (rd)
525                 return 0;
526
527         rd = list_first_entry_or_null(&f->remotes, struct vxlan_rdst, list);
528         if (!rd)
529                 return 0;
530         rd->remote_ip = *ip;
531         rd->remote_port = port;
532         rd->remote_vni = vni;
533         rd->remote_ifindex = ifindex;
534         return 1;
535 }
536
537 /* Add/update destinations for multicast */
538 static int vxlan_fdb_append(struct vxlan_fdb *f,
539                             union vxlan_addr *ip, __be16 port, __u32 vni, __u32 ifindex)
540 {
541         struct vxlan_rdst *rd;
542
543         rd = vxlan_fdb_find_rdst(f, ip, port, vni, ifindex);
544         if (rd)
545                 return 0;
546
547         rd = kmalloc(sizeof(*rd), GFP_ATOMIC);
548         if (rd == NULL)
549                 return -ENOBUFS;
550         rd->remote_ip = *ip;
551         rd->remote_port = port;
552         rd->remote_vni = vni;
553         rd->remote_ifindex = ifindex;
554
555         list_add_tail_rcu(&rd->list, &f->remotes);
556
557         return 1;
558 }
559
560 static struct sk_buff **vxlan_gro_receive(struct sk_buff **head, struct sk_buff *skb)
561 {
562         struct sk_buff *p, **pp = NULL;
563         struct vxlanhdr *vh, *vh2;
564         struct ethhdr *eh, *eh2;
565         unsigned int hlen, off_vx, off_eth;
566         const struct packet_offload *ptype;
567         __be16 type;
568         int flush = 1;
569
570         off_vx = skb_gro_offset(skb);
571         hlen = off_vx + sizeof(*vh);
572         vh   = skb_gro_header_fast(skb, off_vx);
573         if (skb_gro_header_hard(skb, hlen)) {
574                 vh = skb_gro_header_slow(skb, hlen, off_vx);
575                 if (unlikely(!vh))
576                         goto out;
577         }
578         skb_gro_pull(skb, sizeof(struct vxlanhdr)); /* pull vxlan header */
579
580         off_eth = skb_gro_offset(skb);
581         hlen = off_eth + sizeof(*eh);
582         eh   = skb_gro_header_fast(skb, off_eth);
583         if (skb_gro_header_hard(skb, hlen)) {
584                 eh = skb_gro_header_slow(skb, hlen, off_eth);
585                 if (unlikely(!eh))
586                         goto out;
587         }
588
589         flush = 0;
590
591         for (p = *head; p; p = p->next) {
592                 if (!NAPI_GRO_CB(p)->same_flow)
593                         continue;
594
595                 vh2 = (struct vxlanhdr *)(p->data + off_vx);
596                 eh2 = (struct ethhdr   *)(p->data + off_eth);
597                 if (vh->vx_vni != vh2->vx_vni || compare_ether_header(eh, eh2)) {
598                         NAPI_GRO_CB(p)->same_flow = 0;
599                         continue;
600                 }
601         }
602
603         type = eh->h_proto;
604
605         rcu_read_lock();
606         ptype = gro_find_receive_by_type(type);
607         if (ptype == NULL) {
608                 flush = 1;
609                 goto out_unlock;
610         }
611
612         skb_gro_pull(skb, sizeof(*eh)); /* pull inner eth header */
613         pp = ptype->callbacks.gro_receive(head, skb);
614
615 out_unlock:
616         rcu_read_unlock();
617 out:
618         NAPI_GRO_CB(skb)->flush |= flush;
619
620         return pp;
621 }
622
623 static int vxlan_gro_complete(struct sk_buff *skb, int nhoff)
624 {
625         struct ethhdr *eh;
626         struct packet_offload *ptype;
627         __be16 type;
628         int vxlan_len  = sizeof(struct vxlanhdr) + sizeof(struct ethhdr);
629         int err = -ENOSYS;
630
631         eh = (struct ethhdr *)(skb->data + nhoff + sizeof(struct vxlanhdr));
632         type = eh->h_proto;
633
634         rcu_read_lock();
635         ptype = gro_find_complete_by_type(type);
636         if (ptype != NULL)
637                 err = ptype->callbacks.gro_complete(skb, nhoff + vxlan_len);
638
639         rcu_read_unlock();
640         return err;
641 }
642
643 /* Notify netdevs that UDP port started listening */
644 static void vxlan_notify_add_rx_port(struct vxlan_sock *vs)
645 {
646         struct net_device *dev;
647         struct sock *sk = vs->sock->sk;
648         struct net *net = sock_net(sk);
649         sa_family_t sa_family = sk->sk_family;
650         __be16 port = inet_sk(sk)->inet_sport;
651         int err;
652
653         if (sa_family == AF_INET) {
654                 err = udp_add_offload(&vs->udp_offloads);
655                 if (err)
656                         pr_warn("vxlan: udp_add_offload failed with status %d\n", err);
657         }
658
659         rcu_read_lock();
660         for_each_netdev_rcu(net, dev) {
661                 if (dev->netdev_ops->ndo_add_vxlan_port)
662                         dev->netdev_ops->ndo_add_vxlan_port(dev, sa_family,
663                                                             port);
664         }
665         rcu_read_unlock();
666 }
667
668 /* Notify netdevs that UDP port is no more listening */
669 static void vxlan_notify_del_rx_port(struct vxlan_sock *vs)
670 {
671         struct net_device *dev;
672         struct sock *sk = vs->sock->sk;
673         struct net *net = sock_net(sk);
674         sa_family_t sa_family = sk->sk_family;
675         __be16 port = inet_sk(sk)->inet_sport;
676
677         rcu_read_lock();
678         for_each_netdev_rcu(net, dev) {
679                 if (dev->netdev_ops->ndo_del_vxlan_port)
680                         dev->netdev_ops->ndo_del_vxlan_port(dev, sa_family,
681                                                             port);
682         }
683         rcu_read_unlock();
684
685         if (sa_family == AF_INET)
686                 udp_del_offload(&vs->udp_offloads);
687 }
688
689 /* Add new entry to forwarding table -- assumes lock held */
690 static int vxlan_fdb_create(struct vxlan_dev *vxlan,
691                             const u8 *mac, union vxlan_addr *ip,
692                             __u16 state, __u16 flags,
693                             __be16 port, __u32 vni, __u32 ifindex,
694                             __u8 ndm_flags)
695 {
696         struct vxlan_fdb *f;
697         int notify = 0;
698
699         f = __vxlan_find_mac(vxlan, mac);
700         if (f) {
701                 if (flags & NLM_F_EXCL) {
702                         netdev_dbg(vxlan->dev,
703                                    "lost race to create %pM\n", mac);
704                         return -EEXIST;
705                 }
706                 if (f->state != state) {
707                         f->state = state;
708                         f->updated = jiffies;
709                         notify = 1;
710                 }
711                 if (f->flags != ndm_flags) {
712                         f->flags = ndm_flags;
713                         f->updated = jiffies;
714                         notify = 1;
715                 }
716                 if ((flags & NLM_F_REPLACE)) {
717                         /* Only change unicasts */
718                         if (!(is_multicast_ether_addr(f->eth_addr) ||
719                              is_zero_ether_addr(f->eth_addr))) {
720                                 int rc = vxlan_fdb_replace(f, ip, port, vni,
721                                                            ifindex);
722
723                                 if (rc < 0)
724                                         return rc;
725                                 notify |= rc;
726                         } else
727                                 return -EOPNOTSUPP;
728                 }
729                 if ((flags & NLM_F_APPEND) &&
730                     (is_multicast_ether_addr(f->eth_addr) ||
731                      is_zero_ether_addr(f->eth_addr))) {
732                         int rc = vxlan_fdb_append(f, ip, port, vni, ifindex);
733
734                         if (rc < 0)
735                                 return rc;
736                         notify |= rc;
737                 }
738         } else {
739                 if (!(flags & NLM_F_CREATE))
740                         return -ENOENT;
741
742                 if (vxlan->addrmax && vxlan->addrcnt >= vxlan->addrmax)
743                         return -ENOSPC;
744
745                 /* Disallow replace to add a multicast entry */
746                 if ((flags & NLM_F_REPLACE) &&
747                     (is_multicast_ether_addr(mac) || is_zero_ether_addr(mac)))
748                         return -EOPNOTSUPP;
749
750                 netdev_dbg(vxlan->dev, "add %pM -> %pIS\n", mac, ip);
751                 f = kmalloc(sizeof(*f), GFP_ATOMIC);
752                 if (!f)
753                         return -ENOMEM;
754
755                 notify = 1;
756                 f->state = state;
757                 f->flags = ndm_flags;
758                 f->updated = f->used = jiffies;
759                 INIT_LIST_HEAD(&f->remotes);
760                 memcpy(f->eth_addr, mac, ETH_ALEN);
761
762                 vxlan_fdb_append(f, ip, port, vni, ifindex);
763
764                 ++vxlan->addrcnt;
765                 hlist_add_head_rcu(&f->hlist,
766                                    vxlan_fdb_head(vxlan, mac));
767         }
768
769         if (notify)
770                 vxlan_fdb_notify(vxlan, f, RTM_NEWNEIGH);
771
772         return 0;
773 }
774
775 static void vxlan_fdb_free(struct rcu_head *head)
776 {
777         struct vxlan_fdb *f = container_of(head, struct vxlan_fdb, rcu);
778         struct vxlan_rdst *rd, *nd;
779
780         list_for_each_entry_safe(rd, nd, &f->remotes, list)
781                 kfree(rd);
782         kfree(f);
783 }
784
785 static void vxlan_fdb_destroy(struct vxlan_dev *vxlan, struct vxlan_fdb *f)
786 {
787         netdev_dbg(vxlan->dev,
788                     "delete %pM\n", f->eth_addr);
789
790         --vxlan->addrcnt;
791         vxlan_fdb_notify(vxlan, f, RTM_DELNEIGH);
792
793         hlist_del_rcu(&f->hlist);
794         call_rcu(&f->rcu, vxlan_fdb_free);
795 }
796
797 static int vxlan_fdb_parse(struct nlattr *tb[], struct vxlan_dev *vxlan,
798                            union vxlan_addr *ip, __be16 *port, u32 *vni, u32 *ifindex)
799 {
800         struct net *net = dev_net(vxlan->dev);
801         int err;
802
803         if (tb[NDA_DST]) {
804                 err = vxlan_nla_get_addr(ip, tb[NDA_DST]);
805                 if (err)
806                         return err;
807         } else {
808                 union vxlan_addr *remote = &vxlan->default_dst.remote_ip;
809                 if (remote->sa.sa_family == AF_INET) {
810                         ip->sin.sin_addr.s_addr = htonl(INADDR_ANY);
811                         ip->sa.sa_family = AF_INET;
812 #if IS_ENABLED(CONFIG_IPV6)
813                 } else {
814                         ip->sin6.sin6_addr = in6addr_any;
815                         ip->sa.sa_family = AF_INET6;
816 #endif
817                 }
818         }
819
820         if (tb[NDA_PORT]) {
821                 if (nla_len(tb[NDA_PORT]) != sizeof(__be16))
822                         return -EINVAL;
823                 *port = nla_get_be16(tb[NDA_PORT]);
824         } else {
825                 *port = vxlan->dst_port;
826         }
827
828         if (tb[NDA_VNI]) {
829                 if (nla_len(tb[NDA_VNI]) != sizeof(u32))
830                         return -EINVAL;
831                 *vni = nla_get_u32(tb[NDA_VNI]);
832         } else {
833                 *vni = vxlan->default_dst.remote_vni;
834         }
835
836         if (tb[NDA_IFINDEX]) {
837                 struct net_device *tdev;
838
839                 if (nla_len(tb[NDA_IFINDEX]) != sizeof(u32))
840                         return -EINVAL;
841                 *ifindex = nla_get_u32(tb[NDA_IFINDEX]);
842                 tdev = __dev_get_by_index(net, *ifindex);
843                 if (!tdev)
844                         return -EADDRNOTAVAIL;
845         } else {
846                 *ifindex = 0;
847         }
848
849         return 0;
850 }
851
852 /* Add static entry (via netlink) */
853 static int vxlan_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
854                          struct net_device *dev,
855                          const unsigned char *addr, u16 flags)
856 {
857         struct vxlan_dev *vxlan = netdev_priv(dev);
858         /* struct net *net = dev_net(vxlan->dev); */
859         union vxlan_addr ip;
860         __be16 port;
861         u32 vni, ifindex;
862         int err;
863
864         if (!(ndm->ndm_state & (NUD_PERMANENT|NUD_REACHABLE))) {
865                 pr_info("RTM_NEWNEIGH with invalid state %#x\n",
866                         ndm->ndm_state);
867                 return -EINVAL;
868         }
869
870         if (tb[NDA_DST] == NULL)
871                 return -EINVAL;
872
873         err = vxlan_fdb_parse(tb, vxlan, &ip, &port, &vni, &ifindex);
874         if (err)
875                 return err;
876
877         if (vxlan->default_dst.remote_ip.sa.sa_family != ip.sa.sa_family)
878                 return -EAFNOSUPPORT;
879
880         spin_lock_bh(&vxlan->hash_lock);
881         err = vxlan_fdb_create(vxlan, addr, &ip, ndm->ndm_state, flags,
882                                port, vni, ifindex, ndm->ndm_flags);
883         spin_unlock_bh(&vxlan->hash_lock);
884
885         return err;
886 }
887
888 /* Delete entry (via netlink) */
889 static int vxlan_fdb_delete(struct ndmsg *ndm, struct nlattr *tb[],
890                             struct net_device *dev,
891                             const unsigned char *addr)
892 {
893         struct vxlan_dev *vxlan = netdev_priv(dev);
894         struct vxlan_fdb *f;
895         struct vxlan_rdst *rd = NULL;
896         union vxlan_addr ip;
897         __be16 port;
898         u32 vni, ifindex;
899         int err;
900
901         err = vxlan_fdb_parse(tb, vxlan, &ip, &port, &vni, &ifindex);
902         if (err)
903                 return err;
904
905         err = -ENOENT;
906
907         spin_lock_bh(&vxlan->hash_lock);
908         f = vxlan_find_mac(vxlan, addr);
909         if (!f)
910                 goto out;
911
912         if (!vxlan_addr_any(&ip)) {
913                 rd = vxlan_fdb_find_rdst(f, &ip, port, vni, ifindex);
914                 if (!rd)
915                         goto out;
916         }
917
918         err = 0;
919
920         /* remove a destination if it's not the only one on the list,
921          * otherwise destroy the fdb entry
922          */
923         if (rd && !list_is_singular(&f->remotes)) {
924                 list_del_rcu(&rd->list);
925                 kfree_rcu(rd, rcu);
926                 goto out;
927         }
928
929         vxlan_fdb_destroy(vxlan, f);
930
931 out:
932         spin_unlock_bh(&vxlan->hash_lock);
933
934         return err;
935 }
936
937 /* Dump forwarding table */
938 static int vxlan_fdb_dump(struct sk_buff *skb, struct netlink_callback *cb,
939                           struct net_device *dev, int idx)
940 {
941         struct vxlan_dev *vxlan = netdev_priv(dev);
942         unsigned int h;
943
944         for (h = 0; h < FDB_HASH_SIZE; ++h) {
945                 struct vxlan_fdb *f;
946                 int err;
947
948                 hlist_for_each_entry_rcu(f, &vxlan->fdb_head[h], hlist) {
949                         struct vxlan_rdst *rd;
950
951                         if (idx < cb->args[0])
952                                 goto skip;
953
954                         list_for_each_entry_rcu(rd, &f->remotes, list) {
955                                 err = vxlan_fdb_info(skb, vxlan, f,
956                                                      NETLINK_CB(cb->skb).portid,
957                                                      cb->nlh->nlmsg_seq,
958                                                      RTM_NEWNEIGH,
959                                                      NLM_F_MULTI, rd);
960                                 if (err < 0)
961                                         goto out;
962                         }
963 skip:
964                         ++idx;
965                 }
966         }
967 out:
968         return idx;
969 }
970
971 /* Watch incoming packets to learn mapping between Ethernet address
972  * and Tunnel endpoint.
973  * Return true if packet is bogus and should be droppped.
974  */
975 static bool vxlan_snoop(struct net_device *dev,
976                         union vxlan_addr *src_ip, const u8 *src_mac)
977 {
978         struct vxlan_dev *vxlan = netdev_priv(dev);
979         struct vxlan_fdb *f;
980
981         f = vxlan_find_mac(vxlan, src_mac);
982         if (likely(f)) {
983                 struct vxlan_rdst *rdst = first_remote_rcu(f);
984
985                 if (likely(vxlan_addr_equal(&rdst->remote_ip, src_ip)))
986                         return false;
987
988                 /* Don't migrate static entries, drop packets */
989                 if (f->state & NUD_NOARP)
990                         return true;
991
992                 if (net_ratelimit())
993                         netdev_info(dev,
994                                     "%pM migrated from %pIS to %pIS\n",
995                                     src_mac, &rdst->remote_ip, &src_ip);
996
997                 rdst->remote_ip = *src_ip;
998                 f->updated = jiffies;
999                 vxlan_fdb_notify(vxlan, f, RTM_NEWNEIGH);
1000         } else {
1001                 /* learned new entry */
1002                 spin_lock(&vxlan->hash_lock);
1003
1004                 /* close off race between vxlan_flush and incoming packets */
1005                 if (netif_running(dev))
1006                         vxlan_fdb_create(vxlan, src_mac, src_ip,
1007                                          NUD_REACHABLE,
1008                                          NLM_F_EXCL|NLM_F_CREATE,
1009                                          vxlan->dst_port,
1010                                          vxlan->default_dst.remote_vni,
1011                                          0, NTF_SELF);
1012                 spin_unlock(&vxlan->hash_lock);
1013         }
1014
1015         return false;
1016 }
1017
1018 /* See if multicast group is already in use by other ID */
1019 static bool vxlan_group_used(struct vxlan_net *vn, struct vxlan_dev *dev)
1020 {
1021         struct vxlan_dev *vxlan;
1022
1023         /* The vxlan_sock is only used by dev, leaving group has
1024          * no effect on other vxlan devices.
1025          */
1026         if (atomic_read(&dev->vn_sock->refcnt) == 1)
1027                 return false;
1028
1029         list_for_each_entry(vxlan, &vn->vxlan_list, next) {
1030                 if (!netif_running(vxlan->dev) || vxlan == dev)
1031                         continue;
1032
1033                 if (vxlan->vn_sock != dev->vn_sock)
1034                         continue;
1035
1036                 if (!vxlan_addr_equal(&vxlan->default_dst.remote_ip,
1037                                       &dev->default_dst.remote_ip))
1038                         continue;
1039
1040                 if (vxlan->default_dst.remote_ifindex !=
1041                     dev->default_dst.remote_ifindex)
1042                         continue;
1043
1044                 return true;
1045         }
1046
1047         return false;
1048 }
1049
1050 static void vxlan_sock_hold(struct vxlan_sock *vs)
1051 {
1052         atomic_inc(&vs->refcnt);
1053 }
1054
1055 void vxlan_sock_release(struct vxlan_sock *vs)
1056 {
1057         struct sock *sk = vs->sock->sk;
1058         struct net *net = sock_net(sk);
1059         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
1060
1061         if (!atomic_dec_and_test(&vs->refcnt))
1062                 return;
1063
1064         spin_lock(&vn->sock_lock);
1065         hlist_del_rcu(&vs->hlist);
1066         rcu_assign_sk_user_data(vs->sock->sk, NULL);
1067         vxlan_notify_del_rx_port(vs);
1068         spin_unlock(&vn->sock_lock);
1069
1070         queue_work(vxlan_wq, &vs->del_work);
1071 }
1072 EXPORT_SYMBOL_GPL(vxlan_sock_release);
1073
1074 /* Callback to update multicast group membership when first VNI on
1075  * multicast asddress is brought up
1076  * Done as workqueue because ip_mc_join_group acquires RTNL.
1077  */
1078 static void vxlan_igmp_join(struct work_struct *work)
1079 {
1080         struct vxlan_dev *vxlan = container_of(work, struct vxlan_dev, igmp_join);
1081         struct vxlan_sock *vs = vxlan->vn_sock;
1082         struct sock *sk = vs->sock->sk;
1083         union vxlan_addr *ip = &vxlan->default_dst.remote_ip;
1084         int ifindex = vxlan->default_dst.remote_ifindex;
1085
1086         lock_sock(sk);
1087         if (ip->sa.sa_family == AF_INET) {
1088                 struct ip_mreqn mreq = {
1089                         .imr_multiaddr.s_addr   = ip->sin.sin_addr.s_addr,
1090                         .imr_ifindex            = ifindex,
1091                 };
1092
1093                 ip_mc_join_group(sk, &mreq);
1094 #if IS_ENABLED(CONFIG_IPV6)
1095         } else {
1096                 ipv6_stub->ipv6_sock_mc_join(sk, ifindex,
1097                                              &ip->sin6.sin6_addr);
1098 #endif
1099         }
1100         release_sock(sk);
1101
1102         vxlan_sock_release(vs);
1103         dev_put(vxlan->dev);
1104 }
1105
1106 /* Inverse of vxlan_igmp_join when last VNI is brought down */
1107 static void vxlan_igmp_leave(struct work_struct *work)
1108 {
1109         struct vxlan_dev *vxlan = container_of(work, struct vxlan_dev, igmp_leave);
1110         struct vxlan_sock *vs = vxlan->vn_sock;
1111         struct sock *sk = vs->sock->sk;
1112         union vxlan_addr *ip = &vxlan->default_dst.remote_ip;
1113         int ifindex = vxlan->default_dst.remote_ifindex;
1114
1115         lock_sock(sk);
1116         if (ip->sa.sa_family == AF_INET) {
1117                 struct ip_mreqn mreq = {
1118                         .imr_multiaddr.s_addr   = ip->sin.sin_addr.s_addr,
1119                         .imr_ifindex            = ifindex,
1120                 };
1121
1122                 ip_mc_leave_group(sk, &mreq);
1123 #if IS_ENABLED(CONFIG_IPV6)
1124         } else {
1125                 ipv6_stub->ipv6_sock_mc_drop(sk, ifindex,
1126                                              &ip->sin6.sin6_addr);
1127 #endif
1128         }
1129
1130         release_sock(sk);
1131
1132         vxlan_sock_release(vs);
1133         dev_put(vxlan->dev);
1134 }
1135
1136 /* Callback from net/ipv4/udp.c to receive packets */
1137 static int vxlan_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
1138 {
1139         struct vxlan_sock *vs;
1140         struct vxlanhdr *vxh;
1141         __be16 port;
1142
1143         /* Need Vxlan and inner Ethernet header to be present */
1144         if (!pskb_may_pull(skb, VXLAN_HLEN))
1145                 goto error;
1146
1147         /* Return packets with reserved bits set */
1148         vxh = (struct vxlanhdr *)(udp_hdr(skb) + 1);
1149         if (vxh->vx_flags != htonl(VXLAN_FLAGS) ||
1150             (vxh->vx_vni & htonl(0xff))) {
1151                 netdev_dbg(skb->dev, "invalid vxlan flags=%#x vni=%#x\n",
1152                            ntohl(vxh->vx_flags), ntohl(vxh->vx_vni));
1153                 goto error;
1154         }
1155
1156         if (iptunnel_pull_header(skb, VXLAN_HLEN, htons(ETH_P_TEB)))
1157                 goto drop;
1158
1159         port = inet_sk(sk)->inet_sport;
1160
1161         vs = rcu_dereference_sk_user_data(sk);
1162         if (!vs)
1163                 goto drop;
1164
1165         /* If the NIC driver gave us an encapsulated packet
1166          * with the encapsulation mark, the device checksummed it
1167          * for us. Otherwise force the upper layers to verify it.
1168          */
1169         if ((skb->ip_summed != CHECKSUM_UNNECESSARY && skb->ip_summed != CHECKSUM_PARTIAL) ||
1170             !skb->encapsulation)
1171                 skb->ip_summed = CHECKSUM_NONE;
1172
1173         skb->encapsulation = 0;
1174
1175         vs->rcv(vs, skb, vxh->vx_vni);
1176         return 0;
1177
1178 drop:
1179         /* Consume bad packet */
1180         kfree_skb(skb);
1181         return 0;
1182
1183 error:
1184         /* Return non vxlan pkt */
1185         return 1;
1186 }
1187
1188 static void vxlan_rcv(struct vxlan_sock *vs,
1189                       struct sk_buff *skb, __be32 vx_vni)
1190 {
1191         struct iphdr *oip = NULL;
1192         struct ipv6hdr *oip6 = NULL;
1193         struct vxlan_dev *vxlan;
1194         struct pcpu_sw_netstats *stats;
1195         union vxlan_addr saddr;
1196         __u32 vni;
1197         int err = 0;
1198         union vxlan_addr *remote_ip;
1199
1200         vni = ntohl(vx_vni) >> 8;
1201         /* Is this VNI defined? */
1202         vxlan = vxlan_vs_find_vni(vs, vni);
1203         if (!vxlan)
1204                 goto drop;
1205
1206         remote_ip = &vxlan->default_dst.remote_ip;
1207         skb_reset_mac_header(skb);
1208         skb->protocol = eth_type_trans(skb, vxlan->dev);
1209
1210         /* Ignore packet loops (and multicast echo) */
1211         if (ether_addr_equal(eth_hdr(skb)->h_source, vxlan->dev->dev_addr))
1212                 goto drop;
1213
1214         /* Re-examine inner Ethernet packet */
1215         if (remote_ip->sa.sa_family == AF_INET) {
1216                 oip = ip_hdr(skb);
1217                 saddr.sin.sin_addr.s_addr = oip->saddr;
1218                 saddr.sa.sa_family = AF_INET;
1219 #if IS_ENABLED(CONFIG_IPV6)
1220         } else {
1221                 oip6 = ipv6_hdr(skb);
1222                 saddr.sin6.sin6_addr = oip6->saddr;
1223                 saddr.sa.sa_family = AF_INET6;
1224 #endif
1225         }
1226
1227         if ((vxlan->flags & VXLAN_F_LEARN) &&
1228             vxlan_snoop(skb->dev, &saddr, eth_hdr(skb)->h_source))
1229                 goto drop;
1230
1231         skb_reset_network_header(skb);
1232
1233         if (oip6)
1234                 err = IP6_ECN_decapsulate(oip6, skb);
1235         if (oip)
1236                 err = IP_ECN_decapsulate(oip, skb);
1237
1238         if (unlikely(err)) {
1239                 if (log_ecn_error) {
1240                         if (oip6)
1241                                 net_info_ratelimited("non-ECT from %pI6\n",
1242                                                      &oip6->saddr);
1243                         if (oip)
1244                                 net_info_ratelimited("non-ECT from %pI4 with TOS=%#x\n",
1245                                                      &oip->saddr, oip->tos);
1246                 }
1247                 if (err > 1) {
1248                         ++vxlan->dev->stats.rx_frame_errors;
1249                         ++vxlan->dev->stats.rx_errors;
1250                         goto drop;
1251                 }
1252         }
1253
1254         stats = this_cpu_ptr(vxlan->dev->tstats);
1255         u64_stats_update_begin(&stats->syncp);
1256         stats->rx_packets++;
1257         stats->rx_bytes += skb->len;
1258         u64_stats_update_end(&stats->syncp);
1259
1260         netif_rx(skb);
1261
1262         return;
1263 drop:
1264         /* Consume bad packet */
1265         kfree_skb(skb);
1266 }
1267
1268 static int arp_reduce(struct net_device *dev, struct sk_buff *skb)
1269 {
1270         struct vxlan_dev *vxlan = netdev_priv(dev);
1271         struct arphdr *parp;
1272         u8 *arpptr, *sha;
1273         __be32 sip, tip;
1274         struct neighbour *n;
1275
1276         if (dev->flags & IFF_NOARP)
1277                 goto out;
1278
1279         if (!pskb_may_pull(skb, arp_hdr_len(dev))) {
1280                 dev->stats.tx_dropped++;
1281                 goto out;
1282         }
1283         parp = arp_hdr(skb);
1284
1285         if ((parp->ar_hrd != htons(ARPHRD_ETHER) &&
1286              parp->ar_hrd != htons(ARPHRD_IEEE802)) ||
1287             parp->ar_pro != htons(ETH_P_IP) ||
1288             parp->ar_op != htons(ARPOP_REQUEST) ||
1289             parp->ar_hln != dev->addr_len ||
1290             parp->ar_pln != 4)
1291                 goto out;
1292         arpptr = (u8 *)parp + sizeof(struct arphdr);
1293         sha = arpptr;
1294         arpptr += dev->addr_len;        /* sha */
1295         memcpy(&sip, arpptr, sizeof(sip));
1296         arpptr += sizeof(sip);
1297         arpptr += dev->addr_len;        /* tha */
1298         memcpy(&tip, arpptr, sizeof(tip));
1299
1300         if (ipv4_is_loopback(tip) ||
1301             ipv4_is_multicast(tip))
1302                 goto out;
1303
1304         n = neigh_lookup(&arp_tbl, &tip, dev);
1305
1306         if (n) {
1307                 struct vxlan_fdb *f;
1308                 struct sk_buff  *reply;
1309
1310                 if (!(n->nud_state & NUD_CONNECTED)) {
1311                         neigh_release(n);
1312                         goto out;
1313                 }
1314
1315                 f = vxlan_find_mac(vxlan, n->ha);
1316                 if (f && vxlan_addr_any(&(first_remote_rcu(f)->remote_ip))) {
1317                         /* bridge-local neighbor */
1318                         neigh_release(n);
1319                         goto out;
1320                 }
1321
1322                 reply = arp_create(ARPOP_REPLY, ETH_P_ARP, sip, dev, tip, sha,
1323                                 n->ha, sha);
1324
1325                 neigh_release(n);
1326
1327                 if (reply == NULL)
1328                         goto out;
1329
1330                 skb_reset_mac_header(reply);
1331                 __skb_pull(reply, skb_network_offset(reply));
1332                 reply->ip_summed = CHECKSUM_UNNECESSARY;
1333                 reply->pkt_type = PACKET_HOST;
1334
1335                 if (netif_rx_ni(reply) == NET_RX_DROP)
1336                         dev->stats.rx_dropped++;
1337         } else if (vxlan->flags & VXLAN_F_L3MISS) {
1338                 union vxlan_addr ipa = {
1339                         .sin.sin_addr.s_addr = tip,
1340                         .sin.sin_family = AF_INET,
1341                 };
1342
1343                 vxlan_ip_miss(dev, &ipa);
1344         }
1345 out:
1346         consume_skb(skb);
1347         return NETDEV_TX_OK;
1348 }
1349
1350 #if IS_ENABLED(CONFIG_IPV6)
1351
1352 static struct sk_buff *vxlan_na_create(struct sk_buff *request,
1353         struct neighbour *n, bool isrouter)
1354 {
1355         struct net_device *dev = request->dev;
1356         struct sk_buff *reply;
1357         struct nd_msg *ns, *na;
1358         struct ipv6hdr *pip6;
1359         u8 *daddr;
1360         int na_olen = 8; /* opt hdr + ETH_ALEN for target */
1361         int ns_olen;
1362         int i, len;
1363
1364         if (dev == NULL)
1365                 return NULL;
1366
1367         len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) +
1368                 sizeof(*na) + na_olen + dev->needed_tailroom;
1369         reply = alloc_skb(len, GFP_ATOMIC);
1370         if (reply == NULL)
1371                 return NULL;
1372
1373         reply->protocol = htons(ETH_P_IPV6);
1374         reply->dev = dev;
1375         skb_reserve(reply, LL_RESERVED_SPACE(request->dev));
1376         skb_push(reply, sizeof(struct ethhdr));
1377         skb_set_mac_header(reply, 0);
1378
1379         ns = (struct nd_msg *)skb_transport_header(request);
1380
1381         daddr = eth_hdr(request)->h_source;
1382         ns_olen = request->len - skb_transport_offset(request) - sizeof(*ns);
1383         for (i = 0; i < ns_olen-1; i += (ns->opt[i+1]<<3)) {
1384                 if (ns->opt[i] == ND_OPT_SOURCE_LL_ADDR) {
1385                         daddr = ns->opt + i + sizeof(struct nd_opt_hdr);
1386                         break;
1387                 }
1388         }
1389
1390         /* Ethernet header */
1391         ether_addr_copy(eth_hdr(reply)->h_dest, daddr);
1392         ether_addr_copy(eth_hdr(reply)->h_source, n->ha);
1393         eth_hdr(reply)->h_proto = htons(ETH_P_IPV6);
1394         reply->protocol = htons(ETH_P_IPV6);
1395
1396         skb_pull(reply, sizeof(struct ethhdr));
1397         skb_set_network_header(reply, 0);
1398         skb_put(reply, sizeof(struct ipv6hdr));
1399
1400         /* IPv6 header */
1401
1402         pip6 = ipv6_hdr(reply);
1403         memset(pip6, 0, sizeof(struct ipv6hdr));
1404         pip6->version = 6;
1405         pip6->priority = ipv6_hdr(request)->priority;
1406         pip6->nexthdr = IPPROTO_ICMPV6;
1407         pip6->hop_limit = 255;
1408         pip6->daddr = ipv6_hdr(request)->saddr;
1409         pip6->saddr = *(struct in6_addr *)n->primary_key;
1410
1411         skb_pull(reply, sizeof(struct ipv6hdr));
1412         skb_set_transport_header(reply, 0);
1413
1414         na = (struct nd_msg *)skb_put(reply, sizeof(*na) + na_olen);
1415
1416         /* Neighbor Advertisement */
1417         memset(na, 0, sizeof(*na)+na_olen);
1418         na->icmph.icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT;
1419         na->icmph.icmp6_router = isrouter;
1420         na->icmph.icmp6_override = 1;
1421         na->icmph.icmp6_solicited = 1;
1422         na->target = ns->target;
1423         ether_addr_copy(&na->opt[2], n->ha);
1424         na->opt[0] = ND_OPT_TARGET_LL_ADDR;
1425         na->opt[1] = na_olen >> 3;
1426
1427         na->icmph.icmp6_cksum = csum_ipv6_magic(&pip6->saddr,
1428                 &pip6->daddr, sizeof(*na)+na_olen, IPPROTO_ICMPV6,
1429                 csum_partial(na, sizeof(*na)+na_olen, 0));
1430
1431         pip6->payload_len = htons(sizeof(*na)+na_olen);
1432
1433         skb_push(reply, sizeof(struct ipv6hdr));
1434
1435         reply->ip_summed = CHECKSUM_UNNECESSARY;
1436
1437         return reply;
1438 }
1439
1440 static int neigh_reduce(struct net_device *dev, struct sk_buff *skb)
1441 {
1442         struct vxlan_dev *vxlan = netdev_priv(dev);
1443         struct nd_msg *msg;
1444         const struct ipv6hdr *iphdr;
1445         const struct in6_addr *saddr, *daddr;
1446         struct neighbour *n;
1447         struct inet6_dev *in6_dev;
1448
1449         in6_dev = __in6_dev_get(dev);
1450         if (!in6_dev)
1451                 goto out;
1452
1453         iphdr = ipv6_hdr(skb);
1454         saddr = &iphdr->saddr;
1455         daddr = &iphdr->daddr;
1456
1457         msg = (struct nd_msg *)skb_transport_header(skb);
1458         if (msg->icmph.icmp6_code != 0 ||
1459             msg->icmph.icmp6_type != NDISC_NEIGHBOUR_SOLICITATION)
1460                 goto out;
1461
1462         if (ipv6_addr_loopback(daddr) ||
1463             ipv6_addr_is_multicast(&msg->target))
1464                 goto out;
1465
1466         n = neigh_lookup(ipv6_stub->nd_tbl, &msg->target, dev);
1467
1468         if (n) {
1469                 struct vxlan_fdb *f;
1470                 struct sk_buff *reply;
1471
1472                 if (!(n->nud_state & NUD_CONNECTED)) {
1473                         neigh_release(n);
1474                         goto out;
1475                 }
1476
1477                 f = vxlan_find_mac(vxlan, n->ha);
1478                 if (f && vxlan_addr_any(&(first_remote_rcu(f)->remote_ip))) {
1479                         /* bridge-local neighbor */
1480                         neigh_release(n);
1481                         goto out;
1482                 }
1483
1484                 reply = vxlan_na_create(skb, n,
1485                                         !!(f ? f->flags & NTF_ROUTER : 0));
1486
1487                 neigh_release(n);
1488
1489                 if (reply == NULL)
1490                         goto out;
1491
1492                 if (netif_rx_ni(reply) == NET_RX_DROP)
1493                         dev->stats.rx_dropped++;
1494
1495         } else if (vxlan->flags & VXLAN_F_L3MISS) {
1496                 union vxlan_addr ipa = {
1497                         .sin6.sin6_addr = msg->target,
1498                         .sin6.sin6_family = AF_INET6,
1499                 };
1500
1501                 vxlan_ip_miss(dev, &ipa);
1502         }
1503
1504 out:
1505         consume_skb(skb);
1506         return NETDEV_TX_OK;
1507 }
1508 #endif
1509
1510 static bool route_shortcircuit(struct net_device *dev, struct sk_buff *skb)
1511 {
1512         struct vxlan_dev *vxlan = netdev_priv(dev);
1513         struct neighbour *n;
1514
1515         if (is_multicast_ether_addr(eth_hdr(skb)->h_dest))
1516                 return false;
1517
1518         n = NULL;
1519         switch (ntohs(eth_hdr(skb)->h_proto)) {
1520         case ETH_P_IP:
1521         {
1522                 struct iphdr *pip;
1523
1524                 if (!pskb_may_pull(skb, sizeof(struct iphdr)))
1525                         return false;
1526                 pip = ip_hdr(skb);
1527                 n = neigh_lookup(&arp_tbl, &pip->daddr, dev);
1528                 if (!n && (vxlan->flags & VXLAN_F_L3MISS)) {
1529                         union vxlan_addr ipa = {
1530                                 .sin.sin_addr.s_addr = pip->daddr,
1531                                 .sin.sin_family = AF_INET,
1532                         };
1533
1534                         vxlan_ip_miss(dev, &ipa);
1535                         return false;
1536                 }
1537
1538                 break;
1539         }
1540 #if IS_ENABLED(CONFIG_IPV6)
1541         case ETH_P_IPV6:
1542         {
1543                 struct ipv6hdr *pip6;
1544
1545                 if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
1546                         return false;
1547                 pip6 = ipv6_hdr(skb);
1548                 n = neigh_lookup(ipv6_stub->nd_tbl, &pip6->daddr, dev);
1549                 if (!n && (vxlan->flags & VXLAN_F_L3MISS)) {
1550                         union vxlan_addr ipa = {
1551                                 .sin6.sin6_addr = pip6->daddr,
1552                                 .sin6.sin6_family = AF_INET6,
1553                         };
1554
1555                         vxlan_ip_miss(dev, &ipa);
1556                         return false;
1557                 }
1558
1559                 break;
1560         }
1561 #endif
1562         default:
1563                 return false;
1564         }
1565
1566         if (n) {
1567                 bool diff;
1568
1569                 diff = !ether_addr_equal(eth_hdr(skb)->h_dest, n->ha);
1570                 if (diff) {
1571                         memcpy(eth_hdr(skb)->h_source, eth_hdr(skb)->h_dest,
1572                                 dev->addr_len);
1573                         memcpy(eth_hdr(skb)->h_dest, n->ha, dev->addr_len);
1574                 }
1575                 neigh_release(n);
1576                 return diff;
1577         }
1578
1579         return false;
1580 }
1581
1582 /* Compute source port for outgoing packet
1583  *   first choice to use L4 flow hash since it will spread
1584  *     better and maybe available from hardware
1585  *   secondary choice is to use jhash on the Ethernet header
1586  */
1587 __be16 vxlan_src_port(__u16 port_min, __u16 port_max, struct sk_buff *skb)
1588 {
1589         unsigned int range = (port_max - port_min) + 1;
1590         u32 hash;
1591
1592         hash = skb_get_hash(skb);
1593         if (!hash)
1594                 hash = jhash(skb->data, 2 * ETH_ALEN,
1595                              (__force u32) skb->protocol);
1596
1597         return htons((((u64) hash * range) >> 32) + port_min);
1598 }
1599 EXPORT_SYMBOL_GPL(vxlan_src_port);
1600
1601 static int handle_offloads(struct sk_buff *skb)
1602 {
1603         if (skb_is_gso(skb)) {
1604                 int err = skb_unclone(skb, GFP_ATOMIC);
1605                 if (unlikely(err))
1606                         return err;
1607
1608                 skb_shinfo(skb)->gso_type |= SKB_GSO_UDP_TUNNEL;
1609         } else if (skb->ip_summed != CHECKSUM_PARTIAL)
1610                 skb->ip_summed = CHECKSUM_NONE;
1611
1612         return 0;
1613 }
1614
1615 #if IS_ENABLED(CONFIG_IPV6)
1616 static int vxlan6_xmit_skb(struct vxlan_sock *vs,
1617                            struct dst_entry *dst, struct sk_buff *skb,
1618                            struct net_device *dev, struct in6_addr *saddr,
1619                            struct in6_addr *daddr, __u8 prio, __u8 ttl,
1620                            __be16 src_port, __be16 dst_port, __be32 vni)
1621 {
1622         struct ipv6hdr *ip6h;
1623         struct vxlanhdr *vxh;
1624         struct udphdr *uh;
1625         int min_headroom;
1626         int err;
1627
1628         if (!skb->encapsulation) {
1629                 skb_reset_inner_headers(skb);
1630                 skb->encapsulation = 1;
1631         }
1632
1633         skb_scrub_packet(skb, false);
1634
1635         min_headroom = LL_RESERVED_SPACE(dst->dev) + dst->header_len
1636                         + VXLAN_HLEN + sizeof(struct ipv6hdr)
1637                         + (vlan_tx_tag_present(skb) ? VLAN_HLEN : 0);
1638
1639         /* Need space for new headers (invalidates iph ptr) */
1640         err = skb_cow_head(skb, min_headroom);
1641         if (unlikely(err))
1642                 return err;
1643
1644         if (vlan_tx_tag_present(skb)) {
1645                 if (WARN_ON(!__vlan_put_tag(skb,
1646                                             skb->vlan_proto,
1647                                             vlan_tx_tag_get(skb))))
1648                         return -ENOMEM;
1649
1650                 skb->vlan_tci = 0;
1651         }
1652
1653         vxh = (struct vxlanhdr *) __skb_push(skb, sizeof(*vxh));
1654         vxh->vx_flags = htonl(VXLAN_FLAGS);
1655         vxh->vx_vni = vni;
1656
1657         __skb_push(skb, sizeof(*uh));
1658         skb_reset_transport_header(skb);
1659         uh = udp_hdr(skb);
1660
1661         uh->dest = dst_port;
1662         uh->source = src_port;
1663
1664         uh->len = htons(skb->len);
1665         uh->check = 0;
1666
1667         memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1668         IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED |
1669                               IPSKB_REROUTED);
1670         skb_dst_set(skb, dst);
1671
1672         if (!skb_is_gso(skb) && !(dst->dev->features & NETIF_F_IPV6_CSUM)) {
1673                 __wsum csum = skb_checksum(skb, 0, skb->len, 0);
1674                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1675                 uh->check = csum_ipv6_magic(saddr, daddr, skb->len,
1676                                             IPPROTO_UDP, csum);
1677                 if (uh->check == 0)
1678                         uh->check = CSUM_MANGLED_0;
1679         } else {
1680                 skb->ip_summed = CHECKSUM_PARTIAL;
1681                 skb->csum_start = skb_transport_header(skb) - skb->head;
1682                 skb->csum_offset = offsetof(struct udphdr, check);
1683                 uh->check = ~csum_ipv6_magic(saddr, daddr,
1684                                              skb->len, IPPROTO_UDP, 0);
1685         }
1686
1687         __skb_push(skb, sizeof(*ip6h));
1688         skb_reset_network_header(skb);
1689         ip6h              = ipv6_hdr(skb);
1690         ip6h->version     = 6;
1691         ip6h->priority    = prio;
1692         ip6h->flow_lbl[0] = 0;
1693         ip6h->flow_lbl[1] = 0;
1694         ip6h->flow_lbl[2] = 0;
1695         ip6h->payload_len = htons(skb->len);
1696         ip6h->nexthdr     = IPPROTO_UDP;
1697         ip6h->hop_limit   = ttl;
1698         ip6h->daddr       = *daddr;
1699         ip6h->saddr       = *saddr;
1700
1701         err = handle_offloads(skb);
1702         if (err)
1703                 return err;
1704
1705         ip6tunnel_xmit(skb, dev);
1706         return 0;
1707 }
1708 #endif
1709
1710 int vxlan_xmit_skb(struct vxlan_sock *vs,
1711                    struct rtable *rt, struct sk_buff *skb,
1712                    __be32 src, __be32 dst, __u8 tos, __u8 ttl, __be16 df,
1713                    __be16 src_port, __be16 dst_port, __be32 vni)
1714 {
1715         struct vxlanhdr *vxh;
1716         struct udphdr *uh;
1717         int min_headroom;
1718         int err;
1719
1720         if (!skb->encapsulation) {
1721                 skb_reset_inner_headers(skb);
1722                 skb->encapsulation = 1;
1723         }
1724
1725         min_headroom = LL_RESERVED_SPACE(rt->dst.dev) + rt->dst.header_len
1726                         + VXLAN_HLEN + sizeof(struct iphdr)
1727                         + (vlan_tx_tag_present(skb) ? VLAN_HLEN : 0);
1728
1729         /* Need space for new headers (invalidates iph ptr) */
1730         err = skb_cow_head(skb, min_headroom);
1731         if (unlikely(err))
1732                 return err;
1733
1734         if (vlan_tx_tag_present(skb)) {
1735                 if (WARN_ON(!__vlan_put_tag(skb,
1736                                             skb->vlan_proto,
1737                                             vlan_tx_tag_get(skb))))
1738                         return -ENOMEM;
1739
1740                 skb->vlan_tci = 0;
1741         }
1742
1743         vxh = (struct vxlanhdr *) __skb_push(skb, sizeof(*vxh));
1744         vxh->vx_flags = htonl(VXLAN_FLAGS);
1745         vxh->vx_vni = vni;
1746
1747         __skb_push(skb, sizeof(*uh));
1748         skb_reset_transport_header(skb);
1749         uh = udp_hdr(skb);
1750
1751         uh->dest = dst_port;
1752         uh->source = src_port;
1753
1754         uh->len = htons(skb->len);
1755         uh->check = 0;
1756
1757         err = handle_offloads(skb);
1758         if (err)
1759                 return err;
1760
1761         return iptunnel_xmit(rt, skb, src, dst, IPPROTO_UDP, tos, ttl, df,
1762                              false);
1763 }
1764 EXPORT_SYMBOL_GPL(vxlan_xmit_skb);
1765
1766 /* Bypass encapsulation if the destination is local */
1767 static void vxlan_encap_bypass(struct sk_buff *skb, struct vxlan_dev *src_vxlan,
1768                                struct vxlan_dev *dst_vxlan)
1769 {
1770         struct pcpu_sw_netstats *tx_stats, *rx_stats;
1771         union vxlan_addr loopback;
1772         union vxlan_addr *remote_ip = &dst_vxlan->default_dst.remote_ip;
1773         struct net_device *dev = skb->dev;
1774         int len = skb->len;
1775
1776         tx_stats = this_cpu_ptr(src_vxlan->dev->tstats);
1777         rx_stats = this_cpu_ptr(dst_vxlan->dev->tstats);
1778         skb->pkt_type = PACKET_HOST;
1779         skb->encapsulation = 0;
1780         skb->dev = dst_vxlan->dev;
1781         __skb_pull(skb, skb_network_offset(skb));
1782
1783         if (remote_ip->sa.sa_family == AF_INET) {
1784                 loopback.sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1785                 loopback.sa.sa_family =  AF_INET;
1786 #if IS_ENABLED(CONFIG_IPV6)
1787         } else {
1788                 loopback.sin6.sin6_addr = in6addr_loopback;
1789                 loopback.sa.sa_family =  AF_INET6;
1790 #endif
1791         }
1792
1793         if (dst_vxlan->flags & VXLAN_F_LEARN)
1794                 vxlan_snoop(skb->dev, &loopback, eth_hdr(skb)->h_source);
1795
1796         u64_stats_update_begin(&tx_stats->syncp);
1797         tx_stats->tx_packets++;
1798         tx_stats->tx_bytes += len;
1799         u64_stats_update_end(&tx_stats->syncp);
1800
1801         if (netif_rx(skb) == NET_RX_SUCCESS) {
1802                 u64_stats_update_begin(&rx_stats->syncp);
1803                 rx_stats->rx_packets++;
1804                 rx_stats->rx_bytes += len;
1805                 u64_stats_update_end(&rx_stats->syncp);
1806         } else {
1807                 dev->stats.rx_dropped++;
1808         }
1809 }
1810
1811 static void vxlan_xmit_one(struct sk_buff *skb, struct net_device *dev,
1812                            struct vxlan_rdst *rdst, bool did_rsc)
1813 {
1814         struct vxlan_dev *vxlan = netdev_priv(dev);
1815         struct rtable *rt = NULL;
1816         const struct iphdr *old_iph;
1817         struct flowi4 fl4;
1818         union vxlan_addr *dst;
1819         __be16 src_port = 0, dst_port;
1820         u32 vni;
1821         __be16 df = 0;
1822         __u8 tos, ttl;
1823         int err;
1824
1825         dst_port = rdst->remote_port ? rdst->remote_port : vxlan->dst_port;
1826         vni = rdst->remote_vni;
1827         dst = &rdst->remote_ip;
1828
1829         if (vxlan_addr_any(dst)) {
1830                 if (did_rsc) {
1831                         /* short-circuited back to local bridge */
1832                         vxlan_encap_bypass(skb, vxlan, vxlan);
1833                         return;
1834                 }
1835                 goto drop;
1836         }
1837
1838         old_iph = ip_hdr(skb);
1839
1840         ttl = vxlan->ttl;
1841         if (!ttl && vxlan_addr_multicast(dst))
1842                 ttl = 1;
1843
1844         tos = vxlan->tos;
1845         if (tos == 1)
1846                 tos = ip_tunnel_get_dsfield(old_iph, skb);
1847
1848         src_port = vxlan_src_port(vxlan->port_min, vxlan->port_max, skb);
1849
1850         if (dst->sa.sa_family == AF_INET) {
1851                 memset(&fl4, 0, sizeof(fl4));
1852                 fl4.flowi4_oif = rdst->remote_ifindex;
1853                 fl4.flowi4_tos = RT_TOS(tos);
1854                 fl4.daddr = dst->sin.sin_addr.s_addr;
1855                 fl4.saddr = vxlan->saddr.sin.sin_addr.s_addr;
1856
1857                 rt = ip_route_output_key(dev_net(dev), &fl4);
1858                 if (IS_ERR(rt)) {
1859                         netdev_dbg(dev, "no route to %pI4\n",
1860                                    &dst->sin.sin_addr.s_addr);
1861                         dev->stats.tx_carrier_errors++;
1862                         goto tx_error;
1863                 }
1864
1865                 if (rt->dst.dev == dev) {
1866                         netdev_dbg(dev, "circular route to %pI4\n",
1867                                    &dst->sin.sin_addr.s_addr);
1868                         dev->stats.collisions++;
1869                         goto rt_tx_error;
1870                 }
1871
1872                 /* Bypass encapsulation if the destination is local */
1873                 if (rt->rt_flags & RTCF_LOCAL &&
1874                     !(rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))) {
1875                         struct vxlan_dev *dst_vxlan;
1876
1877                         ip_rt_put(rt);
1878                         dst_vxlan = vxlan_find_vni(dev_net(dev), vni,
1879                                                    dst->sa.sa_family, dst_port);
1880                         if (!dst_vxlan)
1881                                 goto tx_error;
1882                         vxlan_encap_bypass(skb, vxlan, dst_vxlan);
1883                         return;
1884                 }
1885
1886                 tos = ip_tunnel_ecn_encap(tos, old_iph, skb);
1887                 ttl = ttl ? : ip4_dst_hoplimit(&rt->dst);
1888
1889                 err = vxlan_xmit_skb(vxlan->vn_sock, rt, skb,
1890                                      fl4.saddr, dst->sin.sin_addr.s_addr,
1891                                      tos, ttl, df, src_port, dst_port,
1892                                      htonl(vni << 8));
1893
1894                 if (err < 0)
1895                         goto rt_tx_error;
1896                 iptunnel_xmit_stats(err, &dev->stats, dev->tstats);
1897 #if IS_ENABLED(CONFIG_IPV6)
1898         } else {
1899                 struct sock *sk = vxlan->vn_sock->sock->sk;
1900                 struct dst_entry *ndst;
1901                 struct flowi6 fl6;
1902                 u32 flags;
1903
1904                 memset(&fl6, 0, sizeof(fl6));
1905                 fl6.flowi6_oif = rdst->remote_ifindex;
1906                 fl6.daddr = dst->sin6.sin6_addr;
1907                 fl6.saddr = vxlan->saddr.sin6.sin6_addr;
1908                 fl6.flowi6_proto = IPPROTO_UDP;
1909
1910                 if (ipv6_stub->ipv6_dst_lookup(sk, &ndst, &fl6)) {
1911                         netdev_dbg(dev, "no route to %pI6\n",
1912                                    &dst->sin6.sin6_addr);
1913                         dev->stats.tx_carrier_errors++;
1914                         goto tx_error;
1915                 }
1916
1917                 if (ndst->dev == dev) {
1918                         netdev_dbg(dev, "circular route to %pI6\n",
1919                                    &dst->sin6.sin6_addr);
1920                         dst_release(ndst);
1921                         dev->stats.collisions++;
1922                         goto tx_error;
1923                 }
1924
1925                 /* Bypass encapsulation if the destination is local */
1926                 flags = ((struct rt6_info *)ndst)->rt6i_flags;
1927                 if (flags & RTF_LOCAL &&
1928                     !(flags & (RTCF_BROADCAST | RTCF_MULTICAST))) {
1929                         struct vxlan_dev *dst_vxlan;
1930
1931                         dst_release(ndst);
1932                         dst_vxlan = vxlan_find_vni(dev_net(dev), vni,
1933                                                    dst->sa.sa_family, dst_port);
1934                         if (!dst_vxlan)
1935                                 goto tx_error;
1936                         vxlan_encap_bypass(skb, vxlan, dst_vxlan);
1937                         return;
1938                 }
1939
1940                 ttl = ttl ? : ip6_dst_hoplimit(ndst);
1941
1942                 err = vxlan6_xmit_skb(vxlan->vn_sock, ndst, skb,
1943                                       dev, &fl6.saddr, &fl6.daddr, 0, ttl,
1944                                       src_port, dst_port, htonl(vni << 8));
1945 #endif
1946         }
1947
1948         return;
1949
1950 drop:
1951         dev->stats.tx_dropped++;
1952         goto tx_free;
1953
1954 rt_tx_error:
1955         ip_rt_put(rt);
1956 tx_error:
1957         dev->stats.tx_errors++;
1958 tx_free:
1959         dev_kfree_skb(skb);
1960 }
1961
1962 /* Transmit local packets over Vxlan
1963  *
1964  * Outer IP header inherits ECN and DF from inner header.
1965  * Outer UDP destination is the VXLAN assigned port.
1966  *           source port is based on hash of flow
1967  */
1968 static netdev_tx_t vxlan_xmit(struct sk_buff *skb, struct net_device *dev)
1969 {
1970         struct vxlan_dev *vxlan = netdev_priv(dev);
1971         struct ethhdr *eth;
1972         bool did_rsc = false;
1973         struct vxlan_rdst *rdst, *fdst = NULL;
1974         struct vxlan_fdb *f;
1975
1976         skb_reset_mac_header(skb);
1977         eth = eth_hdr(skb);
1978
1979         if ((vxlan->flags & VXLAN_F_PROXY)) {
1980                 if (ntohs(eth->h_proto) == ETH_P_ARP)
1981                         return arp_reduce(dev, skb);
1982 #if IS_ENABLED(CONFIG_IPV6)
1983                 else if (ntohs(eth->h_proto) == ETH_P_IPV6 &&
1984                          pskb_may_pull(skb, sizeof(struct ipv6hdr)
1985                                        + sizeof(struct nd_msg)) &&
1986                          ipv6_hdr(skb)->nexthdr == IPPROTO_ICMPV6) {
1987                                 struct nd_msg *msg;
1988
1989                                 msg = (struct nd_msg *)skb_transport_header(skb);
1990                                 if (msg->icmph.icmp6_code == 0 &&
1991                                     msg->icmph.icmp6_type == NDISC_NEIGHBOUR_SOLICITATION)
1992                                         return neigh_reduce(dev, skb);
1993                 }
1994                 eth = eth_hdr(skb);
1995 #endif
1996         }
1997
1998         f = vxlan_find_mac(vxlan, eth->h_dest);
1999         did_rsc = false;
2000
2001         if (f && (f->flags & NTF_ROUTER) && (vxlan->flags & VXLAN_F_RSC) &&
2002             (ntohs(eth->h_proto) == ETH_P_IP ||
2003              ntohs(eth->h_proto) == ETH_P_IPV6)) {
2004                 did_rsc = route_shortcircuit(dev, skb);
2005                 if (did_rsc)
2006                         f = vxlan_find_mac(vxlan, eth->h_dest);
2007         }
2008
2009         if (f == NULL) {
2010                 f = vxlan_find_mac(vxlan, all_zeros_mac);
2011                 if (f == NULL) {
2012                         if ((vxlan->flags & VXLAN_F_L2MISS) &&
2013                             !is_multicast_ether_addr(eth->h_dest))
2014                                 vxlan_fdb_miss(vxlan, eth->h_dest);
2015
2016                         dev->stats.tx_dropped++;
2017                         kfree_skb(skb);
2018                         return NETDEV_TX_OK;
2019                 }
2020         }
2021
2022         list_for_each_entry_rcu(rdst, &f->remotes, list) {
2023                 struct sk_buff *skb1;
2024
2025                 if (!fdst) {
2026                         fdst = rdst;
2027                         continue;
2028                 }
2029                 skb1 = skb_clone(skb, GFP_ATOMIC);
2030                 if (skb1)
2031                         vxlan_xmit_one(skb1, dev, rdst, did_rsc);
2032         }
2033
2034         if (fdst)
2035                 vxlan_xmit_one(skb, dev, fdst, did_rsc);
2036         else
2037                 kfree_skb(skb);
2038         return NETDEV_TX_OK;
2039 }
2040
2041 /* Walk the forwarding table and purge stale entries */
2042 static void vxlan_cleanup(unsigned long arg)
2043 {
2044         struct vxlan_dev *vxlan = (struct vxlan_dev *) arg;
2045         unsigned long next_timer = jiffies + FDB_AGE_INTERVAL;
2046         unsigned int h;
2047
2048         if (!netif_running(vxlan->dev))
2049                 return;
2050
2051         spin_lock_bh(&vxlan->hash_lock);
2052         for (h = 0; h < FDB_HASH_SIZE; ++h) {
2053                 struct hlist_node *p, *n;
2054                 hlist_for_each_safe(p, n, &vxlan->fdb_head[h]) {
2055                         struct vxlan_fdb *f
2056                                 = container_of(p, struct vxlan_fdb, hlist);
2057                         unsigned long timeout;
2058
2059                         if (f->state & NUD_PERMANENT)
2060                                 continue;
2061
2062                         timeout = f->used + vxlan->age_interval * HZ;
2063                         if (time_before_eq(timeout, jiffies)) {
2064                                 netdev_dbg(vxlan->dev,
2065                                            "garbage collect %pM\n",
2066                                            f->eth_addr);
2067                                 f->state = NUD_STALE;
2068                                 vxlan_fdb_destroy(vxlan, f);
2069                         } else if (time_before(timeout, next_timer))
2070                                 next_timer = timeout;
2071                 }
2072         }
2073         spin_unlock_bh(&vxlan->hash_lock);
2074
2075         mod_timer(&vxlan->age_timer, next_timer);
2076 }
2077
2078 static void vxlan_vs_add_dev(struct vxlan_sock *vs, struct vxlan_dev *vxlan)
2079 {
2080         __u32 vni = vxlan->default_dst.remote_vni;
2081
2082         vxlan->vn_sock = vs;
2083         hlist_add_head_rcu(&vxlan->hlist, vni_head(vs, vni));
2084 }
2085
2086 /* Setup stats when device is created */
2087 static int vxlan_init(struct net_device *dev)
2088 {
2089         struct vxlan_dev *vxlan = netdev_priv(dev);
2090         struct vxlan_net *vn = net_generic(dev_net(dev), vxlan_net_id);
2091         bool ipv6 = vxlan->flags & VXLAN_F_IPV6;
2092         struct vxlan_sock *vs;
2093         int i;
2094
2095         dev->tstats = alloc_percpu(struct pcpu_sw_netstats);
2096         if (!dev->tstats)
2097                 return -ENOMEM;
2098
2099         for_each_possible_cpu(i) {
2100                 struct pcpu_sw_netstats *vxlan_stats;
2101                 vxlan_stats = per_cpu_ptr(dev->tstats, i);
2102                 u64_stats_init(&vxlan_stats->syncp);
2103         }
2104
2105
2106         spin_lock(&vn->sock_lock);
2107         vs = vxlan_find_sock(dev_net(dev), ipv6 ? AF_INET6 : AF_INET,
2108                              vxlan->dst_port);
2109         if (vs) {
2110                 /* If we have a socket with same port already, reuse it */
2111                 atomic_inc(&vs->refcnt);
2112                 vxlan_vs_add_dev(vs, vxlan);
2113         } else {
2114                 /* otherwise make new socket outside of RTNL */
2115                 dev_hold(dev);
2116                 queue_work(vxlan_wq, &vxlan->sock_work);
2117         }
2118         spin_unlock(&vn->sock_lock);
2119
2120         return 0;
2121 }
2122
2123 static void vxlan_fdb_delete_default(struct vxlan_dev *vxlan)
2124 {
2125         struct vxlan_fdb *f;
2126
2127         spin_lock_bh(&vxlan->hash_lock);
2128         f = __vxlan_find_mac(vxlan, all_zeros_mac);
2129         if (f)
2130                 vxlan_fdb_destroy(vxlan, f);
2131         spin_unlock_bh(&vxlan->hash_lock);
2132 }
2133
2134 static void vxlan_uninit(struct net_device *dev)
2135 {
2136         struct vxlan_dev *vxlan = netdev_priv(dev);
2137         struct vxlan_sock *vs = vxlan->vn_sock;
2138
2139         vxlan_fdb_delete_default(vxlan);
2140
2141         if (vs)
2142                 vxlan_sock_release(vs);
2143         free_percpu(dev->tstats);
2144 }
2145
2146 /* Start ageing timer and join group when device is brought up */
2147 static int vxlan_open(struct net_device *dev)
2148 {
2149         struct vxlan_dev *vxlan = netdev_priv(dev);
2150         struct vxlan_sock *vs = vxlan->vn_sock;
2151
2152         /* socket hasn't been created */
2153         if (!vs)
2154                 return -ENOTCONN;
2155
2156         if (vxlan_addr_multicast(&vxlan->default_dst.remote_ip)) {
2157                 vxlan_sock_hold(vs);
2158                 dev_hold(dev);
2159                 queue_work(vxlan_wq, &vxlan->igmp_join);
2160         }
2161
2162         if (vxlan->age_interval)
2163                 mod_timer(&vxlan->age_timer, jiffies + FDB_AGE_INTERVAL);
2164
2165         return 0;
2166 }
2167
2168 /* Purge the forwarding table */
2169 static void vxlan_flush(struct vxlan_dev *vxlan)
2170 {
2171         unsigned int h;
2172
2173         spin_lock_bh(&vxlan->hash_lock);
2174         for (h = 0; h < FDB_HASH_SIZE; ++h) {
2175                 struct hlist_node *p, *n;
2176                 hlist_for_each_safe(p, n, &vxlan->fdb_head[h]) {
2177                         struct vxlan_fdb *f
2178                                 = container_of(p, struct vxlan_fdb, hlist);
2179                         /* the all_zeros_mac entry is deleted at vxlan_uninit */
2180                         if (!is_zero_ether_addr(f->eth_addr))
2181                                 vxlan_fdb_destroy(vxlan, f);
2182                 }
2183         }
2184         spin_unlock_bh(&vxlan->hash_lock);
2185 }
2186
2187 /* Cleanup timer and forwarding table on shutdown */
2188 static int vxlan_stop(struct net_device *dev)
2189 {
2190         struct vxlan_net *vn = net_generic(dev_net(dev), vxlan_net_id);
2191         struct vxlan_dev *vxlan = netdev_priv(dev);
2192         struct vxlan_sock *vs = vxlan->vn_sock;
2193
2194         if (vs && vxlan_addr_multicast(&vxlan->default_dst.remote_ip) &&
2195             !vxlan_group_used(vn, vxlan)) {
2196                 vxlan_sock_hold(vs);
2197                 dev_hold(dev);
2198                 queue_work(vxlan_wq, &vxlan->igmp_leave);
2199         }
2200
2201         del_timer_sync(&vxlan->age_timer);
2202
2203         vxlan_flush(vxlan);
2204
2205         return 0;
2206 }
2207
2208 /* Stub, nothing needs to be done. */
2209 static void vxlan_set_multicast_list(struct net_device *dev)
2210 {
2211 }
2212
2213 static int vxlan_change_mtu(struct net_device *dev, int new_mtu)
2214 {
2215         struct vxlan_dev *vxlan = netdev_priv(dev);
2216         struct vxlan_rdst *dst = &vxlan->default_dst;
2217         struct net_device *lowerdev;
2218         int max_mtu;
2219
2220         lowerdev = __dev_get_by_index(dev_net(dev), dst->remote_ifindex);
2221         if (lowerdev == NULL)
2222                 return eth_change_mtu(dev, new_mtu);
2223
2224         if (dst->remote_ip.sa.sa_family == AF_INET6)
2225                 max_mtu = lowerdev->mtu - VXLAN6_HEADROOM;
2226         else
2227                 max_mtu = lowerdev->mtu - VXLAN_HEADROOM;
2228
2229         if (new_mtu < 68 || new_mtu > max_mtu)
2230                 return -EINVAL;
2231
2232         dev->mtu = new_mtu;
2233         return 0;
2234 }
2235
2236 static const struct net_device_ops vxlan_netdev_ops = {
2237         .ndo_init               = vxlan_init,
2238         .ndo_uninit             = vxlan_uninit,
2239         .ndo_open               = vxlan_open,
2240         .ndo_stop               = vxlan_stop,
2241         .ndo_start_xmit         = vxlan_xmit,
2242         .ndo_get_stats64        = ip_tunnel_get_stats64,
2243         .ndo_set_rx_mode        = vxlan_set_multicast_list,
2244         .ndo_change_mtu         = vxlan_change_mtu,
2245         .ndo_validate_addr      = eth_validate_addr,
2246         .ndo_set_mac_address    = eth_mac_addr,
2247         .ndo_fdb_add            = vxlan_fdb_add,
2248         .ndo_fdb_del            = vxlan_fdb_delete,
2249         .ndo_fdb_dump           = vxlan_fdb_dump,
2250 };
2251
2252 /* Info for udev, that this is a virtual tunnel endpoint */
2253 static struct device_type vxlan_type = {
2254         .name = "vxlan",
2255 };
2256
2257 /* Calls the ndo_add_vxlan_port of the caller in order to
2258  * supply the listening VXLAN udp ports. Callers are expected
2259  * to implement the ndo_add_vxlan_port.
2260  */
2261 void vxlan_get_rx_port(struct net_device *dev)
2262 {
2263         struct vxlan_sock *vs;
2264         struct net *net = dev_net(dev);
2265         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2266         sa_family_t sa_family;
2267         __be16 port;
2268         unsigned int i;
2269
2270         spin_lock(&vn->sock_lock);
2271         for (i = 0; i < PORT_HASH_SIZE; ++i) {
2272                 hlist_for_each_entry_rcu(vs, &vn->sock_list[i], hlist) {
2273                         port = inet_sk(vs->sock->sk)->inet_sport;
2274                         sa_family = vs->sock->sk->sk_family;
2275                         dev->netdev_ops->ndo_add_vxlan_port(dev, sa_family,
2276                                                             port);
2277                 }
2278         }
2279         spin_unlock(&vn->sock_lock);
2280 }
2281 EXPORT_SYMBOL_GPL(vxlan_get_rx_port);
2282
2283 /* Initialize the device structure. */
2284 static void vxlan_setup(struct net_device *dev)
2285 {
2286         struct vxlan_dev *vxlan = netdev_priv(dev);
2287         unsigned int h;
2288         int low, high;
2289
2290         eth_hw_addr_random(dev);
2291         ether_setup(dev);
2292         if (vxlan->default_dst.remote_ip.sa.sa_family == AF_INET6)
2293                 dev->needed_headroom = ETH_HLEN + VXLAN6_HEADROOM;
2294         else
2295                 dev->needed_headroom = ETH_HLEN + VXLAN_HEADROOM;
2296
2297         dev->netdev_ops = &vxlan_netdev_ops;
2298         dev->destructor = free_netdev;
2299         SET_NETDEV_DEVTYPE(dev, &vxlan_type);
2300
2301         dev->tx_queue_len = 0;
2302         dev->features   |= NETIF_F_LLTX;
2303         dev->features   |= NETIF_F_NETNS_LOCAL;
2304         dev->features   |= NETIF_F_SG | NETIF_F_HW_CSUM;
2305         dev->features   |= NETIF_F_RXCSUM;
2306         dev->features   |= NETIF_F_GSO_SOFTWARE;
2307
2308         dev->vlan_features = dev->features;
2309         dev->features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX;
2310         dev->hw_features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_RXCSUM;
2311         dev->hw_features |= NETIF_F_GSO_SOFTWARE;
2312         dev->hw_features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX;
2313         dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
2314         dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
2315
2316         INIT_LIST_HEAD(&vxlan->next);
2317         spin_lock_init(&vxlan->hash_lock);
2318         INIT_WORK(&vxlan->igmp_join, vxlan_igmp_join);
2319         INIT_WORK(&vxlan->igmp_leave, vxlan_igmp_leave);
2320         INIT_WORK(&vxlan->sock_work, vxlan_sock_work);
2321
2322         init_timer_deferrable(&vxlan->age_timer);
2323         vxlan->age_timer.function = vxlan_cleanup;
2324         vxlan->age_timer.data = (unsigned long) vxlan;
2325
2326         inet_get_local_port_range(dev_net(dev), &low, &high);
2327         vxlan->port_min = low;
2328         vxlan->port_max = high;
2329         vxlan->dst_port = htons(vxlan_port);
2330
2331         vxlan->dev = dev;
2332
2333         for (h = 0; h < FDB_HASH_SIZE; ++h)
2334                 INIT_HLIST_HEAD(&vxlan->fdb_head[h]);
2335 }
2336
2337 static const struct nla_policy vxlan_policy[IFLA_VXLAN_MAX + 1] = {
2338         [IFLA_VXLAN_ID]         = { .type = NLA_U32 },
2339         [IFLA_VXLAN_GROUP]      = { .len = FIELD_SIZEOF(struct iphdr, daddr) },
2340         [IFLA_VXLAN_GROUP6]     = { .len = sizeof(struct in6_addr) },
2341         [IFLA_VXLAN_LINK]       = { .type = NLA_U32 },
2342         [IFLA_VXLAN_LOCAL]      = { .len = FIELD_SIZEOF(struct iphdr, saddr) },
2343         [IFLA_VXLAN_LOCAL6]     = { .len = sizeof(struct in6_addr) },
2344         [IFLA_VXLAN_TOS]        = { .type = NLA_U8 },
2345         [IFLA_VXLAN_TTL]        = { .type = NLA_U8 },
2346         [IFLA_VXLAN_LEARNING]   = { .type = NLA_U8 },
2347         [IFLA_VXLAN_AGEING]     = { .type = NLA_U32 },
2348         [IFLA_VXLAN_LIMIT]      = { .type = NLA_U32 },
2349         [IFLA_VXLAN_PORT_RANGE] = { .len  = sizeof(struct ifla_vxlan_port_range) },
2350         [IFLA_VXLAN_PROXY]      = { .type = NLA_U8 },
2351         [IFLA_VXLAN_RSC]        = { .type = NLA_U8 },
2352         [IFLA_VXLAN_L2MISS]     = { .type = NLA_U8 },
2353         [IFLA_VXLAN_L3MISS]     = { .type = NLA_U8 },
2354         [IFLA_VXLAN_PORT]       = { .type = NLA_U16 },
2355 };
2356
2357 static int vxlan_validate(struct nlattr *tb[], struct nlattr *data[])
2358 {
2359         if (tb[IFLA_ADDRESS]) {
2360                 if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN) {
2361                         pr_debug("invalid link address (not ethernet)\n");
2362                         return -EINVAL;
2363                 }
2364
2365                 if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS]))) {
2366                         pr_debug("invalid all zero ethernet address\n");
2367                         return -EADDRNOTAVAIL;
2368                 }
2369         }
2370
2371         if (!data)
2372                 return -EINVAL;
2373
2374         if (data[IFLA_VXLAN_ID]) {
2375                 __u32 id = nla_get_u32(data[IFLA_VXLAN_ID]);
2376                 if (id >= VXLAN_VID_MASK)
2377                         return -ERANGE;
2378         }
2379
2380         if (data[IFLA_VXLAN_PORT_RANGE]) {
2381                 const struct ifla_vxlan_port_range *p
2382                         = nla_data(data[IFLA_VXLAN_PORT_RANGE]);
2383
2384                 if (ntohs(p->high) < ntohs(p->low)) {
2385                         pr_debug("port range %u .. %u not valid\n",
2386                                  ntohs(p->low), ntohs(p->high));
2387                         return -EINVAL;
2388                 }
2389         }
2390
2391         return 0;
2392 }
2393
2394 static void vxlan_get_drvinfo(struct net_device *netdev,
2395                               struct ethtool_drvinfo *drvinfo)
2396 {
2397         strlcpy(drvinfo->version, VXLAN_VERSION, sizeof(drvinfo->version));
2398         strlcpy(drvinfo->driver, "vxlan", sizeof(drvinfo->driver));
2399 }
2400
2401 static const struct ethtool_ops vxlan_ethtool_ops = {
2402         .get_drvinfo    = vxlan_get_drvinfo,
2403         .get_link       = ethtool_op_get_link,
2404 };
2405
2406 static void vxlan_del_work(struct work_struct *work)
2407 {
2408         struct vxlan_sock *vs = container_of(work, struct vxlan_sock, del_work);
2409
2410         sk_release_kernel(vs->sock->sk);
2411         kfree_rcu(vs, rcu);
2412 }
2413
2414 #if IS_ENABLED(CONFIG_IPV6)
2415 /* Create UDP socket for encapsulation receive. AF_INET6 socket
2416  * could be used for both IPv4 and IPv6 communications, but
2417  * users may set bindv6only=1.
2418  */
2419 static struct socket *create_v6_sock(struct net *net, __be16 port)
2420 {
2421         struct sock *sk;
2422         struct socket *sock;
2423         struct sockaddr_in6 vxlan_addr = {
2424                 .sin6_family = AF_INET6,
2425                 .sin6_port = port,
2426         };
2427         int rc, val = 1;
2428
2429         rc = sock_create_kern(AF_INET6, SOCK_DGRAM, IPPROTO_UDP, &sock);
2430         if (rc < 0) {
2431                 pr_debug("UDPv6 socket create failed\n");
2432                 return ERR_PTR(rc);
2433         }
2434
2435         /* Put in proper namespace */
2436         sk = sock->sk;
2437         sk_change_net(sk, net);
2438
2439         kernel_setsockopt(sock, SOL_IPV6, IPV6_V6ONLY,
2440                           (char *)&val, sizeof(val));
2441         rc = kernel_bind(sock, (struct sockaddr *)&vxlan_addr,
2442                          sizeof(struct sockaddr_in6));
2443         if (rc < 0) {
2444                 pr_debug("bind for UDPv6 socket %pI6:%u (%d)\n",
2445                          &vxlan_addr.sin6_addr, ntohs(vxlan_addr.sin6_port), rc);
2446                 sk_release_kernel(sk);
2447                 return ERR_PTR(rc);
2448         }
2449         /* At this point, IPv6 module should have been loaded in
2450          * sock_create_kern().
2451          */
2452         BUG_ON(!ipv6_stub);
2453
2454         /* Disable multicast loopback */
2455         inet_sk(sk)->mc_loop = 0;
2456         return sock;
2457 }
2458
2459 #else
2460
2461 static struct socket *create_v6_sock(struct net *net, __be16 port)
2462 {
2463                 return ERR_PTR(-EPFNOSUPPORT);
2464 }
2465 #endif
2466
2467 static struct socket *create_v4_sock(struct net *net, __be16 port)
2468 {
2469         struct sock *sk;
2470         struct socket *sock;
2471         struct sockaddr_in vxlan_addr = {
2472                 .sin_family = AF_INET,
2473                 .sin_addr.s_addr = htonl(INADDR_ANY),
2474                 .sin_port = port,
2475         };
2476         int rc;
2477
2478         /* Create UDP socket for encapsulation receive. */
2479         rc = sock_create_kern(AF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
2480         if (rc < 0) {
2481                 pr_debug("UDP socket create failed\n");
2482                 return ERR_PTR(rc);
2483         }
2484
2485         /* Put in proper namespace */
2486         sk = sock->sk;
2487         sk_change_net(sk, net);
2488
2489         rc = kernel_bind(sock, (struct sockaddr *) &vxlan_addr,
2490                          sizeof(vxlan_addr));
2491         if (rc < 0) {
2492                 pr_debug("bind for UDP socket %pI4:%u (%d)\n",
2493                          &vxlan_addr.sin_addr, ntohs(vxlan_addr.sin_port), rc);
2494                 sk_release_kernel(sk);
2495                 return ERR_PTR(rc);
2496         }
2497
2498         /* Disable multicast loopback */
2499         inet_sk(sk)->mc_loop = 0;
2500         return sock;
2501 }
2502
2503 /* Create new listen socket if needed */
2504 static struct vxlan_sock *vxlan_socket_create(struct net *net, __be16 port,
2505                                               vxlan_rcv_t *rcv, void *data, bool ipv6)
2506 {
2507         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2508         struct vxlan_sock *vs;
2509         struct socket *sock;
2510         struct sock *sk;
2511         unsigned int h;
2512
2513         vs = kzalloc(sizeof(*vs), GFP_KERNEL);
2514         if (!vs)
2515                 return ERR_PTR(-ENOMEM);
2516
2517         for (h = 0; h < VNI_HASH_SIZE; ++h)
2518                 INIT_HLIST_HEAD(&vs->vni_list[h]);
2519
2520         INIT_WORK(&vs->del_work, vxlan_del_work);
2521
2522         if (ipv6)
2523                 sock = create_v6_sock(net, port);
2524         else
2525                 sock = create_v4_sock(net, port);
2526         if (IS_ERR(sock)) {
2527                 kfree(vs);
2528                 return ERR_CAST(sock);
2529         }
2530
2531         vs->sock = sock;
2532         sk = sock->sk;
2533         atomic_set(&vs->refcnt, 1);
2534         vs->rcv = rcv;
2535         vs->data = data;
2536         rcu_assign_sk_user_data(vs->sock->sk, vs);
2537
2538         /* Initialize the vxlan udp offloads structure */
2539         vs->udp_offloads.port = port;
2540         vs->udp_offloads.callbacks.gro_receive  = vxlan_gro_receive;
2541         vs->udp_offloads.callbacks.gro_complete = vxlan_gro_complete;
2542
2543         spin_lock(&vn->sock_lock);
2544         hlist_add_head_rcu(&vs->hlist, vs_head(net, port));
2545         vxlan_notify_add_rx_port(vs);
2546         spin_unlock(&vn->sock_lock);
2547
2548         /* Mark socket as an encapsulation socket. */
2549         udp_sk(sk)->encap_type = 1;
2550         udp_sk(sk)->encap_rcv = vxlan_udp_encap_recv;
2551 #if IS_ENABLED(CONFIG_IPV6)
2552         if (ipv6)
2553                 ipv6_stub->udpv6_encap_enable();
2554         else
2555 #endif
2556                 udp_encap_enable();
2557
2558         return vs;
2559 }
2560
2561 struct vxlan_sock *vxlan_sock_add(struct net *net, __be16 port,
2562                                   vxlan_rcv_t *rcv, void *data,
2563                                   bool no_share, bool ipv6)
2564 {
2565         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2566         struct vxlan_sock *vs;
2567
2568         vs = vxlan_socket_create(net, port, rcv, data, ipv6);
2569         if (!IS_ERR(vs))
2570                 return vs;
2571
2572         if (no_share)   /* Return error if sharing is not allowed. */
2573                 return vs;
2574
2575         spin_lock(&vn->sock_lock);
2576         vs = vxlan_find_sock(net, ipv6 ? AF_INET6 : AF_INET, port);
2577         if (vs) {
2578                 if (vs->rcv == rcv)
2579                         atomic_inc(&vs->refcnt);
2580                 else
2581                         vs = ERR_PTR(-EBUSY);
2582         }
2583         spin_unlock(&vn->sock_lock);
2584
2585         if (!vs)
2586                 vs = ERR_PTR(-EINVAL);
2587
2588         return vs;
2589 }
2590 EXPORT_SYMBOL_GPL(vxlan_sock_add);
2591
2592 /* Scheduled at device creation to bind to a socket */
2593 static void vxlan_sock_work(struct work_struct *work)
2594 {
2595         struct vxlan_dev *vxlan = container_of(work, struct vxlan_dev, sock_work);
2596         struct net *net = dev_net(vxlan->dev);
2597         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2598         __be16 port = vxlan->dst_port;
2599         struct vxlan_sock *nvs;
2600
2601         nvs = vxlan_sock_add(net, port, vxlan_rcv, NULL, false, vxlan->flags & VXLAN_F_IPV6);
2602         spin_lock(&vn->sock_lock);
2603         if (!IS_ERR(nvs))
2604                 vxlan_vs_add_dev(nvs, vxlan);
2605         spin_unlock(&vn->sock_lock);
2606
2607         dev_put(vxlan->dev);
2608 }
2609
2610 static int vxlan_newlink(struct net *net, struct net_device *dev,
2611                          struct nlattr *tb[], struct nlattr *data[])
2612 {
2613         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2614         struct vxlan_dev *vxlan = netdev_priv(dev);
2615         struct vxlan_rdst *dst = &vxlan->default_dst;
2616         __u32 vni;
2617         int err;
2618         bool use_ipv6 = false;
2619
2620         if (!data[IFLA_VXLAN_ID])
2621                 return -EINVAL;
2622
2623         vni = nla_get_u32(data[IFLA_VXLAN_ID]);
2624         dst->remote_vni = vni;
2625
2626         /* Unless IPv6 is explicitly requested, assume IPv4 */
2627         dst->remote_ip.sa.sa_family = AF_INET;
2628         if (data[IFLA_VXLAN_GROUP]) {
2629                 dst->remote_ip.sin.sin_addr.s_addr = nla_get_be32(data[IFLA_VXLAN_GROUP]);
2630         } else if (data[IFLA_VXLAN_GROUP6]) {
2631                 if (!IS_ENABLED(CONFIG_IPV6))
2632                         return -EPFNOSUPPORT;
2633
2634                 nla_memcpy(&dst->remote_ip.sin6.sin6_addr, data[IFLA_VXLAN_GROUP6],
2635                            sizeof(struct in6_addr));
2636                 dst->remote_ip.sa.sa_family = AF_INET6;
2637                 use_ipv6 = true;
2638         }
2639
2640         if (data[IFLA_VXLAN_LOCAL]) {
2641                 vxlan->saddr.sin.sin_addr.s_addr = nla_get_be32(data[IFLA_VXLAN_LOCAL]);
2642                 vxlan->saddr.sa.sa_family = AF_INET;
2643         } else if (data[IFLA_VXLAN_LOCAL6]) {
2644                 if (!IS_ENABLED(CONFIG_IPV6))
2645                         return -EPFNOSUPPORT;
2646
2647                 /* TODO: respect scope id */
2648                 nla_memcpy(&vxlan->saddr.sin6.sin6_addr, data[IFLA_VXLAN_LOCAL6],
2649                            sizeof(struct in6_addr));
2650                 vxlan->saddr.sa.sa_family = AF_INET6;
2651                 use_ipv6 = true;
2652         }
2653
2654         if (data[IFLA_VXLAN_LINK] &&
2655             (dst->remote_ifindex = nla_get_u32(data[IFLA_VXLAN_LINK]))) {
2656                 struct net_device *lowerdev
2657                          = __dev_get_by_index(net, dst->remote_ifindex);
2658
2659                 if (!lowerdev) {
2660                         pr_info("ifindex %d does not exist\n", dst->remote_ifindex);
2661                         return -ENODEV;
2662                 }
2663
2664 #if IS_ENABLED(CONFIG_IPV6)
2665                 if (use_ipv6) {
2666                         struct inet6_dev *idev = __in6_dev_get(lowerdev);
2667                         if (idev && idev->cnf.disable_ipv6) {
2668                                 pr_info("IPv6 is disabled via sysctl\n");
2669                                 return -EPERM;
2670                         }
2671                         vxlan->flags |= VXLAN_F_IPV6;
2672                 }
2673 #endif
2674
2675                 if (!tb[IFLA_MTU])
2676                         dev->mtu = lowerdev->mtu - (use_ipv6 ? VXLAN6_HEADROOM : VXLAN_HEADROOM);
2677
2678                 dev->needed_headroom = lowerdev->hard_header_len +
2679                                        (use_ipv6 ? VXLAN6_HEADROOM : VXLAN_HEADROOM);
2680         } else if (use_ipv6)
2681                 vxlan->flags |= VXLAN_F_IPV6;
2682
2683         if (data[IFLA_VXLAN_TOS])
2684                 vxlan->tos  = nla_get_u8(data[IFLA_VXLAN_TOS]);
2685
2686         if (data[IFLA_VXLAN_TTL])
2687                 vxlan->ttl = nla_get_u8(data[IFLA_VXLAN_TTL]);
2688
2689         if (!data[IFLA_VXLAN_LEARNING] || nla_get_u8(data[IFLA_VXLAN_LEARNING]))
2690                 vxlan->flags |= VXLAN_F_LEARN;
2691
2692         if (data[IFLA_VXLAN_AGEING])
2693                 vxlan->age_interval = nla_get_u32(data[IFLA_VXLAN_AGEING]);
2694         else
2695                 vxlan->age_interval = FDB_AGE_DEFAULT;
2696
2697         if (data[IFLA_VXLAN_PROXY] && nla_get_u8(data[IFLA_VXLAN_PROXY]))
2698                 vxlan->flags |= VXLAN_F_PROXY;
2699
2700         if (data[IFLA_VXLAN_RSC] && nla_get_u8(data[IFLA_VXLAN_RSC]))
2701                 vxlan->flags |= VXLAN_F_RSC;
2702
2703         if (data[IFLA_VXLAN_L2MISS] && nla_get_u8(data[IFLA_VXLAN_L2MISS]))
2704                 vxlan->flags |= VXLAN_F_L2MISS;
2705
2706         if (data[IFLA_VXLAN_L3MISS] && nla_get_u8(data[IFLA_VXLAN_L3MISS]))
2707                 vxlan->flags |= VXLAN_F_L3MISS;
2708
2709         if (data[IFLA_VXLAN_LIMIT])
2710                 vxlan->addrmax = nla_get_u32(data[IFLA_VXLAN_LIMIT]);
2711
2712         if (data[IFLA_VXLAN_PORT_RANGE]) {
2713                 const struct ifla_vxlan_port_range *p
2714                         = nla_data(data[IFLA_VXLAN_PORT_RANGE]);
2715                 vxlan->port_min = ntohs(p->low);
2716                 vxlan->port_max = ntohs(p->high);
2717         }
2718
2719         if (data[IFLA_VXLAN_PORT])
2720                 vxlan->dst_port = nla_get_be16(data[IFLA_VXLAN_PORT]);
2721
2722         if (vxlan_find_vni(net, vni, use_ipv6 ? AF_INET6 : AF_INET,
2723                            vxlan->dst_port)) {
2724                 pr_info("duplicate VNI %u\n", vni);
2725                 return -EEXIST;
2726         }
2727
2728         SET_ETHTOOL_OPS(dev, &vxlan_ethtool_ops);
2729
2730         /* create an fdb entry for a valid default destination */
2731         if (!vxlan_addr_any(&vxlan->default_dst.remote_ip)) {
2732                 err = vxlan_fdb_create(vxlan, all_zeros_mac,
2733                                        &vxlan->default_dst.remote_ip,
2734                                        NUD_REACHABLE|NUD_PERMANENT,
2735                                        NLM_F_EXCL|NLM_F_CREATE,
2736                                        vxlan->dst_port,
2737                                        vxlan->default_dst.remote_vni,
2738                                        vxlan->default_dst.remote_ifindex,
2739                                        NTF_SELF);
2740                 if (err)
2741                         return err;
2742         }
2743
2744         err = register_netdevice(dev);
2745         if (err) {
2746                 vxlan_fdb_delete_default(vxlan);
2747                 return err;
2748         }
2749
2750         list_add(&vxlan->next, &vn->vxlan_list);
2751
2752         return 0;
2753 }
2754
2755 static void vxlan_dellink(struct net_device *dev, struct list_head *head)
2756 {
2757         struct vxlan_net *vn = net_generic(dev_net(dev), vxlan_net_id);
2758         struct vxlan_dev *vxlan = netdev_priv(dev);
2759
2760         spin_lock(&vn->sock_lock);
2761         if (!hlist_unhashed(&vxlan->hlist))
2762                 hlist_del_rcu(&vxlan->hlist);
2763         spin_unlock(&vn->sock_lock);
2764
2765         list_del(&vxlan->next);
2766         unregister_netdevice_queue(dev, head);
2767 }
2768
2769 static size_t vxlan_get_size(const struct net_device *dev)
2770 {
2771
2772         return nla_total_size(sizeof(__u32)) +  /* IFLA_VXLAN_ID */
2773                 nla_total_size(sizeof(struct in6_addr)) + /* IFLA_VXLAN_GROUP{6} */
2774                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_LINK */
2775                 nla_total_size(sizeof(struct in6_addr)) + /* IFLA_VXLAN_LOCAL{6} */
2776                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_TTL */
2777                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_TOS */
2778                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_LEARNING */
2779                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_PROXY */
2780                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_RSC */
2781                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_L2MISS */
2782                 nla_total_size(sizeof(__u8)) +  /* IFLA_VXLAN_L3MISS */
2783                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_AGEING */
2784                 nla_total_size(sizeof(__u32)) + /* IFLA_VXLAN_LIMIT */
2785                 nla_total_size(sizeof(struct ifla_vxlan_port_range)) +
2786                 nla_total_size(sizeof(__be16))+ /* IFLA_VXLAN_PORT */
2787                 0;
2788 }
2789
2790 static int vxlan_fill_info(struct sk_buff *skb, const struct net_device *dev)
2791 {
2792         const struct vxlan_dev *vxlan = netdev_priv(dev);
2793         const struct vxlan_rdst *dst = &vxlan->default_dst;
2794         struct ifla_vxlan_port_range ports = {
2795                 .low =  htons(vxlan->port_min),
2796                 .high = htons(vxlan->port_max),
2797         };
2798
2799         if (nla_put_u32(skb, IFLA_VXLAN_ID, dst->remote_vni))
2800                 goto nla_put_failure;
2801
2802         if (!vxlan_addr_any(&dst->remote_ip)) {
2803                 if (dst->remote_ip.sa.sa_family == AF_INET) {
2804                         if (nla_put_be32(skb, IFLA_VXLAN_GROUP,
2805                                          dst->remote_ip.sin.sin_addr.s_addr))
2806                                 goto nla_put_failure;
2807 #if IS_ENABLED(CONFIG_IPV6)
2808                 } else {
2809                         if (nla_put(skb, IFLA_VXLAN_GROUP6, sizeof(struct in6_addr),
2810                                     &dst->remote_ip.sin6.sin6_addr))
2811                                 goto nla_put_failure;
2812 #endif
2813                 }
2814         }
2815
2816         if (dst->remote_ifindex && nla_put_u32(skb, IFLA_VXLAN_LINK, dst->remote_ifindex))
2817                 goto nla_put_failure;
2818
2819         if (!vxlan_addr_any(&vxlan->saddr)) {
2820                 if (vxlan->saddr.sa.sa_family == AF_INET) {
2821                         if (nla_put_be32(skb, IFLA_VXLAN_LOCAL,
2822                                          vxlan->saddr.sin.sin_addr.s_addr))
2823                                 goto nla_put_failure;
2824 #if IS_ENABLED(CONFIG_IPV6)
2825                 } else {
2826                         if (nla_put(skb, IFLA_VXLAN_LOCAL6, sizeof(struct in6_addr),
2827                                     &vxlan->saddr.sin6.sin6_addr))
2828                                 goto nla_put_failure;
2829 #endif
2830                 }
2831         }
2832
2833         if (nla_put_u8(skb, IFLA_VXLAN_TTL, vxlan->ttl) ||
2834             nla_put_u8(skb, IFLA_VXLAN_TOS, vxlan->tos) ||
2835             nla_put_u8(skb, IFLA_VXLAN_LEARNING,
2836                         !!(vxlan->flags & VXLAN_F_LEARN)) ||
2837             nla_put_u8(skb, IFLA_VXLAN_PROXY,
2838                         !!(vxlan->flags & VXLAN_F_PROXY)) ||
2839             nla_put_u8(skb, IFLA_VXLAN_RSC, !!(vxlan->flags & VXLAN_F_RSC)) ||
2840             nla_put_u8(skb, IFLA_VXLAN_L2MISS,
2841                         !!(vxlan->flags & VXLAN_F_L2MISS)) ||
2842             nla_put_u8(skb, IFLA_VXLAN_L3MISS,
2843                         !!(vxlan->flags & VXLAN_F_L3MISS)) ||
2844             nla_put_u32(skb, IFLA_VXLAN_AGEING, vxlan->age_interval) ||
2845             nla_put_u32(skb, IFLA_VXLAN_LIMIT, vxlan->addrmax) ||
2846             nla_put_be16(skb, IFLA_VXLAN_PORT, vxlan->dst_port))
2847                 goto nla_put_failure;
2848
2849         if (nla_put(skb, IFLA_VXLAN_PORT_RANGE, sizeof(ports), &ports))
2850                 goto nla_put_failure;
2851
2852         return 0;
2853
2854 nla_put_failure:
2855         return -EMSGSIZE;
2856 }
2857
2858 static struct rtnl_link_ops vxlan_link_ops __read_mostly = {
2859         .kind           = "vxlan",
2860         .maxtype        = IFLA_VXLAN_MAX,
2861         .policy         = vxlan_policy,
2862         .priv_size      = sizeof(struct vxlan_dev),
2863         .setup          = vxlan_setup,
2864         .validate       = vxlan_validate,
2865         .newlink        = vxlan_newlink,
2866         .dellink        = vxlan_dellink,
2867         .get_size       = vxlan_get_size,
2868         .fill_info      = vxlan_fill_info,
2869 };
2870
2871 static void vxlan_handle_lowerdev_unregister(struct vxlan_net *vn,
2872                                              struct net_device *dev)
2873 {
2874         struct vxlan_dev *vxlan, *next;
2875         LIST_HEAD(list_kill);
2876
2877         list_for_each_entry_safe(vxlan, next, &vn->vxlan_list, next) {
2878                 struct vxlan_rdst *dst = &vxlan->default_dst;
2879
2880                 /* In case we created vxlan device with carrier
2881                  * and we loose the carrier due to module unload
2882                  * we also need to remove vxlan device. In other
2883                  * cases, it's not necessary and remote_ifindex
2884                  * is 0 here, so no matches.
2885                  */
2886                 if (dst->remote_ifindex == dev->ifindex)
2887                         vxlan_dellink(vxlan->dev, &list_kill);
2888         }
2889
2890         unregister_netdevice_many(&list_kill);
2891 }
2892
2893 static int vxlan_lowerdev_event(struct notifier_block *unused,
2894                                 unsigned long event, void *ptr)
2895 {
2896         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2897         struct vxlan_net *vn = net_generic(dev_net(dev), vxlan_net_id);
2898
2899         if (event == NETDEV_UNREGISTER)
2900                 vxlan_handle_lowerdev_unregister(vn, dev);
2901
2902         return NOTIFY_DONE;
2903 }
2904
2905 static struct notifier_block vxlan_notifier_block __read_mostly = {
2906         .notifier_call = vxlan_lowerdev_event,
2907 };
2908
2909 static __net_init int vxlan_init_net(struct net *net)
2910 {
2911         struct vxlan_net *vn = net_generic(net, vxlan_net_id);
2912         unsigned int h;
2913
2914         INIT_LIST_HEAD(&vn->vxlan_list);
2915         spin_lock_init(&vn->sock_lock);
2916
2917         for (h = 0; h < PORT_HASH_SIZE; ++h)
2918                 INIT_HLIST_HEAD(&vn->sock_list[h]);
2919
2920         return 0;
2921 }
2922
2923 static struct pernet_operations vxlan_net_ops = {
2924         .init = vxlan_init_net,
2925         .id   = &vxlan_net_id,
2926         .size = sizeof(struct vxlan_net),
2927 };
2928
2929 static int __init vxlan_init_module(void)
2930 {
2931         int rc;
2932
2933         vxlan_wq = alloc_workqueue("vxlan", 0, 0);
2934         if (!vxlan_wq)
2935                 return -ENOMEM;
2936
2937         get_random_bytes(&vxlan_salt, sizeof(vxlan_salt));
2938
2939         rc = register_pernet_subsys(&vxlan_net_ops);
2940         if (rc)
2941                 goto out1;
2942
2943         rc = register_netdevice_notifier(&vxlan_notifier_block);
2944         if (rc)
2945                 goto out2;
2946
2947         rc = rtnl_link_register(&vxlan_link_ops);
2948         if (rc)
2949                 goto out3;
2950
2951         return 0;
2952 out3:
2953         unregister_netdevice_notifier(&vxlan_notifier_block);
2954 out2:
2955         unregister_pernet_subsys(&vxlan_net_ops);
2956 out1:
2957         destroy_workqueue(vxlan_wq);
2958         return rc;
2959 }
2960 late_initcall(vxlan_init_module);
2961
2962 static void __exit vxlan_cleanup_module(void)
2963 {
2964         rtnl_link_unregister(&vxlan_link_ops);
2965         unregister_netdevice_notifier(&vxlan_notifier_block);
2966         destroy_workqueue(vxlan_wq);
2967         unregister_pernet_subsys(&vxlan_net_ops);
2968         /* rcu_barrier() is called by netns */
2969 }
2970 module_exit(vxlan_cleanup_module);
2971
2972 MODULE_LICENSE("GPL");
2973 MODULE_VERSION(VXLAN_VERSION);
2974 MODULE_AUTHOR("Stephen Hemminger <stephen@networkplumber.org>");
2975 MODULE_DESCRIPTION("Driver for VXLAN encapsulated traffic");
2976 MODULE_ALIAS_RTNL_LINK("vxlan");