Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / drivers / net / vrf.c
1 /*
2  * vrf.c: device driver to encapsulate a VRF space
3  *
4  * Copyright (c) 2015 Cumulus Networks. All rights reserved.
5  * Copyright (c) 2015 Shrijeet Mukherjee <shm@cumulusnetworks.com>
6  * Copyright (c) 2015 David Ahern <dsa@cumulusnetworks.com>
7  *
8  * Based on dummy, team and ipvlan drivers
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  */
15
16 #include <linux/module.h>
17 #include <linux/kernel.h>
18 #include <linux/netdevice.h>
19 #include <linux/etherdevice.h>
20 #include <linux/ip.h>
21 #include <linux/init.h>
22 #include <linux/moduleparam.h>
23 #include <linux/netfilter.h>
24 #include <linux/rtnetlink.h>
25 #include <net/rtnetlink.h>
26 #include <linux/u64_stats_sync.h>
27 #include <linux/hashtable.h>
28
29 #include <linux/inetdevice.h>
30 #include <net/arp.h>
31 #include <net/ip.h>
32 #include <net/ip_fib.h>
33 #include <net/ip6_fib.h>
34 #include <net/ip6_route.h>
35 #include <net/rtnetlink.h>
36 #include <net/route.h>
37 #include <net/addrconf.h>
38 #include <net/l3mdev.h>
39
40 #define RT_FL_TOS(oldflp4) \
41         ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK))
42
43 #define DRV_NAME        "vrf"
44 #define DRV_VERSION     "1.0"
45
46 #define vrf_master_get_rcu(dev) \
47         ((struct net_device *)rcu_dereference(dev->rx_handler_data))
48
49 struct slave {
50         struct list_head        list;
51         struct net_device       *dev;
52 };
53
54 struct slave_queue {
55         struct list_head        all_slaves;
56 };
57
58 struct net_vrf {
59         struct slave_queue      queue;
60         struct rtable           *rth;
61         struct rt6_info         *rt6;
62         u32                     tb_id;
63 };
64
65 struct pcpu_dstats {
66         u64                     tx_pkts;
67         u64                     tx_bytes;
68         u64                     tx_drps;
69         u64                     rx_pkts;
70         u64                     rx_bytes;
71         struct u64_stats_sync   syncp;
72 };
73
74 static struct dst_entry *vrf_ip_check(struct dst_entry *dst, u32 cookie)
75 {
76         return dst;
77 }
78
79 static int vrf_ip_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
80 {
81         return ip_local_out(net, sk, skb);
82 }
83
84 static unsigned int vrf_v4_mtu(const struct dst_entry *dst)
85 {
86         /* TO-DO: return max ethernet size? */
87         return dst->dev->mtu;
88 }
89
90 static void vrf_dst_destroy(struct dst_entry *dst)
91 {
92         /* our dst lives forever - or until the device is closed */
93 }
94
95 static unsigned int vrf_default_advmss(const struct dst_entry *dst)
96 {
97         return 65535 - 40;
98 }
99
100 static struct dst_ops vrf_dst_ops = {
101         .family         = AF_INET,
102         .local_out      = vrf_ip_local_out,
103         .check          = vrf_ip_check,
104         .mtu            = vrf_v4_mtu,
105         .destroy        = vrf_dst_destroy,
106         .default_advmss = vrf_default_advmss,
107 };
108
109 /* neighbor handling is done with actual device; do not want
110  * to flip skb->dev for those ndisc packets. This really fails
111  * for multiple next protocols (e.g., NEXTHDR_HOP). But it is
112  * a start.
113  */
114 #if IS_ENABLED(CONFIG_IPV6)
115 static bool check_ipv6_frame(const struct sk_buff *skb)
116 {
117         const struct ipv6hdr *ipv6h;
118         struct ipv6hdr _ipv6h;
119         bool rc = true;
120
121         ipv6h = skb_header_pointer(skb, 0, sizeof(_ipv6h), &_ipv6h);
122         if (!ipv6h)
123                 goto out;
124
125         if (ipv6h->nexthdr == NEXTHDR_ICMP) {
126                 const struct icmp6hdr *icmph;
127                 struct icmp6hdr _icmph;
128
129                 icmph = skb_header_pointer(skb, sizeof(_ipv6h),
130                                            sizeof(_icmph), &_icmph);
131                 if (!icmph)
132                         goto out;
133
134                 switch (icmph->icmp6_type) {
135                 case NDISC_ROUTER_SOLICITATION:
136                 case NDISC_ROUTER_ADVERTISEMENT:
137                 case NDISC_NEIGHBOUR_SOLICITATION:
138                 case NDISC_NEIGHBOUR_ADVERTISEMENT:
139                 case NDISC_REDIRECT:
140                         rc = false;
141                         break;
142                 }
143         }
144
145 out:
146         return rc;
147 }
148 #else
149 static bool check_ipv6_frame(const struct sk_buff *skb)
150 {
151         return false;
152 }
153 #endif
154
155 static bool is_ip_rx_frame(struct sk_buff *skb)
156 {
157         switch (skb->protocol) {
158         case htons(ETH_P_IP):
159                 return true;
160         case htons(ETH_P_IPV6):
161                 return check_ipv6_frame(skb);
162         }
163         return false;
164 }
165
166 static void vrf_tx_error(struct net_device *vrf_dev, struct sk_buff *skb)
167 {
168         vrf_dev->stats.tx_errors++;
169         kfree_skb(skb);
170 }
171
172 /* note: already called with rcu_read_lock */
173 static rx_handler_result_t vrf_handle_frame(struct sk_buff **pskb)
174 {
175         struct sk_buff *skb = *pskb;
176
177         if (is_ip_rx_frame(skb)) {
178                 struct net_device *dev = vrf_master_get_rcu(skb->dev);
179                 struct pcpu_dstats *dstats = this_cpu_ptr(dev->dstats);
180
181                 u64_stats_update_begin(&dstats->syncp);
182                 dstats->rx_pkts++;
183                 dstats->rx_bytes += skb->len;
184                 u64_stats_update_end(&dstats->syncp);
185
186                 skb->dev = dev;
187
188                 return RX_HANDLER_ANOTHER;
189         }
190         return RX_HANDLER_PASS;
191 }
192
193 static struct rtnl_link_stats64 *vrf_get_stats64(struct net_device *dev,
194                                                  struct rtnl_link_stats64 *stats)
195 {
196         int i;
197
198         for_each_possible_cpu(i) {
199                 const struct pcpu_dstats *dstats;
200                 u64 tbytes, tpkts, tdrops, rbytes, rpkts;
201                 unsigned int start;
202
203                 dstats = per_cpu_ptr(dev->dstats, i);
204                 do {
205                         start = u64_stats_fetch_begin_irq(&dstats->syncp);
206                         tbytes = dstats->tx_bytes;
207                         tpkts = dstats->tx_pkts;
208                         tdrops = dstats->tx_drps;
209                         rbytes = dstats->rx_bytes;
210                         rpkts = dstats->rx_pkts;
211                 } while (u64_stats_fetch_retry_irq(&dstats->syncp, start));
212                 stats->tx_bytes += tbytes;
213                 stats->tx_packets += tpkts;
214                 stats->tx_dropped += tdrops;
215                 stats->rx_bytes += rbytes;
216                 stats->rx_packets += rpkts;
217         }
218         return stats;
219 }
220
221 #if IS_ENABLED(CONFIG_IPV6)
222 static netdev_tx_t vrf_process_v6_outbound(struct sk_buff *skb,
223                                            struct net_device *dev)
224 {
225         const struct ipv6hdr *iph = ipv6_hdr(skb);
226         struct net *net = dev_net(skb->dev);
227         struct flowi6 fl6 = {
228                 /* needed to match OIF rule */
229                 .flowi6_oif = dev->ifindex,
230                 .flowi6_iif = LOOPBACK_IFINDEX,
231                 .daddr = iph->daddr,
232                 .saddr = iph->saddr,
233                 .flowlabel = ip6_flowinfo(iph),
234                 .flowi6_mark = skb->mark,
235                 .flowi6_proto = iph->nexthdr,
236                 .flowi6_flags = FLOWI_FLAG_L3MDEV_SRC | FLOWI_FLAG_SKIP_NH_OIF,
237         };
238         int ret = NET_XMIT_DROP;
239         struct dst_entry *dst;
240         struct dst_entry *dst_null = &net->ipv6.ip6_null_entry->dst;
241
242         dst = ip6_route_output(net, NULL, &fl6);
243         if (dst == dst_null)
244                 goto err;
245
246         skb_dst_drop(skb);
247         skb_dst_set(skb, dst);
248
249         ret = ip6_local_out(net, skb->sk, skb);
250         if (unlikely(net_xmit_eval(ret)))
251                 dev->stats.tx_errors++;
252         else
253                 ret = NET_XMIT_SUCCESS;
254
255         return ret;
256 err:
257         vrf_tx_error(dev, skb);
258         return NET_XMIT_DROP;
259 }
260 #else
261 static netdev_tx_t vrf_process_v6_outbound(struct sk_buff *skb,
262                                            struct net_device *dev)
263 {
264         vrf_tx_error(dev, skb);
265         return NET_XMIT_DROP;
266 }
267 #endif
268
269 static int vrf_send_v4_prep(struct sk_buff *skb, struct flowi4 *fl4,
270                             struct net_device *vrf_dev)
271 {
272         struct rtable *rt;
273         int err = 1;
274
275         rt = ip_route_output_flow(dev_net(vrf_dev), fl4, NULL);
276         if (IS_ERR(rt))
277                 goto out;
278
279         /* TO-DO: what about broadcast ? */
280         if (rt->rt_type != RTN_UNICAST && rt->rt_type != RTN_LOCAL) {
281                 ip_rt_put(rt);
282                 goto out;
283         }
284
285         skb_dst_drop(skb);
286         skb_dst_set(skb, &rt->dst);
287         err = 0;
288 out:
289         return err;
290 }
291
292 static netdev_tx_t vrf_process_v4_outbound(struct sk_buff *skb,
293                                            struct net_device *vrf_dev)
294 {
295         struct iphdr *ip4h = ip_hdr(skb);
296         int ret = NET_XMIT_DROP;
297         struct flowi4 fl4 = {
298                 /* needed to match OIF rule */
299                 .flowi4_oif = vrf_dev->ifindex,
300                 .flowi4_iif = LOOPBACK_IFINDEX,
301                 .flowi4_tos = RT_TOS(ip4h->tos),
302                 .flowi4_flags = FLOWI_FLAG_ANYSRC | FLOWI_FLAG_L3MDEV_SRC |
303                                 FLOWI_FLAG_SKIP_NH_OIF,
304                 .flowi4_proto = ip4h->protocol,
305                 .daddr = ip4h->daddr,
306                 .saddr = ip4h->saddr,
307         };
308
309         if (vrf_send_v4_prep(skb, &fl4, vrf_dev))
310                 goto err;
311
312         if (!ip4h->saddr) {
313                 ip4h->saddr = inet_select_addr(skb_dst(skb)->dev, 0,
314                                                RT_SCOPE_LINK);
315         }
316
317         ret = ip_local_out(dev_net(skb_dst(skb)->dev), skb->sk, skb);
318         if (unlikely(net_xmit_eval(ret)))
319                 vrf_dev->stats.tx_errors++;
320         else
321                 ret = NET_XMIT_SUCCESS;
322
323 out:
324         return ret;
325 err:
326         vrf_tx_error(vrf_dev, skb);
327         goto out;
328 }
329
330 static netdev_tx_t is_ip_tx_frame(struct sk_buff *skb, struct net_device *dev)
331 {
332         /* strip the ethernet header added for pass through VRF device */
333         __skb_pull(skb, skb_network_offset(skb));
334
335         switch (skb->protocol) {
336         case htons(ETH_P_IP):
337                 return vrf_process_v4_outbound(skb, dev);
338         case htons(ETH_P_IPV6):
339                 return vrf_process_v6_outbound(skb, dev);
340         default:
341                 vrf_tx_error(dev, skb);
342                 return NET_XMIT_DROP;
343         }
344 }
345
346 static netdev_tx_t vrf_xmit(struct sk_buff *skb, struct net_device *dev)
347 {
348         netdev_tx_t ret = is_ip_tx_frame(skb, dev);
349
350         if (likely(ret == NET_XMIT_SUCCESS || ret == NET_XMIT_CN)) {
351                 struct pcpu_dstats *dstats = this_cpu_ptr(dev->dstats);
352
353                 u64_stats_update_begin(&dstats->syncp);
354                 dstats->tx_pkts++;
355                 dstats->tx_bytes += skb->len;
356                 u64_stats_update_end(&dstats->syncp);
357         } else {
358                 this_cpu_inc(dev->dstats->tx_drps);
359         }
360
361         return ret;
362 }
363
364 #if IS_ENABLED(CONFIG_IPV6)
365 static struct dst_entry *vrf_ip6_check(struct dst_entry *dst, u32 cookie)
366 {
367         return dst;
368 }
369
370 static struct dst_ops vrf_dst_ops6 = {
371         .family         = AF_INET6,
372         .local_out      = ip6_local_out,
373         .check          = vrf_ip6_check,
374         .mtu            = vrf_v4_mtu,
375         .destroy        = vrf_dst_destroy,
376         .default_advmss = vrf_default_advmss,
377 };
378
379 static int init_dst_ops6_kmem_cachep(void)
380 {
381         vrf_dst_ops6.kmem_cachep = kmem_cache_create("vrf_ip6_dst_cache",
382                                                      sizeof(struct rt6_info),
383                                                      0,
384                                                      SLAB_HWCACHE_ALIGN,
385                                                      NULL);
386
387         if (!vrf_dst_ops6.kmem_cachep)
388                 return -ENOMEM;
389
390         return 0;
391 }
392
393 static void free_dst_ops6_kmem_cachep(void)
394 {
395         kmem_cache_destroy(vrf_dst_ops6.kmem_cachep);
396 }
397
398 static int vrf_input6(struct sk_buff *skb)
399 {
400         skb->dev->stats.rx_errors++;
401         kfree_skb(skb);
402         return 0;
403 }
404
405 /* modelled after ip6_finish_output2 */
406 static int vrf_finish_output6(struct net *net, struct sock *sk,
407                               struct sk_buff *skb)
408 {
409         struct dst_entry *dst = skb_dst(skb);
410         struct net_device *dev = dst->dev;
411         struct neighbour *neigh;
412         struct in6_addr *nexthop;
413         int ret;
414
415         nf_reset(skb);
416
417         skb->protocol = htons(ETH_P_IPV6);
418         skb->dev = dev;
419
420         rcu_read_lock_bh();
421         nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr);
422         neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop);
423         if (unlikely(!neigh))
424                 neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false);
425         if (!IS_ERR(neigh)) {
426                 ret = dst_neigh_output(dst, neigh, skb);
427                 rcu_read_unlock_bh();
428                 return ret;
429         }
430         rcu_read_unlock_bh();
431
432         IP6_INC_STATS(dev_net(dst->dev),
433                       ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
434         kfree_skb(skb);
435         return -EINVAL;
436 }
437
438 /* modelled after ip6_output */
439 static int vrf_output6(struct net *net, struct sock *sk, struct sk_buff *skb)
440 {
441         return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING,
442                             net, sk, skb, NULL, skb_dst(skb)->dev,
443                             vrf_finish_output6,
444                             !(IP6CB(skb)->flags & IP6SKB_REROUTED));
445 }
446
447 static void vrf_rt6_destroy(struct net_vrf *vrf)
448 {
449         dst_destroy(&vrf->rt6->dst);
450         free_percpu(vrf->rt6->rt6i_pcpu);
451         vrf->rt6 = NULL;
452 }
453
454 static int vrf_rt6_create(struct net_device *dev)
455 {
456         struct net_vrf *vrf = netdev_priv(dev);
457         struct dst_entry *dst;
458         struct rt6_info *rt6;
459         int cpu;
460         int rc = -ENOMEM;
461
462         rt6 = dst_alloc(&vrf_dst_ops6, dev, 0,
463                         DST_OBSOLETE_NONE,
464                         (DST_HOST | DST_NOPOLICY | DST_NOXFRM));
465         if (!rt6)
466                 goto out;
467
468         dst = &rt6->dst;
469
470         rt6->rt6i_pcpu = alloc_percpu_gfp(struct rt6_info *, GFP_KERNEL);
471         if (!rt6->rt6i_pcpu) {
472                 dst_destroy(dst);
473                 goto out;
474         }
475         for_each_possible_cpu(cpu) {
476                 struct rt6_info **p = per_cpu_ptr(rt6->rt6i_pcpu, cpu);
477                 *p =  NULL;
478         }
479
480         memset(dst + 1, 0, sizeof(*rt6) - sizeof(*dst));
481
482         INIT_LIST_HEAD(&rt6->rt6i_siblings);
483         INIT_LIST_HEAD(&rt6->rt6i_uncached);
484
485         rt6->dst.input  = vrf_input6;
486         rt6->dst.output = vrf_output6;
487
488         rt6->rt6i_table = fib6_get_table(dev_net(dev), vrf->tb_id);
489
490         atomic_set(&rt6->dst.__refcnt, 2);
491
492         vrf->rt6 = rt6;
493         rc = 0;
494 out:
495         return rc;
496 }
497 #else
498 static int init_dst_ops6_kmem_cachep(void)
499 {
500         return 0;
501 }
502
503 static void free_dst_ops6_kmem_cachep(void)
504 {
505 }
506
507 static void vrf_rt6_destroy(struct net_vrf *vrf)
508 {
509 }
510
511 static int vrf_rt6_create(struct net_device *dev)
512 {
513         return 0;
514 }
515 #endif
516
517 /* modelled after ip_finish_output2 */
518 static int vrf_finish_output(struct net *net, struct sock *sk, struct sk_buff *skb)
519 {
520         struct dst_entry *dst = skb_dst(skb);
521         struct rtable *rt = (struct rtable *)dst;
522         struct net_device *dev = dst->dev;
523         unsigned int hh_len = LL_RESERVED_SPACE(dev);
524         struct neighbour *neigh;
525         u32 nexthop;
526         int ret = -EINVAL;
527
528         nf_reset(skb);
529
530         /* Be paranoid, rather than too clever. */
531         if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
532                 struct sk_buff *skb2;
533
534                 skb2 = skb_realloc_headroom(skb, LL_RESERVED_SPACE(dev));
535                 if (!skb2) {
536                         ret = -ENOMEM;
537                         goto err;
538                 }
539                 if (skb->sk)
540                         skb_set_owner_w(skb2, skb->sk);
541
542                 consume_skb(skb);
543                 skb = skb2;
544         }
545
546         rcu_read_lock_bh();
547
548         nexthop = (__force u32)rt_nexthop(rt, ip_hdr(skb)->daddr);
549         neigh = __ipv4_neigh_lookup_noref(dev, nexthop);
550         if (unlikely(!neigh))
551                 neigh = __neigh_create(&arp_tbl, &nexthop, dev, false);
552         if (!IS_ERR(neigh))
553                 ret = dst_neigh_output(dst, neigh, skb);
554
555         rcu_read_unlock_bh();
556 err:
557         if (unlikely(ret < 0))
558                 vrf_tx_error(skb->dev, skb);
559         return ret;
560 }
561
562 static int vrf_output(struct net *net, struct sock *sk, struct sk_buff *skb)
563 {
564         struct net_device *dev = skb_dst(skb)->dev;
565
566         IP_UPD_PO_STATS(net, IPSTATS_MIB_OUT, skb->len);
567
568         skb->dev = dev;
569         skb->protocol = htons(ETH_P_IP);
570
571         return NF_HOOK_COND(NFPROTO_IPV4, NF_INET_POST_ROUTING,
572                             net, sk, skb, NULL, dev,
573                             vrf_finish_output,
574                             !(IPCB(skb)->flags & IPSKB_REROUTED));
575 }
576
577 static void vrf_rtable_destroy(struct net_vrf *vrf)
578 {
579         struct dst_entry *dst = (struct dst_entry *)vrf->rth;
580
581         dst_destroy(dst);
582         vrf->rth = NULL;
583 }
584
585 static struct rtable *vrf_rtable_create(struct net_device *dev)
586 {
587         struct net_vrf *vrf = netdev_priv(dev);
588         struct rtable *rth;
589
590         rth = dst_alloc(&vrf_dst_ops, dev, 2,
591                         DST_OBSOLETE_NONE,
592                         (DST_HOST | DST_NOPOLICY | DST_NOXFRM));
593         if (rth) {
594                 rth->dst.output = vrf_output;
595                 rth->rt_genid   = rt_genid_ipv4(dev_net(dev));
596                 rth->rt_flags   = 0;
597                 rth->rt_type    = RTN_UNICAST;
598                 rth->rt_is_input = 0;
599                 rth->rt_iif     = 0;
600                 rth->rt_pmtu    = 0;
601                 rth->rt_gateway = 0;
602                 rth->rt_uses_gateway = 0;
603                 rth->rt_table_id = vrf->tb_id;
604                 INIT_LIST_HEAD(&rth->rt_uncached);
605                 rth->rt_uncached_list = NULL;
606         }
607
608         return rth;
609 }
610
611 /**************************** device handling ********************/
612
613 /* cycle interface to flush neighbor cache and move routes across tables */
614 static void cycle_netdev(struct net_device *dev)
615 {
616         unsigned int flags = dev->flags;
617         int ret;
618
619         if (!netif_running(dev))
620                 return;
621
622         ret = dev_change_flags(dev, flags & ~IFF_UP);
623         if (ret >= 0)
624                 ret = dev_change_flags(dev, flags);
625
626         if (ret < 0) {
627                 netdev_err(dev,
628                            "Failed to cycle device %s; route tables might be wrong!\n",
629                            dev->name);
630         }
631 }
632
633 static struct slave *__vrf_find_slave_dev(struct slave_queue *queue,
634                                           struct net_device *dev)
635 {
636         struct list_head *head = &queue->all_slaves;
637         struct slave *slave;
638
639         list_for_each_entry(slave, head, list) {
640                 if (slave->dev == dev)
641                         return slave;
642         }
643
644         return NULL;
645 }
646
647 /* inverse of __vrf_insert_slave */
648 static void __vrf_remove_slave(struct slave_queue *queue, struct slave *slave)
649 {
650         list_del(&slave->list);
651 }
652
653 static void __vrf_insert_slave(struct slave_queue *queue, struct slave *slave)
654 {
655         list_add(&slave->list, &queue->all_slaves);
656 }
657
658 static int do_vrf_add_slave(struct net_device *dev, struct net_device *port_dev)
659 {
660         struct slave *slave = kzalloc(sizeof(*slave), GFP_KERNEL);
661         struct net_vrf *vrf = netdev_priv(dev);
662         struct slave_queue *queue = &vrf->queue;
663         int ret = -ENOMEM;
664
665         if (!slave)
666                 goto out_fail;
667
668         slave->dev = port_dev;
669
670         /* register the packet handler for slave ports */
671         ret = netdev_rx_handler_register(port_dev, vrf_handle_frame, dev);
672         if (ret) {
673                 netdev_err(port_dev,
674                            "Device %s failed to register rx_handler\n",
675                            port_dev->name);
676                 goto out_fail;
677         }
678
679         ret = netdev_master_upper_dev_link(port_dev, dev);
680         if (ret < 0)
681                 goto out_unregister;
682
683         port_dev->priv_flags |= IFF_L3MDEV_SLAVE;
684         __vrf_insert_slave(queue, slave);
685         cycle_netdev(port_dev);
686
687         return 0;
688
689 out_unregister:
690         netdev_rx_handler_unregister(port_dev);
691 out_fail:
692         kfree(slave);
693         return ret;
694 }
695
696 static int vrf_add_slave(struct net_device *dev, struct net_device *port_dev)
697 {
698         if (netif_is_l3_master(port_dev) || netif_is_l3_slave(port_dev))
699                 return -EINVAL;
700
701         return do_vrf_add_slave(dev, port_dev);
702 }
703
704 /* inverse of do_vrf_add_slave */
705 static int do_vrf_del_slave(struct net_device *dev, struct net_device *port_dev)
706 {
707         struct net_vrf *vrf = netdev_priv(dev);
708         struct slave_queue *queue = &vrf->queue;
709         struct slave *slave;
710
711         netdev_upper_dev_unlink(port_dev, dev);
712         port_dev->priv_flags &= ~IFF_L3MDEV_SLAVE;
713
714         netdev_rx_handler_unregister(port_dev);
715
716         cycle_netdev(port_dev);
717
718         slave = __vrf_find_slave_dev(queue, port_dev);
719         if (slave)
720                 __vrf_remove_slave(queue, slave);
721
722         kfree(slave);
723
724         return 0;
725 }
726
727 static int vrf_del_slave(struct net_device *dev, struct net_device *port_dev)
728 {
729         return do_vrf_del_slave(dev, port_dev);
730 }
731
732 static void vrf_dev_uninit(struct net_device *dev)
733 {
734         struct net_vrf *vrf = netdev_priv(dev);
735         struct slave_queue *queue = &vrf->queue;
736         struct list_head *head = &queue->all_slaves;
737         struct slave *slave, *next;
738
739         vrf_rtable_destroy(vrf);
740         vrf_rt6_destroy(vrf);
741
742         list_for_each_entry_safe(slave, next, head, list)
743                 vrf_del_slave(dev, slave->dev);
744
745         free_percpu(dev->dstats);
746         dev->dstats = NULL;
747 }
748
749 static int vrf_dev_init(struct net_device *dev)
750 {
751         struct net_vrf *vrf = netdev_priv(dev);
752
753         INIT_LIST_HEAD(&vrf->queue.all_slaves);
754
755         dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
756         if (!dev->dstats)
757                 goto out_nomem;
758
759         /* create the default dst which points back to us */
760         vrf->rth = vrf_rtable_create(dev);
761         if (!vrf->rth)
762                 goto out_stats;
763
764         if (vrf_rt6_create(dev) != 0)
765                 goto out_rth;
766
767         dev->flags = IFF_MASTER | IFF_NOARP;
768
769         return 0;
770
771 out_rth:
772         vrf_rtable_destroy(vrf);
773 out_stats:
774         free_percpu(dev->dstats);
775         dev->dstats = NULL;
776 out_nomem:
777         return -ENOMEM;
778 }
779
780 static const struct net_device_ops vrf_netdev_ops = {
781         .ndo_init               = vrf_dev_init,
782         .ndo_uninit             = vrf_dev_uninit,
783         .ndo_start_xmit         = vrf_xmit,
784         .ndo_get_stats64        = vrf_get_stats64,
785         .ndo_add_slave          = vrf_add_slave,
786         .ndo_del_slave          = vrf_del_slave,
787 };
788
789 static u32 vrf_fib_table(const struct net_device *dev)
790 {
791         struct net_vrf *vrf = netdev_priv(dev);
792
793         return vrf->tb_id;
794 }
795
796 static struct rtable *vrf_get_rtable(const struct net_device *dev,
797                                      const struct flowi4 *fl4)
798 {
799         struct rtable *rth = NULL;
800
801         if (!(fl4->flowi4_flags & FLOWI_FLAG_L3MDEV_SRC)) {
802                 struct net_vrf *vrf = netdev_priv(dev);
803
804                 rth = vrf->rth;
805                 atomic_inc(&rth->dst.__refcnt);
806         }
807
808         return rth;
809 }
810
811 /* called under rcu_read_lock */
812 static int vrf_get_saddr(struct net_device *dev, struct flowi4 *fl4)
813 {
814         struct fib_result res = { .tclassid = 0 };
815         struct net *net = dev_net(dev);
816         u32 orig_tos = fl4->flowi4_tos;
817         u8 flags = fl4->flowi4_flags;
818         u8 scope = fl4->flowi4_scope;
819         u8 tos = RT_FL_TOS(fl4);
820         int rc;
821
822         if (unlikely(!fl4->daddr))
823                 return 0;
824
825         fl4->flowi4_flags |= FLOWI_FLAG_SKIP_NH_OIF;
826         fl4->flowi4_iif = LOOPBACK_IFINDEX;
827         fl4->flowi4_tos = tos & IPTOS_RT_MASK;
828         fl4->flowi4_scope = ((tos & RTO_ONLINK) ?
829                              RT_SCOPE_LINK : RT_SCOPE_UNIVERSE);
830
831         rc = fib_lookup(net, fl4, &res, 0);
832         if (!rc) {
833                 if (res.type == RTN_LOCAL)
834                         fl4->saddr = res.fi->fib_prefsrc ? : fl4->daddr;
835                 else
836                         fib_select_path(net, &res, fl4, -1);
837         }
838
839         fl4->flowi4_flags = flags;
840         fl4->flowi4_tos = orig_tos;
841         fl4->flowi4_scope = scope;
842
843         return rc;
844 }
845
846 #if IS_ENABLED(CONFIG_IPV6)
847 static struct dst_entry *vrf_get_rt6_dst(const struct net_device *dev,
848                                          const struct flowi6 *fl6)
849 {
850         struct rt6_info *rt = NULL;
851
852         if (!(fl6->flowi6_flags & FLOWI_FLAG_L3MDEV_SRC)) {
853                 struct net_vrf *vrf = netdev_priv(dev);
854
855                 rt = vrf->rt6;
856                 atomic_inc(&rt->dst.__refcnt);
857         }
858
859         return (struct dst_entry *)rt;
860 }
861 #endif
862
863 static const struct l3mdev_ops vrf_l3mdev_ops = {
864         .l3mdev_fib_table       = vrf_fib_table,
865         .l3mdev_get_rtable      = vrf_get_rtable,
866         .l3mdev_get_saddr       = vrf_get_saddr,
867 #if IS_ENABLED(CONFIG_IPV6)
868         .l3mdev_get_rt6_dst     = vrf_get_rt6_dst,
869 #endif
870 };
871
872 static void vrf_get_drvinfo(struct net_device *dev,
873                             struct ethtool_drvinfo *info)
874 {
875         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
876         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
877 }
878
879 static const struct ethtool_ops vrf_ethtool_ops = {
880         .get_drvinfo    = vrf_get_drvinfo,
881 };
882
883 static void vrf_setup(struct net_device *dev)
884 {
885         ether_setup(dev);
886
887         /* Initialize the device structure. */
888         dev->netdev_ops = &vrf_netdev_ops;
889         dev->l3mdev_ops = &vrf_l3mdev_ops;
890         dev->ethtool_ops = &vrf_ethtool_ops;
891         dev->destructor = free_netdev;
892
893         /* Fill in device structure with ethernet-generic values. */
894         eth_hw_addr_random(dev);
895
896         /* don't acquire vrf device's netif_tx_lock when transmitting */
897         dev->features |= NETIF_F_LLTX;
898
899         /* don't allow vrf devices to change network namespaces. */
900         dev->features |= NETIF_F_NETNS_LOCAL;
901 }
902
903 static int vrf_validate(struct nlattr *tb[], struct nlattr *data[])
904 {
905         if (tb[IFLA_ADDRESS]) {
906                 if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
907                         return -EINVAL;
908                 if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
909                         return -EADDRNOTAVAIL;
910         }
911         return 0;
912 }
913
914 static void vrf_dellink(struct net_device *dev, struct list_head *head)
915 {
916         unregister_netdevice_queue(dev, head);
917 }
918
919 static int vrf_newlink(struct net *src_net, struct net_device *dev,
920                        struct nlattr *tb[], struct nlattr *data[])
921 {
922         struct net_vrf *vrf = netdev_priv(dev);
923
924         if (!data || !data[IFLA_VRF_TABLE])
925                 return -EINVAL;
926
927         vrf->tb_id = nla_get_u32(data[IFLA_VRF_TABLE]);
928         if (vrf->tb_id == RT_TABLE_UNSPEC)
929                 return -EINVAL;
930
931         dev->priv_flags |= IFF_L3MDEV_MASTER;
932
933         return register_netdevice(dev);
934 }
935
936 static size_t vrf_nl_getsize(const struct net_device *dev)
937 {
938         return nla_total_size(sizeof(u32));  /* IFLA_VRF_TABLE */
939 }
940
941 static int vrf_fillinfo(struct sk_buff *skb,
942                         const struct net_device *dev)
943 {
944         struct net_vrf *vrf = netdev_priv(dev);
945
946         return nla_put_u32(skb, IFLA_VRF_TABLE, vrf->tb_id);
947 }
948
949 static const struct nla_policy vrf_nl_policy[IFLA_VRF_MAX + 1] = {
950         [IFLA_VRF_TABLE] = { .type = NLA_U32 },
951 };
952
953 static struct rtnl_link_ops vrf_link_ops __read_mostly = {
954         .kind           = DRV_NAME,
955         .priv_size      = sizeof(struct net_vrf),
956
957         .get_size       = vrf_nl_getsize,
958         .policy         = vrf_nl_policy,
959         .validate       = vrf_validate,
960         .fill_info      = vrf_fillinfo,
961
962         .newlink        = vrf_newlink,
963         .dellink        = vrf_dellink,
964         .setup          = vrf_setup,
965         .maxtype        = IFLA_VRF_MAX,
966 };
967
968 static int vrf_device_event(struct notifier_block *unused,
969                             unsigned long event, void *ptr)
970 {
971         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
972
973         /* only care about unregister events to drop slave references */
974         if (event == NETDEV_UNREGISTER) {
975                 struct net_device *vrf_dev;
976
977                 if (!netif_is_l3_slave(dev))
978                         goto out;
979
980                 vrf_dev = netdev_master_upper_dev_get(dev);
981                 vrf_del_slave(vrf_dev, dev);
982         }
983 out:
984         return NOTIFY_DONE;
985 }
986
987 static struct notifier_block vrf_notifier_block __read_mostly = {
988         .notifier_call = vrf_device_event,
989 };
990
991 static int __init vrf_init_module(void)
992 {
993         int rc;
994
995         vrf_dst_ops.kmem_cachep =
996                 kmem_cache_create("vrf_ip_dst_cache",
997                                   sizeof(struct rtable), 0,
998                                   SLAB_HWCACHE_ALIGN,
999                                   NULL);
1000
1001         if (!vrf_dst_ops.kmem_cachep)
1002                 return -ENOMEM;
1003
1004         rc = init_dst_ops6_kmem_cachep();
1005         if (rc != 0)
1006                 goto error2;
1007
1008         register_netdevice_notifier(&vrf_notifier_block);
1009
1010         rc = rtnl_link_register(&vrf_link_ops);
1011         if (rc < 0)
1012                 goto error;
1013
1014         return 0;
1015
1016 error:
1017         unregister_netdevice_notifier(&vrf_notifier_block);
1018         free_dst_ops6_kmem_cachep();
1019 error2:
1020         kmem_cache_destroy(vrf_dst_ops.kmem_cachep);
1021         return rc;
1022 }
1023
1024 static void __exit vrf_cleanup_module(void)
1025 {
1026         rtnl_link_unregister(&vrf_link_ops);
1027         unregister_netdevice_notifier(&vrf_notifier_block);
1028         kmem_cache_destroy(vrf_dst_ops.kmem_cachep);
1029         free_dst_ops6_kmem_cachep();
1030 }
1031
1032 module_init(vrf_init_module);
1033 module_exit(vrf_cleanup_module);
1034 MODULE_AUTHOR("Shrijeet Mukherjee, David Ahern");
1035 MODULE_DESCRIPTION("Device driver to instantiate VRF domains");
1036 MODULE_LICENSE("GPL");
1037 MODULE_ALIAS_RTNL_LINK(DRV_NAME);
1038 MODULE_VERSION(DRV_VERSION);