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