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