GNU Linux-libre 4.14.265-gnu1
[releases.git] / net / mpls / af_mpls.c
1 #include <linux/types.h>
2 #include <linux/skbuff.h>
3 #include <linux/socket.h>
4 #include <linux/sysctl.h>
5 #include <linux/net.h>
6 #include <linux/module.h>
7 #include <linux/if_arp.h>
8 #include <linux/ipv6.h>
9 #include <linux/mpls.h>
10 #include <linux/netconf.h>
11 #include <linux/nospec.h>
12 #include <linux/vmalloc.h>
13 #include <linux/percpu.h>
14 #include <net/ip.h>
15 #include <net/dst.h>
16 #include <net/sock.h>
17 #include <net/arp.h>
18 #include <net/ip_fib.h>
19 #include <net/netevent.h>
20 #include <net/netns/generic.h>
21 #if IS_ENABLED(CONFIG_IPV6)
22 #include <net/ipv6.h>
23 #endif
24 #include <net/addrconf.h>
25 #include <net/nexthop.h>
26 #include "internal.h"
27
28 /* max memory we will use for mpls_route */
29 #define MAX_MPLS_ROUTE_MEM      4096
30
31 /* Maximum number of labels to look ahead at when selecting a path of
32  * a multipath route
33  */
34 #define MAX_MP_SELECT_LABELS 4
35
36 #define MPLS_NEIGH_TABLE_UNSPEC (NEIGH_LINK_TABLE + 1)
37
38 static int zero = 0;
39 static int one = 1;
40 static int label_limit = (1 << 20) - 1;
41 static int ttl_max = 255;
42
43 static void rtmsg_lfib(int event, u32 label, struct mpls_route *rt,
44                        struct nlmsghdr *nlh, struct net *net, u32 portid,
45                        unsigned int nlm_flags);
46
47 static struct mpls_route *mpls_route_input_rcu(struct net *net, unsigned index)
48 {
49         struct mpls_route *rt = NULL;
50
51         if (index < net->mpls.platform_labels) {
52                 struct mpls_route __rcu **platform_label =
53                         rcu_dereference(net->mpls.platform_label);
54                 rt = rcu_dereference(platform_label[index]);
55         }
56         return rt;
57 }
58
59 bool mpls_output_possible(const struct net_device *dev)
60 {
61         return dev && (dev->flags & IFF_UP) && netif_carrier_ok(dev);
62 }
63 EXPORT_SYMBOL_GPL(mpls_output_possible);
64
65 static u8 *__mpls_nh_via(struct mpls_route *rt, struct mpls_nh *nh)
66 {
67         return (u8 *)nh + rt->rt_via_offset;
68 }
69
70 static const u8 *mpls_nh_via(const struct mpls_route *rt,
71                              const struct mpls_nh *nh)
72 {
73         return __mpls_nh_via((struct mpls_route *)rt, (struct mpls_nh *)nh);
74 }
75
76 static unsigned int mpls_nh_header_size(const struct mpls_nh *nh)
77 {
78         /* The size of the layer 2.5 labels to be added for this route */
79         return nh->nh_labels * sizeof(struct mpls_shim_hdr);
80 }
81
82 unsigned int mpls_dev_mtu(const struct net_device *dev)
83 {
84         /* The amount of data the layer 2 frame can hold */
85         return dev->mtu;
86 }
87 EXPORT_SYMBOL_GPL(mpls_dev_mtu);
88
89 bool mpls_pkt_too_big(const struct sk_buff *skb, unsigned int mtu)
90 {
91         if (skb->len <= mtu)
92                 return false;
93
94         if (skb_is_gso(skb) && skb_gso_validate_mtu(skb, mtu))
95                 return false;
96
97         return true;
98 }
99 EXPORT_SYMBOL_GPL(mpls_pkt_too_big);
100
101 void mpls_stats_inc_outucastpkts(struct net_device *dev,
102                                  const struct sk_buff *skb)
103 {
104         struct mpls_dev *mdev;
105
106         if (skb->protocol == htons(ETH_P_MPLS_UC)) {
107                 mdev = mpls_dev_get(dev);
108                 if (mdev)
109                         MPLS_INC_STATS_LEN(mdev, skb->len,
110                                            tx_packets,
111                                            tx_bytes);
112         } else if (skb->protocol == htons(ETH_P_IP)) {
113                 IP_UPD_PO_STATS(dev_net(dev), IPSTATS_MIB_OUT, skb->len);
114 #if IS_ENABLED(CONFIG_IPV6)
115         } else if (skb->protocol == htons(ETH_P_IPV6)) {
116                 struct inet6_dev *in6dev = __in6_dev_get(dev);
117
118                 if (in6dev)
119                         IP6_UPD_PO_STATS(dev_net(dev), in6dev,
120                                          IPSTATS_MIB_OUT, skb->len);
121 #endif
122         }
123 }
124 EXPORT_SYMBOL_GPL(mpls_stats_inc_outucastpkts);
125
126 static u32 mpls_multipath_hash(struct mpls_route *rt, struct sk_buff *skb)
127 {
128         struct mpls_entry_decoded dec;
129         unsigned int mpls_hdr_len = 0;
130         struct mpls_shim_hdr *hdr;
131         bool eli_seen = false;
132         int label_index;
133         u32 hash = 0;
134
135         for (label_index = 0; label_index < MAX_MP_SELECT_LABELS;
136              label_index++) {
137                 mpls_hdr_len += sizeof(*hdr);
138                 if (!pskb_may_pull(skb, mpls_hdr_len))
139                         break;
140
141                 /* Read and decode the current label */
142                 hdr = mpls_hdr(skb) + label_index;
143                 dec = mpls_entry_decode(hdr);
144
145                 /* RFC6790 - reserved labels MUST NOT be used as keys
146                  * for the load-balancing function
147                  */
148                 if (likely(dec.label >= MPLS_LABEL_FIRST_UNRESERVED)) {
149                         hash = jhash_1word(dec.label, hash);
150
151                         /* The entropy label follows the entropy label
152                          * indicator, so this means that the entropy
153                          * label was just added to the hash - no need to
154                          * go any deeper either in the label stack or in the
155                          * payload
156                          */
157                         if (eli_seen)
158                                 break;
159                 } else if (dec.label == MPLS_LABEL_ENTROPY) {
160                         eli_seen = true;
161                 }
162
163                 if (!dec.bos)
164                         continue;
165
166                 /* found bottom label; does skb have room for a header? */
167                 if (pskb_may_pull(skb, mpls_hdr_len + sizeof(struct iphdr))) {
168                         const struct iphdr *v4hdr;
169
170                         v4hdr = (const struct iphdr *)(hdr + 1);
171                         if (v4hdr->version == 4) {
172                                 hash = jhash_3words(ntohl(v4hdr->saddr),
173                                                     ntohl(v4hdr->daddr),
174                                                     v4hdr->protocol, hash);
175                         } else if (v4hdr->version == 6 &&
176                                    pskb_may_pull(skb, mpls_hdr_len +
177                                                  sizeof(struct ipv6hdr))) {
178                                 const struct ipv6hdr *v6hdr;
179
180                                 v6hdr = (const struct ipv6hdr *)(hdr + 1);
181                                 hash = __ipv6_addr_jhash(&v6hdr->saddr, hash);
182                                 hash = __ipv6_addr_jhash(&v6hdr->daddr, hash);
183                                 hash = jhash_1word(v6hdr->nexthdr, hash);
184                         }
185                 }
186
187                 break;
188         }
189
190         return hash;
191 }
192
193 static struct mpls_nh *mpls_get_nexthop(struct mpls_route *rt, u8 index)
194 {
195         return (struct mpls_nh *)((u8 *)rt->rt_nh + index * rt->rt_nh_size);
196 }
197
198 /* number of alive nexthops (rt->rt_nhn_alive) and the flags for
199  * a next hop (nh->nh_flags) are modified by netdev event handlers.
200  * Since those fields can change at any moment, use READ_ONCE to
201  * access both.
202  */
203 static struct mpls_nh *mpls_select_multipath(struct mpls_route *rt,
204                                              struct sk_buff *skb)
205 {
206         u32 hash = 0;
207         int nh_index = 0;
208         int n = 0;
209         u8 alive;
210
211         /* No need to look further into packet if there's only
212          * one path
213          */
214         if (rt->rt_nhn == 1)
215                 return rt->rt_nh;
216
217         alive = READ_ONCE(rt->rt_nhn_alive);
218         if (alive == 0)
219                 return NULL;
220
221         hash = mpls_multipath_hash(rt, skb);
222         nh_index = hash % alive;
223         if (alive == rt->rt_nhn)
224                 goto out;
225         for_nexthops(rt) {
226                 unsigned int nh_flags = READ_ONCE(nh->nh_flags);
227
228                 if (nh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN))
229                         continue;
230                 if (n == nh_index)
231                         return nh;
232                 n++;
233         } endfor_nexthops(rt);
234
235 out:
236         return mpls_get_nexthop(rt, nh_index);
237 }
238
239 static bool mpls_egress(struct net *net, struct mpls_route *rt,
240                         struct sk_buff *skb, struct mpls_entry_decoded dec)
241 {
242         enum mpls_payload_type payload_type;
243         bool success = false;
244
245         /* The IPv4 code below accesses through the IPv4 header
246          * checksum, which is 12 bytes into the packet.
247          * The IPv6 code below accesses through the IPv6 hop limit
248          * which is 8 bytes into the packet.
249          *
250          * For all supported cases there should always be at least 12
251          * bytes of packet data present.  The IPv4 header is 20 bytes
252          * without options and the IPv6 header is always 40 bytes
253          * long.
254          */
255         if (!pskb_may_pull(skb, 12))
256                 return false;
257
258         payload_type = rt->rt_payload_type;
259         if (payload_type == MPT_UNSPEC)
260                 payload_type = ip_hdr(skb)->version;
261
262         switch (payload_type) {
263         case MPT_IPV4: {
264                 struct iphdr *hdr4 = ip_hdr(skb);
265                 u8 new_ttl;
266                 skb->protocol = htons(ETH_P_IP);
267
268                 /* If propagating TTL, take the decremented TTL from
269                  * the incoming MPLS header, otherwise decrement the
270                  * TTL, but only if not 0 to avoid underflow.
271                  */
272                 if (rt->rt_ttl_propagate == MPLS_TTL_PROP_ENABLED ||
273                     (rt->rt_ttl_propagate == MPLS_TTL_PROP_DEFAULT &&
274                      net->mpls.ip_ttl_propagate))
275                         new_ttl = dec.ttl;
276                 else
277                         new_ttl = hdr4->ttl ? hdr4->ttl - 1 : 0;
278
279                 csum_replace2(&hdr4->check,
280                               htons(hdr4->ttl << 8),
281                               htons(new_ttl << 8));
282                 hdr4->ttl = new_ttl;
283                 success = true;
284                 break;
285         }
286         case MPT_IPV6: {
287                 struct ipv6hdr *hdr6 = ipv6_hdr(skb);
288                 skb->protocol = htons(ETH_P_IPV6);
289
290                 /* If propagating TTL, take the decremented TTL from
291                  * the incoming MPLS header, otherwise decrement the
292                  * hop limit, but only if not 0 to avoid underflow.
293                  */
294                 if (rt->rt_ttl_propagate == MPLS_TTL_PROP_ENABLED ||
295                     (rt->rt_ttl_propagate == MPLS_TTL_PROP_DEFAULT &&
296                      net->mpls.ip_ttl_propagate))
297                         hdr6->hop_limit = dec.ttl;
298                 else if (hdr6->hop_limit)
299                         hdr6->hop_limit = hdr6->hop_limit - 1;
300                 success = true;
301                 break;
302         }
303         case MPT_UNSPEC:
304                 /* Should have decided which protocol it is by now */
305                 break;
306         }
307
308         return success;
309 }
310
311 static int mpls_forward(struct sk_buff *skb, struct net_device *dev,
312                         struct packet_type *pt, struct net_device *orig_dev)
313 {
314         struct net *net = dev_net(dev);
315         struct mpls_shim_hdr *hdr;
316         struct mpls_route *rt;
317         struct mpls_nh *nh;
318         struct mpls_entry_decoded dec;
319         struct net_device *out_dev;
320         struct mpls_dev *out_mdev;
321         struct mpls_dev *mdev;
322         unsigned int hh_len;
323         unsigned int new_header_size;
324         unsigned int mtu;
325         int err;
326
327         /* Careful this entire function runs inside of an rcu critical section */
328
329         mdev = mpls_dev_get(dev);
330         if (!mdev)
331                 goto drop;
332
333         MPLS_INC_STATS_LEN(mdev, skb->len, rx_packets,
334                            rx_bytes);
335
336         if (!mdev->input_enabled) {
337                 MPLS_INC_STATS(mdev, rx_dropped);
338                 goto drop;
339         }
340
341         if (skb->pkt_type != PACKET_HOST)
342                 goto err;
343
344         if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
345                 goto err;
346
347         if (!pskb_may_pull(skb, sizeof(*hdr)))
348                 goto err;
349
350         /* Read and decode the label */
351         hdr = mpls_hdr(skb);
352         dec = mpls_entry_decode(hdr);
353
354         rt = mpls_route_input_rcu(net, dec.label);
355         if (!rt) {
356                 MPLS_INC_STATS(mdev, rx_noroute);
357                 goto drop;
358         }
359
360         nh = mpls_select_multipath(rt, skb);
361         if (!nh)
362                 goto err;
363
364         /* Pop the label */
365         skb_pull(skb, sizeof(*hdr));
366         skb_reset_network_header(skb);
367
368         skb_orphan(skb);
369
370         if (skb_warn_if_lro(skb))
371                 goto err;
372
373         skb_forward_csum(skb);
374
375         /* Verify ttl is valid */
376         if (dec.ttl <= 1)
377                 goto err;
378         dec.ttl -= 1;
379
380         /* Find the output device */
381         out_dev = rcu_dereference(nh->nh_dev);
382         if (!mpls_output_possible(out_dev))
383                 goto tx_err;
384
385         /* Verify the destination can hold the packet */
386         new_header_size = mpls_nh_header_size(nh);
387         mtu = mpls_dev_mtu(out_dev);
388         if (mpls_pkt_too_big(skb, mtu - new_header_size))
389                 goto tx_err;
390
391         hh_len = LL_RESERVED_SPACE(out_dev);
392         if (!out_dev->header_ops)
393                 hh_len = 0;
394
395         /* Ensure there is enough space for the headers in the skb */
396         if (skb_cow(skb, hh_len + new_header_size))
397                 goto tx_err;
398
399         skb->dev = out_dev;
400         skb->protocol = htons(ETH_P_MPLS_UC);
401
402         if (unlikely(!new_header_size && dec.bos)) {
403                 /* Penultimate hop popping */
404                 if (!mpls_egress(dev_net(out_dev), rt, skb, dec))
405                         goto err;
406         } else {
407                 bool bos;
408                 int i;
409                 skb_push(skb, new_header_size);
410                 skb_reset_network_header(skb);
411                 /* Push the new labels */
412                 hdr = mpls_hdr(skb);
413                 bos = dec.bos;
414                 for (i = nh->nh_labels - 1; i >= 0; i--) {
415                         hdr[i] = mpls_entry_encode(nh->nh_label[i],
416                                                    dec.ttl, 0, bos);
417                         bos = false;
418                 }
419         }
420
421         mpls_stats_inc_outucastpkts(out_dev, skb);
422
423         /* If via wasn't specified then send out using device address */
424         if (nh->nh_via_table == MPLS_NEIGH_TABLE_UNSPEC)
425                 err = neigh_xmit(NEIGH_LINK_TABLE, out_dev,
426                                  out_dev->dev_addr, skb);
427         else
428                 err = neigh_xmit(nh->nh_via_table, out_dev,
429                                  mpls_nh_via(rt, nh), skb);
430         if (err)
431                 net_dbg_ratelimited("%s: packet transmission failed: %d\n",
432                                     __func__, err);
433         return 0;
434
435 tx_err:
436         out_mdev = out_dev ? mpls_dev_get(out_dev) : NULL;
437         if (out_mdev)
438                 MPLS_INC_STATS(out_mdev, tx_errors);
439         goto drop;
440 err:
441         MPLS_INC_STATS(mdev, rx_errors);
442 drop:
443         kfree_skb(skb);
444         return NET_RX_DROP;
445 }
446
447 static struct packet_type mpls_packet_type __read_mostly = {
448         .type = cpu_to_be16(ETH_P_MPLS_UC),
449         .func = mpls_forward,
450 };
451
452 static const struct nla_policy rtm_mpls_policy[RTA_MAX+1] = {
453         [RTA_DST]               = { .type = NLA_U32 },
454         [RTA_OIF]               = { .type = NLA_U32 },
455         [RTA_TTL_PROPAGATE]     = { .type = NLA_U8 },
456 };
457
458 struct mpls_route_config {
459         u32                     rc_protocol;
460         u32                     rc_ifindex;
461         u8                      rc_via_table;
462         u8                      rc_via_alen;
463         u8                      rc_via[MAX_VIA_ALEN];
464         u32                     rc_label;
465         u8                      rc_ttl_propagate;
466         u8                      rc_output_labels;
467         u32                     rc_output_label[MAX_NEW_LABELS];
468         u32                     rc_nlflags;
469         enum mpls_payload_type  rc_payload_type;
470         struct nl_info          rc_nlinfo;
471         struct rtnexthop        *rc_mp;
472         int                     rc_mp_len;
473 };
474
475 /* all nexthops within a route have the same size based on max
476  * number of labels and max via length for a hop
477  */
478 static struct mpls_route *mpls_rt_alloc(u8 num_nh, u8 max_alen, u8 max_labels)
479 {
480         u8 nh_size = MPLS_NH_SIZE(max_labels, max_alen);
481         struct mpls_route *rt;
482         size_t size;
483
484         size = sizeof(*rt) + num_nh * nh_size;
485         if (size > MAX_MPLS_ROUTE_MEM)
486                 return ERR_PTR(-EINVAL);
487
488         rt = kzalloc(size, GFP_KERNEL);
489         if (!rt)
490                 return ERR_PTR(-ENOMEM);
491
492         rt->rt_nhn = num_nh;
493         rt->rt_nhn_alive = num_nh;
494         rt->rt_nh_size = nh_size;
495         rt->rt_via_offset = MPLS_NH_VIA_OFF(max_labels);
496
497         return rt;
498 }
499
500 static void mpls_rt_free(struct mpls_route *rt)
501 {
502         if (rt)
503                 kfree_rcu(rt, rt_rcu);
504 }
505
506 static void mpls_notify_route(struct net *net, unsigned index,
507                               struct mpls_route *old, struct mpls_route *new,
508                               const struct nl_info *info)
509 {
510         struct nlmsghdr *nlh = info ? info->nlh : NULL;
511         unsigned portid = info ? info->portid : 0;
512         int event = new ? RTM_NEWROUTE : RTM_DELROUTE;
513         struct mpls_route *rt = new ? new : old;
514         unsigned nlm_flags = (old && new) ? NLM_F_REPLACE : 0;
515         /* Ignore reserved labels for now */
516         if (rt && (index >= MPLS_LABEL_FIRST_UNRESERVED))
517                 rtmsg_lfib(event, index, rt, nlh, net, portid, nlm_flags);
518 }
519
520 static void mpls_route_update(struct net *net, unsigned index,
521                               struct mpls_route *new,
522                               const struct nl_info *info)
523 {
524         struct mpls_route __rcu **platform_label;
525         struct mpls_route *rt;
526
527         ASSERT_RTNL();
528
529         platform_label = rtnl_dereference(net->mpls.platform_label);
530         rt = rtnl_dereference(platform_label[index]);
531         rcu_assign_pointer(platform_label[index], new);
532
533         mpls_notify_route(net, index, rt, new, info);
534
535         /* If we removed a route free it now */
536         mpls_rt_free(rt);
537 }
538
539 static unsigned find_free_label(struct net *net)
540 {
541         struct mpls_route __rcu **platform_label;
542         size_t platform_labels;
543         unsigned index;
544
545         platform_label = rtnl_dereference(net->mpls.platform_label);
546         platform_labels = net->mpls.platform_labels;
547         for (index = MPLS_LABEL_FIRST_UNRESERVED; index < platform_labels;
548              index++) {
549                 if (!rtnl_dereference(platform_label[index]))
550                         return index;
551         }
552         return LABEL_NOT_SPECIFIED;
553 }
554
555 #if IS_ENABLED(CONFIG_INET)
556 static struct net_device *inet_fib_lookup_dev(struct net *net,
557                                               const void *addr)
558 {
559         struct net_device *dev;
560         struct rtable *rt;
561         struct in_addr daddr;
562
563         memcpy(&daddr, addr, sizeof(struct in_addr));
564         rt = ip_route_output(net, daddr.s_addr, 0, 0, 0);
565         if (IS_ERR(rt))
566                 return ERR_CAST(rt);
567
568         dev = rt->dst.dev;
569         dev_hold(dev);
570
571         ip_rt_put(rt);
572
573         return dev;
574 }
575 #else
576 static struct net_device *inet_fib_lookup_dev(struct net *net,
577                                               const void *addr)
578 {
579         return ERR_PTR(-EAFNOSUPPORT);
580 }
581 #endif
582
583 #if IS_ENABLED(CONFIG_IPV6)
584 static struct net_device *inet6_fib_lookup_dev(struct net *net,
585                                                const void *addr)
586 {
587         struct net_device *dev;
588         struct dst_entry *dst;
589         struct flowi6 fl6;
590
591         if (!ipv6_stub)
592                 return ERR_PTR(-EAFNOSUPPORT);
593
594         memset(&fl6, 0, sizeof(fl6));
595         memcpy(&fl6.daddr, addr, sizeof(struct in6_addr));
596         dst = ipv6_stub->ipv6_dst_lookup_flow(net, NULL, &fl6, NULL);
597         if (IS_ERR(dst))
598                 return ERR_CAST(dst);
599
600         dev = dst->dev;
601         dev_hold(dev);
602         dst_release(dst);
603
604         return dev;
605 }
606 #else
607 static struct net_device *inet6_fib_lookup_dev(struct net *net,
608                                                const void *addr)
609 {
610         return ERR_PTR(-EAFNOSUPPORT);
611 }
612 #endif
613
614 static struct net_device *find_outdev(struct net *net,
615                                       struct mpls_route *rt,
616                                       struct mpls_nh *nh, int oif)
617 {
618         struct net_device *dev = NULL;
619
620         if (!oif) {
621                 switch (nh->nh_via_table) {
622                 case NEIGH_ARP_TABLE:
623                         dev = inet_fib_lookup_dev(net, mpls_nh_via(rt, nh));
624                         break;
625                 case NEIGH_ND_TABLE:
626                         dev = inet6_fib_lookup_dev(net, mpls_nh_via(rt, nh));
627                         break;
628                 case NEIGH_LINK_TABLE:
629                         break;
630                 }
631         } else {
632                 dev = dev_get_by_index(net, oif);
633         }
634
635         if (!dev)
636                 return ERR_PTR(-ENODEV);
637
638         if (IS_ERR(dev))
639                 return dev;
640
641         /* The caller is holding rtnl anyways, so release the dev reference */
642         dev_put(dev);
643
644         return dev;
645 }
646
647 static int mpls_nh_assign_dev(struct net *net, struct mpls_route *rt,
648                               struct mpls_nh *nh, int oif)
649 {
650         struct net_device *dev = NULL;
651         int err = -ENODEV;
652
653         dev = find_outdev(net, rt, nh, oif);
654         if (IS_ERR(dev)) {
655                 err = PTR_ERR(dev);
656                 dev = NULL;
657                 goto errout;
658         }
659
660         /* Ensure this is a supported device */
661         err = -EINVAL;
662         if (!mpls_dev_get(dev))
663                 goto errout;
664
665         if ((nh->nh_via_table == NEIGH_LINK_TABLE) &&
666             (dev->addr_len != nh->nh_via_alen))
667                 goto errout;
668
669         RCU_INIT_POINTER(nh->nh_dev, dev);
670
671         if (!(dev->flags & IFF_UP)) {
672                 nh->nh_flags |= RTNH_F_DEAD;
673         } else {
674                 unsigned int flags;
675
676                 flags = dev_get_flags(dev);
677                 if (!(flags & (IFF_RUNNING | IFF_LOWER_UP)))
678                         nh->nh_flags |= RTNH_F_LINKDOWN;
679         }
680
681         return 0;
682
683 errout:
684         return err;
685 }
686
687 static int nla_get_via(const struct nlattr *nla, u8 *via_alen, u8 *via_table,
688                        u8 via_addr[], struct netlink_ext_ack *extack)
689 {
690         struct rtvia *via = nla_data(nla);
691         int err = -EINVAL;
692         int alen;
693
694         if (nla_len(nla) < offsetof(struct rtvia, rtvia_addr)) {
695                 NL_SET_ERR_MSG_ATTR(extack, nla,
696                                     "Invalid attribute length for RTA_VIA");
697                 goto errout;
698         }
699         alen = nla_len(nla) -
700                         offsetof(struct rtvia, rtvia_addr);
701         if (alen > MAX_VIA_ALEN) {
702                 NL_SET_ERR_MSG_ATTR(extack, nla,
703                                     "Invalid address length for RTA_VIA");
704                 goto errout;
705         }
706
707         /* Validate the address family */
708         switch (via->rtvia_family) {
709         case AF_PACKET:
710                 *via_table = NEIGH_LINK_TABLE;
711                 break;
712         case AF_INET:
713                 *via_table = NEIGH_ARP_TABLE;
714                 if (alen != 4)
715                         goto errout;
716                 break;
717         case AF_INET6:
718                 *via_table = NEIGH_ND_TABLE;
719                 if (alen != 16)
720                         goto errout;
721                 break;
722         default:
723                 /* Unsupported address family */
724                 goto errout;
725         }
726
727         memcpy(via_addr, via->rtvia_addr, alen);
728         *via_alen = alen;
729         err = 0;
730
731 errout:
732         return err;
733 }
734
735 static int mpls_nh_build_from_cfg(struct mpls_route_config *cfg,
736                                   struct mpls_route *rt)
737 {
738         struct net *net = cfg->rc_nlinfo.nl_net;
739         struct mpls_nh *nh = rt->rt_nh;
740         int err;
741         int i;
742
743         if (!nh)
744                 return -ENOMEM;
745
746         nh->nh_labels = cfg->rc_output_labels;
747         for (i = 0; i < nh->nh_labels; i++)
748                 nh->nh_label[i] = cfg->rc_output_label[i];
749
750         nh->nh_via_table = cfg->rc_via_table;
751         memcpy(__mpls_nh_via(rt, nh), cfg->rc_via, cfg->rc_via_alen);
752         nh->nh_via_alen = cfg->rc_via_alen;
753
754         err = mpls_nh_assign_dev(net, rt, nh, cfg->rc_ifindex);
755         if (err)
756                 goto errout;
757
758         if (nh->nh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN))
759                 rt->rt_nhn_alive--;
760
761         return 0;
762
763 errout:
764         return err;
765 }
766
767 static int mpls_nh_build(struct net *net, struct mpls_route *rt,
768                          struct mpls_nh *nh, int oif, struct nlattr *via,
769                          struct nlattr *newdst, u8 max_labels,
770                          struct netlink_ext_ack *extack)
771 {
772         int err = -ENOMEM;
773
774         if (!nh)
775                 goto errout;
776
777         if (newdst) {
778                 err = nla_get_labels(newdst, max_labels, &nh->nh_labels,
779                                      nh->nh_label, extack);
780                 if (err)
781                         goto errout;
782         }
783
784         if (via) {
785                 err = nla_get_via(via, &nh->nh_via_alen, &nh->nh_via_table,
786                                   __mpls_nh_via(rt, nh), extack);
787                 if (err)
788                         goto errout;
789         } else {
790                 nh->nh_via_table = MPLS_NEIGH_TABLE_UNSPEC;
791         }
792
793         err = mpls_nh_assign_dev(net, rt, nh, oif);
794         if (err)
795                 goto errout;
796
797         return 0;
798
799 errout:
800         return err;
801 }
802
803 static u8 mpls_count_nexthops(struct rtnexthop *rtnh, int len,
804                               u8 cfg_via_alen, u8 *max_via_alen,
805                               u8 *max_labels)
806 {
807         int remaining = len;
808         u8 nhs = 0;
809
810         *max_via_alen = 0;
811         *max_labels = 0;
812
813         while (rtnh_ok(rtnh, remaining)) {
814                 struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
815                 int attrlen;
816                 u8 n_labels = 0;
817
818                 attrlen = rtnh_attrlen(rtnh);
819                 nla = nla_find(attrs, attrlen, RTA_VIA);
820                 if (nla && nla_len(nla) >=
821                     offsetof(struct rtvia, rtvia_addr)) {
822                         int via_alen = nla_len(nla) -
823                                 offsetof(struct rtvia, rtvia_addr);
824
825                         if (via_alen <= MAX_VIA_ALEN)
826                                 *max_via_alen = max_t(u16, *max_via_alen,
827                                                       via_alen);
828                 }
829
830                 nla = nla_find(attrs, attrlen, RTA_NEWDST);
831                 if (nla &&
832                     nla_get_labels(nla, MAX_NEW_LABELS, &n_labels,
833                                    NULL, NULL) != 0)
834                         return 0;
835
836                 *max_labels = max_t(u8, *max_labels, n_labels);
837
838                 /* number of nexthops is tracked by a u8.
839                  * Check for overflow.
840                  */
841                 if (nhs == 255)
842                         return 0;
843                 nhs++;
844
845                 rtnh = rtnh_next(rtnh, &remaining);
846         }
847
848         /* leftover implies invalid nexthop configuration, discard it */
849         return remaining > 0 ? 0 : nhs;
850 }
851
852 static int mpls_nh_build_multi(struct mpls_route_config *cfg,
853                                struct mpls_route *rt, u8 max_labels,
854                                struct netlink_ext_ack *extack)
855 {
856         struct rtnexthop *rtnh = cfg->rc_mp;
857         struct nlattr *nla_via, *nla_newdst;
858         int remaining = cfg->rc_mp_len;
859         int err = 0;
860         u8 nhs = 0;
861
862         change_nexthops(rt) {
863                 int attrlen;
864
865                 nla_via = NULL;
866                 nla_newdst = NULL;
867
868                 err = -EINVAL;
869                 if (!rtnh_ok(rtnh, remaining))
870                         goto errout;
871
872                 /* neither weighted multipath nor any flags
873                  * are supported
874                  */
875                 if (rtnh->rtnh_hops || rtnh->rtnh_flags)
876                         goto errout;
877
878                 attrlen = rtnh_attrlen(rtnh);
879                 if (attrlen > 0) {
880                         struct nlattr *attrs = rtnh_attrs(rtnh);
881
882                         nla_via = nla_find(attrs, attrlen, RTA_VIA);
883                         nla_newdst = nla_find(attrs, attrlen, RTA_NEWDST);
884                 }
885
886                 err = mpls_nh_build(cfg->rc_nlinfo.nl_net, rt, nh,
887                                     rtnh->rtnh_ifindex, nla_via, nla_newdst,
888                                     max_labels, extack);
889                 if (err)
890                         goto errout;
891
892                 if (nh->nh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN))
893                         rt->rt_nhn_alive--;
894
895                 rtnh = rtnh_next(rtnh, &remaining);
896                 nhs++;
897         } endfor_nexthops(rt);
898
899         rt->rt_nhn = nhs;
900
901         return 0;
902
903 errout:
904         return err;
905 }
906
907 static bool mpls_label_ok(struct net *net, unsigned int *index,
908                           struct netlink_ext_ack *extack)
909 {
910         bool is_ok = true;
911
912         /* Reserved labels may not be set */
913         if (*index < MPLS_LABEL_FIRST_UNRESERVED) {
914                 NL_SET_ERR_MSG(extack,
915                                "Invalid label - must be MPLS_LABEL_FIRST_UNRESERVED or higher");
916                 is_ok = false;
917         }
918
919         /* The full 20 bit range may not be supported. */
920         if (is_ok && *index >= net->mpls.platform_labels) {
921                 NL_SET_ERR_MSG(extack,
922                                "Label >= configured maximum in platform_labels");
923                 is_ok = false;
924         }
925
926         *index = array_index_nospec(*index, net->mpls.platform_labels);
927         return is_ok;
928 }
929
930 static int mpls_route_add(struct mpls_route_config *cfg,
931                           struct netlink_ext_ack *extack)
932 {
933         struct mpls_route __rcu **platform_label;
934         struct net *net = cfg->rc_nlinfo.nl_net;
935         struct mpls_route *rt, *old;
936         int err = -EINVAL;
937         u8 max_via_alen;
938         unsigned index;
939         u8 max_labels;
940         u8 nhs;
941
942         index = cfg->rc_label;
943
944         /* If a label was not specified during insert pick one */
945         if ((index == LABEL_NOT_SPECIFIED) &&
946             (cfg->rc_nlflags & NLM_F_CREATE)) {
947                 index = find_free_label(net);
948         }
949
950         if (!mpls_label_ok(net, &index, extack))
951                 goto errout;
952
953         /* Append makes no sense with mpls */
954         err = -EOPNOTSUPP;
955         if (cfg->rc_nlflags & NLM_F_APPEND) {
956                 NL_SET_ERR_MSG(extack, "MPLS does not support route append");
957                 goto errout;
958         }
959
960         err = -EEXIST;
961         platform_label = rtnl_dereference(net->mpls.platform_label);
962         old = rtnl_dereference(platform_label[index]);
963         if ((cfg->rc_nlflags & NLM_F_EXCL) && old)
964                 goto errout;
965
966         err = -EEXIST;
967         if (!(cfg->rc_nlflags & NLM_F_REPLACE) && old)
968                 goto errout;
969
970         err = -ENOENT;
971         if (!(cfg->rc_nlflags & NLM_F_CREATE) && !old)
972                 goto errout;
973
974         err = -EINVAL;
975         if (cfg->rc_mp) {
976                 nhs = mpls_count_nexthops(cfg->rc_mp, cfg->rc_mp_len,
977                                           cfg->rc_via_alen, &max_via_alen,
978                                           &max_labels);
979         } else {
980                 max_via_alen = cfg->rc_via_alen;
981                 max_labels = cfg->rc_output_labels;
982                 nhs = 1;
983         }
984
985         if (nhs == 0) {
986                 NL_SET_ERR_MSG(extack, "Route does not contain a nexthop");
987                 goto errout;
988         }
989
990         err = -ENOMEM;
991         rt = mpls_rt_alloc(nhs, max_via_alen, max_labels);
992         if (IS_ERR(rt)) {
993                 err = PTR_ERR(rt);
994                 goto errout;
995         }
996
997         rt->rt_protocol = cfg->rc_protocol;
998         rt->rt_payload_type = cfg->rc_payload_type;
999         rt->rt_ttl_propagate = cfg->rc_ttl_propagate;
1000
1001         if (cfg->rc_mp)
1002                 err = mpls_nh_build_multi(cfg, rt, max_labels, extack);
1003         else
1004                 err = mpls_nh_build_from_cfg(cfg, rt);
1005         if (err)
1006                 goto freert;
1007
1008         mpls_route_update(net, index, rt, &cfg->rc_nlinfo);
1009
1010         return 0;
1011
1012 freert:
1013         mpls_rt_free(rt);
1014 errout:
1015         return err;
1016 }
1017
1018 static int mpls_route_del(struct mpls_route_config *cfg,
1019                           struct netlink_ext_ack *extack)
1020 {
1021         struct net *net = cfg->rc_nlinfo.nl_net;
1022         unsigned index;
1023         int err = -EINVAL;
1024
1025         index = cfg->rc_label;
1026
1027         if (!mpls_label_ok(net, &index, extack))
1028                 goto errout;
1029
1030         mpls_route_update(net, index, NULL, &cfg->rc_nlinfo);
1031
1032         err = 0;
1033 errout:
1034         return err;
1035 }
1036
1037 static void mpls_get_stats(struct mpls_dev *mdev,
1038                            struct mpls_link_stats *stats)
1039 {
1040         struct mpls_pcpu_stats *p;
1041         int i;
1042
1043         memset(stats, 0, sizeof(*stats));
1044
1045         for_each_possible_cpu(i) {
1046                 struct mpls_link_stats local;
1047                 unsigned int start;
1048
1049                 p = per_cpu_ptr(mdev->stats, i);
1050                 do {
1051                         start = u64_stats_fetch_begin(&p->syncp);
1052                         local = p->stats;
1053                 } while (u64_stats_fetch_retry(&p->syncp, start));
1054
1055                 stats->rx_packets       += local.rx_packets;
1056                 stats->rx_bytes         += local.rx_bytes;
1057                 stats->tx_packets       += local.tx_packets;
1058                 stats->tx_bytes         += local.tx_bytes;
1059                 stats->rx_errors        += local.rx_errors;
1060                 stats->tx_errors        += local.tx_errors;
1061                 stats->rx_dropped       += local.rx_dropped;
1062                 stats->tx_dropped       += local.tx_dropped;
1063                 stats->rx_noroute       += local.rx_noroute;
1064         }
1065 }
1066
1067 static int mpls_fill_stats_af(struct sk_buff *skb,
1068                               const struct net_device *dev)
1069 {
1070         struct mpls_link_stats *stats;
1071         struct mpls_dev *mdev;
1072         struct nlattr *nla;
1073
1074         mdev = mpls_dev_get(dev);
1075         if (!mdev)
1076                 return -ENODATA;
1077
1078         nla = nla_reserve_64bit(skb, MPLS_STATS_LINK,
1079                                 sizeof(struct mpls_link_stats),
1080                                 MPLS_STATS_UNSPEC);
1081         if (!nla)
1082                 return -EMSGSIZE;
1083
1084         stats = nla_data(nla);
1085         mpls_get_stats(mdev, stats);
1086
1087         return 0;
1088 }
1089
1090 static size_t mpls_get_stats_af_size(const struct net_device *dev)
1091 {
1092         struct mpls_dev *mdev;
1093
1094         mdev = mpls_dev_get(dev);
1095         if (!mdev)
1096                 return 0;
1097
1098         return nla_total_size_64bit(sizeof(struct mpls_link_stats));
1099 }
1100
1101 static int mpls_netconf_fill_devconf(struct sk_buff *skb, struct mpls_dev *mdev,
1102                                      u32 portid, u32 seq, int event,
1103                                      unsigned int flags, int type)
1104 {
1105         struct nlmsghdr  *nlh;
1106         struct netconfmsg *ncm;
1107         bool all = false;
1108
1109         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
1110                         flags);
1111         if (!nlh)
1112                 return -EMSGSIZE;
1113
1114         if (type == NETCONFA_ALL)
1115                 all = true;
1116
1117         ncm = nlmsg_data(nlh);
1118         ncm->ncm_family = AF_MPLS;
1119
1120         if (nla_put_s32(skb, NETCONFA_IFINDEX, mdev->dev->ifindex) < 0)
1121                 goto nla_put_failure;
1122
1123         if ((all || type == NETCONFA_INPUT) &&
1124             nla_put_s32(skb, NETCONFA_INPUT,
1125                         mdev->input_enabled) < 0)
1126                 goto nla_put_failure;
1127
1128         nlmsg_end(skb, nlh);
1129         return 0;
1130
1131 nla_put_failure:
1132         nlmsg_cancel(skb, nlh);
1133         return -EMSGSIZE;
1134 }
1135
1136 static int mpls_netconf_msgsize_devconf(int type)
1137 {
1138         int size = NLMSG_ALIGN(sizeof(struct netconfmsg))
1139                         + nla_total_size(4); /* NETCONFA_IFINDEX */
1140         bool all = false;
1141
1142         if (type == NETCONFA_ALL)
1143                 all = true;
1144
1145         if (all || type == NETCONFA_INPUT)
1146                 size += nla_total_size(4);
1147
1148         return size;
1149 }
1150
1151 static void mpls_netconf_notify_devconf(struct net *net, int event,
1152                                         int type, struct mpls_dev *mdev)
1153 {
1154         struct sk_buff *skb;
1155         int err = -ENOBUFS;
1156
1157         skb = nlmsg_new(mpls_netconf_msgsize_devconf(type), GFP_KERNEL);
1158         if (!skb)
1159                 goto errout;
1160
1161         err = mpls_netconf_fill_devconf(skb, mdev, 0, 0, event, 0, type);
1162         if (err < 0) {
1163                 /* -EMSGSIZE implies BUG in mpls_netconf_msgsize_devconf() */
1164                 WARN_ON(err == -EMSGSIZE);
1165                 kfree_skb(skb);
1166                 goto errout;
1167         }
1168
1169         rtnl_notify(skb, net, 0, RTNLGRP_MPLS_NETCONF, NULL, GFP_KERNEL);
1170         return;
1171 errout:
1172         if (err < 0)
1173                 rtnl_set_sk_err(net, RTNLGRP_MPLS_NETCONF, err);
1174 }
1175
1176 static const struct nla_policy devconf_mpls_policy[NETCONFA_MAX + 1] = {
1177         [NETCONFA_IFINDEX]      = { .len = sizeof(int) },
1178 };
1179
1180 static int mpls_netconf_get_devconf(struct sk_buff *in_skb,
1181                                     struct nlmsghdr *nlh,
1182                                     struct netlink_ext_ack *extack)
1183 {
1184         struct net *net = sock_net(in_skb->sk);
1185         struct nlattr *tb[NETCONFA_MAX + 1];
1186         struct netconfmsg *ncm;
1187         struct net_device *dev;
1188         struct mpls_dev *mdev;
1189         struct sk_buff *skb;
1190         int ifindex;
1191         int err;
1192
1193         err = nlmsg_parse(nlh, sizeof(*ncm), tb, NETCONFA_MAX,
1194                           devconf_mpls_policy, NULL);
1195         if (err < 0)
1196                 goto errout;
1197
1198         err = -EINVAL;
1199         if (!tb[NETCONFA_IFINDEX])
1200                 goto errout;
1201
1202         ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
1203         dev = __dev_get_by_index(net, ifindex);
1204         if (!dev)
1205                 goto errout;
1206
1207         mdev = mpls_dev_get(dev);
1208         if (!mdev)
1209                 goto errout;
1210
1211         err = -ENOBUFS;
1212         skb = nlmsg_new(mpls_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
1213         if (!skb)
1214                 goto errout;
1215
1216         err = mpls_netconf_fill_devconf(skb, mdev,
1217                                         NETLINK_CB(in_skb).portid,
1218                                         nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
1219                                         NETCONFA_ALL);
1220         if (err < 0) {
1221                 /* -EMSGSIZE implies BUG in mpls_netconf_msgsize_devconf() */
1222                 WARN_ON(err == -EMSGSIZE);
1223                 kfree_skb(skb);
1224                 goto errout;
1225         }
1226         err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
1227 errout:
1228         return err;
1229 }
1230
1231 static int mpls_netconf_dump_devconf(struct sk_buff *skb,
1232                                      struct netlink_callback *cb)
1233 {
1234         struct net *net = sock_net(skb->sk);
1235         struct hlist_head *head;
1236         struct net_device *dev;
1237         struct mpls_dev *mdev;
1238         int idx, s_idx;
1239         int h, s_h;
1240
1241         s_h = cb->args[0];
1242         s_idx = idx = cb->args[1];
1243
1244         for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
1245                 idx = 0;
1246                 head = &net->dev_index_head[h];
1247                 rcu_read_lock();
1248                 cb->seq = net->dev_base_seq;
1249                 hlist_for_each_entry_rcu(dev, head, index_hlist) {
1250                         if (idx < s_idx)
1251                                 goto cont;
1252                         mdev = mpls_dev_get(dev);
1253                         if (!mdev)
1254                                 goto cont;
1255                         if (mpls_netconf_fill_devconf(skb, mdev,
1256                                                       NETLINK_CB(cb->skb).portid,
1257                                                       cb->nlh->nlmsg_seq,
1258                                                       RTM_NEWNETCONF,
1259                                                       NLM_F_MULTI,
1260                                                       NETCONFA_ALL) < 0) {
1261                                 rcu_read_unlock();
1262                                 goto done;
1263                         }
1264                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1265 cont:
1266                         idx++;
1267                 }
1268                 rcu_read_unlock();
1269         }
1270 done:
1271         cb->args[0] = h;
1272         cb->args[1] = idx;
1273
1274         return skb->len;
1275 }
1276
1277 #define MPLS_PERDEV_SYSCTL_OFFSET(field)        \
1278         (&((struct mpls_dev *)0)->field)
1279
1280 static int mpls_conf_proc(struct ctl_table *ctl, int write,
1281                           void __user *buffer,
1282                           size_t *lenp, loff_t *ppos)
1283 {
1284         int oval = *(int *)ctl->data;
1285         int ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
1286
1287         if (write) {
1288                 struct mpls_dev *mdev = ctl->extra1;
1289                 int i = (int *)ctl->data - (int *)mdev;
1290                 struct net *net = ctl->extra2;
1291                 int val = *(int *)ctl->data;
1292
1293                 if (i == offsetof(struct mpls_dev, input_enabled) &&
1294                     val != oval) {
1295                         mpls_netconf_notify_devconf(net, RTM_NEWNETCONF,
1296                                                     NETCONFA_INPUT, mdev);
1297                 }
1298         }
1299
1300         return ret;
1301 }
1302
1303 static const struct ctl_table mpls_dev_table[] = {
1304         {
1305                 .procname       = "input",
1306                 .maxlen         = sizeof(int),
1307                 .mode           = 0644,
1308                 .proc_handler   = mpls_conf_proc,
1309                 .data           = MPLS_PERDEV_SYSCTL_OFFSET(input_enabled),
1310         },
1311         { }
1312 };
1313
1314 static int mpls_dev_sysctl_register(struct net_device *dev,
1315                                     struct mpls_dev *mdev)
1316 {
1317         char path[sizeof("net/mpls/conf/") + IFNAMSIZ];
1318         struct net *net = dev_net(dev);
1319         struct ctl_table *table;
1320         int i;
1321
1322         table = kmemdup(&mpls_dev_table, sizeof(mpls_dev_table), GFP_KERNEL);
1323         if (!table)
1324                 goto out;
1325
1326         /* Table data contains only offsets relative to the base of
1327          * the mdev at this point, so make them absolute.
1328          */
1329         for (i = 0; i < ARRAY_SIZE(mpls_dev_table); i++) {
1330                 table[i].data = (char *)mdev + (uintptr_t)table[i].data;
1331                 table[i].extra1 = mdev;
1332                 table[i].extra2 = net;
1333         }
1334
1335         snprintf(path, sizeof(path), "net/mpls/conf/%s", dev->name);
1336
1337         mdev->sysctl = register_net_sysctl(net, path, table);
1338         if (!mdev->sysctl)
1339                 goto free;
1340
1341         mpls_netconf_notify_devconf(net, RTM_NEWNETCONF, NETCONFA_ALL, mdev);
1342         return 0;
1343
1344 free:
1345         kfree(table);
1346 out:
1347         return -ENOBUFS;
1348 }
1349
1350 static void mpls_dev_sysctl_unregister(struct net_device *dev,
1351                                        struct mpls_dev *mdev)
1352 {
1353         struct net *net = dev_net(dev);
1354         struct ctl_table *table;
1355
1356         table = mdev->sysctl->ctl_table_arg;
1357         unregister_net_sysctl_table(mdev->sysctl);
1358         kfree(table);
1359
1360         mpls_netconf_notify_devconf(net, RTM_DELNETCONF, 0, mdev);
1361 }
1362
1363 static struct mpls_dev *mpls_add_dev(struct net_device *dev)
1364 {
1365         struct mpls_dev *mdev;
1366         int err = -ENOMEM;
1367         int i;
1368
1369         ASSERT_RTNL();
1370
1371         mdev = kzalloc(sizeof(*mdev), GFP_KERNEL);
1372         if (!mdev)
1373                 return ERR_PTR(err);
1374
1375         mdev->stats = alloc_percpu(struct mpls_pcpu_stats);
1376         if (!mdev->stats)
1377                 goto free;
1378
1379         for_each_possible_cpu(i) {
1380                 struct mpls_pcpu_stats *mpls_stats;
1381
1382                 mpls_stats = per_cpu_ptr(mdev->stats, i);
1383                 u64_stats_init(&mpls_stats->syncp);
1384         }
1385
1386         mdev->dev = dev;
1387
1388         err = mpls_dev_sysctl_register(dev, mdev);
1389         if (err)
1390                 goto free;
1391
1392         rcu_assign_pointer(dev->mpls_ptr, mdev);
1393
1394         return mdev;
1395
1396 free:
1397         free_percpu(mdev->stats);
1398         kfree(mdev);
1399         return ERR_PTR(err);
1400 }
1401
1402 static void mpls_dev_destroy_rcu(struct rcu_head *head)
1403 {
1404         struct mpls_dev *mdev = container_of(head, struct mpls_dev, rcu);
1405
1406         free_percpu(mdev->stats);
1407         kfree(mdev);
1408 }
1409
1410 static int mpls_ifdown(struct net_device *dev, int event)
1411 {
1412         struct mpls_route __rcu **platform_label;
1413         struct net *net = dev_net(dev);
1414         unsigned index;
1415
1416         platform_label = rtnl_dereference(net->mpls.platform_label);
1417         for (index = 0; index < net->mpls.platform_labels; index++) {
1418                 struct mpls_route *rt = rtnl_dereference(platform_label[index]);
1419                 bool nh_del = false;
1420                 u8 alive = 0;
1421
1422                 if (!rt)
1423                         continue;
1424
1425                 if (event == NETDEV_UNREGISTER) {
1426                         u8 deleted = 0;
1427
1428                         for_nexthops(rt) {
1429                                 struct net_device *nh_dev =
1430                                         rtnl_dereference(nh->nh_dev);
1431
1432                                 if (!nh_dev || nh_dev == dev)
1433                                         deleted++;
1434                                 if (nh_dev == dev)
1435                                         nh_del = true;
1436                         } endfor_nexthops(rt);
1437
1438                         /* if there are no more nexthops, delete the route */
1439                         if (deleted == rt->rt_nhn) {
1440                                 mpls_route_update(net, index, NULL, NULL);
1441                                 continue;
1442                         }
1443
1444                         if (nh_del) {
1445                                 size_t size = sizeof(*rt) + rt->rt_nhn *
1446                                         rt->rt_nh_size;
1447                                 struct mpls_route *orig = rt;
1448
1449                                 rt = kmalloc(size, GFP_KERNEL);
1450                                 if (!rt)
1451                                         return -ENOMEM;
1452                                 memcpy(rt, orig, size);
1453                         }
1454                 }
1455
1456                 change_nexthops(rt) {
1457                         unsigned int nh_flags = nh->nh_flags;
1458
1459                         if (rtnl_dereference(nh->nh_dev) != dev)
1460                                 goto next;
1461
1462                         switch (event) {
1463                         case NETDEV_DOWN:
1464                         case NETDEV_UNREGISTER:
1465                                 nh_flags |= RTNH_F_DEAD;
1466                                 /* fall through */
1467                         case NETDEV_CHANGE:
1468                                 nh_flags |= RTNH_F_LINKDOWN;
1469                                 break;
1470                         }
1471                         if (event == NETDEV_UNREGISTER)
1472                                 RCU_INIT_POINTER(nh->nh_dev, NULL);
1473
1474                         if (nh->nh_flags != nh_flags)
1475                                 WRITE_ONCE(nh->nh_flags, nh_flags);
1476 next:
1477                         if (!(nh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN)))
1478                                 alive++;
1479                 } endfor_nexthops(rt);
1480
1481                 WRITE_ONCE(rt->rt_nhn_alive, alive);
1482
1483                 if (nh_del)
1484                         mpls_route_update(net, index, rt, NULL);
1485         }
1486
1487         return 0;
1488 }
1489
1490 static void mpls_ifup(struct net_device *dev, unsigned int flags)
1491 {
1492         struct mpls_route __rcu **platform_label;
1493         struct net *net = dev_net(dev);
1494         unsigned index;
1495         u8 alive;
1496
1497         platform_label = rtnl_dereference(net->mpls.platform_label);
1498         for (index = 0; index < net->mpls.platform_labels; index++) {
1499                 struct mpls_route *rt = rtnl_dereference(platform_label[index]);
1500
1501                 if (!rt)
1502                         continue;
1503
1504                 alive = 0;
1505                 change_nexthops(rt) {
1506                         unsigned int nh_flags = nh->nh_flags;
1507                         struct net_device *nh_dev =
1508                                 rtnl_dereference(nh->nh_dev);
1509
1510                         if (!(nh_flags & flags)) {
1511                                 alive++;
1512                                 continue;
1513                         }
1514                         if (nh_dev != dev)
1515                                 continue;
1516                         alive++;
1517                         nh_flags &= ~flags;
1518                         WRITE_ONCE(nh->nh_flags, nh_flags);
1519                 } endfor_nexthops(rt);
1520
1521                 WRITE_ONCE(rt->rt_nhn_alive, alive);
1522         }
1523 }
1524
1525 static int mpls_dev_notify(struct notifier_block *this, unsigned long event,
1526                            void *ptr)
1527 {
1528         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1529         struct mpls_dev *mdev;
1530         unsigned int flags;
1531
1532         if (event == NETDEV_REGISTER) {
1533                 /* For now just support Ethernet, IPGRE, SIT and IPIP devices */
1534                 if (dev->type == ARPHRD_ETHER ||
1535                     dev->type == ARPHRD_LOOPBACK ||
1536                     dev->type == ARPHRD_IPGRE ||
1537                     dev->type == ARPHRD_SIT ||
1538                     dev->type == ARPHRD_TUNNEL) {
1539                         mdev = mpls_add_dev(dev);
1540                         if (IS_ERR(mdev))
1541                                 return notifier_from_errno(PTR_ERR(mdev));
1542                 }
1543                 return NOTIFY_OK;
1544         }
1545
1546         mdev = mpls_dev_get(dev);
1547         if (!mdev)
1548                 return NOTIFY_OK;
1549
1550         switch (event) {
1551                 int err;
1552
1553         case NETDEV_DOWN:
1554                 err = mpls_ifdown(dev, event);
1555                 if (err)
1556                         return notifier_from_errno(err);
1557                 break;
1558         case NETDEV_UP:
1559                 flags = dev_get_flags(dev);
1560                 if (flags & (IFF_RUNNING | IFF_LOWER_UP))
1561                         mpls_ifup(dev, RTNH_F_DEAD | RTNH_F_LINKDOWN);
1562                 else
1563                         mpls_ifup(dev, RTNH_F_DEAD);
1564                 break;
1565         case NETDEV_CHANGE:
1566                 flags = dev_get_flags(dev);
1567                 if (flags & (IFF_RUNNING | IFF_LOWER_UP)) {
1568                         mpls_ifup(dev, RTNH_F_DEAD | RTNH_F_LINKDOWN);
1569                 } else {
1570                         err = mpls_ifdown(dev, event);
1571                         if (err)
1572                                 return notifier_from_errno(err);
1573                 }
1574                 break;
1575         case NETDEV_UNREGISTER:
1576                 err = mpls_ifdown(dev, event);
1577                 if (err)
1578                         return notifier_from_errno(err);
1579                 mdev = mpls_dev_get(dev);
1580                 if (mdev) {
1581                         mpls_dev_sysctl_unregister(dev, mdev);
1582                         RCU_INIT_POINTER(dev->mpls_ptr, NULL);
1583                         call_rcu(&mdev->rcu, mpls_dev_destroy_rcu);
1584                 }
1585                 break;
1586         case NETDEV_CHANGENAME:
1587                 mdev = mpls_dev_get(dev);
1588                 if (mdev) {
1589                         mpls_dev_sysctl_unregister(dev, mdev);
1590                         err = mpls_dev_sysctl_register(dev, mdev);
1591                         if (err)
1592                                 return notifier_from_errno(err);
1593                 }
1594                 break;
1595         }
1596         return NOTIFY_OK;
1597 }
1598
1599 static struct notifier_block mpls_dev_notifier = {
1600         .notifier_call = mpls_dev_notify,
1601 };
1602
1603 static int nla_put_via(struct sk_buff *skb,
1604                        u8 table, const void *addr, int alen)
1605 {
1606         static const int table_to_family[NEIGH_NR_TABLES + 1] = {
1607                 AF_INET, AF_INET6, AF_DECnet, AF_PACKET,
1608         };
1609         struct nlattr *nla;
1610         struct rtvia *via;
1611         int family = AF_UNSPEC;
1612
1613         nla = nla_reserve(skb, RTA_VIA, alen + 2);
1614         if (!nla)
1615                 return -EMSGSIZE;
1616
1617         if (table <= NEIGH_NR_TABLES)
1618                 family = table_to_family[table];
1619
1620         via = nla_data(nla);
1621         via->rtvia_family = family;
1622         memcpy(via->rtvia_addr, addr, alen);
1623         return 0;
1624 }
1625
1626 int nla_put_labels(struct sk_buff *skb, int attrtype,
1627                    u8 labels, const u32 label[])
1628 {
1629         struct nlattr *nla;
1630         struct mpls_shim_hdr *nla_label;
1631         bool bos;
1632         int i;
1633         nla = nla_reserve(skb, attrtype, labels*4);
1634         if (!nla)
1635                 return -EMSGSIZE;
1636
1637         nla_label = nla_data(nla);
1638         bos = true;
1639         for (i = labels - 1; i >= 0; i--) {
1640                 nla_label[i] = mpls_entry_encode(label[i], 0, 0, bos);
1641                 bos = false;
1642         }
1643
1644         return 0;
1645 }
1646 EXPORT_SYMBOL_GPL(nla_put_labels);
1647
1648 int nla_get_labels(const struct nlattr *nla, u8 max_labels, u8 *labels,
1649                    u32 label[], struct netlink_ext_ack *extack)
1650 {
1651         unsigned len = nla_len(nla);
1652         struct mpls_shim_hdr *nla_label;
1653         u8 nla_labels;
1654         bool bos;
1655         int i;
1656
1657         /* len needs to be an even multiple of 4 (the label size). Number
1658          * of labels is a u8 so check for overflow.
1659          */
1660         if (len & 3 || len / 4 > 255) {
1661                 NL_SET_ERR_MSG_ATTR(extack, nla,
1662                                     "Invalid length for labels attribute");
1663                 return -EINVAL;
1664         }
1665
1666         /* Limit the number of new labels allowed */
1667         nla_labels = len/4;
1668         if (nla_labels > max_labels) {
1669                 NL_SET_ERR_MSG(extack, "Too many labels");
1670                 return -EINVAL;
1671         }
1672
1673         /* when label == NULL, caller wants number of labels */
1674         if (!label)
1675                 goto out;
1676
1677         nla_label = nla_data(nla);
1678         bos = true;
1679         for (i = nla_labels - 1; i >= 0; i--, bos = false) {
1680                 struct mpls_entry_decoded dec;
1681                 dec = mpls_entry_decode(nla_label + i);
1682
1683                 /* Ensure the bottom of stack flag is properly set
1684                  * and ttl and tc are both clear.
1685                  */
1686                 if (dec.ttl) {
1687                         NL_SET_ERR_MSG_ATTR(extack, nla,
1688                                             "TTL in label must be 0");
1689                         return -EINVAL;
1690                 }
1691
1692                 if (dec.tc) {
1693                         NL_SET_ERR_MSG_ATTR(extack, nla,
1694                                             "Traffic class in label must be 0");
1695                         return -EINVAL;
1696                 }
1697
1698                 if (dec.bos != bos) {
1699                         NL_SET_BAD_ATTR(extack, nla);
1700                         if (bos) {
1701                                 NL_SET_ERR_MSG(extack,
1702                                                "BOS bit must be set in first label");
1703                         } else {
1704                                 NL_SET_ERR_MSG(extack,
1705                                                "BOS bit can only be set in first label");
1706                         }
1707                         return -EINVAL;
1708                 }
1709
1710                 switch (dec.label) {
1711                 case MPLS_LABEL_IMPLNULL:
1712                         /* RFC3032: This is a label that an LSR may
1713                          * assign and distribute, but which never
1714                          * actually appears in the encapsulation.
1715                          */
1716                         NL_SET_ERR_MSG_ATTR(extack, nla,
1717                                             "Implicit NULL Label (3) can not be used in encapsulation");
1718                         return -EINVAL;
1719                 }
1720
1721                 label[i] = dec.label;
1722         }
1723 out:
1724         *labels = nla_labels;
1725         return 0;
1726 }
1727 EXPORT_SYMBOL_GPL(nla_get_labels);
1728
1729 static int rtm_to_route_config(struct sk_buff *skb,
1730                                struct nlmsghdr *nlh,
1731                                struct mpls_route_config *cfg,
1732                                struct netlink_ext_ack *extack)
1733 {
1734         struct rtmsg *rtm;
1735         struct nlattr *tb[RTA_MAX+1];
1736         int index;
1737         int err;
1738
1739         err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_mpls_policy,
1740                           extack);
1741         if (err < 0)
1742                 goto errout;
1743
1744         err = -EINVAL;
1745         rtm = nlmsg_data(nlh);
1746
1747         if (rtm->rtm_family != AF_MPLS) {
1748                 NL_SET_ERR_MSG(extack, "Invalid address family in rtmsg");
1749                 goto errout;
1750         }
1751         if (rtm->rtm_dst_len != 20) {
1752                 NL_SET_ERR_MSG(extack, "rtm_dst_len must be 20 for MPLS");
1753                 goto errout;
1754         }
1755         if (rtm->rtm_src_len != 0) {
1756                 NL_SET_ERR_MSG(extack, "rtm_src_len must be 0 for MPLS");
1757                 goto errout;
1758         }
1759         if (rtm->rtm_tos != 0) {
1760                 NL_SET_ERR_MSG(extack, "rtm_tos must be 0 for MPLS");
1761                 goto errout;
1762         }
1763         if (rtm->rtm_table != RT_TABLE_MAIN) {
1764                 NL_SET_ERR_MSG(extack,
1765                                "MPLS only supports the main route table");
1766                 goto errout;
1767         }
1768         /* Any value is acceptable for rtm_protocol */
1769
1770         /* As mpls uses destination specific addresses
1771          * (or source specific address in the case of multicast)
1772          * all addresses have universal scope.
1773          */
1774         if (rtm->rtm_scope != RT_SCOPE_UNIVERSE) {
1775                 NL_SET_ERR_MSG(extack,
1776                                "Invalid route scope  - MPLS only supports UNIVERSE");
1777                 goto errout;
1778         }
1779         if (rtm->rtm_type != RTN_UNICAST) {
1780                 NL_SET_ERR_MSG(extack,
1781                                "Invalid route type - MPLS only supports UNICAST");
1782                 goto errout;
1783         }
1784         if (rtm->rtm_flags != 0) {
1785                 NL_SET_ERR_MSG(extack, "rtm_flags must be 0 for MPLS");
1786                 goto errout;
1787         }
1788
1789         cfg->rc_label           = LABEL_NOT_SPECIFIED;
1790         cfg->rc_protocol        = rtm->rtm_protocol;
1791         cfg->rc_via_table       = MPLS_NEIGH_TABLE_UNSPEC;
1792         cfg->rc_ttl_propagate   = MPLS_TTL_PROP_DEFAULT;
1793         cfg->rc_nlflags         = nlh->nlmsg_flags;
1794         cfg->rc_nlinfo.portid   = NETLINK_CB(skb).portid;
1795         cfg->rc_nlinfo.nlh      = nlh;
1796         cfg->rc_nlinfo.nl_net   = sock_net(skb->sk);
1797
1798         for (index = 0; index <= RTA_MAX; index++) {
1799                 struct nlattr *nla = tb[index];
1800                 if (!nla)
1801                         continue;
1802
1803                 switch (index) {
1804                 case RTA_OIF:
1805                         cfg->rc_ifindex = nla_get_u32(nla);
1806                         break;
1807                 case RTA_NEWDST:
1808                         if (nla_get_labels(nla, MAX_NEW_LABELS,
1809                                            &cfg->rc_output_labels,
1810                                            cfg->rc_output_label, extack))
1811                                 goto errout;
1812                         break;
1813                 case RTA_DST:
1814                 {
1815                         u8 label_count;
1816                         if (nla_get_labels(nla, 1, &label_count,
1817                                            &cfg->rc_label, extack))
1818                                 goto errout;
1819
1820                         if (!mpls_label_ok(cfg->rc_nlinfo.nl_net,
1821                                            &cfg->rc_label, extack))
1822                                 goto errout;
1823                         break;
1824                 }
1825                 case RTA_GATEWAY:
1826                         NL_SET_ERR_MSG(extack, "MPLS does not support RTA_GATEWAY attribute");
1827                         goto errout;
1828                 case RTA_VIA:
1829                 {
1830                         if (nla_get_via(nla, &cfg->rc_via_alen,
1831                                         &cfg->rc_via_table, cfg->rc_via,
1832                                         extack))
1833                                 goto errout;
1834                         break;
1835                 }
1836                 case RTA_MULTIPATH:
1837                 {
1838                         cfg->rc_mp = nla_data(nla);
1839                         cfg->rc_mp_len = nla_len(nla);
1840                         break;
1841                 }
1842                 case RTA_TTL_PROPAGATE:
1843                 {
1844                         u8 ttl_propagate = nla_get_u8(nla);
1845
1846                         if (ttl_propagate > 1) {
1847                                 NL_SET_ERR_MSG_ATTR(extack, nla,
1848                                                     "RTA_TTL_PROPAGATE can only be 0 or 1");
1849                                 goto errout;
1850                         }
1851                         cfg->rc_ttl_propagate = ttl_propagate ?
1852                                 MPLS_TTL_PROP_ENABLED :
1853                                 MPLS_TTL_PROP_DISABLED;
1854                         break;
1855                 }
1856                 default:
1857                         NL_SET_ERR_MSG_ATTR(extack, nla, "Unknown attribute");
1858                         /* Unsupported attribute */
1859                         goto errout;
1860                 }
1861         }
1862
1863         err = 0;
1864 errout:
1865         return err;
1866 }
1867
1868 static int mpls_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
1869                              struct netlink_ext_ack *extack)
1870 {
1871         struct mpls_route_config *cfg;
1872         int err;
1873
1874         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
1875         if (!cfg)
1876                 return -ENOMEM;
1877
1878         err = rtm_to_route_config(skb, nlh, cfg, extack);
1879         if (err < 0)
1880                 goto out;
1881
1882         err = mpls_route_del(cfg, extack);
1883 out:
1884         kfree(cfg);
1885
1886         return err;
1887 }
1888
1889
1890 static int mpls_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
1891                              struct netlink_ext_ack *extack)
1892 {
1893         struct mpls_route_config *cfg;
1894         int err;
1895
1896         cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
1897         if (!cfg)
1898                 return -ENOMEM;
1899
1900         err = rtm_to_route_config(skb, nlh, cfg, extack);
1901         if (err < 0)
1902                 goto out;
1903
1904         err = mpls_route_add(cfg, extack);
1905 out:
1906         kfree(cfg);
1907
1908         return err;
1909 }
1910
1911 static int mpls_dump_route(struct sk_buff *skb, u32 portid, u32 seq, int event,
1912                            u32 label, struct mpls_route *rt, int flags)
1913 {
1914         struct net_device *dev;
1915         struct nlmsghdr *nlh;
1916         struct rtmsg *rtm;
1917
1918         nlh = nlmsg_put(skb, portid, seq, event, sizeof(*rtm), flags);
1919         if (nlh == NULL)
1920                 return -EMSGSIZE;
1921
1922         rtm = nlmsg_data(nlh);
1923         rtm->rtm_family = AF_MPLS;
1924         rtm->rtm_dst_len = 20;
1925         rtm->rtm_src_len = 0;
1926         rtm->rtm_tos = 0;
1927         rtm->rtm_table = RT_TABLE_MAIN;
1928         rtm->rtm_protocol = rt->rt_protocol;
1929         rtm->rtm_scope = RT_SCOPE_UNIVERSE;
1930         rtm->rtm_type = RTN_UNICAST;
1931         rtm->rtm_flags = 0;
1932
1933         if (nla_put_labels(skb, RTA_DST, 1, &label))
1934                 goto nla_put_failure;
1935
1936         if (rt->rt_ttl_propagate != MPLS_TTL_PROP_DEFAULT) {
1937                 bool ttl_propagate =
1938                         rt->rt_ttl_propagate == MPLS_TTL_PROP_ENABLED;
1939
1940                 if (nla_put_u8(skb, RTA_TTL_PROPAGATE,
1941                                ttl_propagate))
1942                         goto nla_put_failure;
1943         }
1944         if (rt->rt_nhn == 1) {
1945                 const struct mpls_nh *nh = rt->rt_nh;
1946
1947                 if (nh->nh_labels &&
1948                     nla_put_labels(skb, RTA_NEWDST, nh->nh_labels,
1949                                    nh->nh_label))
1950                         goto nla_put_failure;
1951                 if (nh->nh_via_table != MPLS_NEIGH_TABLE_UNSPEC &&
1952                     nla_put_via(skb, nh->nh_via_table, mpls_nh_via(rt, nh),
1953                                 nh->nh_via_alen))
1954                         goto nla_put_failure;
1955                 dev = rtnl_dereference(nh->nh_dev);
1956                 if (dev && nla_put_u32(skb, RTA_OIF, dev->ifindex))
1957                         goto nla_put_failure;
1958                 if (nh->nh_flags & RTNH_F_LINKDOWN)
1959                         rtm->rtm_flags |= RTNH_F_LINKDOWN;
1960                 if (nh->nh_flags & RTNH_F_DEAD)
1961                         rtm->rtm_flags |= RTNH_F_DEAD;
1962         } else {
1963                 struct rtnexthop *rtnh;
1964                 struct nlattr *mp;
1965                 u8 linkdown = 0;
1966                 u8 dead = 0;
1967
1968                 mp = nla_nest_start(skb, RTA_MULTIPATH);
1969                 if (!mp)
1970                         goto nla_put_failure;
1971
1972                 for_nexthops(rt) {
1973                         dev = rtnl_dereference(nh->nh_dev);
1974                         if (!dev)
1975                                 continue;
1976
1977                         rtnh = nla_reserve_nohdr(skb, sizeof(*rtnh));
1978                         if (!rtnh)
1979                                 goto nla_put_failure;
1980
1981                         rtnh->rtnh_ifindex = dev->ifindex;
1982                         if (nh->nh_flags & RTNH_F_LINKDOWN) {
1983                                 rtnh->rtnh_flags |= RTNH_F_LINKDOWN;
1984                                 linkdown++;
1985                         }
1986                         if (nh->nh_flags & RTNH_F_DEAD) {
1987                                 rtnh->rtnh_flags |= RTNH_F_DEAD;
1988                                 dead++;
1989                         }
1990
1991                         if (nh->nh_labels && nla_put_labels(skb, RTA_NEWDST,
1992                                                             nh->nh_labels,
1993                                                             nh->nh_label))
1994                                 goto nla_put_failure;
1995                         if (nh->nh_via_table != MPLS_NEIGH_TABLE_UNSPEC &&
1996                             nla_put_via(skb, nh->nh_via_table,
1997                                         mpls_nh_via(rt, nh),
1998                                         nh->nh_via_alen))
1999                                 goto nla_put_failure;
2000
2001                         /* length of rtnetlink header + attributes */
2002                         rtnh->rtnh_len = nlmsg_get_pos(skb) - (void *)rtnh;
2003                 } endfor_nexthops(rt);
2004
2005                 if (linkdown == rt->rt_nhn)
2006                         rtm->rtm_flags |= RTNH_F_LINKDOWN;
2007                 if (dead == rt->rt_nhn)
2008                         rtm->rtm_flags |= RTNH_F_DEAD;
2009
2010                 nla_nest_end(skb, mp);
2011         }
2012
2013         nlmsg_end(skb, nlh);
2014         return 0;
2015
2016 nla_put_failure:
2017         nlmsg_cancel(skb, nlh);
2018         return -EMSGSIZE;
2019 }
2020
2021 static int mpls_dump_routes(struct sk_buff *skb, struct netlink_callback *cb)
2022 {
2023         struct net *net = sock_net(skb->sk);
2024         struct mpls_route __rcu **platform_label;
2025         size_t platform_labels;
2026         unsigned int index;
2027
2028         ASSERT_RTNL();
2029
2030         index = cb->args[0];
2031         if (index < MPLS_LABEL_FIRST_UNRESERVED)
2032                 index = MPLS_LABEL_FIRST_UNRESERVED;
2033
2034         platform_label = rtnl_dereference(net->mpls.platform_label);
2035         platform_labels = net->mpls.platform_labels;
2036         for (; index < platform_labels; index++) {
2037                 struct mpls_route *rt;
2038                 rt = rtnl_dereference(platform_label[index]);
2039                 if (!rt)
2040                         continue;
2041
2042                 if (mpls_dump_route(skb, NETLINK_CB(cb->skb).portid,
2043                                     cb->nlh->nlmsg_seq, RTM_NEWROUTE,
2044                                     index, rt, NLM_F_MULTI) < 0)
2045                         break;
2046         }
2047         cb->args[0] = index;
2048
2049         return skb->len;
2050 }
2051
2052 static inline size_t lfib_nlmsg_size(struct mpls_route *rt)
2053 {
2054         size_t payload =
2055                 NLMSG_ALIGN(sizeof(struct rtmsg))
2056                 + nla_total_size(4)                     /* RTA_DST */
2057                 + nla_total_size(1);                    /* RTA_TTL_PROPAGATE */
2058
2059         if (rt->rt_nhn == 1) {
2060                 struct mpls_nh *nh = rt->rt_nh;
2061
2062                 if (nh->nh_dev)
2063                         payload += nla_total_size(4); /* RTA_OIF */
2064                 if (nh->nh_via_table != MPLS_NEIGH_TABLE_UNSPEC) /* RTA_VIA */
2065                         payload += nla_total_size(2 + nh->nh_via_alen);
2066                 if (nh->nh_labels) /* RTA_NEWDST */
2067                         payload += nla_total_size(nh->nh_labels * 4);
2068         } else {
2069                 /* each nexthop is packed in an attribute */
2070                 size_t nhsize = 0;
2071
2072                 for_nexthops(rt) {
2073                         if (!rtnl_dereference(nh->nh_dev))
2074                                 continue;
2075                         nhsize += nla_total_size(sizeof(struct rtnexthop));
2076                         /* RTA_VIA */
2077                         if (nh->nh_via_table != MPLS_NEIGH_TABLE_UNSPEC)
2078                                 nhsize += nla_total_size(2 + nh->nh_via_alen);
2079                         if (nh->nh_labels)
2080                                 nhsize += nla_total_size(nh->nh_labels * 4);
2081                 } endfor_nexthops(rt);
2082                 /* nested attribute */
2083                 payload += nla_total_size(nhsize);
2084         }
2085
2086         return payload;
2087 }
2088
2089 static void rtmsg_lfib(int event, u32 label, struct mpls_route *rt,
2090                        struct nlmsghdr *nlh, struct net *net, u32 portid,
2091                        unsigned int nlm_flags)
2092 {
2093         struct sk_buff *skb;
2094         u32 seq = nlh ? nlh->nlmsg_seq : 0;
2095         int err = -ENOBUFS;
2096
2097         skb = nlmsg_new(lfib_nlmsg_size(rt), GFP_KERNEL);
2098         if (skb == NULL)
2099                 goto errout;
2100
2101         err = mpls_dump_route(skb, portid, seq, event, label, rt, nlm_flags);
2102         if (err < 0) {
2103                 /* -EMSGSIZE implies BUG in lfib_nlmsg_size */
2104                 WARN_ON(err == -EMSGSIZE);
2105                 kfree_skb(skb);
2106                 goto errout;
2107         }
2108         rtnl_notify(skb, net, portid, RTNLGRP_MPLS_ROUTE, nlh, GFP_KERNEL);
2109
2110         return;
2111 errout:
2112         if (err < 0)
2113                 rtnl_set_sk_err(net, RTNLGRP_MPLS_ROUTE, err);
2114 }
2115
2116 static int mpls_getroute(struct sk_buff *in_skb, struct nlmsghdr *in_nlh,
2117                          struct netlink_ext_ack *extack)
2118 {
2119         struct net *net = sock_net(in_skb->sk);
2120         u32 portid = NETLINK_CB(in_skb).portid;
2121         u32 in_label = LABEL_NOT_SPECIFIED;
2122         struct nlattr *tb[RTA_MAX + 1];
2123         u32 labels[MAX_NEW_LABELS];
2124         struct mpls_shim_hdr *hdr;
2125         unsigned int hdr_size = 0;
2126         struct net_device *dev;
2127         struct mpls_route *rt;
2128         struct rtmsg *rtm, *r;
2129         struct nlmsghdr *nlh;
2130         struct sk_buff *skb;
2131         struct mpls_nh *nh;
2132         u8 n_labels;
2133         int err;
2134
2135         err = nlmsg_parse(in_nlh, sizeof(*rtm), tb, RTA_MAX,
2136                           rtm_mpls_policy, extack);
2137         if (err < 0)
2138                 goto errout;
2139
2140         rtm = nlmsg_data(in_nlh);
2141
2142         if (tb[RTA_DST]) {
2143                 u8 label_count;
2144
2145                 if (nla_get_labels(tb[RTA_DST], 1, &label_count,
2146                                    &in_label, extack)) {
2147                         err = -EINVAL;
2148                         goto errout;
2149                 }
2150
2151                 if (!mpls_label_ok(net, &in_label, extack)) {
2152                         err = -EINVAL;
2153                         goto errout;
2154                 }
2155         }
2156
2157         rt = mpls_route_input_rcu(net, in_label);
2158         if (!rt) {
2159                 err = -ENETUNREACH;
2160                 goto errout;
2161         }
2162
2163         if (rtm->rtm_flags & RTM_F_FIB_MATCH) {
2164                 skb = nlmsg_new(lfib_nlmsg_size(rt), GFP_KERNEL);
2165                 if (!skb) {
2166                         err = -ENOBUFS;
2167                         goto errout;
2168                 }
2169
2170                 err = mpls_dump_route(skb, portid, in_nlh->nlmsg_seq,
2171                                       RTM_NEWROUTE, in_label, rt, 0);
2172                 if (err < 0) {
2173                         /* -EMSGSIZE implies BUG in lfib_nlmsg_size */
2174                         WARN_ON(err == -EMSGSIZE);
2175                         goto errout_free;
2176                 }
2177
2178                 return rtnl_unicast(skb, net, portid);
2179         }
2180
2181         if (tb[RTA_NEWDST]) {
2182                 if (nla_get_labels(tb[RTA_NEWDST], MAX_NEW_LABELS, &n_labels,
2183                                    labels, extack) != 0) {
2184                         err = -EINVAL;
2185                         goto errout;
2186                 }
2187
2188                 hdr_size = n_labels * sizeof(struct mpls_shim_hdr);
2189         }
2190
2191         skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
2192         if (!skb) {
2193                 err = -ENOBUFS;
2194                 goto errout;
2195         }
2196
2197         skb->protocol = htons(ETH_P_MPLS_UC);
2198
2199         if (hdr_size) {
2200                 bool bos;
2201                 int i;
2202
2203                 if (skb_cow(skb, hdr_size)) {
2204                         err = -ENOBUFS;
2205                         goto errout_free;
2206                 }
2207
2208                 skb_reserve(skb, hdr_size);
2209                 skb_push(skb, hdr_size);
2210                 skb_reset_network_header(skb);
2211
2212                 /* Push new labels */
2213                 hdr = mpls_hdr(skb);
2214                 bos = true;
2215                 for (i = n_labels - 1; i >= 0; i--) {
2216                         hdr[i] = mpls_entry_encode(labels[i],
2217                                                    1, 0, bos);
2218                         bos = false;
2219                 }
2220         }
2221
2222         nh = mpls_select_multipath(rt, skb);
2223         if (!nh) {
2224                 err = -ENETUNREACH;
2225                 goto errout_free;
2226         }
2227
2228         if (hdr_size) {
2229                 skb_pull(skb, hdr_size);
2230                 skb_reset_network_header(skb);
2231         }
2232
2233         nlh = nlmsg_put(skb, portid, in_nlh->nlmsg_seq,
2234                         RTM_NEWROUTE, sizeof(*r), 0);
2235         if (!nlh) {
2236                 err = -EMSGSIZE;
2237                 goto errout_free;
2238         }
2239
2240         r = nlmsg_data(nlh);
2241         r->rtm_family    = AF_MPLS;
2242         r->rtm_dst_len  = 20;
2243         r->rtm_src_len  = 0;
2244         r->rtm_table    = RT_TABLE_MAIN;
2245         r->rtm_type     = RTN_UNICAST;
2246         r->rtm_scope    = RT_SCOPE_UNIVERSE;
2247         r->rtm_protocol = rt->rt_protocol;
2248         r->rtm_flags    = 0;
2249
2250         if (nla_put_labels(skb, RTA_DST, 1, &in_label))
2251                 goto nla_put_failure;
2252
2253         if (nh->nh_labels &&
2254             nla_put_labels(skb, RTA_NEWDST, nh->nh_labels,
2255                            nh->nh_label))
2256                 goto nla_put_failure;
2257
2258         if (nh->nh_via_table != MPLS_NEIGH_TABLE_UNSPEC &&
2259             nla_put_via(skb, nh->nh_via_table, mpls_nh_via(rt, nh),
2260                         nh->nh_via_alen))
2261                 goto nla_put_failure;
2262         dev = rtnl_dereference(nh->nh_dev);
2263         if (dev && nla_put_u32(skb, RTA_OIF, dev->ifindex))
2264                 goto nla_put_failure;
2265
2266         nlmsg_end(skb, nlh);
2267
2268         err = rtnl_unicast(skb, net, portid);
2269 errout:
2270         return err;
2271
2272 nla_put_failure:
2273         nlmsg_cancel(skb, nlh);
2274         err = -EMSGSIZE;
2275 errout_free:
2276         kfree_skb(skb);
2277         return err;
2278 }
2279
2280 static int resize_platform_label_table(struct net *net, size_t limit)
2281 {
2282         size_t size = sizeof(struct mpls_route *) * limit;
2283         size_t old_limit;
2284         size_t cp_size;
2285         struct mpls_route __rcu **labels = NULL, **old;
2286         struct mpls_route *rt0 = NULL, *rt2 = NULL;
2287         unsigned index;
2288
2289         if (size) {
2290                 labels = kvzalloc(size, GFP_KERNEL);
2291                 if (!labels)
2292                         goto nolabels;
2293         }
2294
2295         /* In case the predefined labels need to be populated */
2296         if (limit > MPLS_LABEL_IPV4NULL) {
2297                 struct net_device *lo = net->loopback_dev;
2298                 rt0 = mpls_rt_alloc(1, lo->addr_len, 0);
2299                 if (IS_ERR(rt0))
2300                         goto nort0;
2301                 RCU_INIT_POINTER(rt0->rt_nh->nh_dev, lo);
2302                 rt0->rt_protocol = RTPROT_KERNEL;
2303                 rt0->rt_payload_type = MPT_IPV4;
2304                 rt0->rt_ttl_propagate = MPLS_TTL_PROP_DEFAULT;
2305                 rt0->rt_nh->nh_via_table = NEIGH_LINK_TABLE;
2306                 rt0->rt_nh->nh_via_alen = lo->addr_len;
2307                 memcpy(__mpls_nh_via(rt0, rt0->rt_nh), lo->dev_addr,
2308                        lo->addr_len);
2309         }
2310         if (limit > MPLS_LABEL_IPV6NULL) {
2311                 struct net_device *lo = net->loopback_dev;
2312                 rt2 = mpls_rt_alloc(1, lo->addr_len, 0);
2313                 if (IS_ERR(rt2))
2314                         goto nort2;
2315                 RCU_INIT_POINTER(rt2->rt_nh->nh_dev, lo);
2316                 rt2->rt_protocol = RTPROT_KERNEL;
2317                 rt2->rt_payload_type = MPT_IPV6;
2318                 rt2->rt_ttl_propagate = MPLS_TTL_PROP_DEFAULT;
2319                 rt2->rt_nh->nh_via_table = NEIGH_LINK_TABLE;
2320                 rt2->rt_nh->nh_via_alen = lo->addr_len;
2321                 memcpy(__mpls_nh_via(rt2, rt2->rt_nh), lo->dev_addr,
2322                        lo->addr_len);
2323         }
2324
2325         rtnl_lock();
2326         /* Remember the original table */
2327         old = rtnl_dereference(net->mpls.platform_label);
2328         old_limit = net->mpls.platform_labels;
2329
2330         /* Free any labels beyond the new table */
2331         for (index = limit; index < old_limit; index++)
2332                 mpls_route_update(net, index, NULL, NULL);
2333
2334         /* Copy over the old labels */
2335         cp_size = size;
2336         if (old_limit < limit)
2337                 cp_size = old_limit * sizeof(struct mpls_route *);
2338
2339         memcpy(labels, old, cp_size);
2340
2341         /* If needed set the predefined labels */
2342         if ((old_limit <= MPLS_LABEL_IPV6NULL) &&
2343             (limit > MPLS_LABEL_IPV6NULL)) {
2344                 RCU_INIT_POINTER(labels[MPLS_LABEL_IPV6NULL], rt2);
2345                 rt2 = NULL;
2346         }
2347
2348         if ((old_limit <= MPLS_LABEL_IPV4NULL) &&
2349             (limit > MPLS_LABEL_IPV4NULL)) {
2350                 RCU_INIT_POINTER(labels[MPLS_LABEL_IPV4NULL], rt0);
2351                 rt0 = NULL;
2352         }
2353
2354         /* Update the global pointers */
2355         net->mpls.platform_labels = limit;
2356         rcu_assign_pointer(net->mpls.platform_label, labels);
2357
2358         rtnl_unlock();
2359
2360         mpls_rt_free(rt2);
2361         mpls_rt_free(rt0);
2362
2363         if (old) {
2364                 synchronize_rcu();
2365                 kvfree(old);
2366         }
2367         return 0;
2368
2369 nort2:
2370         mpls_rt_free(rt0);
2371 nort0:
2372         kvfree(labels);
2373 nolabels:
2374         return -ENOMEM;
2375 }
2376
2377 static int mpls_platform_labels(struct ctl_table *table, int write,
2378                                 void __user *buffer, size_t *lenp, loff_t *ppos)
2379 {
2380         struct net *net = table->data;
2381         int platform_labels = net->mpls.platform_labels;
2382         int ret;
2383         struct ctl_table tmp = {
2384                 .procname       = table->procname,
2385                 .data           = &platform_labels,
2386                 .maxlen         = sizeof(int),
2387                 .mode           = table->mode,
2388                 .extra1         = &zero,
2389                 .extra2         = &label_limit,
2390         };
2391
2392         ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
2393
2394         if (write && ret == 0)
2395                 ret = resize_platform_label_table(net, platform_labels);
2396
2397         return ret;
2398 }
2399
2400 #define MPLS_NS_SYSCTL_OFFSET(field)            \
2401         (&((struct net *)0)->field)
2402
2403 static const struct ctl_table mpls_table[] = {
2404         {
2405                 .procname       = "platform_labels",
2406                 .data           = NULL,
2407                 .maxlen         = sizeof(int),
2408                 .mode           = 0644,
2409                 .proc_handler   = mpls_platform_labels,
2410         },
2411         {
2412                 .procname       = "ip_ttl_propagate",
2413                 .data           = MPLS_NS_SYSCTL_OFFSET(mpls.ip_ttl_propagate),
2414                 .maxlen         = sizeof(int),
2415                 .mode           = 0644,
2416                 .proc_handler   = proc_dointvec_minmax,
2417                 .extra1         = &zero,
2418                 .extra2         = &one,
2419         },
2420         {
2421                 .procname       = "default_ttl",
2422                 .data           = MPLS_NS_SYSCTL_OFFSET(mpls.default_ttl),
2423                 .maxlen         = sizeof(int),
2424                 .mode           = 0644,
2425                 .proc_handler   = proc_dointvec_minmax,
2426                 .extra1         = &one,
2427                 .extra2         = &ttl_max,
2428         },
2429         { }
2430 };
2431
2432 static int mpls_net_init(struct net *net)
2433 {
2434         struct ctl_table *table;
2435         int i;
2436
2437         net->mpls.platform_labels = 0;
2438         net->mpls.platform_label = NULL;
2439         net->mpls.ip_ttl_propagate = 1;
2440         net->mpls.default_ttl = 255;
2441
2442         table = kmemdup(mpls_table, sizeof(mpls_table), GFP_KERNEL);
2443         if (table == NULL)
2444                 return -ENOMEM;
2445
2446         /* Table data contains only offsets relative to the base of
2447          * the mdev at this point, so make them absolute.
2448          */
2449         for (i = 0; i < ARRAY_SIZE(mpls_table) - 1; i++)
2450                 table[i].data = (char *)net + (uintptr_t)table[i].data;
2451
2452         net->mpls.ctl = register_net_sysctl(net, "net/mpls", table);
2453         if (net->mpls.ctl == NULL) {
2454                 kfree(table);
2455                 return -ENOMEM;
2456         }
2457
2458         return 0;
2459 }
2460
2461 static void mpls_net_exit(struct net *net)
2462 {
2463         struct mpls_route __rcu **platform_label;
2464         size_t platform_labels;
2465         struct ctl_table *table;
2466         unsigned int index;
2467
2468         table = net->mpls.ctl->ctl_table_arg;
2469         unregister_net_sysctl_table(net->mpls.ctl);
2470         kfree(table);
2471
2472         /* An rcu grace period has passed since there was a device in
2473          * the network namespace (and thus the last in flight packet)
2474          * left this network namespace.  This is because
2475          * unregister_netdevice_many and netdev_run_todo has completed
2476          * for each network device that was in this network namespace.
2477          *
2478          * As such no additional rcu synchronization is necessary when
2479          * freeing the platform_label table.
2480          */
2481         rtnl_lock();
2482         platform_label = rtnl_dereference(net->mpls.platform_label);
2483         platform_labels = net->mpls.platform_labels;
2484         for (index = 0; index < platform_labels; index++) {
2485                 struct mpls_route *rt = rtnl_dereference(platform_label[index]);
2486                 RCU_INIT_POINTER(platform_label[index], NULL);
2487                 mpls_notify_route(net, index, rt, NULL, NULL);
2488                 mpls_rt_free(rt);
2489         }
2490         rtnl_unlock();
2491
2492         kvfree(platform_label);
2493 }
2494
2495 static struct pernet_operations mpls_net_ops = {
2496         .init = mpls_net_init,
2497         .exit = mpls_net_exit,
2498 };
2499
2500 static struct rtnl_af_ops mpls_af_ops __read_mostly = {
2501         .family            = AF_MPLS,
2502         .fill_stats_af     = mpls_fill_stats_af,
2503         .get_stats_af_size = mpls_get_stats_af_size,
2504 };
2505
2506 static int __init mpls_init(void)
2507 {
2508         int err;
2509
2510         BUILD_BUG_ON(sizeof(struct mpls_shim_hdr) != 4);
2511
2512         err = register_pernet_subsys(&mpls_net_ops);
2513         if (err)
2514                 goto out;
2515
2516         err = register_netdevice_notifier(&mpls_dev_notifier);
2517         if (err)
2518                 goto out_unregister_pernet;
2519
2520         dev_add_pack(&mpls_packet_type);
2521
2522         rtnl_af_register(&mpls_af_ops);
2523
2524         rtnl_register(PF_MPLS, RTM_NEWROUTE, mpls_rtm_newroute, NULL, 0);
2525         rtnl_register(PF_MPLS, RTM_DELROUTE, mpls_rtm_delroute, NULL, 0);
2526         rtnl_register(PF_MPLS, RTM_GETROUTE, mpls_getroute, mpls_dump_routes,
2527                       0);
2528         rtnl_register(PF_MPLS, RTM_GETNETCONF, mpls_netconf_get_devconf,
2529                       mpls_netconf_dump_devconf, 0);
2530         err = 0;
2531 out:
2532         return err;
2533
2534 out_unregister_pernet:
2535         unregister_pernet_subsys(&mpls_net_ops);
2536         goto out;
2537 }
2538 module_init(mpls_init);
2539
2540 static void __exit mpls_exit(void)
2541 {
2542         rtnl_unregister_all(PF_MPLS);
2543         rtnl_af_unregister(&mpls_af_ops);
2544         dev_remove_pack(&mpls_packet_type);
2545         unregister_netdevice_notifier(&mpls_dev_notifier);
2546         unregister_pernet_subsys(&mpls_net_ops);
2547 }
2548 module_exit(mpls_exit);
2549
2550 MODULE_DESCRIPTION("MultiProtocol Label Switching");
2551 MODULE_LICENSE("GPL v2");
2552 MODULE_ALIAS_NETPROTO(PF_MPLS);