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