250af6e5a8922f0a9544aa00f35e164f9bcca0fd
[platform/kernel/linux-rpi.git] / net / ipv4 / fib_semantics.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET         An implementation of the TCP/IP protocol suite for the LINUX
4  *              operating system.  INET is implemented using the  BSD Socket
5  *              interface as the means of communication with the user level.
6  *
7  *              IPv4 Forwarding Information Base: semantics.
8  *
9  * Authors:     Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  */
11
12 #include <linux/uaccess.h>
13 #include <linux/bitops.h>
14 #include <linux/types.h>
15 #include <linux/kernel.h>
16 #include <linux/jiffies.h>
17 #include <linux/mm.h>
18 #include <linux/string.h>
19 #include <linux/socket.h>
20 #include <linux/sockios.h>
21 #include <linux/errno.h>
22 #include <linux/in.h>
23 #include <linux/inet.h>
24 #include <linux/inetdevice.h>
25 #include <linux/netdevice.h>
26 #include <linux/if_arp.h>
27 #include <linux/proc_fs.h>
28 #include <linux/skbuff.h>
29 #include <linux/init.h>
30 #include <linux/slab.h>
31 #include <linux/netlink.h>
32 #include <linux/hash.h>
33
34 #include <net/arp.h>
35 #include <net/ip.h>
36 #include <net/protocol.h>
37 #include <net/route.h>
38 #include <net/tcp.h>
39 #include <net/sock.h>
40 #include <net/ip_fib.h>
41 #include <net/ip6_fib.h>
42 #include <net/nexthop.h>
43 #include <net/netlink.h>
44 #include <net/rtnh.h>
45 #include <net/lwtunnel.h>
46 #include <net/fib_notifier.h>
47 #include <net/addrconf.h>
48
49 #include "fib_lookup.h"
50
51 static DEFINE_SPINLOCK(fib_info_lock);
52 static struct hlist_head *fib_info_hash;
53 static struct hlist_head *fib_info_laddrhash;
54 static unsigned int fib_info_hash_size;
55 static unsigned int fib_info_cnt;
56
57 #define DEVINDEX_HASHBITS 8
58 #define DEVINDEX_HASHSIZE (1U << DEVINDEX_HASHBITS)
59 static struct hlist_head fib_info_devhash[DEVINDEX_HASHSIZE];
60
61 /* for_nexthops and change_nexthops only used when nexthop object
62  * is not set in a fib_info. The logic within can reference fib_nh.
63  */
64 #ifdef CONFIG_IP_ROUTE_MULTIPATH
65
66 #define for_nexthops(fi) {                                              \
67         int nhsel; const struct fib_nh *nh;                             \
68         for (nhsel = 0, nh = (fi)->fib_nh;                              \
69              nhsel < fib_info_num_path((fi));                           \
70              nh++, nhsel++)
71
72 #define change_nexthops(fi) {                                           \
73         int nhsel; struct fib_nh *nexthop_nh;                           \
74         for (nhsel = 0, nexthop_nh = (struct fib_nh *)((fi)->fib_nh);   \
75              nhsel < fib_info_num_path((fi));                           \
76              nexthop_nh++, nhsel++)
77
78 #else /* CONFIG_IP_ROUTE_MULTIPATH */
79
80 /* Hope, that gcc will optimize it to get rid of dummy loop */
81
82 #define for_nexthops(fi) {                                              \
83         int nhsel; const struct fib_nh *nh = (fi)->fib_nh;              \
84         for (nhsel = 0; nhsel < 1; nhsel++)
85
86 #define change_nexthops(fi) {                                           \
87         int nhsel;                                                      \
88         struct fib_nh *nexthop_nh = (struct fib_nh *)((fi)->fib_nh);    \
89         for (nhsel = 0; nhsel < 1; nhsel++)
90
91 #endif /* CONFIG_IP_ROUTE_MULTIPATH */
92
93 #define endfor_nexthops(fi) }
94
95
96 const struct fib_prop fib_props[RTN_MAX + 1] = {
97         [RTN_UNSPEC] = {
98                 .error  = 0,
99                 .scope  = RT_SCOPE_NOWHERE,
100         },
101         [RTN_UNICAST] = {
102                 .error  = 0,
103                 .scope  = RT_SCOPE_UNIVERSE,
104         },
105         [RTN_LOCAL] = {
106                 .error  = 0,
107                 .scope  = RT_SCOPE_HOST,
108         },
109         [RTN_BROADCAST] = {
110                 .error  = 0,
111                 .scope  = RT_SCOPE_LINK,
112         },
113         [RTN_ANYCAST] = {
114                 .error  = 0,
115                 .scope  = RT_SCOPE_LINK,
116         },
117         [RTN_MULTICAST] = {
118                 .error  = 0,
119                 .scope  = RT_SCOPE_UNIVERSE,
120         },
121         [RTN_BLACKHOLE] = {
122                 .error  = -EINVAL,
123                 .scope  = RT_SCOPE_UNIVERSE,
124         },
125         [RTN_UNREACHABLE] = {
126                 .error  = -EHOSTUNREACH,
127                 .scope  = RT_SCOPE_UNIVERSE,
128         },
129         [RTN_PROHIBIT] = {
130                 .error  = -EACCES,
131                 .scope  = RT_SCOPE_UNIVERSE,
132         },
133         [RTN_THROW] = {
134                 .error  = -EAGAIN,
135                 .scope  = RT_SCOPE_UNIVERSE,
136         },
137         [RTN_NAT] = {
138                 .error  = -EINVAL,
139                 .scope  = RT_SCOPE_NOWHERE,
140         },
141         [RTN_XRESOLVE] = {
142                 .error  = -EINVAL,
143                 .scope  = RT_SCOPE_NOWHERE,
144         },
145 };
146
147 static void rt_fibinfo_free(struct rtable __rcu **rtp)
148 {
149         struct rtable *rt = rcu_dereference_protected(*rtp, 1);
150
151         if (!rt)
152                 return;
153
154         /* Not even needed : RCU_INIT_POINTER(*rtp, NULL);
155          * because we waited an RCU grace period before calling
156          * free_fib_info_rcu()
157          */
158
159         dst_dev_put(&rt->dst);
160         dst_release_immediate(&rt->dst);
161 }
162
163 static void free_nh_exceptions(struct fib_nh_common *nhc)
164 {
165         struct fnhe_hash_bucket *hash;
166         int i;
167
168         hash = rcu_dereference_protected(nhc->nhc_exceptions, 1);
169         if (!hash)
170                 return;
171         for (i = 0; i < FNHE_HASH_SIZE; i++) {
172                 struct fib_nh_exception *fnhe;
173
174                 fnhe = rcu_dereference_protected(hash[i].chain, 1);
175                 while (fnhe) {
176                         struct fib_nh_exception *next;
177
178                         next = rcu_dereference_protected(fnhe->fnhe_next, 1);
179
180                         rt_fibinfo_free(&fnhe->fnhe_rth_input);
181                         rt_fibinfo_free(&fnhe->fnhe_rth_output);
182
183                         kfree(fnhe);
184
185                         fnhe = next;
186                 }
187         }
188         kfree(hash);
189 }
190
191 static void rt_fibinfo_free_cpus(struct rtable __rcu * __percpu *rtp)
192 {
193         int cpu;
194
195         if (!rtp)
196                 return;
197
198         for_each_possible_cpu(cpu) {
199                 struct rtable *rt;
200
201                 rt = rcu_dereference_protected(*per_cpu_ptr(rtp, cpu), 1);
202                 if (rt) {
203                         dst_dev_put(&rt->dst);
204                         dst_release_immediate(&rt->dst);
205                 }
206         }
207         free_percpu(rtp);
208 }
209
210 void fib_nh_common_release(struct fib_nh_common *nhc)
211 {
212         dev_put(nhc->nhc_dev);
213         lwtstate_put(nhc->nhc_lwtstate);
214         rt_fibinfo_free_cpus(nhc->nhc_pcpu_rth_output);
215         rt_fibinfo_free(&nhc->nhc_rth_input);
216         free_nh_exceptions(nhc);
217 }
218 EXPORT_SYMBOL_GPL(fib_nh_common_release);
219
220 void fib_nh_release(struct net *net, struct fib_nh *fib_nh)
221 {
222 #ifdef CONFIG_IP_ROUTE_CLASSID
223         if (fib_nh->nh_tclassid)
224                 atomic_dec(&net->ipv4.fib_num_tclassid_users);
225 #endif
226         fib_nh_common_release(&fib_nh->nh_common);
227 }
228
229 /* Release a nexthop info record */
230 static void free_fib_info_rcu(struct rcu_head *head)
231 {
232         struct fib_info *fi = container_of(head, struct fib_info, rcu);
233
234         if (fi->nh) {
235                 nexthop_put(fi->nh);
236         } else {
237                 change_nexthops(fi) {
238                         fib_nh_release(fi->fib_net, nexthop_nh);
239                 } endfor_nexthops(fi);
240         }
241
242         ip_fib_metrics_put(fi->fib_metrics);
243
244         kfree(fi);
245 }
246
247 void free_fib_info(struct fib_info *fi)
248 {
249         if (fi->fib_dead == 0) {
250                 pr_warn("Freeing alive fib_info %p\n", fi);
251                 return;
252         }
253
254         call_rcu(&fi->rcu, free_fib_info_rcu);
255 }
256 EXPORT_SYMBOL_GPL(free_fib_info);
257
258 void fib_release_info(struct fib_info *fi)
259 {
260         spin_lock_bh(&fib_info_lock);
261         if (fi && refcount_dec_and_test(&fi->fib_treeref)) {
262                 hlist_del(&fi->fib_hash);
263
264                 /* Paired with READ_ONCE() in fib_create_info(). */
265                 WRITE_ONCE(fib_info_cnt, fib_info_cnt - 1);
266
267                 if (fi->fib_prefsrc)
268                         hlist_del(&fi->fib_lhash);
269                 if (fi->nh) {
270                         list_del(&fi->nh_list);
271                 } else {
272                         change_nexthops(fi) {
273                                 if (!nexthop_nh->fib_nh_dev)
274                                         continue;
275                                 hlist_del(&nexthop_nh->nh_hash);
276                         } endfor_nexthops(fi)
277                 }
278                 fi->fib_dead = 1;
279                 fib_info_put(fi);
280         }
281         spin_unlock_bh(&fib_info_lock);
282 }
283
284 static inline int nh_comp(struct fib_info *fi, struct fib_info *ofi)
285 {
286         const struct fib_nh *onh;
287
288         if (fi->nh || ofi->nh)
289                 return nexthop_cmp(fi->nh, ofi->nh) ? 0 : -1;
290
291         if (ofi->fib_nhs == 0)
292                 return 0;
293
294         for_nexthops(fi) {
295                 onh = fib_info_nh(ofi, nhsel);
296
297                 if (nh->fib_nh_oif != onh->fib_nh_oif ||
298                     nh->fib_nh_gw_family != onh->fib_nh_gw_family ||
299                     nh->fib_nh_scope != onh->fib_nh_scope ||
300 #ifdef CONFIG_IP_ROUTE_MULTIPATH
301                     nh->fib_nh_weight != onh->fib_nh_weight ||
302 #endif
303 #ifdef CONFIG_IP_ROUTE_CLASSID
304                     nh->nh_tclassid != onh->nh_tclassid ||
305 #endif
306                     lwtunnel_cmp_encap(nh->fib_nh_lws, onh->fib_nh_lws) ||
307                     ((nh->fib_nh_flags ^ onh->fib_nh_flags) & ~RTNH_COMPARE_MASK))
308                         return -1;
309
310                 if (nh->fib_nh_gw_family == AF_INET &&
311                     nh->fib_nh_gw4 != onh->fib_nh_gw4)
312                         return -1;
313
314                 if (nh->fib_nh_gw_family == AF_INET6 &&
315                     ipv6_addr_cmp(&nh->fib_nh_gw6, &onh->fib_nh_gw6))
316                         return -1;
317         } endfor_nexthops(fi);
318         return 0;
319 }
320
321 static inline unsigned int fib_devindex_hashfn(unsigned int val)
322 {
323         return hash_32(val, DEVINDEX_HASHBITS);
324 }
325
326 static struct hlist_head *
327 fib_info_devhash_bucket(const struct net_device *dev)
328 {
329         u32 val = net_hash_mix(dev_net(dev)) ^ dev->ifindex;
330
331         return &fib_info_devhash[fib_devindex_hashfn(val)];
332 }
333
334 static unsigned int fib_info_hashfn_1(int init_val, u8 protocol, u8 scope,
335                                       u32 prefsrc, u32 priority)
336 {
337         unsigned int val = init_val;
338
339         val ^= (protocol << 8) | scope;
340         val ^= prefsrc;
341         val ^= priority;
342
343         return val;
344 }
345
346 static unsigned int fib_info_hashfn_result(unsigned int val)
347 {
348         unsigned int mask = (fib_info_hash_size - 1);
349
350         return (val ^ (val >> 7) ^ (val >> 12)) & mask;
351 }
352
353 static inline unsigned int fib_info_hashfn(struct fib_info *fi)
354 {
355         unsigned int val;
356
357         val = fib_info_hashfn_1(fi->fib_nhs, fi->fib_protocol,
358                                 fi->fib_scope, (__force u32)fi->fib_prefsrc,
359                                 fi->fib_priority);
360
361         if (fi->nh) {
362                 val ^= fib_devindex_hashfn(fi->nh->id);
363         } else {
364                 for_nexthops(fi) {
365                         val ^= fib_devindex_hashfn(nh->fib_nh_oif);
366                 } endfor_nexthops(fi)
367         }
368
369         return fib_info_hashfn_result(val);
370 }
371
372 /* no metrics, only nexthop id */
373 static struct fib_info *fib_find_info_nh(struct net *net,
374                                          const struct fib_config *cfg)
375 {
376         struct hlist_head *head;
377         struct fib_info *fi;
378         unsigned int hash;
379
380         hash = fib_info_hashfn_1(fib_devindex_hashfn(cfg->fc_nh_id),
381                                  cfg->fc_protocol, cfg->fc_scope,
382                                  (__force u32)cfg->fc_prefsrc,
383                                  cfg->fc_priority);
384         hash = fib_info_hashfn_result(hash);
385         head = &fib_info_hash[hash];
386
387         hlist_for_each_entry(fi, head, fib_hash) {
388                 if (!net_eq(fi->fib_net, net))
389                         continue;
390                 if (!fi->nh || fi->nh->id != cfg->fc_nh_id)
391                         continue;
392                 if (cfg->fc_protocol == fi->fib_protocol &&
393                     cfg->fc_scope == fi->fib_scope &&
394                     cfg->fc_prefsrc == fi->fib_prefsrc &&
395                     cfg->fc_priority == fi->fib_priority &&
396                     cfg->fc_type == fi->fib_type &&
397                     cfg->fc_table == fi->fib_tb_id &&
398                     !((cfg->fc_flags ^ fi->fib_flags) & ~RTNH_COMPARE_MASK))
399                         return fi;
400         }
401
402         return NULL;
403 }
404
405 static struct fib_info *fib_find_info(struct fib_info *nfi)
406 {
407         struct hlist_head *head;
408         struct fib_info *fi;
409         unsigned int hash;
410
411         hash = fib_info_hashfn(nfi);
412         head = &fib_info_hash[hash];
413
414         hlist_for_each_entry(fi, head, fib_hash) {
415                 if (!net_eq(fi->fib_net, nfi->fib_net))
416                         continue;
417                 if (fi->fib_nhs != nfi->fib_nhs)
418                         continue;
419                 if (nfi->fib_protocol == fi->fib_protocol &&
420                     nfi->fib_scope == fi->fib_scope &&
421                     nfi->fib_prefsrc == fi->fib_prefsrc &&
422                     nfi->fib_priority == fi->fib_priority &&
423                     nfi->fib_type == fi->fib_type &&
424                     nfi->fib_tb_id == fi->fib_tb_id &&
425                     memcmp(nfi->fib_metrics, fi->fib_metrics,
426                            sizeof(u32) * RTAX_MAX) == 0 &&
427                     !((nfi->fib_flags ^ fi->fib_flags) & ~RTNH_COMPARE_MASK) &&
428                     nh_comp(fi, nfi) == 0)
429                         return fi;
430         }
431
432         return NULL;
433 }
434
435 /* Check, that the gateway is already configured.
436  * Used only by redirect accept routine.
437  */
438 int ip_fib_check_default(__be32 gw, struct net_device *dev)
439 {
440         struct hlist_head *head;
441         struct fib_nh *nh;
442
443         spin_lock(&fib_info_lock);
444
445         head = fib_info_devhash_bucket(dev);
446
447         hlist_for_each_entry(nh, head, nh_hash) {
448                 if (nh->fib_nh_dev == dev &&
449                     nh->fib_nh_gw4 == gw &&
450                     !(nh->fib_nh_flags & RTNH_F_DEAD)) {
451                         spin_unlock(&fib_info_lock);
452                         return 0;
453                 }
454         }
455
456         spin_unlock(&fib_info_lock);
457
458         return -1;
459 }
460
461 size_t fib_nlmsg_size(struct fib_info *fi)
462 {
463         size_t payload = NLMSG_ALIGN(sizeof(struct rtmsg))
464                          + nla_total_size(4) /* RTA_TABLE */
465                          + nla_total_size(4) /* RTA_DST */
466                          + nla_total_size(4) /* RTA_PRIORITY */
467                          + nla_total_size(4) /* RTA_PREFSRC */
468                          + nla_total_size(TCP_CA_NAME_MAX); /* RTAX_CC_ALGO */
469         unsigned int nhs = fib_info_num_path(fi);
470
471         /* space for nested metrics */
472         payload += nla_total_size((RTAX_MAX * nla_total_size(4)));
473
474         if (fi->nh)
475                 payload += nla_total_size(4); /* RTA_NH_ID */
476
477         if (nhs) {
478                 size_t nh_encapsize = 0;
479                 /* Also handles the special case nhs == 1 */
480
481                 /* each nexthop is packed in an attribute */
482                 size_t nhsize = nla_total_size(sizeof(struct rtnexthop));
483                 unsigned int i;
484
485                 /* may contain flow and gateway attribute */
486                 nhsize += 2 * nla_total_size(4);
487
488                 /* grab encap info */
489                 for (i = 0; i < fib_info_num_path(fi); i++) {
490                         struct fib_nh_common *nhc = fib_info_nhc(fi, i);
491
492                         if (nhc->nhc_lwtstate) {
493                                 /* RTA_ENCAP_TYPE */
494                                 nh_encapsize += lwtunnel_get_encap_size(
495                                                 nhc->nhc_lwtstate);
496                                 /* RTA_ENCAP */
497                                 nh_encapsize +=  nla_total_size(2);
498                         }
499                 }
500
501                 /* all nexthops are packed in a nested attribute */
502                 payload += nla_total_size((nhs * nhsize) + nh_encapsize);
503
504         }
505
506         return payload;
507 }
508
509 void rtmsg_fib(int event, __be32 key, struct fib_alias *fa,
510                int dst_len, u32 tb_id, const struct nl_info *info,
511                unsigned int nlm_flags)
512 {
513         struct fib_rt_info fri;
514         struct sk_buff *skb;
515         u32 seq = info->nlh ? info->nlh->nlmsg_seq : 0;
516         int err = -ENOBUFS;
517
518         skb = nlmsg_new(fib_nlmsg_size(fa->fa_info), GFP_KERNEL);
519         if (!skb)
520                 goto errout;
521
522         fri.fi = fa->fa_info;
523         fri.tb_id = tb_id;
524         fri.dst = key;
525         fri.dst_len = dst_len;
526         fri.tos = fa->fa_tos;
527         fri.type = fa->fa_type;
528         fri.offload = READ_ONCE(fa->offload);
529         fri.trap = READ_ONCE(fa->trap);
530         fri.offload_failed = READ_ONCE(fa->offload_failed);
531         err = fib_dump_info(skb, info->portid, seq, event, &fri, nlm_flags);
532         if (err < 0) {
533                 /* -EMSGSIZE implies BUG in fib_nlmsg_size() */
534                 WARN_ON(err == -EMSGSIZE);
535                 kfree_skb(skb);
536                 goto errout;
537         }
538         rtnl_notify(skb, info->nl_net, info->portid, RTNLGRP_IPV4_ROUTE,
539                     info->nlh, GFP_KERNEL);
540         return;
541 errout:
542         if (err < 0)
543                 rtnl_set_sk_err(info->nl_net, RTNLGRP_IPV4_ROUTE, err);
544 }
545
546 static int fib_detect_death(struct fib_info *fi, int order,
547                             struct fib_info **last_resort, int *last_idx,
548                             int dflt)
549 {
550         const struct fib_nh_common *nhc = fib_info_nhc(fi, 0);
551         struct neighbour *n;
552         int state = NUD_NONE;
553
554         if (likely(nhc->nhc_gw_family == AF_INET))
555                 n = neigh_lookup(&arp_tbl, &nhc->nhc_gw.ipv4, nhc->nhc_dev);
556         else if (nhc->nhc_gw_family == AF_INET6)
557                 n = neigh_lookup(ipv6_stub->nd_tbl, &nhc->nhc_gw.ipv6,
558                                  nhc->nhc_dev);
559         else
560                 n = NULL;
561
562         if (n) {
563                 state = n->nud_state;
564                 neigh_release(n);
565         } else {
566                 return 0;
567         }
568         if (state == NUD_REACHABLE)
569                 return 0;
570         if ((state & NUD_VALID) && order != dflt)
571                 return 0;
572         if ((state & NUD_VALID) ||
573             (*last_idx < 0 && order > dflt && state != NUD_INCOMPLETE)) {
574                 *last_resort = fi;
575                 *last_idx = order;
576         }
577         return 1;
578 }
579
580 int fib_nh_common_init(struct net *net, struct fib_nh_common *nhc,
581                        struct nlattr *encap, u16 encap_type,
582                        void *cfg, gfp_t gfp_flags,
583                        struct netlink_ext_ack *extack)
584 {
585         int err;
586
587         nhc->nhc_pcpu_rth_output = alloc_percpu_gfp(struct rtable __rcu *,
588                                                     gfp_flags);
589         if (!nhc->nhc_pcpu_rth_output)
590                 return -ENOMEM;
591
592         if (encap) {
593                 struct lwtunnel_state *lwtstate;
594
595                 if (encap_type == LWTUNNEL_ENCAP_NONE) {
596                         NL_SET_ERR_MSG(extack, "LWT encap type not specified");
597                         err = -EINVAL;
598                         goto lwt_failure;
599                 }
600                 err = lwtunnel_build_state(net, encap_type, encap,
601                                            nhc->nhc_family, cfg, &lwtstate,
602                                            extack);
603                 if (err)
604                         goto lwt_failure;
605
606                 nhc->nhc_lwtstate = lwtstate_get(lwtstate);
607         }
608
609         return 0;
610
611 lwt_failure:
612         rt_fibinfo_free_cpus(nhc->nhc_pcpu_rth_output);
613         nhc->nhc_pcpu_rth_output = NULL;
614         return err;
615 }
616 EXPORT_SYMBOL_GPL(fib_nh_common_init);
617
618 int fib_nh_init(struct net *net, struct fib_nh *nh,
619                 struct fib_config *cfg, int nh_weight,
620                 struct netlink_ext_ack *extack)
621 {
622         int err;
623
624         nh->fib_nh_family = AF_INET;
625
626         err = fib_nh_common_init(net, &nh->nh_common, cfg->fc_encap,
627                                  cfg->fc_encap_type, cfg, GFP_KERNEL, extack);
628         if (err)
629                 return err;
630
631         nh->fib_nh_oif = cfg->fc_oif;
632         nh->fib_nh_gw_family = cfg->fc_gw_family;
633         if (cfg->fc_gw_family == AF_INET)
634                 nh->fib_nh_gw4 = cfg->fc_gw4;
635         else if (cfg->fc_gw_family == AF_INET6)
636                 nh->fib_nh_gw6 = cfg->fc_gw6;
637
638         nh->fib_nh_flags = cfg->fc_flags;
639
640 #ifdef CONFIG_IP_ROUTE_CLASSID
641         nh->nh_tclassid = cfg->fc_flow;
642         if (nh->nh_tclassid)
643                 atomic_inc(&net->ipv4.fib_num_tclassid_users);
644 #endif
645 #ifdef CONFIG_IP_ROUTE_MULTIPATH
646         nh->fib_nh_weight = nh_weight;
647 #endif
648         return 0;
649 }
650
651 #ifdef CONFIG_IP_ROUTE_MULTIPATH
652
653 static int fib_count_nexthops(struct rtnexthop *rtnh, int remaining,
654                               struct netlink_ext_ack *extack)
655 {
656         int nhs = 0;
657
658         while (rtnh_ok(rtnh, remaining)) {
659                 nhs++;
660                 rtnh = rtnh_next(rtnh, &remaining);
661         }
662
663         /* leftover implies invalid nexthop configuration, discard it */
664         if (remaining > 0) {
665                 NL_SET_ERR_MSG(extack,
666                                "Invalid nexthop configuration - extra data after nexthops");
667                 nhs = 0;
668         }
669
670         return nhs;
671 }
672
673 static int fib_gw_from_attr(__be32 *gw, struct nlattr *nla,
674                             struct netlink_ext_ack *extack)
675 {
676         if (nla_len(nla) < sizeof(*gw)) {
677                 NL_SET_ERR_MSG(extack, "Invalid IPv4 address in RTA_GATEWAY");
678                 return -EINVAL;
679         }
680
681         *gw = nla_get_in_addr(nla);
682
683         return 0;
684 }
685
686 /* only called when fib_nh is integrated into fib_info */
687 static int fib_get_nhs(struct fib_info *fi, struct rtnexthop *rtnh,
688                        int remaining, struct fib_config *cfg,
689                        struct netlink_ext_ack *extack)
690 {
691         struct net *net = fi->fib_net;
692         struct fib_config fib_cfg;
693         struct fib_nh *nh;
694         int ret;
695
696         change_nexthops(fi) {
697                 int attrlen;
698
699                 memset(&fib_cfg, 0, sizeof(fib_cfg));
700
701                 if (!rtnh_ok(rtnh, remaining)) {
702                         NL_SET_ERR_MSG(extack,
703                                        "Invalid nexthop configuration - extra data after nexthop");
704                         return -EINVAL;
705                 }
706
707                 if (rtnh->rtnh_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN)) {
708                         NL_SET_ERR_MSG(extack,
709                                        "Invalid flags for nexthop - can not contain DEAD or LINKDOWN");
710                         return -EINVAL;
711                 }
712
713                 fib_cfg.fc_flags = (cfg->fc_flags & ~0xFF) | rtnh->rtnh_flags;
714                 fib_cfg.fc_oif = rtnh->rtnh_ifindex;
715
716                 attrlen = rtnh_attrlen(rtnh);
717                 if (attrlen > 0) {
718                         struct nlattr *nla, *nlav, *attrs = rtnh_attrs(rtnh);
719
720                         nla = nla_find(attrs, attrlen, RTA_GATEWAY);
721                         nlav = nla_find(attrs, attrlen, RTA_VIA);
722                         if (nla && nlav) {
723                                 NL_SET_ERR_MSG(extack,
724                                                "Nexthop configuration can not contain both GATEWAY and VIA");
725                                 return -EINVAL;
726                         }
727                         if (nla) {
728                                 ret = fib_gw_from_attr(&fib_cfg.fc_gw4, nla,
729                                                        extack);
730                                 if (ret)
731                                         goto errout;
732
733                                 if (fib_cfg.fc_gw4)
734                                         fib_cfg.fc_gw_family = AF_INET;
735                         } else if (nlav) {
736                                 ret = fib_gw_from_via(&fib_cfg, nlav, extack);
737                                 if (ret)
738                                         goto errout;
739                         }
740
741                         nla = nla_find(attrs, attrlen, RTA_FLOW);
742                         if (nla) {
743                                 if (nla_len(nla) < sizeof(u32)) {
744                                         NL_SET_ERR_MSG(extack, "Invalid RTA_FLOW");
745                                         return -EINVAL;
746                                 }
747                                 fib_cfg.fc_flow = nla_get_u32(nla);
748                         }
749
750                         fib_cfg.fc_encap = nla_find(attrs, attrlen, RTA_ENCAP);
751                         /* RTA_ENCAP_TYPE length checked in
752                          * lwtunnel_valid_encap_type_attr
753                          */
754                         nla = nla_find(attrs, attrlen, RTA_ENCAP_TYPE);
755                         if (nla)
756                                 fib_cfg.fc_encap_type = nla_get_u16(nla);
757                 }
758
759                 ret = fib_nh_init(net, nexthop_nh, &fib_cfg,
760                                   rtnh->rtnh_hops + 1, extack);
761                 if (ret)
762                         goto errout;
763
764                 rtnh = rtnh_next(rtnh, &remaining);
765         } endfor_nexthops(fi);
766
767         ret = -EINVAL;
768         nh = fib_info_nh(fi, 0);
769         if (cfg->fc_oif && nh->fib_nh_oif != cfg->fc_oif) {
770                 NL_SET_ERR_MSG(extack,
771                                "Nexthop device index does not match RTA_OIF");
772                 goto errout;
773         }
774         if (cfg->fc_gw_family) {
775                 if (cfg->fc_gw_family != nh->fib_nh_gw_family ||
776                     (cfg->fc_gw_family == AF_INET &&
777                      nh->fib_nh_gw4 != cfg->fc_gw4) ||
778                     (cfg->fc_gw_family == AF_INET6 &&
779                      ipv6_addr_cmp(&nh->fib_nh_gw6, &cfg->fc_gw6))) {
780                         NL_SET_ERR_MSG(extack,
781                                        "Nexthop gateway does not match RTA_GATEWAY or RTA_VIA");
782                         goto errout;
783                 }
784         }
785 #ifdef CONFIG_IP_ROUTE_CLASSID
786         if (cfg->fc_flow && nh->nh_tclassid != cfg->fc_flow) {
787                 NL_SET_ERR_MSG(extack,
788                                "Nexthop class id does not match RTA_FLOW");
789                 goto errout;
790         }
791 #endif
792         ret = 0;
793 errout:
794         return ret;
795 }
796
797 /* only called when fib_nh is integrated into fib_info */
798 static void fib_rebalance(struct fib_info *fi)
799 {
800         int total;
801         int w;
802
803         if (fib_info_num_path(fi) < 2)
804                 return;
805
806         total = 0;
807         for_nexthops(fi) {
808                 if (nh->fib_nh_flags & RTNH_F_DEAD)
809                         continue;
810
811                 if (ip_ignore_linkdown(nh->fib_nh_dev) &&
812                     nh->fib_nh_flags & RTNH_F_LINKDOWN)
813                         continue;
814
815                 total += nh->fib_nh_weight;
816         } endfor_nexthops(fi);
817
818         w = 0;
819         change_nexthops(fi) {
820                 int upper_bound;
821
822                 if (nexthop_nh->fib_nh_flags & RTNH_F_DEAD) {
823                         upper_bound = -1;
824                 } else if (ip_ignore_linkdown(nexthop_nh->fib_nh_dev) &&
825                            nexthop_nh->fib_nh_flags & RTNH_F_LINKDOWN) {
826                         upper_bound = -1;
827                 } else {
828                         w += nexthop_nh->fib_nh_weight;
829                         upper_bound = DIV_ROUND_CLOSEST_ULL((u64)w << 31,
830                                                             total) - 1;
831                 }
832
833                 atomic_set(&nexthop_nh->fib_nh_upper_bound, upper_bound);
834         } endfor_nexthops(fi);
835 }
836 #else /* CONFIG_IP_ROUTE_MULTIPATH */
837
838 static int fib_get_nhs(struct fib_info *fi, struct rtnexthop *rtnh,
839                        int remaining, struct fib_config *cfg,
840                        struct netlink_ext_ack *extack)
841 {
842         NL_SET_ERR_MSG(extack, "Multipath support not enabled in kernel");
843
844         return -EINVAL;
845 }
846
847 #define fib_rebalance(fi) do { } while (0)
848
849 #endif /* CONFIG_IP_ROUTE_MULTIPATH */
850
851 static int fib_encap_match(struct net *net, u16 encap_type,
852                            struct nlattr *encap,
853                            const struct fib_nh *nh,
854                            const struct fib_config *cfg,
855                            struct netlink_ext_ack *extack)
856 {
857         struct lwtunnel_state *lwtstate;
858         int ret, result = 0;
859
860         if (encap_type == LWTUNNEL_ENCAP_NONE)
861                 return 0;
862
863         ret = lwtunnel_build_state(net, encap_type, encap, AF_INET,
864                                    cfg, &lwtstate, extack);
865         if (!ret) {
866                 result = lwtunnel_cmp_encap(lwtstate, nh->fib_nh_lws);
867                 lwtstate_free(lwtstate);
868         }
869
870         return result;
871 }
872
873 int fib_nh_match(struct net *net, struct fib_config *cfg, struct fib_info *fi,
874                  struct netlink_ext_ack *extack)
875 {
876 #ifdef CONFIG_IP_ROUTE_MULTIPATH
877         struct rtnexthop *rtnh;
878         int remaining;
879 #endif
880
881         if (cfg->fc_priority && cfg->fc_priority != fi->fib_priority)
882                 return 1;
883
884         if (cfg->fc_nh_id) {
885                 if (fi->nh && cfg->fc_nh_id == fi->nh->id)
886                         return 0;
887                 return 1;
888         }
889
890         if (fi->nh) {
891                 if (cfg->fc_oif || cfg->fc_gw_family || cfg->fc_mp)
892                         return 1;
893                 return 0;
894         }
895
896         if (cfg->fc_oif || cfg->fc_gw_family) {
897                 struct fib_nh *nh;
898
899                 nh = fib_info_nh(fi, 0);
900                 if (cfg->fc_encap) {
901                         if (fib_encap_match(net, cfg->fc_encap_type,
902                                             cfg->fc_encap, nh, cfg, extack))
903                                 return 1;
904                 }
905 #ifdef CONFIG_IP_ROUTE_CLASSID
906                 if (cfg->fc_flow &&
907                     cfg->fc_flow != nh->nh_tclassid)
908                         return 1;
909 #endif
910                 if ((cfg->fc_oif && cfg->fc_oif != nh->fib_nh_oif) ||
911                     (cfg->fc_gw_family &&
912                      cfg->fc_gw_family != nh->fib_nh_gw_family))
913                         return 1;
914
915                 if (cfg->fc_gw_family == AF_INET &&
916                     cfg->fc_gw4 != nh->fib_nh_gw4)
917                         return 1;
918
919                 if (cfg->fc_gw_family == AF_INET6 &&
920                     ipv6_addr_cmp(&cfg->fc_gw6, &nh->fib_nh_gw6))
921                         return 1;
922
923                 return 0;
924         }
925
926 #ifdef CONFIG_IP_ROUTE_MULTIPATH
927         if (!cfg->fc_mp)
928                 return 0;
929
930         rtnh = cfg->fc_mp;
931         remaining = cfg->fc_mp_len;
932
933         for_nexthops(fi) {
934                 int attrlen;
935
936                 if (!rtnh_ok(rtnh, remaining))
937                         return -EINVAL;
938
939                 if (rtnh->rtnh_ifindex && rtnh->rtnh_ifindex != nh->fib_nh_oif)
940                         return 1;
941
942                 attrlen = rtnh_attrlen(rtnh);
943                 if (attrlen > 0) {
944                         struct nlattr *nla, *nlav, *attrs = rtnh_attrs(rtnh);
945                         int err;
946
947                         nla = nla_find(attrs, attrlen, RTA_GATEWAY);
948                         nlav = nla_find(attrs, attrlen, RTA_VIA);
949                         if (nla && nlav) {
950                                 NL_SET_ERR_MSG(extack,
951                                                "Nexthop configuration can not contain both GATEWAY and VIA");
952                                 return -EINVAL;
953                         }
954
955                         if (nla) {
956                                 __be32 gw;
957
958                                 err = fib_gw_from_attr(&gw, nla, extack);
959                                 if (err)
960                                         return err;
961
962                                 if (nh->fib_nh_gw_family != AF_INET ||
963                                     gw != nh->fib_nh_gw4)
964                                         return 1;
965                         } else if (nlav) {
966                                 struct fib_config cfg2;
967
968                                 err = fib_gw_from_via(&cfg2, nlav, extack);
969                                 if (err)
970                                         return err;
971
972                                 switch (nh->fib_nh_gw_family) {
973                                 case AF_INET:
974                                         if (cfg2.fc_gw_family != AF_INET ||
975                                             cfg2.fc_gw4 != nh->fib_nh_gw4)
976                                                 return 1;
977                                         break;
978                                 case AF_INET6:
979                                         if (cfg2.fc_gw_family != AF_INET6 ||
980                                             ipv6_addr_cmp(&cfg2.fc_gw6,
981                                                           &nh->fib_nh_gw6))
982                                                 return 1;
983                                         break;
984                                 }
985                         }
986
987 #ifdef CONFIG_IP_ROUTE_CLASSID
988                         nla = nla_find(attrs, attrlen, RTA_FLOW);
989                         if (nla) {
990                                 if (nla_len(nla) < sizeof(u32)) {
991                                         NL_SET_ERR_MSG(extack, "Invalid RTA_FLOW");
992                                         return -EINVAL;
993                                 }
994                                 if (nla_get_u32(nla) != nh->nh_tclassid)
995                                         return 1;
996                         }
997 #endif
998                 }
999
1000                 rtnh = rtnh_next(rtnh, &remaining);
1001         } endfor_nexthops(fi);
1002 #endif
1003         return 0;
1004 }
1005
1006 bool fib_metrics_match(struct fib_config *cfg, struct fib_info *fi)
1007 {
1008         struct nlattr *nla;
1009         int remaining;
1010
1011         if (!cfg->fc_mx)
1012                 return true;
1013
1014         nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
1015                 int type = nla_type(nla);
1016                 u32 fi_val, val;
1017
1018                 if (!type)
1019                         continue;
1020                 if (type > RTAX_MAX)
1021                         return false;
1022
1023                 if (type == RTAX_CC_ALGO) {
1024                         char tmp[TCP_CA_NAME_MAX];
1025                         bool ecn_ca = false;
1026
1027                         nla_strscpy(tmp, nla, sizeof(tmp));
1028                         val = tcp_ca_get_key_by_name(fi->fib_net, tmp, &ecn_ca);
1029                 } else {
1030                         if (nla_len(nla) != sizeof(u32))
1031                                 return false;
1032                         val = nla_get_u32(nla);
1033                 }
1034
1035                 fi_val = fi->fib_metrics->metrics[type - 1];
1036                 if (type == RTAX_FEATURES)
1037                         fi_val &= ~DST_FEATURE_ECN_CA;
1038
1039                 if (fi_val != val)
1040                         return false;
1041         }
1042
1043         return true;
1044 }
1045
1046 static int fib_check_nh_v6_gw(struct net *net, struct fib_nh *nh,
1047                               u32 table, struct netlink_ext_ack *extack)
1048 {
1049         struct fib6_config cfg = {
1050                 .fc_table = table,
1051                 .fc_flags = nh->fib_nh_flags | RTF_GATEWAY,
1052                 .fc_ifindex = nh->fib_nh_oif,
1053                 .fc_gateway = nh->fib_nh_gw6,
1054         };
1055         struct fib6_nh fib6_nh = {};
1056         int err;
1057
1058         err = ipv6_stub->fib6_nh_init(net, &fib6_nh, &cfg, GFP_KERNEL, extack);
1059         if (!err) {
1060                 nh->fib_nh_dev = fib6_nh.fib_nh_dev;
1061                 dev_hold(nh->fib_nh_dev);
1062                 nh->fib_nh_oif = nh->fib_nh_dev->ifindex;
1063                 nh->fib_nh_scope = RT_SCOPE_LINK;
1064
1065                 ipv6_stub->fib6_nh_release(&fib6_nh);
1066         }
1067
1068         return err;
1069 }
1070
1071 /*
1072  * Picture
1073  * -------
1074  *
1075  * Semantics of nexthop is very messy by historical reasons.
1076  * We have to take into account, that:
1077  * a) gateway can be actually local interface address,
1078  *    so that gatewayed route is direct.
1079  * b) gateway must be on-link address, possibly
1080  *    described not by an ifaddr, but also by a direct route.
1081  * c) If both gateway and interface are specified, they should not
1082  *    contradict.
1083  * d) If we use tunnel routes, gateway could be not on-link.
1084  *
1085  * Attempt to reconcile all of these (alas, self-contradictory) conditions
1086  * results in pretty ugly and hairy code with obscure logic.
1087  *
1088  * I chose to generalized it instead, so that the size
1089  * of code does not increase practically, but it becomes
1090  * much more general.
1091  * Every prefix is assigned a "scope" value: "host" is local address,
1092  * "link" is direct route,
1093  * [ ... "site" ... "interior" ... ]
1094  * and "universe" is true gateway route with global meaning.
1095  *
1096  * Every prefix refers to a set of "nexthop"s (gw, oif),
1097  * where gw must have narrower scope. This recursion stops
1098  * when gw has LOCAL scope or if "nexthop" is declared ONLINK,
1099  * which means that gw is forced to be on link.
1100  *
1101  * Code is still hairy, but now it is apparently logically
1102  * consistent and very flexible. F.e. as by-product it allows
1103  * to co-exists in peace independent exterior and interior
1104  * routing processes.
1105  *
1106  * Normally it looks as following.
1107  *
1108  * {universe prefix}  -> (gw, oif) [scope link]
1109  *                |
1110  *                |-> {link prefix} -> (gw, oif) [scope local]
1111  *                                      |
1112  *                                      |-> {local prefix} (terminal node)
1113  */
1114 static int fib_check_nh_v4_gw(struct net *net, struct fib_nh *nh, u32 table,
1115                               u8 scope, struct netlink_ext_ack *extack)
1116 {
1117         struct net_device *dev;
1118         struct fib_result res;
1119         int err = 0;
1120
1121         if (nh->fib_nh_flags & RTNH_F_ONLINK) {
1122                 unsigned int addr_type;
1123
1124                 if (scope >= RT_SCOPE_LINK) {
1125                         NL_SET_ERR_MSG(extack, "Nexthop has invalid scope");
1126                         return -EINVAL;
1127                 }
1128                 dev = __dev_get_by_index(net, nh->fib_nh_oif);
1129                 if (!dev) {
1130                         NL_SET_ERR_MSG(extack, "Nexthop device required for onlink");
1131                         return -ENODEV;
1132                 }
1133                 if (!(dev->flags & IFF_UP)) {
1134                         NL_SET_ERR_MSG(extack, "Nexthop device is not up");
1135                         return -ENETDOWN;
1136                 }
1137                 addr_type = inet_addr_type_dev_table(net, dev, nh->fib_nh_gw4);
1138                 if (addr_type != RTN_UNICAST) {
1139                         NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1140                         return -EINVAL;
1141                 }
1142                 if (!netif_carrier_ok(dev))
1143                         nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1144                 nh->fib_nh_dev = dev;
1145                 dev_hold(dev);
1146                 nh->fib_nh_scope = RT_SCOPE_LINK;
1147                 return 0;
1148         }
1149         rcu_read_lock();
1150         {
1151                 struct fib_table *tbl = NULL;
1152                 struct flowi4 fl4 = {
1153                         .daddr = nh->fib_nh_gw4,
1154                         .flowi4_scope = scope + 1,
1155                         .flowi4_oif = nh->fib_nh_oif,
1156                         .flowi4_iif = LOOPBACK_IFINDEX,
1157                 };
1158
1159                 /* It is not necessary, but requires a bit of thinking */
1160                 if (fl4.flowi4_scope < RT_SCOPE_LINK)
1161                         fl4.flowi4_scope = RT_SCOPE_LINK;
1162
1163                 if (table && table != RT_TABLE_MAIN)
1164                         tbl = fib_get_table(net, table);
1165
1166                 if (tbl)
1167                         err = fib_table_lookup(tbl, &fl4, &res,
1168                                                FIB_LOOKUP_IGNORE_LINKSTATE |
1169                                                FIB_LOOKUP_NOREF);
1170
1171                 /* on error or if no table given do full lookup. This
1172                  * is needed for example when nexthops are in the local
1173                  * table rather than the given table
1174                  */
1175                 if (!tbl || err) {
1176                         err = fib_lookup(net, &fl4, &res,
1177                                          FIB_LOOKUP_IGNORE_LINKSTATE);
1178                 }
1179
1180                 if (err) {
1181                         NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1182                         goto out;
1183                 }
1184         }
1185
1186         err = -EINVAL;
1187         if (res.type != RTN_UNICAST && res.type != RTN_LOCAL) {
1188                 NL_SET_ERR_MSG(extack, "Nexthop has invalid gateway");
1189                 goto out;
1190         }
1191         nh->fib_nh_scope = res.scope;
1192         nh->fib_nh_oif = FIB_RES_OIF(res);
1193         nh->fib_nh_dev = dev = FIB_RES_DEV(res);
1194         if (!dev) {
1195                 NL_SET_ERR_MSG(extack,
1196                                "No egress device for nexthop gateway");
1197                 goto out;
1198         }
1199         dev_hold(dev);
1200         if (!netif_carrier_ok(dev))
1201                 nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1202         err = (dev->flags & IFF_UP) ? 0 : -ENETDOWN;
1203 out:
1204         rcu_read_unlock();
1205         return err;
1206 }
1207
1208 static int fib_check_nh_nongw(struct net *net, struct fib_nh *nh,
1209                               struct netlink_ext_ack *extack)
1210 {
1211         struct in_device *in_dev;
1212         int err;
1213
1214         if (nh->fib_nh_flags & (RTNH_F_PERVASIVE | RTNH_F_ONLINK)) {
1215                 NL_SET_ERR_MSG(extack,
1216                                "Invalid flags for nexthop - PERVASIVE and ONLINK can not be set");
1217                 return -EINVAL;
1218         }
1219
1220         rcu_read_lock();
1221
1222         err = -ENODEV;
1223         in_dev = inetdev_by_index(net, nh->fib_nh_oif);
1224         if (!in_dev)
1225                 goto out;
1226         err = -ENETDOWN;
1227         if (!(in_dev->dev->flags & IFF_UP)) {
1228                 NL_SET_ERR_MSG(extack, "Device for nexthop is not up");
1229                 goto out;
1230         }
1231
1232         nh->fib_nh_dev = in_dev->dev;
1233         dev_hold(nh->fib_nh_dev);
1234         nh->fib_nh_scope = RT_SCOPE_LINK;
1235         if (!netif_carrier_ok(nh->fib_nh_dev))
1236                 nh->fib_nh_flags |= RTNH_F_LINKDOWN;
1237         err = 0;
1238 out:
1239         rcu_read_unlock();
1240         return err;
1241 }
1242
1243 int fib_check_nh(struct net *net, struct fib_nh *nh, u32 table, u8 scope,
1244                  struct netlink_ext_ack *extack)
1245 {
1246         int err;
1247
1248         if (nh->fib_nh_gw_family == AF_INET)
1249                 err = fib_check_nh_v4_gw(net, nh, table, scope, extack);
1250         else if (nh->fib_nh_gw_family == AF_INET6)
1251                 err = fib_check_nh_v6_gw(net, nh, table, extack);
1252         else
1253                 err = fib_check_nh_nongw(net, nh, extack);
1254
1255         return err;
1256 }
1257
1258 static inline unsigned int fib_laddr_hashfn(__be32 val)
1259 {
1260         unsigned int mask = (fib_info_hash_size - 1);
1261
1262         return ((__force u32)val ^
1263                 ((__force u32)val >> 7) ^
1264                 ((__force u32)val >> 14)) & mask;
1265 }
1266
1267 static struct hlist_head *fib_info_hash_alloc(int bytes)
1268 {
1269         if (bytes <= PAGE_SIZE)
1270                 return kzalloc(bytes, GFP_KERNEL);
1271         else
1272                 return (struct hlist_head *)
1273                         __get_free_pages(GFP_KERNEL | __GFP_ZERO,
1274                                          get_order(bytes));
1275 }
1276
1277 static void fib_info_hash_free(struct hlist_head *hash, int bytes)
1278 {
1279         if (!hash)
1280                 return;
1281
1282         if (bytes <= PAGE_SIZE)
1283                 kfree(hash);
1284         else
1285                 free_pages((unsigned long) hash, get_order(bytes));
1286 }
1287
1288 static void fib_info_hash_move(struct hlist_head *new_info_hash,
1289                                struct hlist_head *new_laddrhash,
1290                                unsigned int new_size)
1291 {
1292         struct hlist_head *old_info_hash, *old_laddrhash;
1293         unsigned int old_size = fib_info_hash_size;
1294         unsigned int i, bytes;
1295
1296         spin_lock_bh(&fib_info_lock);
1297         old_info_hash = fib_info_hash;
1298         old_laddrhash = fib_info_laddrhash;
1299         fib_info_hash_size = new_size;
1300
1301         for (i = 0; i < old_size; i++) {
1302                 struct hlist_head *head = &fib_info_hash[i];
1303                 struct hlist_node *n;
1304                 struct fib_info *fi;
1305
1306                 hlist_for_each_entry_safe(fi, n, head, fib_hash) {
1307                         struct hlist_head *dest;
1308                         unsigned int new_hash;
1309
1310                         new_hash = fib_info_hashfn(fi);
1311                         dest = &new_info_hash[new_hash];
1312                         hlist_add_head(&fi->fib_hash, dest);
1313                 }
1314         }
1315         fib_info_hash = new_info_hash;
1316
1317         for (i = 0; i < old_size; i++) {
1318                 struct hlist_head *lhead = &fib_info_laddrhash[i];
1319                 struct hlist_node *n;
1320                 struct fib_info *fi;
1321
1322                 hlist_for_each_entry_safe(fi, n, lhead, fib_lhash) {
1323                         struct hlist_head *ldest;
1324                         unsigned int new_hash;
1325
1326                         new_hash = fib_laddr_hashfn(fi->fib_prefsrc);
1327                         ldest = &new_laddrhash[new_hash];
1328                         hlist_add_head(&fi->fib_lhash, ldest);
1329                 }
1330         }
1331         fib_info_laddrhash = new_laddrhash;
1332
1333         spin_unlock_bh(&fib_info_lock);
1334
1335         bytes = old_size * sizeof(struct hlist_head *);
1336         fib_info_hash_free(old_info_hash, bytes);
1337         fib_info_hash_free(old_laddrhash, bytes);
1338 }
1339
1340 __be32 fib_info_update_nhc_saddr(struct net *net, struct fib_nh_common *nhc,
1341                                  unsigned char scope)
1342 {
1343         struct fib_nh *nh;
1344
1345         if (nhc->nhc_family != AF_INET)
1346                 return inet_select_addr(nhc->nhc_dev, 0, scope);
1347
1348         nh = container_of(nhc, struct fib_nh, nh_common);
1349         nh->nh_saddr = inet_select_addr(nh->fib_nh_dev, nh->fib_nh_gw4, scope);
1350         nh->nh_saddr_genid = atomic_read(&net->ipv4.dev_addr_genid);
1351
1352         return nh->nh_saddr;
1353 }
1354
1355 __be32 fib_result_prefsrc(struct net *net, struct fib_result *res)
1356 {
1357         struct fib_nh_common *nhc = res->nhc;
1358
1359         if (res->fi->fib_prefsrc)
1360                 return res->fi->fib_prefsrc;
1361
1362         if (nhc->nhc_family == AF_INET) {
1363                 struct fib_nh *nh;
1364
1365                 nh = container_of(nhc, struct fib_nh, nh_common);
1366                 if (nh->nh_saddr_genid == atomic_read(&net->ipv4.dev_addr_genid))
1367                         return nh->nh_saddr;
1368         }
1369
1370         return fib_info_update_nhc_saddr(net, nhc, res->fi->fib_scope);
1371 }
1372
1373 static bool fib_valid_prefsrc(struct fib_config *cfg, __be32 fib_prefsrc)
1374 {
1375         if (cfg->fc_type != RTN_LOCAL || !cfg->fc_dst ||
1376             fib_prefsrc != cfg->fc_dst) {
1377                 u32 tb_id = cfg->fc_table;
1378                 int rc;
1379
1380                 if (tb_id == RT_TABLE_MAIN)
1381                         tb_id = RT_TABLE_LOCAL;
1382
1383                 rc = inet_addr_type_table(cfg->fc_nlinfo.nl_net,
1384                                           fib_prefsrc, tb_id);
1385
1386                 if (rc != RTN_LOCAL && tb_id != RT_TABLE_LOCAL) {
1387                         rc = inet_addr_type_table(cfg->fc_nlinfo.nl_net,
1388                                                   fib_prefsrc, RT_TABLE_LOCAL);
1389                 }
1390
1391                 if (rc != RTN_LOCAL)
1392                         return false;
1393         }
1394         return true;
1395 }
1396
1397 struct fib_info *fib_create_info(struct fib_config *cfg,
1398                                  struct netlink_ext_ack *extack)
1399 {
1400         int err;
1401         struct fib_info *fi = NULL;
1402         struct nexthop *nh = NULL;
1403         struct fib_info *ofi;
1404         int nhs = 1;
1405         struct net *net = cfg->fc_nlinfo.nl_net;
1406
1407         if (cfg->fc_type > RTN_MAX)
1408                 goto err_inval;
1409
1410         /* Fast check to catch the most weird cases */
1411         if (fib_props[cfg->fc_type].scope > cfg->fc_scope) {
1412                 NL_SET_ERR_MSG(extack, "Invalid scope");
1413                 goto err_inval;
1414         }
1415
1416         if (cfg->fc_flags & (RTNH_F_DEAD | RTNH_F_LINKDOWN)) {
1417                 NL_SET_ERR_MSG(extack,
1418                                "Invalid rtm_flags - can not contain DEAD or LINKDOWN");
1419                 goto err_inval;
1420         }
1421
1422         if (cfg->fc_nh_id) {
1423                 if (!cfg->fc_mx) {
1424                         fi = fib_find_info_nh(net, cfg);
1425                         if (fi) {
1426                                 refcount_inc(&fi->fib_treeref);
1427                                 return fi;
1428                         }
1429                 }
1430
1431                 nh = nexthop_find_by_id(net, cfg->fc_nh_id);
1432                 if (!nh) {
1433                         NL_SET_ERR_MSG(extack, "Nexthop id does not exist");
1434                         goto err_inval;
1435                 }
1436                 nhs = 0;
1437         }
1438
1439 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1440         if (cfg->fc_mp) {
1441                 nhs = fib_count_nexthops(cfg->fc_mp, cfg->fc_mp_len, extack);
1442                 if (nhs == 0)
1443                         goto err_inval;
1444         }
1445 #endif
1446
1447         err = -ENOBUFS;
1448
1449         /* Paired with WRITE_ONCE() in fib_release_info() */
1450         if (READ_ONCE(fib_info_cnt) >= fib_info_hash_size) {
1451                 unsigned int new_size = fib_info_hash_size << 1;
1452                 struct hlist_head *new_info_hash;
1453                 struct hlist_head *new_laddrhash;
1454                 unsigned int bytes;
1455
1456                 if (!new_size)
1457                         new_size = 16;
1458                 bytes = new_size * sizeof(struct hlist_head *);
1459                 new_info_hash = fib_info_hash_alloc(bytes);
1460                 new_laddrhash = fib_info_hash_alloc(bytes);
1461                 if (!new_info_hash || !new_laddrhash) {
1462                         fib_info_hash_free(new_info_hash, bytes);
1463                         fib_info_hash_free(new_laddrhash, bytes);
1464                 } else
1465                         fib_info_hash_move(new_info_hash, new_laddrhash, new_size);
1466
1467                 if (!fib_info_hash_size)
1468                         goto failure;
1469         }
1470
1471         fi = kzalloc(struct_size(fi, fib_nh, nhs), GFP_KERNEL);
1472         if (!fi)
1473                 goto failure;
1474         fi->fib_metrics = ip_fib_metrics_init(fi->fib_net, cfg->fc_mx,
1475                                               cfg->fc_mx_len, extack);
1476         if (IS_ERR(fi->fib_metrics)) {
1477                 err = PTR_ERR(fi->fib_metrics);
1478                 kfree(fi);
1479                 return ERR_PTR(err);
1480         }
1481
1482         fi->fib_net = net;
1483         fi->fib_protocol = cfg->fc_protocol;
1484         fi->fib_scope = cfg->fc_scope;
1485         fi->fib_flags = cfg->fc_flags;
1486         fi->fib_priority = cfg->fc_priority;
1487         fi->fib_prefsrc = cfg->fc_prefsrc;
1488         fi->fib_type = cfg->fc_type;
1489         fi->fib_tb_id = cfg->fc_table;
1490
1491         fi->fib_nhs = nhs;
1492         if (nh) {
1493                 if (!nexthop_get(nh)) {
1494                         NL_SET_ERR_MSG(extack, "Nexthop has been deleted");
1495                         err = -EINVAL;
1496                 } else {
1497                         err = 0;
1498                         fi->nh = nh;
1499                 }
1500         } else {
1501                 change_nexthops(fi) {
1502                         nexthop_nh->nh_parent = fi;
1503                 } endfor_nexthops(fi)
1504
1505                 if (cfg->fc_mp)
1506                         err = fib_get_nhs(fi, cfg->fc_mp, cfg->fc_mp_len, cfg,
1507                                           extack);
1508                 else
1509                         err = fib_nh_init(net, fi->fib_nh, cfg, 1, extack);
1510         }
1511
1512         if (err != 0)
1513                 goto failure;
1514
1515         if (fib_props[cfg->fc_type].error) {
1516                 if (cfg->fc_gw_family || cfg->fc_oif || cfg->fc_mp) {
1517                         NL_SET_ERR_MSG(extack,
1518                                        "Gateway, device and multipath can not be specified for this route type");
1519                         goto err_inval;
1520                 }
1521                 goto link_it;
1522         } else {
1523                 switch (cfg->fc_type) {
1524                 case RTN_UNICAST:
1525                 case RTN_LOCAL:
1526                 case RTN_BROADCAST:
1527                 case RTN_ANYCAST:
1528                 case RTN_MULTICAST:
1529                         break;
1530                 default:
1531                         NL_SET_ERR_MSG(extack, "Invalid route type");
1532                         goto err_inval;
1533                 }
1534         }
1535
1536         if (cfg->fc_scope > RT_SCOPE_HOST) {
1537                 NL_SET_ERR_MSG(extack, "Invalid scope");
1538                 goto err_inval;
1539         }
1540
1541         if (fi->nh) {
1542                 err = fib_check_nexthop(fi->nh, cfg->fc_scope, extack);
1543                 if (err)
1544                         goto failure;
1545         } else if (cfg->fc_scope == RT_SCOPE_HOST) {
1546                 struct fib_nh *nh = fi->fib_nh;
1547
1548                 /* Local address is added. */
1549                 if (nhs != 1) {
1550                         NL_SET_ERR_MSG(extack,
1551                                        "Route with host scope can not have multiple nexthops");
1552                         goto err_inval;
1553                 }
1554                 if (nh->fib_nh_gw_family) {
1555                         NL_SET_ERR_MSG(extack,
1556                                        "Route with host scope can not have a gateway");
1557                         goto err_inval;
1558                 }
1559                 nh->fib_nh_scope = RT_SCOPE_NOWHERE;
1560                 nh->fib_nh_dev = dev_get_by_index(net, nh->fib_nh_oif);
1561                 err = -ENODEV;
1562                 if (!nh->fib_nh_dev)
1563                         goto failure;
1564         } else {
1565                 int linkdown = 0;
1566
1567                 change_nexthops(fi) {
1568                         err = fib_check_nh(cfg->fc_nlinfo.nl_net, nexthop_nh,
1569                                            cfg->fc_table, cfg->fc_scope,
1570                                            extack);
1571                         if (err != 0)
1572                                 goto failure;
1573                         if (nexthop_nh->fib_nh_flags & RTNH_F_LINKDOWN)
1574                                 linkdown++;
1575                 } endfor_nexthops(fi)
1576                 if (linkdown == fi->fib_nhs)
1577                         fi->fib_flags |= RTNH_F_LINKDOWN;
1578         }
1579
1580         if (fi->fib_prefsrc && !fib_valid_prefsrc(cfg, fi->fib_prefsrc)) {
1581                 NL_SET_ERR_MSG(extack, "Invalid prefsrc address");
1582                 goto err_inval;
1583         }
1584
1585         if (!fi->nh) {
1586                 change_nexthops(fi) {
1587                         fib_info_update_nhc_saddr(net, &nexthop_nh->nh_common,
1588                                                   fi->fib_scope);
1589                         if (nexthop_nh->fib_nh_gw_family == AF_INET6)
1590                                 fi->fib_nh_is_v6 = true;
1591                 } endfor_nexthops(fi)
1592
1593                 fib_rebalance(fi);
1594         }
1595
1596 link_it:
1597         ofi = fib_find_info(fi);
1598         if (ofi) {
1599                 fi->fib_dead = 1;
1600                 free_fib_info(fi);
1601                 refcount_inc(&ofi->fib_treeref);
1602                 return ofi;
1603         }
1604
1605         refcount_set(&fi->fib_treeref, 1);
1606         refcount_set(&fi->fib_clntref, 1);
1607         spin_lock_bh(&fib_info_lock);
1608         fib_info_cnt++;
1609         hlist_add_head(&fi->fib_hash,
1610                        &fib_info_hash[fib_info_hashfn(fi)]);
1611         if (fi->fib_prefsrc) {
1612                 struct hlist_head *head;
1613
1614                 head = &fib_info_laddrhash[fib_laddr_hashfn(fi->fib_prefsrc)];
1615                 hlist_add_head(&fi->fib_lhash, head);
1616         }
1617         if (fi->nh) {
1618                 list_add(&fi->nh_list, &nh->fi_list);
1619         } else {
1620                 change_nexthops(fi) {
1621                         struct hlist_head *head;
1622
1623                         if (!nexthop_nh->fib_nh_dev)
1624                                 continue;
1625                         head = fib_info_devhash_bucket(nexthop_nh->fib_nh_dev);
1626                         hlist_add_head(&nexthop_nh->nh_hash, head);
1627                 } endfor_nexthops(fi)
1628         }
1629         spin_unlock_bh(&fib_info_lock);
1630         return fi;
1631
1632 err_inval:
1633         err = -EINVAL;
1634
1635 failure:
1636         if (fi) {
1637                 fi->fib_dead = 1;
1638                 free_fib_info(fi);
1639         }
1640
1641         return ERR_PTR(err);
1642 }
1643
1644 int fib_nexthop_info(struct sk_buff *skb, const struct fib_nh_common *nhc,
1645                      u8 rt_family, unsigned char *flags, bool skip_oif)
1646 {
1647         if (nhc->nhc_flags & RTNH_F_DEAD)
1648                 *flags |= RTNH_F_DEAD;
1649
1650         if (nhc->nhc_flags & RTNH_F_LINKDOWN) {
1651                 *flags |= RTNH_F_LINKDOWN;
1652
1653                 rcu_read_lock();
1654                 switch (nhc->nhc_family) {
1655                 case AF_INET:
1656                         if (ip_ignore_linkdown(nhc->nhc_dev))
1657                                 *flags |= RTNH_F_DEAD;
1658                         break;
1659                 case AF_INET6:
1660                         if (ip6_ignore_linkdown(nhc->nhc_dev))
1661                                 *flags |= RTNH_F_DEAD;
1662                         break;
1663                 }
1664                 rcu_read_unlock();
1665         }
1666
1667         switch (nhc->nhc_gw_family) {
1668         case AF_INET:
1669                 if (nla_put_in_addr(skb, RTA_GATEWAY, nhc->nhc_gw.ipv4))
1670                         goto nla_put_failure;
1671                 break;
1672         case AF_INET6:
1673                 /* if gateway family does not match nexthop family
1674                  * gateway is encoded as RTA_VIA
1675                  */
1676                 if (rt_family != nhc->nhc_gw_family) {
1677                         int alen = sizeof(struct in6_addr);
1678                         struct nlattr *nla;
1679                         struct rtvia *via;
1680
1681                         nla = nla_reserve(skb, RTA_VIA, alen + 2);
1682                         if (!nla)
1683                                 goto nla_put_failure;
1684
1685                         via = nla_data(nla);
1686                         via->rtvia_family = AF_INET6;
1687                         memcpy(via->rtvia_addr, &nhc->nhc_gw.ipv6, alen);
1688                 } else if (nla_put_in6_addr(skb, RTA_GATEWAY,
1689                                             &nhc->nhc_gw.ipv6) < 0) {
1690                         goto nla_put_failure;
1691                 }
1692                 break;
1693         }
1694
1695         *flags |= (nhc->nhc_flags &
1696                    (RTNH_F_ONLINK | RTNH_F_OFFLOAD | RTNH_F_TRAP));
1697
1698         if (!skip_oif && nhc->nhc_dev &&
1699             nla_put_u32(skb, RTA_OIF, nhc->nhc_dev->ifindex))
1700                 goto nla_put_failure;
1701
1702         if (nhc->nhc_lwtstate &&
1703             lwtunnel_fill_encap(skb, nhc->nhc_lwtstate,
1704                                 RTA_ENCAP, RTA_ENCAP_TYPE) < 0)
1705                 goto nla_put_failure;
1706
1707         return 0;
1708
1709 nla_put_failure:
1710         return -EMSGSIZE;
1711 }
1712 EXPORT_SYMBOL_GPL(fib_nexthop_info);
1713
1714 #if IS_ENABLED(CONFIG_IP_ROUTE_MULTIPATH) || IS_ENABLED(CONFIG_IPV6)
1715 int fib_add_nexthop(struct sk_buff *skb, const struct fib_nh_common *nhc,
1716                     int nh_weight, u8 rt_family, u32 nh_tclassid)
1717 {
1718         const struct net_device *dev = nhc->nhc_dev;
1719         struct rtnexthop *rtnh;
1720         unsigned char flags = 0;
1721
1722         rtnh = nla_reserve_nohdr(skb, sizeof(*rtnh));
1723         if (!rtnh)
1724                 goto nla_put_failure;
1725
1726         rtnh->rtnh_hops = nh_weight - 1;
1727         rtnh->rtnh_ifindex = dev ? dev->ifindex : 0;
1728
1729         if (fib_nexthop_info(skb, nhc, rt_family, &flags, true) < 0)
1730                 goto nla_put_failure;
1731
1732         rtnh->rtnh_flags = flags;
1733
1734         if (nh_tclassid && nla_put_u32(skb, RTA_FLOW, nh_tclassid))
1735                 goto nla_put_failure;
1736
1737         /* length of rtnetlink header + attributes */
1738         rtnh->rtnh_len = nlmsg_get_pos(skb) - (void *)rtnh;
1739
1740         return 0;
1741
1742 nla_put_failure:
1743         return -EMSGSIZE;
1744 }
1745 EXPORT_SYMBOL_GPL(fib_add_nexthop);
1746 #endif
1747
1748 #ifdef CONFIG_IP_ROUTE_MULTIPATH
1749 static int fib_add_multipath(struct sk_buff *skb, struct fib_info *fi)
1750 {
1751         struct nlattr *mp;
1752
1753         mp = nla_nest_start_noflag(skb, RTA_MULTIPATH);
1754         if (!mp)
1755                 goto nla_put_failure;
1756
1757         if (unlikely(fi->nh)) {
1758                 if (nexthop_mpath_fill_node(skb, fi->nh, AF_INET) < 0)
1759                         goto nla_put_failure;
1760                 goto mp_end;
1761         }
1762
1763         for_nexthops(fi) {
1764                 u32 nh_tclassid = 0;
1765 #ifdef CONFIG_IP_ROUTE_CLASSID
1766                 nh_tclassid = nh->nh_tclassid;
1767 #endif
1768                 if (fib_add_nexthop(skb, &nh->nh_common, nh->fib_nh_weight,
1769                                     AF_INET, nh_tclassid) < 0)
1770                         goto nla_put_failure;
1771         } endfor_nexthops(fi);
1772
1773 mp_end:
1774         nla_nest_end(skb, mp);
1775
1776         return 0;
1777
1778 nla_put_failure:
1779         return -EMSGSIZE;
1780 }
1781 #else
1782 static int fib_add_multipath(struct sk_buff *skb, struct fib_info *fi)
1783 {
1784         return 0;
1785 }
1786 #endif
1787
1788 int fib_dump_info(struct sk_buff *skb, u32 portid, u32 seq, int event,
1789                   const struct fib_rt_info *fri, unsigned int flags)
1790 {
1791         unsigned int nhs = fib_info_num_path(fri->fi);
1792         struct fib_info *fi = fri->fi;
1793         u32 tb_id = fri->tb_id;
1794         struct nlmsghdr *nlh;
1795         struct rtmsg *rtm;
1796
1797         nlh = nlmsg_put(skb, portid, seq, event, sizeof(*rtm), flags);
1798         if (!nlh)
1799                 return -EMSGSIZE;
1800
1801         rtm = nlmsg_data(nlh);
1802         rtm->rtm_family = AF_INET;
1803         rtm->rtm_dst_len = fri->dst_len;
1804         rtm->rtm_src_len = 0;
1805         rtm->rtm_tos = fri->tos;
1806         if (tb_id < 256)
1807                 rtm->rtm_table = tb_id;
1808         else
1809                 rtm->rtm_table = RT_TABLE_COMPAT;
1810         if (nla_put_u32(skb, RTA_TABLE, tb_id))
1811                 goto nla_put_failure;
1812         rtm->rtm_type = fri->type;
1813         rtm->rtm_flags = fi->fib_flags;
1814         rtm->rtm_scope = fi->fib_scope;
1815         rtm->rtm_protocol = fi->fib_protocol;
1816
1817         if (rtm->rtm_dst_len &&
1818             nla_put_in_addr(skb, RTA_DST, fri->dst))
1819                 goto nla_put_failure;
1820         if (fi->fib_priority &&
1821             nla_put_u32(skb, RTA_PRIORITY, fi->fib_priority))
1822                 goto nla_put_failure;
1823         if (rtnetlink_put_metrics(skb, fi->fib_metrics->metrics) < 0)
1824                 goto nla_put_failure;
1825
1826         if (fi->fib_prefsrc &&
1827             nla_put_in_addr(skb, RTA_PREFSRC, fi->fib_prefsrc))
1828                 goto nla_put_failure;
1829
1830         if (fi->nh) {
1831                 if (nla_put_u32(skb, RTA_NH_ID, fi->nh->id))
1832                         goto nla_put_failure;
1833                 if (nexthop_is_blackhole(fi->nh))
1834                         rtm->rtm_type = RTN_BLACKHOLE;
1835                 if (!READ_ONCE(fi->fib_net->ipv4.sysctl_nexthop_compat_mode))
1836                         goto offload;
1837         }
1838
1839         if (nhs == 1) {
1840                 const struct fib_nh_common *nhc = fib_info_nhc(fi, 0);
1841                 unsigned char flags = 0;
1842
1843                 if (fib_nexthop_info(skb, nhc, AF_INET, &flags, false) < 0)
1844                         goto nla_put_failure;
1845
1846                 rtm->rtm_flags = flags;
1847 #ifdef CONFIG_IP_ROUTE_CLASSID
1848                 if (nhc->nhc_family == AF_INET) {
1849                         struct fib_nh *nh;
1850
1851                         nh = container_of(nhc, struct fib_nh, nh_common);
1852                         if (nh->nh_tclassid &&
1853                             nla_put_u32(skb, RTA_FLOW, nh->nh_tclassid))
1854                                 goto nla_put_failure;
1855                 }
1856 #endif
1857         } else {
1858                 if (fib_add_multipath(skb, fi) < 0)
1859                         goto nla_put_failure;
1860         }
1861
1862 offload:
1863         if (fri->offload)
1864                 rtm->rtm_flags |= RTM_F_OFFLOAD;
1865         if (fri->trap)
1866                 rtm->rtm_flags |= RTM_F_TRAP;
1867         if (fri->offload_failed)
1868                 rtm->rtm_flags |= RTM_F_OFFLOAD_FAILED;
1869
1870         nlmsg_end(skb, nlh);
1871         return 0;
1872
1873 nla_put_failure:
1874         nlmsg_cancel(skb, nlh);
1875         return -EMSGSIZE;
1876 }
1877
1878 /*
1879  * Update FIB if:
1880  * - local address disappeared -> we must delete all the entries
1881  *   referring to it.
1882  * - device went down -> we must shutdown all nexthops going via it.
1883  */
1884 int fib_sync_down_addr(struct net_device *dev, __be32 local)
1885 {
1886         int ret = 0;
1887         unsigned int hash = fib_laddr_hashfn(local);
1888         struct hlist_head *head = &fib_info_laddrhash[hash];
1889         int tb_id = l3mdev_fib_table(dev) ? : RT_TABLE_MAIN;
1890         struct net *net = dev_net(dev);
1891         struct fib_info *fi;
1892
1893         if (!fib_info_laddrhash || local == 0)
1894                 return 0;
1895
1896         hlist_for_each_entry(fi, head, fib_lhash) {
1897                 if (!net_eq(fi->fib_net, net) ||
1898                     fi->fib_tb_id != tb_id)
1899                         continue;
1900                 if (fi->fib_prefsrc == local) {
1901                         fi->fib_flags |= RTNH_F_DEAD;
1902                         ret++;
1903                 }
1904         }
1905         return ret;
1906 }
1907
1908 static int call_fib_nh_notifiers(struct fib_nh *nh,
1909                                  enum fib_event_type event_type)
1910 {
1911         bool ignore_link_down = ip_ignore_linkdown(nh->fib_nh_dev);
1912         struct fib_nh_notifier_info info = {
1913                 .fib_nh = nh,
1914         };
1915
1916         switch (event_type) {
1917         case FIB_EVENT_NH_ADD:
1918                 if (nh->fib_nh_flags & RTNH_F_DEAD)
1919                         break;
1920                 if (ignore_link_down && nh->fib_nh_flags & RTNH_F_LINKDOWN)
1921                         break;
1922                 return call_fib4_notifiers(dev_net(nh->fib_nh_dev), event_type,
1923                                            &info.info);
1924         case FIB_EVENT_NH_DEL:
1925                 if ((ignore_link_down && nh->fib_nh_flags & RTNH_F_LINKDOWN) ||
1926                     (nh->fib_nh_flags & RTNH_F_DEAD))
1927                         return call_fib4_notifiers(dev_net(nh->fib_nh_dev),
1928                                                    event_type, &info.info);
1929                 break;
1930         default:
1931                 break;
1932         }
1933
1934         return NOTIFY_DONE;
1935 }
1936
1937 /* Update the PMTU of exceptions when:
1938  * - the new MTU of the first hop becomes smaller than the PMTU
1939  * - the old MTU was the same as the PMTU, and it limited discovery of
1940  *   larger MTUs on the path. With that limit raised, we can now
1941  *   discover larger MTUs
1942  * A special case is locked exceptions, for which the PMTU is smaller
1943  * than the minimal accepted PMTU:
1944  * - if the new MTU is greater than the PMTU, don't make any change
1945  * - otherwise, unlock and set PMTU
1946  */
1947 void fib_nhc_update_mtu(struct fib_nh_common *nhc, u32 new, u32 orig)
1948 {
1949         struct fnhe_hash_bucket *bucket;
1950         int i;
1951
1952         bucket = rcu_dereference_protected(nhc->nhc_exceptions, 1);
1953         if (!bucket)
1954                 return;
1955
1956         for (i = 0; i < FNHE_HASH_SIZE; i++) {
1957                 struct fib_nh_exception *fnhe;
1958
1959                 for (fnhe = rcu_dereference_protected(bucket[i].chain, 1);
1960                      fnhe;
1961                      fnhe = rcu_dereference_protected(fnhe->fnhe_next, 1)) {
1962                         if (fnhe->fnhe_mtu_locked) {
1963                                 if (new <= fnhe->fnhe_pmtu) {
1964                                         fnhe->fnhe_pmtu = new;
1965                                         fnhe->fnhe_mtu_locked = false;
1966                                 }
1967                         } else if (new < fnhe->fnhe_pmtu ||
1968                                    orig == fnhe->fnhe_pmtu) {
1969                                 fnhe->fnhe_pmtu = new;
1970                         }
1971                 }
1972         }
1973 }
1974
1975 void fib_sync_mtu(struct net_device *dev, u32 orig_mtu)
1976 {
1977         struct hlist_head *head = fib_info_devhash_bucket(dev);
1978         struct fib_nh *nh;
1979
1980         hlist_for_each_entry(nh, head, nh_hash) {
1981                 if (nh->fib_nh_dev == dev)
1982                         fib_nhc_update_mtu(&nh->nh_common, dev->mtu, orig_mtu);
1983         }
1984 }
1985
1986 /* Event              force Flags           Description
1987  * NETDEV_CHANGE      0     LINKDOWN        Carrier OFF, not for scope host
1988  * NETDEV_DOWN        0     LINKDOWN|DEAD   Link down, not for scope host
1989  * NETDEV_DOWN        1     LINKDOWN|DEAD   Last address removed
1990  * NETDEV_UNREGISTER  1     LINKDOWN|DEAD   Device removed
1991  *
1992  * only used when fib_nh is built into fib_info
1993  */
1994 int fib_sync_down_dev(struct net_device *dev, unsigned long event, bool force)
1995 {
1996         struct hlist_head *head = fib_info_devhash_bucket(dev);
1997         struct fib_info *prev_fi = NULL;
1998         int scope = RT_SCOPE_NOWHERE;
1999         struct fib_nh *nh;
2000         int ret = 0;
2001
2002         if (force)
2003                 scope = -1;
2004
2005         hlist_for_each_entry(nh, head, nh_hash) {
2006                 struct fib_info *fi = nh->nh_parent;
2007                 int dead;
2008
2009                 BUG_ON(!fi->fib_nhs);
2010                 if (nh->fib_nh_dev != dev || fi == prev_fi)
2011                         continue;
2012                 prev_fi = fi;
2013                 dead = 0;
2014                 change_nexthops(fi) {
2015                         if (nexthop_nh->fib_nh_flags & RTNH_F_DEAD)
2016                                 dead++;
2017                         else if (nexthop_nh->fib_nh_dev == dev &&
2018                                  nexthop_nh->fib_nh_scope != scope) {
2019                                 switch (event) {
2020                                 case NETDEV_DOWN:
2021                                 case NETDEV_UNREGISTER:
2022                                         nexthop_nh->fib_nh_flags |= RTNH_F_DEAD;
2023                                         fallthrough;
2024                                 case NETDEV_CHANGE:
2025                                         nexthop_nh->fib_nh_flags |= RTNH_F_LINKDOWN;
2026                                         break;
2027                                 }
2028                                 call_fib_nh_notifiers(nexthop_nh,
2029                                                       FIB_EVENT_NH_DEL);
2030                                 dead++;
2031                         }
2032 #ifdef CONFIG_IP_ROUTE_MULTIPATH
2033                         if (event == NETDEV_UNREGISTER &&
2034                             nexthop_nh->fib_nh_dev == dev) {
2035                                 dead = fi->fib_nhs;
2036                                 break;
2037                         }
2038 #endif
2039                 } endfor_nexthops(fi)
2040                 if (dead == fi->fib_nhs) {
2041                         switch (event) {
2042                         case NETDEV_DOWN:
2043                         case NETDEV_UNREGISTER:
2044                                 fi->fib_flags |= RTNH_F_DEAD;
2045                                 fallthrough;
2046                         case NETDEV_CHANGE:
2047                                 fi->fib_flags |= RTNH_F_LINKDOWN;
2048                                 break;
2049                         }
2050                         ret++;
2051                 }
2052
2053                 fib_rebalance(fi);
2054         }
2055
2056         return ret;
2057 }
2058
2059 /* Must be invoked inside of an RCU protected region.  */
2060 static void fib_select_default(const struct flowi4 *flp, struct fib_result *res)
2061 {
2062         struct fib_info *fi = NULL, *last_resort = NULL;
2063         struct hlist_head *fa_head = res->fa_head;
2064         struct fib_table *tb = res->table;
2065         u8 slen = 32 - res->prefixlen;
2066         int order = -1, last_idx = -1;
2067         struct fib_alias *fa, *fa1 = NULL;
2068         u32 last_prio = res->fi->fib_priority;
2069         u8 last_tos = 0;
2070
2071         hlist_for_each_entry_rcu(fa, fa_head, fa_list) {
2072                 struct fib_info *next_fi = fa->fa_info;
2073                 struct fib_nh_common *nhc;
2074
2075                 if (fa->fa_slen != slen)
2076                         continue;
2077                 if (fa->fa_tos && fa->fa_tos != flp->flowi4_tos)
2078                         continue;
2079                 if (fa->tb_id != tb->tb_id)
2080                         continue;
2081                 if (next_fi->fib_priority > last_prio &&
2082                     fa->fa_tos == last_tos) {
2083                         if (last_tos)
2084                                 continue;
2085                         break;
2086                 }
2087                 if (next_fi->fib_flags & RTNH_F_DEAD)
2088                         continue;
2089                 last_tos = fa->fa_tos;
2090                 last_prio = next_fi->fib_priority;
2091
2092                 if (next_fi->fib_scope != res->scope ||
2093                     fa->fa_type != RTN_UNICAST)
2094                         continue;
2095
2096                 nhc = fib_info_nhc(next_fi, 0);
2097                 if (!nhc->nhc_gw_family || nhc->nhc_scope != RT_SCOPE_LINK)
2098                         continue;
2099
2100                 fib_alias_accessed(fa);
2101
2102                 if (!fi) {
2103                         if (next_fi != res->fi)
2104                                 break;
2105                         fa1 = fa;
2106                 } else if (!fib_detect_death(fi, order, &last_resort,
2107                                              &last_idx, fa1->fa_default)) {
2108                         fib_result_assign(res, fi);
2109                         fa1->fa_default = order;
2110                         goto out;
2111                 }
2112                 fi = next_fi;
2113                 order++;
2114         }
2115
2116         if (order <= 0 || !fi) {
2117                 if (fa1)
2118                         fa1->fa_default = -1;
2119                 goto out;
2120         }
2121
2122         if (!fib_detect_death(fi, order, &last_resort, &last_idx,
2123                               fa1->fa_default)) {
2124                 fib_result_assign(res, fi);
2125                 fa1->fa_default = order;
2126                 goto out;
2127         }
2128
2129         if (last_idx >= 0)
2130                 fib_result_assign(res, last_resort);
2131         fa1->fa_default = last_idx;
2132 out:
2133         return;
2134 }
2135
2136 /*
2137  * Dead device goes up. We wake up dead nexthops.
2138  * It takes sense only on multipath routes.
2139  *
2140  * only used when fib_nh is built into fib_info
2141  */
2142 int fib_sync_up(struct net_device *dev, unsigned char nh_flags)
2143 {
2144         struct fib_info *prev_fi;
2145         struct hlist_head *head;
2146         struct fib_nh *nh;
2147         int ret;
2148
2149         if (!(dev->flags & IFF_UP))
2150                 return 0;
2151
2152         if (nh_flags & RTNH_F_DEAD) {
2153                 unsigned int flags = dev_get_flags(dev);
2154
2155                 if (flags & (IFF_RUNNING | IFF_LOWER_UP))
2156                         nh_flags |= RTNH_F_LINKDOWN;
2157         }
2158
2159         prev_fi = NULL;
2160         head = fib_info_devhash_bucket(dev);
2161         ret = 0;
2162
2163         hlist_for_each_entry(nh, head, nh_hash) {
2164                 struct fib_info *fi = nh->nh_parent;
2165                 int alive;
2166
2167                 BUG_ON(!fi->fib_nhs);
2168                 if (nh->fib_nh_dev != dev || fi == prev_fi)
2169                         continue;
2170
2171                 prev_fi = fi;
2172                 alive = 0;
2173                 change_nexthops(fi) {
2174                         if (!(nexthop_nh->fib_nh_flags & nh_flags)) {
2175                                 alive++;
2176                                 continue;
2177                         }
2178                         if (!nexthop_nh->fib_nh_dev ||
2179                             !(nexthop_nh->fib_nh_dev->flags & IFF_UP))
2180                                 continue;
2181                         if (nexthop_nh->fib_nh_dev != dev ||
2182                             !__in_dev_get_rtnl(dev))
2183                                 continue;
2184                         alive++;
2185                         nexthop_nh->fib_nh_flags &= ~nh_flags;
2186                         call_fib_nh_notifiers(nexthop_nh, FIB_EVENT_NH_ADD);
2187                 } endfor_nexthops(fi)
2188
2189                 if (alive > 0) {
2190                         fi->fib_flags &= ~nh_flags;
2191                         ret++;
2192                 }
2193
2194                 fib_rebalance(fi);
2195         }
2196
2197         return ret;
2198 }
2199
2200 #ifdef CONFIG_IP_ROUTE_MULTIPATH
2201 static bool fib_good_nh(const struct fib_nh *nh)
2202 {
2203         int state = NUD_REACHABLE;
2204
2205         if (nh->fib_nh_scope == RT_SCOPE_LINK) {
2206                 struct neighbour *n;
2207
2208                 rcu_read_lock_bh();
2209
2210                 if (likely(nh->fib_nh_gw_family == AF_INET))
2211                         n = __ipv4_neigh_lookup_noref(nh->fib_nh_dev,
2212                                                    (__force u32)nh->fib_nh_gw4);
2213                 else if (nh->fib_nh_gw_family == AF_INET6)
2214                         n = __ipv6_neigh_lookup_noref_stub(nh->fib_nh_dev,
2215                                                            &nh->fib_nh_gw6);
2216                 else
2217                         n = NULL;
2218                 if (n)
2219                         state = n->nud_state;
2220
2221                 rcu_read_unlock_bh();
2222         }
2223
2224         return !!(state & NUD_VALID);
2225 }
2226
2227 void fib_select_multipath(struct fib_result *res, int hash)
2228 {
2229         struct fib_info *fi = res->fi;
2230         struct net *net = fi->fib_net;
2231         bool first = false;
2232
2233         if (unlikely(res->fi->nh)) {
2234                 nexthop_path_fib_result(res, hash);
2235                 return;
2236         }
2237
2238         change_nexthops(fi) {
2239                 if (READ_ONCE(net->ipv4.sysctl_fib_multipath_use_neigh)) {
2240                         if (!fib_good_nh(nexthop_nh))
2241                                 continue;
2242                         if (!first) {
2243                                 res->nh_sel = nhsel;
2244                                 res->nhc = &nexthop_nh->nh_common;
2245                                 first = true;
2246                         }
2247                 }
2248
2249                 if (hash > atomic_read(&nexthop_nh->fib_nh_upper_bound))
2250                         continue;
2251
2252                 res->nh_sel = nhsel;
2253                 res->nhc = &nexthop_nh->nh_common;
2254                 return;
2255         } endfor_nexthops(fi);
2256 }
2257 #endif
2258
2259 void fib_select_path(struct net *net, struct fib_result *res,
2260                      struct flowi4 *fl4, const struct sk_buff *skb)
2261 {
2262         if (fl4->flowi4_oif && !(fl4->flowi4_flags & FLOWI_FLAG_SKIP_NH_OIF))
2263                 goto check_saddr;
2264
2265 #ifdef CONFIG_IP_ROUTE_MULTIPATH
2266         if (fib_info_num_path(res->fi) > 1) {
2267                 int h = fib_multipath_hash(net, fl4, skb, NULL);
2268
2269                 fib_select_multipath(res, h);
2270         }
2271         else
2272 #endif
2273         if (!res->prefixlen &&
2274             res->table->tb_num_default > 1 &&
2275             res->type == RTN_UNICAST)
2276                 fib_select_default(fl4, res);
2277
2278 check_saddr:
2279         if (!fl4->saddr)
2280                 fl4->saddr = fib_result_prefsrc(net, res);
2281 }