aac2093819039f028f2b55c0b51d857101f62117
[platform/kernel/linux-rpi.git] / net / ipv6 / route.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      Linux INET6 implementation
4  *      FIB front-end.
5  *
6  *      Authors:
7  *      Pedro Roque             <roque@di.fc.ul.pt>
8  */
9
10 /*      Changes:
11  *
12  *      YOSHIFUJI Hideaki @USAGI
13  *              reworked default router selection.
14  *              - respect outgoing interface
15  *              - select from (probably) reachable routers (i.e.
16  *              routers in REACHABLE, STALE, DELAY or PROBE states).
17  *              - always select the same router if it is (probably)
18  *              reachable.  otherwise, round-robin the list.
19  *      Ville Nuorvala
20  *              Fixed routing subtrees.
21  */
22
23 #define pr_fmt(fmt) "IPv6: " fmt
24
25 #include <linux/capability.h>
26 #include <linux/errno.h>
27 #include <linux/export.h>
28 #include <linux/types.h>
29 #include <linux/times.h>
30 #include <linux/socket.h>
31 #include <linux/sockios.h>
32 #include <linux/net.h>
33 #include <linux/route.h>
34 #include <linux/netdevice.h>
35 #include <linux/in6.h>
36 #include <linux/mroute6.h>
37 #include <linux/init.h>
38 #include <linux/if_arp.h>
39 #include <linux/proc_fs.h>
40 #include <linux/seq_file.h>
41 #include <linux/nsproxy.h>
42 #include <linux/slab.h>
43 #include <linux/jhash.h>
44 #include <net/net_namespace.h>
45 #include <net/snmp.h>
46 #include <net/ipv6.h>
47 #include <net/ip6_fib.h>
48 #include <net/ip6_route.h>
49 #include <net/ndisc.h>
50 #include <net/addrconf.h>
51 #include <net/tcp.h>
52 #include <linux/rtnetlink.h>
53 #include <net/dst.h>
54 #include <net/dst_metadata.h>
55 #include <net/xfrm.h>
56 #include <net/netevent.h>
57 #include <net/netlink.h>
58 #include <net/rtnh.h>
59 #include <net/lwtunnel.h>
60 #include <net/ip_tunnels.h>
61 #include <net/l3mdev.h>
62 #include <net/ip.h>
63 #include <linux/uaccess.h>
64
65 #ifdef CONFIG_SYSCTL
66 #include <linux/sysctl.h>
67 #endif
68
69 static int ip6_rt_type_to_error(u8 fib6_type);
70
71 #define CREATE_TRACE_POINTS
72 #include <trace/events/fib6.h>
73 EXPORT_TRACEPOINT_SYMBOL_GPL(fib6_table_lookup);
74 #undef CREATE_TRACE_POINTS
75
76 enum rt6_nud_state {
77         RT6_NUD_FAIL_HARD = -3,
78         RT6_NUD_FAIL_PROBE = -2,
79         RT6_NUD_FAIL_DO_RR = -1,
80         RT6_NUD_SUCCEED = 1
81 };
82
83 static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie);
84 static unsigned int      ip6_default_advmss(const struct dst_entry *dst);
85 static unsigned int      ip6_mtu(const struct dst_entry *dst);
86 static struct dst_entry *ip6_negative_advice(struct dst_entry *);
87 static void             ip6_dst_destroy(struct dst_entry *);
88 static void             ip6_dst_ifdown(struct dst_entry *,
89                                        struct net_device *dev, int how);
90 static int               ip6_dst_gc(struct dst_ops *ops);
91
92 static int              ip6_pkt_discard(struct sk_buff *skb);
93 static int              ip6_pkt_discard_out(struct net *net, struct sock *sk, struct sk_buff *skb);
94 static int              ip6_pkt_prohibit(struct sk_buff *skb);
95 static int              ip6_pkt_prohibit_out(struct net *net, struct sock *sk, struct sk_buff *skb);
96 static void             ip6_link_failure(struct sk_buff *skb);
97 static void             ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
98                                            struct sk_buff *skb, u32 mtu);
99 static void             rt6_do_redirect(struct dst_entry *dst, struct sock *sk,
100                                         struct sk_buff *skb);
101 static int rt6_score_route(const struct fib6_nh *nh, u32 fib6_flags, int oif,
102                            int strict);
103 static size_t rt6_nlmsg_size(struct fib6_info *rt);
104 static int rt6_fill_node(struct net *net, struct sk_buff *skb,
105                          struct fib6_info *rt, struct dst_entry *dst,
106                          struct in6_addr *dest, struct in6_addr *src,
107                          int iif, int type, u32 portid, u32 seq,
108                          unsigned int flags);
109 static struct rt6_info *rt6_find_cached_rt(const struct fib6_result *res,
110                                            const struct in6_addr *daddr,
111                                            const struct in6_addr *saddr);
112
113 #ifdef CONFIG_IPV6_ROUTE_INFO
114 static struct fib6_info *rt6_add_route_info(struct net *net,
115                                            const struct in6_addr *prefix, int prefixlen,
116                                            const struct in6_addr *gwaddr,
117                                            struct net_device *dev,
118                                            unsigned int pref);
119 static struct fib6_info *rt6_get_route_info(struct net *net,
120                                            const struct in6_addr *prefix, int prefixlen,
121                                            const struct in6_addr *gwaddr,
122                                            struct net_device *dev);
123 #endif
124
125 struct uncached_list {
126         spinlock_t              lock;
127         struct list_head        head;
128 };
129
130 static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt6_uncached_list);
131
132 void rt6_uncached_list_add(struct rt6_info *rt)
133 {
134         struct uncached_list *ul = raw_cpu_ptr(&rt6_uncached_list);
135
136         rt->rt6i_uncached_list = ul;
137
138         spin_lock_bh(&ul->lock);
139         list_add_tail(&rt->rt6i_uncached, &ul->head);
140         spin_unlock_bh(&ul->lock);
141 }
142
143 void rt6_uncached_list_del(struct rt6_info *rt)
144 {
145         if (!list_empty(&rt->rt6i_uncached)) {
146                 struct uncached_list *ul = rt->rt6i_uncached_list;
147                 struct net *net = dev_net(rt->dst.dev);
148
149                 spin_lock_bh(&ul->lock);
150                 list_del(&rt->rt6i_uncached);
151                 atomic_dec(&net->ipv6.rt6_stats->fib_rt_uncache);
152                 spin_unlock_bh(&ul->lock);
153         }
154 }
155
156 static void rt6_uncached_list_flush_dev(struct net *net, struct net_device *dev)
157 {
158         struct net_device *loopback_dev = net->loopback_dev;
159         int cpu;
160
161         if (dev == loopback_dev)
162                 return;
163
164         for_each_possible_cpu(cpu) {
165                 struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu);
166                 struct rt6_info *rt;
167
168                 spin_lock_bh(&ul->lock);
169                 list_for_each_entry(rt, &ul->head, rt6i_uncached) {
170                         struct inet6_dev *rt_idev = rt->rt6i_idev;
171                         struct net_device *rt_dev = rt->dst.dev;
172
173                         if (rt_idev->dev == dev) {
174                                 rt->rt6i_idev = in6_dev_get(loopback_dev);
175                                 in6_dev_put(rt_idev);
176                         }
177
178                         if (rt_dev == dev) {
179                                 rt->dst.dev = loopback_dev;
180                                 dev_hold(rt->dst.dev);
181                                 dev_put(rt_dev);
182                         }
183                 }
184                 spin_unlock_bh(&ul->lock);
185         }
186 }
187
188 static inline const void *choose_neigh_daddr(const struct in6_addr *p,
189                                              struct sk_buff *skb,
190                                              const void *daddr)
191 {
192         if (!ipv6_addr_any(p))
193                 return (const void *) p;
194         else if (skb)
195                 return &ipv6_hdr(skb)->daddr;
196         return daddr;
197 }
198
199 struct neighbour *ip6_neigh_lookup(const struct in6_addr *gw,
200                                    struct net_device *dev,
201                                    struct sk_buff *skb,
202                                    const void *daddr)
203 {
204         struct neighbour *n;
205
206         daddr = choose_neigh_daddr(gw, skb, daddr);
207         n = __ipv6_neigh_lookup(dev, daddr);
208         if (n)
209                 return n;
210
211         n = neigh_create(&nd_tbl, daddr, dev);
212         return IS_ERR(n) ? NULL : n;
213 }
214
215 static struct neighbour *ip6_dst_neigh_lookup(const struct dst_entry *dst,
216                                               struct sk_buff *skb,
217                                               const void *daddr)
218 {
219         const struct rt6_info *rt = container_of(dst, struct rt6_info, dst);
220
221         return ip6_neigh_lookup(&rt->rt6i_gateway, dst->dev, skb, daddr);
222 }
223
224 static void ip6_confirm_neigh(const struct dst_entry *dst, const void *daddr)
225 {
226         struct net_device *dev = dst->dev;
227         struct rt6_info *rt = (struct rt6_info *)dst;
228
229         daddr = choose_neigh_daddr(&rt->rt6i_gateway, NULL, daddr);
230         if (!daddr)
231                 return;
232         if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
233                 return;
234         if (ipv6_addr_is_multicast((const struct in6_addr *)daddr))
235                 return;
236         __ipv6_confirm_neigh(dev, daddr);
237 }
238
239 static struct dst_ops ip6_dst_ops_template = {
240         .family                 =       AF_INET6,
241         .gc                     =       ip6_dst_gc,
242         .gc_thresh              =       1024,
243         .check                  =       ip6_dst_check,
244         .default_advmss         =       ip6_default_advmss,
245         .mtu                    =       ip6_mtu,
246         .cow_metrics            =       dst_cow_metrics_generic,
247         .destroy                =       ip6_dst_destroy,
248         .ifdown                 =       ip6_dst_ifdown,
249         .negative_advice        =       ip6_negative_advice,
250         .link_failure           =       ip6_link_failure,
251         .update_pmtu            =       ip6_rt_update_pmtu,
252         .redirect               =       rt6_do_redirect,
253         .local_out              =       __ip6_local_out,
254         .neigh_lookup           =       ip6_dst_neigh_lookup,
255         .confirm_neigh          =       ip6_confirm_neigh,
256 };
257
258 static unsigned int ip6_blackhole_mtu(const struct dst_entry *dst)
259 {
260         unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
261
262         return mtu ? : dst->dev->mtu;
263 }
264
265 static void ip6_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk,
266                                          struct sk_buff *skb, u32 mtu)
267 {
268 }
269
270 static void ip6_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk,
271                                       struct sk_buff *skb)
272 {
273 }
274
275 static struct dst_ops ip6_dst_blackhole_ops = {
276         .family                 =       AF_INET6,
277         .destroy                =       ip6_dst_destroy,
278         .check                  =       ip6_dst_check,
279         .mtu                    =       ip6_blackhole_mtu,
280         .default_advmss         =       ip6_default_advmss,
281         .update_pmtu            =       ip6_rt_blackhole_update_pmtu,
282         .redirect               =       ip6_rt_blackhole_redirect,
283         .cow_metrics            =       dst_cow_metrics_generic,
284         .neigh_lookup           =       ip6_dst_neigh_lookup,
285 };
286
287 static const u32 ip6_template_metrics[RTAX_MAX] = {
288         [RTAX_HOPLIMIT - 1] = 0,
289 };
290
291 static const struct fib6_info fib6_null_entry_template = {
292         .fib6_flags     = (RTF_REJECT | RTF_NONEXTHOP),
293         .fib6_protocol  = RTPROT_KERNEL,
294         .fib6_metric    = ~(u32)0,
295         .fib6_ref       = REFCOUNT_INIT(1),
296         .fib6_type      = RTN_UNREACHABLE,
297         .fib6_metrics   = (struct dst_metrics *)&dst_default_metrics,
298 };
299
300 static const struct rt6_info ip6_null_entry_template = {
301         .dst = {
302                 .__refcnt       = ATOMIC_INIT(1),
303                 .__use          = 1,
304                 .obsolete       = DST_OBSOLETE_FORCE_CHK,
305                 .error          = -ENETUNREACH,
306                 .input          = ip6_pkt_discard,
307                 .output         = ip6_pkt_discard_out,
308         },
309         .rt6i_flags     = (RTF_REJECT | RTF_NONEXTHOP),
310 };
311
312 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
313
314 static const struct rt6_info ip6_prohibit_entry_template = {
315         .dst = {
316                 .__refcnt       = ATOMIC_INIT(1),
317                 .__use          = 1,
318                 .obsolete       = DST_OBSOLETE_FORCE_CHK,
319                 .error          = -EACCES,
320                 .input          = ip6_pkt_prohibit,
321                 .output         = ip6_pkt_prohibit_out,
322         },
323         .rt6i_flags     = (RTF_REJECT | RTF_NONEXTHOP),
324 };
325
326 static const struct rt6_info ip6_blk_hole_entry_template = {
327         .dst = {
328                 .__refcnt       = ATOMIC_INIT(1),
329                 .__use          = 1,
330                 .obsolete       = DST_OBSOLETE_FORCE_CHK,
331                 .error          = -EINVAL,
332                 .input          = dst_discard,
333                 .output         = dst_discard_out,
334         },
335         .rt6i_flags     = (RTF_REJECT | RTF_NONEXTHOP),
336 };
337
338 #endif
339
340 static void rt6_info_init(struct rt6_info *rt)
341 {
342         struct dst_entry *dst = &rt->dst;
343
344         memset(dst + 1, 0, sizeof(*rt) - sizeof(*dst));
345         INIT_LIST_HEAD(&rt->rt6i_uncached);
346 }
347
348 /* allocate dst with ip6_dst_ops */
349 struct rt6_info *ip6_dst_alloc(struct net *net, struct net_device *dev,
350                                int flags)
351 {
352         struct rt6_info *rt = dst_alloc(&net->ipv6.ip6_dst_ops, dev,
353                                         1, DST_OBSOLETE_FORCE_CHK, flags);
354
355         if (rt) {
356                 rt6_info_init(rt);
357                 atomic_inc(&net->ipv6.rt6_stats->fib_rt_alloc);
358         }
359
360         return rt;
361 }
362 EXPORT_SYMBOL(ip6_dst_alloc);
363
364 static void ip6_dst_destroy(struct dst_entry *dst)
365 {
366         struct rt6_info *rt = (struct rt6_info *)dst;
367         struct fib6_info *from;
368         struct inet6_dev *idev;
369
370         ip_dst_metrics_put(dst);
371         rt6_uncached_list_del(rt);
372
373         idev = rt->rt6i_idev;
374         if (idev) {
375                 rt->rt6i_idev = NULL;
376                 in6_dev_put(idev);
377         }
378
379         from = xchg((__force struct fib6_info **)&rt->from, NULL);
380         fib6_info_release(from);
381 }
382
383 static void ip6_dst_ifdown(struct dst_entry *dst, struct net_device *dev,
384                            int how)
385 {
386         struct rt6_info *rt = (struct rt6_info *)dst;
387         struct inet6_dev *idev = rt->rt6i_idev;
388         struct net_device *loopback_dev =
389                 dev_net(dev)->loopback_dev;
390
391         if (idev && idev->dev != loopback_dev) {
392                 struct inet6_dev *loopback_idev = in6_dev_get(loopback_dev);
393                 if (loopback_idev) {
394                         rt->rt6i_idev = loopback_idev;
395                         in6_dev_put(idev);
396                 }
397         }
398 }
399
400 static bool __rt6_check_expired(const struct rt6_info *rt)
401 {
402         if (rt->rt6i_flags & RTF_EXPIRES)
403                 return time_after(jiffies, rt->dst.expires);
404         else
405                 return false;
406 }
407
408 static bool rt6_check_expired(const struct rt6_info *rt)
409 {
410         struct fib6_info *from;
411
412         from = rcu_dereference(rt->from);
413
414         if (rt->rt6i_flags & RTF_EXPIRES) {
415                 if (time_after(jiffies, rt->dst.expires))
416                         return true;
417         } else if (from) {
418                 return rt->dst.obsolete != DST_OBSOLETE_FORCE_CHK ||
419                         fib6_check_expired(from);
420         }
421         return false;
422 }
423
424 void fib6_select_path(const struct net *net, struct fib6_result *res,
425                       struct flowi6 *fl6, int oif, bool have_oif_match,
426                       const struct sk_buff *skb, int strict)
427 {
428         struct fib6_info *sibling, *next_sibling;
429         struct fib6_info *match = res->f6i;
430
431         if ((!match->fib6_nsiblings && !match->nh) || have_oif_match)
432                 goto out;
433
434         /* We might have already computed the hash for ICMPv6 errors. In such
435          * case it will always be non-zero. Otherwise now is the time to do it.
436          */
437         if (!fl6->mp_hash &&
438             (!match->nh || nexthop_is_multipath(match->nh)))
439                 fl6->mp_hash = rt6_multipath_hash(net, fl6, skb, NULL);
440
441         if (unlikely(match->nh)) {
442                 nexthop_path_fib6_result(res, fl6->mp_hash);
443                 return;
444         }
445
446         if (fl6->mp_hash <= atomic_read(&match->fib6_nh->fib_nh_upper_bound))
447                 goto out;
448
449         list_for_each_entry_safe(sibling, next_sibling, &match->fib6_siblings,
450                                  fib6_siblings) {
451                 const struct fib6_nh *nh = sibling->fib6_nh;
452                 int nh_upper_bound;
453
454                 nh_upper_bound = atomic_read(&nh->fib_nh_upper_bound);
455                 if (fl6->mp_hash > nh_upper_bound)
456                         continue;
457                 if (rt6_score_route(nh, sibling->fib6_flags, oif, strict) < 0)
458                         break;
459                 match = sibling;
460                 break;
461         }
462
463 out:
464         res->f6i = match;
465         res->nh = match->fib6_nh;
466 }
467
468 /*
469  *      Route lookup. rcu_read_lock() should be held.
470  */
471
472 static bool __rt6_device_match(struct net *net, const struct fib6_nh *nh,
473                                const struct in6_addr *saddr, int oif, int flags)
474 {
475         const struct net_device *dev;
476
477         if (nh->fib_nh_flags & RTNH_F_DEAD)
478                 return false;
479
480         dev = nh->fib_nh_dev;
481         if (oif) {
482                 if (dev->ifindex == oif)
483                         return true;
484         } else {
485                 if (ipv6_chk_addr(net, saddr, dev,
486                                   flags & RT6_LOOKUP_F_IFACE))
487                         return true;
488         }
489
490         return false;
491 }
492
493 struct fib6_nh_dm_arg {
494         struct net              *net;
495         const struct in6_addr   *saddr;
496         int                     oif;
497         int                     flags;
498         struct fib6_nh          *nh;
499 };
500
501 static int __rt6_nh_dev_match(struct fib6_nh *nh, void *_arg)
502 {
503         struct fib6_nh_dm_arg *arg = _arg;
504
505         arg->nh = nh;
506         return __rt6_device_match(arg->net, nh, arg->saddr, arg->oif,
507                                   arg->flags);
508 }
509
510 /* returns fib6_nh from nexthop or NULL */
511 static struct fib6_nh *rt6_nh_dev_match(struct net *net, struct nexthop *nh,
512                                         struct fib6_result *res,
513                                         const struct in6_addr *saddr,
514                                         int oif, int flags)
515 {
516         struct fib6_nh_dm_arg arg = {
517                 .net   = net,
518                 .saddr = saddr,
519                 .oif   = oif,
520                 .flags = flags,
521         };
522
523         if (nexthop_is_blackhole(nh))
524                 return NULL;
525
526         if (nexthop_for_each_fib6_nh(nh, __rt6_nh_dev_match, &arg))
527                 return arg.nh;
528
529         return NULL;
530 }
531
532 static void rt6_device_match(struct net *net, struct fib6_result *res,
533                              const struct in6_addr *saddr, int oif, int flags)
534 {
535         struct fib6_info *f6i = res->f6i;
536         struct fib6_info *spf6i;
537         struct fib6_nh *nh;
538
539         if (!oif && ipv6_addr_any(saddr)) {
540                 if (unlikely(f6i->nh)) {
541                         nh = nexthop_fib6_nh(f6i->nh);
542                         if (nexthop_is_blackhole(f6i->nh))
543                                 goto out_blackhole;
544                 } else {
545                         nh = f6i->fib6_nh;
546                 }
547                 if (!(nh->fib_nh_flags & RTNH_F_DEAD))
548                         goto out;
549         }
550
551         for (spf6i = f6i; spf6i; spf6i = rcu_dereference(spf6i->fib6_next)) {
552                 bool matched = false;
553
554                 if (unlikely(spf6i->nh)) {
555                         nh = rt6_nh_dev_match(net, spf6i->nh, res, saddr,
556                                               oif, flags);
557                         if (nh)
558                                 matched = true;
559                 } else {
560                         nh = spf6i->fib6_nh;
561                         if (__rt6_device_match(net, nh, saddr, oif, flags))
562                                 matched = true;
563                 }
564                 if (matched) {
565                         res->f6i = spf6i;
566                         goto out;
567                 }
568         }
569
570         if (oif && flags & RT6_LOOKUP_F_IFACE) {
571                 res->f6i = net->ipv6.fib6_null_entry;
572                 nh = res->f6i->fib6_nh;
573                 goto out;
574         }
575
576         if (unlikely(f6i->nh)) {
577                 nh = nexthop_fib6_nh(f6i->nh);
578                 if (nexthop_is_blackhole(f6i->nh))
579                         goto out_blackhole;
580         } else {
581                 nh = f6i->fib6_nh;
582         }
583
584         if (nh->fib_nh_flags & RTNH_F_DEAD) {
585                 res->f6i = net->ipv6.fib6_null_entry;
586                 nh = res->f6i->fib6_nh;
587         }
588 out:
589         res->nh = nh;
590         res->fib6_type = res->f6i->fib6_type;
591         res->fib6_flags = res->f6i->fib6_flags;
592         return;
593
594 out_blackhole:
595         res->fib6_flags |= RTF_REJECT;
596         res->fib6_type = RTN_BLACKHOLE;
597         res->nh = nh;
598 }
599
600 #ifdef CONFIG_IPV6_ROUTER_PREF
601 struct __rt6_probe_work {
602         struct work_struct work;
603         struct in6_addr target;
604         struct net_device *dev;
605 };
606
607 static void rt6_probe_deferred(struct work_struct *w)
608 {
609         struct in6_addr mcaddr;
610         struct __rt6_probe_work *work =
611                 container_of(w, struct __rt6_probe_work, work);
612
613         addrconf_addr_solict_mult(&work->target, &mcaddr);
614         ndisc_send_ns(work->dev, &work->target, &mcaddr, NULL, 0);
615         dev_put(work->dev);
616         kfree(work);
617 }
618
619 static void rt6_probe(struct fib6_nh *fib6_nh)
620 {
621         struct __rt6_probe_work *work = NULL;
622         const struct in6_addr *nh_gw;
623         struct neighbour *neigh;
624         struct net_device *dev;
625         struct inet6_dev *idev;
626
627         /*
628          * Okay, this does not seem to be appropriate
629          * for now, however, we need to check if it
630          * is really so; aka Router Reachability Probing.
631          *
632          * Router Reachability Probe MUST be rate-limited
633          * to no more than one per minute.
634          */
635         if (fib6_nh->fib_nh_gw_family)
636                 return;
637
638         nh_gw = &fib6_nh->fib_nh_gw6;
639         dev = fib6_nh->fib_nh_dev;
640         rcu_read_lock_bh();
641         idev = __in6_dev_get(dev);
642         neigh = __ipv6_neigh_lookup_noref(dev, nh_gw);
643         if (neigh) {
644                 if (neigh->nud_state & NUD_VALID)
645                         goto out;
646
647                 write_lock(&neigh->lock);
648                 if (!(neigh->nud_state & NUD_VALID) &&
649                     time_after(jiffies,
650                                neigh->updated + idev->cnf.rtr_probe_interval)) {
651                         work = kmalloc(sizeof(*work), GFP_ATOMIC);
652                         if (work)
653                                 __neigh_set_probe_once(neigh);
654                 }
655                 write_unlock(&neigh->lock);
656         } else if (time_after(jiffies, fib6_nh->last_probe +
657                                        idev->cnf.rtr_probe_interval)) {
658                 work = kmalloc(sizeof(*work), GFP_ATOMIC);
659         }
660
661         if (work) {
662                 fib6_nh->last_probe = jiffies;
663                 INIT_WORK(&work->work, rt6_probe_deferred);
664                 work->target = *nh_gw;
665                 dev_hold(dev);
666                 work->dev = dev;
667                 schedule_work(&work->work);
668         }
669
670 out:
671         rcu_read_unlock_bh();
672 }
673 #else
674 static inline void rt6_probe(struct fib6_nh *fib6_nh)
675 {
676 }
677 #endif
678
679 /*
680  * Default Router Selection (RFC 2461 6.3.6)
681  */
682 static enum rt6_nud_state rt6_check_neigh(const struct fib6_nh *fib6_nh)
683 {
684         enum rt6_nud_state ret = RT6_NUD_FAIL_HARD;
685         struct neighbour *neigh;
686
687         rcu_read_lock_bh();
688         neigh = __ipv6_neigh_lookup_noref(fib6_nh->fib_nh_dev,
689                                           &fib6_nh->fib_nh_gw6);
690         if (neigh) {
691                 read_lock(&neigh->lock);
692                 if (neigh->nud_state & NUD_VALID)
693                         ret = RT6_NUD_SUCCEED;
694 #ifdef CONFIG_IPV6_ROUTER_PREF
695                 else if (!(neigh->nud_state & NUD_FAILED))
696                         ret = RT6_NUD_SUCCEED;
697                 else
698                         ret = RT6_NUD_FAIL_PROBE;
699 #endif
700                 read_unlock(&neigh->lock);
701         } else {
702                 ret = IS_ENABLED(CONFIG_IPV6_ROUTER_PREF) ?
703                       RT6_NUD_SUCCEED : RT6_NUD_FAIL_DO_RR;
704         }
705         rcu_read_unlock_bh();
706
707         return ret;
708 }
709
710 static int rt6_score_route(const struct fib6_nh *nh, u32 fib6_flags, int oif,
711                            int strict)
712 {
713         int m = 0;
714
715         if (!oif || nh->fib_nh_dev->ifindex == oif)
716                 m = 2;
717
718         if (!m && (strict & RT6_LOOKUP_F_IFACE))
719                 return RT6_NUD_FAIL_HARD;
720 #ifdef CONFIG_IPV6_ROUTER_PREF
721         m |= IPV6_DECODE_PREF(IPV6_EXTRACT_PREF(fib6_flags)) << 2;
722 #endif
723         if ((strict & RT6_LOOKUP_F_REACHABLE) &&
724             !(fib6_flags & RTF_NONEXTHOP) && nh->fib_nh_gw_family) {
725                 int n = rt6_check_neigh(nh);
726                 if (n < 0)
727                         return n;
728         }
729         return m;
730 }
731
732 static bool find_match(struct fib6_nh *nh, u32 fib6_flags,
733                        int oif, int strict, int *mpri, bool *do_rr)
734 {
735         bool match_do_rr = false;
736         bool rc = false;
737         int m;
738
739         if (nh->fib_nh_flags & RTNH_F_DEAD)
740                 goto out;
741
742         if (ip6_ignore_linkdown(nh->fib_nh_dev) &&
743             nh->fib_nh_flags & RTNH_F_LINKDOWN &&
744             !(strict & RT6_LOOKUP_F_IGNORE_LINKSTATE))
745                 goto out;
746
747         m = rt6_score_route(nh, fib6_flags, oif, strict);
748         if (m == RT6_NUD_FAIL_DO_RR) {
749                 match_do_rr = true;
750                 m = 0; /* lowest valid score */
751         } else if (m == RT6_NUD_FAIL_HARD) {
752                 goto out;
753         }
754
755         if (strict & RT6_LOOKUP_F_REACHABLE)
756                 rt6_probe(nh);
757
758         /* note that m can be RT6_NUD_FAIL_PROBE at this point */
759         if (m > *mpri) {
760                 *do_rr = match_do_rr;
761                 *mpri = m;
762                 rc = true;
763         }
764 out:
765         return rc;
766 }
767
768 static void __find_rr_leaf(struct fib6_info *f6i_start,
769                            struct fib6_info *nomatch, u32 metric,
770                            struct fib6_result *res, struct fib6_info **cont,
771                            int oif, int strict, bool *do_rr, int *mpri)
772 {
773         struct fib6_info *f6i;
774
775         for (f6i = f6i_start;
776              f6i && f6i != nomatch;
777              f6i = rcu_dereference(f6i->fib6_next)) {
778                 struct fib6_nh *nh;
779
780                 if (cont && f6i->fib6_metric != metric) {
781                         *cont = f6i;
782                         return;
783                 }
784
785                 if (fib6_check_expired(f6i))
786                         continue;
787
788                 nh = f6i->fib6_nh;
789                 if (find_match(nh, f6i->fib6_flags, oif, strict, mpri, do_rr)) {
790                         res->f6i = f6i;
791                         res->nh = nh;
792                         res->fib6_flags = f6i->fib6_flags;
793                         res->fib6_type = f6i->fib6_type;
794                 }
795         }
796 }
797
798 static void find_rr_leaf(struct fib6_node *fn, struct fib6_info *leaf,
799                          struct fib6_info *rr_head, int oif, int strict,
800                          bool *do_rr, struct fib6_result *res)
801 {
802         u32 metric = rr_head->fib6_metric;
803         struct fib6_info *cont = NULL;
804         int mpri = -1;
805
806         __find_rr_leaf(rr_head, NULL, metric, res, &cont,
807                        oif, strict, do_rr, &mpri);
808
809         __find_rr_leaf(leaf, rr_head, metric, res, &cont,
810                        oif, strict, do_rr, &mpri);
811
812         if (res->f6i || !cont)
813                 return;
814
815         __find_rr_leaf(cont, NULL, metric, res, NULL,
816                        oif, strict, do_rr, &mpri);
817 }
818
819 static void rt6_select(struct net *net, struct fib6_node *fn, int oif,
820                        struct fib6_result *res, int strict)
821 {
822         struct fib6_info *leaf = rcu_dereference(fn->leaf);
823         struct fib6_info *rt0;
824         bool do_rr = false;
825         int key_plen;
826
827         /* make sure this function or its helpers sets f6i */
828         res->f6i = NULL;
829
830         if (!leaf || leaf == net->ipv6.fib6_null_entry)
831                 goto out;
832
833         rt0 = rcu_dereference(fn->rr_ptr);
834         if (!rt0)
835                 rt0 = leaf;
836
837         /* Double check to make sure fn is not an intermediate node
838          * and fn->leaf does not points to its child's leaf
839          * (This might happen if all routes under fn are deleted from
840          * the tree and fib6_repair_tree() is called on the node.)
841          */
842         key_plen = rt0->fib6_dst.plen;
843 #ifdef CONFIG_IPV6_SUBTREES
844         if (rt0->fib6_src.plen)
845                 key_plen = rt0->fib6_src.plen;
846 #endif
847         if (fn->fn_bit != key_plen)
848                 goto out;
849
850         find_rr_leaf(fn, leaf, rt0, oif, strict, &do_rr, res);
851         if (do_rr) {
852                 struct fib6_info *next = rcu_dereference(rt0->fib6_next);
853
854                 /* no entries matched; do round-robin */
855                 if (!next || next->fib6_metric != rt0->fib6_metric)
856                         next = leaf;
857
858                 if (next != rt0) {
859                         spin_lock_bh(&leaf->fib6_table->tb6_lock);
860                         /* make sure next is not being deleted from the tree */
861                         if (next->fib6_node)
862                                 rcu_assign_pointer(fn->rr_ptr, next);
863                         spin_unlock_bh(&leaf->fib6_table->tb6_lock);
864                 }
865         }
866
867 out:
868         if (!res->f6i) {
869                 res->f6i = net->ipv6.fib6_null_entry;
870                 res->nh = res->f6i->fib6_nh;
871                 res->fib6_flags = res->f6i->fib6_flags;
872                 res->fib6_type = res->f6i->fib6_type;
873         }
874 }
875
876 static bool rt6_is_gw_or_nonexthop(const struct fib6_result *res)
877 {
878         return (res->f6i->fib6_flags & RTF_NONEXTHOP) ||
879                res->nh->fib_nh_gw_family;
880 }
881
882 #ifdef CONFIG_IPV6_ROUTE_INFO
883 int rt6_route_rcv(struct net_device *dev, u8 *opt, int len,
884                   const struct in6_addr *gwaddr)
885 {
886         struct net *net = dev_net(dev);
887         struct route_info *rinfo = (struct route_info *) opt;
888         struct in6_addr prefix_buf, *prefix;
889         unsigned int pref;
890         unsigned long lifetime;
891         struct fib6_info *rt;
892
893         if (len < sizeof(struct route_info)) {
894                 return -EINVAL;
895         }
896
897         /* Sanity check for prefix_len and length */
898         if (rinfo->length > 3) {
899                 return -EINVAL;
900         } else if (rinfo->prefix_len > 128) {
901                 return -EINVAL;
902         } else if (rinfo->prefix_len > 64) {
903                 if (rinfo->length < 2) {
904                         return -EINVAL;
905                 }
906         } else if (rinfo->prefix_len > 0) {
907                 if (rinfo->length < 1) {
908                         return -EINVAL;
909                 }
910         }
911
912         pref = rinfo->route_pref;
913         if (pref == ICMPV6_ROUTER_PREF_INVALID)
914                 return -EINVAL;
915
916         lifetime = addrconf_timeout_fixup(ntohl(rinfo->lifetime), HZ);
917
918         if (rinfo->length == 3)
919                 prefix = (struct in6_addr *)rinfo->prefix;
920         else {
921                 /* this function is safe */
922                 ipv6_addr_prefix(&prefix_buf,
923                                  (struct in6_addr *)rinfo->prefix,
924                                  rinfo->prefix_len);
925                 prefix = &prefix_buf;
926         }
927
928         if (rinfo->prefix_len == 0)
929                 rt = rt6_get_dflt_router(net, gwaddr, dev);
930         else
931                 rt = rt6_get_route_info(net, prefix, rinfo->prefix_len,
932                                         gwaddr, dev);
933
934         if (rt && !lifetime) {
935                 ip6_del_rt(net, rt);
936                 rt = NULL;
937         }
938
939         if (!rt && lifetime)
940                 rt = rt6_add_route_info(net, prefix, rinfo->prefix_len, gwaddr,
941                                         dev, pref);
942         else if (rt)
943                 rt->fib6_flags = RTF_ROUTEINFO |
944                                  (rt->fib6_flags & ~RTF_PREF_MASK) | RTF_PREF(pref);
945
946         if (rt) {
947                 if (!addrconf_finite_timeout(lifetime))
948                         fib6_clean_expires(rt);
949                 else
950                         fib6_set_expires(rt, jiffies + HZ * lifetime);
951
952                 fib6_info_release(rt);
953         }
954         return 0;
955 }
956 #endif
957
958 /*
959  *      Misc support functions
960  */
961
962 /* called with rcu_lock held */
963 static struct net_device *ip6_rt_get_dev_rcu(const struct fib6_result *res)
964 {
965         struct net_device *dev = res->nh->fib_nh_dev;
966
967         if (res->fib6_flags & (RTF_LOCAL | RTF_ANYCAST)) {
968                 /* for copies of local routes, dst->dev needs to be the
969                  * device if it is a master device, the master device if
970                  * device is enslaved, and the loopback as the default
971                  */
972                 if (netif_is_l3_slave(dev) &&
973                     !rt6_need_strict(&res->f6i->fib6_dst.addr))
974                         dev = l3mdev_master_dev_rcu(dev);
975                 else if (!netif_is_l3_master(dev))
976                         dev = dev_net(dev)->loopback_dev;
977                 /* last case is netif_is_l3_master(dev) is true in which
978                  * case we want dev returned to be dev
979                  */
980         }
981
982         return dev;
983 }
984
985 static const int fib6_prop[RTN_MAX + 1] = {
986         [RTN_UNSPEC]    = 0,
987         [RTN_UNICAST]   = 0,
988         [RTN_LOCAL]     = 0,
989         [RTN_BROADCAST] = 0,
990         [RTN_ANYCAST]   = 0,
991         [RTN_MULTICAST] = 0,
992         [RTN_BLACKHOLE] = -EINVAL,
993         [RTN_UNREACHABLE] = -EHOSTUNREACH,
994         [RTN_PROHIBIT]  = -EACCES,
995         [RTN_THROW]     = -EAGAIN,
996         [RTN_NAT]       = -EINVAL,
997         [RTN_XRESOLVE]  = -EINVAL,
998 };
999
1000 static int ip6_rt_type_to_error(u8 fib6_type)
1001 {
1002         return fib6_prop[fib6_type];
1003 }
1004
1005 static unsigned short fib6_info_dst_flags(struct fib6_info *rt)
1006 {
1007         unsigned short flags = 0;
1008
1009         if (rt->dst_nocount)
1010                 flags |= DST_NOCOUNT;
1011         if (rt->dst_nopolicy)
1012                 flags |= DST_NOPOLICY;
1013         if (rt->dst_host)
1014                 flags |= DST_HOST;
1015
1016         return flags;
1017 }
1018
1019 static void ip6_rt_init_dst_reject(struct rt6_info *rt, u8 fib6_type)
1020 {
1021         rt->dst.error = ip6_rt_type_to_error(fib6_type);
1022
1023         switch (fib6_type) {
1024         case RTN_BLACKHOLE:
1025                 rt->dst.output = dst_discard_out;
1026                 rt->dst.input = dst_discard;
1027                 break;
1028         case RTN_PROHIBIT:
1029                 rt->dst.output = ip6_pkt_prohibit_out;
1030                 rt->dst.input = ip6_pkt_prohibit;
1031                 break;
1032         case RTN_THROW:
1033         case RTN_UNREACHABLE:
1034         default:
1035                 rt->dst.output = ip6_pkt_discard_out;
1036                 rt->dst.input = ip6_pkt_discard;
1037                 break;
1038         }
1039 }
1040
1041 static void ip6_rt_init_dst(struct rt6_info *rt, const struct fib6_result *res)
1042 {
1043         struct fib6_info *f6i = res->f6i;
1044
1045         if (res->fib6_flags & RTF_REJECT) {
1046                 ip6_rt_init_dst_reject(rt, res->fib6_type);
1047                 return;
1048         }
1049
1050         rt->dst.error = 0;
1051         rt->dst.output = ip6_output;
1052
1053         if (res->fib6_type == RTN_LOCAL || res->fib6_type == RTN_ANYCAST) {
1054                 rt->dst.input = ip6_input;
1055         } else if (ipv6_addr_type(&f6i->fib6_dst.addr) & IPV6_ADDR_MULTICAST) {
1056                 rt->dst.input = ip6_mc_input;
1057         } else {
1058                 rt->dst.input = ip6_forward;
1059         }
1060
1061         if (res->nh->fib_nh_lws) {
1062                 rt->dst.lwtstate = lwtstate_get(res->nh->fib_nh_lws);
1063                 lwtunnel_set_redirect(&rt->dst);
1064         }
1065
1066         rt->dst.lastuse = jiffies;
1067 }
1068
1069 /* Caller must already hold reference to @from */
1070 static void rt6_set_from(struct rt6_info *rt, struct fib6_info *from)
1071 {
1072         rt->rt6i_flags &= ~RTF_EXPIRES;
1073         rcu_assign_pointer(rt->from, from);
1074         ip_dst_init_metrics(&rt->dst, from->fib6_metrics);
1075 }
1076
1077 /* Caller must already hold reference to f6i in result */
1078 static void ip6_rt_copy_init(struct rt6_info *rt, const struct fib6_result *res)
1079 {
1080         const struct fib6_nh *nh = res->nh;
1081         const struct net_device *dev = nh->fib_nh_dev;
1082         struct fib6_info *f6i = res->f6i;
1083
1084         ip6_rt_init_dst(rt, res);
1085
1086         rt->rt6i_dst = f6i->fib6_dst;
1087         rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL;
1088         rt->rt6i_flags = res->fib6_flags;
1089         if (nh->fib_nh_gw_family) {
1090                 rt->rt6i_gateway = nh->fib_nh_gw6;
1091                 rt->rt6i_flags |= RTF_GATEWAY;
1092         }
1093         rt6_set_from(rt, f6i);
1094 #ifdef CONFIG_IPV6_SUBTREES
1095         rt->rt6i_src = f6i->fib6_src;
1096 #endif
1097 }
1098
1099 static struct fib6_node* fib6_backtrack(struct fib6_node *fn,
1100                                         struct in6_addr *saddr)
1101 {
1102         struct fib6_node *pn, *sn;
1103         while (1) {
1104                 if (fn->fn_flags & RTN_TL_ROOT)
1105                         return NULL;
1106                 pn = rcu_dereference(fn->parent);
1107                 sn = FIB6_SUBTREE(pn);
1108                 if (sn && sn != fn)
1109                         fn = fib6_node_lookup(sn, NULL, saddr);
1110                 else
1111                         fn = pn;
1112                 if (fn->fn_flags & RTN_RTINFO)
1113                         return fn;
1114         }
1115 }
1116
1117 static bool ip6_hold_safe(struct net *net, struct rt6_info **prt)
1118 {
1119         struct rt6_info *rt = *prt;
1120
1121         if (dst_hold_safe(&rt->dst))
1122                 return true;
1123         if (net) {
1124                 rt = net->ipv6.ip6_null_entry;
1125                 dst_hold(&rt->dst);
1126         } else {
1127                 rt = NULL;
1128         }
1129         *prt = rt;
1130         return false;
1131 }
1132
1133 /* called with rcu_lock held */
1134 static struct rt6_info *ip6_create_rt_rcu(const struct fib6_result *res)
1135 {
1136         struct net_device *dev = res->nh->fib_nh_dev;
1137         struct fib6_info *f6i = res->f6i;
1138         unsigned short flags;
1139         struct rt6_info *nrt;
1140
1141         if (!fib6_info_hold_safe(f6i))
1142                 goto fallback;
1143
1144         flags = fib6_info_dst_flags(f6i);
1145         nrt = ip6_dst_alloc(dev_net(dev), dev, flags);
1146         if (!nrt) {
1147                 fib6_info_release(f6i);
1148                 goto fallback;
1149         }
1150
1151         ip6_rt_copy_init(nrt, res);
1152         return nrt;
1153
1154 fallback:
1155         nrt = dev_net(dev)->ipv6.ip6_null_entry;
1156         dst_hold(&nrt->dst);
1157         return nrt;
1158 }
1159
1160 static struct rt6_info *ip6_pol_route_lookup(struct net *net,
1161                                              struct fib6_table *table,
1162                                              struct flowi6 *fl6,
1163                                              const struct sk_buff *skb,
1164                                              int flags)
1165 {
1166         struct fib6_result res = {};
1167         struct fib6_node *fn;
1168         struct rt6_info *rt;
1169
1170         if (fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF)
1171                 flags &= ~RT6_LOOKUP_F_IFACE;
1172
1173         rcu_read_lock();
1174         fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
1175 restart:
1176         res.f6i = rcu_dereference(fn->leaf);
1177         if (!res.f6i)
1178                 res.f6i = net->ipv6.fib6_null_entry;
1179         else
1180                 rt6_device_match(net, &res, &fl6->saddr, fl6->flowi6_oif,
1181                                  flags);
1182
1183         if (res.f6i == net->ipv6.fib6_null_entry) {
1184                 fn = fib6_backtrack(fn, &fl6->saddr);
1185                 if (fn)
1186                         goto restart;
1187
1188                 rt = net->ipv6.ip6_null_entry;
1189                 dst_hold(&rt->dst);
1190                 goto out;
1191         } else if (res.fib6_flags & RTF_REJECT) {
1192                 goto do_create;
1193         }
1194
1195         fib6_select_path(net, &res, fl6, fl6->flowi6_oif,
1196                          fl6->flowi6_oif != 0, skb, flags);
1197
1198         /* Search through exception table */
1199         rt = rt6_find_cached_rt(&res, &fl6->daddr, &fl6->saddr);
1200         if (rt) {
1201                 if (ip6_hold_safe(net, &rt))
1202                         dst_use_noref(&rt->dst, jiffies);
1203         } else {
1204 do_create:
1205                 rt = ip6_create_rt_rcu(&res);
1206         }
1207
1208 out:
1209         trace_fib6_table_lookup(net, &res, table, fl6);
1210
1211         rcu_read_unlock();
1212
1213         return rt;
1214 }
1215
1216 struct dst_entry *ip6_route_lookup(struct net *net, struct flowi6 *fl6,
1217                                    const struct sk_buff *skb, int flags)
1218 {
1219         return fib6_rule_lookup(net, fl6, skb, flags, ip6_pol_route_lookup);
1220 }
1221 EXPORT_SYMBOL_GPL(ip6_route_lookup);
1222
1223 struct rt6_info *rt6_lookup(struct net *net, const struct in6_addr *daddr,
1224                             const struct in6_addr *saddr, int oif,
1225                             const struct sk_buff *skb, int strict)
1226 {
1227         struct flowi6 fl6 = {
1228                 .flowi6_oif = oif,
1229                 .daddr = *daddr,
1230         };
1231         struct dst_entry *dst;
1232         int flags = strict ? RT6_LOOKUP_F_IFACE : 0;
1233
1234         if (saddr) {
1235                 memcpy(&fl6.saddr, saddr, sizeof(*saddr));
1236                 flags |= RT6_LOOKUP_F_HAS_SADDR;
1237         }
1238
1239         dst = fib6_rule_lookup(net, &fl6, skb, flags, ip6_pol_route_lookup);
1240         if (dst->error == 0)
1241                 return (struct rt6_info *) dst;
1242
1243         dst_release(dst);
1244
1245         return NULL;
1246 }
1247 EXPORT_SYMBOL(rt6_lookup);
1248
1249 /* ip6_ins_rt is called with FREE table->tb6_lock.
1250  * It takes new route entry, the addition fails by any reason the
1251  * route is released.
1252  * Caller must hold dst before calling it.
1253  */
1254
1255 static int __ip6_ins_rt(struct fib6_info *rt, struct nl_info *info,
1256                         struct netlink_ext_ack *extack)
1257 {
1258         int err;
1259         struct fib6_table *table;
1260
1261         table = rt->fib6_table;
1262         spin_lock_bh(&table->tb6_lock);
1263         err = fib6_add(&table->tb6_root, rt, info, extack);
1264         spin_unlock_bh(&table->tb6_lock);
1265
1266         return err;
1267 }
1268
1269 int ip6_ins_rt(struct net *net, struct fib6_info *rt)
1270 {
1271         struct nl_info info = { .nl_net = net, };
1272
1273         return __ip6_ins_rt(rt, &info, NULL);
1274 }
1275
1276 static struct rt6_info *ip6_rt_cache_alloc(const struct fib6_result *res,
1277                                            const struct in6_addr *daddr,
1278                                            const struct in6_addr *saddr)
1279 {
1280         struct fib6_info *f6i = res->f6i;
1281         struct net_device *dev;
1282         struct rt6_info *rt;
1283
1284         /*
1285          *      Clone the route.
1286          */
1287
1288         if (!fib6_info_hold_safe(f6i))
1289                 return NULL;
1290
1291         dev = ip6_rt_get_dev_rcu(res);
1292         rt = ip6_dst_alloc(dev_net(dev), dev, 0);
1293         if (!rt) {
1294                 fib6_info_release(f6i);
1295                 return NULL;
1296         }
1297
1298         ip6_rt_copy_init(rt, res);
1299         rt->rt6i_flags |= RTF_CACHE;
1300         rt->dst.flags |= DST_HOST;
1301         rt->rt6i_dst.addr = *daddr;
1302         rt->rt6i_dst.plen = 128;
1303
1304         if (!rt6_is_gw_or_nonexthop(res)) {
1305                 if (f6i->fib6_dst.plen != 128 &&
1306                     ipv6_addr_equal(&f6i->fib6_dst.addr, daddr))
1307                         rt->rt6i_flags |= RTF_ANYCAST;
1308 #ifdef CONFIG_IPV6_SUBTREES
1309                 if (rt->rt6i_src.plen && saddr) {
1310                         rt->rt6i_src.addr = *saddr;
1311                         rt->rt6i_src.plen = 128;
1312                 }
1313 #endif
1314         }
1315
1316         return rt;
1317 }
1318
1319 static struct rt6_info *ip6_rt_pcpu_alloc(const struct fib6_result *res)
1320 {
1321         struct fib6_info *f6i = res->f6i;
1322         unsigned short flags = fib6_info_dst_flags(f6i);
1323         struct net_device *dev;
1324         struct rt6_info *pcpu_rt;
1325
1326         if (!fib6_info_hold_safe(f6i))
1327                 return NULL;
1328
1329         rcu_read_lock();
1330         dev = ip6_rt_get_dev_rcu(res);
1331         pcpu_rt = ip6_dst_alloc(dev_net(dev), dev, flags);
1332         rcu_read_unlock();
1333         if (!pcpu_rt) {
1334                 fib6_info_release(f6i);
1335                 return NULL;
1336         }
1337         ip6_rt_copy_init(pcpu_rt, res);
1338         pcpu_rt->rt6i_flags |= RTF_PCPU;
1339         return pcpu_rt;
1340 }
1341
1342 /* It should be called with rcu_read_lock() acquired */
1343 static struct rt6_info *rt6_get_pcpu_route(const struct fib6_result *res)
1344 {
1345         struct rt6_info *pcpu_rt;
1346
1347         pcpu_rt = this_cpu_read(*res->nh->rt6i_pcpu);
1348
1349         if (pcpu_rt)
1350                 ip6_hold_safe(NULL, &pcpu_rt);
1351
1352         return pcpu_rt;
1353 }
1354
1355 static struct rt6_info *rt6_make_pcpu_route(struct net *net,
1356                                             const struct fib6_result *res)
1357 {
1358         struct rt6_info *pcpu_rt, *prev, **p;
1359
1360         pcpu_rt = ip6_rt_pcpu_alloc(res);
1361         if (!pcpu_rt) {
1362                 dst_hold(&net->ipv6.ip6_null_entry->dst);
1363                 return net->ipv6.ip6_null_entry;
1364         }
1365
1366         dst_hold(&pcpu_rt->dst);
1367         p = this_cpu_ptr(res->nh->rt6i_pcpu);
1368         prev = cmpxchg(p, NULL, pcpu_rt);
1369         BUG_ON(prev);
1370
1371         if (res->f6i->fib6_destroying) {
1372                 struct fib6_info *from;
1373
1374                 from = xchg((__force struct fib6_info **)&pcpu_rt->from, NULL);
1375                 fib6_info_release(from);
1376         }
1377
1378         return pcpu_rt;
1379 }
1380
1381 /* exception hash table implementation
1382  */
1383 static DEFINE_SPINLOCK(rt6_exception_lock);
1384
1385 /* Remove rt6_ex from hash table and free the memory
1386  * Caller must hold rt6_exception_lock
1387  */
1388 static void rt6_remove_exception(struct rt6_exception_bucket *bucket,
1389                                  struct rt6_exception *rt6_ex)
1390 {
1391         struct fib6_info *from;
1392         struct net *net;
1393
1394         if (!bucket || !rt6_ex)
1395                 return;
1396
1397         net = dev_net(rt6_ex->rt6i->dst.dev);
1398         net->ipv6.rt6_stats->fib_rt_cache--;
1399
1400         /* purge completely the exception to allow releasing the held resources:
1401          * some [sk] cache may keep the dst around for unlimited time
1402          */
1403         from = xchg((__force struct fib6_info **)&rt6_ex->rt6i->from, NULL);
1404         fib6_info_release(from);
1405         dst_dev_put(&rt6_ex->rt6i->dst);
1406
1407         hlist_del_rcu(&rt6_ex->hlist);
1408         dst_release(&rt6_ex->rt6i->dst);
1409         kfree_rcu(rt6_ex, rcu);
1410         WARN_ON_ONCE(!bucket->depth);
1411         bucket->depth--;
1412 }
1413
1414 /* Remove oldest rt6_ex in bucket and free the memory
1415  * Caller must hold rt6_exception_lock
1416  */
1417 static void rt6_exception_remove_oldest(struct rt6_exception_bucket *bucket)
1418 {
1419         struct rt6_exception *rt6_ex, *oldest = NULL;
1420
1421         if (!bucket)
1422                 return;
1423
1424         hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
1425                 if (!oldest || time_before(rt6_ex->stamp, oldest->stamp))
1426                         oldest = rt6_ex;
1427         }
1428         rt6_remove_exception(bucket, oldest);
1429 }
1430
1431 static u32 rt6_exception_hash(const struct in6_addr *dst,
1432                               const struct in6_addr *src)
1433 {
1434         static u32 seed __read_mostly;
1435         u32 val;
1436
1437         net_get_random_once(&seed, sizeof(seed));
1438         val = jhash(dst, sizeof(*dst), seed);
1439
1440 #ifdef CONFIG_IPV6_SUBTREES
1441         if (src)
1442                 val = jhash(src, sizeof(*src), val);
1443 #endif
1444         return hash_32(val, FIB6_EXCEPTION_BUCKET_SIZE_SHIFT);
1445 }
1446
1447 /* Helper function to find the cached rt in the hash table
1448  * and update bucket pointer to point to the bucket for this
1449  * (daddr, saddr) pair
1450  * Caller must hold rt6_exception_lock
1451  */
1452 static struct rt6_exception *
1453 __rt6_find_exception_spinlock(struct rt6_exception_bucket **bucket,
1454                               const struct in6_addr *daddr,
1455                               const struct in6_addr *saddr)
1456 {
1457         struct rt6_exception *rt6_ex;
1458         u32 hval;
1459
1460         if (!(*bucket) || !daddr)
1461                 return NULL;
1462
1463         hval = rt6_exception_hash(daddr, saddr);
1464         *bucket += hval;
1465
1466         hlist_for_each_entry(rt6_ex, &(*bucket)->chain, hlist) {
1467                 struct rt6_info *rt6 = rt6_ex->rt6i;
1468                 bool matched = ipv6_addr_equal(daddr, &rt6->rt6i_dst.addr);
1469
1470 #ifdef CONFIG_IPV6_SUBTREES
1471                 if (matched && saddr)
1472                         matched = ipv6_addr_equal(saddr, &rt6->rt6i_src.addr);
1473 #endif
1474                 if (matched)
1475                         return rt6_ex;
1476         }
1477         return NULL;
1478 }
1479
1480 /* Helper function to find the cached rt in the hash table
1481  * and update bucket pointer to point to the bucket for this
1482  * (daddr, saddr) pair
1483  * Caller must hold rcu_read_lock()
1484  */
1485 static struct rt6_exception *
1486 __rt6_find_exception_rcu(struct rt6_exception_bucket **bucket,
1487                          const struct in6_addr *daddr,
1488                          const struct in6_addr *saddr)
1489 {
1490         struct rt6_exception *rt6_ex;
1491         u32 hval;
1492
1493         WARN_ON_ONCE(!rcu_read_lock_held());
1494
1495         if (!(*bucket) || !daddr)
1496                 return NULL;
1497
1498         hval = rt6_exception_hash(daddr, saddr);
1499         *bucket += hval;
1500
1501         hlist_for_each_entry_rcu(rt6_ex, &(*bucket)->chain, hlist) {
1502                 struct rt6_info *rt6 = rt6_ex->rt6i;
1503                 bool matched = ipv6_addr_equal(daddr, &rt6->rt6i_dst.addr);
1504
1505 #ifdef CONFIG_IPV6_SUBTREES
1506                 if (matched && saddr)
1507                         matched = ipv6_addr_equal(saddr, &rt6->rt6i_src.addr);
1508 #endif
1509                 if (matched)
1510                         return rt6_ex;
1511         }
1512         return NULL;
1513 }
1514
1515 static unsigned int fib6_mtu(const struct fib6_result *res)
1516 {
1517         const struct fib6_nh *nh = res->nh;
1518         unsigned int mtu;
1519
1520         if (res->f6i->fib6_pmtu) {
1521                 mtu = res->f6i->fib6_pmtu;
1522         } else {
1523                 struct net_device *dev = nh->fib_nh_dev;
1524                 struct inet6_dev *idev;
1525
1526                 rcu_read_lock();
1527                 idev = __in6_dev_get(dev);
1528                 mtu = idev->cnf.mtu6;
1529                 rcu_read_unlock();
1530         }
1531
1532         mtu = min_t(unsigned int, mtu, IP6_MAX_MTU);
1533
1534         return mtu - lwtunnel_headroom(nh->fib_nh_lws, mtu);
1535 }
1536
1537 #define FIB6_EXCEPTION_BUCKET_FLUSHED  0x1UL
1538
1539 /* used when the flushed bit is not relevant, only access to the bucket
1540  * (ie., all bucket users except rt6_insert_exception);
1541  *
1542  * called under rcu lock; sometimes called with rt6_exception_lock held
1543  */
1544 static
1545 struct rt6_exception_bucket *fib6_nh_get_excptn_bucket(const struct fib6_nh *nh,
1546                                                        spinlock_t *lock)
1547 {
1548         struct rt6_exception_bucket *bucket;
1549
1550         if (lock)
1551                 bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1552                                                    lockdep_is_held(lock));
1553         else
1554                 bucket = rcu_dereference(nh->rt6i_exception_bucket);
1555
1556         /* remove bucket flushed bit if set */
1557         if (bucket) {
1558                 unsigned long p = (unsigned long)bucket;
1559
1560                 p &= ~FIB6_EXCEPTION_BUCKET_FLUSHED;
1561                 bucket = (struct rt6_exception_bucket *)p;
1562         }
1563
1564         return bucket;
1565 }
1566
1567 static bool fib6_nh_excptn_bucket_flushed(struct rt6_exception_bucket *bucket)
1568 {
1569         unsigned long p = (unsigned long)bucket;
1570
1571         return !!(p & FIB6_EXCEPTION_BUCKET_FLUSHED);
1572 }
1573
1574 /* called with rt6_exception_lock held */
1575 static void fib6_nh_excptn_bucket_set_flushed(struct fib6_nh *nh,
1576                                               spinlock_t *lock)
1577 {
1578         struct rt6_exception_bucket *bucket;
1579         unsigned long p;
1580
1581         bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1582                                            lockdep_is_held(lock));
1583
1584         p = (unsigned long)bucket;
1585         p |= FIB6_EXCEPTION_BUCKET_FLUSHED;
1586         bucket = (struct rt6_exception_bucket *)p;
1587         rcu_assign_pointer(nh->rt6i_exception_bucket, bucket);
1588 }
1589
1590 static int rt6_insert_exception(struct rt6_info *nrt,
1591                                 const struct fib6_result *res)
1592 {
1593         struct net *net = dev_net(nrt->dst.dev);
1594         struct rt6_exception_bucket *bucket;
1595         struct fib6_info *f6i = res->f6i;
1596         struct in6_addr *src_key = NULL;
1597         struct rt6_exception *rt6_ex;
1598         struct fib6_nh *nh = res->nh;
1599         int err = 0;
1600
1601         spin_lock_bh(&rt6_exception_lock);
1602
1603         bucket = rcu_dereference_protected(nh->rt6i_exception_bucket,
1604                                           lockdep_is_held(&rt6_exception_lock));
1605         if (!bucket) {
1606                 bucket = kcalloc(FIB6_EXCEPTION_BUCKET_SIZE, sizeof(*bucket),
1607                                  GFP_ATOMIC);
1608                 if (!bucket) {
1609                         err = -ENOMEM;
1610                         goto out;
1611                 }
1612                 rcu_assign_pointer(nh->rt6i_exception_bucket, bucket);
1613         } else if (fib6_nh_excptn_bucket_flushed(bucket)) {
1614                 err = -EINVAL;
1615                 goto out;
1616         }
1617
1618 #ifdef CONFIG_IPV6_SUBTREES
1619         /* fib6_src.plen != 0 indicates f6i is in subtree
1620          * and exception table is indexed by a hash of
1621          * both fib6_dst and fib6_src.
1622          * Otherwise, the exception table is indexed by
1623          * a hash of only fib6_dst.
1624          */
1625         if (f6i->fib6_src.plen)
1626                 src_key = &nrt->rt6i_src.addr;
1627 #endif
1628         /* rt6_mtu_change() might lower mtu on f6i.
1629          * Only insert this exception route if its mtu
1630          * is less than f6i's mtu value.
1631          */
1632         if (dst_metric_raw(&nrt->dst, RTAX_MTU) >= fib6_mtu(res)) {
1633                 err = -EINVAL;
1634                 goto out;
1635         }
1636
1637         rt6_ex = __rt6_find_exception_spinlock(&bucket, &nrt->rt6i_dst.addr,
1638                                                src_key);
1639         if (rt6_ex)
1640                 rt6_remove_exception(bucket, rt6_ex);
1641
1642         rt6_ex = kzalloc(sizeof(*rt6_ex), GFP_ATOMIC);
1643         if (!rt6_ex) {
1644                 err = -ENOMEM;
1645                 goto out;
1646         }
1647         rt6_ex->rt6i = nrt;
1648         rt6_ex->stamp = jiffies;
1649         hlist_add_head_rcu(&rt6_ex->hlist, &bucket->chain);
1650         bucket->depth++;
1651         net->ipv6.rt6_stats->fib_rt_cache++;
1652
1653         if (bucket->depth > FIB6_MAX_DEPTH)
1654                 rt6_exception_remove_oldest(bucket);
1655
1656 out:
1657         spin_unlock_bh(&rt6_exception_lock);
1658
1659         /* Update fn->fn_sernum to invalidate all cached dst */
1660         if (!err) {
1661                 spin_lock_bh(&f6i->fib6_table->tb6_lock);
1662                 fib6_update_sernum(net, f6i);
1663                 spin_unlock_bh(&f6i->fib6_table->tb6_lock);
1664                 fib6_force_start_gc(net);
1665         }
1666
1667         return err;
1668 }
1669
1670 static void fib6_nh_flush_exceptions(struct fib6_nh *nh, struct fib6_info *from)
1671 {
1672         struct rt6_exception_bucket *bucket;
1673         struct rt6_exception *rt6_ex;
1674         struct hlist_node *tmp;
1675         int i;
1676
1677         spin_lock_bh(&rt6_exception_lock);
1678
1679         bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1680         if (!bucket)
1681                 goto out;
1682
1683         /* Prevent rt6_insert_exception() to recreate the bucket list */
1684         if (!from)
1685                 fib6_nh_excptn_bucket_set_flushed(nh, &rt6_exception_lock);
1686
1687         for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
1688                 hlist_for_each_entry_safe(rt6_ex, tmp, &bucket->chain, hlist) {
1689                         if (!from ||
1690                             rcu_access_pointer(rt6_ex->rt6i->from) == from)
1691                                 rt6_remove_exception(bucket, rt6_ex);
1692                 }
1693                 WARN_ON_ONCE(!from && bucket->depth);
1694                 bucket++;
1695         }
1696 out:
1697         spin_unlock_bh(&rt6_exception_lock);
1698 }
1699
1700 void rt6_flush_exceptions(struct fib6_info *f6i)
1701 {
1702         fib6_nh_flush_exceptions(f6i->fib6_nh, f6i);
1703 }
1704
1705 /* Find cached rt in the hash table inside passed in rt
1706  * Caller has to hold rcu_read_lock()
1707  */
1708 static struct rt6_info *rt6_find_cached_rt(const struct fib6_result *res,
1709                                            const struct in6_addr *daddr,
1710                                            const struct in6_addr *saddr)
1711 {
1712         const struct in6_addr *src_key = NULL;
1713         struct rt6_exception_bucket *bucket;
1714         struct rt6_exception *rt6_ex;
1715         struct rt6_info *ret = NULL;
1716
1717 #ifdef CONFIG_IPV6_SUBTREES
1718         /* fib6i_src.plen != 0 indicates f6i is in subtree
1719          * and exception table is indexed by a hash of
1720          * both fib6_dst and fib6_src.
1721          * However, the src addr used to create the hash
1722          * might not be exactly the passed in saddr which
1723          * is a /128 addr from the flow.
1724          * So we need to use f6i->fib6_src to redo lookup
1725          * if the passed in saddr does not find anything.
1726          * (See the logic in ip6_rt_cache_alloc() on how
1727          * rt->rt6i_src is updated.)
1728          */
1729         if (res->f6i->fib6_src.plen)
1730                 src_key = saddr;
1731 find_ex:
1732 #endif
1733         bucket = fib6_nh_get_excptn_bucket(res->nh, NULL);
1734         rt6_ex = __rt6_find_exception_rcu(&bucket, daddr, src_key);
1735
1736         if (rt6_ex && !rt6_check_expired(rt6_ex->rt6i))
1737                 ret = rt6_ex->rt6i;
1738
1739 #ifdef CONFIG_IPV6_SUBTREES
1740         /* Use fib6_src as src_key and redo lookup */
1741         if (!ret && src_key && src_key != &res->f6i->fib6_src.addr) {
1742                 src_key = &res->f6i->fib6_src.addr;
1743                 goto find_ex;
1744         }
1745 #endif
1746
1747         return ret;
1748 }
1749
1750 /* Remove the passed in cached rt from the hash table that contains it */
1751 static int fib6_nh_remove_exception(const struct fib6_nh *nh, int plen,
1752                                     const struct rt6_info *rt)
1753 {
1754         const struct in6_addr *src_key = NULL;
1755         struct rt6_exception_bucket *bucket;
1756         struct rt6_exception *rt6_ex;
1757         int err;
1758
1759         if (!rcu_access_pointer(nh->rt6i_exception_bucket))
1760                 return -ENOENT;
1761
1762         spin_lock_bh(&rt6_exception_lock);
1763         bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1764
1765 #ifdef CONFIG_IPV6_SUBTREES
1766         /* rt6i_src.plen != 0 indicates 'from' is in subtree
1767          * and exception table is indexed by a hash of
1768          * both rt6i_dst and rt6i_src.
1769          * Otherwise, the exception table is indexed by
1770          * a hash of only rt6i_dst.
1771          */
1772         if (plen)
1773                 src_key = &rt->rt6i_src.addr;
1774 #endif
1775         rt6_ex = __rt6_find_exception_spinlock(&bucket,
1776                                                &rt->rt6i_dst.addr,
1777                                                src_key);
1778         if (rt6_ex) {
1779                 rt6_remove_exception(bucket, rt6_ex);
1780                 err = 0;
1781         } else {
1782                 err = -ENOENT;
1783         }
1784
1785         spin_unlock_bh(&rt6_exception_lock);
1786         return err;
1787 }
1788
1789 static int rt6_remove_exception_rt(struct rt6_info *rt)
1790 {
1791         struct fib6_info *from;
1792
1793         from = rcu_dereference(rt->from);
1794         if (!from || !(rt->rt6i_flags & RTF_CACHE))
1795                 return -EINVAL;
1796
1797         return fib6_nh_remove_exception(from->fib6_nh,
1798                                         from->fib6_src.plen, rt);
1799 }
1800
1801 /* Find rt6_ex which contains the passed in rt cache and
1802  * refresh its stamp
1803  */
1804 static void fib6_nh_update_exception(const struct fib6_nh *nh, int plen,
1805                                      const struct rt6_info *rt)
1806 {
1807         const struct in6_addr *src_key = NULL;
1808         struct rt6_exception_bucket *bucket;
1809         struct rt6_exception *rt6_ex;
1810
1811         bucket = fib6_nh_get_excptn_bucket(nh, NULL);
1812 #ifdef CONFIG_IPV6_SUBTREES
1813         /* rt6i_src.plen != 0 indicates 'from' is in subtree
1814          * and exception table is indexed by a hash of
1815          * both rt6i_dst and rt6i_src.
1816          * Otherwise, the exception table is indexed by
1817          * a hash of only rt6i_dst.
1818          */
1819         if (plen)
1820                 src_key = &rt->rt6i_src.addr;
1821 #endif
1822         rt6_ex = __rt6_find_exception_rcu(&bucket, &rt->rt6i_dst.addr, src_key);
1823         if (rt6_ex)
1824                 rt6_ex->stamp = jiffies;
1825 }
1826
1827 static void rt6_update_exception_stamp_rt(struct rt6_info *rt)
1828 {
1829         struct fib6_info *from;
1830
1831         rcu_read_lock();
1832
1833         from = rcu_dereference(rt->from);
1834         if (!from || !(rt->rt6i_flags & RTF_CACHE))
1835                 goto unlock;
1836
1837         fib6_nh_update_exception(from->fib6_nh, from->fib6_src.plen, rt);
1838 unlock:
1839         rcu_read_unlock();
1840 }
1841
1842 static bool rt6_mtu_change_route_allowed(struct inet6_dev *idev,
1843                                          struct rt6_info *rt, int mtu)
1844 {
1845         /* If the new MTU is lower than the route PMTU, this new MTU will be the
1846          * lowest MTU in the path: always allow updating the route PMTU to
1847          * reflect PMTU decreases.
1848          *
1849          * If the new MTU is higher, and the route PMTU is equal to the local
1850          * MTU, this means the old MTU is the lowest in the path, so allow
1851          * updating it: if other nodes now have lower MTUs, PMTU discovery will
1852          * handle this.
1853          */
1854
1855         if (dst_mtu(&rt->dst) >= mtu)
1856                 return true;
1857
1858         if (dst_mtu(&rt->dst) == idev->cnf.mtu6)
1859                 return true;
1860
1861         return false;
1862 }
1863
1864 static void rt6_exceptions_update_pmtu(struct inet6_dev *idev,
1865                                        const struct fib6_nh *nh, int mtu)
1866 {
1867         struct rt6_exception_bucket *bucket;
1868         struct rt6_exception *rt6_ex;
1869         int i;
1870
1871         bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1872         if (!bucket)
1873                 return;
1874
1875         for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
1876                 hlist_for_each_entry(rt6_ex, &bucket->chain, hlist) {
1877                         struct rt6_info *entry = rt6_ex->rt6i;
1878
1879                         /* For RTF_CACHE with rt6i_pmtu == 0 (i.e. a redirected
1880                          * route), the metrics of its rt->from have already
1881                          * been updated.
1882                          */
1883                         if (dst_metric_raw(&entry->dst, RTAX_MTU) &&
1884                             rt6_mtu_change_route_allowed(idev, entry, mtu))
1885                                 dst_metric_set(&entry->dst, RTAX_MTU, mtu);
1886                 }
1887                 bucket++;
1888         }
1889 }
1890
1891 #define RTF_CACHE_GATEWAY       (RTF_GATEWAY | RTF_CACHE)
1892
1893 static void fib6_nh_exceptions_clean_tohost(const struct fib6_nh *nh,
1894                                             const struct in6_addr *gateway)
1895 {
1896         struct rt6_exception_bucket *bucket;
1897         struct rt6_exception *rt6_ex;
1898         struct hlist_node *tmp;
1899         int i;
1900
1901         if (!rcu_access_pointer(nh->rt6i_exception_bucket))
1902                 return;
1903
1904         spin_lock_bh(&rt6_exception_lock);
1905         bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1906         if (bucket) {
1907                 for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
1908                         hlist_for_each_entry_safe(rt6_ex, tmp,
1909                                                   &bucket->chain, hlist) {
1910                                 struct rt6_info *entry = rt6_ex->rt6i;
1911
1912                                 if ((entry->rt6i_flags & RTF_CACHE_GATEWAY) ==
1913                                     RTF_CACHE_GATEWAY &&
1914                                     ipv6_addr_equal(gateway,
1915                                                     &entry->rt6i_gateway)) {
1916                                         rt6_remove_exception(bucket, rt6_ex);
1917                                 }
1918                         }
1919                         bucket++;
1920                 }
1921         }
1922
1923         spin_unlock_bh(&rt6_exception_lock);
1924 }
1925
1926 static void rt6_age_examine_exception(struct rt6_exception_bucket *bucket,
1927                                       struct rt6_exception *rt6_ex,
1928                                       struct fib6_gc_args *gc_args,
1929                                       unsigned long now)
1930 {
1931         struct rt6_info *rt = rt6_ex->rt6i;
1932
1933         /* we are pruning and obsoleting aged-out and non gateway exceptions
1934          * even if others have still references to them, so that on next
1935          * dst_check() such references can be dropped.
1936          * EXPIRES exceptions - e.g. pmtu-generated ones are pruned when
1937          * expired, independently from their aging, as per RFC 8201 section 4
1938          */
1939         if (!(rt->rt6i_flags & RTF_EXPIRES)) {
1940                 if (time_after_eq(now, rt->dst.lastuse + gc_args->timeout)) {
1941                         RT6_TRACE("aging clone %p\n", rt);
1942                         rt6_remove_exception(bucket, rt6_ex);
1943                         return;
1944                 }
1945         } else if (time_after(jiffies, rt->dst.expires)) {
1946                 RT6_TRACE("purging expired route %p\n", rt);
1947                 rt6_remove_exception(bucket, rt6_ex);
1948                 return;
1949         }
1950
1951         if (rt->rt6i_flags & RTF_GATEWAY) {
1952                 struct neighbour *neigh;
1953                 __u8 neigh_flags = 0;
1954
1955                 neigh = __ipv6_neigh_lookup_noref(rt->dst.dev, &rt->rt6i_gateway);
1956                 if (neigh)
1957                         neigh_flags = neigh->flags;
1958
1959                 if (!(neigh_flags & NTF_ROUTER)) {
1960                         RT6_TRACE("purging route %p via non-router but gateway\n",
1961                                   rt);
1962                         rt6_remove_exception(bucket, rt6_ex);
1963                         return;
1964                 }
1965         }
1966
1967         gc_args->more++;
1968 }
1969
1970 static void fib6_nh_age_exceptions(const struct fib6_nh *nh,
1971                                    struct fib6_gc_args *gc_args,
1972                                    unsigned long now)
1973 {
1974         struct rt6_exception_bucket *bucket;
1975         struct rt6_exception *rt6_ex;
1976         struct hlist_node *tmp;
1977         int i;
1978
1979         if (!rcu_access_pointer(nh->rt6i_exception_bucket))
1980                 return;
1981
1982         rcu_read_lock_bh();
1983         spin_lock(&rt6_exception_lock);
1984         bucket = fib6_nh_get_excptn_bucket(nh, &rt6_exception_lock);
1985         if (bucket) {
1986                 for (i = 0; i < FIB6_EXCEPTION_BUCKET_SIZE; i++) {
1987                         hlist_for_each_entry_safe(rt6_ex, tmp,
1988                                                   &bucket->chain, hlist) {
1989                                 rt6_age_examine_exception(bucket, rt6_ex,
1990                                                           gc_args, now);
1991                         }
1992                         bucket++;
1993                 }
1994         }
1995         spin_unlock(&rt6_exception_lock);
1996         rcu_read_unlock_bh();
1997 }
1998
1999 void rt6_age_exceptions(struct fib6_info *f6i,
2000                         struct fib6_gc_args *gc_args,
2001                         unsigned long now)
2002 {
2003         fib6_nh_age_exceptions(f6i->fib6_nh, gc_args, now);
2004 }
2005
2006 /* must be called with rcu lock held */
2007 int fib6_table_lookup(struct net *net, struct fib6_table *table, int oif,
2008                       struct flowi6 *fl6, struct fib6_result *res, int strict)
2009 {
2010         struct fib6_node *fn, *saved_fn;
2011
2012         fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
2013         saved_fn = fn;
2014
2015         if (fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF)
2016                 oif = 0;
2017
2018 redo_rt6_select:
2019         rt6_select(net, fn, oif, res, strict);
2020         if (res->f6i == net->ipv6.fib6_null_entry) {
2021                 fn = fib6_backtrack(fn, &fl6->saddr);
2022                 if (fn)
2023                         goto redo_rt6_select;
2024                 else if (strict & RT6_LOOKUP_F_REACHABLE) {
2025                         /* also consider unreachable route */
2026                         strict &= ~RT6_LOOKUP_F_REACHABLE;
2027                         fn = saved_fn;
2028                         goto redo_rt6_select;
2029                 }
2030         }
2031
2032         trace_fib6_table_lookup(net, res, table, fl6);
2033
2034         return 0;
2035 }
2036
2037 struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table,
2038                                int oif, struct flowi6 *fl6,
2039                                const struct sk_buff *skb, int flags)
2040 {
2041         struct fib6_result res = {};
2042         struct rt6_info *rt;
2043         int strict = 0;
2044
2045         strict |= flags & RT6_LOOKUP_F_IFACE;
2046         strict |= flags & RT6_LOOKUP_F_IGNORE_LINKSTATE;
2047         if (net->ipv6.devconf_all->forwarding == 0)
2048                 strict |= RT6_LOOKUP_F_REACHABLE;
2049
2050         rcu_read_lock();
2051
2052         fib6_table_lookup(net, table, oif, fl6, &res, strict);
2053         if (res.f6i == net->ipv6.fib6_null_entry) {
2054                 rt = net->ipv6.ip6_null_entry;
2055                 rcu_read_unlock();
2056                 dst_hold(&rt->dst);
2057                 return rt;
2058         }
2059
2060         fib6_select_path(net, &res, fl6, oif, false, skb, strict);
2061
2062         /*Search through exception table */
2063         rt = rt6_find_cached_rt(&res, &fl6->daddr, &fl6->saddr);
2064         if (rt) {
2065                 if (ip6_hold_safe(net, &rt))
2066                         dst_use_noref(&rt->dst, jiffies);
2067
2068                 rcu_read_unlock();
2069                 return rt;
2070         } else if (unlikely((fl6->flowi6_flags & FLOWI_FLAG_KNOWN_NH) &&
2071                             !res.nh->fib_nh_gw_family)) {
2072                 /* Create a RTF_CACHE clone which will not be
2073                  * owned by the fib6 tree.  It is for the special case where
2074                  * the daddr in the skb during the neighbor look-up is different
2075                  * from the fl6->daddr used to look-up route here.
2076                  */
2077                 struct rt6_info *uncached_rt;
2078
2079                 uncached_rt = ip6_rt_cache_alloc(&res, &fl6->daddr, NULL);
2080
2081                 rcu_read_unlock();
2082
2083                 if (uncached_rt) {
2084                         /* Uncached_rt's refcnt is taken during ip6_rt_cache_alloc()
2085                          * No need for another dst_hold()
2086                          */
2087                         rt6_uncached_list_add(uncached_rt);
2088                         atomic_inc(&net->ipv6.rt6_stats->fib_rt_uncache);
2089                 } else {
2090                         uncached_rt = net->ipv6.ip6_null_entry;
2091                         dst_hold(&uncached_rt->dst);
2092                 }
2093
2094                 return uncached_rt;
2095         } else {
2096                 /* Get a percpu copy */
2097
2098                 struct rt6_info *pcpu_rt;
2099
2100                 local_bh_disable();
2101                 pcpu_rt = rt6_get_pcpu_route(&res);
2102
2103                 if (!pcpu_rt)
2104                         pcpu_rt = rt6_make_pcpu_route(net, &res);
2105
2106                 local_bh_enable();
2107                 rcu_read_unlock();
2108
2109                 return pcpu_rt;
2110         }
2111 }
2112 EXPORT_SYMBOL_GPL(ip6_pol_route);
2113
2114 static struct rt6_info *ip6_pol_route_input(struct net *net,
2115                                             struct fib6_table *table,
2116                                             struct flowi6 *fl6,
2117                                             const struct sk_buff *skb,
2118                                             int flags)
2119 {
2120         return ip6_pol_route(net, table, fl6->flowi6_iif, fl6, skb, flags);
2121 }
2122
2123 struct dst_entry *ip6_route_input_lookup(struct net *net,
2124                                          struct net_device *dev,
2125                                          struct flowi6 *fl6,
2126                                          const struct sk_buff *skb,
2127                                          int flags)
2128 {
2129         if (rt6_need_strict(&fl6->daddr) && dev->type != ARPHRD_PIMREG)
2130                 flags |= RT6_LOOKUP_F_IFACE;
2131
2132         return fib6_rule_lookup(net, fl6, skb, flags, ip6_pol_route_input);
2133 }
2134 EXPORT_SYMBOL_GPL(ip6_route_input_lookup);
2135
2136 static void ip6_multipath_l3_keys(const struct sk_buff *skb,
2137                                   struct flow_keys *keys,
2138                                   struct flow_keys *flkeys)
2139 {
2140         const struct ipv6hdr *outer_iph = ipv6_hdr(skb);
2141         const struct ipv6hdr *key_iph = outer_iph;
2142         struct flow_keys *_flkeys = flkeys;
2143         const struct ipv6hdr *inner_iph;
2144         const struct icmp6hdr *icmph;
2145         struct ipv6hdr _inner_iph;
2146         struct icmp6hdr _icmph;
2147
2148         if (likely(outer_iph->nexthdr != IPPROTO_ICMPV6))
2149                 goto out;
2150
2151         icmph = skb_header_pointer(skb, skb_transport_offset(skb),
2152                                    sizeof(_icmph), &_icmph);
2153         if (!icmph)
2154                 goto out;
2155
2156         if (icmph->icmp6_type != ICMPV6_DEST_UNREACH &&
2157             icmph->icmp6_type != ICMPV6_PKT_TOOBIG &&
2158             icmph->icmp6_type != ICMPV6_TIME_EXCEED &&
2159             icmph->icmp6_type != ICMPV6_PARAMPROB)
2160                 goto out;
2161
2162         inner_iph = skb_header_pointer(skb,
2163                                        skb_transport_offset(skb) + sizeof(*icmph),
2164                                        sizeof(_inner_iph), &_inner_iph);
2165         if (!inner_iph)
2166                 goto out;
2167
2168         key_iph = inner_iph;
2169         _flkeys = NULL;
2170 out:
2171         if (_flkeys) {
2172                 keys->addrs.v6addrs.src = _flkeys->addrs.v6addrs.src;
2173                 keys->addrs.v6addrs.dst = _flkeys->addrs.v6addrs.dst;
2174                 keys->tags.flow_label = _flkeys->tags.flow_label;
2175                 keys->basic.ip_proto = _flkeys->basic.ip_proto;
2176         } else {
2177                 keys->addrs.v6addrs.src = key_iph->saddr;
2178                 keys->addrs.v6addrs.dst = key_iph->daddr;
2179                 keys->tags.flow_label = ip6_flowlabel(key_iph);
2180                 keys->basic.ip_proto = key_iph->nexthdr;
2181         }
2182 }
2183
2184 /* if skb is set it will be used and fl6 can be NULL */
2185 u32 rt6_multipath_hash(const struct net *net, const struct flowi6 *fl6,
2186                        const struct sk_buff *skb, struct flow_keys *flkeys)
2187 {
2188         struct flow_keys hash_keys;
2189         u32 mhash;
2190
2191         switch (ip6_multipath_hash_policy(net)) {
2192         case 0:
2193                 memset(&hash_keys, 0, sizeof(hash_keys));
2194                 hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2195                 if (skb) {
2196                         ip6_multipath_l3_keys(skb, &hash_keys, flkeys);
2197                 } else {
2198                         hash_keys.addrs.v6addrs.src = fl6->saddr;
2199                         hash_keys.addrs.v6addrs.dst = fl6->daddr;
2200                         hash_keys.tags.flow_label = (__force u32)flowi6_get_flowlabel(fl6);
2201                         hash_keys.basic.ip_proto = fl6->flowi6_proto;
2202                 }
2203                 break;
2204         case 1:
2205                 if (skb) {
2206                         unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP;
2207                         struct flow_keys keys;
2208
2209                         /* short-circuit if we already have L4 hash present */
2210                         if (skb->l4_hash)
2211                                 return skb_get_hash_raw(skb) >> 1;
2212
2213                         memset(&hash_keys, 0, sizeof(hash_keys));
2214
2215                         if (!flkeys) {
2216                                 skb_flow_dissect_flow_keys(skb, &keys, flag);
2217                                 flkeys = &keys;
2218                         }
2219                         hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2220                         hash_keys.addrs.v6addrs.src = flkeys->addrs.v6addrs.src;
2221                         hash_keys.addrs.v6addrs.dst = flkeys->addrs.v6addrs.dst;
2222                         hash_keys.ports.src = flkeys->ports.src;
2223                         hash_keys.ports.dst = flkeys->ports.dst;
2224                         hash_keys.basic.ip_proto = flkeys->basic.ip_proto;
2225                 } else {
2226                         memset(&hash_keys, 0, sizeof(hash_keys));
2227                         hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
2228                         hash_keys.addrs.v6addrs.src = fl6->saddr;
2229                         hash_keys.addrs.v6addrs.dst = fl6->daddr;
2230                         hash_keys.ports.src = fl6->fl6_sport;
2231                         hash_keys.ports.dst = fl6->fl6_dport;
2232                         hash_keys.basic.ip_proto = fl6->flowi6_proto;
2233                 }
2234                 break;
2235         }
2236         mhash = flow_hash_from_keys(&hash_keys);
2237
2238         return mhash >> 1;
2239 }
2240
2241 void ip6_route_input(struct sk_buff *skb)
2242 {
2243         const struct ipv6hdr *iph = ipv6_hdr(skb);
2244         struct net *net = dev_net(skb->dev);
2245         int flags = RT6_LOOKUP_F_HAS_SADDR;
2246         struct ip_tunnel_info *tun_info;
2247         struct flowi6 fl6 = {
2248                 .flowi6_iif = skb->dev->ifindex,
2249                 .daddr = iph->daddr,
2250                 .saddr = iph->saddr,
2251                 .flowlabel = ip6_flowinfo(iph),
2252                 .flowi6_mark = skb->mark,
2253                 .flowi6_proto = iph->nexthdr,
2254         };
2255         struct flow_keys *flkeys = NULL, _flkeys;
2256
2257         tun_info = skb_tunnel_info(skb);
2258         if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX))
2259                 fl6.flowi6_tun_key.tun_id = tun_info->key.tun_id;
2260
2261         if (fib6_rules_early_flow_dissect(net, skb, &fl6, &_flkeys))
2262                 flkeys = &_flkeys;
2263
2264         if (unlikely(fl6.flowi6_proto == IPPROTO_ICMPV6))
2265                 fl6.mp_hash = rt6_multipath_hash(net, &fl6, skb, flkeys);
2266         skb_dst_drop(skb);
2267         skb_dst_set(skb,
2268                     ip6_route_input_lookup(net, skb->dev, &fl6, skb, flags));
2269 }
2270
2271 static struct rt6_info *ip6_pol_route_output(struct net *net,
2272                                              struct fib6_table *table,
2273                                              struct flowi6 *fl6,
2274                                              const struct sk_buff *skb,
2275                                              int flags)
2276 {
2277         return ip6_pol_route(net, table, fl6->flowi6_oif, fl6, skb, flags);
2278 }
2279
2280 struct dst_entry *ip6_route_output_flags(struct net *net, const struct sock *sk,
2281                                          struct flowi6 *fl6, int flags)
2282 {
2283         bool any_src;
2284
2285         if (ipv6_addr_type(&fl6->daddr) &
2286             (IPV6_ADDR_MULTICAST | IPV6_ADDR_LINKLOCAL)) {
2287                 struct dst_entry *dst;
2288
2289                 dst = l3mdev_link_scope_lookup(net, fl6);
2290                 if (dst)
2291                         return dst;
2292         }
2293
2294         fl6->flowi6_iif = LOOPBACK_IFINDEX;
2295
2296         any_src = ipv6_addr_any(&fl6->saddr);
2297         if ((sk && sk->sk_bound_dev_if) || rt6_need_strict(&fl6->daddr) ||
2298             (fl6->flowi6_oif && any_src))
2299                 flags |= RT6_LOOKUP_F_IFACE;
2300
2301         if (!any_src)
2302                 flags |= RT6_LOOKUP_F_HAS_SADDR;
2303         else if (sk)
2304                 flags |= rt6_srcprefs2flags(inet6_sk(sk)->srcprefs);
2305
2306         return fib6_rule_lookup(net, fl6, NULL, flags, ip6_pol_route_output);
2307 }
2308 EXPORT_SYMBOL_GPL(ip6_route_output_flags);
2309
2310 struct dst_entry *ip6_blackhole_route(struct net *net, struct dst_entry *dst_orig)
2311 {
2312         struct rt6_info *rt, *ort = (struct rt6_info *) dst_orig;
2313         struct net_device *loopback_dev = net->loopback_dev;
2314         struct dst_entry *new = NULL;
2315
2316         rt = dst_alloc(&ip6_dst_blackhole_ops, loopback_dev, 1,
2317                        DST_OBSOLETE_DEAD, 0);
2318         if (rt) {
2319                 rt6_info_init(rt);
2320                 atomic_inc(&net->ipv6.rt6_stats->fib_rt_alloc);
2321
2322                 new = &rt->dst;
2323                 new->__use = 1;
2324                 new->input = dst_discard;
2325                 new->output = dst_discard_out;
2326
2327                 dst_copy_metrics(new, &ort->dst);
2328
2329                 rt->rt6i_idev = in6_dev_get(loopback_dev);
2330                 rt->rt6i_gateway = ort->rt6i_gateway;
2331                 rt->rt6i_flags = ort->rt6i_flags & ~RTF_PCPU;
2332
2333                 memcpy(&rt->rt6i_dst, &ort->rt6i_dst, sizeof(struct rt6key));
2334 #ifdef CONFIG_IPV6_SUBTREES
2335                 memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
2336 #endif
2337         }
2338
2339         dst_release(dst_orig);
2340         return new ? new : ERR_PTR(-ENOMEM);
2341 }
2342
2343 /*
2344  *      Destination cache support functions
2345  */
2346
2347 static bool fib6_check(struct fib6_info *f6i, u32 cookie)
2348 {
2349         u32 rt_cookie = 0;
2350
2351         if (!fib6_get_cookie_safe(f6i, &rt_cookie) || rt_cookie != cookie)
2352                 return false;
2353
2354         if (fib6_check_expired(f6i))
2355                 return false;
2356
2357         return true;
2358 }
2359
2360 static struct dst_entry *rt6_check(struct rt6_info *rt,
2361                                    struct fib6_info *from,
2362                                    u32 cookie)
2363 {
2364         u32 rt_cookie = 0;
2365
2366         if ((from && !fib6_get_cookie_safe(from, &rt_cookie)) ||
2367             rt_cookie != cookie)
2368                 return NULL;
2369
2370         if (rt6_check_expired(rt))
2371                 return NULL;
2372
2373         return &rt->dst;
2374 }
2375
2376 static struct dst_entry *rt6_dst_from_check(struct rt6_info *rt,
2377                                             struct fib6_info *from,
2378                                             u32 cookie)
2379 {
2380         if (!__rt6_check_expired(rt) &&
2381             rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK &&
2382             fib6_check(from, cookie))
2383                 return &rt->dst;
2384         else
2385                 return NULL;
2386 }
2387
2388 static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie)
2389 {
2390         struct dst_entry *dst_ret;
2391         struct fib6_info *from;
2392         struct rt6_info *rt;
2393
2394         rt = container_of(dst, struct rt6_info, dst);
2395
2396         rcu_read_lock();
2397
2398         /* All IPV6 dsts are created with ->obsolete set to the value
2399          * DST_OBSOLETE_FORCE_CHK which forces validation calls down
2400          * into this function always.
2401          */
2402
2403         from = rcu_dereference(rt->from);
2404
2405         if (from && (rt->rt6i_flags & RTF_PCPU ||
2406             unlikely(!list_empty(&rt->rt6i_uncached))))
2407                 dst_ret = rt6_dst_from_check(rt, from, cookie);
2408         else
2409                 dst_ret = rt6_check(rt, from, cookie);
2410
2411         rcu_read_unlock();
2412
2413         return dst_ret;
2414 }
2415
2416 static struct dst_entry *ip6_negative_advice(struct dst_entry *dst)
2417 {
2418         struct rt6_info *rt = (struct rt6_info *) dst;
2419
2420         if (rt) {
2421                 if (rt->rt6i_flags & RTF_CACHE) {
2422                         rcu_read_lock();
2423                         if (rt6_check_expired(rt)) {
2424                                 rt6_remove_exception_rt(rt);
2425                                 dst = NULL;
2426                         }
2427                         rcu_read_unlock();
2428                 } else {
2429                         dst_release(dst);
2430                         dst = NULL;
2431                 }
2432         }
2433         return dst;
2434 }
2435
2436 static void ip6_link_failure(struct sk_buff *skb)
2437 {
2438         struct rt6_info *rt;
2439
2440         icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0);
2441
2442         rt = (struct rt6_info *) skb_dst(skb);
2443         if (rt) {
2444                 rcu_read_lock();
2445                 if (rt->rt6i_flags & RTF_CACHE) {
2446                         rt6_remove_exception_rt(rt);
2447                 } else {
2448                         struct fib6_info *from;
2449                         struct fib6_node *fn;
2450
2451                         from = rcu_dereference(rt->from);
2452                         if (from) {
2453                                 fn = rcu_dereference(from->fib6_node);
2454                                 if (fn && (rt->rt6i_flags & RTF_DEFAULT))
2455                                         fn->fn_sernum = -1;
2456                         }
2457                 }
2458                 rcu_read_unlock();
2459         }
2460 }
2461
2462 static void rt6_update_expires(struct rt6_info *rt0, int timeout)
2463 {
2464         if (!(rt0->rt6i_flags & RTF_EXPIRES)) {
2465                 struct fib6_info *from;
2466
2467                 rcu_read_lock();
2468                 from = rcu_dereference(rt0->from);
2469                 if (from)
2470                         rt0->dst.expires = from->expires;
2471                 rcu_read_unlock();
2472         }
2473
2474         dst_set_expires(&rt0->dst, timeout);
2475         rt0->rt6i_flags |= RTF_EXPIRES;
2476 }
2477
2478 static void rt6_do_update_pmtu(struct rt6_info *rt, u32 mtu)
2479 {
2480         struct net *net = dev_net(rt->dst.dev);
2481
2482         dst_metric_set(&rt->dst, RTAX_MTU, mtu);
2483         rt->rt6i_flags |= RTF_MODIFIED;
2484         rt6_update_expires(rt, net->ipv6.sysctl.ip6_rt_mtu_expires);
2485 }
2486
2487 static bool rt6_cache_allowed_for_pmtu(const struct rt6_info *rt)
2488 {
2489         return !(rt->rt6i_flags & RTF_CACHE) &&
2490                 (rt->rt6i_flags & RTF_PCPU || rcu_access_pointer(rt->from));
2491 }
2492
2493 static void __ip6_rt_update_pmtu(struct dst_entry *dst, const struct sock *sk,
2494                                  const struct ipv6hdr *iph, u32 mtu)
2495 {
2496         const struct in6_addr *daddr, *saddr;
2497         struct rt6_info *rt6 = (struct rt6_info *)dst;
2498
2499         if (dst_metric_locked(dst, RTAX_MTU))
2500                 return;
2501
2502         if (iph) {
2503                 daddr = &iph->daddr;
2504                 saddr = &iph->saddr;
2505         } else if (sk) {
2506                 daddr = &sk->sk_v6_daddr;
2507                 saddr = &inet6_sk(sk)->saddr;
2508         } else {
2509                 daddr = NULL;
2510                 saddr = NULL;
2511         }
2512         dst_confirm_neigh(dst, daddr);
2513         mtu = max_t(u32, mtu, IPV6_MIN_MTU);
2514         if (mtu >= dst_mtu(dst))
2515                 return;
2516
2517         if (!rt6_cache_allowed_for_pmtu(rt6)) {
2518                 rt6_do_update_pmtu(rt6, mtu);
2519                 /* update rt6_ex->stamp for cache */
2520                 if (rt6->rt6i_flags & RTF_CACHE)
2521                         rt6_update_exception_stamp_rt(rt6);
2522         } else if (daddr) {
2523                 struct fib6_result res = {};
2524                 struct rt6_info *nrt6;
2525
2526                 rcu_read_lock();
2527                 res.f6i = rcu_dereference(rt6->from);
2528                 if (!res.f6i) {
2529                         rcu_read_unlock();
2530                         return;
2531                 }
2532                 res.nh = res.f6i->fib6_nh;
2533                 res.fib6_flags = res.f6i->fib6_flags;
2534                 res.fib6_type = res.f6i->fib6_type;
2535
2536                 nrt6 = ip6_rt_cache_alloc(&res, daddr, saddr);
2537                 if (nrt6) {
2538                         rt6_do_update_pmtu(nrt6, mtu);
2539                         if (rt6_insert_exception(nrt6, &res))
2540                                 dst_release_immediate(&nrt6->dst);
2541                 }
2542                 rcu_read_unlock();
2543         }
2544 }
2545
2546 static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
2547                                struct sk_buff *skb, u32 mtu)
2548 {
2549         __ip6_rt_update_pmtu(dst, sk, skb ? ipv6_hdr(skb) : NULL, mtu);
2550 }
2551
2552 void ip6_update_pmtu(struct sk_buff *skb, struct net *net, __be32 mtu,
2553                      int oif, u32 mark, kuid_t uid)
2554 {
2555         const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
2556         struct dst_entry *dst;
2557         struct flowi6 fl6 = {
2558                 .flowi6_oif = oif,
2559                 .flowi6_mark = mark ? mark : IP6_REPLY_MARK(net, skb->mark),
2560                 .daddr = iph->daddr,
2561                 .saddr = iph->saddr,
2562                 .flowlabel = ip6_flowinfo(iph),
2563                 .flowi6_uid = uid,
2564         };
2565
2566         dst = ip6_route_output(net, NULL, &fl6);
2567         if (!dst->error)
2568                 __ip6_rt_update_pmtu(dst, NULL, iph, ntohl(mtu));
2569         dst_release(dst);
2570 }
2571 EXPORT_SYMBOL_GPL(ip6_update_pmtu);
2572
2573 void ip6_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, __be32 mtu)
2574 {
2575         int oif = sk->sk_bound_dev_if;
2576         struct dst_entry *dst;
2577
2578         if (!oif && skb->dev)
2579                 oif = l3mdev_master_ifindex(skb->dev);
2580
2581         ip6_update_pmtu(skb, sock_net(sk), mtu, oif, sk->sk_mark, sk->sk_uid);
2582
2583         dst = __sk_dst_get(sk);
2584         if (!dst || !dst->obsolete ||
2585             dst->ops->check(dst, inet6_sk(sk)->dst_cookie))
2586                 return;
2587
2588         bh_lock_sock(sk);
2589         if (!sock_owned_by_user(sk) && !ipv6_addr_v4mapped(&sk->sk_v6_daddr))
2590                 ip6_datagram_dst_update(sk, false);
2591         bh_unlock_sock(sk);
2592 }
2593 EXPORT_SYMBOL_GPL(ip6_sk_update_pmtu);
2594
2595 void ip6_sk_dst_store_flow(struct sock *sk, struct dst_entry *dst,
2596                            const struct flowi6 *fl6)
2597 {
2598 #ifdef CONFIG_IPV6_SUBTREES
2599         struct ipv6_pinfo *np = inet6_sk(sk);
2600 #endif
2601
2602         ip6_dst_store(sk, dst,
2603                       ipv6_addr_equal(&fl6->daddr, &sk->sk_v6_daddr) ?
2604                       &sk->sk_v6_daddr : NULL,
2605 #ifdef CONFIG_IPV6_SUBTREES
2606                       ipv6_addr_equal(&fl6->saddr, &np->saddr) ?
2607                       &np->saddr :
2608 #endif
2609                       NULL);
2610 }
2611
2612 static bool ip6_redirect_nh_match(const struct fib6_result *res,
2613                                   struct flowi6 *fl6,
2614                                   const struct in6_addr *gw,
2615                                   struct rt6_info **ret)
2616 {
2617         const struct fib6_nh *nh = res->nh;
2618
2619         if (nh->fib_nh_flags & RTNH_F_DEAD || !nh->fib_nh_gw_family ||
2620             fl6->flowi6_oif != nh->fib_nh_dev->ifindex)
2621                 return false;
2622
2623         /* rt_cache's gateway might be different from its 'parent'
2624          * in the case of an ip redirect.
2625          * So we keep searching in the exception table if the gateway
2626          * is different.
2627          */
2628         if (!ipv6_addr_equal(gw, &nh->fib_nh_gw6)) {
2629                 struct rt6_info *rt_cache;
2630
2631                 rt_cache = rt6_find_cached_rt(res, &fl6->daddr, &fl6->saddr);
2632                 if (rt_cache &&
2633                     ipv6_addr_equal(gw, &rt_cache->rt6i_gateway)) {
2634                         *ret = rt_cache;
2635                         return true;
2636                 }
2637                 return false;
2638         }
2639         return true;
2640 }
2641
2642 /* Handle redirects */
2643 struct ip6rd_flowi {
2644         struct flowi6 fl6;
2645         struct in6_addr gateway;
2646 };
2647
2648 static struct rt6_info *__ip6_route_redirect(struct net *net,
2649                                              struct fib6_table *table,
2650                                              struct flowi6 *fl6,
2651                                              const struct sk_buff *skb,
2652                                              int flags)
2653 {
2654         struct ip6rd_flowi *rdfl = (struct ip6rd_flowi *)fl6;
2655         struct rt6_info *ret = NULL;
2656         struct fib6_result res = {};
2657         struct fib6_info *rt;
2658         struct fib6_node *fn;
2659
2660         /* l3mdev_update_flow overrides oif if the device is enslaved; in
2661          * this case we must match on the real ingress device, so reset it
2662          */
2663         if (fl6->flowi6_flags & FLOWI_FLAG_SKIP_NH_OIF)
2664                 fl6->flowi6_oif = skb->dev->ifindex;
2665
2666         /* Get the "current" route for this destination and
2667          * check if the redirect has come from appropriate router.
2668          *
2669          * RFC 4861 specifies that redirects should only be
2670          * accepted if they come from the nexthop to the target.
2671          * Due to the way the routes are chosen, this notion
2672          * is a bit fuzzy and one might need to check all possible
2673          * routes.
2674          */
2675
2676         rcu_read_lock();
2677         fn = fib6_node_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
2678 restart:
2679         for_each_fib6_node_rt_rcu(fn) {
2680                 res.f6i = rt;
2681                 res.nh = rt->fib6_nh;
2682
2683                 if (fib6_check_expired(rt))
2684                         continue;
2685                 if (rt->fib6_flags & RTF_REJECT)
2686                         break;
2687                 if (ip6_redirect_nh_match(&res, fl6, &rdfl->gateway, &ret))
2688                         goto out;
2689         }
2690
2691         if (!rt)
2692                 rt = net->ipv6.fib6_null_entry;
2693         else if (rt->fib6_flags & RTF_REJECT) {
2694                 ret = net->ipv6.ip6_null_entry;
2695                 goto out;
2696         }
2697
2698         if (rt == net->ipv6.fib6_null_entry) {
2699                 fn = fib6_backtrack(fn, &fl6->saddr);
2700                 if (fn)
2701                         goto restart;
2702         }
2703
2704         res.f6i = rt;
2705         res.nh = rt->fib6_nh;
2706 out:
2707         if (ret) {
2708                 ip6_hold_safe(net, &ret);
2709         } else {
2710                 res.fib6_flags = res.f6i->fib6_flags;
2711                 res.fib6_type = res.f6i->fib6_type;
2712                 ret = ip6_create_rt_rcu(&res);
2713         }
2714
2715         rcu_read_unlock();
2716
2717         trace_fib6_table_lookup(net, &res, table, fl6);
2718         return ret;
2719 };
2720
2721 static struct dst_entry *ip6_route_redirect(struct net *net,
2722                                             const struct flowi6 *fl6,
2723                                             const struct sk_buff *skb,
2724                                             const struct in6_addr *gateway)
2725 {
2726         int flags = RT6_LOOKUP_F_HAS_SADDR;
2727         struct ip6rd_flowi rdfl;
2728
2729         rdfl.fl6 = *fl6;
2730         rdfl.gateway = *gateway;
2731
2732         return fib6_rule_lookup(net, &rdfl.fl6, skb,
2733                                 flags, __ip6_route_redirect);
2734 }
2735
2736 void ip6_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark,
2737                   kuid_t uid)
2738 {
2739         const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
2740         struct dst_entry *dst;
2741         struct flowi6 fl6 = {
2742                 .flowi6_iif = LOOPBACK_IFINDEX,
2743                 .flowi6_oif = oif,
2744                 .flowi6_mark = mark,
2745                 .daddr = iph->daddr,
2746                 .saddr = iph->saddr,
2747                 .flowlabel = ip6_flowinfo(iph),
2748                 .flowi6_uid = uid,
2749         };
2750
2751         dst = ip6_route_redirect(net, &fl6, skb, &ipv6_hdr(skb)->saddr);
2752         rt6_do_redirect(dst, NULL, skb);
2753         dst_release(dst);
2754 }
2755 EXPORT_SYMBOL_GPL(ip6_redirect);
2756
2757 void ip6_redirect_no_header(struct sk_buff *skb, struct net *net, int oif)
2758 {
2759         const struct ipv6hdr *iph = ipv6_hdr(skb);
2760         const struct rd_msg *msg = (struct rd_msg *)icmp6_hdr(skb);
2761         struct dst_entry *dst;
2762         struct flowi6 fl6 = {
2763                 .flowi6_iif = LOOPBACK_IFINDEX,
2764                 .flowi6_oif = oif,
2765                 .daddr = msg->dest,
2766                 .saddr = iph->daddr,
2767                 .flowi6_uid = sock_net_uid(net, NULL),
2768         };
2769
2770         dst = ip6_route_redirect(net, &fl6, skb, &iph->saddr);
2771         rt6_do_redirect(dst, NULL, skb);
2772         dst_release(dst);
2773 }
2774
2775 void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk)
2776 {
2777         ip6_redirect(skb, sock_net(sk), sk->sk_bound_dev_if, sk->sk_mark,
2778                      sk->sk_uid);
2779 }
2780 EXPORT_SYMBOL_GPL(ip6_sk_redirect);
2781
2782 static unsigned int ip6_default_advmss(const struct dst_entry *dst)
2783 {
2784         struct net_device *dev = dst->dev;
2785         unsigned int mtu = dst_mtu(dst);
2786         struct net *net = dev_net(dev);
2787
2788         mtu -= sizeof(struct ipv6hdr) + sizeof(struct tcphdr);
2789
2790         if (mtu < net->ipv6.sysctl.ip6_rt_min_advmss)
2791                 mtu = net->ipv6.sysctl.ip6_rt_min_advmss;
2792
2793         /*
2794          * Maximal non-jumbo IPv6 payload is IPV6_MAXPLEN and
2795          * corresponding MSS is IPV6_MAXPLEN - tcp_header_size.
2796          * IPV6_MAXPLEN is also valid and means: "any MSS,
2797          * rely only on pmtu discovery"
2798          */
2799         if (mtu > IPV6_MAXPLEN - sizeof(struct tcphdr))
2800                 mtu = IPV6_MAXPLEN;
2801         return mtu;
2802 }
2803
2804 static unsigned int ip6_mtu(const struct dst_entry *dst)
2805 {
2806         struct inet6_dev *idev;
2807         unsigned int mtu;
2808
2809         mtu = dst_metric_raw(dst, RTAX_MTU);
2810         if (mtu)
2811                 goto out;
2812
2813         mtu = IPV6_MIN_MTU;
2814
2815         rcu_read_lock();
2816         idev = __in6_dev_get(dst->dev);
2817         if (idev)
2818                 mtu = idev->cnf.mtu6;
2819         rcu_read_unlock();
2820
2821 out:
2822         mtu = min_t(unsigned int, mtu, IP6_MAX_MTU);
2823
2824         return mtu - lwtunnel_headroom(dst->lwtstate, mtu);
2825 }
2826
2827 /* MTU selection:
2828  * 1. mtu on route is locked - use it
2829  * 2. mtu from nexthop exception
2830  * 3. mtu from egress device
2831  *
2832  * based on ip6_dst_mtu_forward and exception logic of
2833  * rt6_find_cached_rt; called with rcu_read_lock
2834  */
2835 u32 ip6_mtu_from_fib6(const struct fib6_result *res,
2836                       const struct in6_addr *daddr,
2837                       const struct in6_addr *saddr)
2838 {
2839         const struct fib6_nh *nh = res->nh;
2840         struct fib6_info *f6i = res->f6i;
2841         struct inet6_dev *idev;
2842         struct rt6_info *rt;
2843         u32 mtu = 0;
2844
2845         if (unlikely(fib6_metric_locked(f6i, RTAX_MTU))) {
2846                 mtu = f6i->fib6_pmtu;
2847                 if (mtu)
2848                         goto out;
2849         }
2850
2851         rt = rt6_find_cached_rt(res, daddr, saddr);
2852         if (unlikely(rt)) {
2853                 mtu = dst_metric_raw(&rt->dst, RTAX_MTU);
2854         } else {
2855                 struct net_device *dev = nh->fib_nh_dev;
2856
2857                 mtu = IPV6_MIN_MTU;
2858                 idev = __in6_dev_get(dev);
2859                 if (idev && idev->cnf.mtu6 > mtu)
2860                         mtu = idev->cnf.mtu6;
2861         }
2862
2863         mtu = min_t(unsigned int, mtu, IP6_MAX_MTU);
2864 out:
2865         return mtu - lwtunnel_headroom(nh->fib_nh_lws, mtu);
2866 }
2867
2868 struct dst_entry *icmp6_dst_alloc(struct net_device *dev,
2869                                   struct flowi6 *fl6)
2870 {
2871         struct dst_entry *dst;
2872         struct rt6_info *rt;
2873         struct inet6_dev *idev = in6_dev_get(dev);
2874         struct net *net = dev_net(dev);
2875
2876         if (unlikely(!idev))
2877                 return ERR_PTR(-ENODEV);
2878
2879         rt = ip6_dst_alloc(net, dev, 0);
2880         if (unlikely(!rt)) {
2881                 in6_dev_put(idev);
2882                 dst = ERR_PTR(-ENOMEM);
2883                 goto out;
2884         }
2885
2886         rt->dst.flags |= DST_HOST;
2887         rt->dst.input = ip6_input;
2888         rt->dst.output  = ip6_output;
2889         rt->rt6i_gateway  = fl6->daddr;
2890         rt->rt6i_dst.addr = fl6->daddr;
2891         rt->rt6i_dst.plen = 128;
2892         rt->rt6i_idev     = idev;
2893         dst_metric_set(&rt->dst, RTAX_HOPLIMIT, 0);
2894
2895         /* Add this dst into uncached_list so that rt6_disable_ip() can
2896          * do proper release of the net_device
2897          */
2898         rt6_uncached_list_add(rt);
2899         atomic_inc(&net->ipv6.rt6_stats->fib_rt_uncache);
2900
2901         dst = xfrm_lookup(net, &rt->dst, flowi6_to_flowi(fl6), NULL, 0);
2902
2903 out:
2904         return dst;
2905 }
2906
2907 static int ip6_dst_gc(struct dst_ops *ops)
2908 {
2909         struct net *net = container_of(ops, struct net, ipv6.ip6_dst_ops);
2910         int rt_min_interval = net->ipv6.sysctl.ip6_rt_gc_min_interval;
2911         int rt_max_size = net->ipv6.sysctl.ip6_rt_max_size;
2912         int rt_elasticity = net->ipv6.sysctl.ip6_rt_gc_elasticity;
2913         int rt_gc_timeout = net->ipv6.sysctl.ip6_rt_gc_timeout;
2914         unsigned long rt_last_gc = net->ipv6.ip6_rt_last_gc;
2915         int entries;
2916
2917         entries = dst_entries_get_fast(ops);
2918         if (time_after(rt_last_gc + rt_min_interval, jiffies) &&
2919             entries <= rt_max_size)
2920                 goto out;
2921
2922         net->ipv6.ip6_rt_gc_expire++;
2923         fib6_run_gc(net->ipv6.ip6_rt_gc_expire, net, true);
2924         entries = dst_entries_get_slow(ops);
2925         if (entries < ops->gc_thresh)
2926                 net->ipv6.ip6_rt_gc_expire = rt_gc_timeout>>1;
2927 out:
2928         net->ipv6.ip6_rt_gc_expire -= net->ipv6.ip6_rt_gc_expire>>rt_elasticity;
2929         return entries > rt_max_size;
2930 }
2931
2932 static struct rt6_info *ip6_nh_lookup_table(struct net *net,
2933                                             struct fib6_config *cfg,
2934                                             const struct in6_addr *gw_addr,
2935                                             u32 tbid, int flags)
2936 {
2937         struct flowi6 fl6 = {
2938                 .flowi6_oif = cfg->fc_ifindex,
2939                 .daddr = *gw_addr,
2940                 .saddr = cfg->fc_prefsrc,
2941         };
2942         struct fib6_table *table;
2943         struct rt6_info *rt;
2944
2945         table = fib6_get_table(net, tbid);
2946         if (!table)
2947                 return NULL;
2948
2949         if (!ipv6_addr_any(&cfg->fc_prefsrc))
2950                 flags |= RT6_LOOKUP_F_HAS_SADDR;
2951
2952         flags |= RT6_LOOKUP_F_IGNORE_LINKSTATE;
2953         rt = ip6_pol_route(net, table, cfg->fc_ifindex, &fl6, NULL, flags);
2954
2955         /* if table lookup failed, fall back to full lookup */
2956         if (rt == net->ipv6.ip6_null_entry) {
2957                 ip6_rt_put(rt);
2958                 rt = NULL;
2959         }
2960
2961         return rt;
2962 }
2963
2964 static int ip6_route_check_nh_onlink(struct net *net,
2965                                      struct fib6_config *cfg,
2966                                      const struct net_device *dev,
2967                                      struct netlink_ext_ack *extack)
2968 {
2969         u32 tbid = l3mdev_fib_table(dev) ? : RT_TABLE_MAIN;
2970         const struct in6_addr *gw_addr = &cfg->fc_gateway;
2971         u32 flags = RTF_LOCAL | RTF_ANYCAST | RTF_REJECT;
2972         struct fib6_info *from;
2973         struct rt6_info *grt;
2974         int err;
2975
2976         err = 0;
2977         grt = ip6_nh_lookup_table(net, cfg, gw_addr, tbid, 0);
2978         if (grt) {
2979                 rcu_read_lock();
2980                 from = rcu_dereference(grt->from);
2981                 if (!grt->dst.error &&
2982                     /* ignore match if it is the default route */
2983                     from && !ipv6_addr_any(&from->fib6_dst.addr) &&
2984                     (grt->rt6i_flags & flags || dev != grt->dst.dev)) {
2985                         NL_SET_ERR_MSG(extack,
2986                                        "Nexthop has invalid gateway or device mismatch");
2987                         err = -EINVAL;
2988                 }
2989                 rcu_read_unlock();
2990
2991                 ip6_rt_put(grt);
2992         }
2993
2994         return err;
2995 }
2996
2997 static int ip6_route_check_nh(struct net *net,
2998                               struct fib6_config *cfg,
2999                               struct net_device **_dev,
3000                               struct inet6_dev **idev)
3001 {
3002         const struct in6_addr *gw_addr = &cfg->fc_gateway;
3003         struct net_device *dev = _dev ? *_dev : NULL;
3004         struct rt6_info *grt = NULL;
3005         int err = -EHOSTUNREACH;
3006
3007         if (cfg->fc_table) {
3008                 int flags = RT6_LOOKUP_F_IFACE;
3009
3010                 grt = ip6_nh_lookup_table(net, cfg, gw_addr,
3011                                           cfg->fc_table, flags);
3012                 if (grt) {
3013                         if (grt->rt6i_flags & RTF_GATEWAY ||
3014                             (dev && dev != grt->dst.dev)) {
3015                                 ip6_rt_put(grt);
3016                                 grt = NULL;
3017                         }
3018                 }
3019         }
3020
3021         if (!grt)
3022                 grt = rt6_lookup(net, gw_addr, NULL, cfg->fc_ifindex, NULL, 1);
3023
3024         if (!grt)
3025                 goto out;
3026
3027         if (dev) {
3028                 if (dev != grt->dst.dev) {
3029                         ip6_rt_put(grt);
3030                         goto out;
3031                 }
3032         } else {
3033                 *_dev = dev = grt->dst.dev;
3034                 *idev = grt->rt6i_idev;
3035                 dev_hold(dev);
3036                 in6_dev_hold(grt->rt6i_idev);
3037         }
3038
3039         if (!(grt->rt6i_flags & RTF_GATEWAY))
3040                 err = 0;
3041
3042         ip6_rt_put(grt);
3043
3044 out:
3045         return err;
3046 }
3047
3048 static int ip6_validate_gw(struct net *net, struct fib6_config *cfg,
3049                            struct net_device **_dev, struct inet6_dev **idev,
3050                            struct netlink_ext_ack *extack)
3051 {
3052         const struct in6_addr *gw_addr = &cfg->fc_gateway;
3053         int gwa_type = ipv6_addr_type(gw_addr);
3054         bool skip_dev = gwa_type & IPV6_ADDR_LINKLOCAL ? false : true;
3055         const struct net_device *dev = *_dev;
3056         bool need_addr_check = !dev;
3057         int err = -EINVAL;
3058
3059         /* if gw_addr is local we will fail to detect this in case
3060          * address is still TENTATIVE (DAD in progress). rt6_lookup()
3061          * will return already-added prefix route via interface that
3062          * prefix route was assigned to, which might be non-loopback.
3063          */
3064         if (dev &&
3065             ipv6_chk_addr_and_flags(net, gw_addr, dev, skip_dev, 0, 0)) {
3066                 NL_SET_ERR_MSG(extack, "Gateway can not be a local address");
3067                 goto out;
3068         }
3069
3070         if (gwa_type != (IPV6_ADDR_LINKLOCAL | IPV6_ADDR_UNICAST)) {
3071                 /* IPv6 strictly inhibits using not link-local
3072                  * addresses as nexthop address.
3073                  * Otherwise, router will not able to send redirects.
3074                  * It is very good, but in some (rare!) circumstances
3075                  * (SIT, PtP, NBMA NOARP links) it is handy to allow
3076                  * some exceptions. --ANK
3077                  * We allow IPv4-mapped nexthops to support RFC4798-type
3078                  * addressing
3079                  */
3080                 if (!(gwa_type & (IPV6_ADDR_UNICAST | IPV6_ADDR_MAPPED))) {
3081                         NL_SET_ERR_MSG(extack, "Invalid gateway address");
3082                         goto out;
3083                 }
3084
3085                 if (cfg->fc_flags & RTNH_F_ONLINK)
3086                         err = ip6_route_check_nh_onlink(net, cfg, dev, extack);
3087                 else
3088                         err = ip6_route_check_nh(net, cfg, _dev, idev);
3089
3090                 if (err)
3091                         goto out;
3092         }
3093
3094         /* reload in case device was changed */
3095         dev = *_dev;
3096
3097         err = -EINVAL;
3098         if (!dev) {
3099                 NL_SET_ERR_MSG(extack, "Egress device not specified");
3100                 goto out;
3101         } else if (dev->flags & IFF_LOOPBACK) {
3102                 NL_SET_ERR_MSG(extack,
3103                                "Egress device can not be loopback device for this route");
3104                 goto out;
3105         }
3106
3107         /* if we did not check gw_addr above, do so now that the
3108          * egress device has been resolved.
3109          */
3110         if (need_addr_check &&
3111             ipv6_chk_addr_and_flags(net, gw_addr, dev, skip_dev, 0, 0)) {
3112                 NL_SET_ERR_MSG(extack, "Gateway can not be a local address");
3113                 goto out;
3114         }
3115
3116         err = 0;
3117 out:
3118         return err;
3119 }
3120
3121 static bool fib6_is_reject(u32 flags, struct net_device *dev, int addr_type)
3122 {
3123         if ((flags & RTF_REJECT) ||
3124             (dev && (dev->flags & IFF_LOOPBACK) &&
3125              !(addr_type & IPV6_ADDR_LOOPBACK) &&
3126              !(flags & RTF_LOCAL)))
3127                 return true;
3128
3129         return false;
3130 }
3131
3132 int fib6_nh_init(struct net *net, struct fib6_nh *fib6_nh,
3133                  struct fib6_config *cfg, gfp_t gfp_flags,
3134                  struct netlink_ext_ack *extack)
3135 {
3136         struct net_device *dev = NULL;
3137         struct inet6_dev *idev = NULL;
3138         int addr_type;
3139         int err;
3140
3141         fib6_nh->fib_nh_family = AF_INET6;
3142
3143         err = -ENODEV;
3144         if (cfg->fc_ifindex) {
3145                 dev = dev_get_by_index(net, cfg->fc_ifindex);
3146                 if (!dev)
3147                         goto out;
3148                 idev = in6_dev_get(dev);
3149                 if (!idev)
3150                         goto out;
3151         }
3152
3153         if (cfg->fc_flags & RTNH_F_ONLINK) {
3154                 if (!dev) {
3155                         NL_SET_ERR_MSG(extack,
3156                                        "Nexthop device required for onlink");
3157                         goto out;
3158                 }
3159
3160                 if (!(dev->flags & IFF_UP)) {
3161                         NL_SET_ERR_MSG(extack, "Nexthop device is not up");
3162                         err = -ENETDOWN;
3163                         goto out;
3164                 }
3165
3166                 fib6_nh->fib_nh_flags |= RTNH_F_ONLINK;
3167         }
3168
3169         fib6_nh->fib_nh_weight = 1;
3170
3171         /* We cannot add true routes via loopback here,
3172          * they would result in kernel looping; promote them to reject routes
3173          */
3174         addr_type = ipv6_addr_type(&cfg->fc_dst);
3175         if (fib6_is_reject(cfg->fc_flags, dev, addr_type)) {
3176                 /* hold loopback dev/idev if we haven't done so. */
3177                 if (dev != net->loopback_dev) {
3178                         if (dev) {
3179                                 dev_put(dev);
3180                                 in6_dev_put(idev);
3181                         }
3182                         dev = net->loopback_dev;
3183                         dev_hold(dev);
3184                         idev = in6_dev_get(dev);
3185                         if (!idev) {
3186                                 err = -ENODEV;
3187                                 goto out;
3188                         }
3189                 }
3190                 goto pcpu_alloc;
3191         }
3192
3193         if (cfg->fc_flags & RTF_GATEWAY) {
3194                 err = ip6_validate_gw(net, cfg, &dev, &idev, extack);
3195                 if (err)
3196                         goto out;
3197
3198                 fib6_nh->fib_nh_gw6 = cfg->fc_gateway;
3199                 fib6_nh->fib_nh_gw_family = AF_INET6;
3200         }
3201
3202         err = -ENODEV;
3203         if (!dev)
3204                 goto out;
3205
3206         if (idev->cnf.disable_ipv6) {
3207                 NL_SET_ERR_MSG(extack, "IPv6 is disabled on nexthop device");
3208                 err = -EACCES;
3209                 goto out;
3210         }
3211
3212         if (!(dev->flags & IFF_UP) && !cfg->fc_ignore_dev_down) {
3213                 NL_SET_ERR_MSG(extack, "Nexthop device is not up");
3214                 err = -ENETDOWN;
3215                 goto out;
3216         }
3217
3218         if (!(cfg->fc_flags & (RTF_LOCAL | RTF_ANYCAST)) &&
3219             !netif_carrier_ok(dev))
3220                 fib6_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
3221
3222         err = fib_nh_common_init(&fib6_nh->nh_common, cfg->fc_encap,
3223                                  cfg->fc_encap_type, cfg, gfp_flags, extack);
3224         if (err)
3225                 goto out;
3226
3227 pcpu_alloc:
3228         fib6_nh->rt6i_pcpu = alloc_percpu_gfp(struct rt6_info *, gfp_flags);
3229         if (!fib6_nh->rt6i_pcpu) {
3230                 err = -ENOMEM;
3231                 goto out;
3232         }
3233
3234         fib6_nh->fib_nh_dev = dev;
3235         fib6_nh->fib_nh_oif = dev->ifindex;
3236         err = 0;
3237 out:
3238         if (idev)
3239                 in6_dev_put(idev);
3240
3241         if (err) {
3242                 lwtstate_put(fib6_nh->fib_nh_lws);
3243                 fib6_nh->fib_nh_lws = NULL;
3244                 if (dev)
3245                         dev_put(dev);
3246         }
3247
3248         return err;
3249 }
3250
3251 void fib6_nh_release(struct fib6_nh *fib6_nh)
3252 {
3253         struct rt6_exception_bucket *bucket;
3254
3255         rcu_read_lock();
3256
3257         fib6_nh_flush_exceptions(fib6_nh, NULL);
3258         bucket = fib6_nh_get_excptn_bucket(fib6_nh, NULL);
3259         if (bucket) {
3260                 rcu_assign_pointer(fib6_nh->rt6i_exception_bucket, NULL);
3261                 kfree(bucket);
3262         }
3263
3264         rcu_read_unlock();
3265
3266         if (fib6_nh->rt6i_pcpu) {
3267                 int cpu;
3268
3269                 for_each_possible_cpu(cpu) {
3270                         struct rt6_info **ppcpu_rt;
3271                         struct rt6_info *pcpu_rt;
3272
3273                         ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
3274                         pcpu_rt = *ppcpu_rt;
3275                         if (pcpu_rt) {
3276                                 dst_dev_put(&pcpu_rt->dst);
3277                                 dst_release(&pcpu_rt->dst);
3278                                 *ppcpu_rt = NULL;
3279                         }
3280                 }
3281
3282                 free_percpu(fib6_nh->rt6i_pcpu);
3283         }
3284
3285         fib_nh_common_release(&fib6_nh->nh_common);
3286 }
3287
3288 static struct fib6_info *ip6_route_info_create(struct fib6_config *cfg,
3289                                               gfp_t gfp_flags,
3290                                               struct netlink_ext_ack *extack)
3291 {
3292         struct net *net = cfg->fc_nlinfo.nl_net;
3293         struct fib6_info *rt = NULL;
3294         struct nexthop *nh = NULL;
3295         struct fib6_table *table;
3296         struct fib6_nh *fib6_nh;
3297         int err = -EINVAL;
3298         int addr_type;
3299
3300         /* RTF_PCPU is an internal flag; can not be set by userspace */
3301         if (cfg->fc_flags & RTF_PCPU) {
3302                 NL_SET_ERR_MSG(extack, "Userspace can not set RTF_PCPU");
3303                 goto out;
3304         }
3305
3306         /* RTF_CACHE is an internal flag; can not be set by userspace */
3307         if (cfg->fc_flags & RTF_CACHE) {
3308                 NL_SET_ERR_MSG(extack, "Userspace can not set RTF_CACHE");
3309                 goto out;
3310         }
3311
3312         if (cfg->fc_type > RTN_MAX) {
3313                 NL_SET_ERR_MSG(extack, "Invalid route type");
3314                 goto out;
3315         }
3316
3317         if (cfg->fc_dst_len > 128) {
3318                 NL_SET_ERR_MSG(extack, "Invalid prefix length");
3319                 goto out;
3320         }
3321         if (cfg->fc_src_len > 128) {
3322                 NL_SET_ERR_MSG(extack, "Invalid source address length");
3323                 goto out;
3324         }
3325 #ifndef CONFIG_IPV6_SUBTREES
3326         if (cfg->fc_src_len) {
3327                 NL_SET_ERR_MSG(extack,
3328                                "Specifying source address requires IPV6_SUBTREES to be enabled");
3329                 goto out;
3330         }
3331 #endif
3332
3333         err = -ENOBUFS;
3334         if (cfg->fc_nlinfo.nlh &&
3335             !(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
3336                 table = fib6_get_table(net, cfg->fc_table);
3337                 if (!table) {
3338                         pr_warn("NLM_F_CREATE should be specified when creating new route\n");
3339                         table = fib6_new_table(net, cfg->fc_table);
3340                 }
3341         } else {
3342                 table = fib6_new_table(net, cfg->fc_table);
3343         }
3344
3345         if (!table)
3346                 goto out;
3347
3348         err = -ENOMEM;
3349         rt = fib6_info_alloc(gfp_flags, !nh);
3350         if (!rt)
3351                 goto out;
3352
3353         rt->fib6_metrics = ip_fib_metrics_init(net, cfg->fc_mx, cfg->fc_mx_len,
3354                                                extack);
3355         if (IS_ERR(rt->fib6_metrics)) {
3356                 err = PTR_ERR(rt->fib6_metrics);
3357                 /* Do not leave garbage there. */
3358                 rt->fib6_metrics = (struct dst_metrics *)&dst_default_metrics;
3359                 goto out;
3360         }
3361
3362         if (cfg->fc_flags & RTF_ADDRCONF)
3363                 rt->dst_nocount = true;
3364
3365         if (cfg->fc_flags & RTF_EXPIRES)
3366                 fib6_set_expires(rt, jiffies +
3367                                 clock_t_to_jiffies(cfg->fc_expires));
3368         else
3369                 fib6_clean_expires(rt);
3370
3371         if (cfg->fc_protocol == RTPROT_UNSPEC)
3372                 cfg->fc_protocol = RTPROT_BOOT;
3373         rt->fib6_protocol = cfg->fc_protocol;
3374
3375         rt->fib6_table = table;
3376         rt->fib6_metric = cfg->fc_metric;
3377         rt->fib6_type = cfg->fc_type;
3378         rt->fib6_flags = cfg->fc_flags & ~RTF_GATEWAY;
3379
3380         ipv6_addr_prefix(&rt->fib6_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
3381         rt->fib6_dst.plen = cfg->fc_dst_len;
3382         if (rt->fib6_dst.plen == 128)
3383                 rt->dst_host = true;
3384
3385 #ifdef CONFIG_IPV6_SUBTREES
3386         ipv6_addr_prefix(&rt->fib6_src.addr, &cfg->fc_src, cfg->fc_src_len);
3387         rt->fib6_src.plen = cfg->fc_src_len;
3388 #endif
3389         if (nh) {
3390                 if (!nexthop_get(nh)) {
3391                         NL_SET_ERR_MSG(extack, "Nexthop has been deleted");
3392                         goto out;
3393                 }
3394                 if (rt->fib6_src.plen) {
3395                         NL_SET_ERR_MSG(extack, "Nexthops can not be used with source routing");
3396                         goto out;
3397                 }
3398                 rt->nh = nh;
3399                 fib6_nh = nexthop_fib6_nh(rt->nh);
3400         } else {
3401                 err = fib6_nh_init(net, rt->fib6_nh, cfg, gfp_flags, extack);
3402                 if (err)
3403                         goto out;
3404
3405                 fib6_nh = rt->fib6_nh;
3406
3407                 /* We cannot add true routes via loopback here, they would
3408                  * result in kernel looping; promote them to reject routes
3409                  */
3410                 addr_type = ipv6_addr_type(&cfg->fc_dst);
3411                 if (fib6_is_reject(cfg->fc_flags, rt->fib6_nh->fib_nh_dev,
3412                                    addr_type))
3413                         rt->fib6_flags = RTF_REJECT | RTF_NONEXTHOP;
3414         }
3415
3416         if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
3417                 struct net_device *dev = fib6_nh->fib_nh_dev;
3418
3419                 if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
3420                         NL_SET_ERR_MSG(extack, "Invalid source address");
3421                         err = -EINVAL;
3422                         goto out;
3423                 }
3424                 rt->fib6_prefsrc.addr = cfg->fc_prefsrc;
3425                 rt->fib6_prefsrc.plen = 128;
3426         } else
3427                 rt->fib6_prefsrc.plen = 0;
3428
3429         return rt;
3430 out:
3431         fib6_info_release(rt);
3432         return ERR_PTR(err);
3433 }
3434
3435 int ip6_route_add(struct fib6_config *cfg, gfp_t gfp_flags,
3436                   struct netlink_ext_ack *extack)
3437 {
3438         struct fib6_info *rt;
3439         int err;
3440
3441         rt = ip6_route_info_create(cfg, gfp_flags, extack);
3442         if (IS_ERR(rt))
3443                 return PTR_ERR(rt);
3444
3445         err = __ip6_ins_rt(rt, &cfg->fc_nlinfo, extack);
3446         fib6_info_release(rt);
3447
3448         return err;
3449 }
3450
3451 static int __ip6_del_rt(struct fib6_info *rt, struct nl_info *info)
3452 {
3453         struct net *net = info->nl_net;
3454         struct fib6_table *table;
3455         int err;
3456
3457         if (rt == net->ipv6.fib6_null_entry) {
3458                 err = -ENOENT;
3459                 goto out;
3460         }
3461
3462         table = rt->fib6_table;
3463         spin_lock_bh(&table->tb6_lock);
3464         err = fib6_del(rt, info);
3465         spin_unlock_bh(&table->tb6_lock);
3466
3467 out:
3468         fib6_info_release(rt);
3469         return err;
3470 }
3471
3472 int ip6_del_rt(struct net *net, struct fib6_info *rt)
3473 {
3474         struct nl_info info = { .nl_net = net };
3475
3476         return __ip6_del_rt(rt, &info);
3477 }
3478
3479 static int __ip6_del_rt_siblings(struct fib6_info *rt, struct fib6_config *cfg)
3480 {
3481         struct nl_info *info = &cfg->fc_nlinfo;
3482         struct net *net = info->nl_net;
3483         struct sk_buff *skb = NULL;
3484         struct fib6_table *table;
3485         int err = -ENOENT;
3486
3487         if (rt == net->ipv6.fib6_null_entry)
3488                 goto out_put;
3489         table = rt->fib6_table;
3490         spin_lock_bh(&table->tb6_lock);
3491
3492         if (rt->fib6_nsiblings && cfg->fc_delete_all_nh) {
3493                 struct fib6_info *sibling, *next_sibling;
3494
3495                 /* prefer to send a single notification with all hops */
3496                 skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
3497                 if (skb) {
3498                         u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
3499
3500                         if (rt6_fill_node(net, skb, rt, NULL,
3501                                           NULL, NULL, 0, RTM_DELROUTE,
3502                                           info->portid, seq, 0) < 0) {
3503                                 kfree_skb(skb);
3504                                 skb = NULL;
3505                         } else
3506                                 info->skip_notify = 1;
3507                 }
3508
3509                 list_for_each_entry_safe(sibling, next_sibling,
3510                                          &rt->fib6_siblings,
3511                                          fib6_siblings) {
3512                         err = fib6_del(sibling, info);
3513                         if (err)
3514                                 goto out_unlock;
3515                 }
3516         }
3517
3518         err = fib6_del(rt, info);
3519 out_unlock:
3520         spin_unlock_bh(&table->tb6_lock);
3521 out_put:
3522         fib6_info_release(rt);
3523
3524         if (skb) {
3525                 rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
3526                             info->nlh, gfp_any());
3527         }
3528         return err;
3529 }
3530
3531 static int __ip6_del_cached_rt(struct rt6_info *rt, struct fib6_config *cfg)
3532 {
3533         int rc = -ESRCH;
3534
3535         if (cfg->fc_ifindex && rt->dst.dev->ifindex != cfg->fc_ifindex)
3536                 goto out;
3537
3538         if (cfg->fc_flags & RTF_GATEWAY &&
3539             !ipv6_addr_equal(&cfg->fc_gateway, &rt->rt6i_gateway))
3540                 goto out;
3541
3542         rc = rt6_remove_exception_rt(rt);
3543 out:
3544         return rc;
3545 }
3546
3547 static int ip6_del_cached_rt(struct fib6_config *cfg, struct fib6_info *rt,
3548                              struct fib6_nh *nh)
3549 {
3550         struct fib6_result res = {
3551                 .f6i = rt,
3552                 .nh = nh,
3553         };
3554         struct rt6_info *rt_cache;
3555
3556         rt_cache = rt6_find_cached_rt(&res, &cfg->fc_dst, &cfg->fc_src);
3557         if (rt_cache)
3558                 return __ip6_del_cached_rt(rt_cache, cfg);
3559
3560         return 0;
3561 }
3562
3563 static int ip6_route_del(struct fib6_config *cfg,
3564                          struct netlink_ext_ack *extack)
3565 {
3566         struct fib6_table *table;
3567         struct fib6_info *rt;
3568         struct fib6_node *fn;
3569         int err = -ESRCH;
3570
3571         table = fib6_get_table(cfg->fc_nlinfo.nl_net, cfg->fc_table);
3572         if (!table) {
3573                 NL_SET_ERR_MSG(extack, "FIB table does not exist");
3574                 return err;
3575         }
3576
3577         rcu_read_lock();
3578
3579         fn = fib6_locate(&table->tb6_root,
3580                          &cfg->fc_dst, cfg->fc_dst_len,
3581                          &cfg->fc_src, cfg->fc_src_len,
3582                          !(cfg->fc_flags & RTF_CACHE));
3583
3584         if (fn) {
3585                 for_each_fib6_node_rt_rcu(fn) {
3586                         struct fib6_nh *nh;
3587
3588                         nh = rt->fib6_nh;
3589                         if (cfg->fc_flags & RTF_CACHE) {
3590                                 int rc;
3591
3592                                 rc = ip6_del_cached_rt(cfg, rt, nh);
3593                                 if (rc != -ESRCH) {
3594                                         rcu_read_unlock();
3595                                         return rc;
3596                                 }
3597                                 continue;
3598                         }
3599
3600                         if (cfg->fc_ifindex &&
3601                             (!nh->fib_nh_dev ||
3602                              nh->fib_nh_dev->ifindex != cfg->fc_ifindex))
3603                                 continue;
3604                         if (cfg->fc_flags & RTF_GATEWAY &&
3605                             !ipv6_addr_equal(&cfg->fc_gateway, &nh->fib_nh_gw6))
3606                                 continue;
3607                         if (cfg->fc_metric && cfg->fc_metric != rt->fib6_metric)
3608                                 continue;
3609                         if (cfg->fc_protocol && cfg->fc_protocol != rt->fib6_protocol)
3610                                 continue;
3611                         if (!fib6_info_hold_safe(rt))
3612                                 continue;
3613                         rcu_read_unlock();
3614
3615                         /* if gateway was specified only delete the one hop */
3616                         if (cfg->fc_flags & RTF_GATEWAY)
3617                                 return __ip6_del_rt(rt, &cfg->fc_nlinfo);
3618
3619                         return __ip6_del_rt_siblings(rt, cfg);
3620                 }
3621         }
3622         rcu_read_unlock();
3623
3624         return err;
3625 }
3626
3627 static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
3628 {
3629         struct netevent_redirect netevent;
3630         struct rt6_info *rt, *nrt = NULL;
3631         struct fib6_result res = {};
3632         struct ndisc_options ndopts;
3633         struct inet6_dev *in6_dev;
3634         struct neighbour *neigh;
3635         struct rd_msg *msg;
3636         int optlen, on_link;
3637         u8 *lladdr;
3638
3639         optlen = skb_tail_pointer(skb) - skb_transport_header(skb);
3640         optlen -= sizeof(*msg);
3641
3642         if (optlen < 0) {
3643                 net_dbg_ratelimited("rt6_do_redirect: packet too short\n");
3644                 return;
3645         }
3646
3647         msg = (struct rd_msg *)icmp6_hdr(skb);
3648
3649         if (ipv6_addr_is_multicast(&msg->dest)) {
3650                 net_dbg_ratelimited("rt6_do_redirect: destination address is multicast\n");
3651                 return;
3652         }
3653
3654         on_link = 0;
3655         if (ipv6_addr_equal(&msg->dest, &msg->target)) {
3656                 on_link = 1;
3657         } else if (ipv6_addr_type(&msg->target) !=
3658                    (IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) {
3659                 net_dbg_ratelimited("rt6_do_redirect: target address is not link-local unicast\n");
3660                 return;
3661         }
3662
3663         in6_dev = __in6_dev_get(skb->dev);
3664         if (!in6_dev)
3665                 return;
3666         if (in6_dev->cnf.forwarding || !in6_dev->cnf.accept_redirects)
3667                 return;
3668
3669         /* RFC2461 8.1:
3670          *      The IP source address of the Redirect MUST be the same as the current
3671          *      first-hop router for the specified ICMP Destination Address.
3672          */
3673
3674         if (!ndisc_parse_options(skb->dev, msg->opt, optlen, &ndopts)) {
3675                 net_dbg_ratelimited("rt6_redirect: invalid ND options\n");
3676                 return;
3677         }
3678
3679         lladdr = NULL;
3680         if (ndopts.nd_opts_tgt_lladdr) {
3681                 lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr,
3682                                              skb->dev);
3683                 if (!lladdr) {
3684                         net_dbg_ratelimited("rt6_redirect: invalid link-layer address length\n");
3685                         return;
3686                 }
3687         }
3688
3689         rt = (struct rt6_info *) dst;
3690         if (rt->rt6i_flags & RTF_REJECT) {
3691                 net_dbg_ratelimited("rt6_redirect: source isn't a valid nexthop for redirect target\n");
3692                 return;
3693         }
3694
3695         /* Redirect received -> path was valid.
3696          * Look, redirects are sent only in response to data packets,
3697          * so that this nexthop apparently is reachable. --ANK
3698          */
3699         dst_confirm_neigh(&rt->dst, &ipv6_hdr(skb)->saddr);
3700
3701         neigh = __neigh_lookup(&nd_tbl, &msg->target, skb->dev, 1);
3702         if (!neigh)
3703                 return;
3704
3705         /*
3706          *      We have finally decided to accept it.
3707          */
3708
3709         ndisc_update(skb->dev, neigh, lladdr, NUD_STALE,
3710                      NEIGH_UPDATE_F_WEAK_OVERRIDE|
3711                      NEIGH_UPDATE_F_OVERRIDE|
3712                      (on_link ? 0 : (NEIGH_UPDATE_F_OVERRIDE_ISROUTER|
3713                                      NEIGH_UPDATE_F_ISROUTER)),
3714                      NDISC_REDIRECT, &ndopts);
3715
3716         rcu_read_lock();
3717         res.f6i = rcu_dereference(rt->from);
3718         if (!res.f6i)
3719                 goto out;
3720
3721         res.nh = res.f6i->fib6_nh;
3722         res.fib6_flags = res.f6i->fib6_flags;
3723         res.fib6_type = res.f6i->fib6_type;
3724         nrt = ip6_rt_cache_alloc(&res, &msg->dest, NULL);
3725         if (!nrt)
3726                 goto out;
3727
3728         nrt->rt6i_flags = RTF_GATEWAY|RTF_UP|RTF_DYNAMIC|RTF_CACHE;
3729         if (on_link)
3730                 nrt->rt6i_flags &= ~RTF_GATEWAY;
3731
3732         nrt->rt6i_gateway = *(struct in6_addr *)neigh->primary_key;
3733
3734         /* rt6_insert_exception() will take care of duplicated exceptions */
3735         if (rt6_insert_exception(nrt, &res)) {
3736                 dst_release_immediate(&nrt->dst);
3737                 goto out;
3738         }
3739
3740         netevent.old = &rt->dst;
3741         netevent.new = &nrt->dst;
3742         netevent.daddr = &msg->dest;
3743         netevent.neigh = neigh;
3744         call_netevent_notifiers(NETEVENT_REDIRECT, &netevent);
3745
3746 out:
3747         rcu_read_unlock();
3748         neigh_release(neigh);
3749 }
3750
3751 #ifdef CONFIG_IPV6_ROUTE_INFO
3752 static struct fib6_info *rt6_get_route_info(struct net *net,
3753                                            const struct in6_addr *prefix, int prefixlen,
3754                                            const struct in6_addr *gwaddr,
3755                                            struct net_device *dev)
3756 {
3757         u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_INFO;
3758         int ifindex = dev->ifindex;
3759         struct fib6_node *fn;
3760         struct fib6_info *rt = NULL;
3761         struct fib6_table *table;
3762
3763         table = fib6_get_table(net, tb_id);
3764         if (!table)
3765                 return NULL;
3766
3767         rcu_read_lock();
3768         fn = fib6_locate(&table->tb6_root, prefix, prefixlen, NULL, 0, true);
3769         if (!fn)
3770                 goto out;
3771
3772         for_each_fib6_node_rt_rcu(fn) {
3773                 /* these routes do not use nexthops */
3774                 if (rt->nh)
3775                         continue;
3776                 if (rt->fib6_nh->fib_nh_dev->ifindex != ifindex)
3777                         continue;
3778                 if (!(rt->fib6_flags & RTF_ROUTEINFO) ||
3779                     !rt->fib6_nh->fib_nh_gw_family)
3780                         continue;
3781                 if (!ipv6_addr_equal(&rt->fib6_nh->fib_nh_gw6, gwaddr))
3782                         continue;
3783                 if (!fib6_info_hold_safe(rt))
3784                         continue;
3785                 break;
3786         }
3787 out:
3788         rcu_read_unlock();
3789         return rt;
3790 }
3791
3792 static struct fib6_info *rt6_add_route_info(struct net *net,
3793                                            const struct in6_addr *prefix, int prefixlen,
3794                                            const struct in6_addr *gwaddr,
3795                                            struct net_device *dev,
3796                                            unsigned int pref)
3797 {
3798         struct fib6_config cfg = {
3799                 .fc_metric      = IP6_RT_PRIO_USER,
3800                 .fc_ifindex     = dev->ifindex,
3801                 .fc_dst_len     = prefixlen,
3802                 .fc_flags       = RTF_GATEWAY | RTF_ADDRCONF | RTF_ROUTEINFO |
3803                                   RTF_UP | RTF_PREF(pref),
3804                 .fc_protocol = RTPROT_RA,
3805                 .fc_type = RTN_UNICAST,
3806                 .fc_nlinfo.portid = 0,
3807                 .fc_nlinfo.nlh = NULL,
3808                 .fc_nlinfo.nl_net = net,
3809         };
3810
3811         cfg.fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_INFO,
3812         cfg.fc_dst = *prefix;
3813         cfg.fc_gateway = *gwaddr;
3814
3815         /* We should treat it as a default route if prefix length is 0. */
3816         if (!prefixlen)
3817                 cfg.fc_flags |= RTF_DEFAULT;
3818
3819         ip6_route_add(&cfg, GFP_ATOMIC, NULL);
3820
3821         return rt6_get_route_info(net, prefix, prefixlen, gwaddr, dev);
3822 }
3823 #endif
3824
3825 struct fib6_info *rt6_get_dflt_router(struct net *net,
3826                                      const struct in6_addr *addr,
3827                                      struct net_device *dev)
3828 {
3829         u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_DFLT;
3830         struct fib6_info *rt;
3831         struct fib6_table *table;
3832
3833         table = fib6_get_table(net, tb_id);
3834         if (!table)
3835                 return NULL;
3836
3837         rcu_read_lock();
3838         for_each_fib6_node_rt_rcu(&table->tb6_root) {
3839                 struct fib6_nh *nh;
3840
3841                 /* RA routes do not use nexthops */
3842                 if (rt->nh)
3843                         continue;
3844
3845                 nh = rt->fib6_nh;
3846                 if (dev == nh->fib_nh_dev &&
3847                     ((rt->fib6_flags & (RTF_ADDRCONF | RTF_DEFAULT)) == (RTF_ADDRCONF | RTF_DEFAULT)) &&
3848                     ipv6_addr_equal(&nh->fib_nh_gw6, addr))
3849                         break;
3850         }
3851         if (rt && !fib6_info_hold_safe(rt))
3852                 rt = NULL;
3853         rcu_read_unlock();
3854         return rt;
3855 }
3856
3857 struct fib6_info *rt6_add_dflt_router(struct net *net,
3858                                      const struct in6_addr *gwaddr,
3859                                      struct net_device *dev,
3860                                      unsigned int pref)
3861 {
3862         struct fib6_config cfg = {
3863                 .fc_table       = l3mdev_fib_table(dev) ? : RT6_TABLE_DFLT,
3864                 .fc_metric      = IP6_RT_PRIO_USER,
3865                 .fc_ifindex     = dev->ifindex,
3866                 .fc_flags       = RTF_GATEWAY | RTF_ADDRCONF | RTF_DEFAULT |
3867                                   RTF_UP | RTF_EXPIRES | RTF_PREF(pref),
3868                 .fc_protocol = RTPROT_RA,
3869                 .fc_type = RTN_UNICAST,
3870                 .fc_nlinfo.portid = 0,
3871                 .fc_nlinfo.nlh = NULL,
3872                 .fc_nlinfo.nl_net = net,
3873         };
3874
3875         cfg.fc_gateway = *gwaddr;
3876
3877         if (!ip6_route_add(&cfg, GFP_ATOMIC, NULL)) {
3878                 struct fib6_table *table;
3879
3880                 table = fib6_get_table(dev_net(dev), cfg.fc_table);
3881                 if (table)
3882                         table->flags |= RT6_TABLE_HAS_DFLT_ROUTER;
3883         }
3884
3885         return rt6_get_dflt_router(net, gwaddr, dev);
3886 }
3887
3888 static void __rt6_purge_dflt_routers(struct net *net,
3889                                      struct fib6_table *table)
3890 {
3891         struct fib6_info *rt;
3892
3893 restart:
3894         rcu_read_lock();
3895         for_each_fib6_node_rt_rcu(&table->tb6_root) {
3896                 struct net_device *dev = fib6_info_nh_dev(rt);
3897                 struct inet6_dev *idev = dev ? __in6_dev_get(dev) : NULL;
3898
3899                 if (rt->fib6_flags & (RTF_DEFAULT | RTF_ADDRCONF) &&
3900                     (!idev || idev->cnf.accept_ra != 2) &&
3901                     fib6_info_hold_safe(rt)) {
3902                         rcu_read_unlock();
3903                         ip6_del_rt(net, rt);
3904                         goto restart;
3905                 }
3906         }
3907         rcu_read_unlock();
3908
3909         table->flags &= ~RT6_TABLE_HAS_DFLT_ROUTER;
3910 }
3911
3912 void rt6_purge_dflt_routers(struct net *net)
3913 {
3914         struct fib6_table *table;
3915         struct hlist_head *head;
3916         unsigned int h;
3917
3918         rcu_read_lock();
3919
3920         for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
3921                 head = &net->ipv6.fib_table_hash[h];
3922                 hlist_for_each_entry_rcu(table, head, tb6_hlist) {
3923                         if (table->flags & RT6_TABLE_HAS_DFLT_ROUTER)
3924                                 __rt6_purge_dflt_routers(net, table);
3925                 }
3926         }
3927
3928         rcu_read_unlock();
3929 }
3930
3931 static void rtmsg_to_fib6_config(struct net *net,
3932                                  struct in6_rtmsg *rtmsg,
3933                                  struct fib6_config *cfg)
3934 {
3935         *cfg = (struct fib6_config){
3936                 .fc_table = l3mdev_fib_table_by_index(net, rtmsg->rtmsg_ifindex) ?
3937                          : RT6_TABLE_MAIN,
3938                 .fc_ifindex = rtmsg->rtmsg_ifindex,
3939                 .fc_metric = rtmsg->rtmsg_metric ? : IP6_RT_PRIO_USER,
3940                 .fc_expires = rtmsg->rtmsg_info,
3941                 .fc_dst_len = rtmsg->rtmsg_dst_len,
3942                 .fc_src_len = rtmsg->rtmsg_src_len,
3943                 .fc_flags = rtmsg->rtmsg_flags,
3944                 .fc_type = rtmsg->rtmsg_type,
3945
3946                 .fc_nlinfo.nl_net = net,
3947
3948                 .fc_dst = rtmsg->rtmsg_dst,
3949                 .fc_src = rtmsg->rtmsg_src,
3950                 .fc_gateway = rtmsg->rtmsg_gateway,
3951         };
3952 }
3953
3954 int ipv6_route_ioctl(struct net *net, unsigned int cmd, void __user *arg)
3955 {
3956         struct fib6_config cfg;
3957         struct in6_rtmsg rtmsg;
3958         int err;
3959
3960         switch (cmd) {
3961         case SIOCADDRT:         /* Add a route */
3962         case SIOCDELRT:         /* Delete a route */
3963                 if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3964                         return -EPERM;
3965                 err = copy_from_user(&rtmsg, arg,
3966                                      sizeof(struct in6_rtmsg));
3967                 if (err)
3968                         return -EFAULT;
3969
3970                 rtmsg_to_fib6_config(net, &rtmsg, &cfg);
3971
3972                 rtnl_lock();
3973                 switch (cmd) {
3974                 case SIOCADDRT:
3975                         err = ip6_route_add(&cfg, GFP_KERNEL, NULL);
3976                         break;
3977                 case SIOCDELRT:
3978                         err = ip6_route_del(&cfg, NULL);
3979                         break;
3980                 default:
3981                         err = -EINVAL;
3982                 }
3983                 rtnl_unlock();
3984
3985                 return err;
3986         }
3987
3988         return -EINVAL;
3989 }
3990
3991 /*
3992  *      Drop the packet on the floor
3993  */
3994
3995 static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
3996 {
3997         struct dst_entry *dst = skb_dst(skb);
3998         struct net *net = dev_net(dst->dev);
3999         struct inet6_dev *idev;
4000         int type;
4001
4002         if (netif_is_l3_master(skb->dev) &&
4003             dst->dev == net->loopback_dev)
4004                 idev = __in6_dev_get_safely(dev_get_by_index_rcu(net, IP6CB(skb)->iif));
4005         else
4006                 idev = ip6_dst_idev(dst);
4007
4008         switch (ipstats_mib_noroutes) {
4009         case IPSTATS_MIB_INNOROUTES:
4010                 type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
4011                 if (type == IPV6_ADDR_ANY) {
4012                         IP6_INC_STATS(net, idev, IPSTATS_MIB_INADDRERRORS);
4013                         break;
4014                 }
4015                 /* FALLTHROUGH */
4016         case IPSTATS_MIB_OUTNOROUTES:
4017                 IP6_INC_STATS(net, idev, ipstats_mib_noroutes);
4018                 break;
4019         }
4020
4021         /* Start over by dropping the dst for l3mdev case */
4022         if (netif_is_l3_master(skb->dev))
4023                 skb_dst_drop(skb);
4024
4025         icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
4026         kfree_skb(skb);
4027         return 0;
4028 }
4029
4030 static int ip6_pkt_discard(struct sk_buff *skb)
4031 {
4032         return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
4033 }
4034
4035 static int ip6_pkt_discard_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4036 {
4037         skb->dev = skb_dst(skb)->dev;
4038         return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
4039 }
4040
4041 static int ip6_pkt_prohibit(struct sk_buff *skb)
4042 {
4043         return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
4044 }
4045
4046 static int ip6_pkt_prohibit_out(struct net *net, struct sock *sk, struct sk_buff *skb)
4047 {
4048         skb->dev = skb_dst(skb)->dev;
4049         return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
4050 }
4051
4052 /*
4053  *      Allocate a dst for local (unicast / anycast) address.
4054  */
4055
4056 struct fib6_info *addrconf_f6i_alloc(struct net *net,
4057                                      struct inet6_dev *idev,
4058                                      const struct in6_addr *addr,
4059                                      bool anycast, gfp_t gfp_flags)
4060 {
4061         struct fib6_config cfg = {
4062                 .fc_table = l3mdev_fib_table(idev->dev) ? : RT6_TABLE_LOCAL,
4063                 .fc_ifindex = idev->dev->ifindex,
4064                 .fc_flags = RTF_UP | RTF_ADDRCONF | RTF_NONEXTHOP,
4065                 .fc_dst = *addr,
4066                 .fc_dst_len = 128,
4067                 .fc_protocol = RTPROT_KERNEL,
4068                 .fc_nlinfo.nl_net = net,
4069                 .fc_ignore_dev_down = true,
4070         };
4071
4072         if (anycast) {
4073                 cfg.fc_type = RTN_ANYCAST;
4074                 cfg.fc_flags |= RTF_ANYCAST;
4075         } else {
4076                 cfg.fc_type = RTN_LOCAL;
4077                 cfg.fc_flags |= RTF_LOCAL;
4078         }
4079
4080         return ip6_route_info_create(&cfg, gfp_flags, NULL);
4081 }
4082
4083 /* remove deleted ip from prefsrc entries */
4084 struct arg_dev_net_ip {
4085         struct net_device *dev;
4086         struct net *net;
4087         struct in6_addr *addr;
4088 };
4089
4090 static int fib6_remove_prefsrc(struct fib6_info *rt, void *arg)
4091 {
4092         struct net_device *dev = ((struct arg_dev_net_ip *)arg)->dev;
4093         struct net *net = ((struct arg_dev_net_ip *)arg)->net;
4094         struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
4095
4096         if (!rt->nh &&
4097             ((void *)rt->fib6_nh->fib_nh_dev == dev || !dev) &&
4098             rt != net->ipv6.fib6_null_entry &&
4099             ipv6_addr_equal(addr, &rt->fib6_prefsrc.addr)) {
4100                 spin_lock_bh(&rt6_exception_lock);
4101                 /* remove prefsrc entry */
4102                 rt->fib6_prefsrc.plen = 0;
4103                 spin_unlock_bh(&rt6_exception_lock);
4104         }
4105         return 0;
4106 }
4107
4108 void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
4109 {
4110         struct net *net = dev_net(ifp->idev->dev);
4111         struct arg_dev_net_ip adni = {
4112                 .dev = ifp->idev->dev,
4113                 .net = net,
4114                 .addr = &ifp->addr,
4115         };
4116         fib6_clean_all(net, fib6_remove_prefsrc, &adni);
4117 }
4118
4119 #define RTF_RA_ROUTER           (RTF_ADDRCONF | RTF_DEFAULT)
4120
4121 /* Remove routers and update dst entries when gateway turn into host. */
4122 static int fib6_clean_tohost(struct fib6_info *rt, void *arg)
4123 {
4124         struct in6_addr *gateway = (struct in6_addr *)arg;
4125         struct fib6_nh *nh;
4126
4127         /* RA routes do not use nexthops */
4128         if (rt->nh)
4129                 return 0;
4130
4131         nh = rt->fib6_nh;
4132         if (((rt->fib6_flags & RTF_RA_ROUTER) == RTF_RA_ROUTER) &&
4133             nh->fib_nh_gw_family && ipv6_addr_equal(gateway, &nh->fib_nh_gw6))
4134                 return -1;
4135
4136         /* Further clean up cached routes in exception table.
4137          * This is needed because cached route may have a different
4138          * gateway than its 'parent' in the case of an ip redirect.
4139          */
4140         fib6_nh_exceptions_clean_tohost(nh, gateway);
4141
4142         return 0;
4143 }
4144
4145 void rt6_clean_tohost(struct net *net, struct in6_addr *gateway)
4146 {
4147         fib6_clean_all(net, fib6_clean_tohost, gateway);
4148 }
4149
4150 struct arg_netdev_event {
4151         const struct net_device *dev;
4152         union {
4153                 unsigned char nh_flags;
4154                 unsigned long event;
4155         };
4156 };
4157
4158 static struct fib6_info *rt6_multipath_first_sibling(const struct fib6_info *rt)
4159 {
4160         struct fib6_info *iter;
4161         struct fib6_node *fn;
4162
4163         fn = rcu_dereference_protected(rt->fib6_node,
4164                         lockdep_is_held(&rt->fib6_table->tb6_lock));
4165         iter = rcu_dereference_protected(fn->leaf,
4166                         lockdep_is_held(&rt->fib6_table->tb6_lock));
4167         while (iter) {
4168                 if (iter->fib6_metric == rt->fib6_metric &&
4169                     rt6_qualify_for_ecmp(iter))
4170                         return iter;
4171                 iter = rcu_dereference_protected(iter->fib6_next,
4172                                 lockdep_is_held(&rt->fib6_table->tb6_lock));
4173         }
4174
4175         return NULL;
4176 }
4177
4178 /* only called for fib entries with builtin fib6_nh */
4179 static bool rt6_is_dead(const struct fib6_info *rt)
4180 {
4181         if (rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD ||
4182             (rt->fib6_nh->fib_nh_flags & RTNH_F_LINKDOWN &&
4183              ip6_ignore_linkdown(rt->fib6_nh->fib_nh_dev)))
4184                 return true;
4185
4186         return false;
4187 }
4188
4189 static int rt6_multipath_total_weight(const struct fib6_info *rt)
4190 {
4191         struct fib6_info *iter;
4192         int total = 0;
4193
4194         if (!rt6_is_dead(rt))
4195                 total += rt->fib6_nh->fib_nh_weight;
4196
4197         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings) {
4198                 if (!rt6_is_dead(iter))
4199                         total += iter->fib6_nh->fib_nh_weight;
4200         }
4201
4202         return total;
4203 }
4204
4205 static void rt6_upper_bound_set(struct fib6_info *rt, int *weight, int total)
4206 {
4207         int upper_bound = -1;
4208
4209         if (!rt6_is_dead(rt)) {
4210                 *weight += rt->fib6_nh->fib_nh_weight;
4211                 upper_bound = DIV_ROUND_CLOSEST_ULL((u64) (*weight) << 31,
4212                                                     total) - 1;
4213         }
4214         atomic_set(&rt->fib6_nh->fib_nh_upper_bound, upper_bound);
4215 }
4216
4217 static void rt6_multipath_upper_bound_set(struct fib6_info *rt, int total)
4218 {
4219         struct fib6_info *iter;
4220         int weight = 0;
4221
4222         rt6_upper_bound_set(rt, &weight, total);
4223
4224         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4225                 rt6_upper_bound_set(iter, &weight, total);
4226 }
4227
4228 void rt6_multipath_rebalance(struct fib6_info *rt)
4229 {
4230         struct fib6_info *first;
4231         int total;
4232
4233         /* In case the entire multipath route was marked for flushing,
4234          * then there is no need to rebalance upon the removal of every
4235          * sibling route.
4236          */
4237         if (!rt->fib6_nsiblings || rt->should_flush)
4238                 return;
4239
4240         /* During lookup routes are evaluated in order, so we need to
4241          * make sure upper bounds are assigned from the first sibling
4242          * onwards.
4243          */
4244         first = rt6_multipath_first_sibling(rt);
4245         if (WARN_ON_ONCE(!first))
4246                 return;
4247
4248         total = rt6_multipath_total_weight(first);
4249         rt6_multipath_upper_bound_set(first, total);
4250 }
4251
4252 static int fib6_ifup(struct fib6_info *rt, void *p_arg)
4253 {
4254         const struct arg_netdev_event *arg = p_arg;
4255         struct net *net = dev_net(arg->dev);
4256
4257         if (rt != net->ipv6.fib6_null_entry && !rt->nh &&
4258             rt->fib6_nh->fib_nh_dev == arg->dev) {
4259                 rt->fib6_nh->fib_nh_flags &= ~arg->nh_flags;
4260                 fib6_update_sernum_upto_root(net, rt);
4261                 rt6_multipath_rebalance(rt);
4262         }
4263
4264         return 0;
4265 }
4266
4267 void rt6_sync_up(struct net_device *dev, unsigned char nh_flags)
4268 {
4269         struct arg_netdev_event arg = {
4270                 .dev = dev,
4271                 {
4272                         .nh_flags = nh_flags,
4273                 },
4274         };
4275
4276         if (nh_flags & RTNH_F_DEAD && netif_carrier_ok(dev))
4277                 arg.nh_flags |= RTNH_F_LINKDOWN;
4278
4279         fib6_clean_all(dev_net(dev), fib6_ifup, &arg);
4280 }
4281
4282 /* only called for fib entries with inline fib6_nh */
4283 static bool rt6_multipath_uses_dev(const struct fib6_info *rt,
4284                                    const struct net_device *dev)
4285 {
4286         struct fib6_info *iter;
4287
4288         if (rt->fib6_nh->fib_nh_dev == dev)
4289                 return true;
4290         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4291                 if (iter->fib6_nh->fib_nh_dev == dev)
4292                         return true;
4293
4294         return false;
4295 }
4296
4297 static void rt6_multipath_flush(struct fib6_info *rt)
4298 {
4299         struct fib6_info *iter;
4300
4301         rt->should_flush = 1;
4302         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4303                 iter->should_flush = 1;
4304 }
4305
4306 static unsigned int rt6_multipath_dead_count(const struct fib6_info *rt,
4307                                              const struct net_device *down_dev)
4308 {
4309         struct fib6_info *iter;
4310         unsigned int dead = 0;
4311
4312         if (rt->fib6_nh->fib_nh_dev == down_dev ||
4313             rt->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4314                 dead++;
4315         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4316                 if (iter->fib6_nh->fib_nh_dev == down_dev ||
4317                     iter->fib6_nh->fib_nh_flags & RTNH_F_DEAD)
4318                         dead++;
4319
4320         return dead;
4321 }
4322
4323 static void rt6_multipath_nh_flags_set(struct fib6_info *rt,
4324                                        const struct net_device *dev,
4325                                        unsigned char nh_flags)
4326 {
4327         struct fib6_info *iter;
4328
4329         if (rt->fib6_nh->fib_nh_dev == dev)
4330                 rt->fib6_nh->fib_nh_flags |= nh_flags;
4331         list_for_each_entry(iter, &rt->fib6_siblings, fib6_siblings)
4332                 if (iter->fib6_nh->fib_nh_dev == dev)
4333                         iter->fib6_nh->fib_nh_flags |= nh_flags;
4334 }
4335
4336 /* called with write lock held for table with rt */
4337 static int fib6_ifdown(struct fib6_info *rt, void *p_arg)
4338 {
4339         const struct arg_netdev_event *arg = p_arg;
4340         const struct net_device *dev = arg->dev;
4341         struct net *net = dev_net(dev);
4342
4343         if (rt == net->ipv6.fib6_null_entry || rt->nh)
4344                 return 0;
4345
4346         switch (arg->event) {
4347         case NETDEV_UNREGISTER:
4348                 return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4349         case NETDEV_DOWN:
4350                 if (rt->should_flush)
4351                         return -1;
4352                 if (!rt->fib6_nsiblings)
4353                         return rt->fib6_nh->fib_nh_dev == dev ? -1 : 0;
4354                 if (rt6_multipath_uses_dev(rt, dev)) {
4355                         unsigned int count;
4356
4357                         count = rt6_multipath_dead_count(rt, dev);
4358                         if (rt->fib6_nsiblings + 1 == count) {
4359                                 rt6_multipath_flush(rt);
4360                                 return -1;
4361                         }
4362                         rt6_multipath_nh_flags_set(rt, dev, RTNH_F_DEAD |
4363                                                    RTNH_F_LINKDOWN);
4364                         fib6_update_sernum(net, rt);
4365                         rt6_multipath_rebalance(rt);
4366                 }
4367                 return -2;
4368         case NETDEV_CHANGE:
4369                 if (rt->fib6_nh->fib_nh_dev != dev ||
4370                     rt->fib6_flags & (RTF_LOCAL | RTF_ANYCAST))
4371                         break;
4372                 rt->fib6_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
4373                 rt6_multipath_rebalance(rt);
4374                 break;
4375         }
4376
4377         return 0;
4378 }
4379
4380 void rt6_sync_down_dev(struct net_device *dev, unsigned long event)
4381 {
4382         struct arg_netdev_event arg = {
4383                 .dev = dev,
4384                 {
4385                         .event = event,
4386                 },
4387         };
4388         struct net *net = dev_net(dev);
4389
4390         if (net->ipv6.sysctl.skip_notify_on_dev_down)
4391                 fib6_clean_all_skip_notify(net, fib6_ifdown, &arg);
4392         else
4393                 fib6_clean_all(net, fib6_ifdown, &arg);
4394 }
4395
4396 void rt6_disable_ip(struct net_device *dev, unsigned long event)
4397 {
4398         rt6_sync_down_dev(dev, event);
4399         rt6_uncached_list_flush_dev(dev_net(dev), dev);
4400         neigh_ifdown(&nd_tbl, dev);
4401 }
4402
4403 struct rt6_mtu_change_arg {
4404         struct net_device *dev;
4405         unsigned int mtu;
4406         struct fib6_info *f6i;
4407 };
4408
4409 static int fib6_nh_mtu_change(struct fib6_nh *nh, void *_arg)
4410 {
4411         struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *)_arg;
4412         struct fib6_info *f6i = arg->f6i;
4413
4414         /* For administrative MTU increase, there is no way to discover
4415          * IPv6 PMTU increase, so PMTU increase should be updated here.
4416          * Since RFC 1981 doesn't include administrative MTU increase
4417          * update PMTU increase is a MUST. (i.e. jumbo frame)
4418          */
4419         if (nh->fib_nh_dev == arg->dev) {
4420                 struct inet6_dev *idev = __in6_dev_get(arg->dev);
4421                 u32 mtu = f6i->fib6_pmtu;
4422
4423                 if (mtu >= arg->mtu ||
4424                     (mtu < arg->mtu && mtu == idev->cnf.mtu6))
4425                         fib6_metric_set(f6i, RTAX_MTU, arg->mtu);
4426
4427                 spin_lock_bh(&rt6_exception_lock);
4428                 rt6_exceptions_update_pmtu(idev, nh, arg->mtu);
4429                 spin_unlock_bh(&rt6_exception_lock);
4430         }
4431
4432         return 0;
4433 }
4434
4435 static int rt6_mtu_change_route(struct fib6_info *f6i, void *p_arg)
4436 {
4437         struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
4438         struct inet6_dev *idev;
4439
4440         /* In IPv6 pmtu discovery is not optional,
4441            so that RTAX_MTU lock cannot disable it.
4442            We still use this lock to block changes
4443            caused by addrconf/ndisc.
4444         */
4445
4446         idev = __in6_dev_get(arg->dev);
4447         if (!idev)
4448                 return 0;
4449
4450         if (fib6_metric_locked(f6i, RTAX_MTU))
4451                 return 0;
4452
4453         arg->f6i = f6i;
4454         return fib6_nh_mtu_change(f6i->fib6_nh, arg);
4455 }
4456
4457 void rt6_mtu_change(struct net_device *dev, unsigned int mtu)
4458 {
4459         struct rt6_mtu_change_arg arg = {
4460                 .dev = dev,
4461                 .mtu = mtu,
4462         };
4463
4464         fib6_clean_all(dev_net(dev), rt6_mtu_change_route, &arg);
4465 }
4466
4467 static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
4468         [RTA_UNSPEC]            = { .strict_start_type = RTA_DPORT + 1 },
4469         [RTA_GATEWAY]           = { .len = sizeof(struct in6_addr) },
4470         [RTA_PREFSRC]           = { .len = sizeof(struct in6_addr) },
4471         [RTA_OIF]               = { .type = NLA_U32 },
4472         [RTA_IIF]               = { .type = NLA_U32 },
4473         [RTA_PRIORITY]          = { .type = NLA_U32 },
4474         [RTA_METRICS]           = { .type = NLA_NESTED },
4475         [RTA_MULTIPATH]         = { .len = sizeof(struct rtnexthop) },
4476         [RTA_PREF]              = { .type = NLA_U8 },
4477         [RTA_ENCAP_TYPE]        = { .type = NLA_U16 },
4478         [RTA_ENCAP]             = { .type = NLA_NESTED },
4479         [RTA_EXPIRES]           = { .type = NLA_U32 },
4480         [RTA_UID]               = { .type = NLA_U32 },
4481         [RTA_MARK]              = { .type = NLA_U32 },
4482         [RTA_TABLE]             = { .type = NLA_U32 },
4483         [RTA_IP_PROTO]          = { .type = NLA_U8 },
4484         [RTA_SPORT]             = { .type = NLA_U16 },
4485         [RTA_DPORT]             = { .type = NLA_U16 },
4486 };
4487
4488 static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
4489                               struct fib6_config *cfg,
4490                               struct netlink_ext_ack *extack)
4491 {
4492         struct rtmsg *rtm;
4493         struct nlattr *tb[RTA_MAX+1];
4494         unsigned int pref;
4495         int err;
4496
4497         err = nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
4498                                      rtm_ipv6_policy, extack);
4499         if (err < 0)
4500                 goto errout;
4501
4502         err = -EINVAL;
4503         rtm = nlmsg_data(nlh);
4504
4505         *cfg = (struct fib6_config){
4506                 .fc_table = rtm->rtm_table,
4507                 .fc_dst_len = rtm->rtm_dst_len,
4508                 .fc_src_len = rtm->rtm_src_len,
4509                 .fc_flags = RTF_UP,
4510                 .fc_protocol = rtm->rtm_protocol,
4511                 .fc_type = rtm->rtm_type,
4512
4513                 .fc_nlinfo.portid = NETLINK_CB(skb).portid,
4514                 .fc_nlinfo.nlh = nlh,
4515                 .fc_nlinfo.nl_net = sock_net(skb->sk),
4516         };
4517
4518         if (rtm->rtm_type == RTN_UNREACHABLE ||
4519             rtm->rtm_type == RTN_BLACKHOLE ||
4520             rtm->rtm_type == RTN_PROHIBIT ||
4521             rtm->rtm_type == RTN_THROW)
4522                 cfg->fc_flags |= RTF_REJECT;
4523
4524         if (rtm->rtm_type == RTN_LOCAL)
4525                 cfg->fc_flags |= RTF_LOCAL;
4526
4527         if (rtm->rtm_flags & RTM_F_CLONED)
4528                 cfg->fc_flags |= RTF_CACHE;
4529
4530         cfg->fc_flags |= (rtm->rtm_flags & RTNH_F_ONLINK);
4531
4532         if (tb[RTA_GATEWAY]) {
4533                 cfg->fc_gateway = nla_get_in6_addr(tb[RTA_GATEWAY]);
4534                 cfg->fc_flags |= RTF_GATEWAY;
4535         }
4536         if (tb[RTA_VIA]) {
4537                 NL_SET_ERR_MSG(extack, "IPv6 does not support RTA_VIA attribute");
4538                 goto errout;
4539         }
4540
4541         if (tb[RTA_DST]) {
4542                 int plen = (rtm->rtm_dst_len + 7) >> 3;
4543
4544                 if (nla_len(tb[RTA_DST]) < plen)
4545                         goto errout;
4546
4547                 nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
4548         }
4549
4550         if (tb[RTA_SRC]) {
4551                 int plen = (rtm->rtm_src_len + 7) >> 3;
4552
4553                 if (nla_len(tb[RTA_SRC]) < plen)
4554                         goto errout;
4555
4556                 nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
4557         }
4558
4559         if (tb[RTA_PREFSRC])
4560                 cfg->fc_prefsrc = nla_get_in6_addr(tb[RTA_PREFSRC]);
4561
4562         if (tb[RTA_OIF])
4563                 cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
4564
4565         if (tb[RTA_PRIORITY])
4566                 cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
4567
4568         if (tb[RTA_METRICS]) {
4569                 cfg->fc_mx = nla_data(tb[RTA_METRICS]);
4570                 cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
4571         }
4572
4573         if (tb[RTA_TABLE])
4574                 cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
4575
4576         if (tb[RTA_MULTIPATH]) {
4577                 cfg->fc_mp = nla_data(tb[RTA_MULTIPATH]);
4578                 cfg->fc_mp_len = nla_len(tb[RTA_MULTIPATH]);
4579
4580                 err = lwtunnel_valid_encap_type_attr(cfg->fc_mp,
4581                                                      cfg->fc_mp_len, extack);
4582                 if (err < 0)
4583                         goto errout;
4584         }
4585
4586         if (tb[RTA_PREF]) {
4587                 pref = nla_get_u8(tb[RTA_PREF]);
4588                 if (pref != ICMPV6_ROUTER_PREF_LOW &&
4589                     pref != ICMPV6_ROUTER_PREF_HIGH)
4590                         pref = ICMPV6_ROUTER_PREF_MEDIUM;
4591                 cfg->fc_flags |= RTF_PREF(pref);
4592         }
4593
4594         if (tb[RTA_ENCAP])
4595                 cfg->fc_encap = tb[RTA_ENCAP];
4596
4597         if (tb[RTA_ENCAP_TYPE]) {
4598                 cfg->fc_encap_type = nla_get_u16(tb[RTA_ENCAP_TYPE]);
4599
4600                 err = lwtunnel_valid_encap_type(cfg->fc_encap_type, extack);
4601                 if (err < 0)
4602                         goto errout;
4603         }
4604
4605         if (tb[RTA_EXPIRES]) {
4606                 unsigned long timeout = addrconf_timeout_fixup(nla_get_u32(tb[RTA_EXPIRES]), HZ);
4607
4608                 if (addrconf_finite_timeout(timeout)) {
4609                         cfg->fc_expires = jiffies_to_clock_t(timeout * HZ);
4610                         cfg->fc_flags |= RTF_EXPIRES;
4611                 }
4612         }
4613
4614         err = 0;
4615 errout:
4616         return err;
4617 }
4618
4619 struct rt6_nh {
4620         struct fib6_info *fib6_info;
4621         struct fib6_config r_cfg;
4622         struct list_head next;
4623 };
4624
4625 static int ip6_route_info_append(struct net *net,
4626                                  struct list_head *rt6_nh_list,
4627                                  struct fib6_info *rt,
4628                                  struct fib6_config *r_cfg)
4629 {
4630         struct rt6_nh *nh;
4631         int err = -EEXIST;
4632
4633         list_for_each_entry(nh, rt6_nh_list, next) {
4634                 /* check if fib6_info already exists */
4635                 if (rt6_duplicate_nexthop(nh->fib6_info, rt))
4636                         return err;
4637         }
4638
4639         nh = kzalloc(sizeof(*nh), GFP_KERNEL);
4640         if (!nh)
4641                 return -ENOMEM;
4642         nh->fib6_info = rt;
4643         memcpy(&nh->r_cfg, r_cfg, sizeof(*r_cfg));
4644         list_add_tail(&nh->next, rt6_nh_list);
4645
4646         return 0;
4647 }
4648
4649 static void ip6_route_mpath_notify(struct fib6_info *rt,
4650                                    struct fib6_info *rt_last,
4651                                    struct nl_info *info,
4652                                    __u16 nlflags)
4653 {
4654         /* if this is an APPEND route, then rt points to the first route
4655          * inserted and rt_last points to last route inserted. Userspace
4656          * wants a consistent dump of the route which starts at the first
4657          * nexthop. Since sibling routes are always added at the end of
4658          * the list, find the first sibling of the last route appended
4659          */
4660         if ((nlflags & NLM_F_APPEND) && rt_last && rt_last->fib6_nsiblings) {
4661                 rt = list_first_entry(&rt_last->fib6_siblings,
4662                                       struct fib6_info,
4663                                       fib6_siblings);
4664         }
4665
4666         if (rt)
4667                 inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
4668 }
4669
4670 static int ip6_route_multipath_add(struct fib6_config *cfg,
4671                                    struct netlink_ext_ack *extack)
4672 {
4673         struct fib6_info *rt_notif = NULL, *rt_last = NULL;
4674         struct nl_info *info = &cfg->fc_nlinfo;
4675         struct fib6_config r_cfg;
4676         struct rtnexthop *rtnh;
4677         struct fib6_info *rt;
4678         struct rt6_nh *err_nh;
4679         struct rt6_nh *nh, *nh_safe;
4680         __u16 nlflags;
4681         int remaining;
4682         int attrlen;
4683         int err = 1;
4684         int nhn = 0;
4685         int replace = (cfg->fc_nlinfo.nlh &&
4686                        (cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_REPLACE));
4687         LIST_HEAD(rt6_nh_list);
4688
4689         nlflags = replace ? NLM_F_REPLACE : NLM_F_CREATE;
4690         if (info->nlh && info->nlh->nlmsg_flags & NLM_F_APPEND)
4691                 nlflags |= NLM_F_APPEND;
4692
4693         remaining = cfg->fc_mp_len;
4694         rtnh = (struct rtnexthop *)cfg->fc_mp;
4695
4696         /* Parse a Multipath Entry and build a list (rt6_nh_list) of
4697          * fib6_info structs per nexthop
4698          */
4699         while (rtnh_ok(rtnh, remaining)) {
4700                 memcpy(&r_cfg, cfg, sizeof(*cfg));
4701                 if (rtnh->rtnh_ifindex)
4702                         r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
4703
4704                 attrlen = rtnh_attrlen(rtnh);
4705                 if (attrlen > 0) {
4706                         struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
4707
4708                         nla = nla_find(attrs, attrlen, RTA_GATEWAY);
4709                         if (nla) {
4710                                 r_cfg.fc_gateway = nla_get_in6_addr(nla);
4711                                 r_cfg.fc_flags |= RTF_GATEWAY;
4712                         }
4713                         r_cfg.fc_encap = nla_find(attrs, attrlen, RTA_ENCAP);
4714                         nla = nla_find(attrs, attrlen, RTA_ENCAP_TYPE);
4715                         if (nla)
4716                                 r_cfg.fc_encap_type = nla_get_u16(nla);
4717                 }
4718
4719                 r_cfg.fc_flags |= (rtnh->rtnh_flags & RTNH_F_ONLINK);
4720                 rt = ip6_route_info_create(&r_cfg, GFP_KERNEL, extack);
4721                 if (IS_ERR(rt)) {
4722                         err = PTR_ERR(rt);
4723                         rt = NULL;
4724                         goto cleanup;
4725                 }
4726                 if (!rt6_qualify_for_ecmp(rt)) {
4727                         err = -EINVAL;
4728                         NL_SET_ERR_MSG(extack,
4729                                        "Device only routes can not be added for IPv6 using the multipath API.");
4730                         fib6_info_release(rt);
4731                         goto cleanup;
4732                 }
4733
4734                 rt->fib6_nh->fib_nh_weight = rtnh->rtnh_hops + 1;
4735
4736                 err = ip6_route_info_append(info->nl_net, &rt6_nh_list,
4737                                             rt, &r_cfg);
4738                 if (err) {
4739                         fib6_info_release(rt);
4740                         goto cleanup;
4741                 }
4742
4743                 rtnh = rtnh_next(rtnh, &remaining);
4744         }
4745
4746         /* for add and replace send one notification with all nexthops.
4747          * Skip the notification in fib6_add_rt2node and send one with
4748          * the full route when done
4749          */
4750         info->skip_notify = 1;
4751
4752         err_nh = NULL;
4753         list_for_each_entry(nh, &rt6_nh_list, next) {
4754                 err = __ip6_ins_rt(nh->fib6_info, info, extack);
4755                 fib6_info_release(nh->fib6_info);
4756
4757                 if (!err) {
4758                         /* save reference to last route successfully inserted */
4759                         rt_last = nh->fib6_info;
4760
4761                         /* save reference to first route for notification */
4762                         if (!rt_notif)
4763                                 rt_notif = nh->fib6_info;
4764                 }
4765
4766                 /* nh->fib6_info is used or freed at this point, reset to NULL*/
4767                 nh->fib6_info = NULL;
4768                 if (err) {
4769                         if (replace && nhn)
4770                                 NL_SET_ERR_MSG_MOD(extack,
4771                                                    "multipath route replace failed (check consistency of installed routes)");
4772                         err_nh = nh;
4773                         goto add_errout;
4774                 }
4775
4776                 /* Because each route is added like a single route we remove
4777                  * these flags after the first nexthop: if there is a collision,
4778                  * we have already failed to add the first nexthop:
4779                  * fib6_add_rt2node() has rejected it; when replacing, old
4780                  * nexthops have been replaced by first new, the rest should
4781                  * be added to it.
4782                  */
4783                 cfg->fc_nlinfo.nlh->nlmsg_flags &= ~(NLM_F_EXCL |
4784                                                      NLM_F_REPLACE);
4785                 nhn++;
4786         }
4787
4788         /* success ... tell user about new route */
4789         ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
4790         goto cleanup;
4791
4792 add_errout:
4793         /* send notification for routes that were added so that
4794          * the delete notifications sent by ip6_route_del are
4795          * coherent
4796          */
4797         if (rt_notif)
4798                 ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
4799
4800         /* Delete routes that were already added */
4801         list_for_each_entry(nh, &rt6_nh_list, next) {
4802                 if (err_nh == nh)
4803                         break;
4804                 ip6_route_del(&nh->r_cfg, extack);
4805         }
4806
4807 cleanup:
4808         list_for_each_entry_safe(nh, nh_safe, &rt6_nh_list, next) {
4809                 if (nh->fib6_info)
4810                         fib6_info_release(nh->fib6_info);
4811                 list_del(&nh->next);
4812                 kfree(nh);
4813         }
4814
4815         return err;
4816 }
4817
4818 static int ip6_route_multipath_del(struct fib6_config *cfg,
4819                                    struct netlink_ext_ack *extack)
4820 {
4821         struct fib6_config r_cfg;
4822         struct rtnexthop *rtnh;
4823         int remaining;
4824         int attrlen;
4825         int err = 1, last_err = 0;
4826
4827         remaining = cfg->fc_mp_len;
4828         rtnh = (struct rtnexthop *)cfg->fc_mp;
4829
4830         /* Parse a Multipath Entry */
4831         while (rtnh_ok(rtnh, remaining)) {
4832                 memcpy(&r_cfg, cfg, sizeof(*cfg));
4833                 if (rtnh->rtnh_ifindex)
4834                         r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
4835
4836                 attrlen = rtnh_attrlen(rtnh);
4837                 if (attrlen > 0) {
4838                         struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
4839
4840                         nla = nla_find(attrs, attrlen, RTA_GATEWAY);
4841                         if (nla) {
4842                                 nla_memcpy(&r_cfg.fc_gateway, nla, 16);
4843                                 r_cfg.fc_flags |= RTF_GATEWAY;
4844                         }
4845                 }
4846                 err = ip6_route_del(&r_cfg, extack);
4847                 if (err)
4848                         last_err = err;
4849
4850                 rtnh = rtnh_next(rtnh, &remaining);
4851         }
4852
4853         return last_err;
4854 }
4855
4856 static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
4857                               struct netlink_ext_ack *extack)
4858 {
4859         struct fib6_config cfg;
4860         int err;
4861
4862         err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
4863         if (err < 0)
4864                 return err;
4865
4866         if (cfg.fc_mp)
4867                 return ip6_route_multipath_del(&cfg, extack);
4868         else {
4869                 cfg.fc_delete_all_nh = 1;
4870                 return ip6_route_del(&cfg, extack);
4871         }
4872 }
4873
4874 static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
4875                               struct netlink_ext_ack *extack)
4876 {
4877         struct fib6_config cfg;
4878         int err;
4879
4880         err = rtm_to_fib6_config(skb, nlh, &cfg, extack);
4881         if (err < 0)
4882                 return err;
4883
4884         if (cfg.fc_metric == 0)
4885                 cfg.fc_metric = IP6_RT_PRIO_USER;
4886
4887         if (cfg.fc_mp)
4888                 return ip6_route_multipath_add(&cfg, extack);
4889         else
4890                 return ip6_route_add(&cfg, GFP_KERNEL, extack);
4891 }
4892
4893 static size_t rt6_nlmsg_size(struct fib6_info *rt)
4894 {
4895         int nexthop_len = 0;
4896
4897         if (rt->nh)
4898                 nexthop_len += nla_total_size(4); /* RTA_NH_ID */
4899
4900         if (rt->fib6_nsiblings) {
4901                 nexthop_len = nla_total_size(0)  /* RTA_MULTIPATH */
4902                             + NLA_ALIGN(sizeof(struct rtnexthop))
4903                             + nla_total_size(16) /* RTA_GATEWAY */
4904                             + lwtunnel_get_encap_size(rt->fib6_nh->fib_nh_lws);
4905
4906                 nexthop_len *= rt->fib6_nsiblings;
4907         }
4908
4909         return NLMSG_ALIGN(sizeof(struct rtmsg))
4910                + nla_total_size(16) /* RTA_SRC */
4911                + nla_total_size(16) /* RTA_DST */
4912                + nla_total_size(16) /* RTA_GATEWAY */
4913                + nla_total_size(16) /* RTA_PREFSRC */
4914                + nla_total_size(4) /* RTA_TABLE */
4915                + nla_total_size(4) /* RTA_IIF */
4916                + nla_total_size(4) /* RTA_OIF */
4917                + nla_total_size(4) /* RTA_PRIORITY */
4918                + RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
4919                + nla_total_size(sizeof(struct rta_cacheinfo))
4920                + nla_total_size(TCP_CA_NAME_MAX) /* RTAX_CC_ALGO */
4921                + nla_total_size(1) /* RTA_PREF */
4922                + lwtunnel_get_encap_size(rt->fib6_nh->fib_nh_lws)
4923                + nexthop_len;
4924 }
4925
4926 static int rt6_fill_node_nexthop(struct sk_buff *skb, struct nexthop *nh,
4927                                  unsigned char *flags)
4928 {
4929         if (nexthop_is_multipath(nh)) {
4930                 struct nlattr *mp;
4931
4932                 mp = nla_nest_start(skb, RTA_MULTIPATH);
4933                 if (!mp)
4934                         goto nla_put_failure;
4935
4936                 if (nexthop_mpath_fill_node(skb, nh))
4937                         goto nla_put_failure;
4938
4939                 nla_nest_end(skb, mp);
4940         } else {
4941                 struct fib6_nh *fib6_nh;
4942
4943                 fib6_nh = nexthop_fib6_nh(nh);
4944                 if (fib_nexthop_info(skb, &fib6_nh->nh_common,
4945                                      flags, false) < 0)
4946                         goto nla_put_failure;
4947         }
4948
4949         return 0;
4950
4951 nla_put_failure:
4952         return -EMSGSIZE;
4953 }
4954
4955 static int rt6_fill_node(struct net *net, struct sk_buff *skb,
4956                          struct fib6_info *rt, struct dst_entry *dst,
4957                          struct in6_addr *dest, struct in6_addr *src,
4958                          int iif, int type, u32 portid, u32 seq,
4959                          unsigned int flags)
4960 {
4961         struct rt6_info *rt6 = (struct rt6_info *)dst;
4962         struct rt6key *rt6_dst, *rt6_src;
4963         u32 *pmetrics, table, rt6_flags;
4964         unsigned char nh_flags = 0;
4965         struct nlmsghdr *nlh;
4966         struct rtmsg *rtm;
4967         long expires = 0;
4968
4969         nlh = nlmsg_put(skb, portid, seq, type, sizeof(*rtm), flags);
4970         if (!nlh)
4971                 return -EMSGSIZE;
4972
4973         if (rt6) {
4974                 rt6_dst = &rt6->rt6i_dst;
4975                 rt6_src = &rt6->rt6i_src;
4976                 rt6_flags = rt6->rt6i_flags;
4977         } else {
4978                 rt6_dst = &rt->fib6_dst;
4979                 rt6_src = &rt->fib6_src;
4980                 rt6_flags = rt->fib6_flags;
4981         }
4982
4983         rtm = nlmsg_data(nlh);
4984         rtm->rtm_family = AF_INET6;
4985         rtm->rtm_dst_len = rt6_dst->plen;
4986         rtm->rtm_src_len = rt6_src->plen;
4987         rtm->rtm_tos = 0;
4988         if (rt->fib6_table)
4989                 table = rt->fib6_table->tb6_id;
4990         else
4991                 table = RT6_TABLE_UNSPEC;
4992         rtm->rtm_table = table < 256 ? table : RT_TABLE_COMPAT;
4993         if (nla_put_u32(skb, RTA_TABLE, table))
4994                 goto nla_put_failure;
4995
4996         rtm->rtm_type = rt->fib6_type;
4997         rtm->rtm_flags = 0;
4998         rtm->rtm_scope = RT_SCOPE_UNIVERSE;
4999         rtm->rtm_protocol = rt->fib6_protocol;
5000
5001         if (rt6_flags & RTF_CACHE)
5002                 rtm->rtm_flags |= RTM_F_CLONED;
5003
5004         if (dest) {
5005                 if (nla_put_in6_addr(skb, RTA_DST, dest))
5006                         goto nla_put_failure;
5007                 rtm->rtm_dst_len = 128;
5008         } else if (rtm->rtm_dst_len)
5009                 if (nla_put_in6_addr(skb, RTA_DST, &rt6_dst->addr))
5010                         goto nla_put_failure;
5011 #ifdef CONFIG_IPV6_SUBTREES
5012         if (src) {
5013                 if (nla_put_in6_addr(skb, RTA_SRC, src))
5014                         goto nla_put_failure;
5015                 rtm->rtm_src_len = 128;
5016         } else if (rtm->rtm_src_len &&
5017                    nla_put_in6_addr(skb, RTA_SRC, &rt6_src->addr))
5018                 goto nla_put_failure;
5019 #endif
5020         if (iif) {
5021 #ifdef CONFIG_IPV6_MROUTE
5022                 if (ipv6_addr_is_multicast(&rt6_dst->addr)) {
5023                         int err = ip6mr_get_route(net, skb, rtm, portid);
5024
5025                         if (err == 0)
5026                                 return 0;
5027                         if (err < 0)
5028                                 goto nla_put_failure;
5029                 } else
5030 #endif
5031                         if (nla_put_u32(skb, RTA_IIF, iif))
5032                                 goto nla_put_failure;
5033         } else if (dest) {
5034                 struct in6_addr saddr_buf;
5035                 if (ip6_route_get_saddr(net, rt, dest, 0, &saddr_buf) == 0 &&
5036                     nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5037                         goto nla_put_failure;
5038         }
5039
5040         if (rt->fib6_prefsrc.plen) {
5041                 struct in6_addr saddr_buf;
5042                 saddr_buf = rt->fib6_prefsrc.addr;
5043                 if (nla_put_in6_addr(skb, RTA_PREFSRC, &saddr_buf))
5044                         goto nla_put_failure;
5045         }
5046
5047         pmetrics = dst ? dst_metrics_ptr(dst) : rt->fib6_metrics->metrics;
5048         if (rtnetlink_put_metrics(skb, pmetrics) < 0)
5049                 goto nla_put_failure;
5050
5051         if (nla_put_u32(skb, RTA_PRIORITY, rt->fib6_metric))
5052                 goto nla_put_failure;
5053
5054         /* For multipath routes, walk the siblings list and add
5055          * each as a nexthop within RTA_MULTIPATH.
5056          */
5057         if (rt6) {
5058                 if (rt6_flags & RTF_GATEWAY &&
5059                     nla_put_in6_addr(skb, RTA_GATEWAY, &rt6->rt6i_gateway))
5060                         goto nla_put_failure;
5061
5062                 if (dst->dev && nla_put_u32(skb, RTA_OIF, dst->dev->ifindex))
5063                         goto nla_put_failure;
5064         } else if (rt->fib6_nsiblings) {
5065                 struct fib6_info *sibling, *next_sibling;
5066                 struct nlattr *mp;
5067
5068                 mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
5069                 if (!mp)
5070                         goto nla_put_failure;
5071
5072                 if (fib_add_nexthop(skb, &rt->fib6_nh->nh_common,
5073                                     rt->fib6_nh->fib_nh_weight) < 0)
5074                         goto nla_put_failure;
5075
5076                 list_for_each_entry_safe(sibling, next_sibling,
5077                                          &rt->fib6_siblings, fib6_siblings) {
5078                         if (fib_add_nexthop(skb, &sibling->fib6_nh->nh_common,
5079                                             sibling->fib6_nh->fib_nh_weight) < 0)
5080                                 goto nla_put_failure;
5081                 }
5082
5083                 nla_nest_end(skb, mp);
5084         } else if (rt->nh) {
5085                 if (nla_put_u32(skb, RTA_NH_ID, rt->nh->id))
5086                         goto nla_put_failure;
5087
5088                 if (nexthop_is_blackhole(rt->nh))
5089                         rtm->rtm_type = RTN_BLACKHOLE;
5090
5091                 if (rt6_fill_node_nexthop(skb, rt->nh, &nh_flags) < 0)
5092                         goto nla_put_failure;
5093
5094                 rtm->rtm_flags |= nh_flags;
5095         } else {
5096                 if (fib_nexthop_info(skb, &rt->fib6_nh->nh_common,
5097                                      &nh_flags, false) < 0)
5098                         goto nla_put_failure;
5099
5100                 rtm->rtm_flags |= nh_flags;
5101         }
5102
5103         if (rt6_flags & RTF_EXPIRES) {
5104                 expires = dst ? dst->expires : rt->expires;
5105                 expires -= jiffies;
5106         }
5107
5108         if (rtnl_put_cacheinfo(skb, dst, 0, expires, dst ? dst->error : 0) < 0)
5109                 goto nla_put_failure;
5110
5111         if (nla_put_u8(skb, RTA_PREF, IPV6_EXTRACT_PREF(rt6_flags)))
5112                 goto nla_put_failure;
5113
5114
5115         nlmsg_end(skb, nlh);
5116         return 0;
5117
5118 nla_put_failure:
5119         nlmsg_cancel(skb, nlh);
5120         return -EMSGSIZE;
5121 }
5122
5123 static bool fib6_info_uses_dev(const struct fib6_info *f6i,
5124                                const struct net_device *dev)
5125 {
5126         if (f6i->fib6_nh->fib_nh_dev == dev)
5127                 return true;
5128
5129         if (f6i->fib6_nsiblings) {
5130                 struct fib6_info *sibling, *next_sibling;
5131
5132                 list_for_each_entry_safe(sibling, next_sibling,
5133                                          &f6i->fib6_siblings, fib6_siblings) {
5134                         if (sibling->fib6_nh->fib_nh_dev == dev)
5135                                 return true;
5136                 }
5137         }
5138
5139         return false;
5140 }
5141
5142 int rt6_dump_route(struct fib6_info *rt, void *p_arg)
5143 {
5144         struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
5145         struct fib_dump_filter *filter = &arg->filter;
5146         unsigned int flags = NLM_F_MULTI;
5147         struct net *net = arg->net;
5148
5149         if (rt == net->ipv6.fib6_null_entry)
5150                 return 0;
5151
5152         if ((filter->flags & RTM_F_PREFIX) &&
5153             !(rt->fib6_flags & RTF_PREFIX_RT)) {
5154                 /* success since this is not a prefix route */
5155                 return 1;
5156         }
5157         if (filter->filter_set) {
5158                 if ((filter->rt_type && rt->fib6_type != filter->rt_type) ||
5159                     (filter->dev && !fib6_info_uses_dev(rt, filter->dev)) ||
5160                     (filter->protocol && rt->fib6_protocol != filter->protocol)) {
5161                         return 1;
5162                 }
5163                 flags |= NLM_F_DUMP_FILTERED;
5164         }
5165
5166         return rt6_fill_node(net, arg->skb, rt, NULL, NULL, NULL, 0,
5167                              RTM_NEWROUTE, NETLINK_CB(arg->cb->skb).portid,
5168                              arg->cb->nlh->nlmsg_seq, flags);
5169 }
5170
5171 static int inet6_rtm_valid_getroute_req(struct sk_buff *skb,
5172                                         const struct nlmsghdr *nlh,
5173                                         struct nlattr **tb,
5174                                         struct netlink_ext_ack *extack)
5175 {
5176         struct rtmsg *rtm;
5177         int i, err;
5178
5179         if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) {
5180                 NL_SET_ERR_MSG_MOD(extack,
5181                                    "Invalid header for get route request");
5182                 return -EINVAL;
5183         }
5184
5185         if (!netlink_strict_get_check(skb))
5186                 return nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
5187                                               rtm_ipv6_policy, extack);
5188
5189         rtm = nlmsg_data(nlh);
5190         if ((rtm->rtm_src_len && rtm->rtm_src_len != 128) ||
5191             (rtm->rtm_dst_len && rtm->rtm_dst_len != 128) ||
5192             rtm->rtm_table || rtm->rtm_protocol || rtm->rtm_scope ||
5193             rtm->rtm_type) {
5194                 NL_SET_ERR_MSG_MOD(extack, "Invalid values in header for get route request");
5195                 return -EINVAL;
5196         }
5197         if (rtm->rtm_flags & ~RTM_F_FIB_MATCH) {
5198                 NL_SET_ERR_MSG_MOD(extack,
5199                                    "Invalid flags for get route request");
5200                 return -EINVAL;
5201         }
5202
5203         err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
5204                                             rtm_ipv6_policy, extack);
5205         if (err)
5206                 return err;
5207
5208         if ((tb[RTA_SRC] && !rtm->rtm_src_len) ||
5209             (tb[RTA_DST] && !rtm->rtm_dst_len)) {
5210                 NL_SET_ERR_MSG_MOD(extack, "rtm_src_len and rtm_dst_len must be 128 for IPv6");
5211                 return -EINVAL;
5212         }
5213
5214         for (i = 0; i <= RTA_MAX; i++) {
5215                 if (!tb[i])
5216                         continue;
5217
5218                 switch (i) {
5219                 case RTA_SRC:
5220                 case RTA_DST:
5221                 case RTA_IIF:
5222                 case RTA_OIF:
5223                 case RTA_MARK:
5224                 case RTA_UID:
5225                 case RTA_SPORT:
5226                 case RTA_DPORT:
5227                 case RTA_IP_PROTO:
5228                         break;
5229                 default:
5230                         NL_SET_ERR_MSG_MOD(extack, "Unsupported attribute in get route request");
5231                         return -EINVAL;
5232                 }
5233         }
5234
5235         return 0;
5236 }
5237
5238 static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
5239                               struct netlink_ext_ack *extack)
5240 {
5241         struct net *net = sock_net(in_skb->sk);
5242         struct nlattr *tb[RTA_MAX+1];
5243         int err, iif = 0, oif = 0;
5244         struct fib6_info *from;
5245         struct dst_entry *dst;
5246         struct rt6_info *rt;
5247         struct sk_buff *skb;
5248         struct rtmsg *rtm;
5249         struct flowi6 fl6 = {};
5250         bool fibmatch;
5251
5252         err = inet6_rtm_valid_getroute_req(in_skb, nlh, tb, extack);
5253         if (err < 0)
5254                 goto errout;
5255
5256         err = -EINVAL;
5257         rtm = nlmsg_data(nlh);
5258         fl6.flowlabel = ip6_make_flowinfo(rtm->rtm_tos, 0);
5259         fibmatch = !!(rtm->rtm_flags & RTM_F_FIB_MATCH);
5260
5261         if (tb[RTA_SRC]) {
5262                 if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
5263                         goto errout;
5264
5265                 fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
5266         }
5267
5268         if (tb[RTA_DST]) {
5269                 if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
5270                         goto errout;
5271
5272                 fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
5273         }
5274
5275         if (tb[RTA_IIF])
5276                 iif = nla_get_u32(tb[RTA_IIF]);
5277
5278         if (tb[RTA_OIF])
5279                 oif = nla_get_u32(tb[RTA_OIF]);
5280
5281         if (tb[RTA_MARK])
5282                 fl6.flowi6_mark = nla_get_u32(tb[RTA_MARK]);
5283
5284         if (tb[RTA_UID])
5285                 fl6.flowi6_uid = make_kuid(current_user_ns(),
5286                                            nla_get_u32(tb[RTA_UID]));
5287         else
5288                 fl6.flowi6_uid = iif ? INVALID_UID : current_uid();
5289
5290         if (tb[RTA_SPORT])
5291                 fl6.fl6_sport = nla_get_be16(tb[RTA_SPORT]);
5292
5293         if (tb[RTA_DPORT])
5294                 fl6.fl6_dport = nla_get_be16(tb[RTA_DPORT]);
5295
5296         if (tb[RTA_IP_PROTO]) {
5297                 err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO],
5298                                                   &fl6.flowi6_proto, AF_INET6,
5299                                                   extack);
5300                 if (err)
5301                         goto errout;
5302         }
5303
5304         if (iif) {
5305                 struct net_device *dev;
5306                 int flags = 0;
5307
5308                 rcu_read_lock();
5309
5310                 dev = dev_get_by_index_rcu(net, iif);
5311                 if (!dev) {
5312                         rcu_read_unlock();
5313                         err = -ENODEV;
5314                         goto errout;
5315                 }
5316
5317                 fl6.flowi6_iif = iif;
5318
5319                 if (!ipv6_addr_any(&fl6.saddr))
5320                         flags |= RT6_LOOKUP_F_HAS_SADDR;
5321
5322                 dst = ip6_route_input_lookup(net, dev, &fl6, NULL, flags);
5323
5324                 rcu_read_unlock();
5325         } else {
5326                 fl6.flowi6_oif = oif;
5327
5328                 dst = ip6_route_output(net, NULL, &fl6);
5329         }
5330
5331
5332         rt = container_of(dst, struct rt6_info, dst);
5333         if (rt->dst.error) {
5334                 err = rt->dst.error;
5335                 ip6_rt_put(rt);
5336                 goto errout;
5337         }
5338
5339         if (rt == net->ipv6.ip6_null_entry) {
5340                 err = rt->dst.error;
5341                 ip6_rt_put(rt);
5342                 goto errout;
5343         }
5344
5345         skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
5346         if (!skb) {
5347                 ip6_rt_put(rt);
5348                 err = -ENOBUFS;
5349                 goto errout;
5350         }
5351
5352         skb_dst_set(skb, &rt->dst);
5353
5354         rcu_read_lock();
5355         from = rcu_dereference(rt->from);
5356         if (from) {
5357                 if (fibmatch)
5358                         err = rt6_fill_node(net, skb, from, NULL, NULL, NULL,
5359                                             iif, RTM_NEWROUTE,
5360                                             NETLINK_CB(in_skb).portid,
5361                                             nlh->nlmsg_seq, 0);
5362                 else
5363                         err = rt6_fill_node(net, skb, from, dst, &fl6.daddr,
5364                                             &fl6.saddr, iif, RTM_NEWROUTE,
5365                                             NETLINK_CB(in_skb).portid,
5366                                             nlh->nlmsg_seq, 0);
5367         } else {
5368                 err = -ENETUNREACH;
5369         }
5370         rcu_read_unlock();
5371
5372         if (err < 0) {
5373                 kfree_skb(skb);
5374                 goto errout;
5375         }
5376
5377         err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
5378 errout:
5379         return err;
5380 }
5381
5382 void inet6_rt_notify(int event, struct fib6_info *rt, struct nl_info *info,
5383                      unsigned int nlm_flags)
5384 {
5385         struct sk_buff *skb;
5386         struct net *net = info->nl_net;
5387         u32 seq;
5388         int err;
5389
5390         err = -ENOBUFS;
5391         seq = info->nlh ? info->nlh->nlmsg_seq : 0;
5392
5393         skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
5394         if (!skb)
5395                 goto errout;
5396
5397         err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
5398                             event, info->portid, seq, nlm_flags);
5399         if (err < 0) {
5400                 /* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
5401                 WARN_ON(err == -EMSGSIZE);
5402                 kfree_skb(skb);
5403                 goto errout;
5404         }
5405         rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
5406                     info->nlh, gfp_any());
5407         return;
5408 errout:
5409         if (err < 0)
5410                 rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
5411 }
5412
5413 void fib6_rt_update(struct net *net, struct fib6_info *rt,
5414                     struct nl_info *info)
5415 {
5416         u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
5417         struct sk_buff *skb;
5418         int err = -ENOBUFS;
5419
5420         /* call_fib6_entry_notifiers will be removed when in-kernel notifier
5421          * is implemented and supported for nexthop objects
5422          */
5423         call_fib6_entry_notifiers(net, FIB_EVENT_ENTRY_REPLACE, rt, NULL);
5424
5425         skb = nlmsg_new(rt6_nlmsg_size(rt), gfp_any());
5426         if (!skb)
5427                 goto errout;
5428
5429         err = rt6_fill_node(net, skb, rt, NULL, NULL, NULL, 0,
5430                             RTM_NEWROUTE, info->portid, seq, NLM_F_REPLACE);
5431         if (err < 0) {
5432                 /* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
5433                 WARN_ON(err == -EMSGSIZE);
5434                 kfree_skb(skb);
5435                 goto errout;
5436         }
5437         rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
5438                     info->nlh, gfp_any());
5439         return;
5440 errout:
5441         if (err < 0)
5442                 rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
5443 }
5444
5445 static int ip6_route_dev_notify(struct notifier_block *this,
5446                                 unsigned long event, void *ptr)
5447 {
5448         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
5449         struct net *net = dev_net(dev);
5450
5451         if (!(dev->flags & IFF_LOOPBACK))
5452                 return NOTIFY_OK;
5453
5454         if (event == NETDEV_REGISTER) {
5455                 net->ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = dev;
5456                 net->ipv6.ip6_null_entry->dst.dev = dev;
5457                 net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
5458 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5459                 net->ipv6.ip6_prohibit_entry->dst.dev = dev;
5460                 net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
5461                 net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
5462                 net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
5463 #endif
5464          } else if (event == NETDEV_UNREGISTER &&
5465                     dev->reg_state != NETREG_UNREGISTERED) {
5466                 /* NETDEV_UNREGISTER could be fired for multiple times by
5467                  * netdev_wait_allrefs(). Make sure we only call this once.
5468                  */
5469                 in6_dev_put_clear(&net->ipv6.ip6_null_entry->rt6i_idev);
5470 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5471                 in6_dev_put_clear(&net->ipv6.ip6_prohibit_entry->rt6i_idev);
5472                 in6_dev_put_clear(&net->ipv6.ip6_blk_hole_entry->rt6i_idev);
5473 #endif
5474         }
5475
5476         return NOTIFY_OK;
5477 }
5478
5479 /*
5480  *      /proc
5481  */
5482
5483 #ifdef CONFIG_PROC_FS
5484 static int rt6_stats_seq_show(struct seq_file *seq, void *v)
5485 {
5486         struct net *net = (struct net *)seq->private;
5487         seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
5488                    net->ipv6.rt6_stats->fib_nodes,
5489                    net->ipv6.rt6_stats->fib_route_nodes,
5490                    atomic_read(&net->ipv6.rt6_stats->fib_rt_alloc),
5491                    net->ipv6.rt6_stats->fib_rt_entries,
5492                    net->ipv6.rt6_stats->fib_rt_cache,
5493                    dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
5494                    net->ipv6.rt6_stats->fib_discarded_routes);
5495
5496         return 0;
5497 }
5498 #endif  /* CONFIG_PROC_FS */
5499
5500 #ifdef CONFIG_SYSCTL
5501
5502 static
5503 int ipv6_sysctl_rtcache_flush(struct ctl_table *ctl, int write,
5504                               void __user *buffer, size_t *lenp, loff_t *ppos)
5505 {
5506         struct net *net;
5507         int delay;
5508         int ret;
5509         if (!write)
5510                 return -EINVAL;
5511
5512         net = (struct net *)ctl->extra1;
5513         delay = net->ipv6.sysctl.flush_delay;
5514         ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
5515         if (ret)
5516                 return ret;
5517
5518         fib6_run_gc(delay <= 0 ? 0 : (unsigned long)delay, net, delay > 0);
5519         return 0;
5520 }
5521
5522 static int zero;
5523 static int one = 1;
5524
5525 static struct ctl_table ipv6_route_table_template[] = {
5526         {
5527                 .procname       =       "flush",
5528                 .data           =       &init_net.ipv6.sysctl.flush_delay,
5529                 .maxlen         =       sizeof(int),
5530                 .mode           =       0200,
5531                 .proc_handler   =       ipv6_sysctl_rtcache_flush
5532         },
5533         {
5534                 .procname       =       "gc_thresh",
5535                 .data           =       &ip6_dst_ops_template.gc_thresh,
5536                 .maxlen         =       sizeof(int),
5537                 .mode           =       0644,
5538                 .proc_handler   =       proc_dointvec,
5539         },
5540         {
5541                 .procname       =       "max_size",
5542                 .data           =       &init_net.ipv6.sysctl.ip6_rt_max_size,
5543                 .maxlen         =       sizeof(int),
5544                 .mode           =       0644,
5545                 .proc_handler   =       proc_dointvec,
5546         },
5547         {
5548                 .procname       =       "gc_min_interval",
5549                 .data           =       &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
5550                 .maxlen         =       sizeof(int),
5551                 .mode           =       0644,
5552                 .proc_handler   =       proc_dointvec_jiffies,
5553         },
5554         {
5555                 .procname       =       "gc_timeout",
5556                 .data           =       &init_net.ipv6.sysctl.ip6_rt_gc_timeout,
5557                 .maxlen         =       sizeof(int),
5558                 .mode           =       0644,
5559                 .proc_handler   =       proc_dointvec_jiffies,
5560         },
5561         {
5562                 .procname       =       "gc_interval",
5563                 .data           =       &init_net.ipv6.sysctl.ip6_rt_gc_interval,
5564                 .maxlen         =       sizeof(int),
5565                 .mode           =       0644,
5566                 .proc_handler   =       proc_dointvec_jiffies,
5567         },
5568         {
5569                 .procname       =       "gc_elasticity",
5570                 .data           =       &init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
5571                 .maxlen         =       sizeof(int),
5572                 .mode           =       0644,
5573                 .proc_handler   =       proc_dointvec,
5574         },
5575         {
5576                 .procname       =       "mtu_expires",
5577                 .data           =       &init_net.ipv6.sysctl.ip6_rt_mtu_expires,
5578                 .maxlen         =       sizeof(int),
5579                 .mode           =       0644,
5580                 .proc_handler   =       proc_dointvec_jiffies,
5581         },
5582         {
5583                 .procname       =       "min_adv_mss",
5584                 .data           =       &init_net.ipv6.sysctl.ip6_rt_min_advmss,
5585                 .maxlen         =       sizeof(int),
5586                 .mode           =       0644,
5587                 .proc_handler   =       proc_dointvec,
5588         },
5589         {
5590                 .procname       =       "gc_min_interval_ms",
5591                 .data           =       &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
5592                 .maxlen         =       sizeof(int),
5593                 .mode           =       0644,
5594                 .proc_handler   =       proc_dointvec_ms_jiffies,
5595         },
5596         {
5597                 .procname       =       "skip_notify_on_dev_down",
5598                 .data           =       &init_net.ipv6.sysctl.skip_notify_on_dev_down,
5599                 .maxlen         =       sizeof(int),
5600                 .mode           =       0644,
5601                 .proc_handler   =       proc_dointvec,
5602                 .extra1         =       &zero,
5603                 .extra2         =       &one,
5604         },
5605         { }
5606 };
5607
5608 struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
5609 {
5610         struct ctl_table *table;
5611
5612         table = kmemdup(ipv6_route_table_template,
5613                         sizeof(ipv6_route_table_template),
5614                         GFP_KERNEL);
5615
5616         if (table) {
5617                 table[0].data = &net->ipv6.sysctl.flush_delay;
5618                 table[0].extra1 = net;
5619                 table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
5620                 table[2].data = &net->ipv6.sysctl.ip6_rt_max_size;
5621                 table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
5622                 table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
5623                 table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
5624                 table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
5625                 table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
5626                 table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
5627                 table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
5628                 table[10].data = &net->ipv6.sysctl.skip_notify_on_dev_down;
5629
5630                 /* Don't export sysctls to unprivileged users */
5631                 if (net->user_ns != &init_user_ns)
5632                         table[0].procname = NULL;
5633         }
5634
5635         return table;
5636 }
5637 #endif
5638
5639 static int __net_init ip6_route_net_init(struct net *net)
5640 {
5641         int ret = -ENOMEM;
5642
5643         memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
5644                sizeof(net->ipv6.ip6_dst_ops));
5645
5646         if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
5647                 goto out_ip6_dst_ops;
5648
5649         net->ipv6.fib6_null_entry = fib6_info_alloc(GFP_KERNEL, true);
5650         if (!net->ipv6.fib6_null_entry)
5651                 goto out_ip6_dst_entries;
5652         memcpy(net->ipv6.fib6_null_entry, &fib6_null_entry_template,
5653                sizeof(*net->ipv6.fib6_null_entry));
5654
5655         net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
5656                                            sizeof(*net->ipv6.ip6_null_entry),
5657                                            GFP_KERNEL);
5658         if (!net->ipv6.ip6_null_entry)
5659                 goto out_fib6_null_entry;
5660         net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
5661         dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
5662                          ip6_template_metrics, true);
5663
5664 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5665         net->ipv6.fib6_has_custom_rules = false;
5666         net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
5667                                                sizeof(*net->ipv6.ip6_prohibit_entry),
5668                                                GFP_KERNEL);
5669         if (!net->ipv6.ip6_prohibit_entry)
5670                 goto out_ip6_null_entry;
5671         net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
5672         dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
5673                          ip6_template_metrics, true);
5674
5675         net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
5676                                                sizeof(*net->ipv6.ip6_blk_hole_entry),
5677                                                GFP_KERNEL);
5678         if (!net->ipv6.ip6_blk_hole_entry)
5679                 goto out_ip6_prohibit_entry;
5680         net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
5681         dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
5682                          ip6_template_metrics, true);
5683 #endif
5684
5685         net->ipv6.sysctl.flush_delay = 0;
5686         net->ipv6.sysctl.ip6_rt_max_size = 4096;
5687         net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
5688         net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
5689         net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
5690         net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
5691         net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
5692         net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
5693         net->ipv6.sysctl.skip_notify_on_dev_down = 0;
5694
5695         net->ipv6.ip6_rt_gc_expire = 30*HZ;
5696
5697         ret = 0;
5698 out:
5699         return ret;
5700
5701 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5702 out_ip6_prohibit_entry:
5703         kfree(net->ipv6.ip6_prohibit_entry);
5704 out_ip6_null_entry:
5705         kfree(net->ipv6.ip6_null_entry);
5706 #endif
5707 out_fib6_null_entry:
5708         kfree(net->ipv6.fib6_null_entry);
5709 out_ip6_dst_entries:
5710         dst_entries_destroy(&net->ipv6.ip6_dst_ops);
5711 out_ip6_dst_ops:
5712         goto out;
5713 }
5714
5715 static void __net_exit ip6_route_net_exit(struct net *net)
5716 {
5717         kfree(net->ipv6.fib6_null_entry);
5718         kfree(net->ipv6.ip6_null_entry);
5719 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5720         kfree(net->ipv6.ip6_prohibit_entry);
5721         kfree(net->ipv6.ip6_blk_hole_entry);
5722 #endif
5723         dst_entries_destroy(&net->ipv6.ip6_dst_ops);
5724 }
5725
5726 static int __net_init ip6_route_net_init_late(struct net *net)
5727 {
5728 #ifdef CONFIG_PROC_FS
5729         proc_create_net("ipv6_route", 0, net->proc_net, &ipv6_route_seq_ops,
5730                         sizeof(struct ipv6_route_iter));
5731         proc_create_net_single("rt6_stats", 0444, net->proc_net,
5732                         rt6_stats_seq_show, NULL);
5733 #endif
5734         return 0;
5735 }
5736
5737 static void __net_exit ip6_route_net_exit_late(struct net *net)
5738 {
5739 #ifdef CONFIG_PROC_FS
5740         remove_proc_entry("ipv6_route", net->proc_net);
5741         remove_proc_entry("rt6_stats", net->proc_net);
5742 #endif
5743 }
5744
5745 static struct pernet_operations ip6_route_net_ops = {
5746         .init = ip6_route_net_init,
5747         .exit = ip6_route_net_exit,
5748 };
5749
5750 static int __net_init ipv6_inetpeer_init(struct net *net)
5751 {
5752         struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
5753
5754         if (!bp)
5755                 return -ENOMEM;
5756         inet_peer_base_init(bp);
5757         net->ipv6.peers = bp;
5758         return 0;
5759 }
5760
5761 static void __net_exit ipv6_inetpeer_exit(struct net *net)
5762 {
5763         struct inet_peer_base *bp = net->ipv6.peers;
5764
5765         net->ipv6.peers = NULL;
5766         inetpeer_invalidate_tree(bp);
5767         kfree(bp);
5768 }
5769
5770 static struct pernet_operations ipv6_inetpeer_ops = {
5771         .init   =       ipv6_inetpeer_init,
5772         .exit   =       ipv6_inetpeer_exit,
5773 };
5774
5775 static struct pernet_operations ip6_route_net_late_ops = {
5776         .init = ip6_route_net_init_late,
5777         .exit = ip6_route_net_exit_late,
5778 };
5779
5780 static struct notifier_block ip6_route_dev_notifier = {
5781         .notifier_call = ip6_route_dev_notify,
5782         .priority = ADDRCONF_NOTIFY_PRIORITY - 10,
5783 };
5784
5785 void __init ip6_route_init_special_entries(void)
5786 {
5787         /* Registering of the loopback is done before this portion of code,
5788          * the loopback reference in rt6_info will not be taken, do it
5789          * manually for init_net */
5790         init_net.ipv6.fib6_null_entry->fib6_nh->fib_nh_dev = init_net.loopback_dev;
5791         init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
5792         init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
5793   #ifdef CONFIG_IPV6_MULTIPLE_TABLES
5794         init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
5795         init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
5796         init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
5797         init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
5798   #endif
5799 }
5800
5801 int __init ip6_route_init(void)
5802 {
5803         int ret;
5804         int cpu;
5805
5806         ret = -ENOMEM;
5807         ip6_dst_ops_template.kmem_cachep =
5808                 kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
5809                                   SLAB_HWCACHE_ALIGN, NULL);
5810         if (!ip6_dst_ops_template.kmem_cachep)
5811                 goto out;
5812
5813         ret = dst_entries_init(&ip6_dst_blackhole_ops);
5814         if (ret)
5815                 goto out_kmem_cache;
5816
5817         ret = register_pernet_subsys(&ipv6_inetpeer_ops);
5818         if (ret)
5819                 goto out_dst_entries;
5820
5821         ret = register_pernet_subsys(&ip6_route_net_ops);
5822         if (ret)
5823                 goto out_register_inetpeer;
5824
5825         ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
5826
5827         ret = fib6_init();
5828         if (ret)
5829                 goto out_register_subsys;
5830
5831         ret = xfrm6_init();
5832         if (ret)
5833                 goto out_fib6_init;
5834
5835         ret = fib6_rules_init();
5836         if (ret)
5837                 goto xfrm6_init;
5838
5839         ret = register_pernet_subsys(&ip6_route_net_late_ops);
5840         if (ret)
5841                 goto fib6_rules_init;
5842
5843         ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_NEWROUTE,
5844                                    inet6_rtm_newroute, NULL, 0);
5845         if (ret < 0)
5846                 goto out_register_late_subsys;
5847
5848         ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_DELROUTE,
5849                                    inet6_rtm_delroute, NULL, 0);
5850         if (ret < 0)
5851                 goto out_register_late_subsys;
5852
5853         ret = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETROUTE,
5854                                    inet6_rtm_getroute, NULL,
5855                                    RTNL_FLAG_DOIT_UNLOCKED);
5856         if (ret < 0)
5857                 goto out_register_late_subsys;
5858
5859         ret = register_netdevice_notifier(&ip6_route_dev_notifier);
5860         if (ret)
5861                 goto out_register_late_subsys;
5862
5863         for_each_possible_cpu(cpu) {
5864                 struct uncached_list *ul = per_cpu_ptr(&rt6_uncached_list, cpu);
5865
5866                 INIT_LIST_HEAD(&ul->head);
5867                 spin_lock_init(&ul->lock);
5868         }
5869
5870 out:
5871         return ret;
5872
5873 out_register_late_subsys:
5874         rtnl_unregister_all(PF_INET6);
5875         unregister_pernet_subsys(&ip6_route_net_late_ops);
5876 fib6_rules_init:
5877         fib6_rules_cleanup();
5878 xfrm6_init:
5879         xfrm6_fini();
5880 out_fib6_init:
5881         fib6_gc_cleanup();
5882 out_register_subsys:
5883         unregister_pernet_subsys(&ip6_route_net_ops);
5884 out_register_inetpeer:
5885         unregister_pernet_subsys(&ipv6_inetpeer_ops);
5886 out_dst_entries:
5887         dst_entries_destroy(&ip6_dst_blackhole_ops);
5888 out_kmem_cache:
5889         kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
5890         goto out;
5891 }
5892
5893 void ip6_route_cleanup(void)
5894 {
5895         unregister_netdevice_notifier(&ip6_route_dev_notifier);
5896         unregister_pernet_subsys(&ip6_route_net_late_ops);
5897         fib6_rules_cleanup();
5898         xfrm6_fini();
5899         fib6_gc_cleanup();
5900         unregister_pernet_subsys(&ipv6_inetpeer_ops);
5901         unregister_pernet_subsys(&ip6_route_net_ops);
5902         dst_entries_destroy(&ip6_dst_blackhole_ops);
5903         kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
5904 }