4a96ebbf8eda5f59a6ff88e836d666a404d2bf0d
[sfrench/cifs-2.6.git] / net / ipv6 / addrconf.c
1 /*
2  *      IPv6 Address [auto]configuration
3  *      Linux INET6 implementation
4  *
5  *      Authors:
6  *      Pedro Roque             <roque@di.fc.ul.pt>
7  *      Alexey Kuznetsov        <kuznet@ms2.inr.ac.ru>
8  *
9  *      This program is free software; you can redistribute it and/or
10  *      modify it under the terms of the GNU General Public License
11  *      as published by the Free Software Foundation; either version
12  *      2 of the License, or (at your option) any later version.
13  */
14
15 /*
16  *      Changes:
17  *
18  *      Janos Farkas                    :       delete timer on ifdown
19  *      <chexum@bankinf.banki.hu>
20  *      Andi Kleen                      :       kill double kfree on module
21  *                                              unload.
22  *      Maciej W. Rozycki               :       FDDI support
23  *      sekiya@USAGI                    :       Don't send too many RS
24  *                                              packets.
25  *      yoshfuji@USAGI                  :       Fixed interval between DAD
26  *                                              packets.
27  *      YOSHIFUJI Hideaki @USAGI        :       improved accuracy of
28  *                                              address validation timer.
29  *      YOSHIFUJI Hideaki @USAGI        :       Privacy Extensions (RFC3041)
30  *                                              support.
31  *      Yuji SEKIYA @USAGI              :       Don't assign a same IPv6
32  *                                              address on a same interface.
33  *      YOSHIFUJI Hideaki @USAGI        :       ARCnet support
34  *      YOSHIFUJI Hideaki @USAGI        :       convert /proc/net/if_inet6 to
35  *                                              seq_file.
36  *      YOSHIFUJI Hideaki @USAGI        :       improved source address
37  *                                              selection; consider scope,
38  *                                              status etc.
39  */
40
41 #define pr_fmt(fmt) "IPv6: " fmt
42
43 #include <linux/errno.h>
44 #include <linux/types.h>
45 #include <linux/kernel.h>
46 #include <linux/sched/signal.h>
47 #include <linux/socket.h>
48 #include <linux/sockios.h>
49 #include <linux/net.h>
50 #include <linux/inet.h>
51 #include <linux/in6.h>
52 #include <linux/netdevice.h>
53 #include <linux/if_addr.h>
54 #include <linux/if_arp.h>
55 #include <linux/if_arcnet.h>
56 #include <linux/if_infiniband.h>
57 #include <linux/route.h>
58 #include <linux/inetdevice.h>
59 #include <linux/init.h>
60 #include <linux/slab.h>
61 #ifdef CONFIG_SYSCTL
62 #include <linux/sysctl.h>
63 #endif
64 #include <linux/capability.h>
65 #include <linux/delay.h>
66 #include <linux/notifier.h>
67 #include <linux/string.h>
68 #include <linux/hash.h>
69
70 #include <net/net_namespace.h>
71 #include <net/sock.h>
72 #include <net/snmp.h>
73
74 #include <net/6lowpan.h>
75 #include <net/firewire.h>
76 #include <net/ipv6.h>
77 #include <net/protocol.h>
78 #include <net/ndisc.h>
79 #include <net/ip6_route.h>
80 #include <net/addrconf.h>
81 #include <net/tcp.h>
82 #include <net/ip.h>
83 #include <net/netlink.h>
84 #include <net/pkt_sched.h>
85 #include <net/l3mdev.h>
86 #include <linux/if_tunnel.h>
87 #include <linux/rtnetlink.h>
88 #include <linux/netconf.h>
89 #include <linux/random.h>
90 #include <linux/uaccess.h>
91 #include <asm/unaligned.h>
92
93 #include <linux/proc_fs.h>
94 #include <linux/seq_file.h>
95 #include <linux/export.h>
96
97 /* Set to 3 to get tracing... */
98 #define ACONF_DEBUG 2
99
100 #if ACONF_DEBUG >= 3
101 #define ADBG(fmt, ...) printk(fmt, ##__VA_ARGS__)
102 #else
103 #define ADBG(fmt, ...) do { if (0) printk(fmt, ##__VA_ARGS__); } while (0)
104 #endif
105
106 #define INFINITY_LIFE_TIME      0xFFFFFFFF
107
108 #define IPV6_MAX_STRLEN \
109         sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
110
111 static inline u32 cstamp_delta(unsigned long cstamp)
112 {
113         return (cstamp - INITIAL_JIFFIES) * 100UL / HZ;
114 }
115
116 static inline s32 rfc3315_s14_backoff_init(s32 irt)
117 {
118         /* multiply 'initial retransmission time' by 0.9 .. 1.1 */
119         u64 tmp = (900000 + prandom_u32() % 200001) * (u64)irt;
120         do_div(tmp, 1000000);
121         return (s32)tmp;
122 }
123
124 static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
125 {
126         /* multiply 'retransmission timeout' by 1.9 .. 2.1 */
127         u64 tmp = (1900000 + prandom_u32() % 200001) * (u64)rt;
128         do_div(tmp, 1000000);
129         if ((s32)tmp > mrt) {
130                 /* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
131                 tmp = (900000 + prandom_u32() % 200001) * (u64)mrt;
132                 do_div(tmp, 1000000);
133         }
134         return (s32)tmp;
135 }
136
137 #ifdef CONFIG_SYSCTL
138 static int addrconf_sysctl_register(struct inet6_dev *idev);
139 static void addrconf_sysctl_unregister(struct inet6_dev *idev);
140 #else
141 static inline int addrconf_sysctl_register(struct inet6_dev *idev)
142 {
143         return 0;
144 }
145
146 static inline void addrconf_sysctl_unregister(struct inet6_dev *idev)
147 {
148 }
149 #endif
150
151 static void ipv6_regen_rndid(struct inet6_dev *idev);
152 static void ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr);
153
154 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev);
155 static int ipv6_count_addresses(struct inet6_dev *idev);
156 static int ipv6_generate_stable_address(struct in6_addr *addr,
157                                         u8 dad_count,
158                                         const struct inet6_dev *idev);
159
160 /*
161  *      Configured unicast address hash table
162  */
163 static struct hlist_head inet6_addr_lst[IN6_ADDR_HSIZE];
164 static DEFINE_SPINLOCK(addrconf_hash_lock);
165
166 static void addrconf_verify(void);
167 static void addrconf_verify_rtnl(void);
168 static void addrconf_verify_work(struct work_struct *);
169
170 static struct workqueue_struct *addrconf_wq;
171 static DECLARE_DELAYED_WORK(addr_chk_work, addrconf_verify_work);
172
173 static void addrconf_join_anycast(struct inet6_ifaddr *ifp);
174 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp);
175
176 static void addrconf_type_change(struct net_device *dev,
177                                  unsigned long event);
178 static int addrconf_ifdown(struct net_device *dev, int how);
179
180 static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
181                                                   int plen,
182                                                   const struct net_device *dev,
183                                                   u32 flags, u32 noflags);
184
185 static void addrconf_dad_start(struct inet6_ifaddr *ifp);
186 static void addrconf_dad_work(struct work_struct *w);
187 static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id);
188 static void addrconf_dad_run(struct inet6_dev *idev);
189 static void addrconf_rs_timer(unsigned long data);
190 static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
191 static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
192
193 static void inet6_prefix_notify(int event, struct inet6_dev *idev,
194                                 struct prefix_info *pinfo);
195 static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
196                                struct net_device *dev);
197
198 static struct ipv6_devconf ipv6_devconf __read_mostly = {
199         .forwarding             = 0,
200         .hop_limit              = IPV6_DEFAULT_HOPLIMIT,
201         .mtu6                   = IPV6_MIN_MTU,
202         .accept_ra              = 1,
203         .accept_redirects       = 1,
204         .autoconf               = 1,
205         .force_mld_version      = 0,
206         .mldv1_unsolicited_report_interval = 10 * HZ,
207         .mldv2_unsolicited_report_interval = HZ,
208         .dad_transmits          = 1,
209         .rtr_solicits           = MAX_RTR_SOLICITATIONS,
210         .rtr_solicit_interval   = RTR_SOLICITATION_INTERVAL,
211         .rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
212         .rtr_solicit_delay      = MAX_RTR_SOLICITATION_DELAY,
213         .use_tempaddr           = 0,
214         .temp_valid_lft         = TEMP_VALID_LIFETIME,
215         .temp_prefered_lft      = TEMP_PREFERRED_LIFETIME,
216         .regen_max_retry        = REGEN_MAX_RETRY,
217         .max_desync_factor      = MAX_DESYNC_FACTOR,
218         .max_addresses          = IPV6_MAX_ADDRESSES,
219         .accept_ra_defrtr       = 1,
220         .accept_ra_from_local   = 0,
221         .accept_ra_min_hop_limit= 1,
222         .accept_ra_pinfo        = 1,
223 #ifdef CONFIG_IPV6_ROUTER_PREF
224         .accept_ra_rtr_pref     = 1,
225         .rtr_probe_interval     = 60 * HZ,
226 #ifdef CONFIG_IPV6_ROUTE_INFO
227         .accept_ra_rt_info_min_plen = 0,
228         .accept_ra_rt_info_max_plen = 0,
229 #endif
230 #endif
231         .proxy_ndp              = 0,
232         .accept_source_route    = 0,    /* we do not accept RH0 by default. */
233         .disable_ipv6           = 0,
234         .accept_dad             = 1,
235         .suppress_frag_ndisc    = 1,
236         .accept_ra_mtu          = 1,
237         .stable_secret          = {
238                 .initialized = false,
239         },
240         .use_oif_addrs_only     = 0,
241         .ignore_routes_with_linkdown = 0,
242         .keep_addr_on_down      = 0,
243         .seg6_enabled           = 0,
244 #ifdef CONFIG_IPV6_SEG6_HMAC
245         .seg6_require_hmac      = 0,
246 #endif
247         .enhanced_dad           = 1,
248         .addr_gen_mode          = IN6_ADDR_GEN_MODE_EUI64,
249         .disable_policy         = 0,
250 };
251
252 static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
253         .forwarding             = 0,
254         .hop_limit              = IPV6_DEFAULT_HOPLIMIT,
255         .mtu6                   = IPV6_MIN_MTU,
256         .accept_ra              = 1,
257         .accept_redirects       = 1,
258         .autoconf               = 1,
259         .force_mld_version      = 0,
260         .mldv1_unsolicited_report_interval = 10 * HZ,
261         .mldv2_unsolicited_report_interval = HZ,
262         .dad_transmits          = 1,
263         .rtr_solicits           = MAX_RTR_SOLICITATIONS,
264         .rtr_solicit_interval   = RTR_SOLICITATION_INTERVAL,
265         .rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
266         .rtr_solicit_delay      = MAX_RTR_SOLICITATION_DELAY,
267         .use_tempaddr           = 0,
268         .temp_valid_lft         = TEMP_VALID_LIFETIME,
269         .temp_prefered_lft      = TEMP_PREFERRED_LIFETIME,
270         .regen_max_retry        = REGEN_MAX_RETRY,
271         .max_desync_factor      = MAX_DESYNC_FACTOR,
272         .max_addresses          = IPV6_MAX_ADDRESSES,
273         .accept_ra_defrtr       = 1,
274         .accept_ra_from_local   = 0,
275         .accept_ra_min_hop_limit= 1,
276         .accept_ra_pinfo        = 1,
277 #ifdef CONFIG_IPV6_ROUTER_PREF
278         .accept_ra_rtr_pref     = 1,
279         .rtr_probe_interval     = 60 * HZ,
280 #ifdef CONFIG_IPV6_ROUTE_INFO
281         .accept_ra_rt_info_min_plen = 0,
282         .accept_ra_rt_info_max_plen = 0,
283 #endif
284 #endif
285         .proxy_ndp              = 0,
286         .accept_source_route    = 0,    /* we do not accept RH0 by default. */
287         .disable_ipv6           = 0,
288         .accept_dad             = 1,
289         .suppress_frag_ndisc    = 1,
290         .accept_ra_mtu          = 1,
291         .stable_secret          = {
292                 .initialized = false,
293         },
294         .use_oif_addrs_only     = 0,
295         .ignore_routes_with_linkdown = 0,
296         .keep_addr_on_down      = 0,
297         .seg6_enabled           = 0,
298 #ifdef CONFIG_IPV6_SEG6_HMAC
299         .seg6_require_hmac      = 0,
300 #endif
301         .enhanced_dad           = 1,
302         .addr_gen_mode          = IN6_ADDR_GEN_MODE_EUI64,
303         .disable_policy         = 0,
304 };
305
306 /* Check if a valid qdisc is available */
307 static inline bool addrconf_qdisc_ok(const struct net_device *dev)
308 {
309         return !qdisc_tx_is_noop(dev);
310 }
311
312 static void addrconf_del_rs_timer(struct inet6_dev *idev)
313 {
314         if (del_timer(&idev->rs_timer))
315                 __in6_dev_put(idev);
316 }
317
318 static void addrconf_del_dad_work(struct inet6_ifaddr *ifp)
319 {
320         if (cancel_delayed_work(&ifp->dad_work))
321                 __in6_ifa_put(ifp);
322 }
323
324 static void addrconf_mod_rs_timer(struct inet6_dev *idev,
325                                   unsigned long when)
326 {
327         if (!timer_pending(&idev->rs_timer))
328                 in6_dev_hold(idev);
329         mod_timer(&idev->rs_timer, jiffies + when);
330 }
331
332 static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp,
333                                    unsigned long delay)
334 {
335         in6_ifa_hold(ifp);
336         if (mod_delayed_work(addrconf_wq, &ifp->dad_work, delay))
337                 in6_ifa_put(ifp);
338 }
339
340 static int snmp6_alloc_dev(struct inet6_dev *idev)
341 {
342         int i;
343
344         idev->stats.ipv6 = alloc_percpu(struct ipstats_mib);
345         if (!idev->stats.ipv6)
346                 goto err_ip;
347
348         for_each_possible_cpu(i) {
349                 struct ipstats_mib *addrconf_stats;
350                 addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i);
351                 u64_stats_init(&addrconf_stats->syncp);
352         }
353
354
355         idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device),
356                                         GFP_KERNEL);
357         if (!idev->stats.icmpv6dev)
358                 goto err_icmp;
359         idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device),
360                                            GFP_KERNEL);
361         if (!idev->stats.icmpv6msgdev)
362                 goto err_icmpmsg;
363
364         return 0;
365
366 err_icmpmsg:
367         kfree(idev->stats.icmpv6dev);
368 err_icmp:
369         free_percpu(idev->stats.ipv6);
370 err_ip:
371         return -ENOMEM;
372 }
373
374 static struct inet6_dev *ipv6_add_dev(struct net_device *dev)
375 {
376         struct inet6_dev *ndev;
377         int err = -ENOMEM;
378
379         ASSERT_RTNL();
380
381         if (dev->mtu < IPV6_MIN_MTU)
382                 return ERR_PTR(-EINVAL);
383
384         ndev = kzalloc(sizeof(struct inet6_dev), GFP_KERNEL);
385         if (!ndev)
386                 return ERR_PTR(err);
387
388         rwlock_init(&ndev->lock);
389         ndev->dev = dev;
390         INIT_LIST_HEAD(&ndev->addr_list);
391         setup_timer(&ndev->rs_timer, addrconf_rs_timer,
392                     (unsigned long)ndev);
393         memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf));
394
395         if (ndev->cnf.stable_secret.initialized)
396                 ndev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
397         else
398                 ndev->cnf.addr_gen_mode = ipv6_devconf_dflt.addr_gen_mode;
399
400         ndev->cnf.mtu6 = dev->mtu;
401         ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl);
402         if (!ndev->nd_parms) {
403                 kfree(ndev);
404                 return ERR_PTR(err);
405         }
406         if (ndev->cnf.forwarding)
407                 dev_disable_lro(dev);
408         /* We refer to the device */
409         dev_hold(dev);
410
411         if (snmp6_alloc_dev(ndev) < 0) {
412                 ADBG(KERN_WARNING
413                         "%s: cannot allocate memory for statistics; dev=%s.\n",
414                         __func__, dev->name);
415                 neigh_parms_release(&nd_tbl, ndev->nd_parms);
416                 dev_put(dev);
417                 kfree(ndev);
418                 return ERR_PTR(err);
419         }
420
421         if (snmp6_register_dev(ndev) < 0) {
422                 ADBG(KERN_WARNING
423                         "%s: cannot create /proc/net/dev_snmp6/%s\n",
424                         __func__, dev->name);
425                 goto err_release;
426         }
427
428         /* One reference from device. */
429         refcount_set(&ndev->refcnt, 1);
430
431         if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
432                 ndev->cnf.accept_dad = -1;
433
434 #if IS_ENABLED(CONFIG_IPV6_SIT)
435         if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) {
436                 pr_info("%s: Disabled Multicast RS\n", dev->name);
437                 ndev->cnf.rtr_solicits = 0;
438         }
439 #endif
440
441         INIT_LIST_HEAD(&ndev->tempaddr_list);
442         ndev->desync_factor = U32_MAX;
443         if ((dev->flags&IFF_LOOPBACK) ||
444             dev->type == ARPHRD_TUNNEL ||
445             dev->type == ARPHRD_TUNNEL6 ||
446             dev->type == ARPHRD_SIT ||
447             dev->type == ARPHRD_NONE) {
448                 ndev->cnf.use_tempaddr = -1;
449         } else
450                 ipv6_regen_rndid(ndev);
451
452         ndev->token = in6addr_any;
453
454         if (netif_running(dev) && addrconf_qdisc_ok(dev))
455                 ndev->if_flags |= IF_READY;
456
457         ipv6_mc_init_dev(ndev);
458         ndev->tstamp = jiffies;
459         err = addrconf_sysctl_register(ndev);
460         if (err) {
461                 ipv6_mc_destroy_dev(ndev);
462                 snmp6_unregister_dev(ndev);
463                 goto err_release;
464         }
465         /* protected by rtnl_lock */
466         rcu_assign_pointer(dev->ip6_ptr, ndev);
467
468         /* Join interface-local all-node multicast group */
469         ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes);
470
471         /* Join all-node multicast group */
472         ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes);
473
474         /* Join all-router multicast group if forwarding is set */
475         if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST))
476                 ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
477
478         return ndev;
479
480 err_release:
481         neigh_parms_release(&nd_tbl, ndev->nd_parms);
482         ndev->dead = 1;
483         in6_dev_finish_destroy(ndev);
484         return ERR_PTR(err);
485 }
486
487 static struct inet6_dev *ipv6_find_idev(struct net_device *dev)
488 {
489         struct inet6_dev *idev;
490
491         ASSERT_RTNL();
492
493         idev = __in6_dev_get(dev);
494         if (!idev) {
495                 idev = ipv6_add_dev(dev);
496                 if (IS_ERR(idev))
497                         return NULL;
498         }
499
500         if (dev->flags&IFF_UP)
501                 ipv6_mc_up(idev);
502         return idev;
503 }
504
505 static int inet6_netconf_msgsize_devconf(int type)
506 {
507         int size =  NLMSG_ALIGN(sizeof(struct netconfmsg))
508                     + nla_total_size(4);        /* NETCONFA_IFINDEX */
509         bool all = false;
510
511         if (type == NETCONFA_ALL)
512                 all = true;
513
514         if (all || type == NETCONFA_FORWARDING)
515                 size += nla_total_size(4);
516 #ifdef CONFIG_IPV6_MROUTE
517         if (all || type == NETCONFA_MC_FORWARDING)
518                 size += nla_total_size(4);
519 #endif
520         if (all || type == NETCONFA_PROXY_NEIGH)
521                 size += nla_total_size(4);
522
523         if (all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN)
524                 size += nla_total_size(4);
525
526         return size;
527 }
528
529 static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
530                                       struct ipv6_devconf *devconf, u32 portid,
531                                       u32 seq, int event, unsigned int flags,
532                                       int type)
533 {
534         struct nlmsghdr  *nlh;
535         struct netconfmsg *ncm;
536         bool all = false;
537
538         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
539                         flags);
540         if (!nlh)
541                 return -EMSGSIZE;
542
543         if (type == NETCONFA_ALL)
544                 all = true;
545
546         ncm = nlmsg_data(nlh);
547         ncm->ncm_family = AF_INET6;
548
549         if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
550                 goto nla_put_failure;
551
552         if (!devconf)
553                 goto out;
554
555         if ((all || type == NETCONFA_FORWARDING) &&
556             nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0)
557                 goto nla_put_failure;
558 #ifdef CONFIG_IPV6_MROUTE
559         if ((all || type == NETCONFA_MC_FORWARDING) &&
560             nla_put_s32(skb, NETCONFA_MC_FORWARDING,
561                         devconf->mc_forwarding) < 0)
562                 goto nla_put_failure;
563 #endif
564         if ((all || type == NETCONFA_PROXY_NEIGH) &&
565             nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0)
566                 goto nla_put_failure;
567
568         if ((all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN) &&
569             nla_put_s32(skb, NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
570                         devconf->ignore_routes_with_linkdown) < 0)
571                 goto nla_put_failure;
572
573 out:
574         nlmsg_end(skb, nlh);
575         return 0;
576
577 nla_put_failure:
578         nlmsg_cancel(skb, nlh);
579         return -EMSGSIZE;
580 }
581
582 void inet6_netconf_notify_devconf(struct net *net, int event, int type,
583                                   int ifindex, struct ipv6_devconf *devconf)
584 {
585         struct sk_buff *skb;
586         int err = -ENOBUFS;
587
588         skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_KERNEL);
589         if (!skb)
590                 goto errout;
591
592         err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0,
593                                          event, 0, type);
594         if (err < 0) {
595                 /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
596                 WARN_ON(err == -EMSGSIZE);
597                 kfree_skb(skb);
598                 goto errout;
599         }
600         rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_KERNEL);
601         return;
602 errout:
603         rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err);
604 }
605
606 static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = {
607         [NETCONFA_IFINDEX]      = { .len = sizeof(int) },
608         [NETCONFA_FORWARDING]   = { .len = sizeof(int) },
609         [NETCONFA_PROXY_NEIGH]  = { .len = sizeof(int) },
610         [NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN]  = { .len = sizeof(int) },
611 };
612
613 static int inet6_netconf_get_devconf(struct sk_buff *in_skb,
614                                      struct nlmsghdr *nlh,
615                                      struct netlink_ext_ack *extack)
616 {
617         struct net *net = sock_net(in_skb->sk);
618         struct nlattr *tb[NETCONFA_MAX+1];
619         struct netconfmsg *ncm;
620         struct sk_buff *skb;
621         struct ipv6_devconf *devconf;
622         struct inet6_dev *in6_dev;
623         struct net_device *dev;
624         int ifindex;
625         int err;
626
627         err = nlmsg_parse(nlh, sizeof(*ncm), tb, NETCONFA_MAX,
628                           devconf_ipv6_policy, extack);
629         if (err < 0)
630                 goto errout;
631
632         err = -EINVAL;
633         if (!tb[NETCONFA_IFINDEX])
634                 goto errout;
635
636         ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
637         switch (ifindex) {
638         case NETCONFA_IFINDEX_ALL:
639                 devconf = net->ipv6.devconf_all;
640                 break;
641         case NETCONFA_IFINDEX_DEFAULT:
642                 devconf = net->ipv6.devconf_dflt;
643                 break;
644         default:
645                 dev = __dev_get_by_index(net, ifindex);
646                 if (!dev)
647                         goto errout;
648                 in6_dev = __in6_dev_get(dev);
649                 if (!in6_dev)
650                         goto errout;
651                 devconf = &in6_dev->cnf;
652                 break;
653         }
654
655         err = -ENOBUFS;
656         skb = nlmsg_new(inet6_netconf_msgsize_devconf(NETCONFA_ALL), GFP_ATOMIC);
657         if (!skb)
658                 goto errout;
659
660         err = inet6_netconf_fill_devconf(skb, ifindex, devconf,
661                                          NETLINK_CB(in_skb).portid,
662                                          nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
663                                          NETCONFA_ALL);
664         if (err < 0) {
665                 /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
666                 WARN_ON(err == -EMSGSIZE);
667                 kfree_skb(skb);
668                 goto errout;
669         }
670         err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
671 errout:
672         return err;
673 }
674
675 static int inet6_netconf_dump_devconf(struct sk_buff *skb,
676                                       struct netlink_callback *cb)
677 {
678         struct net *net = sock_net(skb->sk);
679         int h, s_h;
680         int idx, s_idx;
681         struct net_device *dev;
682         struct inet6_dev *idev;
683         struct hlist_head *head;
684
685         s_h = cb->args[0];
686         s_idx = idx = cb->args[1];
687
688         for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
689                 idx = 0;
690                 head = &net->dev_index_head[h];
691                 rcu_read_lock();
692                 cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^
693                           net->dev_base_seq;
694                 hlist_for_each_entry_rcu(dev, head, index_hlist) {
695                         if (idx < s_idx)
696                                 goto cont;
697                         idev = __in6_dev_get(dev);
698                         if (!idev)
699                                 goto cont;
700
701                         if (inet6_netconf_fill_devconf(skb, dev->ifindex,
702                                                        &idev->cnf,
703                                                        NETLINK_CB(cb->skb).portid,
704                                                        cb->nlh->nlmsg_seq,
705                                                        RTM_NEWNETCONF,
706                                                        NLM_F_MULTI,
707                                                        NETCONFA_ALL) < 0) {
708                                 rcu_read_unlock();
709                                 goto done;
710                         }
711                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
712 cont:
713                         idx++;
714                 }
715                 rcu_read_unlock();
716         }
717         if (h == NETDEV_HASHENTRIES) {
718                 if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL,
719                                                net->ipv6.devconf_all,
720                                                NETLINK_CB(cb->skb).portid,
721                                                cb->nlh->nlmsg_seq,
722                                                RTM_NEWNETCONF, NLM_F_MULTI,
723                                                NETCONFA_ALL) < 0)
724                         goto done;
725                 else
726                         h++;
727         }
728         if (h == NETDEV_HASHENTRIES + 1) {
729                 if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT,
730                                                net->ipv6.devconf_dflt,
731                                                NETLINK_CB(cb->skb).portid,
732                                                cb->nlh->nlmsg_seq,
733                                                RTM_NEWNETCONF, NLM_F_MULTI,
734                                                NETCONFA_ALL) < 0)
735                         goto done;
736                 else
737                         h++;
738         }
739 done:
740         cb->args[0] = h;
741         cb->args[1] = idx;
742
743         return skb->len;
744 }
745
746 #ifdef CONFIG_SYSCTL
747 static void dev_forward_change(struct inet6_dev *idev)
748 {
749         struct net_device *dev;
750         struct inet6_ifaddr *ifa;
751
752         if (!idev)
753                 return;
754         dev = idev->dev;
755         if (idev->cnf.forwarding)
756                 dev_disable_lro(dev);
757         if (dev->flags & IFF_MULTICAST) {
758                 if (idev->cnf.forwarding) {
759                         ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
760                         ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters);
761                         ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters);
762                 } else {
763                         ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters);
764                         ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters);
765                         ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters);
766                 }
767         }
768
769         list_for_each_entry(ifa, &idev->addr_list, if_list) {
770                 if (ifa->flags&IFA_F_TENTATIVE)
771                         continue;
772                 if (idev->cnf.forwarding)
773                         addrconf_join_anycast(ifa);
774                 else
775                         addrconf_leave_anycast(ifa);
776         }
777         inet6_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
778                                      NETCONFA_FORWARDING,
779                                      dev->ifindex, &idev->cnf);
780 }
781
782
783 static void addrconf_forward_change(struct net *net, __s32 newf)
784 {
785         struct net_device *dev;
786         struct inet6_dev *idev;
787
788         for_each_netdev(net, dev) {
789                 idev = __in6_dev_get(dev);
790                 if (idev) {
791                         int changed = (!idev->cnf.forwarding) ^ (!newf);
792                         idev->cnf.forwarding = newf;
793                         if (changed)
794                                 dev_forward_change(idev);
795                 }
796         }
797 }
798
799 static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf)
800 {
801         struct net *net;
802         int old;
803
804         if (!rtnl_trylock())
805                 return restart_syscall();
806
807         net = (struct net *)table->extra2;
808         old = *p;
809         *p = newf;
810
811         if (p == &net->ipv6.devconf_dflt->forwarding) {
812                 if ((!newf) ^ (!old))
813                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
814                                                      NETCONFA_FORWARDING,
815                                                      NETCONFA_IFINDEX_DEFAULT,
816                                                      net->ipv6.devconf_dflt);
817                 rtnl_unlock();
818                 return 0;
819         }
820
821         if (p == &net->ipv6.devconf_all->forwarding) {
822                 int old_dflt = net->ipv6.devconf_dflt->forwarding;
823
824                 net->ipv6.devconf_dflt->forwarding = newf;
825                 if ((!newf) ^ (!old_dflt))
826                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
827                                                      NETCONFA_FORWARDING,
828                                                      NETCONFA_IFINDEX_DEFAULT,
829                                                      net->ipv6.devconf_dflt);
830
831                 addrconf_forward_change(net, newf);
832                 if ((!newf) ^ (!old))
833                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
834                                                      NETCONFA_FORWARDING,
835                                                      NETCONFA_IFINDEX_ALL,
836                                                      net->ipv6.devconf_all);
837         } else if ((!newf) ^ (!old))
838                 dev_forward_change((struct inet6_dev *)table->extra1);
839         rtnl_unlock();
840
841         if (newf)
842                 rt6_purge_dflt_routers(net);
843         return 1;
844 }
845
846 static void addrconf_linkdown_change(struct net *net, __s32 newf)
847 {
848         struct net_device *dev;
849         struct inet6_dev *idev;
850
851         for_each_netdev(net, dev) {
852                 idev = __in6_dev_get(dev);
853                 if (idev) {
854                         int changed = (!idev->cnf.ignore_routes_with_linkdown) ^ (!newf);
855
856                         idev->cnf.ignore_routes_with_linkdown = newf;
857                         if (changed)
858                                 inet6_netconf_notify_devconf(dev_net(dev),
859                                                              RTM_NEWNETCONF,
860                                                              NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
861                                                              dev->ifindex,
862                                                              &idev->cnf);
863                 }
864         }
865 }
866
867 static int addrconf_fixup_linkdown(struct ctl_table *table, int *p, int newf)
868 {
869         struct net *net;
870         int old;
871
872         if (!rtnl_trylock())
873                 return restart_syscall();
874
875         net = (struct net *)table->extra2;
876         old = *p;
877         *p = newf;
878
879         if (p == &net->ipv6.devconf_dflt->ignore_routes_with_linkdown) {
880                 if ((!newf) ^ (!old))
881                         inet6_netconf_notify_devconf(net,
882                                                      RTM_NEWNETCONF,
883                                                      NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
884                                                      NETCONFA_IFINDEX_DEFAULT,
885                                                      net->ipv6.devconf_dflt);
886                 rtnl_unlock();
887                 return 0;
888         }
889
890         if (p == &net->ipv6.devconf_all->ignore_routes_with_linkdown) {
891                 net->ipv6.devconf_dflt->ignore_routes_with_linkdown = newf;
892                 addrconf_linkdown_change(net, newf);
893                 if ((!newf) ^ (!old))
894                         inet6_netconf_notify_devconf(net,
895                                                      RTM_NEWNETCONF,
896                                                      NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
897                                                      NETCONFA_IFINDEX_ALL,
898                                                      net->ipv6.devconf_all);
899         }
900         rtnl_unlock();
901
902         return 1;
903 }
904
905 #endif
906
907 /* Nobody refers to this ifaddr, destroy it */
908 void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp)
909 {
910         WARN_ON(!hlist_unhashed(&ifp->addr_lst));
911
912 #ifdef NET_REFCNT_DEBUG
913         pr_debug("%s\n", __func__);
914 #endif
915
916         in6_dev_put(ifp->idev);
917
918         if (cancel_delayed_work(&ifp->dad_work))
919                 pr_notice("delayed DAD work was pending while freeing ifa=%p\n",
920                           ifp);
921
922         if (ifp->state != INET6_IFADDR_STATE_DEAD) {
923                 pr_warn("Freeing alive inet6 address %p\n", ifp);
924                 return;
925         }
926         ip6_rt_put(ifp->rt);
927
928         kfree_rcu(ifp, rcu);
929 }
930
931 static void
932 ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp)
933 {
934         struct list_head *p;
935         int ifp_scope = ipv6_addr_src_scope(&ifp->addr);
936
937         /*
938          * Each device address list is sorted in order of scope -
939          * global before linklocal.
940          */
941         list_for_each(p, &idev->addr_list) {
942                 struct inet6_ifaddr *ifa
943                         = list_entry(p, struct inet6_ifaddr, if_list);
944                 if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr))
945                         break;
946         }
947
948         list_add_tail(&ifp->if_list, p);
949 }
950
951 static u32 inet6_addr_hash(const struct in6_addr *addr)
952 {
953         return hash_32(ipv6_addr_hash(addr), IN6_ADDR_HSIZE_SHIFT);
954 }
955
956 /* On success it returns ifp with increased reference count */
957
958 static struct inet6_ifaddr *
959 ipv6_add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
960               const struct in6_addr *peer_addr, int pfxlen,
961               int scope, u32 flags, u32 valid_lft, u32 prefered_lft)
962 {
963         struct net *net = dev_net(idev->dev);
964         struct inet6_ifaddr *ifa = NULL;
965         struct rt6_info *rt;
966         struct in6_validator_info i6vi;
967         unsigned int hash;
968         int err = 0;
969         int addr_type = ipv6_addr_type(addr);
970
971         if (addr_type == IPV6_ADDR_ANY ||
972             addr_type & IPV6_ADDR_MULTICAST ||
973             (!(idev->dev->flags & IFF_LOOPBACK) &&
974              addr_type & IPV6_ADDR_LOOPBACK))
975                 return ERR_PTR(-EADDRNOTAVAIL);
976
977         rcu_read_lock_bh();
978
979         in6_dev_hold(idev);
980
981         if (idev->dead) {
982                 err = -ENODEV;                  /*XXX*/
983                 goto out2;
984         }
985
986         if (idev->cnf.disable_ipv6) {
987                 err = -EACCES;
988                 goto out2;
989         }
990
991         i6vi.i6vi_addr = *addr;
992         i6vi.i6vi_dev = idev;
993         rcu_read_unlock_bh();
994
995         err = inet6addr_validator_notifier_call_chain(NETDEV_UP, &i6vi);
996
997         rcu_read_lock_bh();
998         err = notifier_to_errno(err);
999         if (err)
1000                 goto out2;
1001
1002         spin_lock(&addrconf_hash_lock);
1003
1004         /* Ignore adding duplicate addresses on an interface */
1005         if (ipv6_chk_same_addr(dev_net(idev->dev), addr, idev->dev)) {
1006                 ADBG("ipv6_add_addr: already assigned\n");
1007                 err = -EEXIST;
1008                 goto out;
1009         }
1010
1011         ifa = kzalloc(sizeof(struct inet6_ifaddr), GFP_ATOMIC);
1012
1013         if (!ifa) {
1014                 ADBG("ipv6_add_addr: malloc failed\n");
1015                 err = -ENOBUFS;
1016                 goto out;
1017         }
1018
1019         rt = addrconf_dst_alloc(idev, addr, false);
1020         if (IS_ERR(rt)) {
1021                 err = PTR_ERR(rt);
1022                 goto out;
1023         }
1024
1025         if (net->ipv6.devconf_all->disable_policy ||
1026             idev->cnf.disable_policy)
1027                 rt->dst.flags |= DST_NOPOLICY;
1028
1029         neigh_parms_data_state_setall(idev->nd_parms);
1030
1031         ifa->addr = *addr;
1032         if (peer_addr)
1033                 ifa->peer_addr = *peer_addr;
1034
1035         spin_lock_init(&ifa->lock);
1036         INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work);
1037         INIT_HLIST_NODE(&ifa->addr_lst);
1038         ifa->scope = scope;
1039         ifa->prefix_len = pfxlen;
1040         ifa->flags = flags;
1041         /* No need to add the TENTATIVE flag for addresses with NODAD */
1042         if (!(flags & IFA_F_NODAD))
1043                 ifa->flags |= IFA_F_TENTATIVE;
1044         ifa->valid_lft = valid_lft;
1045         ifa->prefered_lft = prefered_lft;
1046         ifa->cstamp = ifa->tstamp = jiffies;
1047         ifa->tokenized = false;
1048
1049         ifa->rt = rt;
1050
1051         ifa->idev = idev;
1052         /* For caller */
1053         refcount_set(&ifa->refcnt, 1);
1054
1055         /* Add to big hash table */
1056         hash = inet6_addr_hash(addr);
1057
1058         hlist_add_head_rcu(&ifa->addr_lst, &inet6_addr_lst[hash]);
1059         spin_unlock(&addrconf_hash_lock);
1060
1061         write_lock(&idev->lock);
1062         /* Add to inet6_dev unicast addr list. */
1063         ipv6_link_dev_addr(idev, ifa);
1064
1065         if (ifa->flags&IFA_F_TEMPORARY) {
1066                 list_add(&ifa->tmp_list, &idev->tempaddr_list);
1067                 in6_ifa_hold(ifa);
1068         }
1069
1070         in6_ifa_hold(ifa);
1071         write_unlock(&idev->lock);
1072 out2:
1073         rcu_read_unlock_bh();
1074
1075         if (likely(err == 0))
1076                 inet6addr_notifier_call_chain(NETDEV_UP, ifa);
1077         else {
1078                 kfree(ifa);
1079                 in6_dev_put(idev);
1080                 ifa = ERR_PTR(err);
1081         }
1082
1083         return ifa;
1084 out:
1085         spin_unlock(&addrconf_hash_lock);
1086         goto out2;
1087 }
1088
1089 enum cleanup_prefix_rt_t {
1090         CLEANUP_PREFIX_RT_NOP,    /* no cleanup action for prefix route */
1091         CLEANUP_PREFIX_RT_DEL,    /* delete the prefix route */
1092         CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */
1093 };
1094
1095 /*
1096  * Check, whether the prefix for ifp would still need a prefix route
1097  * after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_*
1098  * constants.
1099  *
1100  * 1) we don't purge prefix if address was not permanent.
1101  *    prefix is managed by its own lifetime.
1102  * 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE.
1103  * 3) if there are no addresses, delete prefix.
1104  * 4) if there are still other permanent address(es),
1105  *    corresponding prefix is still permanent.
1106  * 5) if there are still other addresses with IFA_F_NOPREFIXROUTE,
1107  *    don't purge the prefix, assume user space is managing it.
1108  * 6) otherwise, update prefix lifetime to the
1109  *    longest valid lifetime among the corresponding
1110  *    addresses on the device.
1111  *    Note: subsequent RA will update lifetime.
1112  **/
1113 static enum cleanup_prefix_rt_t
1114 check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires)
1115 {
1116         struct inet6_ifaddr *ifa;
1117         struct inet6_dev *idev = ifp->idev;
1118         unsigned long lifetime;
1119         enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL;
1120
1121         *expires = jiffies;
1122
1123         list_for_each_entry(ifa, &idev->addr_list, if_list) {
1124                 if (ifa == ifp)
1125                         continue;
1126                 if (!ipv6_prefix_equal(&ifa->addr, &ifp->addr,
1127                                        ifp->prefix_len))
1128                         continue;
1129                 if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE))
1130                         return CLEANUP_PREFIX_RT_NOP;
1131
1132                 action = CLEANUP_PREFIX_RT_EXPIRE;
1133
1134                 spin_lock(&ifa->lock);
1135
1136                 lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ);
1137                 /*
1138                  * Note: Because this address is
1139                  * not permanent, lifetime <
1140                  * LONG_MAX / HZ here.
1141                  */
1142                 if (time_before(*expires, ifa->tstamp + lifetime * HZ))
1143                         *expires = ifa->tstamp + lifetime * HZ;
1144                 spin_unlock(&ifa->lock);
1145         }
1146
1147         return action;
1148 }
1149
1150 static void
1151 cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires, bool del_rt)
1152 {
1153         struct rt6_info *rt;
1154
1155         rt = addrconf_get_prefix_route(&ifp->addr,
1156                                        ifp->prefix_len,
1157                                        ifp->idev->dev,
1158                                        0, RTF_GATEWAY | RTF_DEFAULT);
1159         if (rt) {
1160                 if (del_rt)
1161                         ip6_del_rt(rt);
1162                 else {
1163                         if (!(rt->rt6i_flags & RTF_EXPIRES))
1164                                 rt6_set_expires(rt, expires);
1165                         ip6_rt_put(rt);
1166                 }
1167         }
1168 }
1169
1170
1171 /* This function wants to get referenced ifp and releases it before return */
1172
1173 static void ipv6_del_addr(struct inet6_ifaddr *ifp)
1174 {
1175         int state;
1176         enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP;
1177         unsigned long expires;
1178
1179         ASSERT_RTNL();
1180
1181         spin_lock_bh(&ifp->lock);
1182         state = ifp->state;
1183         ifp->state = INET6_IFADDR_STATE_DEAD;
1184         spin_unlock_bh(&ifp->lock);
1185
1186         if (state == INET6_IFADDR_STATE_DEAD)
1187                 goto out;
1188
1189         spin_lock_bh(&addrconf_hash_lock);
1190         hlist_del_init_rcu(&ifp->addr_lst);
1191         spin_unlock_bh(&addrconf_hash_lock);
1192
1193         write_lock_bh(&ifp->idev->lock);
1194
1195         if (ifp->flags&IFA_F_TEMPORARY) {
1196                 list_del(&ifp->tmp_list);
1197                 if (ifp->ifpub) {
1198                         in6_ifa_put(ifp->ifpub);
1199                         ifp->ifpub = NULL;
1200                 }
1201                 __in6_ifa_put(ifp);
1202         }
1203
1204         if (ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE))
1205                 action = check_cleanup_prefix_route(ifp, &expires);
1206
1207         list_del_init(&ifp->if_list);
1208         __in6_ifa_put(ifp);
1209
1210         write_unlock_bh(&ifp->idev->lock);
1211
1212         addrconf_del_dad_work(ifp);
1213
1214         ipv6_ifa_notify(RTM_DELADDR, ifp);
1215
1216         inet6addr_notifier_call_chain(NETDEV_DOWN, ifp);
1217
1218         if (action != CLEANUP_PREFIX_RT_NOP) {
1219                 cleanup_prefix_route(ifp, expires,
1220                         action == CLEANUP_PREFIX_RT_DEL);
1221         }
1222
1223         /* clean up prefsrc entries */
1224         rt6_remove_prefsrc(ifp);
1225 out:
1226         in6_ifa_put(ifp);
1227 }
1228
1229 static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, struct inet6_ifaddr *ift)
1230 {
1231         struct inet6_dev *idev = ifp->idev;
1232         struct in6_addr addr, *tmpaddr;
1233         unsigned long tmp_prefered_lft, tmp_valid_lft, tmp_tstamp, age;
1234         unsigned long regen_advance;
1235         int tmp_plen;
1236         int ret = 0;
1237         u32 addr_flags;
1238         unsigned long now = jiffies;
1239         long max_desync_factor;
1240         s32 cnf_temp_preferred_lft;
1241
1242         write_lock_bh(&idev->lock);
1243         if (ift) {
1244                 spin_lock_bh(&ift->lock);
1245                 memcpy(&addr.s6_addr[8], &ift->addr.s6_addr[8], 8);
1246                 spin_unlock_bh(&ift->lock);
1247                 tmpaddr = &addr;
1248         } else {
1249                 tmpaddr = NULL;
1250         }
1251 retry:
1252         in6_dev_hold(idev);
1253         if (idev->cnf.use_tempaddr <= 0) {
1254                 write_unlock_bh(&idev->lock);
1255                 pr_info("%s: use_tempaddr is disabled\n", __func__);
1256                 in6_dev_put(idev);
1257                 ret = -1;
1258                 goto out;
1259         }
1260         spin_lock_bh(&ifp->lock);
1261         if (ifp->regen_count++ >= idev->cnf.regen_max_retry) {
1262                 idev->cnf.use_tempaddr = -1;    /*XXX*/
1263                 spin_unlock_bh(&ifp->lock);
1264                 write_unlock_bh(&idev->lock);
1265                 pr_warn("%s: regeneration time exceeded - disabled temporary address support\n",
1266                         __func__);
1267                 in6_dev_put(idev);
1268                 ret = -1;
1269                 goto out;
1270         }
1271         in6_ifa_hold(ifp);
1272         memcpy(addr.s6_addr, ifp->addr.s6_addr, 8);
1273         ipv6_try_regen_rndid(idev, tmpaddr);
1274         memcpy(&addr.s6_addr[8], idev->rndid, 8);
1275         age = (now - ifp->tstamp) / HZ;
1276
1277         regen_advance = idev->cnf.regen_max_retry *
1278                         idev->cnf.dad_transmits *
1279                         NEIGH_VAR(idev->nd_parms, RETRANS_TIME) / HZ;
1280
1281         /* recalculate max_desync_factor each time and update
1282          * idev->desync_factor if it's larger
1283          */
1284         cnf_temp_preferred_lft = READ_ONCE(idev->cnf.temp_prefered_lft);
1285         max_desync_factor = min_t(__u32,
1286                                   idev->cnf.max_desync_factor,
1287                                   cnf_temp_preferred_lft - regen_advance);
1288
1289         if (unlikely(idev->desync_factor > max_desync_factor)) {
1290                 if (max_desync_factor > 0) {
1291                         get_random_bytes(&idev->desync_factor,
1292                                          sizeof(idev->desync_factor));
1293                         idev->desync_factor %= max_desync_factor;
1294                 } else {
1295                         idev->desync_factor = 0;
1296                 }
1297         }
1298
1299         tmp_valid_lft = min_t(__u32,
1300                               ifp->valid_lft,
1301                               idev->cnf.temp_valid_lft + age);
1302         tmp_prefered_lft = cnf_temp_preferred_lft + age -
1303                             idev->desync_factor;
1304         tmp_prefered_lft = min_t(__u32, ifp->prefered_lft, tmp_prefered_lft);
1305         tmp_plen = ifp->prefix_len;
1306         tmp_tstamp = ifp->tstamp;
1307         spin_unlock_bh(&ifp->lock);
1308
1309         write_unlock_bh(&idev->lock);
1310
1311         /* A temporary address is created only if this calculated Preferred
1312          * Lifetime is greater than REGEN_ADVANCE time units.  In particular,
1313          * an implementation must not create a temporary address with a zero
1314          * Preferred Lifetime.
1315          * Use age calculation as in addrconf_verify to avoid unnecessary
1316          * temporary addresses being generated.
1317          */
1318         age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
1319         if (tmp_prefered_lft <= regen_advance + age) {
1320                 in6_ifa_put(ifp);
1321                 in6_dev_put(idev);
1322                 ret = -1;
1323                 goto out;
1324         }
1325
1326         addr_flags = IFA_F_TEMPORARY;
1327         /* set in addrconf_prefix_rcv() */
1328         if (ifp->flags & IFA_F_OPTIMISTIC)
1329                 addr_flags |= IFA_F_OPTIMISTIC;
1330
1331         ift = ipv6_add_addr(idev, &addr, NULL, tmp_plen,
1332                             ipv6_addr_scope(&addr), addr_flags,
1333                             tmp_valid_lft, tmp_prefered_lft);
1334         if (IS_ERR(ift)) {
1335                 in6_ifa_put(ifp);
1336                 in6_dev_put(idev);
1337                 pr_info("%s: retry temporary address regeneration\n", __func__);
1338                 tmpaddr = &addr;
1339                 write_lock_bh(&idev->lock);
1340                 goto retry;
1341         }
1342
1343         spin_lock_bh(&ift->lock);
1344         ift->ifpub = ifp;
1345         ift->cstamp = now;
1346         ift->tstamp = tmp_tstamp;
1347         spin_unlock_bh(&ift->lock);
1348
1349         addrconf_dad_start(ift);
1350         in6_ifa_put(ift);
1351         in6_dev_put(idev);
1352 out:
1353         return ret;
1354 }
1355
1356 /*
1357  *      Choose an appropriate source address (RFC3484)
1358  */
1359 enum {
1360         IPV6_SADDR_RULE_INIT = 0,
1361         IPV6_SADDR_RULE_LOCAL,
1362         IPV6_SADDR_RULE_SCOPE,
1363         IPV6_SADDR_RULE_PREFERRED,
1364 #ifdef CONFIG_IPV6_MIP6
1365         IPV6_SADDR_RULE_HOA,
1366 #endif
1367         IPV6_SADDR_RULE_OIF,
1368         IPV6_SADDR_RULE_LABEL,
1369         IPV6_SADDR_RULE_PRIVACY,
1370         IPV6_SADDR_RULE_ORCHID,
1371         IPV6_SADDR_RULE_PREFIX,
1372 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1373         IPV6_SADDR_RULE_NOT_OPTIMISTIC,
1374 #endif
1375         IPV6_SADDR_RULE_MAX
1376 };
1377
1378 struct ipv6_saddr_score {
1379         int                     rule;
1380         int                     addr_type;
1381         struct inet6_ifaddr     *ifa;
1382         DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX);
1383         int                     scopedist;
1384         int                     matchlen;
1385 };
1386
1387 struct ipv6_saddr_dst {
1388         const struct in6_addr *addr;
1389         int ifindex;
1390         int scope;
1391         int label;
1392         unsigned int prefs;
1393 };
1394
1395 static inline int ipv6_saddr_preferred(int type)
1396 {
1397         if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK))
1398                 return 1;
1399         return 0;
1400 }
1401
1402 static bool ipv6_use_optimistic_addr(struct net *net,
1403                                      struct inet6_dev *idev)
1404 {
1405 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1406         if (!idev)
1407                 return false;
1408         if (!net->ipv6.devconf_all->optimistic_dad && !idev->cnf.optimistic_dad)
1409                 return false;
1410         if (!net->ipv6.devconf_all->use_optimistic && !idev->cnf.use_optimistic)
1411                 return false;
1412
1413         return true;
1414 #else
1415         return false;
1416 #endif
1417 }
1418
1419 static int ipv6_get_saddr_eval(struct net *net,
1420                                struct ipv6_saddr_score *score,
1421                                struct ipv6_saddr_dst *dst,
1422                                int i)
1423 {
1424         int ret;
1425
1426         if (i <= score->rule) {
1427                 switch (i) {
1428                 case IPV6_SADDR_RULE_SCOPE:
1429                         ret = score->scopedist;
1430                         break;
1431                 case IPV6_SADDR_RULE_PREFIX:
1432                         ret = score->matchlen;
1433                         break;
1434                 default:
1435                         ret = !!test_bit(i, score->scorebits);
1436                 }
1437                 goto out;
1438         }
1439
1440         switch (i) {
1441         case IPV6_SADDR_RULE_INIT:
1442                 /* Rule 0: remember if hiscore is not ready yet */
1443                 ret = !!score->ifa;
1444                 break;
1445         case IPV6_SADDR_RULE_LOCAL:
1446                 /* Rule 1: Prefer same address */
1447                 ret = ipv6_addr_equal(&score->ifa->addr, dst->addr);
1448                 break;
1449         case IPV6_SADDR_RULE_SCOPE:
1450                 /* Rule 2: Prefer appropriate scope
1451                  *
1452                  *      ret
1453                  *       ^
1454                  *    -1 |  d 15
1455                  *    ---+--+-+---> scope
1456                  *       |
1457                  *       |             d is scope of the destination.
1458                  *  B-d  |  \
1459                  *       |   \      <- smaller scope is better if
1460                  *  B-15 |    \        if scope is enough for destination.
1461                  *       |             ret = B - scope (-1 <= scope >= d <= 15).
1462                  * d-C-1 | /
1463                  *       |/         <- greater is better
1464                  *   -C  /             if scope is not enough for destination.
1465                  *      /|             ret = scope - C (-1 <= d < scope <= 15).
1466                  *
1467                  * d - C - 1 < B -15 (for all -1 <= d <= 15).
1468                  * C > d + 14 - B >= 15 + 14 - B = 29 - B.
1469                  * Assume B = 0 and we get C > 29.
1470                  */
1471                 ret = __ipv6_addr_src_scope(score->addr_type);
1472                 if (ret >= dst->scope)
1473                         ret = -ret;
1474                 else
1475                         ret -= 128;     /* 30 is enough */
1476                 score->scopedist = ret;
1477                 break;
1478         case IPV6_SADDR_RULE_PREFERRED:
1479             {
1480                 /* Rule 3: Avoid deprecated and optimistic addresses */
1481                 u8 avoid = IFA_F_DEPRECATED;
1482
1483                 if (!ipv6_use_optimistic_addr(net, score->ifa->idev))
1484                         avoid |= IFA_F_OPTIMISTIC;
1485                 ret = ipv6_saddr_preferred(score->addr_type) ||
1486                       !(score->ifa->flags & avoid);
1487                 break;
1488             }
1489 #ifdef CONFIG_IPV6_MIP6
1490         case IPV6_SADDR_RULE_HOA:
1491             {
1492                 /* Rule 4: Prefer home address */
1493                 int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA);
1494                 ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome;
1495                 break;
1496             }
1497 #endif
1498         case IPV6_SADDR_RULE_OIF:
1499                 /* Rule 5: Prefer outgoing interface */
1500                 ret = (!dst->ifindex ||
1501                        dst->ifindex == score->ifa->idev->dev->ifindex);
1502                 break;
1503         case IPV6_SADDR_RULE_LABEL:
1504                 /* Rule 6: Prefer matching label */
1505                 ret = ipv6_addr_label(net,
1506                                       &score->ifa->addr, score->addr_type,
1507                                       score->ifa->idev->dev->ifindex) == dst->label;
1508                 break;
1509         case IPV6_SADDR_RULE_PRIVACY:
1510             {
1511                 /* Rule 7: Prefer public address
1512                  * Note: prefer temporary address if use_tempaddr >= 2
1513                  */
1514                 int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ?
1515                                 !!(dst->prefs & IPV6_PREFER_SRC_TMP) :
1516                                 score->ifa->idev->cnf.use_tempaddr >= 2;
1517                 ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp;
1518                 break;
1519             }
1520         case IPV6_SADDR_RULE_ORCHID:
1521                 /* Rule 8-: Prefer ORCHID vs ORCHID or
1522                  *          non-ORCHID vs non-ORCHID
1523                  */
1524                 ret = !(ipv6_addr_orchid(&score->ifa->addr) ^
1525                         ipv6_addr_orchid(dst->addr));
1526                 break;
1527         case IPV6_SADDR_RULE_PREFIX:
1528                 /* Rule 8: Use longest matching prefix */
1529                 ret = ipv6_addr_diff(&score->ifa->addr, dst->addr);
1530                 if (ret > score->ifa->prefix_len)
1531                         ret = score->ifa->prefix_len;
1532                 score->matchlen = ret;
1533                 break;
1534 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1535         case IPV6_SADDR_RULE_NOT_OPTIMISTIC:
1536                 /* Optimistic addresses still have lower precedence than other
1537                  * preferred addresses.
1538                  */
1539                 ret = !(score->ifa->flags & IFA_F_OPTIMISTIC);
1540                 break;
1541 #endif
1542         default:
1543                 ret = 0;
1544         }
1545
1546         if (ret)
1547                 __set_bit(i, score->scorebits);
1548         score->rule = i;
1549 out:
1550         return ret;
1551 }
1552
1553 static int __ipv6_dev_get_saddr(struct net *net,
1554                                 struct ipv6_saddr_dst *dst,
1555                                 struct inet6_dev *idev,
1556                                 struct ipv6_saddr_score *scores,
1557                                 int hiscore_idx)
1558 {
1559         struct ipv6_saddr_score *score = &scores[1 - hiscore_idx], *hiscore = &scores[hiscore_idx];
1560
1561         read_lock_bh(&idev->lock);
1562         list_for_each_entry(score->ifa, &idev->addr_list, if_list) {
1563                 int i;
1564
1565                 /*
1566                  * - Tentative Address (RFC2462 section 5.4)
1567                  *  - A tentative address is not considered
1568                  *    "assigned to an interface" in the traditional
1569                  *    sense, unless it is also flagged as optimistic.
1570                  * - Candidate Source Address (section 4)
1571                  *  - In any case, anycast addresses, multicast
1572                  *    addresses, and the unspecified address MUST
1573                  *    NOT be included in a candidate set.
1574                  */
1575                 if ((score->ifa->flags & IFA_F_TENTATIVE) &&
1576                     (!(score->ifa->flags & IFA_F_OPTIMISTIC)))
1577                         continue;
1578
1579                 score->addr_type = __ipv6_addr_type(&score->ifa->addr);
1580
1581                 if (unlikely(score->addr_type == IPV6_ADDR_ANY ||
1582                              score->addr_type & IPV6_ADDR_MULTICAST)) {
1583                         net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s",
1584                                             idev->dev->name);
1585                         continue;
1586                 }
1587
1588                 score->rule = -1;
1589                 bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX);
1590
1591                 for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) {
1592                         int minihiscore, miniscore;
1593
1594                         minihiscore = ipv6_get_saddr_eval(net, hiscore, dst, i);
1595                         miniscore = ipv6_get_saddr_eval(net, score, dst, i);
1596
1597                         if (minihiscore > miniscore) {
1598                                 if (i == IPV6_SADDR_RULE_SCOPE &&
1599                                     score->scopedist > 0) {
1600                                         /*
1601                                          * special case:
1602                                          * each remaining entry
1603                                          * has too small (not enough)
1604                                          * scope, because ifa entries
1605                                          * are sorted by their scope
1606                                          * values.
1607                                          */
1608                                         goto out;
1609                                 }
1610                                 break;
1611                         } else if (minihiscore < miniscore) {
1612                                 if (hiscore->ifa)
1613                                         in6_ifa_put(hiscore->ifa);
1614
1615                                 in6_ifa_hold(score->ifa);
1616
1617                                 swap(hiscore, score);
1618                                 hiscore_idx = 1 - hiscore_idx;
1619
1620                                 /* restore our iterator */
1621                                 score->ifa = hiscore->ifa;
1622
1623                                 break;
1624                         }
1625                 }
1626         }
1627 out:
1628         read_unlock_bh(&idev->lock);
1629         return hiscore_idx;
1630 }
1631
1632 static int ipv6_get_saddr_master(struct net *net,
1633                                  const struct net_device *dst_dev,
1634                                  const struct net_device *master,
1635                                  struct ipv6_saddr_dst *dst,
1636                                  struct ipv6_saddr_score *scores,
1637                                  int hiscore_idx)
1638 {
1639         struct inet6_dev *idev;
1640
1641         idev = __in6_dev_get(dst_dev);
1642         if (idev)
1643                 hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1644                                                    scores, hiscore_idx);
1645
1646         idev = __in6_dev_get(master);
1647         if (idev)
1648                 hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1649                                                    scores, hiscore_idx);
1650
1651         return hiscore_idx;
1652 }
1653
1654 int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev,
1655                        const struct in6_addr *daddr, unsigned int prefs,
1656                        struct in6_addr *saddr)
1657 {
1658         struct ipv6_saddr_score scores[2], *hiscore;
1659         struct ipv6_saddr_dst dst;
1660         struct inet6_dev *idev;
1661         struct net_device *dev;
1662         int dst_type;
1663         bool use_oif_addr = false;
1664         int hiscore_idx = 0;
1665
1666         dst_type = __ipv6_addr_type(daddr);
1667         dst.addr = daddr;
1668         dst.ifindex = dst_dev ? dst_dev->ifindex : 0;
1669         dst.scope = __ipv6_addr_src_scope(dst_type);
1670         dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex);
1671         dst.prefs = prefs;
1672
1673         scores[hiscore_idx].rule = -1;
1674         scores[hiscore_idx].ifa = NULL;
1675
1676         rcu_read_lock();
1677
1678         /* Candidate Source Address (section 4)
1679          *  - multicast and link-local destination address,
1680          *    the set of candidate source address MUST only
1681          *    include addresses assigned to interfaces
1682          *    belonging to the same link as the outgoing
1683          *    interface.
1684          * (- For site-local destination addresses, the
1685          *    set of candidate source addresses MUST only
1686          *    include addresses assigned to interfaces
1687          *    belonging to the same site as the outgoing
1688          *    interface.)
1689          *  - "It is RECOMMENDED that the candidate source addresses
1690          *    be the set of unicast addresses assigned to the
1691          *    interface that will be used to send to the destination
1692          *    (the 'outgoing' interface)." (RFC 6724)
1693          */
1694         if (dst_dev) {
1695                 idev = __in6_dev_get(dst_dev);
1696                 if ((dst_type & IPV6_ADDR_MULTICAST) ||
1697                     dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL ||
1698                     (idev && idev->cnf.use_oif_addrs_only)) {
1699                         use_oif_addr = true;
1700                 }
1701         }
1702
1703         if (use_oif_addr) {
1704                 if (idev)
1705                         hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1706         } else {
1707                 const struct net_device *master;
1708                 int master_idx = 0;
1709
1710                 /* if dst_dev exists and is enslaved to an L3 device, then
1711                  * prefer addresses from dst_dev and then the master over
1712                  * any other enslaved devices in the L3 domain.
1713                  */
1714                 master = l3mdev_master_dev_rcu(dst_dev);
1715                 if (master) {
1716                         master_idx = master->ifindex;
1717
1718                         hiscore_idx = ipv6_get_saddr_master(net, dst_dev,
1719                                                             master, &dst,
1720                                                             scores, hiscore_idx);
1721
1722                         if (scores[hiscore_idx].ifa)
1723                                 goto out;
1724                 }
1725
1726                 for_each_netdev_rcu(net, dev) {
1727                         /* only consider addresses on devices in the
1728                          * same L3 domain
1729                          */
1730                         if (l3mdev_master_ifindex_rcu(dev) != master_idx)
1731                                 continue;
1732                         idev = __in6_dev_get(dev);
1733                         if (!idev)
1734                                 continue;
1735                         hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1736                 }
1737         }
1738
1739 out:
1740         rcu_read_unlock();
1741
1742         hiscore = &scores[hiscore_idx];
1743         if (!hiscore->ifa)
1744                 return -EADDRNOTAVAIL;
1745
1746         *saddr = hiscore->ifa->addr;
1747         in6_ifa_put(hiscore->ifa);
1748         return 0;
1749 }
1750 EXPORT_SYMBOL(ipv6_dev_get_saddr);
1751
1752 int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr,
1753                       u32 banned_flags)
1754 {
1755         struct inet6_ifaddr *ifp;
1756         int err = -EADDRNOTAVAIL;
1757
1758         list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
1759                 if (ifp->scope > IFA_LINK)
1760                         break;
1761                 if (ifp->scope == IFA_LINK &&
1762                     !(ifp->flags & banned_flags)) {
1763                         *addr = ifp->addr;
1764                         err = 0;
1765                         break;
1766                 }
1767         }
1768         return err;
1769 }
1770
1771 int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr,
1772                     u32 banned_flags)
1773 {
1774         struct inet6_dev *idev;
1775         int err = -EADDRNOTAVAIL;
1776
1777         rcu_read_lock();
1778         idev = __in6_dev_get(dev);
1779         if (idev) {
1780                 read_lock_bh(&idev->lock);
1781                 err = __ipv6_get_lladdr(idev, addr, banned_flags);
1782                 read_unlock_bh(&idev->lock);
1783         }
1784         rcu_read_unlock();
1785         return err;
1786 }
1787
1788 static int ipv6_count_addresses(struct inet6_dev *idev)
1789 {
1790         int cnt = 0;
1791         struct inet6_ifaddr *ifp;
1792
1793         read_lock_bh(&idev->lock);
1794         list_for_each_entry(ifp, &idev->addr_list, if_list)
1795                 cnt++;
1796         read_unlock_bh(&idev->lock);
1797         return cnt;
1798 }
1799
1800 int ipv6_chk_addr(struct net *net, const struct in6_addr *addr,
1801                   const struct net_device *dev, int strict)
1802 {
1803         return ipv6_chk_addr_and_flags(net, addr, dev, strict, IFA_F_TENTATIVE);
1804 }
1805 EXPORT_SYMBOL(ipv6_chk_addr);
1806
1807 int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
1808                             const struct net_device *dev, int strict,
1809                             u32 banned_flags)
1810 {
1811         struct inet6_ifaddr *ifp;
1812         unsigned int hash = inet6_addr_hash(addr);
1813         u32 ifp_flags;
1814
1815         rcu_read_lock_bh();
1816         hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) {
1817                 if (!net_eq(dev_net(ifp->idev->dev), net))
1818                         continue;
1819                 /* Decouple optimistic from tentative for evaluation here.
1820                  * Ban optimistic addresses explicitly, when required.
1821                  */
1822                 ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC)
1823                             ? (ifp->flags&~IFA_F_TENTATIVE)
1824                             : ifp->flags;
1825                 if (ipv6_addr_equal(&ifp->addr, addr) &&
1826                     !(ifp_flags&banned_flags) &&
1827                     (!dev || ifp->idev->dev == dev ||
1828                      !(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) {
1829                         rcu_read_unlock_bh();
1830                         return 1;
1831                 }
1832         }
1833
1834         rcu_read_unlock_bh();
1835         return 0;
1836 }
1837 EXPORT_SYMBOL(ipv6_chk_addr_and_flags);
1838
1839 static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
1840                                struct net_device *dev)
1841 {
1842         unsigned int hash = inet6_addr_hash(addr);
1843         struct inet6_ifaddr *ifp;
1844
1845         hlist_for_each_entry(ifp, &inet6_addr_lst[hash], addr_lst) {
1846                 if (!net_eq(dev_net(ifp->idev->dev), net))
1847                         continue;
1848                 if (ipv6_addr_equal(&ifp->addr, addr)) {
1849                         if (!dev || ifp->idev->dev == dev)
1850                                 return true;
1851                 }
1852         }
1853         return false;
1854 }
1855
1856 /* Compares an address/prefix_len with addresses on device @dev.
1857  * If one is found it returns true.
1858  */
1859 bool ipv6_chk_custom_prefix(const struct in6_addr *addr,
1860         const unsigned int prefix_len, struct net_device *dev)
1861 {
1862         struct inet6_dev *idev;
1863         struct inet6_ifaddr *ifa;
1864         bool ret = false;
1865
1866         rcu_read_lock();
1867         idev = __in6_dev_get(dev);
1868         if (idev) {
1869                 read_lock_bh(&idev->lock);
1870                 list_for_each_entry(ifa, &idev->addr_list, if_list) {
1871                         ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len);
1872                         if (ret)
1873                                 break;
1874                 }
1875                 read_unlock_bh(&idev->lock);
1876         }
1877         rcu_read_unlock();
1878
1879         return ret;
1880 }
1881 EXPORT_SYMBOL(ipv6_chk_custom_prefix);
1882
1883 int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev)
1884 {
1885         struct inet6_dev *idev;
1886         struct inet6_ifaddr *ifa;
1887         int     onlink;
1888
1889         onlink = 0;
1890         rcu_read_lock();
1891         idev = __in6_dev_get(dev);
1892         if (idev) {
1893                 read_lock_bh(&idev->lock);
1894                 list_for_each_entry(ifa, &idev->addr_list, if_list) {
1895                         onlink = ipv6_prefix_equal(addr, &ifa->addr,
1896                                                    ifa->prefix_len);
1897                         if (onlink)
1898                                 break;
1899                 }
1900                 read_unlock_bh(&idev->lock);
1901         }
1902         rcu_read_unlock();
1903         return onlink;
1904 }
1905 EXPORT_SYMBOL(ipv6_chk_prefix);
1906
1907 struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr,
1908                                      struct net_device *dev, int strict)
1909 {
1910         struct inet6_ifaddr *ifp, *result = NULL;
1911         unsigned int hash = inet6_addr_hash(addr);
1912
1913         rcu_read_lock_bh();
1914         hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[hash], addr_lst) {
1915                 if (!net_eq(dev_net(ifp->idev->dev), net))
1916                         continue;
1917                 if (ipv6_addr_equal(&ifp->addr, addr)) {
1918                         if (!dev || ifp->idev->dev == dev ||
1919                             !(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) {
1920                                 result = ifp;
1921                                 in6_ifa_hold(ifp);
1922                                 break;
1923                         }
1924                 }
1925         }
1926         rcu_read_unlock_bh();
1927
1928         return result;
1929 }
1930
1931 /* Gets referenced address, destroys ifaddr */
1932
1933 static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed)
1934 {
1935         if (dad_failed)
1936                 ifp->flags |= IFA_F_DADFAILED;
1937
1938         if (ifp->flags&IFA_F_TEMPORARY) {
1939                 struct inet6_ifaddr *ifpub;
1940                 spin_lock_bh(&ifp->lock);
1941                 ifpub = ifp->ifpub;
1942                 if (ifpub) {
1943                         in6_ifa_hold(ifpub);
1944                         spin_unlock_bh(&ifp->lock);
1945                         ipv6_create_tempaddr(ifpub, ifp);
1946                         in6_ifa_put(ifpub);
1947                 } else {
1948                         spin_unlock_bh(&ifp->lock);
1949                 }
1950                 ipv6_del_addr(ifp);
1951         } else if (ifp->flags&IFA_F_PERMANENT || !dad_failed) {
1952                 spin_lock_bh(&ifp->lock);
1953                 addrconf_del_dad_work(ifp);
1954                 ifp->flags |= IFA_F_TENTATIVE;
1955                 spin_unlock_bh(&ifp->lock);
1956                 if (dad_failed)
1957                         ipv6_ifa_notify(0, ifp);
1958                 in6_ifa_put(ifp);
1959         } else {
1960                 ipv6_del_addr(ifp);
1961         }
1962 }
1963
1964 static int addrconf_dad_end(struct inet6_ifaddr *ifp)
1965 {
1966         int err = -ENOENT;
1967
1968         spin_lock_bh(&ifp->lock);
1969         if (ifp->state == INET6_IFADDR_STATE_DAD) {
1970                 ifp->state = INET6_IFADDR_STATE_POSTDAD;
1971                 err = 0;
1972         }
1973         spin_unlock_bh(&ifp->lock);
1974
1975         return err;
1976 }
1977
1978 void addrconf_dad_failure(struct inet6_ifaddr *ifp)
1979 {
1980         struct inet6_dev *idev = ifp->idev;
1981         struct net *net = dev_net(ifp->idev->dev);
1982
1983         if (addrconf_dad_end(ifp)) {
1984                 in6_ifa_put(ifp);
1985                 return;
1986         }
1987
1988         net_info_ratelimited("%s: IPv6 duplicate address %pI6c detected!\n",
1989                              ifp->idev->dev->name, &ifp->addr);
1990
1991         spin_lock_bh(&ifp->lock);
1992
1993         if (ifp->flags & IFA_F_STABLE_PRIVACY) {
1994                 int scope = ifp->scope;
1995                 u32 flags = ifp->flags;
1996                 struct in6_addr new_addr;
1997                 struct inet6_ifaddr *ifp2;
1998                 u32 valid_lft, preferred_lft;
1999                 int pfxlen = ifp->prefix_len;
2000                 int retries = ifp->stable_privacy_retry + 1;
2001
2002                 if (retries > net->ipv6.sysctl.idgen_retries) {
2003                         net_info_ratelimited("%s: privacy stable address generation failed because of DAD conflicts!\n",
2004                                              ifp->idev->dev->name);
2005                         goto errdad;
2006                 }
2007
2008                 new_addr = ifp->addr;
2009                 if (ipv6_generate_stable_address(&new_addr, retries,
2010                                                  idev))
2011                         goto errdad;
2012
2013                 valid_lft = ifp->valid_lft;
2014                 preferred_lft = ifp->prefered_lft;
2015
2016                 spin_unlock_bh(&ifp->lock);
2017
2018                 if (idev->cnf.max_addresses &&
2019                     ipv6_count_addresses(idev) >=
2020                     idev->cnf.max_addresses)
2021                         goto lock_errdad;
2022
2023                 net_info_ratelimited("%s: generating new stable privacy address because of DAD conflict\n",
2024                                      ifp->idev->dev->name);
2025
2026                 ifp2 = ipv6_add_addr(idev, &new_addr, NULL, pfxlen,
2027                                      scope, flags, valid_lft,
2028                                      preferred_lft);
2029                 if (IS_ERR(ifp2))
2030                         goto lock_errdad;
2031
2032                 spin_lock_bh(&ifp2->lock);
2033                 ifp2->stable_privacy_retry = retries;
2034                 ifp2->state = INET6_IFADDR_STATE_PREDAD;
2035                 spin_unlock_bh(&ifp2->lock);
2036
2037                 addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
2038                 in6_ifa_put(ifp2);
2039 lock_errdad:
2040                 spin_lock_bh(&ifp->lock);
2041         }
2042
2043 errdad:
2044         /* transition from _POSTDAD to _ERRDAD */
2045         ifp->state = INET6_IFADDR_STATE_ERRDAD;
2046         spin_unlock_bh(&ifp->lock);
2047
2048         addrconf_mod_dad_work(ifp, 0);
2049         in6_ifa_put(ifp);
2050 }
2051
2052 /* Join to solicited addr multicast group.
2053  * caller must hold RTNL */
2054 void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr)
2055 {
2056         struct in6_addr maddr;
2057
2058         if (dev->flags&(IFF_LOOPBACK|IFF_NOARP))
2059                 return;
2060
2061         addrconf_addr_solict_mult(addr, &maddr);
2062         ipv6_dev_mc_inc(dev, &maddr);
2063 }
2064
2065 /* caller must hold RTNL */
2066 void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr)
2067 {
2068         struct in6_addr maddr;
2069
2070         if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP))
2071                 return;
2072
2073         addrconf_addr_solict_mult(addr, &maddr);
2074         __ipv6_dev_mc_dec(idev, &maddr);
2075 }
2076
2077 /* caller must hold RTNL */
2078 static void addrconf_join_anycast(struct inet6_ifaddr *ifp)
2079 {
2080         struct in6_addr addr;
2081
2082         if (ifp->prefix_len >= 127) /* RFC 6164 */
2083                 return;
2084         ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2085         if (ipv6_addr_any(&addr))
2086                 return;
2087         __ipv6_dev_ac_inc(ifp->idev, &addr);
2088 }
2089
2090 /* caller must hold RTNL */
2091 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp)
2092 {
2093         struct in6_addr addr;
2094
2095         if (ifp->prefix_len >= 127) /* RFC 6164 */
2096                 return;
2097         ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2098         if (ipv6_addr_any(&addr))
2099                 return;
2100         __ipv6_dev_ac_dec(ifp->idev, &addr);
2101 }
2102
2103 static int addrconf_ifid_6lowpan(u8 *eui, struct net_device *dev)
2104 {
2105         switch (dev->addr_len) {
2106         case ETH_ALEN:
2107                 memcpy(eui, dev->dev_addr, 3);
2108                 eui[3] = 0xFF;
2109                 eui[4] = 0xFE;
2110                 memcpy(eui + 5, dev->dev_addr + 3, 3);
2111                 break;
2112         case EUI64_ADDR_LEN:
2113                 memcpy(eui, dev->dev_addr, EUI64_ADDR_LEN);
2114                 eui[0] ^= 2;
2115                 break;
2116         default:
2117                 return -1;
2118         }
2119
2120         return 0;
2121 }
2122
2123 static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev)
2124 {
2125         union fwnet_hwaddr *ha;
2126
2127         if (dev->addr_len != FWNET_ALEN)
2128                 return -1;
2129
2130         ha = (union fwnet_hwaddr *)dev->dev_addr;
2131
2132         memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id));
2133         eui[0] ^= 2;
2134         return 0;
2135 }
2136
2137 static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev)
2138 {
2139         /* XXX: inherit EUI-64 from other interface -- yoshfuji */
2140         if (dev->addr_len != ARCNET_ALEN)
2141                 return -1;
2142         memset(eui, 0, 7);
2143         eui[7] = *(u8 *)dev->dev_addr;
2144         return 0;
2145 }
2146
2147 static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev)
2148 {
2149         if (dev->addr_len != INFINIBAND_ALEN)
2150                 return -1;
2151         memcpy(eui, dev->dev_addr + 12, 8);
2152         eui[0] |= 2;
2153         return 0;
2154 }
2155
2156 static int __ipv6_isatap_ifid(u8 *eui, __be32 addr)
2157 {
2158         if (addr == 0)
2159                 return -1;
2160         eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) ||
2161                   ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) ||
2162                   ipv4_is_private_172(addr) || ipv4_is_test_192(addr) ||
2163                   ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) ||
2164                   ipv4_is_test_198(addr) || ipv4_is_multicast(addr) ||
2165                   ipv4_is_lbcast(addr)) ? 0x00 : 0x02;
2166         eui[1] = 0;
2167         eui[2] = 0x5E;
2168         eui[3] = 0xFE;
2169         memcpy(eui + 4, &addr, 4);
2170         return 0;
2171 }
2172
2173 static int addrconf_ifid_sit(u8 *eui, struct net_device *dev)
2174 {
2175         if (dev->priv_flags & IFF_ISATAP)
2176                 return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2177         return -1;
2178 }
2179
2180 static int addrconf_ifid_gre(u8 *eui, struct net_device *dev)
2181 {
2182         return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2183 }
2184
2185 static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev)
2186 {
2187         memcpy(eui, dev->perm_addr, 3);
2188         memcpy(eui + 5, dev->perm_addr + 3, 3);
2189         eui[3] = 0xFF;
2190         eui[4] = 0xFE;
2191         eui[0] ^= 2;
2192         return 0;
2193 }
2194
2195 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev)
2196 {
2197         switch (dev->type) {
2198         case ARPHRD_ETHER:
2199         case ARPHRD_FDDI:
2200                 return addrconf_ifid_eui48(eui, dev);
2201         case ARPHRD_ARCNET:
2202                 return addrconf_ifid_arcnet(eui, dev);
2203         case ARPHRD_INFINIBAND:
2204                 return addrconf_ifid_infiniband(eui, dev);
2205         case ARPHRD_SIT:
2206                 return addrconf_ifid_sit(eui, dev);
2207         case ARPHRD_IPGRE:
2208         case ARPHRD_TUNNEL:
2209                 return addrconf_ifid_gre(eui, dev);
2210         case ARPHRD_6LOWPAN:
2211                 return addrconf_ifid_6lowpan(eui, dev);
2212         case ARPHRD_IEEE1394:
2213                 return addrconf_ifid_ieee1394(eui, dev);
2214         case ARPHRD_TUNNEL6:
2215         case ARPHRD_IP6GRE:
2216                 return addrconf_ifid_ip6tnl(eui, dev);
2217         }
2218         return -1;
2219 }
2220
2221 static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev)
2222 {
2223         int err = -1;
2224         struct inet6_ifaddr *ifp;
2225
2226         read_lock_bh(&idev->lock);
2227         list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
2228                 if (ifp->scope > IFA_LINK)
2229                         break;
2230                 if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) {
2231                         memcpy(eui, ifp->addr.s6_addr+8, 8);
2232                         err = 0;
2233                         break;
2234                 }
2235         }
2236         read_unlock_bh(&idev->lock);
2237         return err;
2238 }
2239
2240 /* (re)generation of randomized interface identifier (RFC 3041 3.2, 3.5) */
2241 static void ipv6_regen_rndid(struct inet6_dev *idev)
2242 {
2243 regen:
2244         get_random_bytes(idev->rndid, sizeof(idev->rndid));
2245         idev->rndid[0] &= ~0x02;
2246
2247         /*
2248          * <draft-ietf-ipngwg-temp-addresses-v2-00.txt>:
2249          * check if generated address is not inappropriate
2250          *
2251          *  - Reserved subnet anycast (RFC 2526)
2252          *      11111101 11....11 1xxxxxxx
2253          *  - ISATAP (RFC4214) 6.1
2254          *      00-00-5E-FE-xx-xx-xx-xx
2255          *  - value 0
2256          *  - XXX: already assigned to an address on the device
2257          */
2258         if (idev->rndid[0] == 0xfd &&
2259             (idev->rndid[1]&idev->rndid[2]&idev->rndid[3]&idev->rndid[4]&idev->rndid[5]&idev->rndid[6]) == 0xff &&
2260             (idev->rndid[7]&0x80))
2261                 goto regen;
2262         if ((idev->rndid[0]|idev->rndid[1]) == 0) {
2263                 if (idev->rndid[2] == 0x5e && idev->rndid[3] == 0xfe)
2264                         goto regen;
2265                 if ((idev->rndid[2]|idev->rndid[3]|idev->rndid[4]|idev->rndid[5]|idev->rndid[6]|idev->rndid[7]) == 0x00)
2266                         goto regen;
2267         }
2268 }
2269
2270 static void  ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr)
2271 {
2272         if (tmpaddr && memcmp(idev->rndid, &tmpaddr->s6_addr[8], 8) == 0)
2273                 ipv6_regen_rndid(idev);
2274 }
2275
2276 /*
2277  *      Add prefix route.
2278  */
2279
2280 static void
2281 addrconf_prefix_route(struct in6_addr *pfx, int plen, struct net_device *dev,
2282                       unsigned long expires, u32 flags)
2283 {
2284         struct fib6_config cfg = {
2285                 .fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX,
2286                 .fc_metric = IP6_RT_PRIO_ADDRCONF,
2287                 .fc_ifindex = dev->ifindex,
2288                 .fc_expires = expires,
2289                 .fc_dst_len = plen,
2290                 .fc_flags = RTF_UP | flags,
2291                 .fc_nlinfo.nl_net = dev_net(dev),
2292                 .fc_protocol = RTPROT_KERNEL,
2293         };
2294
2295         cfg.fc_dst = *pfx;
2296
2297         /* Prevent useless cloning on PtP SIT.
2298            This thing is done here expecting that the whole
2299            class of non-broadcast devices need not cloning.
2300          */
2301 #if IS_ENABLED(CONFIG_IPV6_SIT)
2302         if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT))
2303                 cfg.fc_flags |= RTF_NONEXTHOP;
2304 #endif
2305
2306         ip6_route_add(&cfg, NULL);
2307 }
2308
2309
2310 static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
2311                                                   int plen,
2312                                                   const struct net_device *dev,
2313                                                   u32 flags, u32 noflags)
2314 {
2315         struct fib6_node *fn;
2316         struct rt6_info *rt = NULL;
2317         struct fib6_table *table;
2318         u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX;
2319
2320         table = fib6_get_table(dev_net(dev), tb_id);
2321         if (!table)
2322                 return NULL;
2323
2324         read_lock_bh(&table->tb6_lock);
2325         fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0);
2326         if (!fn)
2327                 goto out;
2328
2329         noflags |= RTF_CACHE;
2330         for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
2331                 if (rt->dst.dev->ifindex != dev->ifindex)
2332                         continue;
2333                 if ((rt->rt6i_flags & flags) != flags)
2334                         continue;
2335                 if ((rt->rt6i_flags & noflags) != 0)
2336                         continue;
2337                 dst_hold(&rt->dst);
2338                 break;
2339         }
2340 out:
2341         read_unlock_bh(&table->tb6_lock);
2342         return rt;
2343 }
2344
2345
2346 /* Create "default" multicast route to the interface */
2347
2348 static void addrconf_add_mroute(struct net_device *dev)
2349 {
2350         struct fib6_config cfg = {
2351                 .fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_LOCAL,
2352                 .fc_metric = IP6_RT_PRIO_ADDRCONF,
2353                 .fc_ifindex = dev->ifindex,
2354                 .fc_dst_len = 8,
2355                 .fc_flags = RTF_UP,
2356                 .fc_nlinfo.nl_net = dev_net(dev),
2357         };
2358
2359         ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);
2360
2361         ip6_route_add(&cfg, NULL);
2362 }
2363
2364 static struct inet6_dev *addrconf_add_dev(struct net_device *dev)
2365 {
2366         struct inet6_dev *idev;
2367
2368         ASSERT_RTNL();
2369
2370         idev = ipv6_find_idev(dev);
2371         if (!idev)
2372                 return ERR_PTR(-ENOBUFS);
2373
2374         if (idev->cnf.disable_ipv6)
2375                 return ERR_PTR(-EACCES);
2376
2377         /* Add default multicast route */
2378         if (!(dev->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev))
2379                 addrconf_add_mroute(dev);
2380
2381         return idev;
2382 }
2383
2384 static void manage_tempaddrs(struct inet6_dev *idev,
2385                              struct inet6_ifaddr *ifp,
2386                              __u32 valid_lft, __u32 prefered_lft,
2387                              bool create, unsigned long now)
2388 {
2389         u32 flags;
2390         struct inet6_ifaddr *ift;
2391
2392         read_lock_bh(&idev->lock);
2393         /* update all temporary addresses in the list */
2394         list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) {
2395                 int age, max_valid, max_prefered;
2396
2397                 if (ifp != ift->ifpub)
2398                         continue;
2399
2400                 /* RFC 4941 section 3.3:
2401                  * If a received option will extend the lifetime of a public
2402                  * address, the lifetimes of temporary addresses should
2403                  * be extended, subject to the overall constraint that no
2404                  * temporary addresses should ever remain "valid" or "preferred"
2405                  * for a time longer than (TEMP_VALID_LIFETIME) or
2406                  * (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively.
2407                  */
2408                 age = (now - ift->cstamp) / HZ;
2409                 max_valid = idev->cnf.temp_valid_lft - age;
2410                 if (max_valid < 0)
2411                         max_valid = 0;
2412
2413                 max_prefered = idev->cnf.temp_prefered_lft -
2414                                idev->desync_factor - age;
2415                 if (max_prefered < 0)
2416                         max_prefered = 0;
2417
2418                 if (valid_lft > max_valid)
2419                         valid_lft = max_valid;
2420
2421                 if (prefered_lft > max_prefered)
2422                         prefered_lft = max_prefered;
2423
2424                 spin_lock(&ift->lock);
2425                 flags = ift->flags;
2426                 ift->valid_lft = valid_lft;
2427                 ift->prefered_lft = prefered_lft;
2428                 ift->tstamp = now;
2429                 if (prefered_lft > 0)
2430                         ift->flags &= ~IFA_F_DEPRECATED;
2431
2432                 spin_unlock(&ift->lock);
2433                 if (!(flags&IFA_F_TENTATIVE))
2434                         ipv6_ifa_notify(0, ift);
2435         }
2436
2437         if ((create || list_empty(&idev->tempaddr_list)) &&
2438             idev->cnf.use_tempaddr > 0) {
2439                 /* When a new public address is created as described
2440                  * in [ADDRCONF], also create a new temporary address.
2441                  * Also create a temporary address if it's enabled but
2442                  * no temporary address currently exists.
2443                  */
2444                 read_unlock_bh(&idev->lock);
2445                 ipv6_create_tempaddr(ifp, NULL);
2446         } else {
2447                 read_unlock_bh(&idev->lock);
2448         }
2449 }
2450
2451 static bool is_addr_mode_generate_stable(struct inet6_dev *idev)
2452 {
2453         return idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY ||
2454                idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_RANDOM;
2455 }
2456
2457 int addrconf_prefix_rcv_add_addr(struct net *net, struct net_device *dev,
2458                                  const struct prefix_info *pinfo,
2459                                  struct inet6_dev *in6_dev,
2460                                  const struct in6_addr *addr, int addr_type,
2461                                  u32 addr_flags, bool sllao, bool tokenized,
2462                                  __u32 valid_lft, u32 prefered_lft)
2463 {
2464         struct inet6_ifaddr *ifp = ipv6_get_ifaddr(net, addr, dev, 1);
2465         int create = 0, update_lft = 0;
2466
2467         if (!ifp && valid_lft) {
2468                 int max_addresses = in6_dev->cnf.max_addresses;
2469
2470 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
2471                 if ((net->ipv6.devconf_all->optimistic_dad ||
2472                      in6_dev->cnf.optimistic_dad) &&
2473                     !net->ipv6.devconf_all->forwarding && sllao)
2474                         addr_flags |= IFA_F_OPTIMISTIC;
2475 #endif
2476
2477                 /* Do not allow to create too much of autoconfigured
2478                  * addresses; this would be too easy way to crash kernel.
2479                  */
2480                 if (!max_addresses ||
2481                     ipv6_count_addresses(in6_dev) < max_addresses)
2482                         ifp = ipv6_add_addr(in6_dev, addr, NULL,
2483                                             pinfo->prefix_len,
2484                                             addr_type&IPV6_ADDR_SCOPE_MASK,
2485                                             addr_flags, valid_lft,
2486                                             prefered_lft);
2487
2488                 if (IS_ERR_OR_NULL(ifp))
2489                         return -1;
2490
2491                 update_lft = 0;
2492                 create = 1;
2493                 spin_lock_bh(&ifp->lock);
2494                 ifp->flags |= IFA_F_MANAGETEMPADDR;
2495                 ifp->cstamp = jiffies;
2496                 ifp->tokenized = tokenized;
2497                 spin_unlock_bh(&ifp->lock);
2498                 addrconf_dad_start(ifp);
2499         }
2500
2501         if (ifp) {
2502                 u32 flags;
2503                 unsigned long now;
2504                 u32 stored_lft;
2505
2506                 /* update lifetime (RFC2462 5.5.3 e) */
2507                 spin_lock_bh(&ifp->lock);
2508                 now = jiffies;
2509                 if (ifp->valid_lft > (now - ifp->tstamp) / HZ)
2510                         stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ;
2511                 else
2512                         stored_lft = 0;
2513                 if (!update_lft && !create && stored_lft) {
2514                         const u32 minimum_lft = min_t(u32,
2515                                 stored_lft, MIN_VALID_LIFETIME);
2516                         valid_lft = max(valid_lft, minimum_lft);
2517
2518                         /* RFC4862 Section 5.5.3e:
2519                          * "Note that the preferred lifetime of the
2520                          *  corresponding address is always reset to
2521                          *  the Preferred Lifetime in the received
2522                          *  Prefix Information option, regardless of
2523                          *  whether the valid lifetime is also reset or
2524                          *  ignored."
2525                          *
2526                          * So we should always update prefered_lft here.
2527                          */
2528                         update_lft = 1;
2529                 }
2530
2531                 if (update_lft) {
2532                         ifp->valid_lft = valid_lft;
2533                         ifp->prefered_lft = prefered_lft;
2534                         ifp->tstamp = now;
2535                         flags = ifp->flags;
2536                         ifp->flags &= ~IFA_F_DEPRECATED;
2537                         spin_unlock_bh(&ifp->lock);
2538
2539                         if (!(flags&IFA_F_TENTATIVE))
2540                                 ipv6_ifa_notify(0, ifp);
2541                 } else
2542                         spin_unlock_bh(&ifp->lock);
2543
2544                 manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft,
2545                                  create, now);
2546
2547                 in6_ifa_put(ifp);
2548                 addrconf_verify();
2549         }
2550
2551         return 0;
2552 }
2553 EXPORT_SYMBOL_GPL(addrconf_prefix_rcv_add_addr);
2554
2555 void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao)
2556 {
2557         struct prefix_info *pinfo;
2558         __u32 valid_lft;
2559         __u32 prefered_lft;
2560         int addr_type, err;
2561         u32 addr_flags = 0;
2562         struct inet6_dev *in6_dev;
2563         struct net *net = dev_net(dev);
2564
2565         pinfo = (struct prefix_info *) opt;
2566
2567         if (len < sizeof(struct prefix_info)) {
2568                 ADBG("addrconf: prefix option too short\n");
2569                 return;
2570         }
2571
2572         /*
2573          *      Validation checks ([ADDRCONF], page 19)
2574          */
2575
2576         addr_type = ipv6_addr_type(&pinfo->prefix);
2577
2578         if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL))
2579                 return;
2580
2581         valid_lft = ntohl(pinfo->valid);
2582         prefered_lft = ntohl(pinfo->prefered);
2583
2584         if (prefered_lft > valid_lft) {
2585                 net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n");
2586                 return;
2587         }
2588
2589         in6_dev = in6_dev_get(dev);
2590
2591         if (!in6_dev) {
2592                 net_dbg_ratelimited("addrconf: device %s not configured\n",
2593                                     dev->name);
2594                 return;
2595         }
2596
2597         /*
2598          *      Two things going on here:
2599          *      1) Add routes for on-link prefixes
2600          *      2) Configure prefixes with the auto flag set
2601          */
2602
2603         if (pinfo->onlink) {
2604                 struct rt6_info *rt;
2605                 unsigned long rt_expires;
2606
2607                 /* Avoid arithmetic overflow. Really, we could
2608                  * save rt_expires in seconds, likely valid_lft,
2609                  * but it would require division in fib gc, that it
2610                  * not good.
2611                  */
2612                 if (HZ > USER_HZ)
2613                         rt_expires = addrconf_timeout_fixup(valid_lft, HZ);
2614                 else
2615                         rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ);
2616
2617                 if (addrconf_finite_timeout(rt_expires))
2618                         rt_expires *= HZ;
2619
2620                 rt = addrconf_get_prefix_route(&pinfo->prefix,
2621                                                pinfo->prefix_len,
2622                                                dev,
2623                                                RTF_ADDRCONF | RTF_PREFIX_RT,
2624                                                RTF_GATEWAY | RTF_DEFAULT);
2625
2626                 if (rt) {
2627                         /* Autoconf prefix route */
2628                         if (valid_lft == 0) {
2629                                 ip6_del_rt(rt);
2630                                 rt = NULL;
2631                         } else if (addrconf_finite_timeout(rt_expires)) {
2632                                 /* not infinity */
2633                                 rt6_set_expires(rt, jiffies + rt_expires);
2634                         } else {
2635                                 rt6_clean_expires(rt);
2636                         }
2637                 } else if (valid_lft) {
2638                         clock_t expires = 0;
2639                         int flags = RTF_ADDRCONF | RTF_PREFIX_RT;
2640                         if (addrconf_finite_timeout(rt_expires)) {
2641                                 /* not infinity */
2642                                 flags |= RTF_EXPIRES;
2643                                 expires = jiffies_to_clock_t(rt_expires);
2644                         }
2645                         addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len,
2646                                               dev, expires, flags);
2647                 }
2648                 ip6_rt_put(rt);
2649         }
2650
2651         /* Try to figure out our local address for this prefix */
2652
2653         if (pinfo->autoconf && in6_dev->cnf.autoconf) {
2654                 struct in6_addr addr;
2655                 bool tokenized = false, dev_addr_generated = false;
2656
2657                 if (pinfo->prefix_len == 64) {
2658                         memcpy(&addr, &pinfo->prefix, 8);
2659
2660                         if (!ipv6_addr_any(&in6_dev->token)) {
2661                                 read_lock_bh(&in6_dev->lock);
2662                                 memcpy(addr.s6_addr + 8,
2663                                        in6_dev->token.s6_addr + 8, 8);
2664                                 read_unlock_bh(&in6_dev->lock);
2665                                 tokenized = true;
2666                         } else if (is_addr_mode_generate_stable(in6_dev) &&
2667                                    !ipv6_generate_stable_address(&addr, 0,
2668                                                                  in6_dev)) {
2669                                 addr_flags |= IFA_F_STABLE_PRIVACY;
2670                                 goto ok;
2671                         } else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) &&
2672                                    ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) {
2673                                 goto put;
2674                         } else {
2675                                 dev_addr_generated = true;
2676                         }
2677                         goto ok;
2678                 }
2679                 net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n",
2680                                     pinfo->prefix_len);
2681                 goto put;
2682
2683 ok:
2684                 err = addrconf_prefix_rcv_add_addr(net, dev, pinfo, in6_dev,
2685                                                    &addr, addr_type,
2686                                                    addr_flags, sllao,
2687                                                    tokenized, valid_lft,
2688                                                    prefered_lft);
2689                 if (err)
2690                         goto put;
2691
2692                 /* Ignore error case here because previous prefix add addr was
2693                  * successful which will be notified.
2694                  */
2695                 ndisc_ops_prefix_rcv_add_addr(net, dev, pinfo, in6_dev, &addr,
2696                                               addr_type, addr_flags, sllao,
2697                                               tokenized, valid_lft,
2698                                               prefered_lft,
2699                                               dev_addr_generated);
2700         }
2701         inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo);
2702 put:
2703         in6_dev_put(in6_dev);
2704 }
2705
2706 /*
2707  *      Set destination address.
2708  *      Special case for SIT interfaces where we create a new "virtual"
2709  *      device.
2710  */
2711 int addrconf_set_dstaddr(struct net *net, void __user *arg)
2712 {
2713         struct in6_ifreq ireq;
2714         struct net_device *dev;
2715         int err = -EINVAL;
2716
2717         rtnl_lock();
2718
2719         err = -EFAULT;
2720         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
2721                 goto err_exit;
2722
2723         dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
2724
2725         err = -ENODEV;
2726         if (!dev)
2727                 goto err_exit;
2728
2729 #if IS_ENABLED(CONFIG_IPV6_SIT)
2730         if (dev->type == ARPHRD_SIT) {
2731                 const struct net_device_ops *ops = dev->netdev_ops;
2732                 struct ifreq ifr;
2733                 struct ip_tunnel_parm p;
2734
2735                 err = -EADDRNOTAVAIL;
2736                 if (!(ipv6_addr_type(&ireq.ifr6_addr) & IPV6_ADDR_COMPATv4))
2737                         goto err_exit;
2738
2739                 memset(&p, 0, sizeof(p));
2740                 p.iph.daddr = ireq.ifr6_addr.s6_addr32[3];
2741                 p.iph.saddr = 0;
2742                 p.iph.version = 4;
2743                 p.iph.ihl = 5;
2744                 p.iph.protocol = IPPROTO_IPV6;
2745                 p.iph.ttl = 64;
2746                 ifr.ifr_ifru.ifru_data = (__force void __user *)&p;
2747
2748                 if (ops->ndo_do_ioctl) {
2749                         mm_segment_t oldfs = get_fs();
2750
2751                         set_fs(KERNEL_DS);
2752                         err = ops->ndo_do_ioctl(dev, &ifr, SIOCADDTUNNEL);
2753                         set_fs(oldfs);
2754                 } else
2755                         err = -EOPNOTSUPP;
2756
2757                 if (err == 0) {
2758                         err = -ENOBUFS;
2759                         dev = __dev_get_by_name(net, p.name);
2760                         if (!dev)
2761                                 goto err_exit;
2762                         err = dev_open(dev);
2763                 }
2764         }
2765 #endif
2766
2767 err_exit:
2768         rtnl_unlock();
2769         return err;
2770 }
2771
2772 static int ipv6_mc_config(struct sock *sk, bool join,
2773                           const struct in6_addr *addr, int ifindex)
2774 {
2775         int ret;
2776
2777         ASSERT_RTNL();
2778
2779         lock_sock(sk);
2780         if (join)
2781                 ret = ipv6_sock_mc_join(sk, ifindex, addr);
2782         else
2783                 ret = ipv6_sock_mc_drop(sk, ifindex, addr);
2784         release_sock(sk);
2785
2786         return ret;
2787 }
2788
2789 /*
2790  *      Manual configuration of address on an interface
2791  */
2792 static int inet6_addr_add(struct net *net, int ifindex,
2793                           const struct in6_addr *pfx,
2794                           const struct in6_addr *peer_pfx,
2795                           unsigned int plen, __u32 ifa_flags,
2796                           __u32 prefered_lft, __u32 valid_lft)
2797 {
2798         struct inet6_ifaddr *ifp;
2799         struct inet6_dev *idev;
2800         struct net_device *dev;
2801         unsigned long timeout;
2802         clock_t expires;
2803         int scope;
2804         u32 flags;
2805
2806         ASSERT_RTNL();
2807
2808         if (plen > 128)
2809                 return -EINVAL;
2810
2811         /* check the lifetime */
2812         if (!valid_lft || prefered_lft > valid_lft)
2813                 return -EINVAL;
2814
2815         if (ifa_flags & IFA_F_MANAGETEMPADDR && plen != 64)
2816                 return -EINVAL;
2817
2818         dev = __dev_get_by_index(net, ifindex);
2819         if (!dev)
2820                 return -ENODEV;
2821
2822         idev = addrconf_add_dev(dev);
2823         if (IS_ERR(idev))
2824                 return PTR_ERR(idev);
2825
2826         if (ifa_flags & IFA_F_MCAUTOJOIN) {
2827                 int ret = ipv6_mc_config(net->ipv6.mc_autojoin_sk,
2828                                          true, pfx, ifindex);
2829
2830                 if (ret < 0)
2831                         return ret;
2832         }
2833
2834         scope = ipv6_addr_scope(pfx);
2835
2836         timeout = addrconf_timeout_fixup(valid_lft, HZ);
2837         if (addrconf_finite_timeout(timeout)) {
2838                 expires = jiffies_to_clock_t(timeout * HZ);
2839                 valid_lft = timeout;
2840                 flags = RTF_EXPIRES;
2841         } else {
2842                 expires = 0;
2843                 flags = 0;
2844                 ifa_flags |= IFA_F_PERMANENT;
2845         }
2846
2847         timeout = addrconf_timeout_fixup(prefered_lft, HZ);
2848         if (addrconf_finite_timeout(timeout)) {
2849                 if (timeout == 0)
2850                         ifa_flags |= IFA_F_DEPRECATED;
2851                 prefered_lft = timeout;
2852         }
2853
2854         ifp = ipv6_add_addr(idev, pfx, peer_pfx, plen, scope, ifa_flags,
2855                             valid_lft, prefered_lft);
2856
2857         if (!IS_ERR(ifp)) {
2858                 if (!(ifa_flags & IFA_F_NOPREFIXROUTE)) {
2859                         addrconf_prefix_route(&ifp->addr, ifp->prefix_len, dev,
2860                                               expires, flags);
2861                 }
2862
2863                 /*
2864                  * Note that section 3.1 of RFC 4429 indicates
2865                  * that the Optimistic flag should not be set for
2866                  * manually configured addresses
2867                  */
2868                 addrconf_dad_start(ifp);
2869                 if (ifa_flags & IFA_F_MANAGETEMPADDR)
2870                         manage_tempaddrs(idev, ifp, valid_lft, prefered_lft,
2871                                          true, jiffies);
2872                 in6_ifa_put(ifp);
2873                 addrconf_verify_rtnl();
2874                 return 0;
2875         } else if (ifa_flags & IFA_F_MCAUTOJOIN) {
2876                 ipv6_mc_config(net->ipv6.mc_autojoin_sk,
2877                                false, pfx, ifindex);
2878         }
2879
2880         return PTR_ERR(ifp);
2881 }
2882
2883 static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags,
2884                           const struct in6_addr *pfx, unsigned int plen)
2885 {
2886         struct inet6_ifaddr *ifp;
2887         struct inet6_dev *idev;
2888         struct net_device *dev;
2889
2890         if (plen > 128)
2891                 return -EINVAL;
2892
2893         dev = __dev_get_by_index(net, ifindex);
2894         if (!dev)
2895                 return -ENODEV;
2896
2897         idev = __in6_dev_get(dev);
2898         if (!idev)
2899                 return -ENXIO;
2900
2901         read_lock_bh(&idev->lock);
2902         list_for_each_entry(ifp, &idev->addr_list, if_list) {
2903                 if (ifp->prefix_len == plen &&
2904                     ipv6_addr_equal(pfx, &ifp->addr)) {
2905                         in6_ifa_hold(ifp);
2906                         read_unlock_bh(&idev->lock);
2907
2908                         if (!(ifp->flags & IFA_F_TEMPORARY) &&
2909                             (ifa_flags & IFA_F_MANAGETEMPADDR))
2910                                 manage_tempaddrs(idev, ifp, 0, 0, false,
2911                                                  jiffies);
2912                         ipv6_del_addr(ifp);
2913                         addrconf_verify_rtnl();
2914                         if (ipv6_addr_is_multicast(pfx)) {
2915                                 ipv6_mc_config(net->ipv6.mc_autojoin_sk,
2916                                                false, pfx, dev->ifindex);
2917                         }
2918                         return 0;
2919                 }
2920         }
2921         read_unlock_bh(&idev->lock);
2922         return -EADDRNOTAVAIL;
2923 }
2924
2925
2926 int addrconf_add_ifaddr(struct net *net, void __user *arg)
2927 {
2928         struct in6_ifreq ireq;
2929         int err;
2930
2931         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2932                 return -EPERM;
2933
2934         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
2935                 return -EFAULT;
2936
2937         rtnl_lock();
2938         err = inet6_addr_add(net, ireq.ifr6_ifindex, &ireq.ifr6_addr, NULL,
2939                              ireq.ifr6_prefixlen, IFA_F_PERMANENT,
2940                              INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
2941         rtnl_unlock();
2942         return err;
2943 }
2944
2945 int addrconf_del_ifaddr(struct net *net, void __user *arg)
2946 {
2947         struct in6_ifreq ireq;
2948         int err;
2949
2950         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
2951                 return -EPERM;
2952
2953         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
2954                 return -EFAULT;
2955
2956         rtnl_lock();
2957         err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr,
2958                              ireq.ifr6_prefixlen);
2959         rtnl_unlock();
2960         return err;
2961 }
2962
2963 static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
2964                      int plen, int scope)
2965 {
2966         struct inet6_ifaddr *ifp;
2967
2968         ifp = ipv6_add_addr(idev, addr, NULL, plen,
2969                             scope, IFA_F_PERMANENT,
2970                             INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
2971         if (!IS_ERR(ifp)) {
2972                 spin_lock_bh(&ifp->lock);
2973                 ifp->flags &= ~IFA_F_TENTATIVE;
2974                 spin_unlock_bh(&ifp->lock);
2975                 rt_genid_bump_ipv6(dev_net(idev->dev));
2976                 ipv6_ifa_notify(RTM_NEWADDR, ifp);
2977                 in6_ifa_put(ifp);
2978         }
2979 }
2980
2981 #if IS_ENABLED(CONFIG_IPV6_SIT)
2982 static void sit_add_v4_addrs(struct inet6_dev *idev)
2983 {
2984         struct in6_addr addr;
2985         struct net_device *dev;
2986         struct net *net = dev_net(idev->dev);
2987         int scope, plen;
2988         u32 pflags = 0;
2989
2990         ASSERT_RTNL();
2991
2992         memset(&addr, 0, sizeof(struct in6_addr));
2993         memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4);
2994
2995         if (idev->dev->flags&IFF_POINTOPOINT) {
2996                 addr.s6_addr32[0] = htonl(0xfe800000);
2997                 scope = IFA_LINK;
2998                 plen = 64;
2999         } else {
3000                 scope = IPV6_ADDR_COMPATv4;
3001                 plen = 96;
3002                 pflags |= RTF_NONEXTHOP;
3003         }
3004
3005         if (addr.s6_addr32[3]) {
3006                 add_addr(idev, &addr, plen, scope);
3007                 addrconf_prefix_route(&addr, plen, idev->dev, 0, pflags);
3008                 return;
3009         }
3010
3011         for_each_netdev(net, dev) {
3012                 struct in_device *in_dev = __in_dev_get_rtnl(dev);
3013                 if (in_dev && (dev->flags & IFF_UP)) {
3014                         struct in_ifaddr *ifa;
3015
3016                         int flag = scope;
3017
3018                         for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
3019
3020                                 addr.s6_addr32[3] = ifa->ifa_local;
3021
3022                                 if (ifa->ifa_scope == RT_SCOPE_LINK)
3023                                         continue;
3024                                 if (ifa->ifa_scope >= RT_SCOPE_HOST) {
3025                                         if (idev->dev->flags&IFF_POINTOPOINT)
3026                                                 continue;
3027                                         flag |= IFA_HOST;
3028                                 }
3029
3030                                 add_addr(idev, &addr, plen, flag);
3031                                 addrconf_prefix_route(&addr, plen, idev->dev, 0,
3032                                                       pflags);
3033                         }
3034                 }
3035         }
3036 }
3037 #endif
3038
3039 static void init_loopback(struct net_device *dev)
3040 {
3041         struct inet6_dev  *idev;
3042
3043         /* ::1 */
3044
3045         ASSERT_RTNL();
3046
3047         idev = ipv6_find_idev(dev);
3048         if (!idev) {
3049                 pr_debug("%s: add_dev failed\n", __func__);
3050                 return;
3051         }
3052
3053         add_addr(idev, &in6addr_loopback, 128, IFA_HOST);
3054 }
3055
3056 void addrconf_add_linklocal(struct inet6_dev *idev,
3057                             const struct in6_addr *addr, u32 flags)
3058 {
3059         struct inet6_ifaddr *ifp;
3060         u32 addr_flags = flags | IFA_F_PERMANENT;
3061
3062 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
3063         if ((dev_net(idev->dev)->ipv6.devconf_all->optimistic_dad ||
3064              idev->cnf.optimistic_dad) &&
3065             !dev_net(idev->dev)->ipv6.devconf_all->forwarding)
3066                 addr_flags |= IFA_F_OPTIMISTIC;
3067 #endif
3068
3069         ifp = ipv6_add_addr(idev, addr, NULL, 64, IFA_LINK, addr_flags,
3070                             INFINITY_LIFE_TIME, INFINITY_LIFE_TIME);
3071         if (!IS_ERR(ifp)) {
3072                 addrconf_prefix_route(&ifp->addr, ifp->prefix_len, idev->dev, 0, 0);
3073                 addrconf_dad_start(ifp);
3074                 in6_ifa_put(ifp);
3075         }
3076 }
3077 EXPORT_SYMBOL_GPL(addrconf_add_linklocal);
3078
3079 static bool ipv6_reserved_interfaceid(struct in6_addr address)
3080 {
3081         if ((address.s6_addr32[2] | address.s6_addr32[3]) == 0)
3082                 return true;
3083
3084         if (address.s6_addr32[2] == htonl(0x02005eff) &&
3085             ((address.s6_addr32[3] & htonl(0xfe000000)) == htonl(0xfe000000)))
3086                 return true;
3087
3088         if (address.s6_addr32[2] == htonl(0xfdffffff) &&
3089             ((address.s6_addr32[3] & htonl(0xffffff80)) == htonl(0xffffff80)))
3090                 return true;
3091
3092         return false;
3093 }
3094
3095 static int ipv6_generate_stable_address(struct in6_addr *address,
3096                                         u8 dad_count,
3097                                         const struct inet6_dev *idev)
3098 {
3099         static DEFINE_SPINLOCK(lock);
3100         static __u32 digest[SHA_DIGEST_WORDS];
3101         static __u32 workspace[SHA_WORKSPACE_WORDS];
3102
3103         static union {
3104                 char __data[SHA_MESSAGE_BYTES];
3105                 struct {
3106                         struct in6_addr secret;
3107                         __be32 prefix[2];
3108                         unsigned char hwaddr[MAX_ADDR_LEN];
3109                         u8 dad_count;
3110                 } __packed;
3111         } data;
3112
3113         struct in6_addr secret;
3114         struct in6_addr temp;
3115         struct net *net = dev_net(idev->dev);
3116
3117         BUILD_BUG_ON(sizeof(data.__data) != sizeof(data));
3118
3119         if (idev->cnf.stable_secret.initialized)
3120                 secret = idev->cnf.stable_secret.secret;
3121         else if (net->ipv6.devconf_dflt->stable_secret.initialized)
3122                 secret = net->ipv6.devconf_dflt->stable_secret.secret;
3123         else
3124                 return -1;
3125
3126 retry:
3127         spin_lock_bh(&lock);
3128
3129         sha_init(digest);
3130         memset(&data, 0, sizeof(data));
3131         memset(workspace, 0, sizeof(workspace));
3132         memcpy(data.hwaddr, idev->dev->perm_addr, idev->dev->addr_len);
3133         data.prefix[0] = address->s6_addr32[0];
3134         data.prefix[1] = address->s6_addr32[1];
3135         data.secret = secret;
3136         data.dad_count = dad_count;
3137
3138         sha_transform(digest, data.__data, workspace);
3139
3140         temp = *address;
3141         temp.s6_addr32[2] = (__force __be32)digest[0];
3142         temp.s6_addr32[3] = (__force __be32)digest[1];
3143
3144         spin_unlock_bh(&lock);
3145
3146         if (ipv6_reserved_interfaceid(temp)) {
3147                 dad_count++;
3148                 if (dad_count > dev_net(idev->dev)->ipv6.sysctl.idgen_retries)
3149                         return -1;
3150                 goto retry;
3151         }
3152
3153         *address = temp;
3154         return 0;
3155 }
3156
3157 static void ipv6_gen_mode_random_init(struct inet6_dev *idev)
3158 {
3159         struct ipv6_stable_secret *s = &idev->cnf.stable_secret;
3160
3161         if (s->initialized)
3162                 return;
3163         s = &idev->cnf.stable_secret;
3164         get_random_bytes(&s->secret, sizeof(s->secret));
3165         s->initialized = true;
3166 }
3167
3168 static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
3169 {
3170         struct in6_addr addr;
3171
3172         /* no link local addresses on L3 master devices */
3173         if (netif_is_l3_master(idev->dev))
3174                 return;
3175
3176         ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
3177
3178         switch (idev->cnf.addr_gen_mode) {
3179         case IN6_ADDR_GEN_MODE_RANDOM:
3180                 ipv6_gen_mode_random_init(idev);
3181                 /* fallthrough */
3182         case IN6_ADDR_GEN_MODE_STABLE_PRIVACY:
3183                 if (!ipv6_generate_stable_address(&addr, 0, idev))
3184                         addrconf_add_linklocal(idev, &addr,
3185                                                IFA_F_STABLE_PRIVACY);
3186                 else if (prefix_route)
3187                         addrconf_prefix_route(&addr, 64, idev->dev, 0, 0);
3188                 break;
3189         case IN6_ADDR_GEN_MODE_EUI64:
3190                 /* addrconf_add_linklocal also adds a prefix_route and we
3191                  * only need to care about prefix routes if ipv6_generate_eui64
3192                  * couldn't generate one.
3193                  */
3194                 if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
3195                         addrconf_add_linklocal(idev, &addr, 0);
3196                 else if (prefix_route)
3197                         addrconf_prefix_route(&addr, 64, idev->dev, 0, 0);
3198                 break;
3199         case IN6_ADDR_GEN_MODE_NONE:
3200         default:
3201                 /* will not add any link local address */
3202                 break;
3203         }
3204 }
3205
3206 static void addrconf_dev_config(struct net_device *dev)
3207 {
3208         struct inet6_dev *idev;
3209
3210         ASSERT_RTNL();
3211
3212         if ((dev->type != ARPHRD_ETHER) &&
3213             (dev->type != ARPHRD_FDDI) &&
3214             (dev->type != ARPHRD_ARCNET) &&
3215             (dev->type != ARPHRD_INFINIBAND) &&
3216             (dev->type != ARPHRD_IEEE1394) &&
3217             (dev->type != ARPHRD_TUNNEL6) &&
3218             (dev->type != ARPHRD_6LOWPAN) &&
3219             (dev->type != ARPHRD_IP6GRE) &&
3220             (dev->type != ARPHRD_IPGRE) &&
3221             (dev->type != ARPHRD_TUNNEL) &&
3222             (dev->type != ARPHRD_NONE)) {
3223                 /* Alas, we support only Ethernet autoconfiguration. */
3224                 return;
3225         }
3226
3227         idev = addrconf_add_dev(dev);
3228         if (IS_ERR(idev))
3229                 return;
3230
3231         /* this device type has no EUI support */
3232         if (dev->type == ARPHRD_NONE &&
3233             idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64)
3234                 idev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_RANDOM;
3235
3236         addrconf_addr_gen(idev, false);
3237 }
3238
3239 #if IS_ENABLED(CONFIG_IPV6_SIT)
3240 static void addrconf_sit_config(struct net_device *dev)
3241 {
3242         struct inet6_dev *idev;
3243
3244         ASSERT_RTNL();
3245
3246         /*
3247          * Configure the tunnel with one of our IPv4
3248          * addresses... we should configure all of
3249          * our v4 addrs in the tunnel
3250          */
3251
3252         idev = ipv6_find_idev(dev);
3253         if (!idev) {
3254                 pr_debug("%s: add_dev failed\n", __func__);
3255                 return;
3256         }
3257
3258         if (dev->priv_flags & IFF_ISATAP) {
3259                 addrconf_addr_gen(idev, false);
3260                 return;
3261         }
3262
3263         sit_add_v4_addrs(idev);
3264
3265         if (dev->flags&IFF_POINTOPOINT)
3266                 addrconf_add_mroute(dev);
3267 }
3268 #endif
3269
3270 #if IS_ENABLED(CONFIG_NET_IPGRE)
3271 static void addrconf_gre_config(struct net_device *dev)
3272 {
3273         struct inet6_dev *idev;
3274
3275         ASSERT_RTNL();
3276
3277         idev = ipv6_find_idev(dev);
3278         if (!idev) {
3279                 pr_debug("%s: add_dev failed\n", __func__);
3280                 return;
3281         }
3282
3283         addrconf_addr_gen(idev, true);
3284         if (dev->flags & IFF_POINTOPOINT)
3285                 addrconf_add_mroute(dev);
3286 }
3287 #endif
3288
3289 static int fixup_permanent_addr(struct inet6_dev *idev,
3290                                 struct inet6_ifaddr *ifp)
3291 {
3292         /* !rt6i_node means the host route was removed from the
3293          * FIB, for example, if 'lo' device is taken down. In that
3294          * case regenerate the host route.
3295          */
3296         if (!ifp->rt || !ifp->rt->rt6i_node) {
3297                 struct rt6_info *rt, *prev;
3298
3299                 rt = addrconf_dst_alloc(idev, &ifp->addr, false);
3300                 if (unlikely(IS_ERR(rt)))
3301                         return PTR_ERR(rt);
3302
3303                 /* ifp->rt can be accessed outside of rtnl */
3304                 spin_lock(&ifp->lock);
3305                 prev = ifp->rt;
3306                 ifp->rt = rt;
3307                 spin_unlock(&ifp->lock);
3308
3309                 ip6_rt_put(prev);
3310         }
3311
3312         if (!(ifp->flags & IFA_F_NOPREFIXROUTE)) {
3313                 addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
3314                                       idev->dev, 0, 0);
3315         }
3316
3317         if (ifp->state == INET6_IFADDR_STATE_PREDAD)
3318                 addrconf_dad_start(ifp);
3319
3320         return 0;
3321 }
3322
3323 static void addrconf_permanent_addr(struct net_device *dev)
3324 {
3325         struct inet6_ifaddr *ifp, *tmp;
3326         struct inet6_dev *idev;
3327
3328         idev = __in6_dev_get(dev);
3329         if (!idev)
3330                 return;
3331
3332         write_lock_bh(&idev->lock);
3333
3334         list_for_each_entry_safe(ifp, tmp, &idev->addr_list, if_list) {
3335                 if ((ifp->flags & IFA_F_PERMANENT) &&
3336                     fixup_permanent_addr(idev, ifp) < 0) {
3337                         write_unlock_bh(&idev->lock);
3338                         ipv6_del_addr(ifp);
3339                         write_lock_bh(&idev->lock);
3340
3341                         net_info_ratelimited("%s: Failed to add prefix route for address %pI6c; dropping\n",
3342                                              idev->dev->name, &ifp->addr);
3343                 }
3344         }
3345
3346         write_unlock_bh(&idev->lock);
3347 }
3348
3349 static int addrconf_notify(struct notifier_block *this, unsigned long event,
3350                            void *ptr)
3351 {
3352         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3353         struct netdev_notifier_changeupper_info *info;
3354         struct inet6_dev *idev = __in6_dev_get(dev);
3355         struct net *net = dev_net(dev);
3356         int run_pending = 0;
3357         int err;
3358
3359         switch (event) {
3360         case NETDEV_REGISTER:
3361                 if (!idev && dev->mtu >= IPV6_MIN_MTU) {
3362                         idev = ipv6_add_dev(dev);
3363                         if (IS_ERR(idev))
3364                                 return notifier_from_errno(PTR_ERR(idev));
3365                 }
3366                 break;
3367
3368         case NETDEV_CHANGEMTU:
3369                 /* if MTU under IPV6_MIN_MTU stop IPv6 on this interface. */
3370                 if (dev->mtu < IPV6_MIN_MTU) {
3371                         addrconf_ifdown(dev, dev != net->loopback_dev);
3372                         break;
3373                 }
3374
3375                 if (idev) {
3376                         rt6_mtu_change(dev, dev->mtu);
3377                         idev->cnf.mtu6 = dev->mtu;
3378                         break;
3379                 }
3380
3381                 /* allocate new idev */
3382                 idev = ipv6_add_dev(dev);
3383                 if (IS_ERR(idev))
3384                         break;
3385
3386                 /* device is still not ready */
3387                 if (!(idev->if_flags & IF_READY))
3388                         break;
3389
3390                 run_pending = 1;
3391
3392                 /* fall through */
3393
3394         case NETDEV_UP:
3395         case NETDEV_CHANGE:
3396                 if (dev->flags & IFF_SLAVE)
3397                         break;
3398
3399                 if (idev && idev->cnf.disable_ipv6)
3400                         break;
3401
3402                 if (event == NETDEV_UP) {
3403                         /* restore routes for permanent addresses */
3404                         addrconf_permanent_addr(dev);
3405
3406                         if (!addrconf_qdisc_ok(dev)) {
3407                                 /* device is not ready yet. */
3408                                 pr_info("ADDRCONF(NETDEV_UP): %s: link is not ready\n",
3409                                         dev->name);
3410                                 break;
3411                         }
3412
3413                         if (!idev && dev->mtu >= IPV6_MIN_MTU)
3414                                 idev = ipv6_add_dev(dev);
3415
3416                         if (!IS_ERR_OR_NULL(idev)) {
3417                                 idev->if_flags |= IF_READY;
3418                                 run_pending = 1;
3419                         }
3420                 } else if (event == NETDEV_CHANGE) {
3421                         if (!addrconf_qdisc_ok(dev)) {
3422                                 /* device is still not ready. */
3423                                 break;
3424                         }
3425
3426                         if (idev) {
3427                                 if (idev->if_flags & IF_READY) {
3428                                         /* device is already configured -
3429                                          * but resend MLD reports, we might
3430                                          * have roamed and need to update
3431                                          * multicast snooping switches
3432                                          */
3433                                         ipv6_mc_up(idev);
3434                                         break;
3435                                 }
3436                                 idev->if_flags |= IF_READY;
3437                         }
3438
3439                         pr_info("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n",
3440                                 dev->name);
3441
3442                         run_pending = 1;
3443                 }
3444
3445                 switch (dev->type) {
3446 #if IS_ENABLED(CONFIG_IPV6_SIT)
3447                 case ARPHRD_SIT:
3448                         addrconf_sit_config(dev);
3449                         break;
3450 #endif
3451 #if IS_ENABLED(CONFIG_NET_IPGRE)
3452                 case ARPHRD_IPGRE:
3453                         addrconf_gre_config(dev);
3454                         break;
3455 #endif
3456                 case ARPHRD_LOOPBACK:
3457                         init_loopback(dev);
3458                         break;
3459
3460                 default:
3461                         addrconf_dev_config(dev);
3462                         break;
3463                 }
3464
3465                 if (!IS_ERR_OR_NULL(idev)) {
3466                         if (run_pending)
3467                                 addrconf_dad_run(idev);
3468
3469                         /*
3470                          * If the MTU changed during the interface down,
3471                          * when the interface up, the changed MTU must be
3472                          * reflected in the idev as well as routers.
3473                          */
3474                         if (idev->cnf.mtu6 != dev->mtu &&
3475                             dev->mtu >= IPV6_MIN_MTU) {
3476                                 rt6_mtu_change(dev, dev->mtu);
3477                                 idev->cnf.mtu6 = dev->mtu;
3478                         }
3479                         idev->tstamp = jiffies;
3480                         inet6_ifinfo_notify(RTM_NEWLINK, idev);
3481
3482                         /*
3483                          * If the changed mtu during down is lower than
3484                          * IPV6_MIN_MTU stop IPv6 on this interface.
3485                          */
3486                         if (dev->mtu < IPV6_MIN_MTU)
3487                                 addrconf_ifdown(dev, dev != net->loopback_dev);
3488                 }
3489                 break;
3490
3491         case NETDEV_DOWN:
3492         case NETDEV_UNREGISTER:
3493                 /*
3494                  *      Remove all addresses from this interface.
3495                  */
3496                 addrconf_ifdown(dev, event != NETDEV_DOWN);
3497                 break;
3498
3499         case NETDEV_CHANGENAME:
3500                 if (idev) {
3501                         snmp6_unregister_dev(idev);
3502                         addrconf_sysctl_unregister(idev);
3503                         err = addrconf_sysctl_register(idev);
3504                         if (err)
3505                                 return notifier_from_errno(err);
3506                         err = snmp6_register_dev(idev);
3507                         if (err) {
3508                                 addrconf_sysctl_unregister(idev);
3509                                 return notifier_from_errno(err);
3510                         }
3511                 }
3512                 break;
3513
3514         case NETDEV_PRE_TYPE_CHANGE:
3515         case NETDEV_POST_TYPE_CHANGE:
3516                 if (idev)
3517                         addrconf_type_change(dev, event);
3518                 break;
3519
3520         case NETDEV_CHANGEUPPER:
3521                 info = ptr;
3522
3523                 /* flush all routes if dev is linked to or unlinked from
3524                  * an L3 master device (e.g., VRF)
3525                  */
3526                 if (info->upper_dev && netif_is_l3_master(info->upper_dev))
3527                         addrconf_ifdown(dev, 0);
3528         }
3529
3530         return NOTIFY_OK;
3531 }
3532
3533 /*
3534  *      addrconf module should be notified of a device going up
3535  */
3536 static struct notifier_block ipv6_dev_notf = {
3537         .notifier_call = addrconf_notify,
3538         .priority = ADDRCONF_NOTIFY_PRIORITY,
3539 };
3540
3541 static void addrconf_type_change(struct net_device *dev, unsigned long event)
3542 {
3543         struct inet6_dev *idev;
3544         ASSERT_RTNL();
3545
3546         idev = __in6_dev_get(dev);
3547
3548         if (event == NETDEV_POST_TYPE_CHANGE)
3549                 ipv6_mc_remap(idev);
3550         else if (event == NETDEV_PRE_TYPE_CHANGE)
3551                 ipv6_mc_unmap(idev);
3552 }
3553
3554 static bool addr_is_local(const struct in6_addr *addr)
3555 {
3556         return ipv6_addr_type(addr) &
3557                 (IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
3558 }
3559
3560 static int addrconf_ifdown(struct net_device *dev, int how)
3561 {
3562         struct net *net = dev_net(dev);
3563         struct inet6_dev *idev;
3564         struct inet6_ifaddr *ifa, *tmp;
3565         struct list_head del_list;
3566         int _keep_addr;
3567         bool keep_addr;
3568         int state, i;
3569
3570         ASSERT_RTNL();
3571
3572         rt6_ifdown(net, dev);
3573         neigh_ifdown(&nd_tbl, dev);
3574
3575         idev = __in6_dev_get(dev);
3576         if (!idev)
3577                 return -ENODEV;
3578
3579         /*
3580          * Step 1: remove reference to ipv6 device from parent device.
3581          *         Do not dev_put!
3582          */
3583         if (how) {
3584                 idev->dead = 1;
3585
3586                 /* protected by rtnl_lock */
3587                 RCU_INIT_POINTER(dev->ip6_ptr, NULL);
3588
3589                 /* Step 1.5: remove snmp6 entry */
3590                 snmp6_unregister_dev(idev);
3591
3592         }
3593
3594         /* aggregate the system setting and interface setting */
3595         _keep_addr = net->ipv6.devconf_all->keep_addr_on_down;
3596         if (!_keep_addr)
3597                 _keep_addr = idev->cnf.keep_addr_on_down;
3598
3599         /* combine the user config with event to determine if permanent
3600          * addresses are to be removed from address hash table
3601          */
3602         keep_addr = !(how || _keep_addr <= 0 || idev->cnf.disable_ipv6);
3603
3604         /* Step 2: clear hash table */
3605         for (i = 0; i < IN6_ADDR_HSIZE; i++) {
3606                 struct hlist_head *h = &inet6_addr_lst[i];
3607
3608                 spin_lock_bh(&addrconf_hash_lock);
3609 restart:
3610                 hlist_for_each_entry_rcu(ifa, h, addr_lst) {
3611                         if (ifa->idev == idev) {
3612                                 addrconf_del_dad_work(ifa);
3613                                 /* combined flag + permanent flag decide if
3614                                  * address is retained on a down event
3615                                  */
3616                                 if (!keep_addr ||
3617                                     !(ifa->flags & IFA_F_PERMANENT) ||
3618                                     addr_is_local(&ifa->addr)) {
3619                                         hlist_del_init_rcu(&ifa->addr_lst);
3620                                         goto restart;
3621                                 }
3622                         }
3623                 }
3624                 spin_unlock_bh(&addrconf_hash_lock);
3625         }
3626
3627         write_lock_bh(&idev->lock);
3628
3629         addrconf_del_rs_timer(idev);
3630
3631         /* Step 2: clear flags for stateless addrconf */
3632         if (!how)
3633                 idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY);
3634
3635         /* Step 3: clear tempaddr list */
3636         while (!list_empty(&idev->tempaddr_list)) {
3637                 ifa = list_first_entry(&idev->tempaddr_list,
3638                                        struct inet6_ifaddr, tmp_list);
3639                 list_del(&ifa->tmp_list);
3640                 write_unlock_bh(&idev->lock);
3641                 spin_lock_bh(&ifa->lock);
3642
3643                 if (ifa->ifpub) {
3644                         in6_ifa_put(ifa->ifpub);
3645                         ifa->ifpub = NULL;
3646                 }
3647                 spin_unlock_bh(&ifa->lock);
3648                 in6_ifa_put(ifa);
3649                 write_lock_bh(&idev->lock);
3650         }
3651
3652         /* re-combine the user config with event to determine if permanent
3653          * addresses are to be removed from the interface list
3654          */
3655         keep_addr = (!how && _keep_addr > 0 && !idev->cnf.disable_ipv6);
3656
3657         INIT_LIST_HEAD(&del_list);
3658         list_for_each_entry_safe(ifa, tmp, &idev->addr_list, if_list) {
3659                 struct rt6_info *rt = NULL;
3660                 bool keep;
3661
3662                 addrconf_del_dad_work(ifa);
3663
3664                 keep = keep_addr && (ifa->flags & IFA_F_PERMANENT) &&
3665                         !addr_is_local(&ifa->addr);
3666                 if (!keep)
3667                         list_move(&ifa->if_list, &del_list);
3668
3669                 write_unlock_bh(&idev->lock);
3670                 spin_lock_bh(&ifa->lock);
3671
3672                 if (keep) {
3673                         /* set state to skip the notifier below */
3674                         state = INET6_IFADDR_STATE_DEAD;
3675                         ifa->state = INET6_IFADDR_STATE_PREDAD;
3676                         if (!(ifa->flags & IFA_F_NODAD))
3677                                 ifa->flags |= IFA_F_TENTATIVE;
3678
3679                         rt = ifa->rt;
3680                         ifa->rt = NULL;
3681                 } else {
3682                         state = ifa->state;
3683                         ifa->state = INET6_IFADDR_STATE_DEAD;
3684                 }
3685
3686                 spin_unlock_bh(&ifa->lock);
3687
3688                 if (rt)
3689                         ip6_del_rt(rt);
3690
3691                 if (state != INET6_IFADDR_STATE_DEAD) {
3692                         __ipv6_ifa_notify(RTM_DELADDR, ifa);
3693                         inet6addr_notifier_call_chain(NETDEV_DOWN, ifa);
3694                 } else {
3695                         if (idev->cnf.forwarding)
3696                                 addrconf_leave_anycast(ifa);
3697                         addrconf_leave_solict(ifa->idev, &ifa->addr);