GNU Linux-libre 4.19.314-gnu1
[releases.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 #define INFINITY_LIFE_TIME      0xFFFFFFFF
98
99 #define IPV6_MAX_STRLEN \
100         sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")
101
102 static inline u32 cstamp_delta(unsigned long cstamp)
103 {
104         return (cstamp - INITIAL_JIFFIES) * 100UL / HZ;
105 }
106
107 static inline s32 rfc3315_s14_backoff_init(s32 irt)
108 {
109         /* multiply 'initial retransmission time' by 0.9 .. 1.1 */
110         u64 tmp = (900000 + prandom_u32() % 200001) * (u64)irt;
111         do_div(tmp, 1000000);
112         return (s32)tmp;
113 }
114
115 static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
116 {
117         /* multiply 'retransmission timeout' by 1.9 .. 2.1 */
118         u64 tmp = (1900000 + prandom_u32() % 200001) * (u64)rt;
119         do_div(tmp, 1000000);
120         if ((s32)tmp > mrt) {
121                 /* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
122                 tmp = (900000 + prandom_u32() % 200001) * (u64)mrt;
123                 do_div(tmp, 1000000);
124         }
125         return (s32)tmp;
126 }
127
128 #ifdef CONFIG_SYSCTL
129 static int addrconf_sysctl_register(struct inet6_dev *idev);
130 static void addrconf_sysctl_unregister(struct inet6_dev *idev);
131 #else
132 static inline int addrconf_sysctl_register(struct inet6_dev *idev)
133 {
134         return 0;
135 }
136
137 static inline void addrconf_sysctl_unregister(struct inet6_dev *idev)
138 {
139 }
140 #endif
141
142 static void ipv6_regen_rndid(struct inet6_dev *idev);
143 static void ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr);
144
145 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev);
146 static int ipv6_count_addresses(const struct inet6_dev *idev);
147 static int ipv6_generate_stable_address(struct in6_addr *addr,
148                                         u8 dad_count,
149                                         const struct inet6_dev *idev);
150
151 #define IN6_ADDR_HSIZE_SHIFT    8
152 #define IN6_ADDR_HSIZE          (1 << IN6_ADDR_HSIZE_SHIFT)
153 /*
154  *      Configured unicast address hash table
155  */
156 static struct hlist_head inet6_addr_lst[IN6_ADDR_HSIZE];
157 static DEFINE_SPINLOCK(addrconf_hash_lock);
158
159 static void addrconf_verify(void);
160 static void addrconf_verify_rtnl(void);
161 static void addrconf_verify_work(struct work_struct *);
162
163 static struct workqueue_struct *addrconf_wq;
164 static DECLARE_DELAYED_WORK(addr_chk_work, addrconf_verify_work);
165
166 static void addrconf_join_anycast(struct inet6_ifaddr *ifp);
167 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp);
168
169 static void addrconf_type_change(struct net_device *dev,
170                                  unsigned long event);
171 static int addrconf_ifdown(struct net_device *dev, int how);
172
173 static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
174                                                   int plen,
175                                                   const struct net_device *dev,
176                                                   u32 flags, u32 noflags);
177
178 static void addrconf_dad_start(struct inet6_ifaddr *ifp);
179 static void addrconf_dad_work(struct work_struct *w);
180 static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
181                                    bool send_na);
182 static void addrconf_dad_run(struct inet6_dev *idev, bool restart);
183 static void addrconf_rs_timer(struct timer_list *t);
184 static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
185 static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa);
186
187 static void inet6_prefix_notify(int event, struct inet6_dev *idev,
188                                 struct prefix_info *pinfo);
189
190 static struct ipv6_devconf ipv6_devconf __read_mostly = {
191         .forwarding             = 0,
192         .hop_limit              = IPV6_DEFAULT_HOPLIMIT,
193         .mtu6                   = IPV6_MIN_MTU,
194         .accept_ra              = 1,
195         .accept_redirects       = 1,
196         .autoconf               = 1,
197         .force_mld_version      = 0,
198         .mldv1_unsolicited_report_interval = 10 * HZ,
199         .mldv2_unsolicited_report_interval = HZ,
200         .dad_transmits          = 1,
201         .rtr_solicits           = MAX_RTR_SOLICITATIONS,
202         .rtr_solicit_interval   = RTR_SOLICITATION_INTERVAL,
203         .rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
204         .rtr_solicit_delay      = MAX_RTR_SOLICITATION_DELAY,
205         .use_tempaddr           = 0,
206         .temp_valid_lft         = TEMP_VALID_LIFETIME,
207         .temp_prefered_lft      = TEMP_PREFERRED_LIFETIME,
208         .regen_max_retry        = REGEN_MAX_RETRY,
209         .max_desync_factor      = MAX_DESYNC_FACTOR,
210         .max_addresses          = IPV6_MAX_ADDRESSES,
211         .accept_ra_defrtr       = 1,
212         .accept_ra_from_local   = 0,
213         .accept_ra_min_hop_limit= 1,
214         .accept_ra_pinfo        = 1,
215 #ifdef CONFIG_IPV6_ROUTER_PREF
216         .accept_ra_rtr_pref     = 1,
217         .rtr_probe_interval     = 60 * HZ,
218 #ifdef CONFIG_IPV6_ROUTE_INFO
219         .accept_ra_rt_info_min_plen = 0,
220         .accept_ra_rt_info_max_plen = 0,
221 #endif
222 #endif
223         .proxy_ndp              = 0,
224         .accept_source_route    = 0,    /* we do not accept RH0 by default. */
225         .disable_ipv6           = 0,
226         .accept_dad             = 0,
227         .suppress_frag_ndisc    = 1,
228         .accept_ra_mtu          = 1,
229         .stable_secret          = {
230                 .initialized = false,
231         },
232         .use_oif_addrs_only     = 0,
233         .ignore_routes_with_linkdown = 0,
234         .keep_addr_on_down      = 0,
235         .seg6_enabled           = 0,
236 #ifdef CONFIG_IPV6_SEG6_HMAC
237         .seg6_require_hmac      = 0,
238 #endif
239         .enhanced_dad           = 1,
240         .addr_gen_mode          = IN6_ADDR_GEN_MODE_EUI64,
241         .disable_policy         = 0,
242 };
243
244 static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = {
245         .forwarding             = 0,
246         .hop_limit              = IPV6_DEFAULT_HOPLIMIT,
247         .mtu6                   = IPV6_MIN_MTU,
248         .accept_ra              = 1,
249         .accept_redirects       = 1,
250         .autoconf               = 1,
251         .force_mld_version      = 0,
252         .mldv1_unsolicited_report_interval = 10 * HZ,
253         .mldv2_unsolicited_report_interval = HZ,
254         .dad_transmits          = 1,
255         .rtr_solicits           = MAX_RTR_SOLICITATIONS,
256         .rtr_solicit_interval   = RTR_SOLICITATION_INTERVAL,
257         .rtr_solicit_max_interval = RTR_SOLICITATION_MAX_INTERVAL,
258         .rtr_solicit_delay      = MAX_RTR_SOLICITATION_DELAY,
259         .use_tempaddr           = 0,
260         .temp_valid_lft         = TEMP_VALID_LIFETIME,
261         .temp_prefered_lft      = TEMP_PREFERRED_LIFETIME,
262         .regen_max_retry        = REGEN_MAX_RETRY,
263         .max_desync_factor      = MAX_DESYNC_FACTOR,
264         .max_addresses          = IPV6_MAX_ADDRESSES,
265         .accept_ra_defrtr       = 1,
266         .accept_ra_from_local   = 0,
267         .accept_ra_min_hop_limit= 1,
268         .accept_ra_pinfo        = 1,
269 #ifdef CONFIG_IPV6_ROUTER_PREF
270         .accept_ra_rtr_pref     = 1,
271         .rtr_probe_interval     = 60 * HZ,
272 #ifdef CONFIG_IPV6_ROUTE_INFO
273         .accept_ra_rt_info_min_plen = 0,
274         .accept_ra_rt_info_max_plen = 0,
275 #endif
276 #endif
277         .proxy_ndp              = 0,
278         .accept_source_route    = 0,    /* we do not accept RH0 by default. */
279         .disable_ipv6           = 0,
280         .accept_dad             = 1,
281         .suppress_frag_ndisc    = 1,
282         .accept_ra_mtu          = 1,
283         .stable_secret          = {
284                 .initialized = false,
285         },
286         .use_oif_addrs_only     = 0,
287         .ignore_routes_with_linkdown = 0,
288         .keep_addr_on_down      = 0,
289         .seg6_enabled           = 0,
290 #ifdef CONFIG_IPV6_SEG6_HMAC
291         .seg6_require_hmac      = 0,
292 #endif
293         .enhanced_dad           = 1,
294         .addr_gen_mode          = IN6_ADDR_GEN_MODE_EUI64,
295         .disable_policy         = 0,
296 };
297
298 /* Check if link is ready: is it up and is a valid qdisc available */
299 static inline bool addrconf_link_ready(const struct net_device *dev)
300 {
301         return netif_oper_up(dev) && !qdisc_tx_is_noop(dev);
302 }
303
304 static void addrconf_del_rs_timer(struct inet6_dev *idev)
305 {
306         if (del_timer(&idev->rs_timer))
307                 __in6_dev_put(idev);
308 }
309
310 static void addrconf_del_dad_work(struct inet6_ifaddr *ifp)
311 {
312         if (cancel_delayed_work(&ifp->dad_work))
313                 __in6_ifa_put(ifp);
314 }
315
316 static void addrconf_mod_rs_timer(struct inet6_dev *idev,
317                                   unsigned long when)
318 {
319         if (!mod_timer(&idev->rs_timer, jiffies + when))
320                 in6_dev_hold(idev);
321 }
322
323 static void addrconf_mod_dad_work(struct inet6_ifaddr *ifp,
324                                    unsigned long delay)
325 {
326         in6_ifa_hold(ifp);
327         if (mod_delayed_work(addrconf_wq, &ifp->dad_work, delay))
328                 in6_ifa_put(ifp);
329 }
330
331 static int snmp6_alloc_dev(struct inet6_dev *idev)
332 {
333         int i;
334
335         idev->stats.ipv6 = alloc_percpu(struct ipstats_mib);
336         if (!idev->stats.ipv6)
337                 goto err_ip;
338
339         for_each_possible_cpu(i) {
340                 struct ipstats_mib *addrconf_stats;
341                 addrconf_stats = per_cpu_ptr(idev->stats.ipv6, i);
342                 u64_stats_init(&addrconf_stats->syncp);
343         }
344
345
346         idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device),
347                                         GFP_KERNEL);
348         if (!idev->stats.icmpv6dev)
349                 goto err_icmp;
350         idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device),
351                                            GFP_KERNEL);
352         if (!idev->stats.icmpv6msgdev)
353                 goto err_icmpmsg;
354
355         return 0;
356
357 err_icmpmsg:
358         kfree(idev->stats.icmpv6dev);
359 err_icmp:
360         free_percpu(idev->stats.ipv6);
361 err_ip:
362         return -ENOMEM;
363 }
364
365 static struct inet6_dev *ipv6_add_dev(struct net_device *dev)
366 {
367         struct inet6_dev *ndev;
368         int err = -ENOMEM;
369
370         ASSERT_RTNL();
371
372         if (dev->mtu < IPV6_MIN_MTU)
373                 return ERR_PTR(-EINVAL);
374
375         ndev = kzalloc(sizeof(struct inet6_dev), GFP_KERNEL);
376         if (!ndev)
377                 return ERR_PTR(err);
378
379         rwlock_init(&ndev->lock);
380         ndev->dev = dev;
381         INIT_LIST_HEAD(&ndev->addr_list);
382         timer_setup(&ndev->rs_timer, addrconf_rs_timer, 0);
383         memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf));
384
385         if (ndev->cnf.stable_secret.initialized)
386                 ndev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
387
388         ndev->cnf.mtu6 = dev->mtu;
389         ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl);
390         if (!ndev->nd_parms) {
391                 kfree(ndev);
392                 return ERR_PTR(err);
393         }
394         if (ndev->cnf.forwarding)
395                 dev_disable_lro(dev);
396         /* We refer to the device */
397         dev_hold(dev);
398
399         if (snmp6_alloc_dev(ndev) < 0) {
400                 netdev_dbg(dev, "%s: cannot allocate memory for statistics\n",
401                            __func__);
402                 neigh_parms_release(&nd_tbl, ndev->nd_parms);
403                 dev_put(dev);
404                 kfree(ndev);
405                 return ERR_PTR(err);
406         }
407
408         if (snmp6_register_dev(ndev) < 0) {
409                 netdev_dbg(dev, "%s: cannot create /proc/net/dev_snmp6/%s\n",
410                            __func__, dev->name);
411                 goto err_release;
412         }
413
414         /* One reference from device. */
415         refcount_set(&ndev->refcnt, 1);
416
417         if (dev->flags & (IFF_NOARP | IFF_LOOPBACK))
418                 ndev->cnf.accept_dad = -1;
419
420 #if IS_ENABLED(CONFIG_IPV6_SIT)
421         if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) {
422                 pr_info("%s: Disabled Multicast RS\n", dev->name);
423                 ndev->cnf.rtr_solicits = 0;
424         }
425 #endif
426
427         INIT_LIST_HEAD(&ndev->tempaddr_list);
428         ndev->desync_factor = U32_MAX;
429         if ((dev->flags&IFF_LOOPBACK) ||
430             dev->type == ARPHRD_TUNNEL ||
431             dev->type == ARPHRD_TUNNEL6 ||
432             dev->type == ARPHRD_SIT ||
433             dev->type == ARPHRD_NONE) {
434                 ndev->cnf.use_tempaddr = -1;
435         } else
436                 ipv6_regen_rndid(ndev);
437
438         ndev->token = in6addr_any;
439
440         if (netif_running(dev) && addrconf_link_ready(dev))
441                 ndev->if_flags |= IF_READY;
442
443         ipv6_mc_init_dev(ndev);
444         ndev->tstamp = jiffies;
445         err = addrconf_sysctl_register(ndev);
446         if (err) {
447                 ipv6_mc_destroy_dev(ndev);
448                 snmp6_unregister_dev(ndev);
449                 goto err_release;
450         }
451         /* protected by rtnl_lock */
452         rcu_assign_pointer(dev->ip6_ptr, ndev);
453
454         /* Join interface-local all-node multicast group */
455         ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allnodes);
456
457         /* Join all-node multicast group */
458         ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes);
459
460         /* Join all-router multicast group if forwarding is set */
461         if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST))
462                 ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
463
464         return ndev;
465
466 err_release:
467         neigh_parms_release(&nd_tbl, ndev->nd_parms);
468         ndev->dead = 1;
469         in6_dev_finish_destroy(ndev);
470         return ERR_PTR(err);
471 }
472
473 static struct inet6_dev *ipv6_find_idev(struct net_device *dev)
474 {
475         struct inet6_dev *idev;
476
477         ASSERT_RTNL();
478
479         idev = __in6_dev_get(dev);
480         if (!idev) {
481                 idev = ipv6_add_dev(dev);
482                 if (IS_ERR(idev))
483                         return NULL;
484         }
485
486         if (dev->flags&IFF_UP)
487                 ipv6_mc_up(idev);
488         return idev;
489 }
490
491 static int inet6_netconf_msgsize_devconf(int type)
492 {
493         int size =  NLMSG_ALIGN(sizeof(struct netconfmsg))
494                     + nla_total_size(4);        /* NETCONFA_IFINDEX */
495         bool all = false;
496
497         if (type == NETCONFA_ALL)
498                 all = true;
499
500         if (all || type == NETCONFA_FORWARDING)
501                 size += nla_total_size(4);
502 #ifdef CONFIG_IPV6_MROUTE
503         if (all || type == NETCONFA_MC_FORWARDING)
504                 size += nla_total_size(4);
505 #endif
506         if (all || type == NETCONFA_PROXY_NEIGH)
507                 size += nla_total_size(4);
508
509         if (all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN)
510                 size += nla_total_size(4);
511
512         return size;
513 }
514
515 static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
516                                       struct ipv6_devconf *devconf, u32 portid,
517                                       u32 seq, int event, unsigned int flags,
518                                       int type)
519 {
520         struct nlmsghdr  *nlh;
521         struct netconfmsg *ncm;
522         bool all = false;
523
524         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
525                         flags);
526         if (!nlh)
527                 return -EMSGSIZE;
528
529         if (type == NETCONFA_ALL)
530                 all = true;
531
532         ncm = nlmsg_data(nlh);
533         ncm->ncm_family = AF_INET6;
534
535         if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
536                 goto nla_put_failure;
537
538         if (!devconf)
539                 goto out;
540
541         if ((all || type == NETCONFA_FORWARDING) &&
542             nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0)
543                 goto nla_put_failure;
544 #ifdef CONFIG_IPV6_MROUTE
545         if ((all || type == NETCONFA_MC_FORWARDING) &&
546             nla_put_s32(skb, NETCONFA_MC_FORWARDING,
547                         devconf->mc_forwarding) < 0)
548                 goto nla_put_failure;
549 #endif
550         if ((all || type == NETCONFA_PROXY_NEIGH) &&
551             nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0)
552                 goto nla_put_failure;
553
554         if ((all || type == NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN) &&
555             nla_put_s32(skb, NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
556                         devconf->ignore_routes_with_linkdown) < 0)
557                 goto nla_put_failure;
558
559 out:
560         nlmsg_end(skb, nlh);
561         return 0;
562
563 nla_put_failure:
564         nlmsg_cancel(skb, nlh);
565         return -EMSGSIZE;
566 }
567
568 void inet6_netconf_notify_devconf(struct net *net, int event, int type,
569                                   int ifindex, struct ipv6_devconf *devconf)
570 {
571         struct sk_buff *skb;
572         int err = -ENOBUFS;
573
574         skb = nlmsg_new(inet6_netconf_msgsize_devconf(type), GFP_KERNEL);
575         if (!skb)
576                 goto errout;
577
578         err = inet6_netconf_fill_devconf(skb, ifindex, devconf, 0, 0,
579                                          event, 0, type);
580         if (err < 0) {
581                 /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
582                 WARN_ON(err == -EMSGSIZE);
583                 kfree_skb(skb);
584                 goto errout;
585         }
586         rtnl_notify(skb, net, 0, RTNLGRP_IPV6_NETCONF, NULL, GFP_KERNEL);
587         return;
588 errout:
589         rtnl_set_sk_err(net, RTNLGRP_IPV6_NETCONF, err);
590 }
591
592 static const struct nla_policy devconf_ipv6_policy[NETCONFA_MAX+1] = {
593         [NETCONFA_IFINDEX]      = { .len = sizeof(int) },
594         [NETCONFA_FORWARDING]   = { .len = sizeof(int) },
595         [NETCONFA_PROXY_NEIGH]  = { .len = sizeof(int) },
596         [NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN]  = { .len = sizeof(int) },
597 };
598
599 static int inet6_netconf_get_devconf(struct sk_buff *in_skb,
600                                      struct nlmsghdr *nlh,
601                                      struct netlink_ext_ack *extack)
602 {
603         struct net *net = sock_net(in_skb->sk);
604         struct nlattr *tb[NETCONFA_MAX+1];
605         struct inet6_dev *in6_dev = NULL;
606         struct net_device *dev = NULL;
607         struct netconfmsg *ncm;
608         struct sk_buff *skb;
609         struct ipv6_devconf *devconf;
610         int ifindex;
611         int err;
612
613         err = nlmsg_parse(nlh, sizeof(*ncm), tb, NETCONFA_MAX,
614                           devconf_ipv6_policy, extack);
615         if (err < 0)
616                 return err;
617
618         if (!tb[NETCONFA_IFINDEX])
619                 return -EINVAL;
620
621         err = -EINVAL;
622         ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
623         switch (ifindex) {
624         case NETCONFA_IFINDEX_ALL:
625                 devconf = net->ipv6.devconf_all;
626                 break;
627         case NETCONFA_IFINDEX_DEFAULT:
628                 devconf = net->ipv6.devconf_dflt;
629                 break;
630         default:
631                 dev = dev_get_by_index(net, ifindex);
632                 if (!dev)
633                         return -EINVAL;
634                 in6_dev = in6_dev_get(dev);
635                 if (!in6_dev)
636                         goto errout;
637                 devconf = &in6_dev->cnf;
638                 break;
639         }
640
641         err = -ENOBUFS;
642         skb = nlmsg_new(inet6_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
643         if (!skb)
644                 goto errout;
645
646         err = inet6_netconf_fill_devconf(skb, ifindex, devconf,
647                                          NETLINK_CB(in_skb).portid,
648                                          nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
649                                          NETCONFA_ALL);
650         if (err < 0) {
651                 /* -EMSGSIZE implies BUG in inet6_netconf_msgsize_devconf() */
652                 WARN_ON(err == -EMSGSIZE);
653                 kfree_skb(skb);
654                 goto errout;
655         }
656         err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
657 errout:
658         if (in6_dev)
659                 in6_dev_put(in6_dev);
660         if (dev)
661                 dev_put(dev);
662         return err;
663 }
664
665 static int inet6_netconf_dump_devconf(struct sk_buff *skb,
666                                       struct netlink_callback *cb)
667 {
668         struct net *net = sock_net(skb->sk);
669         int h, s_h;
670         int idx, s_idx;
671         struct net_device *dev;
672         struct inet6_dev *idev;
673         struct hlist_head *head;
674
675         s_h = cb->args[0];
676         s_idx = idx = cb->args[1];
677
678         for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
679                 idx = 0;
680                 head = &net->dev_index_head[h];
681                 rcu_read_lock();
682                 cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^
683                           net->dev_base_seq;
684                 hlist_for_each_entry_rcu(dev, head, index_hlist) {
685                         if (idx < s_idx)
686                                 goto cont;
687                         idev = __in6_dev_get(dev);
688                         if (!idev)
689                                 goto cont;
690
691                         if (inet6_netconf_fill_devconf(skb, dev->ifindex,
692                                                        &idev->cnf,
693                                                        NETLINK_CB(cb->skb).portid,
694                                                        cb->nlh->nlmsg_seq,
695                                                        RTM_NEWNETCONF,
696                                                        NLM_F_MULTI,
697                                                        NETCONFA_ALL) < 0) {
698                                 rcu_read_unlock();
699                                 goto done;
700                         }
701                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
702 cont:
703                         idx++;
704                 }
705                 rcu_read_unlock();
706         }
707         if (h == NETDEV_HASHENTRIES) {
708                 if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_ALL,
709                                                net->ipv6.devconf_all,
710                                                NETLINK_CB(cb->skb).portid,
711                                                cb->nlh->nlmsg_seq,
712                                                RTM_NEWNETCONF, NLM_F_MULTI,
713                                                NETCONFA_ALL) < 0)
714                         goto done;
715                 else
716                         h++;
717         }
718         if (h == NETDEV_HASHENTRIES + 1) {
719                 if (inet6_netconf_fill_devconf(skb, NETCONFA_IFINDEX_DEFAULT,
720                                                net->ipv6.devconf_dflt,
721                                                NETLINK_CB(cb->skb).portid,
722                                                cb->nlh->nlmsg_seq,
723                                                RTM_NEWNETCONF, NLM_F_MULTI,
724                                                NETCONFA_ALL) < 0)
725                         goto done;
726                 else
727                         h++;
728         }
729 done:
730         cb->args[0] = h;
731         cb->args[1] = idx;
732
733         return skb->len;
734 }
735
736 #ifdef CONFIG_SYSCTL
737 static void dev_forward_change(struct inet6_dev *idev)
738 {
739         struct net_device *dev;
740         struct inet6_ifaddr *ifa;
741         LIST_HEAD(tmp_addr_list);
742
743         if (!idev)
744                 return;
745         dev = idev->dev;
746         if (idev->cnf.forwarding)
747                 dev_disable_lro(dev);
748         if (dev->flags & IFF_MULTICAST) {
749                 if (idev->cnf.forwarding) {
750                         ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters);
751                         ipv6_dev_mc_inc(dev, &in6addr_interfacelocal_allrouters);
752                         ipv6_dev_mc_inc(dev, &in6addr_sitelocal_allrouters);
753                 } else {
754                         ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters);
755                         ipv6_dev_mc_dec(dev, &in6addr_interfacelocal_allrouters);
756                         ipv6_dev_mc_dec(dev, &in6addr_sitelocal_allrouters);
757                 }
758         }
759
760         read_lock_bh(&idev->lock);
761         list_for_each_entry(ifa, &idev->addr_list, if_list) {
762                 if (ifa->flags&IFA_F_TENTATIVE)
763                         continue;
764                 list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
765         }
766         read_unlock_bh(&idev->lock);
767
768         while (!list_empty(&tmp_addr_list)) {
769                 ifa = list_first_entry(&tmp_addr_list,
770                                        struct inet6_ifaddr, if_list_aux);
771                 list_del(&ifa->if_list_aux);
772                 if (idev->cnf.forwarding)
773                         addrconf_join_anycast(ifa);
774                 else
775                         addrconf_leave_anycast(ifa);
776         }
777
778         inet6_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
779                                      NETCONFA_FORWARDING,
780                                      dev->ifindex, &idev->cnf);
781 }
782
783
784 static void addrconf_forward_change(struct net *net, __s32 newf)
785 {
786         struct net_device *dev;
787         struct inet6_dev *idev;
788
789         for_each_netdev(net, dev) {
790                 idev = __in6_dev_get(dev);
791                 if (idev) {
792                         int changed = (!idev->cnf.forwarding) ^ (!newf);
793                         idev->cnf.forwarding = newf;
794                         if (changed)
795                                 dev_forward_change(idev);
796                 }
797         }
798 }
799
800 static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf)
801 {
802         struct net *net;
803         int old;
804
805         if (!rtnl_trylock())
806                 return restart_syscall();
807
808         net = (struct net *)table->extra2;
809         old = *p;
810         *p = newf;
811
812         if (p == &net->ipv6.devconf_dflt->forwarding) {
813                 if ((!newf) ^ (!old))
814                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
815                                                      NETCONFA_FORWARDING,
816                                                      NETCONFA_IFINDEX_DEFAULT,
817                                                      net->ipv6.devconf_dflt);
818                 rtnl_unlock();
819                 return 0;
820         }
821
822         if (p == &net->ipv6.devconf_all->forwarding) {
823                 int old_dflt = net->ipv6.devconf_dflt->forwarding;
824
825                 net->ipv6.devconf_dflt->forwarding = newf;
826                 if ((!newf) ^ (!old_dflt))
827                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
828                                                      NETCONFA_FORWARDING,
829                                                      NETCONFA_IFINDEX_DEFAULT,
830                                                      net->ipv6.devconf_dflt);
831
832                 addrconf_forward_change(net, newf);
833                 if ((!newf) ^ (!old))
834                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
835                                                      NETCONFA_FORWARDING,
836                                                      NETCONFA_IFINDEX_ALL,
837                                                      net->ipv6.devconf_all);
838         } else if ((!newf) ^ (!old))
839                 dev_forward_change((struct inet6_dev *)table->extra1);
840         rtnl_unlock();
841
842         if (newf)
843                 rt6_purge_dflt_routers(net);
844         return 1;
845 }
846
847 static void addrconf_linkdown_change(struct net *net, __s32 newf)
848 {
849         struct net_device *dev;
850         struct inet6_dev *idev;
851
852         for_each_netdev(net, dev) {
853                 idev = __in6_dev_get(dev);
854                 if (idev) {
855                         int changed = (!idev->cnf.ignore_routes_with_linkdown) ^ (!newf);
856
857                         idev->cnf.ignore_routes_with_linkdown = newf;
858                         if (changed)
859                                 inet6_netconf_notify_devconf(dev_net(dev),
860                                                              RTM_NEWNETCONF,
861                                                              NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
862                                                              dev->ifindex,
863                                                              &idev->cnf);
864                 }
865         }
866 }
867
868 static int addrconf_fixup_linkdown(struct ctl_table *table, int *p, int newf)
869 {
870         struct net *net;
871         int old;
872
873         if (!rtnl_trylock())
874                 return restart_syscall();
875
876         net = (struct net *)table->extra2;
877         old = *p;
878         *p = newf;
879
880         if (p == &net->ipv6.devconf_dflt->ignore_routes_with_linkdown) {
881                 if ((!newf) ^ (!old))
882                         inet6_netconf_notify_devconf(net,
883                                                      RTM_NEWNETCONF,
884                                                      NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
885                                                      NETCONFA_IFINDEX_DEFAULT,
886                                                      net->ipv6.devconf_dflt);
887                 rtnl_unlock();
888                 return 0;
889         }
890
891         if (p == &net->ipv6.devconf_all->ignore_routes_with_linkdown) {
892                 net->ipv6.devconf_dflt->ignore_routes_with_linkdown = newf;
893                 addrconf_linkdown_change(net, newf);
894                 if ((!newf) ^ (!old))
895                         inet6_netconf_notify_devconf(net,
896                                                      RTM_NEWNETCONF,
897                                                      NETCONFA_IGNORE_ROUTES_WITH_LINKDOWN,
898                                                      NETCONFA_IFINDEX_ALL,
899                                                      net->ipv6.devconf_all);
900         }
901         rtnl_unlock();
902
903         return 1;
904 }
905
906 #endif
907
908 /* Nobody refers to this ifaddr, destroy it */
909 void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp)
910 {
911         WARN_ON(!hlist_unhashed(&ifp->addr_lst));
912
913 #ifdef NET_REFCNT_DEBUG
914         pr_debug("%s\n", __func__);
915 #endif
916
917         in6_dev_put(ifp->idev);
918
919         if (cancel_delayed_work(&ifp->dad_work))
920                 pr_notice("delayed DAD work was pending while freeing ifa=%p\n",
921                           ifp);
922
923         if (ifp->state != INET6_IFADDR_STATE_DEAD) {
924                 pr_warn("Freeing alive inet6 address %p\n", ifp);
925                 return;
926         }
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_rcu(&ifp->if_list, p);
949 }
950
951 static u32 inet6_addr_hash(const struct net *net, const struct in6_addr *addr)
952 {
953         u32 val = ipv6_addr_hash(addr) ^ net_hash_mix(net);
954
955         return hash_32(val, IN6_ADDR_HSIZE_SHIFT);
956 }
957
958 static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr,
959                                struct net_device *dev, unsigned int hash)
960 {
961         struct inet6_ifaddr *ifp;
962
963         hlist_for_each_entry(ifp, &inet6_addr_lst[hash], addr_lst) {
964                 if (!net_eq(dev_net(ifp->idev->dev), net))
965                         continue;
966                 if (ipv6_addr_equal(&ifp->addr, addr)) {
967                         if (!dev || ifp->idev->dev == dev)
968                                 return true;
969                 }
970         }
971         return false;
972 }
973
974 static int ipv6_add_addr_hash(struct net_device *dev, struct inet6_ifaddr *ifa)
975 {
976         unsigned int hash = inet6_addr_hash(dev_net(dev), &ifa->addr);
977         int err = 0;
978
979         spin_lock(&addrconf_hash_lock);
980
981         /* Ignore adding duplicate addresses on an interface */
982         if (ipv6_chk_same_addr(dev_net(dev), &ifa->addr, dev, hash)) {
983                 netdev_dbg(dev, "ipv6_add_addr: already assigned\n");
984                 err = -EEXIST;
985         } else {
986                 hlist_add_head_rcu(&ifa->addr_lst, &inet6_addr_lst[hash]);
987         }
988
989         spin_unlock(&addrconf_hash_lock);
990
991         return err;
992 }
993
994 /* On success it returns ifp with increased reference count */
995
996 static struct inet6_ifaddr *
997 ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
998               bool can_block, struct netlink_ext_ack *extack)
999 {
1000         gfp_t gfp_flags = can_block ? GFP_KERNEL : GFP_ATOMIC;
1001         int addr_type = ipv6_addr_type(cfg->pfx);
1002         struct net *net = dev_net(idev->dev);
1003         struct inet6_ifaddr *ifa = NULL;
1004         struct fib6_info *f6i = NULL;
1005         int err = 0;
1006
1007         if (addr_type == IPV6_ADDR_ANY ||
1008             (addr_type & IPV6_ADDR_MULTICAST &&
1009              !(cfg->ifa_flags & IFA_F_MCAUTOJOIN)) ||
1010             (!(idev->dev->flags & IFF_LOOPBACK) &&
1011              addr_type & IPV6_ADDR_LOOPBACK))
1012                 return ERR_PTR(-EADDRNOTAVAIL);
1013
1014         if (idev->dead) {
1015                 err = -ENODEV;                  /*XXX*/
1016                 goto out;
1017         }
1018
1019         if (idev->cnf.disable_ipv6) {
1020                 err = -EACCES;
1021                 goto out;
1022         }
1023
1024         /* validator notifier needs to be blocking;
1025          * do not call in atomic context
1026          */
1027         if (can_block) {
1028                 struct in6_validator_info i6vi = {
1029                         .i6vi_addr = *cfg->pfx,
1030                         .i6vi_dev = idev,
1031                         .extack = extack,
1032                 };
1033
1034                 err = inet6addr_validator_notifier_call_chain(NETDEV_UP, &i6vi);
1035                 err = notifier_to_errno(err);
1036                 if (err < 0)
1037                         goto out;
1038         }
1039
1040         ifa = kzalloc(sizeof(*ifa), gfp_flags);
1041         if (!ifa) {
1042                 err = -ENOBUFS;
1043                 goto out;
1044         }
1045
1046         f6i = addrconf_f6i_alloc(net, idev, cfg->pfx, false, gfp_flags);
1047         if (IS_ERR(f6i)) {
1048                 err = PTR_ERR(f6i);
1049                 f6i = NULL;
1050                 goto out;
1051         }
1052
1053         if (net->ipv6.devconf_all->disable_policy ||
1054             idev->cnf.disable_policy)
1055                 f6i->dst_nopolicy = true;
1056
1057         neigh_parms_data_state_setall(idev->nd_parms);
1058
1059         ifa->addr = *cfg->pfx;
1060         if (cfg->peer_pfx)
1061                 ifa->peer_addr = *cfg->peer_pfx;
1062
1063         spin_lock_init(&ifa->lock);
1064         INIT_DELAYED_WORK(&ifa->dad_work, addrconf_dad_work);
1065         INIT_HLIST_NODE(&ifa->addr_lst);
1066         ifa->scope = cfg->scope;
1067         ifa->prefix_len = cfg->plen;
1068         ifa->rt_priority = cfg->rt_priority;
1069         ifa->flags = cfg->ifa_flags;
1070         /* No need to add the TENTATIVE flag for addresses with NODAD */
1071         if (!(cfg->ifa_flags & IFA_F_NODAD))
1072                 ifa->flags |= IFA_F_TENTATIVE;
1073         ifa->valid_lft = cfg->valid_lft;
1074         ifa->prefered_lft = cfg->preferred_lft;
1075         ifa->cstamp = ifa->tstamp = jiffies;
1076         ifa->tokenized = false;
1077
1078         ifa->rt = f6i;
1079
1080         ifa->idev = idev;
1081         in6_dev_hold(idev);
1082
1083         /* For caller */
1084         refcount_set(&ifa->refcnt, 1);
1085
1086         rcu_read_lock_bh();
1087
1088         err = ipv6_add_addr_hash(idev->dev, ifa);
1089         if (err < 0) {
1090                 rcu_read_unlock_bh();
1091                 goto out;
1092         }
1093
1094         write_lock(&idev->lock);
1095
1096         /* Add to inet6_dev unicast addr list. */
1097         ipv6_link_dev_addr(idev, ifa);
1098
1099         if (ifa->flags&IFA_F_TEMPORARY) {
1100                 list_add(&ifa->tmp_list, &idev->tempaddr_list);
1101                 in6_ifa_hold(ifa);
1102         }
1103
1104         in6_ifa_hold(ifa);
1105         write_unlock(&idev->lock);
1106
1107         rcu_read_unlock_bh();
1108
1109         inet6addr_notifier_call_chain(NETDEV_UP, ifa);
1110 out:
1111         if (unlikely(err < 0)) {
1112                 fib6_info_release(f6i);
1113
1114                 if (ifa) {
1115                         if (ifa->idev)
1116                                 in6_dev_put(ifa->idev);
1117                         kfree(ifa);
1118                 }
1119                 ifa = ERR_PTR(err);
1120         }
1121
1122         return ifa;
1123 }
1124
1125 enum cleanup_prefix_rt_t {
1126         CLEANUP_PREFIX_RT_NOP,    /* no cleanup action for prefix route */
1127         CLEANUP_PREFIX_RT_DEL,    /* delete the prefix route */
1128         CLEANUP_PREFIX_RT_EXPIRE, /* update the lifetime of the prefix route */
1129 };
1130
1131 /*
1132  * Check, whether the prefix for ifp would still need a prefix route
1133  * after deleting ifp. The function returns one of the CLEANUP_PREFIX_RT_*
1134  * constants.
1135  *
1136  * 1) we don't purge prefix if address was not permanent.
1137  *    prefix is managed by its own lifetime.
1138  * 2) we also don't purge, if the address was IFA_F_NOPREFIXROUTE.
1139  * 3) if there are no addresses, delete prefix.
1140  * 4) if there are still other permanent address(es),
1141  *    corresponding prefix is still permanent.
1142  * 5) if there are still other addresses with IFA_F_NOPREFIXROUTE,
1143  *    don't purge the prefix, assume user space is managing it.
1144  * 6) otherwise, update prefix lifetime to the
1145  *    longest valid lifetime among the corresponding
1146  *    addresses on the device.
1147  *    Note: subsequent RA will update lifetime.
1148  **/
1149 static enum cleanup_prefix_rt_t
1150 check_cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long *expires)
1151 {
1152         struct inet6_ifaddr *ifa;
1153         struct inet6_dev *idev = ifp->idev;
1154         unsigned long lifetime;
1155         enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_DEL;
1156
1157         *expires = jiffies;
1158
1159         list_for_each_entry(ifa, &idev->addr_list, if_list) {
1160                 if (ifa == ifp)
1161                         continue;
1162                 if (ifa->prefix_len != ifp->prefix_len ||
1163                     !ipv6_prefix_equal(&ifa->addr, &ifp->addr,
1164                                        ifp->prefix_len))
1165                         continue;
1166                 if (ifa->flags & (IFA_F_PERMANENT | IFA_F_NOPREFIXROUTE))
1167                         return CLEANUP_PREFIX_RT_NOP;
1168
1169                 action = CLEANUP_PREFIX_RT_EXPIRE;
1170
1171                 spin_lock(&ifa->lock);
1172
1173                 lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ);
1174                 /*
1175                  * Note: Because this address is
1176                  * not permanent, lifetime <
1177                  * LONG_MAX / HZ here.
1178                  */
1179                 if (time_before(*expires, ifa->tstamp + lifetime * HZ))
1180                         *expires = ifa->tstamp + lifetime * HZ;
1181                 spin_unlock(&ifa->lock);
1182         }
1183
1184         return action;
1185 }
1186
1187 static void
1188 cleanup_prefix_route(struct inet6_ifaddr *ifp, unsigned long expires,
1189                      bool del_rt, bool del_peer)
1190 {
1191         struct fib6_info *f6i;
1192
1193         f6i = addrconf_get_prefix_route(del_peer ? &ifp->peer_addr : &ifp->addr,
1194                                        ifp->prefix_len,
1195                                        ifp->idev->dev,
1196                                        0, RTF_GATEWAY | RTF_DEFAULT);
1197         if (f6i) {
1198                 if (del_rt)
1199                         ip6_del_rt(dev_net(ifp->idev->dev), f6i);
1200                 else {
1201                         if (!(f6i->fib6_flags & RTF_EXPIRES))
1202                                 fib6_set_expires(f6i, expires);
1203                         fib6_info_release(f6i);
1204                 }
1205         }
1206 }
1207
1208
1209 /* This function wants to get referenced ifp and releases it before return */
1210
1211 static void ipv6_del_addr(struct inet6_ifaddr *ifp)
1212 {
1213         int state;
1214         enum cleanup_prefix_rt_t action = CLEANUP_PREFIX_RT_NOP;
1215         unsigned long expires;
1216
1217         ASSERT_RTNL();
1218
1219         spin_lock_bh(&ifp->lock);
1220         state = ifp->state;
1221         ifp->state = INET6_IFADDR_STATE_DEAD;
1222         spin_unlock_bh(&ifp->lock);
1223
1224         if (state == INET6_IFADDR_STATE_DEAD)
1225                 goto out;
1226
1227         spin_lock_bh(&addrconf_hash_lock);
1228         hlist_del_init_rcu(&ifp->addr_lst);
1229         spin_unlock_bh(&addrconf_hash_lock);
1230
1231         write_lock_bh(&ifp->idev->lock);
1232
1233         if (ifp->flags&IFA_F_TEMPORARY) {
1234                 list_del(&ifp->tmp_list);
1235                 if (ifp->ifpub) {
1236                         in6_ifa_put(ifp->ifpub);
1237                         ifp->ifpub = NULL;
1238                 }
1239                 __in6_ifa_put(ifp);
1240         }
1241
1242         if (ifp->flags & IFA_F_PERMANENT && !(ifp->flags & IFA_F_NOPREFIXROUTE))
1243                 action = check_cleanup_prefix_route(ifp, &expires);
1244
1245         list_del_rcu(&ifp->if_list);
1246         __in6_ifa_put(ifp);
1247
1248         write_unlock_bh(&ifp->idev->lock);
1249
1250         addrconf_del_dad_work(ifp);
1251
1252         ipv6_ifa_notify(RTM_DELADDR, ifp);
1253
1254         inet6addr_notifier_call_chain(NETDEV_DOWN, ifp);
1255
1256         if (action != CLEANUP_PREFIX_RT_NOP) {
1257                 cleanup_prefix_route(ifp, expires,
1258                         action == CLEANUP_PREFIX_RT_DEL, false);
1259         }
1260
1261         /* clean up prefsrc entries */
1262         rt6_remove_prefsrc(ifp);
1263 out:
1264         in6_ifa_put(ifp);
1265 }
1266
1267 static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp,
1268                                 struct inet6_ifaddr *ift,
1269                                 bool block)
1270 {
1271         struct inet6_dev *idev = ifp->idev;
1272         struct in6_addr addr, *tmpaddr;
1273         unsigned long tmp_tstamp, age;
1274         unsigned long regen_advance;
1275         struct ifa6_config cfg;
1276         int ret = 0;
1277         unsigned long now = jiffies;
1278         long max_desync_factor;
1279         s32 cnf_temp_preferred_lft;
1280
1281         write_lock_bh(&idev->lock);
1282         if (ift) {
1283                 spin_lock_bh(&ift->lock);
1284                 memcpy(&addr.s6_addr[8], &ift->addr.s6_addr[8], 8);
1285                 spin_unlock_bh(&ift->lock);
1286                 tmpaddr = &addr;
1287         } else {
1288                 tmpaddr = NULL;
1289         }
1290 retry:
1291         in6_dev_hold(idev);
1292         if (idev->cnf.use_tempaddr <= 0) {
1293                 write_unlock_bh(&idev->lock);
1294                 pr_info("%s: use_tempaddr is disabled\n", __func__);
1295                 in6_dev_put(idev);
1296                 ret = -1;
1297                 goto out;
1298         }
1299         spin_lock_bh(&ifp->lock);
1300         if (ifp->regen_count++ >= idev->cnf.regen_max_retry) {
1301                 idev->cnf.use_tempaddr = -1;    /*XXX*/
1302                 spin_unlock_bh(&ifp->lock);
1303                 write_unlock_bh(&idev->lock);
1304                 pr_warn("%s: regeneration time exceeded - disabled temporary address support\n",
1305                         __func__);
1306                 in6_dev_put(idev);
1307                 ret = -1;
1308                 goto out;
1309         }
1310         in6_ifa_hold(ifp);
1311         memcpy(addr.s6_addr, ifp->addr.s6_addr, 8);
1312         ipv6_try_regen_rndid(idev, tmpaddr);
1313         memcpy(&addr.s6_addr[8], idev->rndid, 8);
1314         age = (now - ifp->tstamp) / HZ;
1315
1316         regen_advance = idev->cnf.regen_max_retry *
1317                         idev->cnf.dad_transmits *
1318                         NEIGH_VAR(idev->nd_parms, RETRANS_TIME) / HZ;
1319
1320         /* recalculate max_desync_factor each time and update
1321          * idev->desync_factor if it's larger
1322          */
1323         cnf_temp_preferred_lft = READ_ONCE(idev->cnf.temp_prefered_lft);
1324         max_desync_factor = min_t(long,
1325                                   idev->cnf.max_desync_factor,
1326                                   cnf_temp_preferred_lft - regen_advance);
1327
1328         if (unlikely(idev->desync_factor > max_desync_factor)) {
1329                 if (max_desync_factor > 0) {
1330                         get_random_bytes(&idev->desync_factor,
1331                                          sizeof(idev->desync_factor));
1332                         idev->desync_factor %= max_desync_factor;
1333                 } else {
1334                         idev->desync_factor = 0;
1335                 }
1336         }
1337
1338         memset(&cfg, 0, sizeof(cfg));
1339         cfg.valid_lft = min_t(__u32, ifp->valid_lft,
1340                               idev->cnf.temp_valid_lft + age);
1341         cfg.preferred_lft = cnf_temp_preferred_lft + age - idev->desync_factor;
1342         cfg.preferred_lft = min_t(__u32, ifp->prefered_lft, cfg.preferred_lft);
1343
1344         cfg.plen = ifp->prefix_len;
1345         tmp_tstamp = ifp->tstamp;
1346         spin_unlock_bh(&ifp->lock);
1347
1348         write_unlock_bh(&idev->lock);
1349
1350         /* A temporary address is created only if this calculated Preferred
1351          * Lifetime is greater than REGEN_ADVANCE time units.  In particular,
1352          * an implementation must not create a temporary address with a zero
1353          * Preferred Lifetime.
1354          * Use age calculation as in addrconf_verify to avoid unnecessary
1355          * temporary addresses being generated.
1356          */
1357         age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
1358         if (cfg.preferred_lft <= regen_advance + age) {
1359                 in6_ifa_put(ifp);
1360                 in6_dev_put(idev);
1361                 ret = -1;
1362                 goto out;
1363         }
1364
1365         cfg.ifa_flags = IFA_F_TEMPORARY;
1366         /* set in addrconf_prefix_rcv() */
1367         if (ifp->flags & IFA_F_OPTIMISTIC)
1368                 cfg.ifa_flags |= IFA_F_OPTIMISTIC;
1369
1370         cfg.pfx = &addr;
1371         cfg.scope = ipv6_addr_scope(cfg.pfx);
1372
1373         ift = ipv6_add_addr(idev, &cfg, block, NULL);
1374         if (IS_ERR(ift)) {
1375                 in6_ifa_put(ifp);
1376                 in6_dev_put(idev);
1377                 pr_info("%s: retry temporary address regeneration\n", __func__);
1378                 tmpaddr = &addr;
1379                 write_lock_bh(&idev->lock);
1380                 goto retry;
1381         }
1382
1383         spin_lock_bh(&ift->lock);
1384         ift->ifpub = ifp;
1385         ift->cstamp = now;
1386         ift->tstamp = tmp_tstamp;
1387         spin_unlock_bh(&ift->lock);
1388
1389         addrconf_dad_start(ift);
1390         in6_ifa_put(ift);
1391         in6_dev_put(idev);
1392 out:
1393         return ret;
1394 }
1395
1396 /*
1397  *      Choose an appropriate source address (RFC3484)
1398  */
1399 enum {
1400         IPV6_SADDR_RULE_INIT = 0,
1401         IPV6_SADDR_RULE_LOCAL,
1402         IPV6_SADDR_RULE_SCOPE,
1403         IPV6_SADDR_RULE_PREFERRED,
1404 #ifdef CONFIG_IPV6_MIP6
1405         IPV6_SADDR_RULE_HOA,
1406 #endif
1407         IPV6_SADDR_RULE_OIF,
1408         IPV6_SADDR_RULE_LABEL,
1409         IPV6_SADDR_RULE_PRIVACY,
1410         IPV6_SADDR_RULE_ORCHID,
1411         IPV6_SADDR_RULE_PREFIX,
1412 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1413         IPV6_SADDR_RULE_NOT_OPTIMISTIC,
1414 #endif
1415         IPV6_SADDR_RULE_MAX
1416 };
1417
1418 struct ipv6_saddr_score {
1419         int                     rule;
1420         int                     addr_type;
1421         struct inet6_ifaddr     *ifa;
1422         DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX);
1423         int                     scopedist;
1424         int                     matchlen;
1425 };
1426
1427 struct ipv6_saddr_dst {
1428         const struct in6_addr *addr;
1429         int ifindex;
1430         int scope;
1431         int label;
1432         unsigned int prefs;
1433 };
1434
1435 static inline int ipv6_saddr_preferred(int type)
1436 {
1437         if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK))
1438                 return 1;
1439         return 0;
1440 }
1441
1442 static bool ipv6_use_optimistic_addr(struct net *net,
1443                                      struct inet6_dev *idev)
1444 {
1445 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1446         if (!idev)
1447                 return false;
1448         if (!net->ipv6.devconf_all->optimistic_dad && !idev->cnf.optimistic_dad)
1449                 return false;
1450         if (!net->ipv6.devconf_all->use_optimistic && !idev->cnf.use_optimistic)
1451                 return false;
1452
1453         return true;
1454 #else
1455         return false;
1456 #endif
1457 }
1458
1459 static bool ipv6_allow_optimistic_dad(struct net *net,
1460                                       struct inet6_dev *idev)
1461 {
1462 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1463         if (!idev)
1464                 return false;
1465         if (!net->ipv6.devconf_all->optimistic_dad && !idev->cnf.optimistic_dad)
1466                 return false;
1467
1468         return true;
1469 #else
1470         return false;
1471 #endif
1472 }
1473
1474 static int ipv6_get_saddr_eval(struct net *net,
1475                                struct ipv6_saddr_score *score,
1476                                struct ipv6_saddr_dst *dst,
1477                                int i)
1478 {
1479         int ret;
1480
1481         if (i <= score->rule) {
1482                 switch (i) {
1483                 case IPV6_SADDR_RULE_SCOPE:
1484                         ret = score->scopedist;
1485                         break;
1486                 case IPV6_SADDR_RULE_PREFIX:
1487                         ret = score->matchlen;
1488                         break;
1489                 default:
1490                         ret = !!test_bit(i, score->scorebits);
1491                 }
1492                 goto out;
1493         }
1494
1495         switch (i) {
1496         case IPV6_SADDR_RULE_INIT:
1497                 /* Rule 0: remember if hiscore is not ready yet */
1498                 ret = !!score->ifa;
1499                 break;
1500         case IPV6_SADDR_RULE_LOCAL:
1501                 /* Rule 1: Prefer same address */
1502                 ret = ipv6_addr_equal(&score->ifa->addr, dst->addr);
1503                 break;
1504         case IPV6_SADDR_RULE_SCOPE:
1505                 /* Rule 2: Prefer appropriate scope
1506                  *
1507                  *      ret
1508                  *       ^
1509                  *    -1 |  d 15
1510                  *    ---+--+-+---> scope
1511                  *       |
1512                  *       |             d is scope of the destination.
1513                  *  B-d  |  \
1514                  *       |   \      <- smaller scope is better if
1515                  *  B-15 |    \        if scope is enough for destination.
1516                  *       |             ret = B - scope (-1 <= scope >= d <= 15).
1517                  * d-C-1 | /
1518                  *       |/         <- greater is better
1519                  *   -C  /             if scope is not enough for destination.
1520                  *      /|             ret = scope - C (-1 <= d < scope <= 15).
1521                  *
1522                  * d - C - 1 < B -15 (for all -1 <= d <= 15).
1523                  * C > d + 14 - B >= 15 + 14 - B = 29 - B.
1524                  * Assume B = 0 and we get C > 29.
1525                  */
1526                 ret = __ipv6_addr_src_scope(score->addr_type);
1527                 if (ret >= dst->scope)
1528                         ret = -ret;
1529                 else
1530                         ret -= 128;     /* 30 is enough */
1531                 score->scopedist = ret;
1532                 break;
1533         case IPV6_SADDR_RULE_PREFERRED:
1534             {
1535                 /* Rule 3: Avoid deprecated and optimistic addresses */
1536                 u8 avoid = IFA_F_DEPRECATED;
1537
1538                 if (!ipv6_use_optimistic_addr(net, score->ifa->idev))
1539                         avoid |= IFA_F_OPTIMISTIC;
1540                 ret = ipv6_saddr_preferred(score->addr_type) ||
1541                       !(score->ifa->flags & avoid);
1542                 break;
1543             }
1544 #ifdef CONFIG_IPV6_MIP6
1545         case IPV6_SADDR_RULE_HOA:
1546             {
1547                 /* Rule 4: Prefer home address */
1548                 int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA);
1549                 ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome;
1550                 break;
1551             }
1552 #endif
1553         case IPV6_SADDR_RULE_OIF:
1554                 /* Rule 5: Prefer outgoing interface */
1555                 ret = (!dst->ifindex ||
1556                        dst->ifindex == score->ifa->idev->dev->ifindex);
1557                 break;
1558         case IPV6_SADDR_RULE_LABEL:
1559                 /* Rule 6: Prefer matching label */
1560                 ret = ipv6_addr_label(net,
1561                                       &score->ifa->addr, score->addr_type,
1562                                       score->ifa->idev->dev->ifindex) == dst->label;
1563                 break;
1564         case IPV6_SADDR_RULE_PRIVACY:
1565             {
1566                 /* Rule 7: Prefer public address
1567                  * Note: prefer temporary address if use_tempaddr >= 2
1568                  */
1569                 int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ?
1570                                 !!(dst->prefs & IPV6_PREFER_SRC_TMP) :
1571                                 score->ifa->idev->cnf.use_tempaddr >= 2;
1572                 ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp;
1573                 break;
1574             }
1575         case IPV6_SADDR_RULE_ORCHID:
1576                 /* Rule 8-: Prefer ORCHID vs ORCHID or
1577                  *          non-ORCHID vs non-ORCHID
1578                  */
1579                 ret = !(ipv6_addr_orchid(&score->ifa->addr) ^
1580                         ipv6_addr_orchid(dst->addr));
1581                 break;
1582         case IPV6_SADDR_RULE_PREFIX:
1583                 /* Rule 8: Use longest matching prefix */
1584                 ret = ipv6_addr_diff(&score->ifa->addr, dst->addr);
1585                 if (ret > score->ifa->prefix_len)
1586                         ret = score->ifa->prefix_len;
1587                 score->matchlen = ret;
1588                 break;
1589 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
1590         case IPV6_SADDR_RULE_NOT_OPTIMISTIC:
1591                 /* Optimistic addresses still have lower precedence than other
1592                  * preferred addresses.
1593                  */
1594                 ret = !(score->ifa->flags & IFA_F_OPTIMISTIC);
1595                 break;
1596 #endif
1597         default:
1598                 ret = 0;
1599         }
1600
1601         if (ret)
1602                 __set_bit(i, score->scorebits);
1603         score->rule = i;
1604 out:
1605         return ret;
1606 }
1607
1608 static int __ipv6_dev_get_saddr(struct net *net,
1609                                 struct ipv6_saddr_dst *dst,
1610                                 struct inet6_dev *idev,
1611                                 struct ipv6_saddr_score *scores,
1612                                 int hiscore_idx)
1613 {
1614         struct ipv6_saddr_score *score = &scores[1 - hiscore_idx], *hiscore = &scores[hiscore_idx];
1615
1616         list_for_each_entry_rcu(score->ifa, &idev->addr_list, if_list) {
1617                 int i;
1618
1619                 /*
1620                  * - Tentative Address (RFC2462 section 5.4)
1621                  *  - A tentative address is not considered
1622                  *    "assigned to an interface" in the traditional
1623                  *    sense, unless it is also flagged as optimistic.
1624                  * - Candidate Source Address (section 4)
1625                  *  - In any case, anycast addresses, multicast
1626                  *    addresses, and the unspecified address MUST
1627                  *    NOT be included in a candidate set.
1628                  */
1629                 if ((score->ifa->flags & IFA_F_TENTATIVE) &&
1630                     (!(score->ifa->flags & IFA_F_OPTIMISTIC)))
1631                         continue;
1632
1633                 score->addr_type = __ipv6_addr_type(&score->ifa->addr);
1634
1635                 if (unlikely(score->addr_type == IPV6_ADDR_ANY ||
1636                              score->addr_type & IPV6_ADDR_MULTICAST)) {
1637                         net_dbg_ratelimited("ADDRCONF: unspecified / multicast address assigned as unicast address on %s",
1638                                             idev->dev->name);
1639                         continue;
1640                 }
1641
1642                 score->rule = -1;
1643                 bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX);
1644
1645                 for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) {
1646                         int minihiscore, miniscore;
1647
1648                         minihiscore = ipv6_get_saddr_eval(net, hiscore, dst, i);
1649                         miniscore = ipv6_get_saddr_eval(net, score, dst, i);
1650
1651                         if (minihiscore > miniscore) {
1652                                 if (i == IPV6_SADDR_RULE_SCOPE &&
1653                                     score->scopedist > 0) {
1654                                         /*
1655                                          * special case:
1656                                          * each remaining entry
1657                                          * has too small (not enough)
1658                                          * scope, because ifa entries
1659                                          * are sorted by their scope
1660                                          * values.
1661                                          */
1662                                         goto out;
1663                                 }
1664                                 break;
1665                         } else if (minihiscore < miniscore) {
1666                                 swap(hiscore, score);
1667                                 hiscore_idx = 1 - hiscore_idx;
1668
1669                                 /* restore our iterator */
1670                                 score->ifa = hiscore->ifa;
1671
1672                                 break;
1673                         }
1674                 }
1675         }
1676 out:
1677         return hiscore_idx;
1678 }
1679
1680 static int ipv6_get_saddr_master(struct net *net,
1681                                  const struct net_device *dst_dev,
1682                                  const struct net_device *master,
1683                                  struct ipv6_saddr_dst *dst,
1684                                  struct ipv6_saddr_score *scores,
1685                                  int hiscore_idx)
1686 {
1687         struct inet6_dev *idev;
1688
1689         idev = __in6_dev_get(dst_dev);
1690         if (idev)
1691                 hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1692                                                    scores, hiscore_idx);
1693
1694         idev = __in6_dev_get(master);
1695         if (idev)
1696                 hiscore_idx = __ipv6_dev_get_saddr(net, dst, idev,
1697                                                    scores, hiscore_idx);
1698
1699         return hiscore_idx;
1700 }
1701
1702 int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev,
1703                        const struct in6_addr *daddr, unsigned int prefs,
1704                        struct in6_addr *saddr)
1705 {
1706         struct ipv6_saddr_score scores[2], *hiscore;
1707         struct ipv6_saddr_dst dst;
1708         struct inet6_dev *idev;
1709         struct net_device *dev;
1710         int dst_type;
1711         bool use_oif_addr = false;
1712         int hiscore_idx = 0;
1713         int ret = 0;
1714
1715         dst_type = __ipv6_addr_type(daddr);
1716         dst.addr = daddr;
1717         dst.ifindex = dst_dev ? dst_dev->ifindex : 0;
1718         dst.scope = __ipv6_addr_src_scope(dst_type);
1719         dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex);
1720         dst.prefs = prefs;
1721
1722         scores[hiscore_idx].rule = -1;
1723         scores[hiscore_idx].ifa = NULL;
1724
1725         rcu_read_lock();
1726
1727         /* Candidate Source Address (section 4)
1728          *  - multicast and link-local destination address,
1729          *    the set of candidate source address MUST only
1730          *    include addresses assigned to interfaces
1731          *    belonging to the same link as the outgoing
1732          *    interface.
1733          * (- For site-local destination addresses, the
1734          *    set of candidate source addresses MUST only
1735          *    include addresses assigned to interfaces
1736          *    belonging to the same site as the outgoing
1737          *    interface.)
1738          *  - "It is RECOMMENDED that the candidate source addresses
1739          *    be the set of unicast addresses assigned to the
1740          *    interface that will be used to send to the destination
1741          *    (the 'outgoing' interface)." (RFC 6724)
1742          */
1743         if (dst_dev) {
1744                 idev = __in6_dev_get(dst_dev);
1745                 if ((dst_type & IPV6_ADDR_MULTICAST) ||
1746                     dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL ||
1747                     (idev && idev->cnf.use_oif_addrs_only)) {
1748                         use_oif_addr = true;
1749                 }
1750         }
1751
1752         if (use_oif_addr) {
1753                 if (idev)
1754                         hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1755         } else {
1756                 const struct net_device *master;
1757                 int master_idx = 0;
1758
1759                 /* if dst_dev exists and is enslaved to an L3 device, then
1760                  * prefer addresses from dst_dev and then the master over
1761                  * any other enslaved devices in the L3 domain.
1762                  */
1763                 master = l3mdev_master_dev_rcu(dst_dev);
1764                 if (master) {
1765                         master_idx = master->ifindex;
1766
1767                         hiscore_idx = ipv6_get_saddr_master(net, dst_dev,
1768                                                             master, &dst,
1769                                                             scores, hiscore_idx);
1770
1771                         if (scores[hiscore_idx].ifa)
1772                                 goto out;
1773                 }
1774
1775                 for_each_netdev_rcu(net, dev) {
1776                         /* only consider addresses on devices in the
1777                          * same L3 domain
1778                          */
1779                         if (l3mdev_master_ifindex_rcu(dev) != master_idx)
1780                                 continue;
1781                         idev = __in6_dev_get(dev);
1782                         if (!idev)
1783                                 continue;
1784                         hiscore_idx = __ipv6_dev_get_saddr(net, &dst, idev, scores, hiscore_idx);
1785                 }
1786         }
1787
1788 out:
1789         hiscore = &scores[hiscore_idx];
1790         if (!hiscore->ifa)
1791                 ret = -EADDRNOTAVAIL;
1792         else
1793                 *saddr = hiscore->ifa->addr;
1794
1795         rcu_read_unlock();
1796         return ret;
1797 }
1798 EXPORT_SYMBOL(ipv6_dev_get_saddr);
1799
1800 int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr,
1801                       u32 banned_flags)
1802 {
1803         struct inet6_ifaddr *ifp;
1804         int err = -EADDRNOTAVAIL;
1805
1806         list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
1807                 if (ifp->scope > IFA_LINK)
1808                         break;
1809                 if (ifp->scope == IFA_LINK &&
1810                     !(ifp->flags & banned_flags)) {
1811                         *addr = ifp->addr;
1812                         err = 0;
1813                         break;
1814                 }
1815         }
1816         return err;
1817 }
1818
1819 int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr,
1820                     u32 banned_flags)
1821 {
1822         struct inet6_dev *idev;
1823         int err = -EADDRNOTAVAIL;
1824
1825         rcu_read_lock();
1826         idev = __in6_dev_get(dev);
1827         if (idev) {
1828                 read_lock_bh(&idev->lock);
1829                 err = __ipv6_get_lladdr(idev, addr, banned_flags);
1830                 read_unlock_bh(&idev->lock);
1831         }
1832         rcu_read_unlock();
1833         return err;
1834 }
1835
1836 static int ipv6_count_addresses(const struct inet6_dev *idev)
1837 {
1838         const struct inet6_ifaddr *ifp;
1839         int cnt = 0;
1840
1841         rcu_read_lock();
1842         list_for_each_entry_rcu(ifp, &idev->addr_list, if_list)
1843                 cnt++;
1844         rcu_read_unlock();
1845         return cnt;
1846 }
1847
1848 int ipv6_chk_addr(struct net *net, const struct in6_addr *addr,
1849                   const struct net_device *dev, int strict)
1850 {
1851         return ipv6_chk_addr_and_flags(net, addr, dev, !dev,
1852                                        strict, IFA_F_TENTATIVE);
1853 }
1854 EXPORT_SYMBOL(ipv6_chk_addr);
1855
1856 /* device argument is used to find the L3 domain of interest. If
1857  * skip_dev_check is set, then the ifp device is not checked against
1858  * the passed in dev argument. So the 2 cases for addresses checks are:
1859  *   1. does the address exist in the L3 domain that dev is part of
1860  *      (skip_dev_check = true), or
1861  *
1862  *   2. does the address exist on the specific device
1863  *      (skip_dev_check = false)
1864  */
1865 int ipv6_chk_addr_and_flags(struct net *net, const struct in6_addr *addr,
1866                             const struct net_device *dev, bool skip_dev_check,
1867                             int strict, u32 banned_flags)
1868 {
1869         unsigned int hash = inet6_addr_hash(net, addr);
1870         const struct net_device *l3mdev;
1871         struct inet6_ifaddr *ifp;
1872         u32 ifp_flags;
1873
1874         rcu_read_lock();
1875
1876         l3mdev = l3mdev_master_dev_rcu(dev);
1877         if (skip_dev_check)
1878                 dev = NULL;
1879
1880         hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) {
1881                 if (!net_eq(dev_net(ifp->idev->dev), net))
1882                         continue;
1883
1884                 if (l3mdev_master_dev_rcu(ifp->idev->dev) != l3mdev)
1885                         continue;
1886
1887                 /* Decouple optimistic from tentative for evaluation here.
1888                  * Ban optimistic addresses explicitly, when required.
1889                  */
1890                 ifp_flags = (ifp->flags&IFA_F_OPTIMISTIC)
1891                             ? (ifp->flags&~IFA_F_TENTATIVE)
1892                             : ifp->flags;
1893                 if (ipv6_addr_equal(&ifp->addr, addr) &&
1894                     !(ifp_flags&banned_flags) &&
1895                     (!dev || ifp->idev->dev == dev ||
1896                      !(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) {
1897                         rcu_read_unlock();
1898                         return 1;
1899                 }
1900         }
1901
1902         rcu_read_unlock();
1903         return 0;
1904 }
1905 EXPORT_SYMBOL(ipv6_chk_addr_and_flags);
1906
1907
1908 /* Compares an address/prefix_len with addresses on device @dev.
1909  * If one is found it returns true.
1910  */
1911 bool ipv6_chk_custom_prefix(const struct in6_addr *addr,
1912         const unsigned int prefix_len, struct net_device *dev)
1913 {
1914         const struct inet6_ifaddr *ifa;
1915         const struct inet6_dev *idev;
1916         bool ret = false;
1917
1918         rcu_read_lock();
1919         idev = __in6_dev_get(dev);
1920         if (idev) {
1921                 list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
1922                         ret = ipv6_prefix_equal(addr, &ifa->addr, prefix_len);
1923                         if (ret)
1924                                 break;
1925                 }
1926         }
1927         rcu_read_unlock();
1928
1929         return ret;
1930 }
1931 EXPORT_SYMBOL(ipv6_chk_custom_prefix);
1932
1933 int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev)
1934 {
1935         const struct inet6_ifaddr *ifa;
1936         const struct inet6_dev *idev;
1937         int     onlink;
1938
1939         onlink = 0;
1940         rcu_read_lock();
1941         idev = __in6_dev_get(dev);
1942         if (idev) {
1943                 list_for_each_entry_rcu(ifa, &idev->addr_list, if_list) {
1944                         onlink = ipv6_prefix_equal(addr, &ifa->addr,
1945                                                    ifa->prefix_len);
1946                         if (onlink)
1947                                 break;
1948                 }
1949         }
1950         rcu_read_unlock();
1951         return onlink;
1952 }
1953 EXPORT_SYMBOL(ipv6_chk_prefix);
1954
1955 struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr,
1956                                      struct net_device *dev, int strict)
1957 {
1958         unsigned int hash = inet6_addr_hash(net, addr);
1959         struct inet6_ifaddr *ifp, *result = NULL;
1960
1961         rcu_read_lock();
1962         hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) {
1963                 if (!net_eq(dev_net(ifp->idev->dev), net))
1964                         continue;
1965                 if (ipv6_addr_equal(&ifp->addr, addr)) {
1966                         if (!dev || ifp->idev->dev == dev ||
1967                             !(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) {
1968                                 if (in6_ifa_hold_safe(ifp)) {
1969                                         result = ifp;
1970                                         break;
1971                                 }
1972                         }
1973                 }
1974         }
1975         rcu_read_unlock();
1976
1977         return result;
1978 }
1979
1980 /* Gets referenced address, destroys ifaddr */
1981
1982 static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed)
1983 {
1984         if (dad_failed)
1985                 ifp->flags |= IFA_F_DADFAILED;
1986
1987         if (ifp->flags&IFA_F_TEMPORARY) {
1988                 struct inet6_ifaddr *ifpub;
1989                 spin_lock_bh(&ifp->lock);
1990                 ifpub = ifp->ifpub;
1991                 if (ifpub) {
1992                         in6_ifa_hold(ifpub);
1993                         spin_unlock_bh(&ifp->lock);
1994                         ipv6_create_tempaddr(ifpub, ifp, true);
1995                         in6_ifa_put(ifpub);
1996                 } else {
1997                         spin_unlock_bh(&ifp->lock);
1998                 }
1999                 ipv6_del_addr(ifp);
2000         } else if (ifp->flags&IFA_F_PERMANENT || !dad_failed) {
2001                 spin_lock_bh(&ifp->lock);
2002                 addrconf_del_dad_work(ifp);
2003                 ifp->flags |= IFA_F_TENTATIVE;
2004                 if (dad_failed)
2005                         ifp->flags &= ~IFA_F_OPTIMISTIC;
2006                 spin_unlock_bh(&ifp->lock);
2007                 if (dad_failed)
2008                         ipv6_ifa_notify(0, ifp);
2009                 in6_ifa_put(ifp);
2010         } else {
2011                 ipv6_del_addr(ifp);
2012         }
2013 }
2014
2015 static int addrconf_dad_end(struct inet6_ifaddr *ifp)
2016 {
2017         int err = -ENOENT;
2018
2019         spin_lock_bh(&ifp->lock);
2020         if (ifp->state == INET6_IFADDR_STATE_DAD) {
2021                 ifp->state = INET6_IFADDR_STATE_POSTDAD;
2022                 err = 0;
2023         }
2024         spin_unlock_bh(&ifp->lock);
2025
2026         return err;
2027 }
2028
2029 void addrconf_dad_failure(struct sk_buff *skb, struct inet6_ifaddr *ifp)
2030 {
2031         struct inet6_dev *idev = ifp->idev;
2032         struct net *net = dev_net(ifp->idev->dev);
2033
2034         if (addrconf_dad_end(ifp)) {
2035                 in6_ifa_put(ifp);
2036                 return;
2037         }
2038
2039         net_info_ratelimited("%s: IPv6 duplicate address %pI6c used by %pM detected!\n",
2040                              ifp->idev->dev->name, &ifp->addr, eth_hdr(skb)->h_source);
2041
2042         spin_lock_bh(&ifp->lock);
2043
2044         if (ifp->flags & IFA_F_STABLE_PRIVACY) {
2045                 struct in6_addr new_addr;
2046                 struct inet6_ifaddr *ifp2;
2047                 int retries = ifp->stable_privacy_retry + 1;
2048                 struct ifa6_config cfg = {
2049                         .pfx = &new_addr,
2050                         .plen = ifp->prefix_len,
2051                         .ifa_flags = ifp->flags,
2052                         .valid_lft = ifp->valid_lft,
2053                         .preferred_lft = ifp->prefered_lft,
2054                         .scope = ifp->scope,
2055                 };
2056
2057                 if (retries > net->ipv6.sysctl.idgen_retries) {
2058                         net_info_ratelimited("%s: privacy stable address generation failed because of DAD conflicts!\n",
2059                                              ifp->idev->dev->name);
2060                         goto errdad;
2061                 }
2062
2063                 new_addr = ifp->addr;
2064                 if (ipv6_generate_stable_address(&new_addr, retries,
2065                                                  idev))
2066                         goto errdad;
2067
2068                 spin_unlock_bh(&ifp->lock);
2069
2070                 if (idev->cnf.max_addresses &&
2071                     ipv6_count_addresses(idev) >=
2072                     idev->cnf.max_addresses)
2073                         goto lock_errdad;
2074
2075                 net_info_ratelimited("%s: generating new stable privacy address because of DAD conflict\n",
2076                                      ifp->idev->dev->name);
2077
2078                 ifp2 = ipv6_add_addr(idev, &cfg, false, NULL);
2079                 if (IS_ERR(ifp2))
2080                         goto lock_errdad;
2081
2082                 spin_lock_bh(&ifp2->lock);
2083                 ifp2->stable_privacy_retry = retries;
2084                 ifp2->state = INET6_IFADDR_STATE_PREDAD;
2085                 spin_unlock_bh(&ifp2->lock);
2086
2087                 addrconf_mod_dad_work(ifp2, net->ipv6.sysctl.idgen_delay);
2088                 in6_ifa_put(ifp2);
2089 lock_errdad:
2090                 spin_lock_bh(&ifp->lock);
2091         }
2092
2093 errdad:
2094         /* transition from _POSTDAD to _ERRDAD */
2095         ifp->state = INET6_IFADDR_STATE_ERRDAD;
2096         spin_unlock_bh(&ifp->lock);
2097
2098         addrconf_mod_dad_work(ifp, 0);
2099         in6_ifa_put(ifp);
2100 }
2101
2102 /* Join to solicited addr multicast group.
2103  * caller must hold RTNL */
2104 void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr)
2105 {
2106         struct in6_addr maddr;
2107
2108         if (dev->flags&(IFF_LOOPBACK|IFF_NOARP))
2109                 return;
2110
2111         addrconf_addr_solict_mult(addr, &maddr);
2112         ipv6_dev_mc_inc(dev, &maddr);
2113 }
2114
2115 /* caller must hold RTNL */
2116 void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr)
2117 {
2118         struct in6_addr maddr;
2119
2120         if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP))
2121                 return;
2122
2123         addrconf_addr_solict_mult(addr, &maddr);
2124         __ipv6_dev_mc_dec(idev, &maddr);
2125 }
2126
2127 /* caller must hold RTNL */
2128 static void addrconf_join_anycast(struct inet6_ifaddr *ifp)
2129 {
2130         struct in6_addr addr;
2131
2132         if (ifp->prefix_len >= 127) /* RFC 6164 */
2133                 return;
2134         ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2135         if (ipv6_addr_any(&addr))
2136                 return;
2137         __ipv6_dev_ac_inc(ifp->idev, &addr);
2138 }
2139
2140 /* caller must hold RTNL */
2141 static void addrconf_leave_anycast(struct inet6_ifaddr *ifp)
2142 {
2143         struct in6_addr addr;
2144
2145         if (ifp->prefix_len >= 127) /* RFC 6164 */
2146                 return;
2147         ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len);
2148         if (ipv6_addr_any(&addr))
2149                 return;
2150         __ipv6_dev_ac_dec(ifp->idev, &addr);
2151 }
2152
2153 static int addrconf_ifid_6lowpan(u8 *eui, struct net_device *dev)
2154 {
2155         switch (dev->addr_len) {
2156         case ETH_ALEN:
2157                 memcpy(eui, dev->dev_addr, 3);
2158                 eui[3] = 0xFF;
2159                 eui[4] = 0xFE;
2160                 memcpy(eui + 5, dev->dev_addr + 3, 3);
2161                 break;
2162         case EUI64_ADDR_LEN:
2163                 memcpy(eui, dev->dev_addr, EUI64_ADDR_LEN);
2164                 eui[0] ^= 2;
2165                 break;
2166         default:
2167                 return -1;
2168         }
2169
2170         return 0;
2171 }
2172
2173 static int addrconf_ifid_ieee1394(u8 *eui, struct net_device *dev)
2174 {
2175         union fwnet_hwaddr *ha;
2176
2177         if (dev->addr_len != FWNET_ALEN)
2178                 return -1;
2179
2180         ha = (union fwnet_hwaddr *)dev->dev_addr;
2181
2182         memcpy(eui, &ha->uc.uniq_id, sizeof(ha->uc.uniq_id));
2183         eui[0] ^= 2;
2184         return 0;
2185 }
2186
2187 static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev)
2188 {
2189         /* XXX: inherit EUI-64 from other interface -- yoshfuji */
2190         if (dev->addr_len != ARCNET_ALEN)
2191                 return -1;
2192         memset(eui, 0, 7);
2193         eui[7] = *(u8 *)dev->dev_addr;
2194         return 0;
2195 }
2196
2197 static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev)
2198 {
2199         if (dev->addr_len != INFINIBAND_ALEN)
2200                 return -1;
2201         memcpy(eui, dev->dev_addr + 12, 8);
2202         eui[0] |= 2;
2203         return 0;
2204 }
2205
2206 static int __ipv6_isatap_ifid(u8 *eui, __be32 addr)
2207 {
2208         if (addr == 0)
2209                 return -1;
2210         eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) ||
2211                   ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) ||
2212                   ipv4_is_private_172(addr) || ipv4_is_test_192(addr) ||
2213                   ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) ||
2214                   ipv4_is_test_198(addr) || ipv4_is_multicast(addr) ||
2215                   ipv4_is_lbcast(addr)) ? 0x00 : 0x02;
2216         eui[1] = 0;
2217         eui[2] = 0x5E;
2218         eui[3] = 0xFE;
2219         memcpy(eui + 4, &addr, 4);
2220         return 0;
2221 }
2222
2223 static int addrconf_ifid_sit(u8 *eui, struct net_device *dev)
2224 {
2225         if (dev->priv_flags & IFF_ISATAP)
2226                 return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2227         return -1;
2228 }
2229
2230 static int addrconf_ifid_gre(u8 *eui, struct net_device *dev)
2231 {
2232         return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr);
2233 }
2234
2235 static int addrconf_ifid_ip6tnl(u8 *eui, struct net_device *dev)
2236 {
2237         memcpy(eui, dev->perm_addr, 3);
2238         memcpy(eui + 5, dev->perm_addr + 3, 3);
2239         eui[3] = 0xFF;
2240         eui[4] = 0xFE;
2241         eui[0] ^= 2;
2242         return 0;
2243 }
2244
2245 static int ipv6_generate_eui64(u8 *eui, struct net_device *dev)
2246 {
2247         switch (dev->type) {
2248         case ARPHRD_ETHER:
2249         case ARPHRD_FDDI:
2250                 return addrconf_ifid_eui48(eui, dev);
2251         case ARPHRD_ARCNET:
2252                 return addrconf_ifid_arcnet(eui, dev);
2253         case ARPHRD_INFINIBAND:
2254                 return addrconf_ifid_infiniband(eui, dev);
2255         case ARPHRD_SIT:
2256                 return addrconf_ifid_sit(eui, dev);
2257         case ARPHRD_IPGRE:
2258         case ARPHRD_TUNNEL:
2259                 return addrconf_ifid_gre(eui, dev);
2260         case ARPHRD_6LOWPAN:
2261                 return addrconf_ifid_6lowpan(eui, dev);
2262         case ARPHRD_IEEE1394:
2263                 return addrconf_ifid_ieee1394(eui, dev);
2264         case ARPHRD_TUNNEL6:
2265         case ARPHRD_IP6GRE:
2266         case ARPHRD_RAWIP:
2267                 return addrconf_ifid_ip6tnl(eui, dev);
2268         }
2269         return -1;
2270 }
2271
2272 static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev)
2273 {
2274         int err = -1;
2275         struct inet6_ifaddr *ifp;
2276
2277         read_lock_bh(&idev->lock);
2278         list_for_each_entry_reverse(ifp, &idev->addr_list, if_list) {
2279                 if (ifp->scope > IFA_LINK)
2280                         break;
2281                 if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) {
2282                         memcpy(eui, ifp->addr.s6_addr+8, 8);
2283                         err = 0;
2284                         break;
2285                 }
2286         }
2287         read_unlock_bh(&idev->lock);
2288         return err;
2289 }
2290
2291 /* (re)generation of randomized interface identifier (RFC 3041 3.2, 3.5) */
2292 static void ipv6_regen_rndid(struct inet6_dev *idev)
2293 {
2294 regen:
2295         get_random_bytes(idev->rndid, sizeof(idev->rndid));
2296         idev->rndid[0] &= ~0x02;
2297
2298         /*
2299          * <draft-ietf-ipngwg-temp-addresses-v2-00.txt>:
2300          * check if generated address is not inappropriate
2301          *
2302          *  - Reserved subnet anycast (RFC 2526)
2303          *      11111101 11....11 1xxxxxxx
2304          *  - ISATAP (RFC4214) 6.1
2305          *      00-00-5E-FE-xx-xx-xx-xx
2306          *  - value 0
2307          *  - XXX: already assigned to an address on the device
2308          */
2309         if (idev->rndid[0] == 0xfd &&
2310             (idev->rndid[1]&idev->rndid[2]&idev->rndid[3]&idev->rndid[4]&idev->rndid[5]&idev->rndid[6]) == 0xff &&
2311             (idev->rndid[7]&0x80))
2312                 goto regen;
2313         if ((idev->rndid[0]|idev->rndid[1]) == 0) {
2314                 if (idev->rndid[2] == 0x5e && idev->rndid[3] == 0xfe)
2315                         goto regen;
2316                 if ((idev->rndid[2]|idev->rndid[3]|idev->rndid[4]|idev->rndid[5]|idev->rndid[6]|idev->rndid[7]) == 0x00)
2317                         goto regen;
2318         }
2319 }
2320
2321 static void  ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr)
2322 {
2323         if (tmpaddr && memcmp(idev->rndid, &tmpaddr->s6_addr[8], 8) == 0)
2324                 ipv6_regen_rndid(idev);
2325 }
2326
2327 /*
2328  *      Add prefix route.
2329  */
2330
2331 static void
2332 addrconf_prefix_route(struct in6_addr *pfx, int plen, u32 metric,
2333                       struct net_device *dev, unsigned long expires,
2334                       u32 flags, gfp_t gfp_flags)
2335 {
2336         struct fib6_config cfg = {
2337                 .fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX,
2338                 .fc_metric = metric ? : IP6_RT_PRIO_ADDRCONF,
2339                 .fc_ifindex = dev->ifindex,
2340                 .fc_expires = expires,
2341                 .fc_dst_len = plen,
2342                 .fc_flags = RTF_UP | flags,
2343                 .fc_nlinfo.nl_net = dev_net(dev),
2344                 .fc_protocol = RTPROT_KERNEL,
2345                 .fc_type = RTN_UNICAST,
2346         };
2347
2348         cfg.fc_dst = *pfx;
2349
2350         /* Prevent useless cloning on PtP SIT.
2351            This thing is done here expecting that the whole
2352            class of non-broadcast devices need not cloning.
2353          */
2354 #if IS_ENABLED(CONFIG_IPV6_SIT)
2355         if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT))
2356                 cfg.fc_flags |= RTF_NONEXTHOP;
2357 #endif
2358
2359         ip6_route_add(&cfg, gfp_flags, NULL);
2360 }
2361
2362
2363 static struct fib6_info *addrconf_get_prefix_route(const struct in6_addr *pfx,
2364                                                   int plen,
2365                                                   const struct net_device *dev,
2366                                                   u32 flags, u32 noflags)
2367 {
2368         struct fib6_node *fn;
2369         struct fib6_info *rt = NULL;
2370         struct fib6_table *table;
2371         u32 tb_id = l3mdev_fib_table(dev) ? : RT6_TABLE_PREFIX;
2372
2373         table = fib6_get_table(dev_net(dev), tb_id);
2374         if (!table)
2375                 return NULL;
2376
2377         rcu_read_lock();
2378         fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0, true);
2379         if (!fn)
2380                 goto out;
2381
2382         for_each_fib6_node_rt_rcu(fn) {
2383                 if (rt->fib6_nh.nh_dev->ifindex != dev->ifindex)
2384                         continue;
2385                 if ((rt->fib6_flags & flags) != flags)
2386                         continue;
2387                 if ((rt->fib6_flags & noflags) != 0)
2388                         continue;
2389                 if (!fib6_info_hold_safe(rt))
2390                         continue;
2391                 break;
2392         }
2393 out:
2394         rcu_read_unlock();
2395         return rt;
2396 }
2397
2398
2399 /* Create "default" multicast route to the interface */
2400
2401 static void addrconf_add_mroute(struct net_device *dev)
2402 {
2403         struct fib6_config cfg = {
2404                 .fc_table = l3mdev_fib_table(dev) ? : RT6_TABLE_LOCAL,
2405                 .fc_metric = IP6_RT_PRIO_ADDRCONF,
2406                 .fc_ifindex = dev->ifindex,
2407                 .fc_dst_len = 8,
2408                 .fc_flags = RTF_UP,
2409                 .fc_type = RTN_MULTICAST,
2410                 .fc_nlinfo.nl_net = dev_net(dev),
2411                 .fc_protocol = RTPROT_KERNEL,
2412         };
2413
2414         ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0);
2415
2416         ip6_route_add(&cfg, GFP_KERNEL, NULL);
2417 }
2418
2419 static struct inet6_dev *addrconf_add_dev(struct net_device *dev)
2420 {
2421         struct inet6_dev *idev;
2422
2423         ASSERT_RTNL();
2424
2425         idev = ipv6_find_idev(dev);
2426         if (!idev)
2427                 return ERR_PTR(-ENOBUFS);
2428
2429         if (idev->cnf.disable_ipv6)
2430                 return ERR_PTR(-EACCES);
2431
2432         /* Add default multicast route */
2433         if (!(dev->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev))
2434                 addrconf_add_mroute(dev);
2435
2436         return idev;
2437 }
2438
2439 static void manage_tempaddrs(struct inet6_dev *idev,
2440                              struct inet6_ifaddr *ifp,
2441                              __u32 valid_lft, __u32 prefered_lft,
2442                              bool create, unsigned long now)
2443 {
2444         u32 flags;
2445         struct inet6_ifaddr *ift;
2446
2447         read_lock_bh(&idev->lock);
2448         /* update all temporary addresses in the list */
2449         list_for_each_entry(ift, &idev->tempaddr_list, tmp_list) {
2450                 int age, max_valid, max_prefered;
2451
2452                 if (ifp != ift->ifpub)
2453                         continue;
2454
2455                 /* RFC 4941 section 3.3:
2456                  * If a received option will extend the lifetime of a public
2457                  * address, the lifetimes of temporary addresses should
2458                  * be extended, subject to the overall constraint that no
2459                  * temporary addresses should ever remain "valid" or "preferred"
2460                  * for a time longer than (TEMP_VALID_LIFETIME) or
2461                  * (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), respectively.
2462                  */
2463                 age = (now - ift->cstamp) / HZ;
2464                 max_valid = idev->cnf.temp_valid_lft - age;
2465                 if (max_valid < 0)
2466                         max_valid = 0;
2467
2468                 max_prefered = idev->cnf.temp_prefered_lft -
2469                                idev->desync_factor - age;
2470                 if (max_prefered < 0)
2471                         max_prefered = 0;
2472
2473                 if (valid_lft > max_valid)
2474                         valid_lft = max_valid;
2475
2476                 if (prefered_lft > max_prefered)
2477                         prefered_lft = max_prefered;
2478
2479                 spin_lock(&ift->lock);
2480                 flags = ift->flags;
2481                 ift->valid_lft = valid_lft;
2482                 ift->prefered_lft = prefered_lft;
2483                 ift->tstamp = now;
2484                 if (prefered_lft > 0)
2485                         ift->flags &= ~IFA_F_DEPRECATED;
2486
2487                 spin_unlock(&ift->lock);
2488                 if (!(flags&IFA_F_TENTATIVE))
2489                         ipv6_ifa_notify(0, ift);
2490         }
2491
2492         /* Also create a temporary address if it's enabled but no temporary
2493          * address currently exists.
2494          * However, we get called with valid_lft == 0, prefered_lft == 0, create == false
2495          * as part of cleanup (ie. deleting the mngtmpaddr).
2496          * We don't want that to result in creating a new temporary ip address.
2497          */
2498         if (list_empty(&idev->tempaddr_list) && (valid_lft || prefered_lft))
2499                 create = true;
2500
2501         if (create && idev->cnf.use_tempaddr > 0) {
2502                 /* When a new public address is created as described
2503                  * in [ADDRCONF], also create a new temporary address.
2504                  */
2505                 read_unlock_bh(&idev->lock);
2506                 ipv6_create_tempaddr(ifp, NULL, false);
2507         } else {
2508                 read_unlock_bh(&idev->lock);
2509         }
2510 }
2511
2512 static bool is_addr_mode_generate_stable(struct inet6_dev *idev)
2513 {
2514         return idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY ||
2515                idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_RANDOM;
2516 }
2517
2518 int addrconf_prefix_rcv_add_addr(struct net *net, struct net_device *dev,
2519                                  const struct prefix_info *pinfo,
2520                                  struct inet6_dev *in6_dev,
2521                                  const struct in6_addr *addr, int addr_type,
2522                                  u32 addr_flags, bool sllao, bool tokenized,
2523                                  __u32 valid_lft, u32 prefered_lft)
2524 {
2525         struct inet6_ifaddr *ifp = ipv6_get_ifaddr(net, addr, dev, 1);
2526         int create = 0, update_lft = 0;
2527
2528         if (!ifp && valid_lft) {
2529                 int max_addresses = in6_dev->cnf.max_addresses;
2530                 struct ifa6_config cfg = {
2531                         .pfx = addr,
2532                         .plen = pinfo->prefix_len,
2533                         .ifa_flags = addr_flags,
2534                         .valid_lft = valid_lft,
2535                         .preferred_lft = prefered_lft,
2536                         .scope = addr_type & IPV6_ADDR_SCOPE_MASK,
2537                 };
2538
2539 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
2540                 if ((net->ipv6.devconf_all->optimistic_dad ||
2541                      in6_dev->cnf.optimistic_dad) &&
2542                     !net->ipv6.devconf_all->forwarding && sllao)
2543                         cfg.ifa_flags |= IFA_F_OPTIMISTIC;
2544 #endif
2545
2546                 /* Do not allow to create too much of autoconfigured
2547                  * addresses; this would be too easy way to crash kernel.
2548                  */
2549                 if (!max_addresses ||
2550                     ipv6_count_addresses(in6_dev) < max_addresses)
2551                         ifp = ipv6_add_addr(in6_dev, &cfg, false, NULL);
2552
2553                 if (IS_ERR_OR_NULL(ifp))
2554                         return -1;
2555
2556                 create = 1;
2557                 spin_lock_bh(&ifp->lock);
2558                 ifp->flags |= IFA_F_MANAGETEMPADDR;
2559                 ifp->cstamp = jiffies;
2560                 ifp->tokenized = tokenized;
2561                 spin_unlock_bh(&ifp->lock);
2562                 addrconf_dad_start(ifp);
2563         }
2564
2565         if (ifp) {
2566                 u32 flags;
2567                 unsigned long now;
2568                 u32 stored_lft;
2569
2570                 /* update lifetime (RFC2462 5.5.3 e) */
2571                 spin_lock_bh(&ifp->lock);
2572                 now = jiffies;
2573                 if (ifp->valid_lft > (now - ifp->tstamp) / HZ)
2574                         stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ;
2575                 else
2576                         stored_lft = 0;
2577                 if (!create && stored_lft) {
2578                         const u32 minimum_lft = min_t(u32,
2579                                 stored_lft, MIN_VALID_LIFETIME);
2580                         valid_lft = max(valid_lft, minimum_lft);
2581
2582                         /* RFC4862 Section 5.5.3e:
2583                          * "Note that the preferred lifetime of the
2584                          *  corresponding address is always reset to
2585                          *  the Preferred Lifetime in the received
2586                          *  Prefix Information option, regardless of
2587                          *  whether the valid lifetime is also reset or
2588                          *  ignored."
2589                          *
2590                          * So we should always update prefered_lft here.
2591                          */
2592                         update_lft = 1;
2593                 }
2594
2595                 if (update_lft) {
2596                         ifp->valid_lft = valid_lft;
2597                         ifp->prefered_lft = prefered_lft;
2598                         ifp->tstamp = now;
2599                         flags = ifp->flags;
2600                         ifp->flags &= ~IFA_F_DEPRECATED;
2601                         spin_unlock_bh(&ifp->lock);
2602
2603                         if (!(flags&IFA_F_TENTATIVE))
2604                                 ipv6_ifa_notify(0, ifp);
2605                 } else
2606                         spin_unlock_bh(&ifp->lock);
2607
2608                 manage_tempaddrs(in6_dev, ifp, valid_lft, prefered_lft,
2609                                  create, now);
2610
2611                 in6_ifa_put(ifp);
2612                 addrconf_verify();
2613         }
2614
2615         return 0;
2616 }
2617 EXPORT_SYMBOL_GPL(addrconf_prefix_rcv_add_addr);
2618
2619 void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao)
2620 {
2621         struct prefix_info *pinfo;
2622         __u32 valid_lft;
2623         __u32 prefered_lft;
2624         int addr_type, err;
2625         u32 addr_flags = 0;
2626         struct inet6_dev *in6_dev;
2627         struct net *net = dev_net(dev);
2628
2629         pinfo = (struct prefix_info *) opt;
2630
2631         if (len < sizeof(struct prefix_info)) {
2632                 netdev_dbg(dev, "addrconf: prefix option too short\n");
2633                 return;
2634         }
2635
2636         /*
2637          *      Validation checks ([ADDRCONF], page 19)
2638          */
2639
2640         addr_type = ipv6_addr_type(&pinfo->prefix);
2641
2642         if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL))
2643                 return;
2644
2645         valid_lft = ntohl(pinfo->valid);
2646         prefered_lft = ntohl(pinfo->prefered);
2647
2648         if (prefered_lft > valid_lft) {
2649                 net_warn_ratelimited("addrconf: prefix option has invalid lifetime\n");
2650                 return;
2651         }
2652
2653         in6_dev = in6_dev_get(dev);
2654
2655         if (!in6_dev) {
2656                 net_dbg_ratelimited("addrconf: device %s not configured\n",
2657                                     dev->name);
2658                 return;
2659         }
2660
2661         /*
2662          *      Two things going on here:
2663          *      1) Add routes for on-link prefixes
2664          *      2) Configure prefixes with the auto flag set
2665          */
2666
2667         if (pinfo->onlink) {
2668                 struct fib6_info *rt;
2669                 unsigned long rt_expires;
2670
2671                 /* Avoid arithmetic overflow. Really, we could
2672                  * save rt_expires in seconds, likely valid_lft,
2673                  * but it would require division in fib gc, that it
2674                  * not good.
2675                  */
2676                 if (HZ > USER_HZ)
2677                         rt_expires = addrconf_timeout_fixup(valid_lft, HZ);
2678                 else
2679                         rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ);
2680
2681                 if (addrconf_finite_timeout(rt_expires))
2682                         rt_expires *= HZ;
2683
2684                 rt = addrconf_get_prefix_route(&pinfo->prefix,
2685                                                pinfo->prefix_len,
2686                                                dev,
2687                                                RTF_ADDRCONF | RTF_PREFIX_RT,
2688                                                RTF_GATEWAY | RTF_DEFAULT);
2689
2690                 if (rt) {
2691                         /* Autoconf prefix route */
2692                         if (valid_lft == 0) {
2693                                 ip6_del_rt(net, rt);
2694                                 rt = NULL;
2695                         } else if (addrconf_finite_timeout(rt_expires)) {
2696                                 /* not infinity */
2697                                 fib6_set_expires(rt, jiffies + rt_expires);
2698                         } else {
2699                                 fib6_clean_expires(rt);
2700                         }
2701                 } else if (valid_lft) {
2702                         clock_t expires = 0;
2703                         int flags = RTF_ADDRCONF | RTF_PREFIX_RT;
2704                         if (addrconf_finite_timeout(rt_expires)) {
2705                                 /* not infinity */
2706                                 flags |= RTF_EXPIRES;
2707                                 expires = jiffies_to_clock_t(rt_expires);
2708                         }
2709                         addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len,
2710                                               0, dev, expires, flags,
2711                                               GFP_ATOMIC);
2712                 }
2713                 fib6_info_release(rt);
2714         }
2715
2716         /* Try to figure out our local address for this prefix */
2717
2718         if (pinfo->autoconf && in6_dev->cnf.autoconf) {
2719                 struct in6_addr addr;
2720                 bool tokenized = false, dev_addr_generated = false;
2721
2722                 if (pinfo->prefix_len == 64) {
2723                         memcpy(&addr, &pinfo->prefix, 8);
2724
2725                         if (!ipv6_addr_any(&in6_dev->token)) {
2726                                 read_lock_bh(&in6_dev->lock);
2727                                 memcpy(addr.s6_addr + 8,
2728                                        in6_dev->token.s6_addr + 8, 8);
2729                                 read_unlock_bh(&in6_dev->lock);
2730                                 tokenized = true;
2731                         } else if (is_addr_mode_generate_stable(in6_dev) &&
2732                                    !ipv6_generate_stable_address(&addr, 0,
2733                                                                  in6_dev)) {
2734                                 addr_flags |= IFA_F_STABLE_PRIVACY;
2735                                 goto ok;
2736                         } else if (ipv6_generate_eui64(addr.s6_addr + 8, dev) &&
2737                                    ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) {
2738                                 goto put;
2739                         } else {
2740                                 dev_addr_generated = true;
2741                         }
2742                         goto ok;
2743                 }
2744                 net_dbg_ratelimited("IPv6 addrconf: prefix with wrong length %d\n",
2745                                     pinfo->prefix_len);
2746                 goto put;
2747
2748 ok:
2749                 err = addrconf_prefix_rcv_add_addr(net, dev, pinfo, in6_dev,
2750                                                    &addr, addr_type,
2751                                                    addr_flags, sllao,
2752                                                    tokenized, valid_lft,
2753                                                    prefered_lft);
2754                 if (err)
2755                         goto put;
2756
2757                 /* Ignore error case here because previous prefix add addr was
2758                  * successful which will be notified.
2759                  */
2760                 ndisc_ops_prefix_rcv_add_addr(net, dev, pinfo, in6_dev, &addr,
2761                                               addr_type, addr_flags, sllao,
2762                                               tokenized, valid_lft,
2763                                               prefered_lft,
2764                                               dev_addr_generated);
2765         }
2766         inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo);
2767 put:
2768         in6_dev_put(in6_dev);
2769 }
2770
2771 /*
2772  *      Set destination address.
2773  *      Special case for SIT interfaces where we create a new "virtual"
2774  *      device.
2775  */
2776 int addrconf_set_dstaddr(struct net *net, void __user *arg)
2777 {
2778         struct in6_ifreq ireq;
2779         struct net_device *dev;
2780         int err = -EINVAL;
2781
2782         rtnl_lock();
2783
2784         err = -EFAULT;
2785         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
2786                 goto err_exit;
2787
2788         dev = __dev_get_by_index(net, ireq.ifr6_ifindex);
2789
2790         err = -ENODEV;
2791         if (!dev)
2792                 goto err_exit;
2793
2794 #if IS_ENABLED(CONFIG_IPV6_SIT)
2795         if (dev->type == ARPHRD_SIT) {
2796                 const struct net_device_ops *ops = dev->netdev_ops;
2797                 struct ifreq ifr;
2798                 struct ip_tunnel_parm p;
2799
2800                 err = -EADDRNOTAVAIL;
2801                 if (!(ipv6_addr_type(&ireq.ifr6_addr) & IPV6_ADDR_COMPATv4))
2802                         goto err_exit;
2803
2804                 memset(&p, 0, sizeof(p));
2805                 p.iph.daddr = ireq.ifr6_addr.s6_addr32[3];
2806                 p.iph.saddr = 0;
2807                 p.iph.version = 4;
2808                 p.iph.ihl = 5;
2809                 p.iph.protocol = IPPROTO_IPV6;
2810                 p.iph.ttl = 64;
2811                 ifr.ifr_ifru.ifru_data = (__force void __user *)&p;
2812
2813                 if (ops->ndo_do_ioctl) {
2814                         mm_segment_t oldfs = get_fs();
2815
2816                         set_fs(KERNEL_DS);
2817                         err = ops->ndo_do_ioctl(dev, &ifr, SIOCADDTUNNEL);
2818                         set_fs(oldfs);
2819                 } else
2820                         err = -EOPNOTSUPP;
2821
2822                 if (err == 0) {
2823                         err = -ENOBUFS;
2824                         dev = __dev_get_by_name(net, p.name);
2825                         if (!dev)
2826                                 goto err_exit;
2827                         err = dev_open(dev);
2828                 }
2829         }
2830 #endif
2831
2832 err_exit:
2833         rtnl_unlock();
2834         return err;
2835 }
2836
2837 static int ipv6_mc_config(struct sock *sk, bool join,
2838                           const struct in6_addr *addr, int ifindex)
2839 {
2840         int ret;
2841
2842         ASSERT_RTNL();
2843
2844         lock_sock(sk);
2845         if (join)
2846                 ret = ipv6_sock_mc_join(sk, ifindex, addr);
2847         else
2848                 ret = ipv6_sock_mc_drop(sk, ifindex, addr);
2849         release_sock(sk);
2850
2851         return ret;
2852 }
2853
2854 /*
2855  *      Manual configuration of address on an interface
2856  */
2857 static int inet6_addr_add(struct net *net, int ifindex,
2858                           struct ifa6_config *cfg,
2859                           struct netlink_ext_ack *extack)
2860 {
2861         struct inet6_ifaddr *ifp;
2862         struct inet6_dev *idev;
2863         struct net_device *dev;
2864         unsigned long timeout;
2865         clock_t expires;
2866         u32 flags;
2867
2868         ASSERT_RTNL();
2869
2870         if (cfg->plen > 128)
2871                 return -EINVAL;
2872
2873         /* check the lifetime */
2874         if (!cfg->valid_lft || cfg->preferred_lft > cfg->valid_lft)
2875                 return -EINVAL;
2876
2877         if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR && cfg->plen != 64)
2878                 return -EINVAL;
2879
2880         dev = __dev_get_by_index(net, ifindex);
2881         if (!dev)
2882                 return -ENODEV;
2883
2884         idev = addrconf_add_dev(dev);
2885         if (IS_ERR(idev))
2886                 return PTR_ERR(idev);
2887
2888         if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
2889                 int ret = ipv6_mc_config(net->ipv6.mc_autojoin_sk,
2890                                          true, cfg->pfx, ifindex);
2891
2892                 if (ret < 0)
2893                         return ret;
2894         }
2895
2896         cfg->scope = ipv6_addr_scope(cfg->pfx);
2897
2898         timeout = addrconf_timeout_fixup(cfg->valid_lft, HZ);
2899         if (addrconf_finite_timeout(timeout)) {
2900                 expires = jiffies_to_clock_t(timeout * HZ);
2901                 cfg->valid_lft = timeout;
2902                 flags = RTF_EXPIRES;
2903         } else {
2904                 expires = 0;
2905                 flags = 0;
2906                 cfg->ifa_flags |= IFA_F_PERMANENT;
2907         }
2908
2909         timeout = addrconf_timeout_fixup(cfg->preferred_lft, HZ);
2910         if (addrconf_finite_timeout(timeout)) {
2911                 if (timeout == 0)
2912                         cfg->ifa_flags |= IFA_F_DEPRECATED;
2913                 cfg->preferred_lft = timeout;
2914         }
2915
2916         ifp = ipv6_add_addr(idev, cfg, true, extack);
2917         if (!IS_ERR(ifp)) {
2918                 if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
2919                         addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
2920                                               ifp->rt_priority, dev, expires,
2921                                               flags, GFP_KERNEL);
2922                 }
2923
2924                 /* Send a netlink notification if DAD is enabled and
2925                  * optimistic flag is not set
2926                  */
2927                 if (!(ifp->flags & (IFA_F_OPTIMISTIC | IFA_F_NODAD)))
2928                         ipv6_ifa_notify(0, ifp);
2929                 /*
2930                  * Note that section 3.1 of RFC 4429 indicates
2931                  * that the Optimistic flag should not be set for
2932                  * manually configured addresses
2933                  */
2934                 addrconf_dad_start(ifp);
2935                 if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR)
2936                         manage_tempaddrs(idev, ifp, cfg->valid_lft,
2937                                          cfg->preferred_lft, true, jiffies);
2938                 in6_ifa_put(ifp);
2939                 addrconf_verify_rtnl();
2940                 return 0;
2941         } else if (cfg->ifa_flags & IFA_F_MCAUTOJOIN) {
2942                 ipv6_mc_config(net->ipv6.mc_autojoin_sk, false,
2943                                cfg->pfx, ifindex);
2944         }
2945
2946         return PTR_ERR(ifp);
2947 }
2948
2949 static int inet6_addr_del(struct net *net, int ifindex, u32 ifa_flags,
2950                           const struct in6_addr *pfx, unsigned int plen)
2951 {
2952         struct inet6_ifaddr *ifp;
2953         struct inet6_dev *idev;
2954         struct net_device *dev;
2955
2956         if (plen > 128)
2957                 return -EINVAL;
2958
2959         dev = __dev_get_by_index(net, ifindex);
2960         if (!dev)
2961                 return -ENODEV;
2962
2963         idev = __in6_dev_get(dev);
2964         if (!idev)
2965                 return -ENXIO;
2966
2967         read_lock_bh(&idev->lock);
2968         list_for_each_entry(ifp, &idev->addr_list, if_list) {
2969                 if (ifp->prefix_len == plen &&
2970                     ipv6_addr_equal(pfx, &ifp->addr)) {
2971                         in6_ifa_hold(ifp);
2972                         read_unlock_bh(&idev->lock);
2973
2974                         if (!(ifp->flags & IFA_F_TEMPORARY) &&
2975                             (ifa_flags & IFA_F_MANAGETEMPADDR))
2976                                 manage_tempaddrs(idev, ifp, 0, 0, false,
2977                                                  jiffies);
2978                         ipv6_del_addr(ifp);
2979                         addrconf_verify_rtnl();
2980                         if (ipv6_addr_is_multicast(pfx)) {
2981                                 ipv6_mc_config(net->ipv6.mc_autojoin_sk,
2982                                                false, pfx, dev->ifindex);
2983                         }
2984                         return 0;
2985                 }
2986         }
2987         read_unlock_bh(&idev->lock);
2988         return -EADDRNOTAVAIL;
2989 }
2990
2991
2992 int addrconf_add_ifaddr(struct net *net, void __user *arg)
2993 {
2994         struct ifa6_config cfg = {
2995                 .ifa_flags = IFA_F_PERMANENT,
2996                 .preferred_lft = INFINITY_LIFE_TIME,
2997                 .valid_lft = INFINITY_LIFE_TIME,
2998         };
2999         struct in6_ifreq ireq;
3000         int err;
3001
3002         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3003                 return -EPERM;
3004
3005         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
3006                 return -EFAULT;
3007
3008         cfg.pfx = &ireq.ifr6_addr;
3009         cfg.plen = ireq.ifr6_prefixlen;
3010
3011         rtnl_lock();
3012         err = inet6_addr_add(net, ireq.ifr6_ifindex, &cfg, NULL);
3013         rtnl_unlock();
3014         return err;
3015 }
3016
3017 int addrconf_del_ifaddr(struct net *net, void __user *arg)
3018 {
3019         struct in6_ifreq ireq;
3020         int err;
3021
3022         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
3023                 return -EPERM;
3024
3025         if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq)))
3026                 return -EFAULT;
3027
3028         rtnl_lock();
3029         err = inet6_addr_del(net, ireq.ifr6_ifindex, 0, &ireq.ifr6_addr,
3030                              ireq.ifr6_prefixlen);
3031         rtnl_unlock();
3032         return err;
3033 }
3034
3035 static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr,
3036                      int plen, int scope)
3037 {
3038         struct inet6_ifaddr *ifp;
3039         struct ifa6_config cfg = {
3040                 .pfx = addr,
3041                 .plen = plen,
3042                 .ifa_flags = IFA_F_PERMANENT,
3043                 .valid_lft = INFINITY_LIFE_TIME,
3044                 .preferred_lft = INFINITY_LIFE_TIME,
3045                 .scope = scope
3046         };
3047
3048         ifp = ipv6_add_addr(idev, &cfg, true, NULL);
3049         if (!IS_ERR(ifp)) {
3050                 spin_lock_bh(&ifp->lock);
3051                 ifp->flags &= ~IFA_F_TENTATIVE;
3052                 spin_unlock_bh(&ifp->lock);
3053                 rt_genid_bump_ipv6(dev_net(idev->dev));
3054                 ipv6_ifa_notify(RTM_NEWADDR, ifp);
3055                 in6_ifa_put(ifp);
3056         }
3057 }
3058
3059 #if IS_ENABLED(CONFIG_IPV6_SIT)
3060 static void sit_add_v4_addrs(struct inet6_dev *idev)
3061 {
3062         struct in6_addr addr;
3063         struct net_device *dev;
3064         struct net *net = dev_net(idev->dev);
3065         int scope, plen;
3066         u32 pflags = 0;
3067
3068         ASSERT_RTNL();
3069
3070         memset(&addr, 0, sizeof(struct in6_addr));
3071         memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4);
3072
3073         if (idev->dev->flags&IFF_POINTOPOINT) {
3074                 if (idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_NONE)
3075                         return;
3076
3077                 addr.s6_addr32[0] = htonl(0xfe800000);
3078                 scope = IFA_LINK;
3079                 plen = 64;
3080         } else {
3081                 scope = IPV6_ADDR_COMPATv4;
3082                 plen = 96;
3083                 pflags |= RTF_NONEXTHOP;
3084         }
3085
3086         if (addr.s6_addr32[3]) {
3087                 add_addr(idev, &addr, plen, scope);
3088                 addrconf_prefix_route(&addr, plen, 0, idev->dev, 0, pflags,
3089                                       GFP_KERNEL);
3090                 return;
3091         }
3092
3093         for_each_netdev(net, dev) {
3094                 struct in_device *in_dev = __in_dev_get_rtnl(dev);
3095                 if (in_dev && (dev->flags & IFF_UP)) {
3096                         struct in_ifaddr *ifa;
3097
3098                         int flag = scope;
3099
3100                         for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
3101
3102                                 addr.s6_addr32[3] = ifa->ifa_local;
3103
3104                                 if (ifa->ifa_scope == RT_SCOPE_LINK)
3105                                         continue;
3106                                 if (ifa->ifa_scope >= RT_SCOPE_HOST) {
3107                                         if (idev->dev->flags&IFF_POINTOPOINT)
3108                                                 continue;
3109                                         flag |= IFA_HOST;
3110                                 }
3111
3112                                 add_addr(idev, &addr, plen, flag);
3113                                 addrconf_prefix_route(&addr, plen, 0, idev->dev,
3114                                                       0, pflags, GFP_KERNEL);
3115                         }
3116                 }
3117         }
3118 }
3119 #endif
3120
3121 static void init_loopback(struct net_device *dev)
3122 {
3123         struct inet6_dev  *idev;
3124
3125         /* ::1 */
3126
3127         ASSERT_RTNL();
3128
3129         idev = ipv6_find_idev(dev);
3130         if (!idev) {
3131                 pr_debug("%s: add_dev failed\n", __func__);
3132                 return;
3133         }
3134
3135         add_addr(idev, &in6addr_loopback, 128, IFA_HOST);
3136 }
3137
3138 void addrconf_add_linklocal(struct inet6_dev *idev,
3139                             const struct in6_addr *addr, u32 flags)
3140 {
3141         struct ifa6_config cfg = {
3142                 .pfx = addr,
3143                 .plen = 64,
3144                 .ifa_flags = flags | IFA_F_PERMANENT,
3145                 .valid_lft = INFINITY_LIFE_TIME,
3146                 .preferred_lft = INFINITY_LIFE_TIME,
3147                 .scope = IFA_LINK
3148         };
3149         struct inet6_ifaddr *ifp;
3150
3151 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
3152         if ((dev_net(idev->dev)->ipv6.devconf_all->optimistic_dad ||
3153              idev->cnf.optimistic_dad) &&
3154             !dev_net(idev->dev)->ipv6.devconf_all->forwarding)
3155                 cfg.ifa_flags |= IFA_F_OPTIMISTIC;
3156 #endif
3157
3158         ifp = ipv6_add_addr(idev, &cfg, true, NULL);
3159         if (!IS_ERR(ifp)) {
3160                 addrconf_prefix_route(&ifp->addr, ifp->prefix_len, 0, idev->dev,
3161                                       0, 0, GFP_ATOMIC);
3162                 addrconf_dad_start(ifp);
3163                 in6_ifa_put(ifp);
3164         }
3165 }
3166 EXPORT_SYMBOL_GPL(addrconf_add_linklocal);
3167
3168 static bool ipv6_reserved_interfaceid(struct in6_addr address)
3169 {
3170         if ((address.s6_addr32[2] | address.s6_addr32[3]) == 0)
3171                 return true;
3172
3173         if (address.s6_addr32[2] == htonl(0x02005eff) &&
3174             ((address.s6_addr32[3] & htonl(0xfe000000)) == htonl(0xfe000000)))
3175                 return true;
3176
3177         if (address.s6_addr32[2] == htonl(0xfdffffff) &&
3178             ((address.s6_addr32[3] & htonl(0xffffff80)) == htonl(0xffffff80)))
3179                 return true;
3180
3181         return false;
3182 }
3183
3184 static int ipv6_generate_stable_address(struct in6_addr *address,
3185                                         u8 dad_count,
3186                                         const struct inet6_dev *idev)
3187 {
3188         static DEFINE_SPINLOCK(lock);
3189         static __u32 digest[SHA_DIGEST_WORDS];
3190         static __u32 workspace[SHA_WORKSPACE_WORDS];
3191
3192         static union {
3193                 char __data[SHA_MESSAGE_BYTES];
3194                 struct {
3195                         struct in6_addr secret;
3196                         __be32 prefix[2];
3197                         unsigned char hwaddr[MAX_ADDR_LEN];
3198                         u8 dad_count;
3199                 } __packed;
3200         } data;
3201
3202         struct in6_addr secret;
3203         struct in6_addr temp;
3204         struct net *net = dev_net(idev->dev);
3205
3206         BUILD_BUG_ON(sizeof(data.__data) != sizeof(data));
3207
3208         if (idev->cnf.stable_secret.initialized)
3209                 secret = idev->cnf.stable_secret.secret;
3210         else if (net->ipv6.devconf_dflt->stable_secret.initialized)
3211                 secret = net->ipv6.devconf_dflt->stable_secret.secret;
3212         else
3213                 return -1;
3214
3215 retry:
3216         spin_lock_bh(&lock);
3217
3218         sha_init(digest);
3219         memset(&data, 0, sizeof(data));
3220         memset(workspace, 0, sizeof(workspace));
3221         memcpy(data.hwaddr, idev->dev->perm_addr, idev->dev->addr_len);
3222         data.prefix[0] = address->s6_addr32[0];
3223         data.prefix[1] = address->s6_addr32[1];
3224         data.secret = secret;
3225         data.dad_count = dad_count;
3226
3227         sha_transform(digest, data.__data, workspace);
3228
3229         temp = *address;
3230         temp.s6_addr32[2] = (__force __be32)digest[0];
3231         temp.s6_addr32[3] = (__force __be32)digest[1];
3232
3233         spin_unlock_bh(&lock);
3234
3235         if (ipv6_reserved_interfaceid(temp)) {
3236                 dad_count++;
3237                 if (dad_count > dev_net(idev->dev)->ipv6.sysctl.idgen_retries)
3238                         return -1;
3239                 goto retry;
3240         }
3241
3242         *address = temp;
3243         return 0;
3244 }
3245
3246 static void ipv6_gen_mode_random_init(struct inet6_dev *idev)
3247 {
3248         struct ipv6_stable_secret *s = &idev->cnf.stable_secret;
3249
3250         if (s->initialized)
3251                 return;
3252         s = &idev->cnf.stable_secret;
3253         get_random_bytes(&s->secret, sizeof(s->secret));
3254         s->initialized = true;
3255 }
3256
3257 static void addrconf_addr_gen(struct inet6_dev *idev, bool prefix_route)
3258 {
3259         struct in6_addr addr;
3260
3261         /* no link local addresses on L3 master devices */
3262         if (netif_is_l3_master(idev->dev))
3263                 return;
3264
3265         /* no link local addresses on devices flagged as slaves */
3266         if (idev->dev->flags & IFF_SLAVE)
3267                 return;
3268
3269         ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0);
3270
3271         switch (idev->cnf.addr_gen_mode) {
3272         case IN6_ADDR_GEN_MODE_RANDOM:
3273                 ipv6_gen_mode_random_init(idev);
3274                 /* fallthrough */
3275         case IN6_ADDR_GEN_MODE_STABLE_PRIVACY:
3276                 if (!ipv6_generate_stable_address(&addr, 0, idev))
3277                         addrconf_add_linklocal(idev, &addr,
3278                                                IFA_F_STABLE_PRIVACY);
3279                 else if (prefix_route)
3280                         addrconf_prefix_route(&addr, 64, 0, idev->dev,
3281                                               0, 0, GFP_KERNEL);
3282                 break;
3283         case IN6_ADDR_GEN_MODE_EUI64:
3284                 /* addrconf_add_linklocal also adds a prefix_route and we
3285                  * only need to care about prefix routes if ipv6_generate_eui64
3286                  * couldn't generate one.
3287                  */
3288                 if (ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) == 0)
3289                         addrconf_add_linklocal(idev, &addr, 0);
3290                 else if (prefix_route)
3291                         addrconf_prefix_route(&addr, 64, 0, idev->dev,
3292                                               0, 0, GFP_KERNEL);
3293                 break;
3294         case IN6_ADDR_GEN_MODE_NONE:
3295         default:
3296                 /* will not add any link local address */
3297                 break;
3298         }
3299 }
3300
3301 static void addrconf_dev_config(struct net_device *dev)
3302 {
3303         struct inet6_dev *idev;
3304
3305         ASSERT_RTNL();
3306
3307         if ((dev->type != ARPHRD_ETHER) &&
3308             (dev->type != ARPHRD_FDDI) &&
3309             (dev->type != ARPHRD_ARCNET) &&
3310             (dev->type != ARPHRD_INFINIBAND) &&
3311             (dev->type != ARPHRD_IEEE1394) &&
3312             (dev->type != ARPHRD_TUNNEL6) &&
3313             (dev->type != ARPHRD_6LOWPAN) &&
3314             (dev->type != ARPHRD_IP6GRE) &&
3315             (dev->type != ARPHRD_IPGRE) &&
3316             (dev->type != ARPHRD_TUNNEL) &&
3317             (dev->type != ARPHRD_NONE) &&
3318             (dev->type != ARPHRD_RAWIP)) {
3319                 /* Alas, we support only Ethernet autoconfiguration. */
3320                 idev = __in6_dev_get(dev);
3321                 if (!IS_ERR_OR_NULL(idev) && dev->flags & IFF_UP &&
3322                     dev->flags & IFF_MULTICAST)
3323                         ipv6_mc_up(idev);
3324                 return;
3325         }
3326
3327         idev = addrconf_add_dev(dev);
3328         if (IS_ERR(idev))
3329                 return;
3330
3331         /* this device type has no EUI support */
3332         if (dev->type == ARPHRD_NONE &&
3333             idev->cnf.addr_gen_mode == IN6_ADDR_GEN_MODE_EUI64)
3334                 idev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_RANDOM;
3335
3336         addrconf_addr_gen(idev, false);
3337 }
3338
3339 #if IS_ENABLED(CONFIG_IPV6_SIT)
3340 static void addrconf_sit_config(struct net_device *dev)
3341 {
3342         struct inet6_dev *idev;
3343
3344         ASSERT_RTNL();
3345
3346         /*
3347          * Configure the tunnel with one of our IPv4
3348          * addresses... we should configure all of
3349          * our v4 addrs in the tunnel
3350          */
3351
3352         idev = ipv6_find_idev(dev);
3353         if (!idev) {
3354                 pr_debug("%s: add_dev failed\n", __func__);
3355                 return;
3356         }
3357
3358         if (dev->priv_flags & IFF_ISATAP) {
3359                 addrconf_addr_gen(idev, false);
3360                 return;
3361         }
3362
3363         sit_add_v4_addrs(idev);
3364
3365         if (dev->flags&IFF_POINTOPOINT)
3366                 addrconf_add_mroute(dev);
3367 }
3368 #endif
3369
3370 #if IS_ENABLED(CONFIG_NET_IPGRE)
3371 static void addrconf_gre_config(struct net_device *dev)
3372 {
3373         struct inet6_dev *idev;
3374
3375         ASSERT_RTNL();
3376
3377         idev = ipv6_find_idev(dev);
3378         if (!idev) {
3379                 pr_debug("%s: add_dev failed\n", __func__);
3380                 return;
3381         }
3382
3383         addrconf_addr_gen(idev, true);
3384         if (dev->flags & IFF_POINTOPOINT)
3385                 addrconf_add_mroute(dev);
3386 }
3387 #endif
3388
3389 static int fixup_permanent_addr(struct net *net,
3390                                 struct inet6_dev *idev,
3391                                 struct inet6_ifaddr *ifp)
3392 {
3393         /* !fib6_node means the host route was removed from the
3394          * FIB, for example, if 'lo' device is taken down. In that
3395          * case regenerate the host route.
3396          */
3397         if (!ifp->rt || !ifp->rt->fib6_node) {
3398                 struct fib6_info *f6i, *prev;
3399
3400                 f6i = addrconf_f6i_alloc(net, idev, &ifp->addr, false,
3401                                          GFP_ATOMIC);
3402                 if (IS_ERR(f6i))
3403                         return PTR_ERR(f6i);
3404
3405                 /* ifp->rt can be accessed outside of rtnl */
3406                 spin_lock(&ifp->lock);
3407                 prev = ifp->rt;
3408                 ifp->rt = f6i;
3409                 spin_unlock(&ifp->lock);
3410
3411                 fib6_info_release(prev);
3412         }
3413
3414         if (!(ifp->flags & IFA_F_NOPREFIXROUTE)) {
3415                 addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
3416                                       ifp->rt_priority, idev->dev, 0, 0,
3417                                       GFP_ATOMIC);
3418         }
3419
3420         if (ifp->state == INET6_IFADDR_STATE_PREDAD)
3421                 addrconf_dad_start(ifp);
3422
3423         return 0;
3424 }
3425
3426 static void addrconf_permanent_addr(struct net *net, struct net_device *dev)
3427 {
3428         struct inet6_ifaddr *ifp, *tmp;
3429         struct inet6_dev *idev;
3430
3431         idev = __in6_dev_get(dev);
3432         if (!idev)
3433                 return;
3434
3435         write_lock_bh(&idev->lock);
3436
3437         list_for_each_entry_safe(ifp, tmp, &idev->addr_list, if_list) {
3438                 if ((ifp->flags & IFA_F_PERMANENT) &&
3439                     fixup_permanent_addr(net, idev, ifp) < 0) {
3440                         write_unlock_bh(&idev->lock);
3441                         in6_ifa_hold(ifp);
3442                         ipv6_del_addr(ifp);
3443                         write_lock_bh(&idev->lock);
3444
3445                         net_info_ratelimited("%s: Failed to add prefix route for address %pI6c; dropping\n",
3446                                              idev->dev->name, &ifp->addr);
3447                 }
3448         }
3449
3450         write_unlock_bh(&idev->lock);
3451 }
3452
3453 static int addrconf_notify(struct notifier_block *this, unsigned long event,
3454                            void *ptr)
3455 {
3456         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3457         struct netdev_notifier_change_info *change_info;
3458         struct netdev_notifier_changeupper_info *info;
3459         struct inet6_dev *idev = __in6_dev_get(dev);
3460         struct net *net = dev_net(dev);
3461         int run_pending = 0;
3462         int err;
3463
3464         switch (event) {
3465         case NETDEV_REGISTER:
3466                 if (!idev && dev->mtu >= IPV6_MIN_MTU) {
3467                         idev = ipv6_add_dev(dev);
3468                         if (IS_ERR(idev))
3469                                 return notifier_from_errno(PTR_ERR(idev));
3470                 }
3471                 break;
3472
3473         case NETDEV_CHANGEMTU:
3474                 /* if MTU under IPV6_MIN_MTU stop IPv6 on this interface. */
3475                 if (dev->mtu < IPV6_MIN_MTU) {
3476                         addrconf_ifdown(dev, dev != net->loopback_dev);
3477                         break;
3478                 }
3479
3480                 if (idev) {
3481                         rt6_mtu_change(dev, dev->mtu);
3482                         idev->cnf.mtu6 = dev->mtu;
3483                         break;
3484                 }
3485
3486                 /* allocate new idev */
3487                 idev = ipv6_add_dev(dev);
3488                 if (IS_ERR(idev))
3489                         break;
3490
3491                 /* device is still not ready */
3492                 if (!(idev->if_flags & IF_READY))
3493                         break;
3494
3495                 run_pending = 1;
3496
3497                 /* fall through */
3498
3499         case NETDEV_UP:
3500         case NETDEV_CHANGE:
3501                 if (dev->flags & IFF_SLAVE)
3502                         break;
3503
3504                 if (idev && idev->cnf.disable_ipv6)
3505                         break;
3506
3507                 if (event == NETDEV_UP) {
3508                         /* restore routes for permanent addresses */
3509                         addrconf_permanent_addr(net, dev);
3510
3511                         if (!addrconf_link_ready(dev)) {
3512                                 /* device is not ready yet. */
3513                                 pr_info("ADDRCONF(NETDEV_UP): %s: link is not ready\n",
3514                                         dev->name);
3515                                 break;
3516                         }
3517
3518                         if (!idev && dev->mtu >= IPV6_MIN_MTU)
3519                                 idev = ipv6_add_dev(dev);
3520
3521                         if (!IS_ERR_OR_NULL(idev)) {
3522                                 idev->if_flags |= IF_READY;
3523                                 run_pending = 1;
3524                         }
3525                 } else if (event == NETDEV_CHANGE) {
3526                         if (!addrconf_link_ready(dev)) {
3527                                 /* device is still not ready. */
3528                                 rt6_sync_down_dev(dev, event);
3529                                 break;
3530                         }
3531
3532                         if (!IS_ERR_OR_NULL(idev)) {
3533                                 if (idev->if_flags & IF_READY) {
3534                                         /* device is already configured -
3535                                          * but resend MLD reports, we might
3536                                          * have roamed and need to update
3537                                          * multicast snooping switches
3538                                          */
3539                                         ipv6_mc_up(idev);
3540                                         change_info = ptr;
3541                                         if (change_info->flags_changed & IFF_NOARP)
3542                                                 addrconf_dad_run(idev, true);
3543                                         rt6_sync_up(dev, RTNH_F_LINKDOWN);
3544                                         break;
3545                                 }
3546                                 idev->if_flags |= IF_READY;
3547                         }
3548
3549                         pr_info("ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\n",
3550                                 dev->name);
3551
3552                         run_pending = 1;
3553                 }
3554
3555                 switch (dev->type) {
3556 #if IS_ENABLED(CONFIG_IPV6_SIT)
3557                 case ARPHRD_SIT:
3558                         addrconf_sit_config(dev);
3559                         break;
3560 #endif
3561 #if IS_ENABLED(CONFIG_NET_IPGRE)
3562                 case ARPHRD_IPGRE:
3563                         addrconf_gre_config(dev);
3564                         break;
3565 #endif
3566                 case ARPHRD_LOOPBACK:
3567                         init_loopback(dev);
3568                         break;
3569
3570                 default:
3571                         addrconf_dev_config(dev);
3572                         break;
3573                 }
3574
3575                 if (!IS_ERR_OR_NULL(idev)) {
3576                         if (run_pending)
3577                                 addrconf_dad_run(idev, false);
3578
3579                         /* Device has an address by now */
3580                         rt6_sync_up(dev, RTNH_F_DEAD);
3581
3582                         /*
3583                          * If the MTU changed during the interface down,
3584                          * when the interface up, the changed MTU must be
3585                          * reflected in the idev as well as routers.
3586                          */
3587                         if (idev->cnf.mtu6 != dev->mtu &&
3588                             dev->mtu >= IPV6_MIN_MTU) {
3589                                 rt6_mtu_change(dev, dev->mtu);
3590                                 idev->cnf.mtu6 = dev->mtu;
3591                         }
3592                         idev->tstamp = jiffies;
3593                         inet6_ifinfo_notify(RTM_NEWLINK, idev);
3594
3595                         /*
3596                          * If the changed mtu during down is lower than
3597                          * IPV6_MIN_MTU stop IPv6 on this interface.
3598                          */
3599                         if (dev->mtu < IPV6_MIN_MTU)
3600                                 addrconf_ifdown(dev, dev != net->loopback_dev);
3601                 }
3602                 break;
3603
3604         case NETDEV_DOWN:
3605         case NETDEV_UNREGISTER:
3606                 /*
3607                  *      Remove all addresses from this interface.
3608                  */
3609                 addrconf_ifdown(dev, event != NETDEV_DOWN);
3610                 break;
3611
3612         case NETDEV_CHANGENAME:
3613                 if (idev) {
3614                         snmp6_unregister_dev(idev);
3615                         addrconf_sysctl_unregister(idev);
3616                         err = addrconf_sysctl_register(idev);
3617                         if (err)
3618                                 return notifier_from_errno(err);
3619                         err = snmp6_register_dev(idev);
3620                         if (err) {
3621                                 addrconf_sysctl_unregister(idev);
3622                                 return notifier_from_errno(err);
3623                         }
3624                 }
3625                 break;
3626
3627         case NETDEV_PRE_TYPE_CHANGE:
3628         case NETDEV_POST_TYPE_CHANGE:
3629                 if (idev)
3630                         addrconf_type_change(dev, event);
3631                 break;
3632
3633         case NETDEV_CHANGEUPPER:
3634                 info = ptr;
3635
3636                 /* flush all routes if dev is linked to or unlinked from
3637                  * an L3 master device (e.g., VRF)
3638                  */
3639                 if (info->upper_dev && netif_is_l3_master(info->upper_dev))
3640                         addrconf_ifdown(dev, 0);
3641         }
3642
3643         return NOTIFY_OK;
3644 }
3645
3646 /*
3647  *      addrconf module should be notified of a device going up
3648  */
3649 static struct notifier_block ipv6_dev_notf = {
3650         .notifier_call = addrconf_notify,
3651         .priority = ADDRCONF_NOTIFY_PRIORITY,
3652 };
3653
3654 static void addrconf_type_change(struct net_device *dev, unsigned long event)
3655 {
3656         struct inet6_dev *idev;
3657         ASSERT_RTNL();
3658
3659         idev = __in6_dev_get(dev);
3660
3661         if (event == NETDEV_POST_TYPE_CHANGE)
3662                 ipv6_mc_remap(idev);
3663         else if (event == NETDEV_PRE_TYPE_CHANGE)
3664                 ipv6_mc_unmap(idev);
3665 }
3666
3667 static bool addr_is_local(const struct in6_addr *addr)
3668 {
3669         return ipv6_addr_type(addr) &
3670                 (IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
3671 }
3672
3673 static int addrconf_ifdown(struct net_device *dev, int how)
3674 {
3675         unsigned long event = how ? NETDEV_UNREGISTER : NETDEV_DOWN;
3676         struct net *net = dev_net(dev);
3677         struct inet6_dev *idev;
3678         struct inet6_ifaddr *ifa;
3679         LIST_HEAD(tmp_addr_list);
3680         bool keep_addr = false;
3681         int state, i;
3682
3683         ASSERT_RTNL();
3684
3685         rt6_disable_ip(dev, event);
3686
3687         idev = __in6_dev_get(dev);
3688         if (!idev)
3689                 return -ENODEV;
3690
3691         /*
3692          * Step 1: remove reference to ipv6 device from parent device.
3693          *         Do not dev_put!
3694          */
3695         if (how) {
3696                 idev->dead = 1;
3697
3698                 /* protected by rtnl_lock */
3699                 RCU_INIT_POINTER(dev->ip6_ptr, NULL);
3700
3701                 /* Step 1.5: remove snmp6 entry */
3702                 snmp6_unregister_dev(idev);
3703
3704         }
3705
3706         /* combine the user config with event to determine if permanent
3707          * addresses are to be removed from address hash table
3708          */
3709         if (!how && !idev->cnf.disable_ipv6) {
3710                 /* aggregate the system setting and interface setting */
3711                 int _keep_addr = net->ipv6.devconf_all->keep_addr_on_down;
3712
3713                 if (!_keep_addr)
3714                         _keep_addr = idev->cnf.keep_addr_on_down;
3715
3716                 keep_addr = (_keep_addr > 0);
3717         }
3718
3719         /* Step 2: clear hash table */
3720         for (i = 0; i < IN6_ADDR_HSIZE; i++) {
3721                 struct hlist_head *h = &inet6_addr_lst[i];
3722
3723                 spin_lock_bh(&addrconf_hash_lock);
3724 restart:
3725                 hlist_for_each_entry_rcu(ifa, h, addr_lst) {
3726                         if (ifa->idev == idev) {
3727                                 addrconf_del_dad_work(ifa);
3728                                 /* combined flag + permanent flag decide if
3729                                  * address is retained on a down event
3730                                  */
3731                                 if (!keep_addr ||
3732                                     !(ifa->flags & IFA_F_PERMANENT) ||
3733                                     addr_is_local(&ifa->addr)) {
3734                                         hlist_del_init_rcu(&ifa->addr_lst);
3735                                         goto restart;
3736                                 }
3737                         }
3738                 }
3739                 spin_unlock_bh(&addrconf_hash_lock);
3740         }
3741
3742         write_lock_bh(&idev->lock);
3743
3744         addrconf_del_rs_timer(idev);
3745
3746         /* Step 2: clear flags for stateless addrconf */
3747         if (!how)
3748                 idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY);
3749
3750         /* Step 3: clear tempaddr list */
3751         while (!list_empty(&idev->tempaddr_list)) {
3752                 ifa = list_first_entry(&idev->tempaddr_list,
3753                                        struct inet6_ifaddr, tmp_list);
3754                 list_del(&ifa->tmp_list);
3755                 write_unlock_bh(&idev->lock);
3756                 spin_lock_bh(&ifa->lock);
3757
3758                 if (ifa->ifpub) {
3759                         in6_ifa_put(ifa->ifpub);
3760                         ifa->ifpub = NULL;
3761                 }
3762                 spin_unlock_bh(&ifa->lock);
3763                 in6_ifa_put(ifa);
3764                 write_lock_bh(&idev->lock);
3765         }
3766
3767         list_for_each_entry(ifa, &idev->addr_list, if_list)
3768                 list_add_tail(&ifa->if_list_aux, &tmp_addr_list);
3769         write_unlock_bh(&idev->lock);
3770
3771         while (!list_empty(&tmp_addr_list)) {
3772                 struct fib6_info *rt = NULL;
3773                 bool keep;
3774
3775                 ifa = list_first_entry(&tmp_addr_list,
3776                                        struct inet6_ifaddr, if_list_aux);
3777                 list_del(&ifa->if_list_aux);
3778
3779                 addrconf_del_dad_work(ifa);
3780
3781                 keep = keep_addr && (ifa->flags & IFA_F_PERMANENT) &&
3782                         !addr_is_local(&ifa->addr);
3783
3784                 spin_lock_bh(&ifa->lock);
3785
3786                 if (keep) {
3787                         /* set state to skip the notifier below */
3788                         state = INET6_IFADDR_STATE_DEAD;
3789                         ifa->state = INET6_IFADDR_STATE_PREDAD;
3790                         if (!(ifa->flags & IFA_F_NODAD))
3791                                 ifa->flags |= IFA_F_TENTATIVE;
3792
3793                         rt = ifa->rt;
3794                         ifa->rt = NULL;
3795                 } else {
3796                         state = ifa->state;
3797                         ifa->state = INET6_IFADDR_STATE_DEAD;
3798                 }
3799
3800                 spin_unlock_bh(&ifa->lock);
3801
3802                 if (rt)
3803                         ip6_del_rt(net, rt);
3804
3805                 if (state != INET6_IFADDR_STATE_DEAD) {
3806                         __ipv6_ifa_notify(RTM_DELADDR, ifa);
3807                         inet6addr_notifier_call_chain(NETDEV_DOWN, ifa);
3808                 } else {
3809                         if (idev->cnf.forwarding)
3810                                 addrconf_leave_anycast(ifa);
3811                         addrconf_leave_solict(ifa->idev, &ifa->addr);
3812                 }
3813
3814                 if (!keep) {
3815                         write_lock_bh(&idev->lock);
3816                         list_del_rcu(&ifa->if_list);
3817                         write_unlock_bh(&idev->lock);
3818                         in6_ifa_put(ifa);
3819                 }
3820         }
3821
3822         /* Step 5: Discard anycast and multicast list */
3823         if (how) {
3824                 ipv6_ac_destroy_dev(idev);
3825                 ipv6_mc_destroy_dev(idev);
3826         } else {
3827                 ipv6_mc_down(idev);
3828         }
3829
3830         idev->tstamp = jiffies;
3831
3832         /* Last: Shot the device (if unregistered) */
3833         if (how) {
3834                 addrconf_sysctl_unregister(idev);
3835                 neigh_parms_release(&nd_tbl, idev->nd_parms);
3836                 neigh_ifdown(&nd_tbl, dev);
3837                 in6_dev_put(idev);
3838         }
3839         return 0;
3840 }
3841
3842 static void addrconf_rs_timer(struct timer_list *t)
3843 {
3844         struct inet6_dev *idev = from_timer(idev, t, rs_timer);
3845         struct net_device *dev = idev->dev;
3846         struct in6_addr lladdr;
3847
3848         write_lock(&idev->lock);
3849         if (idev->dead || !(idev->if_flags & IF_READY))
3850                 goto out;
3851
3852         if (!ipv6_accept_ra(idev))
3853                 goto out;
3854
3855         /* Announcement received after solicitation was sent */
3856         if (idev->if_flags & IF_RA_RCVD)
3857                 goto out;
3858
3859         if (idev->rs_probes++ < idev->cnf.rtr_solicits || idev->cnf.rtr_solicits < 0) {
3860                 write_unlock(&idev->lock);
3861                 if (!ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
3862                         ndisc_send_rs(dev, &lladdr,
3863                                       &in6addr_linklocal_allrouters);
3864                 else
3865                         goto put;
3866
3867                 write_lock(&idev->lock);
3868                 idev->rs_interval = rfc3315_s14_backoff_update(
3869                         idev->rs_interval, idev->cnf.rtr_solicit_max_interval);
3870                 /* The wait after the last probe can be shorter */
3871                 addrconf_mod_rs_timer(idev, (idev->rs_probes ==
3872                                              idev->cnf.rtr_solicits) ?
3873                                       idev->cnf.rtr_solicit_delay :
3874                                       idev->rs_interval);
3875         } else {
3876                 /*
3877                  * Note: we do not support deprecated "all on-link"
3878                  * assumption any longer.
3879                  */
3880                 pr_debug("%s: no IPv6 routers present\n", idev->dev->name);
3881         }
3882
3883 out:
3884         write_unlock(&idev->lock);
3885 put:
3886         in6_dev_put(idev);
3887 }
3888
3889 /*
3890  *      Duplicate Address Detection
3891  */
3892 static void addrconf_dad_kick(struct inet6_ifaddr *ifp)
3893 {
3894         unsigned long rand_num;
3895         struct inet6_dev *idev = ifp->idev;
3896         u64 nonce;
3897
3898         if (ifp->flags & IFA_F_OPTIMISTIC)
3899                 rand_num = 0;
3900         else
3901                 rand_num = prandom_u32() % (idev->cnf.rtr_solicit_delay ? : 1);
3902
3903         nonce = 0;
3904         if (idev->cnf.enhanced_dad ||
3905             dev_net(idev->dev)->ipv6.devconf_all->enhanced_dad) {
3906                 do
3907                         get_random_bytes(&nonce, 6);
3908                 while (nonce == 0);
3909         }
3910         ifp->dad_nonce = nonce;
3911         ifp->dad_probes = idev->cnf.dad_transmits;
3912         addrconf_mod_dad_work(ifp, rand_num);
3913 }
3914
3915 static void addrconf_dad_begin(struct inet6_ifaddr *ifp)
3916 {
3917         struct inet6_dev *idev = ifp->idev;
3918         struct net_device *dev = idev->dev;
3919         bool bump_id, notify = false;
3920         struct net *net;
3921
3922         addrconf_join_solict(dev, &ifp->addr);
3923
3924         prandom_seed((__force u32) ifp->addr.s6_addr32[3]);
3925
3926         read_lock_bh(&idev->lock);
3927         spin_lock(&ifp->lock);
3928         if (ifp->state == INET6_IFADDR_STATE_DEAD)
3929                 goto out;
3930
3931         net = dev_net(dev);
3932         if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) ||
3933             (net->ipv6.devconf_all->accept_dad < 1 &&
3934              idev->cnf.accept_dad < 1) ||
3935             !(ifp->flags&IFA_F_TENTATIVE) ||
3936             ifp->flags & IFA_F_NODAD) {
3937                 bool send_na = false;
3938
3939                 if (ifp->flags & IFA_F_TENTATIVE &&
3940                     !(ifp->flags & IFA_F_OPTIMISTIC))
3941                         send_na = true;
3942                 bump_id = ifp->flags & IFA_F_TENTATIVE;
3943                 ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
3944                 spin_unlock(&ifp->lock);
3945                 read_unlock_bh(&idev->lock);
3946
3947                 addrconf_dad_completed(ifp, bump_id, send_na);
3948                 return;
3949         }
3950
3951         if (!(idev->if_flags & IF_READY)) {
3952                 spin_unlock(&ifp->lock);
3953                 read_unlock_bh(&idev->lock);
3954                 /*
3955                  * If the device is not ready:
3956                  * - keep it tentative if it is a permanent address.
3957                  * - otherwise, kill it.
3958                  */
3959                 in6_ifa_hold(ifp);
3960                 addrconf_dad_stop(ifp, 0);
3961                 return;
3962         }
3963
3964         /*
3965          * Optimistic nodes can start receiving
3966          * Frames right away
3967          */
3968         if (ifp->flags & IFA_F_OPTIMISTIC) {
3969                 ip6_ins_rt(net, ifp->rt);
3970                 if (ipv6_use_optimistic_addr(net, idev)) {
3971                         /* Because optimistic nodes can use this address,
3972                          * notify listeners. If DAD fails, RTM_DELADDR is sent.
3973                          */
3974                         notify = true;
3975                 }
3976         }
3977
3978         addrconf_dad_kick(ifp);
3979 out:
3980         spin_unlock(&ifp->lock);
3981         read_unlock_bh(&idev->lock);
3982         if (notify)
3983                 ipv6_ifa_notify(RTM_NEWADDR, ifp);
3984 }
3985
3986 static void addrconf_dad_start(struct inet6_ifaddr *ifp)
3987 {
3988         bool begin_dad = false;
3989
3990         spin_lock_bh(&ifp->lock);
3991         if (ifp->state != INET6_IFADDR_STATE_DEAD) {
3992                 ifp->state = INET6_IFADDR_STATE_PREDAD;
3993                 begin_dad = true;
3994         }
3995         spin_unlock_bh(&ifp->lock);
3996
3997         if (begin_dad)
3998                 addrconf_mod_dad_work(ifp, 0);
3999 }
4000
4001 static void addrconf_dad_work(struct work_struct *w)
4002 {
4003         struct inet6_ifaddr *ifp = container_of(to_delayed_work(w),
4004                                                 struct inet6_ifaddr,
4005                                                 dad_work);
4006         struct inet6_dev *idev = ifp->idev;
4007         bool bump_id, disable_ipv6 = false;
4008         struct in6_addr mcaddr;
4009
4010         enum {
4011                 DAD_PROCESS,
4012                 DAD_BEGIN,
4013                 DAD_ABORT,
4014         } action = DAD_PROCESS;
4015
4016         rtnl_lock();
4017
4018         spin_lock_bh(&ifp->lock);
4019         if (ifp->state == INET6_IFADDR_STATE_PREDAD) {
4020                 action = DAD_BEGIN;
4021                 ifp->state = INET6_IFADDR_STATE_DAD;
4022         } else if (ifp->state == INET6_IFADDR_STATE_ERRDAD) {
4023                 action = DAD_ABORT;
4024                 ifp->state = INET6_IFADDR_STATE_POSTDAD;
4025
4026                 if ((dev_net(idev->dev)->ipv6.devconf_all->accept_dad > 1 ||
4027                      idev->cnf.accept_dad > 1) &&
4028                     !idev->cnf.disable_ipv6 &&
4029                     !(ifp->flags & IFA_F_STABLE_PRIVACY)) {
4030                         struct in6_addr addr;
4031
4032                         addr.s6_addr32[0] = htonl(0xfe800000);
4033                         addr.s6_addr32[1] = 0;
4034
4035                         if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) &&
4036                             ipv6_addr_equal(&ifp->addr, &addr)) {
4037                                 /* DAD failed for link-local based on MAC */
4038                                 idev->cnf.disable_ipv6 = 1;
4039
4040                                 pr_info("%s: IPv6 being disabled!\n",
4041                                         ifp->idev->dev->name);
4042                                 disable_ipv6 = true;
4043                         }
4044                 }
4045         }
4046         spin_unlock_bh(&ifp->lock);
4047
4048         if (action == DAD_BEGIN) {
4049                 addrconf_dad_begin(ifp);
4050                 goto out;
4051         } else if (action == DAD_ABORT) {
4052                 in6_ifa_hold(ifp);
4053                 addrconf_dad_stop(ifp, 1);
4054                 if (disable_ipv6)
4055                         addrconf_ifdown(idev->dev, 0);
4056                 goto out;
4057         }
4058
4059         if (!ifp->dad_probes && addrconf_dad_end(ifp))
4060                 goto out;
4061
4062         write_lock_bh(&idev->lock);
4063         if (idev->dead || !(idev->if_flags & IF_READY)) {
4064                 write_unlock_bh(&idev->lock);
4065                 goto out;
4066         }
4067
4068         spin_lock(&ifp->lock);
4069         if (ifp->state == INET6_IFADDR_STATE_DEAD) {
4070                 spin_unlock(&ifp->lock);
4071                 write_unlock_bh(&idev->lock);
4072                 goto out;
4073         }
4074
4075         if (ifp->dad_probes == 0) {
4076                 bool send_na = false;
4077
4078                 /*
4079                  * DAD was successful
4080                  */
4081
4082                 if (ifp->flags & IFA_F_TENTATIVE &&
4083                     !(ifp->flags & IFA_F_OPTIMISTIC))
4084                         send_na = true;
4085                 bump_id = ifp->flags & IFA_F_TENTATIVE;
4086                 ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED);
4087                 spin_unlock(&ifp->lock);
4088                 write_unlock_bh(&idev->lock);
4089
4090                 addrconf_dad_completed(ifp, bump_id, send_na);
4091
4092                 goto out;
4093         }
4094
4095         ifp->dad_probes--;
4096         addrconf_mod_dad_work(ifp,
4097                               NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME));
4098         spin_unlock(&ifp->lock);
4099         write_unlock_bh(&idev->lock);
4100
4101         /* send a neighbour solicitation for our addr */
4102         addrconf_addr_solict_mult(&ifp->addr, &mcaddr);
4103         ndisc_send_ns(ifp->idev->dev, &ifp->addr, &mcaddr, &in6addr_any,
4104                       ifp->dad_nonce);
4105 out:
4106         in6_ifa_put(ifp);
4107         rtnl_unlock();
4108 }
4109
4110 /* ifp->idev must be at least read locked */
4111 static bool ipv6_lonely_lladdr(struct inet6_ifaddr *ifp)
4112 {
4113         struct inet6_ifaddr *ifpiter;
4114         struct inet6_dev *idev = ifp->idev;
4115
4116         list_for_each_entry_reverse(ifpiter, &idev->addr_list, if_list) {
4117                 if (ifpiter->scope > IFA_LINK)
4118                         break;
4119                 if (ifp != ifpiter && ifpiter->scope == IFA_LINK &&
4120                     (ifpiter->flags & (IFA_F_PERMANENT|IFA_F_TENTATIVE|
4121                                        IFA_F_OPTIMISTIC|IFA_F_DADFAILED)) ==
4122                     IFA_F_PERMANENT)
4123                         return false;
4124         }
4125         return true;
4126 }
4127
4128 static void addrconf_dad_completed(struct inet6_ifaddr *ifp, bool bump_id,
4129                                    bool send_na)
4130 {
4131         struct net_device *dev = ifp->idev->dev;
4132         struct in6_addr lladdr;
4133         bool send_rs, send_mld;
4134
4135         addrconf_del_dad_work(ifp);
4136
4137         /*
4138          *      Configure the address for reception. Now it is valid.
4139          */
4140
4141         ipv6_ifa_notify(RTM_NEWADDR, ifp);
4142
4143         /* If added prefix is link local and we are prepared to process
4144            router advertisements, start sending router solicitations.
4145          */
4146
4147         read_lock_bh(&ifp->idev->lock);
4148         send_mld = ifp->scope == IFA_LINK && ipv6_lonely_lladdr(ifp);
4149         send_rs = send_mld &&
4150                   ipv6_accept_ra(ifp->idev) &&
4151                   ifp->idev->cnf.rtr_solicits != 0 &&
4152                   (dev->flags & IFF_LOOPBACK) == 0 &&
4153                   (dev->type != ARPHRD_TUNNEL);
4154         read_unlock_bh(&ifp->idev->lock);
4155
4156         /* While dad is in progress mld report's source address is in6_addrany.
4157          * Resend with proper ll now.
4158          */
4159         if (send_mld)
4160                 ipv6_mc_dad_complete(ifp->idev);
4161
4162         /* send unsolicited NA if enabled */
4163         if (send_na &&
4164             (ifp->idev->cnf.ndisc_notify ||
4165              dev_net(dev)->ipv6.devconf_all->ndisc_notify)) {
4166                 ndisc_send_na(dev, &in6addr_linklocal_allnodes, &ifp->addr,
4167                               /*router=*/ !!ifp->idev->cnf.forwarding,
4168                               /*solicited=*/ false, /*override=*/ true,
4169                               /*inc_opt=*/ true);
4170         }
4171
4172         if (send_rs) {
4173                 /*
4174                  *      If a host as already performed a random delay
4175                  *      [...] as part of DAD [...] there is no need
4176                  *      to delay again before sending the first RS
4177                  */
4178                 if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE))
4179                         return;
4180                 ndisc_send_rs(dev, &lladdr, &in6addr_linklocal_allrouters);
4181
4182                 write_lock_bh(&ifp->idev->lock);
4183                 spin_lock(&ifp->lock);
4184                 ifp->idev->rs_interval = rfc3315_s14_backoff_init(
4185                         ifp->idev->cnf.rtr_solicit_interval);
4186                 ifp->idev->rs_probes = 1;
4187                 ifp->idev->if_flags |= IF_RS_SENT;
4188                 addrconf_mod_rs_timer(ifp->idev, ifp->idev->rs_interval);
4189                 spin_unlock(&ifp->lock);
4190                 write_unlock_bh(&ifp->idev->lock);
4191         }
4192
4193         if (bump_id)
4194                 rt_genid_bump_ipv6(dev_net(dev));
4195
4196         /* Make sure that a new temporary address will be created
4197          * before this temporary address becomes deprecated.
4198          */
4199         if (ifp->flags & IFA_F_TEMPORARY)
4200                 addrconf_verify_rtnl();
4201 }
4202
4203 static void addrconf_dad_run(struct inet6_dev *idev, bool restart)
4204 {
4205         struct inet6_ifaddr *ifp;
4206
4207         read_lock_bh(&idev->lock);
4208         list_for_each_entry(ifp, &idev->addr_list, if_list) {
4209                 spin_lock(&ifp->lock);
4210                 if ((ifp->flags & IFA_F_TENTATIVE &&
4211                      ifp->state == INET6_IFADDR_STATE_DAD) || restart) {
4212                         if (restart)
4213                                 ifp->state = INET6_IFADDR_STATE_PREDAD;
4214                         addrconf_dad_kick(ifp);
4215                 }
4216                 spin_unlock(&ifp->lock);
4217         }
4218         read_unlock_bh(&idev->lock);
4219 }
4220
4221 #ifdef CONFIG_PROC_FS
4222 struct if6_iter_state {
4223         struct seq_net_private p;
4224         int bucket;
4225         int offset;
4226 };
4227
4228 static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos)
4229 {
4230         struct if6_iter_state *state = seq->private;
4231         struct net *net = seq_file_net(seq);
4232         struct inet6_ifaddr *ifa = NULL;
4233         int p = 0;
4234
4235         /* initial bucket if pos is 0 */
4236         if (pos == 0) {
4237                 state->bucket = 0;
4238                 state->offset = 0;
4239         }
4240
4241         for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) {
4242                 hlist_for_each_entry_rcu(ifa, &inet6_addr_lst[state->bucket],
4243                                          addr_lst) {
4244                         if (!net_eq(dev_net(ifa->idev->dev), net))
4245                                 continue;
4246                         /* sync with offset */
4247                         if (p < state->offset) {
4248                                 p++;
4249                                 continue;
4250                         }
4251                         return ifa;
4252                 }
4253
4254                 /* prepare for next bucket */
4255                 state->offset = 0;
4256                 p = 0;
4257         }
4258         return NULL;
4259 }
4260
4261 static struct inet6_ifaddr *if6_get_next(struct seq_file *seq,
4262                                          struct inet6_ifaddr *ifa)
4263 {
4264         struct if6_iter_state *state = seq->private;
4265         struct net *net = seq_file_net(seq);
4266
4267         hlist_for_each_entry_continue_rcu(ifa, addr_lst) {
4268                 if (!net_eq(dev_net(ifa->idev->dev), net))
4269                         continue;
4270                 state->offset++;
4271                 return ifa;
4272         }
4273
4274         state->offset = 0;
4275         while (++state->bucket < IN6_ADDR_HSIZE) {
4276                 hlist_for_each_entry_rcu(ifa,
4277                                      &inet6_addr_lst[state->bucket], addr_lst) {
4278                         if (!net_eq(dev_net(ifa->idev->dev), net))
4279                                 continue;
4280                         return ifa;
4281                 }
4282         }
4283
4284         return NULL;
4285 }
4286
4287 static void *if6_seq_start(struct seq_file *seq, loff_t *pos)
4288         __acquires(rcu)
4289 {
4290         rcu_read_lock();
4291         return if6_get_first(seq, *pos);
4292 }
4293
4294 static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4295 {
4296         struct inet6_ifaddr *ifa;
4297
4298         ifa = if6_get_next(seq, v);
4299         ++*pos;
4300         return ifa;
4301 }
4302
4303 static void if6_seq_stop(struct seq_file *seq, void *v)
4304         __releases(rcu)
4305 {
4306         rcu_read_unlock();
4307 }
4308
4309 static int if6_seq_show(struct seq_file *seq, void *v)
4310 {
4311         struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v;
4312         seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n",
4313                    &ifp->addr,
4314                    ifp->idev->dev->ifindex,
4315                    ifp->prefix_len,
4316                    ifp->scope,
4317                    (u8) ifp->flags,
4318                    ifp->idev->dev->name);
4319         return 0;
4320 }
4321
4322 static const struct seq_operations if6_seq_ops = {
4323         .start  = if6_seq_start,
4324         .next   = if6_seq_next,
4325         .show   = if6_seq_show,
4326         .stop   = if6_seq_stop,
4327 };
4328
4329 static int __net_init if6_proc_net_init(struct net *net)
4330 {
4331         if (!proc_create_net("if_inet6", 0444, net->proc_net, &if6_seq_ops,
4332                         sizeof(struct if6_iter_state)))
4333                 return -ENOMEM;
4334         return 0;
4335 }
4336
4337 static void __net_exit if6_proc_net_exit(struct net *net)
4338 {
4339         remove_proc_entry("if_inet6", net->proc_net);
4340 }
4341
4342 static struct pernet_operations if6_proc_net_ops = {
4343         .init = if6_proc_net_init,
4344         .exit = if6_proc_net_exit,
4345 };
4346
4347 int __init if6_proc_init(void)
4348 {
4349         return register_pernet_subsys(&if6_proc_net_ops);
4350 }
4351
4352 void if6_proc_exit(void)
4353 {
4354         unregister_pernet_subsys(&if6_proc_net_ops);
4355 }
4356 #endif  /* CONFIG_PROC_FS */
4357
4358 #if IS_ENABLED(CONFIG_IPV6_MIP6)
4359 /* Check if address is a home address configured on any interface. */
4360 int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr)
4361 {
4362         unsigned int hash = inet6_addr_hash(net, addr);
4363         struct inet6_ifaddr *ifp = NULL;
4364         int ret = 0;
4365
4366         rcu_read_lock();
4367         hlist_for_each_entry_rcu(ifp, &inet6_addr_lst[hash], addr_lst) {
4368                 if (!net_eq(dev_net(ifp->idev->dev), net))
4369                         continue;
4370                 if (ipv6_addr_equal(&ifp->addr, addr) &&
4371                     (ifp->flags & IFA_F_HOMEADDRESS)) {
4372                         ret = 1;
4373                         break;
4374                 }
4375         }
4376         rcu_read_unlock();
4377         return ret;
4378 }
4379 #endif
4380
4381 /*
4382  *      Periodic address status verification
4383  */
4384
4385 static void addrconf_verify_rtnl(void)
4386 {
4387         unsigned long now, next, next_sec, next_sched;
4388         struct inet6_ifaddr *ifp;
4389         int i;
4390
4391         ASSERT_RTNL();
4392
4393         rcu_read_lock_bh();
4394         now = jiffies;
4395         next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY);
4396
4397         cancel_delayed_work(&addr_chk_work);
4398
4399         for (i = 0; i < IN6_ADDR_HSIZE; i++) {
4400 restart:
4401                 hlist_for_each_entry_rcu_bh(ifp, &inet6_addr_lst[i], addr_lst) {
4402                         unsigned long age;
4403
4404                         /* When setting preferred_lft to a value not zero or
4405                          * infinity, while valid_lft is infinity
4406                          * IFA_F_PERMANENT has a non-infinity life time.
4407                          */
4408                         if ((ifp->flags & IFA_F_PERMANENT) &&
4409                             (ifp->prefered_lft == INFINITY_LIFE_TIME))
4410                                 continue;
4411
4412                         spin_lock(&ifp->lock);
4413                         /* We try to batch several events at once. */
4414                         age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ;
4415
4416                         if (ifp->valid_lft != INFINITY_LIFE_TIME &&
4417                             age >= ifp->valid_lft) {
4418                                 spin_unlock(&ifp->lock);
4419                                 in6_ifa_hold(ifp);
4420                                 ipv6_del_addr(ifp);
4421                                 goto restart;
4422                         } else if (ifp->prefered_lft == INFINITY_LIFE_TIME) {
4423                                 spin_unlock(&ifp->lock);
4424                                 continue;
4425                         } else if (age >= ifp->prefered_lft) {
4426                                 /* jiffies - ifp->tstamp > age >= ifp->prefered_lft */
4427                                 int deprecate = 0;
4428
4429                                 if (!(ifp->flags&IFA_F_DEPRECATED)) {
4430                                         deprecate = 1;
4431                                         ifp->flags |= IFA_F_DEPRECATED;
4432                                 }
4433
4434                                 if ((ifp->valid_lft != INFINITY_LIFE_TIME) &&
4435                                     (time_before(ifp->tstamp + ifp->valid_lft * HZ, next)))
4436                                         next = ifp->tstamp + ifp->valid_lft * HZ;
4437
4438                                 spin_unlock(&ifp->lock);
4439
4440                                 if (deprecate) {
4441                                         in6_ifa_hold(ifp);
4442
4443                                         ipv6_ifa_notify(0, ifp);
4444                                         in6_ifa_put(ifp);
4445                                         goto restart;
4446                                 }
4447                         } else if ((ifp->flags&IFA_F_TEMPORARY) &&
4448                                    !(ifp->flags&IFA_F_TENTATIVE)) {
4449                                 unsigned long regen_advance = ifp->idev->cnf.regen_max_retry *
4450                                         ifp->idev->cnf.dad_transmits *
4451                                         NEIGH_VAR(ifp->idev->nd_parms, RETRANS_TIME) / HZ;
4452
4453                                 if (age >= ifp->prefered_lft - regen_advance) {
4454                                         struct inet6_ifaddr *ifpub = ifp->ifpub;
4455                                         if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
4456                                                 next = ifp->tstamp + ifp->prefered_lft * HZ;
4457                                         if (!ifp->regen_count && ifpub) {
4458                                                 ifp->regen_count++;
4459                                                 in6_ifa_hold(ifp);
4460                                                 in6_ifa_hold(ifpub);
4461                                                 spin_unlock(&ifp->lock);
4462
4463                                                 spin_lock(&ifpub->lock);
4464                                                 ifpub->regen_count = 0;
4465                                                 spin_unlock(&ifpub->lock);
4466                                                 rcu_read_unlock_bh();
4467                                                 ipv6_create_tempaddr(ifpub, ifp, true);
4468                                                 in6_ifa_put(ifpub);
4469                                                 in6_ifa_put(ifp);
4470                                                 rcu_read_lock_bh();
4471                                                 goto restart;
4472                                         }
4473                                 } else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next))
4474                                         next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ;
4475                                 spin_unlock(&ifp->lock);
4476                         } else {
4477                                 /* ifp->prefered_lft <= ifp->valid_lft */
4478                                 if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next))
4479                                         next = ifp->tstamp + ifp->prefered_lft * HZ;
4480                                 spin_unlock(&ifp->lock);
4481                         }
4482                 }
4483         }
4484
4485         next_sec = round_jiffies_up(next);
4486         next_sched = next;
4487
4488         /* If rounded timeout is accurate enough, accept it. */
4489         if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ))
4490                 next_sched = next_sec;
4491
4492         /* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */
4493         if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX))
4494                 next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX;
4495
4496         pr_debug("now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n",
4497                  now, next, next_sec, next_sched);
4498         mod_delayed_work(addrconf_wq, &addr_chk_work, next_sched - now);
4499         rcu_read_unlock_bh();
4500 }
4501
4502 static void addrconf_verify_work(struct work_struct *w)
4503 {
4504         rtnl_lock();
4505         addrconf_verify_rtnl();
4506         rtnl_unlock();
4507 }
4508
4509 static void addrconf_verify(void)
4510 {
4511         mod_delayed_work(addrconf_wq, &addr_chk_work, 0);
4512 }
4513
4514 static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local,
4515                                      struct in6_addr **peer_pfx)
4516 {
4517         struct in6_addr *pfx = NULL;
4518
4519         *peer_pfx = NULL;
4520
4521         if (addr)
4522                 pfx = nla_data(addr);
4523
4524         if (local) {
4525                 if (pfx && nla_memcmp(local, pfx, sizeof(*pfx)))
4526                         *peer_pfx = pfx;
4527                 pfx = nla_data(local);
4528         }
4529
4530         return pfx;
4531 }
4532
4533 static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = {
4534         [IFA_ADDRESS]           = { .len = sizeof(struct in6_addr) },
4535         [IFA_LOCAL]             = { .len = sizeof(struct in6_addr) },
4536         [IFA_CACHEINFO]         = { .len = sizeof(struct ifa_cacheinfo) },
4537         [IFA_FLAGS]             = { .len = sizeof(u32) },
4538         [IFA_RT_PRIORITY]       = { .len = sizeof(u32) },
4539 };
4540
4541 static int
4542 inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh,
4543                   struct netlink_ext_ack *extack)
4544 {
4545         struct net *net = sock_net(skb->sk);
4546         struct ifaddrmsg *ifm;
4547         struct nlattr *tb[IFA_MAX+1];
4548         struct in6_addr *pfx, *peer_pfx;
4549         u32 ifa_flags;
4550         int err;
4551
4552         err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy,
4553                           extack);
4554         if (err < 0)
4555                 return err;
4556
4557         ifm = nlmsg_data(nlh);
4558         pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
4559         if (!pfx)
4560                 return -EINVAL;
4561
4562         ifa_flags = tb[IFA_FLAGS] ? nla_get_u32(tb[IFA_FLAGS]) : ifm->ifa_flags;
4563
4564         /* We ignore other flags so far. */
4565         ifa_flags &= IFA_F_MANAGETEMPADDR;
4566
4567         return inet6_addr_del(net, ifm->ifa_index, ifa_flags, pfx,
4568                               ifm->ifa_prefixlen);
4569 }
4570
4571 static int modify_prefix_route(struct inet6_ifaddr *ifp,
4572                                unsigned long expires, u32 flags,
4573                                bool modify_peer)
4574 {
4575         struct fib6_info *f6i;
4576         u32 prio;
4577
4578         f6i = addrconf_get_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
4579                                         ifp->prefix_len,
4580                                         ifp->idev->dev,
4581                                         0, RTF_GATEWAY | RTF_DEFAULT);
4582         if (!f6i)
4583                 return -ENOENT;
4584
4585         prio = ifp->rt_priority ? : IP6_RT_PRIO_ADDRCONF;
4586         if (f6i->fib6_metric != prio) {
4587                 /* delete old one */
4588                 ip6_del_rt(dev_net(ifp->idev->dev), f6i);
4589
4590                 /* add new one */
4591                 addrconf_prefix_route(modify_peer ? &ifp->peer_addr : &ifp->addr,
4592                                       ifp->prefix_len,
4593                                       ifp->rt_priority, ifp->idev->dev,
4594                                       expires, flags, GFP_KERNEL);
4595         } else {
4596                 if (!expires)
4597                         fib6_clean_expires(f6i);
4598                 else
4599                         fib6_set_expires(f6i, expires);
4600
4601                 fib6_info_release(f6i);
4602         }
4603
4604         return 0;
4605 }
4606
4607 static int inet6_addr_modify(struct inet6_ifaddr *ifp, struct ifa6_config *cfg)
4608 {
4609         u32 flags;
4610         clock_t expires;
4611         unsigned long timeout;
4612         bool was_managetempaddr;
4613         bool had_prefixroute;
4614         bool new_peer = false;
4615
4616         ASSERT_RTNL();
4617
4618         if (!cfg->valid_lft || cfg->preferred_lft > cfg->valid_lft)
4619                 return -EINVAL;
4620
4621         if (cfg->ifa_flags & IFA_F_MANAGETEMPADDR &&
4622             (ifp->flags & IFA_F_TEMPORARY || ifp->prefix_len != 64))
4623                 return -EINVAL;
4624
4625         if (!(ifp->flags & IFA_F_TENTATIVE) || ifp->flags & IFA_F_DADFAILED)
4626                 cfg->ifa_flags &= ~IFA_F_OPTIMISTIC;
4627
4628         timeout = addrconf_timeout_fixup(cfg->valid_lft, HZ);
4629         if (addrconf_finite_timeout(timeout)) {
4630                 expires = jiffies_to_clock_t(timeout * HZ);
4631                 cfg->valid_lft = timeout;
4632                 flags = RTF_EXPIRES;
4633         } else {
4634                 expires = 0;
4635                 flags = 0;
4636                 cfg->ifa_flags |= IFA_F_PERMANENT;
4637         }
4638
4639         timeout = addrconf_timeout_fixup(cfg->preferred_lft, HZ);
4640         if (addrconf_finite_timeout(timeout)) {
4641                 if (timeout == 0)
4642                         cfg->ifa_flags |= IFA_F_DEPRECATED;
4643                 cfg->preferred_lft = timeout;
4644         }
4645
4646         if (cfg->peer_pfx &&
4647             memcmp(&ifp->peer_addr, cfg->peer_pfx, sizeof(struct in6_addr))) {
4648                 if (!ipv6_addr_any(&ifp->peer_addr))
4649                         cleanup_prefix_route(ifp, expires, true, true);
4650                 new_peer = true;
4651         }
4652
4653         spin_lock_bh(&ifp->lock);
4654         was_managetempaddr = ifp->flags & IFA_F_MANAGETEMPADDR;
4655         had_prefixroute = ifp->flags & IFA_F_PERMANENT &&
4656                           !(ifp->flags & IFA_F_NOPREFIXROUTE);
4657         ifp->flags &= ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD |
4658                         IFA_F_HOMEADDRESS | IFA_F_MANAGETEMPADDR |
4659                         IFA_F_NOPREFIXROUTE);
4660         ifp->flags |= cfg->ifa_flags;
4661         ifp->tstamp = jiffies;
4662         ifp->valid_lft = cfg->valid_lft;
4663         ifp->prefered_lft = cfg->preferred_lft;
4664
4665         if (cfg->rt_priority && cfg->rt_priority != ifp->rt_priority)
4666                 ifp->rt_priority = cfg->rt_priority;
4667
4668         if (new_peer)
4669                 ifp->peer_addr = *cfg->peer_pfx;
4670
4671         spin_unlock_bh(&ifp->lock);
4672         if (!(ifp->flags&IFA_F_TENTATIVE))
4673                 ipv6_ifa_notify(0, ifp);
4674
4675         if (!(cfg->ifa_flags & IFA_F_NOPREFIXROUTE)) {
4676                 int rc = -ENOENT;
4677
4678                 if (had_prefixroute)
4679                         rc = modify_prefix_route(ifp, expires, flags, false);
4680
4681                 /* prefix route could have been deleted; if so restore it */
4682                 if (rc == -ENOENT) {
4683                         addrconf_prefix_route(&ifp->addr, ifp->prefix_len,
4684                                               ifp->rt_priority, ifp->idev->dev,
4685                                               expires, flags, GFP_KERNEL);
4686                 }
4687
4688                 if (had_prefixroute && !ipv6_addr_any(&ifp->peer_addr))
4689                         rc = modify_prefix_route(ifp, expires, flags, true);
4690
4691                 if (rc == -ENOENT && !ipv6_addr_any(&ifp->peer_addr)) {
4692                         addrconf_prefix_route(&ifp->peer_addr, ifp->prefix_len,
4693                                               ifp->rt_priority, ifp->idev->dev,
4694                                               expires, flags, GFP_KERNEL);
4695                 }
4696         } else if (had_prefixroute) {
4697                 enum cleanup_prefix_rt_t action;
4698                 unsigned long rt_expires;
4699
4700                 write_lock_bh(&ifp->idev->lock);
4701                 action = check_cleanup_prefix_route(ifp, &rt_expires);
4702                 write_unlock_bh(&ifp->idev->lock);
4703
4704                 if (action != CLEANUP_PREFIX_RT_NOP) {
4705                         cleanup_prefix_route(ifp, rt_expires,
4706                                 action == CLEANUP_PREFIX_RT_DEL, false);
4707                 }
4708         }
4709
4710         if (was_managetempaddr || ifp->flags & IFA_F_MANAGETEMPADDR) {
4711                 if (was_managetempaddr &&
4712                     !(ifp->flags & IFA_F_MANAGETEMPADDR)) {
4713                         cfg->valid_lft = 0;
4714                         cfg->preferred_lft = 0;
4715                 }
4716                 manage_tempaddrs(ifp->idev, ifp, cfg->valid_lft,
4717                                  cfg->preferred_lft, !was_managetempaddr,
4718                                  jiffies);
4719         }
4720
4721         addrconf_verify_rtnl();
4722
4723         return 0;
4724 }
4725
4726 static int
4727 inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh,
4728                   struct netlink_ext_ack *extack)
4729 {
4730         struct net *net = sock_net(skb->sk);
4731         struct ifaddrmsg *ifm;
4732         struct nlattr *tb[IFA_MAX+1];
4733         struct in6_addr *peer_pfx;
4734         struct inet6_ifaddr *ifa;
4735         struct net_device *dev;
4736         struct inet6_dev *idev;
4737         struct ifa6_config cfg;
4738         int err;
4739
4740         err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy,
4741                           extack);
4742         if (err < 0)
4743                 return err;
4744
4745         memset(&cfg, 0, sizeof(cfg));
4746
4747         ifm = nlmsg_data(nlh);
4748         cfg.pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer_pfx);
4749         if (!cfg.pfx)
4750                 return -EINVAL;
4751
4752         cfg.peer_pfx = peer_pfx;
4753         cfg.plen = ifm->ifa_prefixlen;
4754         if (tb[IFA_RT_PRIORITY])
4755                 cfg.rt_priority = nla_get_u32(tb[IFA_RT_PRIORITY]);
4756
4757         cfg.valid_lft = INFINITY_LIFE_TIME;
4758         cfg.preferred_lft = INFINITY_LIFE_TIME;
4759
4760         if (tb[IFA_CACHEINFO]) {
4761                 struct ifa_cacheinfo *ci;
4762
4763                 ci = nla_data(tb[IFA_CACHEINFO]);
4764                 cfg.valid_lft = ci->ifa_valid;
4765                 cfg.preferred_lft = ci->ifa_prefered;
4766         }
4767
4768         dev =  __dev_get_by_index(net, ifm->ifa_index);
4769         if (!dev)
4770                 return -ENODEV;
4771
4772         if (tb[IFA_FLAGS])
4773                 cfg.ifa_flags = nla_get_u32(tb[IFA_FLAGS]);
4774         else
4775                 cfg.ifa_flags = ifm->ifa_flags;
4776
4777         /* We ignore other flags so far. */
4778         cfg.ifa_flags &= IFA_F_NODAD | IFA_F_HOMEADDRESS |
4779                          IFA_F_MANAGETEMPADDR | IFA_F_NOPREFIXROUTE |
4780                          IFA_F_MCAUTOJOIN | IFA_F_OPTIMISTIC;
4781
4782         idev = ipv6_find_idev(dev);
4783         if (!idev)
4784                 return -ENOBUFS;
4785
4786         if (!ipv6_allow_optimistic_dad(net, idev))
4787                 cfg.ifa_flags &= ~IFA_F_OPTIMISTIC;
4788
4789         if (cfg.ifa_flags & IFA_F_NODAD &&
4790             cfg.ifa_flags & IFA_F_OPTIMISTIC) {
4791                 NL_SET_ERR_MSG(extack, "IFA_F_NODAD and IFA_F_OPTIMISTIC are mutually exclusive");
4792                 return -EINVAL;
4793         }
4794
4795         ifa = ipv6_get_ifaddr(net, cfg.pfx, dev, 1);
4796         if (!ifa) {
4797                 /*
4798                  * It would be best to check for !NLM_F_CREATE here but
4799                  * userspace already relies on not having to provide this.
4800                  */
4801                 return inet6_addr_add(net, ifm->ifa_index, &cfg, extack);
4802         }
4803
4804         if (nlh->nlmsg_flags & NLM_F_EXCL ||
4805             !(nlh->nlmsg_flags & NLM_F_REPLACE))
4806                 err = -EEXIST;
4807         else
4808                 err = inet6_addr_modify(ifa, &cfg);
4809
4810         in6_ifa_put(ifa);
4811
4812         return err;
4813 }
4814
4815 static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u32 flags,
4816                           u8 scope, int ifindex)
4817 {
4818         struct ifaddrmsg *ifm;
4819
4820         ifm = nlmsg_data(nlh);
4821         ifm->ifa_family = AF_INET6;
4822         ifm->ifa_prefixlen = prefixlen;
4823         ifm->ifa_flags = flags;
4824         ifm->ifa_scope = scope;
4825         ifm->ifa_index = ifindex;
4826 }
4827
4828 static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp,
4829                          unsigned long tstamp, u32 preferred, u32 valid)
4830 {
4831         struct ifa_cacheinfo ci;
4832
4833         ci.cstamp = cstamp_delta(cstamp);
4834         ci.tstamp = cstamp_delta(tstamp);
4835         ci.ifa_prefered = preferred;
4836         ci.ifa_valid = valid;
4837
4838         return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci);
4839 }
4840
4841 static inline int rt_scope(int ifa_scope)
4842 {
4843         if (ifa_scope & IFA_HOST)
4844                 return RT_SCOPE_HOST;
4845         else if (ifa_scope & IFA_LINK)
4846                 return RT_SCOPE_LINK;
4847         else if (ifa_scope & IFA_SITE)
4848                 return RT_SCOPE_SITE;
4849         else
4850                 return RT_SCOPE_UNIVERSE;
4851 }
4852
4853 static inline int inet6_ifaddr_msgsize(void)
4854 {
4855         return NLMSG_ALIGN(sizeof(struct ifaddrmsg))
4856                + nla_total_size(16) /* IFA_LOCAL */
4857                + nla_total_size(16) /* IFA_ADDRESS */
4858                + nla_total_size(sizeof(struct ifa_cacheinfo))
4859                + nla_total_size(4)  /* IFA_FLAGS */
4860                + nla_total_size(4)  /* IFA_RT_PRIORITY */;
4861 }
4862
4863 static int inet6_fill_ifaddr(struct sk_buff *skb, struct inet6_ifaddr *ifa,
4864                              u32 portid, u32 seq, int event, unsigned int flags)
4865 {
4866         struct nlmsghdr  *nlh;
4867         u32 preferred, valid;
4868
4869         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
4870         if (!nlh)
4871                 return -EMSGSIZE;
4872
4873         put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope),
4874                       ifa->idev->dev->ifindex);
4875
4876         if (!((ifa->flags&IFA_F_PERMANENT) &&
4877               (ifa->prefered_lft == INFINITY_LIFE_TIME))) {
4878                 preferred = ifa->prefered_lft;
4879                 valid = ifa->valid_lft;
4880                 if (preferred != INFINITY_LIFE_TIME) {
4881                         long tval = (jiffies - ifa->tstamp)/HZ;
4882                         if (preferred > tval)
4883                                 preferred -= tval;
4884                         else
4885                                 preferred = 0;
4886                         if (valid != INFINITY_LIFE_TIME) {
4887                                 if (valid > tval)
4888                                         valid -= tval;
4889                                 else
4890                                         valid = 0;
4891                         }
4892                 }
4893         } else {
4894                 preferred = INFINITY_LIFE_TIME;
4895                 valid = INFINITY_LIFE_TIME;
4896         }
4897
4898         if (!ipv6_addr_any(&ifa->peer_addr)) {
4899                 if (nla_put_in6_addr(skb, IFA_LOCAL, &ifa->addr) < 0 ||
4900                     nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->peer_addr) < 0)
4901                         goto error;
4902         } else
4903                 if (nla_put_in6_addr(skb, IFA_ADDRESS, &ifa->addr) < 0)
4904                         goto error;
4905
4906         if (ifa->rt_priority &&
4907             nla_put_u32(skb, IFA_RT_PRIORITY, ifa->rt_priority))
4908                 goto error;
4909
4910         if (put_cacheinfo(skb, ifa->cstamp, ifa->tstamp, preferred, valid) < 0)
4911                 goto error;
4912
4913         if (nla_put_u32(skb, IFA_FLAGS, ifa->flags) < 0)
4914                 goto error;
4915
4916         nlmsg_end(skb, nlh);
4917         return 0;
4918
4919 error:
4920         nlmsg_cancel(skb, nlh);
4921         return -EMSGSIZE;
4922 }
4923
4924 static int inet6_fill_ifmcaddr(struct sk_buff *skb, struct ifmcaddr6 *ifmca,
4925                                 u32 portid, u32 seq, int event, u16 flags)
4926 {
4927         struct nlmsghdr  *nlh;
4928         u8 scope = RT_SCOPE_UNIVERSE;
4929         int ifindex = ifmca->idev->dev->ifindex;
4930
4931         if (ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE)
4932                 scope = RT_SCOPE_SITE;
4933
4934         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
4935         if (!nlh)
4936                 return -EMSGSIZE;
4937
4938         put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
4939         if (nla_put_in6_addr(skb, IFA_MULTICAST, &ifmca->mca_addr) < 0 ||
4940             put_cacheinfo(skb, ifmca->mca_cstamp, ifmca->mca_tstamp,
4941                           INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
4942                 nlmsg_cancel(skb, nlh);
4943                 return -EMSGSIZE;
4944         }
4945
4946         nlmsg_end(skb, nlh);
4947         return 0;
4948 }
4949
4950 static int inet6_fill_ifacaddr(struct sk_buff *skb, struct ifacaddr6 *ifaca,
4951                                 u32 portid, u32 seq, int event, unsigned int flags)
4952 {
4953         struct net_device *dev = fib6_info_nh_dev(ifaca->aca_rt);
4954         int ifindex = dev ? dev->ifindex : 1;
4955         struct nlmsghdr  *nlh;
4956         u8 scope = RT_SCOPE_UNIVERSE;
4957
4958         if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE)
4959                 scope = RT_SCOPE_SITE;
4960
4961         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct ifaddrmsg), flags);
4962         if (!nlh)
4963                 return -EMSGSIZE;
4964
4965         put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex);
4966         if (nla_put_in6_addr(skb, IFA_ANYCAST, &ifaca->aca_addr) < 0 ||
4967             put_cacheinfo(skb, ifaca->aca_cstamp, ifaca->aca_tstamp,
4968                           INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) {
4969                 nlmsg_cancel(skb, nlh);
4970                 return -EMSGSIZE;
4971         }
4972
4973         nlmsg_end(skb, nlh);
4974         return 0;
4975 }
4976
4977 enum addr_type_t {
4978         UNICAST_ADDR,
4979         MULTICAST_ADDR,
4980         ANYCAST_ADDR,
4981 };
4982
4983 /* called with rcu_read_lock() */
4984 static int in6_dump_addrs(struct inet6_dev *idev, struct sk_buff *skb,
4985                           struct netlink_callback *cb, enum addr_type_t type,
4986                           int s_ip_idx, int *p_ip_idx)
4987 {
4988         struct ifmcaddr6 *ifmca;
4989         struct ifacaddr6 *ifaca;
4990         int err = 1;
4991         int ip_idx = *p_ip_idx;
4992
4993         read_lock_bh(&idev->lock);
4994         switch (type) {
4995         case UNICAST_ADDR: {
4996                 struct inet6_ifaddr *ifa;
4997
4998                 /* unicast address incl. temp addr */
4999                 list_for_each_entry(ifa, &idev->addr_list, if_list) {
5000                         if (ip_idx < s_ip_idx)
5001                                 goto next;
5002                         err = inet6_fill_ifaddr(skb, ifa,
5003                                                 NETLINK_CB(cb->skb).portid,
5004                                                 cb->nlh->nlmsg_seq,
5005                                                 RTM_NEWADDR,
5006                                                 NLM_F_MULTI);
5007                         if (err < 0)
5008                                 break;
5009                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5010 next:
5011                         ip_idx++;
5012                 }
5013                 break;
5014         }
5015         case MULTICAST_ADDR:
5016                 /* multicast address */
5017                 for (ifmca = idev->mc_list; ifmca;
5018                      ifmca = ifmca->next, ip_idx++) {
5019                         if (ip_idx < s_ip_idx)
5020                                 continue;
5021                         err = inet6_fill_ifmcaddr(skb, ifmca,
5022                                                   NETLINK_CB(cb->skb).portid,
5023                                                   cb->nlh->nlmsg_seq,
5024                                                   RTM_GETMULTICAST,
5025                                                   NLM_F_MULTI);
5026                         if (err < 0)
5027                                 break;
5028                 }
5029                 break;
5030         case ANYCAST_ADDR:
5031                 /* anycast address */
5032                 for (ifaca = idev->ac_list; ifaca;
5033                      ifaca = ifaca->aca_next, ip_idx++) {
5034                         if (ip_idx < s_ip_idx)
5035                                 continue;
5036                         err = inet6_fill_ifacaddr(skb, ifaca,
5037                                                   NETLINK_CB(cb->skb).portid,
5038                                                   cb->nlh->nlmsg_seq,
5039                                                   RTM_GETANYCAST,
5040                                                   NLM_F_MULTI);
5041                         if (err < 0)
5042                                 break;
5043                 }
5044                 break;
5045         default:
5046                 break;
5047         }
5048         read_unlock_bh(&idev->lock);
5049         *p_ip_idx = ip_idx;
5050         return err;
5051 }
5052
5053 static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb,
5054                            enum addr_type_t type)
5055 {
5056         struct net *net = sock_net(skb->sk);
5057         int h, s_h;
5058         int idx, ip_idx;
5059         int s_idx, s_ip_idx;
5060         struct net_device *dev;
5061         struct inet6_dev *idev;
5062         struct hlist_head *head;
5063
5064         s_h = cb->args[0];
5065         s_idx = idx = cb->args[1];
5066         s_ip_idx = ip_idx = cb->args[2];
5067
5068         rcu_read_lock();
5069         cb->seq = atomic_read(&net->ipv6.dev_addr_genid) ^ net->dev_base_seq;
5070         for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
5071                 idx = 0;
5072                 head = &net->dev_index_head[h];
5073                 hlist_for_each_entry_rcu(dev, head, index_hlist) {
5074                         if (idx < s_idx)
5075                                 goto cont;
5076                         if (h > s_h || idx > s_idx)
5077                                 s_ip_idx = 0;
5078                         ip_idx = 0;
5079                         idev = __in6_dev_get(dev);
5080                         if (!idev)
5081                                 goto cont;
5082
5083                         if (in6_dump_addrs(idev, skb, cb, type,
5084                                            s_ip_idx, &ip_idx) < 0)
5085                                 goto done;
5086 cont:
5087                         idx++;
5088                 }
5089         }
5090 done:
5091         rcu_read_unlock();
5092         cb->args[0] = h;
5093         cb->args[1] = idx;
5094         cb->args[2] = ip_idx;
5095
5096         return skb->len;
5097 }
5098
5099 static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb)
5100 {
5101         enum addr_type_t type = UNICAST_ADDR;
5102
5103         return inet6_dump_addr(skb, cb, type);
5104 }
5105
5106 static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb)
5107 {
5108         enum addr_type_t type = MULTICAST_ADDR;
5109
5110         return inet6_dump_addr(skb, cb, type);
5111 }
5112
5113
5114 static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb)
5115 {
5116         enum addr_type_t type = ANYCAST_ADDR;
5117
5118         return inet6_dump_addr(skb, cb, type);
5119 }
5120
5121 static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr *nlh,
5122                              struct netlink_ext_ack *extack)
5123 {
5124         struct net *net = sock_net(in_skb->sk);
5125         struct ifaddrmsg *ifm;
5126         struct nlattr *tb[IFA_MAX+1];
5127         struct in6_addr *addr = NULL, *peer;
5128         struct net_device *dev = NULL;
5129         struct inet6_ifaddr *ifa;
5130         struct sk_buff *skb;
5131         int err;
5132
5133         err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy,
5134                           extack);
5135         if (err < 0)
5136                 return err;
5137
5138         addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL], &peer);
5139         if (!addr)
5140                 return -EINVAL;
5141
5142         ifm = nlmsg_data(nlh);
5143         if (ifm->ifa_index)
5144                 dev = dev_get_by_index(net, ifm->ifa_index);
5145
5146         ifa = ipv6_get_ifaddr(net, addr, dev, 1);
5147         if (!ifa) {
5148                 err = -EADDRNOTAVAIL;
5149                 goto errout;
5150         }
5151
5152         skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL);
5153         if (!skb) {
5154                 err = -ENOBUFS;
5155                 goto errout_ifa;
5156         }
5157
5158         err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(in_skb).portid,
5159                                 nlh->nlmsg_seq, RTM_NEWADDR, 0);
5160         if (err < 0) {
5161                 /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
5162                 WARN_ON(err == -EMSGSIZE);
5163                 kfree_skb(skb);
5164                 goto errout_ifa;
5165         }
5166         err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
5167 errout_ifa:
5168         in6_ifa_put(ifa);
5169 errout:
5170         if (dev)
5171                 dev_put(dev);
5172         return err;
5173 }
5174
5175 static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa)
5176 {
5177         struct sk_buff *skb;
5178         struct net *net = dev_net(ifa->idev->dev);
5179         int err = -ENOBUFS;
5180
5181         skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC);
5182         if (!skb)
5183                 goto errout;
5184
5185         err = inet6_fill_ifaddr(skb, ifa, 0, 0, event, 0);
5186         if (err < 0) {
5187                 /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */
5188                 WARN_ON(err == -EMSGSIZE);
5189                 kfree_skb(skb);
5190                 goto errout;
5191         }
5192         rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC);
5193         return;
5194 errout:
5195         if (err < 0)
5196                 rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err);
5197 }
5198
5199 static inline void ipv6_store_devconf(struct ipv6_devconf *cnf,
5200                                 __s32 *array, int bytes)
5201 {
5202         BUG_ON(bytes < (DEVCONF_MAX * 4));
5203
5204         memset(array, 0, bytes);
5205         array[DEVCONF_FORWARDING] = cnf->forwarding;
5206         array[DEVCONF_HOPLIMIT] = cnf->hop_limit;
5207         array[DEVCONF_MTU6] = cnf->mtu6;
5208         array[DEVCONF_ACCEPT_RA] = cnf->accept_ra;
5209         array[DEVCONF_ACCEPT_REDIRECTS] = cnf->accept_redirects;
5210         array[DEVCONF_AUTOCONF] = cnf->autoconf;
5211         array[DEVCONF_DAD_TRANSMITS] = cnf->dad_transmits;
5212         array[DEVCONF_RTR_SOLICITS] = cnf->rtr_solicits;
5213         array[DEVCONF_RTR_SOLICIT_INTERVAL] =
5214                 jiffies_to_msecs(cnf->rtr_solicit_interval);
5215         array[DEVCONF_RTR_SOLICIT_MAX_INTERVAL] =
5216                 jiffies_to_msecs(cnf->rtr_solicit_max_interval);
5217         array[DEVCONF_RTR_SOLICIT_DELAY] =
5218                 jiffies_to_msecs(cnf->rtr_solicit_delay);
5219         array[DEVCONF_FORCE_MLD_VERSION] = cnf->force_mld_version;
5220         array[DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL] =
5221                 jiffies_to_msecs(cnf->mldv1_unsolicited_report_interval);
5222         array[DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL] =
5223                 jiffies_to_msecs(cnf->mldv2_unsolicited_report_interval);
5224         array[DEVCONF_USE_TEMPADDR] = cnf->use_tempaddr;
5225         array[DEVCONF_TEMP_VALID_LFT] = cnf->temp_valid_lft;
5226         array[DEVCONF_TEMP_PREFERED_LFT] = cnf->temp_prefered_lft;
5227         array[DEVCONF_REGEN_MAX_RETRY] = cnf->regen_max_retry;
5228         array[DEVCONF_MAX_DESYNC_FACTOR] = cnf->max_desync_factor;
5229         array[DEVCONF_MAX_ADDRESSES] = cnf->max_addresses;
5230         array[DEVCONF_ACCEPT_RA_DEFRTR] = cnf->accept_ra_defrtr;
5231         array[DEVCONF_ACCEPT_RA_MIN_HOP_LIMIT] = cnf->accept_ra_min_hop_limit;
5232         array[DEVCONF_ACCEPT_RA_PINFO] = cnf->accept_ra_pinfo;
5233 #ifdef CONFIG_IPV6_ROUTER_PREF
5234         array[DEVCONF_ACCEPT_RA_RTR_PREF] = cnf->accept_ra_rtr_pref;
5235         array[DEVCONF_RTR_PROBE_INTERVAL] =
5236                 jiffies_to_msecs(cnf->rtr_probe_interval);
5237 #ifdef CONFIG_IPV6_ROUTE_INFO
5238         array[DEVCONF_ACCEPT_RA_RT_INFO_MIN_PLEN] = cnf->accept_ra_rt_info_min_plen;
5239         array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] = cnf->accept_ra_rt_info_max_plen;
5240 #endif
5241 #endif
5242         array[DEVCONF_PROXY_NDP] = cnf->proxy_ndp;
5243         array[DEVCONF_ACCEPT_SOURCE_ROUTE] = cnf->accept_source_route;
5244 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
5245         array[DEVCONF_OPTIMISTIC_DAD] = cnf->optimistic_dad;
5246         array[DEVCONF_USE_OPTIMISTIC] = cnf->use_optimistic;
5247 #endif
5248 #ifdef CONFIG_IPV6_MROUTE
5249         array[DEVCONF_MC_FORWARDING] = cnf->mc_forwarding;
5250 #endif
5251         array[DEVCONF_DISABLE_IPV6] = cnf->disable_ipv6;
5252         array[DEVCONF_ACCEPT_DAD] = cnf->accept_dad;
5253         array[DEVCONF_FORCE_TLLAO] = cnf->force_tllao;
5254         array[DEVCONF_NDISC_NOTIFY] = cnf->ndisc_notify;
5255         array[DEVCONF_SUPPRESS_FRAG_NDISC] = cnf->suppress_frag_ndisc;
5256         array[DEVCONF_ACCEPT_RA_FROM_LOCAL] = cnf->accept_ra_from_local;
5257         array[DEVCONF_ACCEPT_RA_MTU] = cnf->accept_ra_mtu;
5258         array[DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN] = cnf->ignore_routes_with_linkdown;
5259         /* we omit DEVCONF_STABLE_SECRET for now */
5260         array[DEVCONF_USE_OIF_ADDRS_ONLY] = cnf->use_oif_addrs_only;
5261         array[DEVCONF_DROP_UNICAST_IN_L2_MULTICAST] = cnf->drop_unicast_in_l2_multicast;
5262         array[DEVCONF_DROP_UNSOLICITED_NA] = cnf->drop_unsolicited_na;
5263         array[DEVCONF_KEEP_ADDR_ON_DOWN] = cnf->keep_addr_on_down;
5264         array[DEVCONF_SEG6_ENABLED] = cnf->seg6_enabled;
5265 #ifdef CONFIG_IPV6_SEG6_HMAC
5266         array[DEVCONF_SEG6_REQUIRE_HMAC] = cnf->seg6_require_hmac;
5267 #endif
5268         array[DEVCONF_ENHANCED_DAD] = cnf->enhanced_dad;
5269         array[DEVCONF_ADDR_GEN_MODE] = cnf->addr_gen_mode;
5270         array[DEVCONF_DISABLE_POLICY] = cnf->disable_policy;
5271         array[DEVCONF_NDISC_TCLASS] = cnf->ndisc_tclass;
5272 }
5273
5274 static inline size_t inet6_ifla6_size(void)
5275 {
5276         return nla_total_size(4) /* IFLA_INET6_FLAGS */
5277              + nla_total_size(sizeof(struct ifla_cacheinfo))
5278              + nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */
5279              + nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */
5280              + nla_total_size(ICMP6_MIB_MAX * 8) /* IFLA_INET6_ICMP6STATS */
5281              + nla_total_size(sizeof(struct in6_addr)) /* IFLA_INET6_TOKEN */
5282              + nla_total_size(1) /* IFLA_INET6_ADDR_GEN_MODE */
5283              + 0;
5284 }
5285
5286 static inline size_t inet6_if_nlmsg_size(void)
5287 {
5288         return NLMSG_ALIGN(sizeof(struct ifinfomsg))
5289                + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */
5290                + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */
5291                + nla_total_size(4) /* IFLA_MTU */
5292                + nla_total_size(4) /* IFLA_LINK */
5293                + nla_total_size(1) /* IFLA_OPERSTATE */
5294                + nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */
5295 }
5296
5297 static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib,
5298                                         int bytes)
5299 {
5300         int i;
5301         int pad = bytes - sizeof(u64) * ICMP6_MIB_MAX;
5302         BUG_ON(pad < 0);
5303
5304         /* Use put_unaligned() because stats may not be aligned for u64. */
5305         put_unaligned(ICMP6_MIB_MAX, &stats[0]);
5306         for (i = 1; i < ICMP6_MIB_MAX; i++)
5307                 put_unaligned(atomic_long_read(&mib[i]), &stats[i]);
5308
5309         memset(&stats[ICMP6_MIB_MAX], 0, pad);
5310 }
5311
5312 static inline void __snmp6_fill_stats64(u64 *stats, void __percpu *mib,
5313                                         int bytes, size_t syncpoff)
5314 {
5315         int i, c;
5316         u64 buff[IPSTATS_MIB_MAX];
5317         int pad = bytes - sizeof(u64) * IPSTATS_MIB_MAX;
5318
5319         BUG_ON(pad < 0);
5320
5321         memset(buff, 0, sizeof(buff));
5322         buff[0] = IPSTATS_MIB_MAX;
5323
5324         for_each_possible_cpu(c) {
5325                 for (i = 1; i < IPSTATS_MIB_MAX; i++)
5326                         buff[i] += snmp_get_cpu_field64(mib, c, i, syncpoff);
5327         }
5328
5329         memcpy(stats, buff, IPSTATS_MIB_MAX * sizeof(u64));
5330         memset(&stats[IPSTATS_MIB_MAX], 0, pad);
5331 }
5332
5333 static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype,
5334                              int bytes)
5335 {
5336         switch (attrtype) {
5337         case IFLA_INET6_STATS:
5338                 __snmp6_fill_stats64(stats, idev->stats.ipv6, bytes,
5339                                      offsetof(struct ipstats_mib, syncp));
5340                 break;
5341         case IFLA_INET6_ICMP6STATS:
5342                 __snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, bytes);
5343                 break;
5344         }
5345 }
5346
5347 static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev,
5348                                   u32 ext_filter_mask)
5349 {
5350         struct nlattr *nla;
5351         struct ifla_cacheinfo ci;
5352
5353         if (nla_put_u32(skb, IFLA_INET6_FLAGS, idev->if_flags))
5354                 goto nla_put_failure;
5355         ci.max_reasm_len = IPV6_MAXPLEN;
5356         ci.tstamp = cstamp_delta(idev->tstamp);
5357         ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time);
5358         ci.retrans_time = jiffies_to_msecs(NEIGH_VAR(idev->nd_parms, RETRANS_TIME));
5359         if (nla_put(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci))
5360                 goto nla_put_failure;
5361         nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32));
5362         if (!nla)
5363                 goto nla_put_failure;
5364         ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla));
5365
5366         /* XXX - MC not implemented */
5367
5368         if (ext_filter_mask & RTEXT_FILTER_SKIP_STATS)
5369                 return 0;
5370
5371         nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64));
5372         if (!nla)
5373                 goto nla_put_failure;
5374         snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla));
5375
5376         nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64));
5377         if (!nla)
5378                 goto nla_put_failure;
5379         snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla));
5380
5381         nla = nla_reserve(skb, IFLA_INET6_TOKEN, sizeof(struct in6_addr));
5382         if (!nla)
5383                 goto nla_put_failure;
5384
5385         if (nla_put_u8(skb, IFLA_INET6_ADDR_GEN_MODE, idev->cnf.addr_gen_mode))
5386                 goto nla_put_failure;
5387
5388         read_lock_bh(&idev->lock);
5389         memcpy(nla_data(nla), idev->token.s6_addr, nla_len(nla));
5390         read_unlock_bh(&idev->lock);
5391
5392         return 0;
5393
5394 nla_put_failure:
5395         return -EMSGSIZE;
5396 }
5397
5398 static size_t inet6_get_link_af_size(const struct net_device *dev,
5399                                      u32 ext_filter_mask)
5400 {
5401         if (!__in6_dev_get(dev))
5402                 return 0;
5403
5404         return inet6_ifla6_size();
5405 }
5406
5407 static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev,
5408                               u32 ext_filter_mask)
5409 {
5410         struct inet6_dev *idev = __in6_dev_get(dev);
5411
5412         if (!idev)
5413                 return -ENODATA;
5414
5415         if (inet6_fill_ifla6_attrs(skb, idev, ext_filter_mask) < 0)
5416                 return -EMSGSIZE;
5417
5418         return 0;
5419 }
5420
5421 static int inet6_set_iftoken(struct inet6_dev *idev, struct in6_addr *token)
5422 {
5423         struct inet6_ifaddr *ifp;
5424         struct net_device *dev = idev->dev;
5425         bool clear_token, update_rs = false;
5426         struct in6_addr ll_addr;
5427
5428         ASSERT_RTNL();
5429
5430         if (!token)
5431                 return -EINVAL;
5432         if (dev->flags & (IFF_LOOPBACK | IFF_NOARP))
5433                 return -EINVAL;
5434         if (!ipv6_accept_ra(idev))
5435                 return -EINVAL;
5436         if (idev->cnf.rtr_solicits == 0)
5437                 return -EINVAL;
5438
5439         write_lock_bh(&idev->lock);
5440
5441         BUILD_BUG_ON(sizeof(token->s6_addr) != 16);
5442         memcpy(idev->token.s6_addr + 8, token->s6_addr + 8, 8);
5443
5444         write_unlock_bh(&idev->lock);
5445
5446         clear_token = ipv6_addr_any(token);
5447         if (clear_token)
5448                 goto update_lft;
5449
5450         if (!idev->dead && (idev->if_flags & IF_READY) &&
5451             !ipv6_get_lladdr(dev, &ll_addr, IFA_F_TENTATIVE |
5452                              IFA_F_OPTIMISTIC)) {
5453                 /* If we're not ready, then normal ifup will take care
5454                  * of this. Otherwise, we need to request our rs here.
5455                  */
5456                 ndisc_send_rs(dev, &ll_addr, &in6addr_linklocal_allrouters);
5457                 update_rs = true;
5458         }
5459
5460 update_lft:
5461         write_lock_bh(&idev->lock);
5462
5463         if (update_rs) {
5464                 idev->if_flags |= IF_RS_SENT;
5465                 idev->rs_interval = rfc3315_s14_backoff_init(
5466                         idev->cnf.rtr_solicit_interval);
5467                 idev->rs_probes = 1;
5468                 addrconf_mod_rs_timer(idev, idev->rs_interval);
5469         }
5470
5471         /* Well, that's kinda nasty ... */
5472         list_for_each_entry(ifp, &idev->addr_list, if_list) {
5473                 spin_lock(&ifp->lock);
5474                 if (ifp->tokenized) {
5475                         ifp->valid_lft = 0;
5476                         ifp->prefered_lft = 0;
5477                 }
5478                 spin_unlock(&ifp->lock);
5479         }
5480
5481         write_unlock_bh(&idev->lock);
5482         inet6_ifinfo_notify(RTM_NEWLINK, idev);
5483         addrconf_verify_rtnl();
5484         return 0;
5485 }
5486
5487 static const struct nla_policy inet6_af_policy[IFLA_INET6_MAX + 1] = {
5488         [IFLA_INET6_ADDR_GEN_MODE]      = { .type = NLA_U8 },
5489         [IFLA_INET6_TOKEN]              = { .len = sizeof(struct in6_addr) },
5490 };
5491
5492 static int inet6_validate_link_af(const struct net_device *dev,
5493                                   const struct nlattr *nla)
5494 {
5495         struct nlattr *tb[IFLA_INET6_MAX + 1];
5496
5497         if (dev && !__in6_dev_get(dev))
5498                 return -EAFNOSUPPORT;
5499
5500         return nla_parse_nested(tb, IFLA_INET6_MAX, nla, inet6_af_policy,
5501                                 NULL);
5502 }
5503
5504 static int check_addr_gen_mode(int mode)
5505 {
5506         if (mode != IN6_ADDR_GEN_MODE_EUI64 &&
5507             mode != IN6_ADDR_GEN_MODE_NONE &&
5508             mode != IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
5509             mode != IN6_ADDR_GEN_MODE_RANDOM)
5510                 return -EINVAL;
5511         return 1;
5512 }
5513
5514 static int check_stable_privacy(struct inet6_dev *idev, struct net *net,
5515                                 int mode)
5516 {
5517         if (mode == IN6_ADDR_GEN_MODE_STABLE_PRIVACY &&
5518             !idev->cnf.stable_secret.initialized &&
5519             !net->ipv6.devconf_dflt->stable_secret.initialized)
5520                 return -EINVAL;
5521         return 1;
5522 }
5523
5524 static int inet6_set_link_af(struct net_device *dev, const struct nlattr *nla)
5525 {
5526         int err = -EINVAL;
5527         struct inet6_dev *idev = __in6_dev_get(dev);
5528         struct nlattr *tb[IFLA_INET6_MAX + 1];
5529
5530         if (!idev)
5531                 return -EAFNOSUPPORT;
5532
5533         if (nla_parse_nested(tb, IFLA_INET6_MAX, nla, NULL, NULL) < 0)
5534                 BUG();
5535
5536         if (tb[IFLA_INET6_TOKEN]) {
5537                 err = inet6_set_iftoken(idev, nla_data(tb[IFLA_INET6_TOKEN]));
5538                 if (err)
5539                         return err;
5540         }
5541
5542         if (tb[IFLA_INET6_ADDR_GEN_MODE]) {
5543                 u8 mode = nla_get_u8(tb[IFLA_INET6_ADDR_GEN_MODE]);
5544
5545                 if (check_addr_gen_mode(mode) < 0 ||
5546                     check_stable_privacy(idev, dev_net(dev), mode) < 0)
5547                         return -EINVAL;
5548
5549                 idev->cnf.addr_gen_mode = mode;
5550                 err = 0;
5551         }
5552
5553         return err;
5554 }
5555
5556 static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev,
5557                              u32 portid, u32 seq, int event, unsigned int flags)
5558 {
5559         struct net_device *dev = idev->dev;
5560         struct ifinfomsg *hdr;
5561         struct nlmsghdr *nlh;
5562         void *protoinfo;
5563
5564         nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags);
5565         if (!nlh)
5566                 return -EMSGSIZE;
5567
5568         hdr = nlmsg_data(nlh);
5569         hdr->ifi_family = AF_INET6;
5570         hdr->__ifi_pad = 0;
5571         hdr->ifi_type = dev->type;
5572         hdr->ifi_index = dev->ifindex;
5573         hdr->ifi_flags = dev_get_flags(dev);
5574         hdr->ifi_change = 0;
5575
5576         if (nla_put_string(skb, IFLA_IFNAME, dev->name) ||
5577             (dev->addr_len &&
5578              nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) ||
5579             nla_put_u32(skb, IFLA_MTU, dev->mtu) ||
5580             (dev->ifindex != dev_get_iflink(dev) &&
5581              nla_put_u32(skb, IFLA_LINK, dev_get_iflink(dev))) ||
5582             nla_put_u8(skb, IFLA_OPERSTATE,
5583                        netif_running(dev) ? dev->operstate : IF_OPER_DOWN))
5584                 goto nla_put_failure;
5585         protoinfo = nla_nest_start(skb, IFLA_PROTINFO);
5586         if (!protoinfo)
5587                 goto nla_put_failure;
5588
5589         if (inet6_fill_ifla6_attrs(skb, idev, 0) < 0)
5590                 goto nla_put_failure;
5591
5592         nla_nest_end(skb, protoinfo);
5593         nlmsg_end(skb, nlh);
5594         return 0;
5595
5596 nla_put_failure:
5597         nlmsg_cancel(skb, nlh);
5598         return -EMSGSIZE;
5599 }
5600
5601 static int inet6_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb)
5602 {
5603         struct net *net = sock_net(skb->sk);
5604         int h, s_h;
5605         int idx = 0, s_idx;
5606         struct net_device *dev;
5607         struct inet6_dev *idev;
5608         struct hlist_head *head;
5609
5610         s_h = cb->args[0];
5611         s_idx = cb->args[1];
5612
5613         rcu_read_lock();
5614         for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) {
5615                 idx = 0;
5616                 head = &net->dev_index_head[h];
5617                 hlist_for_each_entry_rcu(dev, head, index_hlist) {
5618                         if (idx < s_idx)
5619                                 goto cont;
5620                         idev = __in6_dev_get(dev);
5621                         if (!idev)
5622                                 goto cont;
5623                         if (inet6_fill_ifinfo(skb, idev,
5624                                               NETLINK_CB(cb->skb).portid,
5625                                               cb->nlh->nlmsg_seq,
5626                                               RTM_NEWLINK, NLM_F_MULTI) < 0)
5627                                 goto out;
5628 cont:
5629                         idx++;
5630                 }
5631         }
5632 out:
5633         rcu_read_unlock();
5634         cb->args[1] = idx;
5635         cb->args[0] = h;
5636
5637         return skb->len;
5638 }
5639
5640 void inet6_ifinfo_notify(int event, struct inet6_dev *idev)
5641 {
5642         struct sk_buff *skb;
5643         struct net *net = dev_net(idev->dev);
5644         int err = -ENOBUFS;
5645
5646         skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC);
5647         if (!skb)
5648                 goto errout;
5649
5650         err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0);
5651         if (err < 0) {
5652                 /* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */
5653                 WARN_ON(err == -EMSGSIZE);
5654                 kfree_skb(skb);
5655                 goto errout;
5656         }
5657         rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC);
5658         return;
5659 errout:
5660         if (err < 0)
5661                 rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err);
5662 }
5663
5664 static inline size_t inet6_prefix_nlmsg_size(void)
5665 {
5666         return NLMSG_ALIGN(sizeof(struct prefixmsg))
5667                + nla_total_size(sizeof(struct in6_addr))
5668                + nla_total_size(sizeof(struct prefix_cacheinfo));
5669 }
5670
5671 static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev,
5672                              struct prefix_info *pinfo, u32 portid, u32 seq,
5673                              int event, unsigned int flags)
5674 {
5675         struct prefixmsg *pmsg;
5676         struct nlmsghdr *nlh;
5677         struct prefix_cacheinfo ci;
5678
5679         nlh = nlmsg_put(skb, portid, seq, event, sizeof(*pmsg), flags);
5680         if (!nlh)
5681                 return -EMSGSIZE;
5682
5683         pmsg = nlmsg_data(nlh);
5684         pmsg->prefix_family = AF_INET6;
5685         pmsg->prefix_pad1 = 0;
5686         pmsg->prefix_pad2 = 0;
5687         pmsg->prefix_ifindex = idev->dev->ifindex;
5688         pmsg->prefix_len = pinfo->prefix_len;
5689         pmsg->prefix_type = pinfo->type;
5690         pmsg->prefix_pad3 = 0;
5691         pmsg->prefix_flags = 0;
5692         if (pinfo->onlink)
5693                 pmsg->prefix_flags |= IF_PREFIX_ONLINK;
5694         if (pinfo->autoconf)
5695                 pmsg->prefix_flags |= IF_PREFIX_AUTOCONF;
5696
5697         if (nla_put(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix))
5698                 goto nla_put_failure;
5699         ci.preferred_time = ntohl(pinfo->prefered);
5700         ci.valid_time = ntohl(pinfo->valid);
5701         if (nla_put(skb, PREFIX_CACHEINFO, sizeof(ci), &ci))
5702                 goto nla_put_failure;
5703         nlmsg_end(skb, nlh);
5704         return 0;
5705
5706 nla_put_failure:
5707         nlmsg_cancel(skb, nlh);
5708         return -EMSGSIZE;
5709 }
5710
5711 static void inet6_prefix_notify(int event, struct inet6_dev *idev,
5712                          struct prefix_info *pinfo)
5713 {
5714         struct sk_buff *skb;
5715         struct net *net = dev_net(idev->dev);
5716         int err = -ENOBUFS;
5717
5718         skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC);
5719         if (!skb)
5720                 goto errout;
5721
5722         err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0);
5723         if (err < 0) {
5724                 /* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */
5725                 WARN_ON(err == -EMSGSIZE);
5726                 kfree_skb(skb);
5727                 goto errout;
5728         }
5729         rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC);
5730         return;
5731 errout:
5732         if (err < 0)
5733                 rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err);
5734 }
5735
5736 static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
5737 {
5738         struct net *net = dev_net(ifp->idev->dev);
5739
5740         if (event)
5741                 ASSERT_RTNL();
5742
5743         inet6_ifa_notify(event ? : RTM_NEWADDR, ifp);
5744
5745         switch (event) {
5746         case RTM_NEWADDR:
5747                 /*
5748                  * If the address was optimistic we inserted the route at the
5749                  * start of our DAD process, so we don't need to do it again.
5750                  * If the device was taken down in the middle of the DAD
5751                  * cycle there is a race where we could get here without a
5752                  * host route, so nothing to insert. That will be fixed when
5753                  * the device is brought up.
5754                  */
5755                 if (ifp->rt && !rcu_access_pointer(ifp->rt->fib6_node)) {
5756                         ip6_ins_rt(net, ifp->rt);
5757                 } else if (!ifp->rt && (ifp->idev->dev->flags & IFF_UP)) {
5758                         pr_warn("BUG: Address %pI6c on device %s is missing its host route.\n",
5759                                 &ifp->addr, ifp->idev->dev->name);
5760                 }
5761
5762                 if (ifp->idev->cnf.forwarding)
5763                         addrconf_join_anycast(ifp);
5764                 if (!ipv6_addr_any(&ifp->peer_addr))
5765                         addrconf_prefix_route(&ifp->peer_addr, 128,
5766                                               ifp->rt_priority, ifp->idev->dev,
5767                                               0, 0, GFP_ATOMIC);
5768                 break;
5769         case RTM_DELADDR:
5770                 if (ifp->idev->cnf.forwarding)
5771                         addrconf_leave_anycast(ifp);
5772                 addrconf_leave_solict(ifp->idev, &ifp->addr);
5773                 if (!ipv6_addr_any(&ifp->peer_addr)) {
5774                         struct fib6_info *rt;
5775
5776                         rt = addrconf_get_prefix_route(&ifp->peer_addr, 128,
5777                                                        ifp->idev->dev, 0, 0);
5778                         if (rt)
5779                                 ip6_del_rt(net, rt);
5780                 }
5781                 if (ifp->rt) {
5782                         ip6_del_rt(net, ifp->rt);
5783                         ifp->rt = NULL;
5784                 }
5785                 rt_genid_bump_ipv6(net);
5786                 break;
5787         }
5788         atomic_inc(&net->ipv6.dev_addr_genid);
5789 }
5790
5791 static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp)
5792 {
5793         rcu_read_lock_bh();
5794         if (likely(ifp->idev->dead == 0))
5795                 __ipv6_ifa_notify(event, ifp);
5796         rcu_read_unlock_bh();
5797 }
5798
5799 #ifdef CONFIG_SYSCTL
5800
5801 static
5802 int addrconf_sysctl_forward(struct ctl_table *ctl, int write,
5803                            void __user *buffer, size_t *lenp, loff_t *ppos)
5804 {
5805         int *valp = ctl->data;
5806         int val = *valp;
5807         loff_t pos = *ppos;
5808         struct ctl_table lctl;
5809         int ret;
5810
5811         /*
5812          * ctl->data points to idev->cnf.forwarding, we should
5813          * not modify it until we get the rtnl lock.
5814          */
5815         lctl = *ctl;
5816         lctl.data = &val;
5817
5818         ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
5819
5820         if (write)
5821                 ret = addrconf_fixup_forwarding(ctl, valp, val);
5822         if (ret)
5823                 *ppos = pos;
5824         return ret;
5825 }
5826
5827 static
5828 int addrconf_sysctl_mtu(struct ctl_table *ctl, int write,
5829                         void __user *buffer, size_t *lenp, loff_t *ppos)
5830 {
5831         struct inet6_dev *idev = ctl->extra1;
5832         int min_mtu = IPV6_MIN_MTU;
5833         struct ctl_table lctl;
5834
5835         lctl = *ctl;
5836         lctl.extra1 = &min_mtu;
5837         lctl.extra2 = idev ? &idev->dev->mtu : NULL;
5838
5839         return proc_dointvec_minmax(&lctl, write, buffer, lenp, ppos);
5840 }
5841
5842 static void dev_disable_change(struct inet6_dev *idev)
5843 {
5844         struct netdev_notifier_info info;
5845
5846         if (!idev || !idev->dev)
5847                 return;
5848
5849         netdev_notifier_info_init(&info, idev->dev);
5850         if (idev->cnf.disable_ipv6)
5851                 addrconf_notify(NULL, NETDEV_DOWN, &info);
5852         else
5853                 addrconf_notify(NULL, NETDEV_UP, &info);
5854 }
5855
5856 static void addrconf_disable_change(struct net *net, __s32 newf)
5857 {
5858         struct net_device *dev;
5859         struct inet6_dev *idev;
5860
5861         for_each_netdev(net, dev) {
5862                 idev = __in6_dev_get(dev);
5863                 if (idev) {
5864                         int changed = (!idev->cnf.disable_ipv6) ^ (!newf);
5865                         idev->cnf.disable_ipv6 = newf;
5866                         if (changed)
5867                                 dev_disable_change(idev);
5868                 }
5869         }
5870 }
5871
5872 static int addrconf_disable_ipv6(struct ctl_table *table, int *p, int newf)
5873 {
5874         struct net *net;
5875         int old;
5876
5877         if (!rtnl_trylock())
5878                 return restart_syscall();
5879
5880         net = (struct net *)table->extra2;
5881         old = *p;
5882         *p = newf;
5883
5884         if (p == &net->ipv6.devconf_dflt->disable_ipv6) {
5885                 rtnl_unlock();
5886                 return 0;
5887         }
5888
5889         if (p == &net->ipv6.devconf_all->disable_ipv6) {
5890                 net->ipv6.devconf_dflt->disable_ipv6 = newf;
5891                 addrconf_disable_change(net, newf);
5892         } else if ((!newf) ^ (!old))
5893                 dev_disable_change((struct inet6_dev *)table->extra1);
5894
5895         rtnl_unlock();
5896         return 0;
5897 }
5898
5899 static
5900 int addrconf_sysctl_disable(struct ctl_table *ctl, int write,
5901                             void __user *buffer, size_t *lenp, loff_t *ppos)
5902 {
5903         int *valp = ctl->data;
5904         int val = *valp;
5905         loff_t pos = *ppos;
5906         struct ctl_table lctl;
5907         int ret;
5908
5909         /*
5910          * ctl->data points to idev->cnf.disable_ipv6, we should
5911          * not modify it until we get the rtnl lock.
5912          */
5913         lctl = *ctl;
5914         lctl.data = &val;
5915
5916         ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
5917
5918         if (write)
5919                 ret = addrconf_disable_ipv6(ctl, valp, val);
5920         if (ret)
5921                 *ppos = pos;
5922         return ret;
5923 }
5924
5925 static
5926 int addrconf_sysctl_proxy_ndp(struct ctl_table *ctl, int write,
5927                               void __user *buffer, size_t *lenp, loff_t *ppos)
5928 {
5929         int *valp = ctl->data;
5930         int ret;
5931         int old, new;
5932
5933         old = *valp;
5934         ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
5935         new = *valp;
5936
5937         if (write && old != new) {
5938                 struct net *net = ctl->extra2;
5939
5940                 if (!rtnl_trylock())
5941                         return restart_syscall();
5942
5943                 if (valp == &net->ipv6.devconf_dflt->proxy_ndp)
5944                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
5945                                                      NETCONFA_PROXY_NEIGH,
5946                                                      NETCONFA_IFINDEX_DEFAULT,
5947                                                      net->ipv6.devconf_dflt);
5948                 else if (valp == &net->ipv6.devconf_all->proxy_ndp)
5949                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
5950                                                      NETCONFA_PROXY_NEIGH,
5951                                                      NETCONFA_IFINDEX_ALL,
5952                                                      net->ipv6.devconf_all);
5953                 else {
5954                         struct inet6_dev *idev = ctl->extra1;
5955
5956                         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF,
5957                                                      NETCONFA_PROXY_NEIGH,
5958                                                      idev->dev->ifindex,
5959                                                      &idev->cnf);
5960                 }
5961                 rtnl_unlock();
5962         }
5963
5964         return ret;
5965 }
5966
5967 static int addrconf_sysctl_addr_gen_mode(struct ctl_table *ctl, int write,
5968                                          void __user *buffer, size_t *lenp,
5969                                          loff_t *ppos)
5970 {
5971         int ret = 0;
5972         u32 new_val;
5973         struct inet6_dev *idev = (struct inet6_dev *)ctl->extra1;
5974         struct net *net = (struct net *)ctl->extra2;
5975         struct ctl_table tmp = {
5976                 .data = &new_val,
5977                 .maxlen = sizeof(new_val),
5978                 .mode = ctl->mode,
5979         };
5980
5981         if (!rtnl_trylock())
5982                 return restart_syscall();
5983
5984         new_val = *((u32 *)ctl->data);
5985
5986         ret = proc_douintvec(&tmp, write, buffer, lenp, ppos);
5987         if (ret != 0)
5988                 goto out;
5989
5990         if (write) {
5991                 if (check_addr_gen_mode(new_val) < 0) {
5992                         ret = -EINVAL;
5993                         goto out;
5994                 }
5995
5996                 if (idev) {
5997                         if (check_stable_privacy(idev, net, new_val) < 0) {
5998                                 ret = -EINVAL;
5999                                 goto out;
6000                         }
6001
6002                         if (idev->cnf.addr_gen_mode != new_val) {
6003                                 idev->cnf.addr_gen_mode = new_val;
6004                                 addrconf_dev_config(idev->dev);
6005                         }
6006                 } else if (&net->ipv6.devconf_all->addr_gen_mode == ctl->data) {
6007                         struct net_device *dev;
6008
6009                         net->ipv6.devconf_dflt->addr_gen_mode = new_val;
6010                         for_each_netdev(net, dev) {
6011                                 idev = __in6_dev_get(dev);
6012                                 if (idev &&
6013                                     idev->cnf.addr_gen_mode != new_val) {
6014                                         idev->cnf.addr_gen_mode = new_val;
6015                                         addrconf_dev_config(idev->dev);
6016                                 }
6017                         }
6018                 }
6019
6020                 *((u32 *)ctl->data) = new_val;
6021         }
6022
6023 out:
6024         rtnl_unlock();
6025
6026         return ret;
6027 }
6028
6029 static int addrconf_sysctl_stable_secret(struct ctl_table *ctl, int write,
6030                                          void __user *buffer, size_t *lenp,
6031                                          loff_t *ppos)
6032 {
6033         int err;
6034         struct in6_addr addr;
6035         char str[IPV6_MAX_STRLEN];
6036         struct ctl_table lctl = *ctl;
6037         struct net *net = ctl->extra2;
6038         struct ipv6_stable_secret *secret = ctl->data;
6039
6040         if (&net->ipv6.devconf_all->stable_secret == ctl->data)
6041                 return -EIO;
6042
6043         lctl.maxlen = IPV6_MAX_STRLEN;
6044         lctl.data = str;
6045
6046         if (!rtnl_trylock())
6047                 return restart_syscall();
6048
6049         if (!write && !secret->initialized) {
6050                 err = -EIO;
6051                 goto out;
6052         }
6053
6054         err = snprintf(str, sizeof(str), "%pI6", &secret->secret);
6055         if (err >= sizeof(str)) {
6056                 err = -EIO;
6057                 goto out;
6058         }
6059
6060         err = proc_dostring(&lctl, write, buffer, lenp, ppos);
6061         if (err || !write)
6062                 goto out;
6063
6064         if (in6_pton(str, -1, addr.in6_u.u6_addr8, -1, NULL) != 1) {
6065                 err = -EIO;
6066                 goto out;
6067         }
6068
6069         secret->initialized = true;
6070         secret->secret = addr;
6071
6072         if (&net->ipv6.devconf_dflt->stable_secret == ctl->data) {
6073                 struct net_device *dev;
6074
6075                 for_each_netdev(net, dev) {
6076                         struct inet6_dev *idev = __in6_dev_get(dev);
6077
6078                         if (idev) {
6079                                 idev->cnf.addr_gen_mode =
6080                                         IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
6081                         }
6082                 }
6083         } else {
6084                 struct inet6_dev *idev = ctl->extra1;
6085
6086                 idev->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_STABLE_PRIVACY;
6087         }
6088
6089 out:
6090         rtnl_unlock();
6091
6092         return err;
6093 }
6094
6095 static
6096 int addrconf_sysctl_ignore_routes_with_linkdown(struct ctl_table *ctl,
6097                                                 int write,
6098                                                 void __user *buffer,
6099                                                 size_t *lenp,
6100                                                 loff_t *ppos)
6101 {
6102         int *valp = ctl->data;
6103         int val = *valp;
6104         loff_t pos = *ppos;
6105         struct ctl_table lctl;
6106         int ret;
6107
6108         /* ctl->data points to idev->cnf.ignore_routes_when_linkdown
6109          * we should not modify it until we get the rtnl lock.
6110          */
6111         lctl = *ctl;
6112         lctl.data = &val;
6113
6114         ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6115
6116         if (write)
6117                 ret = addrconf_fixup_linkdown(ctl, valp, val);
6118         if (ret)
6119                 *ppos = pos;
6120         return ret;
6121 }
6122
6123 static
6124 void addrconf_set_nopolicy(struct rt6_info *rt, int action)
6125 {
6126         if (rt) {
6127                 if (action)
6128                         rt->dst.flags |= DST_NOPOLICY;
6129                 else
6130                         rt->dst.flags &= ~DST_NOPOLICY;
6131         }
6132 }
6133
6134 static
6135 void addrconf_disable_policy_idev(struct inet6_dev *idev, int val)
6136 {
6137         struct inet6_ifaddr *ifa;
6138
6139         read_lock_bh(&idev->lock);
6140         list_for_each_entry(ifa, &idev->addr_list, if_list) {
6141                 spin_lock(&ifa->lock);
6142                 if (ifa->rt) {
6143                         struct fib6_info *rt = ifa->rt;
6144                         int cpu;
6145
6146                         rcu_read_lock();
6147                         ifa->rt->dst_nopolicy = val ? true : false;
6148                         if (rt->rt6i_pcpu) {
6149                                 for_each_possible_cpu(cpu) {
6150                                         struct rt6_info **rtp;
6151
6152                                         rtp = per_cpu_ptr(rt->rt6i_pcpu, cpu);
6153                                         addrconf_set_nopolicy(*rtp, val);
6154                                 }
6155                         }
6156                         rcu_read_unlock();
6157                 }
6158                 spin_unlock(&ifa->lock);
6159         }
6160         read_unlock_bh(&idev->lock);
6161 }
6162
6163 static
6164 int addrconf_disable_policy(struct ctl_table *ctl, int *valp, int val)
6165 {
6166         struct inet6_dev *idev;
6167         struct net *net;
6168
6169         if (!rtnl_trylock())
6170                 return restart_syscall();
6171
6172         *valp = val;
6173
6174         net = (struct net *)ctl->extra2;
6175         if (valp == &net->ipv6.devconf_dflt->disable_policy) {
6176                 rtnl_unlock();
6177                 return 0;
6178         }
6179
6180         if (valp == &net->ipv6.devconf_all->disable_policy)  {
6181                 struct net_device *dev;
6182
6183                 for_each_netdev(net, dev) {
6184                         idev = __in6_dev_get(dev);
6185                         if (idev)
6186                                 addrconf_disable_policy_idev(idev, val);
6187                 }
6188         } else {
6189                 idev = (struct inet6_dev *)ctl->extra1;
6190                 addrconf_disable_policy_idev(idev, val);
6191         }
6192
6193         rtnl_unlock();
6194         return 0;
6195 }
6196
6197 static
6198 int addrconf_sysctl_disable_policy(struct ctl_table *ctl, int write,
6199                                    void __user *buffer, size_t *lenp,
6200                                    loff_t *ppos)
6201 {
6202         int *valp = ctl->data;
6203         int val = *valp;
6204         loff_t pos = *ppos;
6205         struct ctl_table lctl;
6206         int ret;
6207
6208         lctl = *ctl;
6209         lctl.data = &val;
6210         ret = proc_dointvec(&lctl, write, buffer, lenp, ppos);
6211
6212         if (write && (*valp != val))
6213                 ret = addrconf_disable_policy(ctl, valp, val);
6214
6215         if (ret)
6216                 *ppos = pos;
6217
6218         return ret;
6219 }
6220
6221 static int minus_one = -1;
6222 static const int zero = 0;
6223 static const int one = 1;
6224 static const int two_five_five = 255;
6225
6226 static const struct ctl_table addrconf_sysctl[] = {
6227         {
6228                 .procname       = "forwarding",
6229                 .data           = &ipv6_devconf.forwarding,
6230                 .maxlen         = sizeof(int),
6231                 .mode           = 0644,
6232                 .proc_handler   = addrconf_sysctl_forward,
6233         },
6234         {
6235                 .procname       = "hop_limit",
6236                 .data           = &ipv6_devconf.hop_limit,
6237                 .maxlen         = sizeof(int),
6238                 .mode           = 0644,
6239                 .proc_handler   = proc_dointvec_minmax,
6240                 .extra1         = (void *)&one,
6241                 .extra2         = (void *)&two_five_five,
6242         },
6243         {
6244                 .procname       = "mtu",
6245                 .data           = &ipv6_devconf.mtu6,
6246                 .maxlen         = sizeof(int),
6247                 .mode           = 0644,
6248                 .proc_handler   = addrconf_sysctl_mtu,
6249         },
6250         {
6251                 .procname       = "accept_ra",
6252                 .data           = &ipv6_devconf.accept_ra,
6253                 .maxlen         = sizeof(int),
6254                 .mode           = 0644,
6255                 .proc_handler   = proc_dointvec,
6256         },
6257         {
6258                 .procname       = "accept_redirects",
6259                 .data           = &ipv6_devconf.accept_redirects,
6260                 .maxlen         = sizeof(int),
6261                 .mode           = 0644,
6262                 .proc_handler   = proc_dointvec,
6263         },
6264         {
6265                 .procname       = "autoconf",
6266                 .data           = &ipv6_devconf.autoconf,
6267                 .maxlen         = sizeof(int),
6268                 .mode           = 0644,
6269                 .proc_handler   = proc_dointvec,
6270         },
6271         {
6272                 .procname       = "dad_transmits",
6273                 .data           = &ipv6_devconf.dad_transmits,
6274                 .maxlen         = sizeof(int),
6275                 .mode           = 0644,
6276                 .proc_handler   = proc_dointvec,
6277         },
6278         {
6279                 .procname       = "router_solicitations",
6280                 .data           = &ipv6_devconf.rtr_solicits,
6281                 .maxlen         = sizeof(int),
6282                 .mode           = 0644,
6283                 .proc_handler   = proc_dointvec_minmax,
6284                 .extra1         = &minus_one,
6285         },
6286         {
6287                 .procname       = "router_solicitation_interval",
6288                 .data           = &ipv6_devconf.rtr_solicit_interval,
6289                 .maxlen         = sizeof(int),
6290                 .mode           = 0644,
6291                 .proc_handler   = proc_dointvec_jiffies,
6292         },
6293         {
6294                 .procname       = "router_solicitation_max_interval",
6295                 .data           = &ipv6_devconf.rtr_solicit_max_interval,
6296                 .maxlen         = sizeof(int),
6297                 .mode           = 0644,
6298                 .proc_handler   = proc_dointvec_jiffies,
6299         },
6300         {
6301                 .procname       = "router_solicitation_delay",
6302                 .data           = &ipv6_devconf.rtr_solicit_delay,
6303                 .maxlen         = sizeof(int),
6304                 .mode           = 0644,
6305                 .proc_handler   = proc_dointvec_jiffies,
6306         },
6307         {
6308                 .procname       = "force_mld_version",
6309                 .data           = &ipv6_devconf.force_mld_version,
6310                 .maxlen         = sizeof(int),
6311                 .mode           = 0644,
6312                 .proc_handler   = proc_dointvec,
6313         },
6314         {
6315                 .procname       = "mldv1_unsolicited_report_interval",
6316                 .data           =
6317                         &ipv6_devconf.mldv1_unsolicited_report_interval,
6318                 .maxlen         = sizeof(int),
6319                 .mode           = 0644,
6320                 .proc_handler   = proc_dointvec_ms_jiffies,
6321         },
6322         {
6323                 .procname       = "mldv2_unsolicited_report_interval",
6324                 .data           =
6325                         &ipv6_devconf.mldv2_unsolicited_report_interval,
6326                 .maxlen         = sizeof(int),
6327                 .mode           = 0644,
6328                 .proc_handler   = proc_dointvec_ms_jiffies,
6329         },
6330         {
6331                 .procname       = "use_tempaddr",
6332                 .data           = &ipv6_devconf.use_tempaddr,
6333                 .maxlen         = sizeof(int),
6334                 .mode           = 0644,
6335                 .proc_handler   = proc_dointvec,
6336         },
6337         {
6338                 .procname       = "temp_valid_lft",
6339                 .data           = &ipv6_devconf.temp_valid_lft,
6340                 .maxlen         = sizeof(int),
6341                 .mode           = 0644,
6342                 .proc_handler   = proc_dointvec,
6343         },
6344         {
6345                 .procname       = "temp_prefered_lft",
6346                 .data           = &ipv6_devconf.temp_prefered_lft,
6347                 .maxlen         = sizeof(int),
6348                 .mode           = 0644,
6349                 .proc_handler   = proc_dointvec,
6350         },
6351         {
6352                 .procname       = "regen_max_retry",
6353                 .data           = &ipv6_devconf.regen_max_retry,
6354                 .maxlen         = sizeof(int),
6355                 .mode           = 0644,
6356                 .proc_handler   = proc_dointvec,
6357         },
6358         {
6359                 .procname       = "max_desync_factor",
6360                 .data           = &ipv6_devconf.max_desync_factor,
6361                 .maxlen         = sizeof(int),
6362                 .mode           = 0644,
6363                 .proc_handler   = proc_dointvec,
6364         },
6365         {
6366                 .procname       = "max_addresses",
6367                 .data           = &ipv6_devconf.max_addresses,
6368                 .maxlen         = sizeof(int),
6369                 .mode           = 0644,
6370                 .proc_handler   = proc_dointvec,
6371         },
6372         {
6373                 .procname       = "accept_ra_defrtr",
6374                 .data           = &ipv6_devconf.accept_ra_defrtr,
6375                 .maxlen         = sizeof(int),
6376                 .mode           = 0644,
6377                 .proc_handler   = proc_dointvec,
6378         },
6379         {
6380                 .procname       = "accept_ra_min_hop_limit",
6381                 .data           = &ipv6_devconf.accept_ra_min_hop_limit,
6382                 .maxlen         = sizeof(int),
6383                 .mode           = 0644,
6384                 .proc_handler   = proc_dointvec,
6385         },
6386         {
6387                 .procname       = "accept_ra_pinfo",
6388                 .data           = &ipv6_devconf.accept_ra_pinfo,
6389                 .maxlen         = sizeof(int),
6390                 .mode           = 0644,
6391                 .proc_handler   = proc_dointvec,
6392         },
6393 #ifdef CONFIG_IPV6_ROUTER_PREF
6394         {
6395                 .procname       = "accept_ra_rtr_pref",
6396                 .data           = &ipv6_devconf.accept_ra_rtr_pref,
6397                 .maxlen         = sizeof(int),
6398                 .mode           = 0644,
6399                 .proc_handler   = proc_dointvec,
6400         },
6401         {
6402                 .procname       = "router_probe_interval",
6403                 .data           = &ipv6_devconf.rtr_probe_interval,
6404                 .maxlen         = sizeof(int),
6405                 .mode           = 0644,
6406                 .proc_handler   = proc_dointvec_jiffies,
6407         },
6408 #ifdef CONFIG_IPV6_ROUTE_INFO
6409         {
6410                 .procname       = "accept_ra_rt_info_min_plen",
6411                 .data           = &ipv6_devconf.accept_ra_rt_info_min_plen,
6412                 .maxlen         = sizeof(int),
6413                 .mode           = 0644,
6414                 .proc_handler   = proc_dointvec,
6415         },
6416         {
6417                 .procname       = "accept_ra_rt_info_max_plen",
6418                 .data           = &ipv6_devconf.accept_ra_rt_info_max_plen,
6419                 .maxlen         = sizeof(int),
6420                 .mode           = 0644,
6421                 .proc_handler   = proc_dointvec,
6422         },
6423 #endif
6424 #endif
6425         {
6426                 .procname       = "proxy_ndp",
6427                 .data           = &ipv6_devconf.proxy_ndp,
6428                 .maxlen         = sizeof(int),
6429                 .mode           = 0644,
6430                 .proc_handler   = addrconf_sysctl_proxy_ndp,
6431         },
6432         {
6433                 .procname       = "accept_source_route",
6434                 .data           = &ipv6_devconf.accept_source_route,
6435                 .maxlen         = sizeof(int),
6436                 .mode           = 0644,
6437                 .proc_handler   = proc_dointvec,
6438         },
6439 #ifdef CONFIG_IPV6_OPTIMISTIC_DAD
6440         {
6441                 .procname       = "optimistic_dad",
6442                 .data           = &ipv6_devconf.optimistic_dad,
6443                 .maxlen         = sizeof(int),
6444                 .mode           = 0644,
6445                 .proc_handler   = proc_dointvec,
6446         },
6447         {
6448                 .procname       = "use_optimistic",
6449                 .data           = &ipv6_devconf.use_optimistic,
6450                 .maxlen         = sizeof(int),
6451                 .mode           = 0644,
6452                 .proc_handler   = proc_dointvec,
6453         },
6454 #endif
6455 #ifdef CONFIG_IPV6_MROUTE
6456         {
6457                 .procname       = "mc_forwarding",
6458                 .data           = &ipv6_devconf.mc_forwarding,
6459                 .maxlen         = sizeof(int),
6460                 .mode           = 0444,
6461                 .proc_handler   = proc_dointvec,
6462         },
6463 #endif
6464         {
6465                 .procname       = "disable_ipv6",
6466                 .data           = &ipv6_devconf.disable_ipv6,
6467                 .maxlen         = sizeof(int),
6468                 .mode           = 0644,
6469                 .proc_handler   = addrconf_sysctl_disable,
6470         },
6471         {
6472                 .procname       = "accept_dad",
6473                 .data           = &ipv6_devconf.accept_dad,
6474                 .maxlen         = sizeof(int),
6475                 .mode           = 0644,
6476                 .proc_handler   = proc_dointvec,
6477         },
6478         {
6479                 .procname       = "force_tllao",
6480                 .data           = &ipv6_devconf.force_tllao,
6481                 .maxlen         = sizeof(int),
6482                 .mode           = 0644,
6483                 .proc_handler   = proc_dointvec
6484         },
6485         {
6486                 .procname       = "ndisc_notify",
6487                 .data           = &ipv6_devconf.ndisc_notify,
6488                 .maxlen         = sizeof(int),
6489                 .mode           = 0644,
6490                 .proc_handler   = proc_dointvec
6491         },
6492         {
6493                 .procname       = "suppress_frag_ndisc",
6494                 .data           = &ipv6_devconf.suppress_frag_ndisc,
6495                 .maxlen         = sizeof(int),
6496                 .mode           = 0644,
6497                 .proc_handler   = proc_dointvec
6498         },
6499         {
6500                 .procname       = "accept_ra_from_local",
6501                 .data           = &ipv6_devconf.accept_ra_from_local,
6502                 .maxlen         = sizeof(int),
6503                 .mode           = 0644,
6504                 .proc_handler   = proc_dointvec,
6505         },
6506         {
6507                 .procname       = "accept_ra_mtu",
6508                 .data           = &ipv6_devconf.accept_ra_mtu,
6509                 .maxlen         = sizeof(int),
6510                 .mode           = 0644,
6511                 .proc_handler   = proc_dointvec,
6512         },
6513         {
6514                 .procname       = "stable_secret",
6515                 .data           = &ipv6_devconf.stable_secret,
6516                 .maxlen         = IPV6_MAX_STRLEN,
6517                 .mode           = 0600,
6518                 .proc_handler   = addrconf_sysctl_stable_secret,
6519         },
6520         {
6521                 .procname       = "use_oif_addrs_only",
6522                 .data           = &ipv6_devconf.use_oif_addrs_only,
6523                 .maxlen         = sizeof(int),
6524                 .mode           = 0644,
6525                 .proc_handler   = proc_dointvec,
6526         },
6527         {
6528                 .procname       = "ignore_routes_with_linkdown",
6529                 .data           = &ipv6_devconf.ignore_routes_with_linkdown,
6530                 .maxlen         = sizeof(int),
6531                 .mode           = 0644,
6532                 .proc_handler   = addrconf_sysctl_ignore_routes_with_linkdown,
6533         },
6534         {
6535                 .procname       = "drop_unicast_in_l2_multicast",
6536                 .data           = &ipv6_devconf.drop_unicast_in_l2_multicast,
6537                 .maxlen         = sizeof(int),
6538                 .mode           = 0644,
6539                 .proc_handler   = proc_dointvec,
6540         },
6541         {
6542                 .procname       = "drop_unsolicited_na",
6543                 .data           = &ipv6_devconf.drop_unsolicited_na,
6544                 .maxlen         = sizeof(int),
6545                 .mode           = 0644,
6546                 .proc_handler   = proc_dointvec,
6547         },
6548         {
6549                 .procname       = "keep_addr_on_down",
6550                 .data           = &ipv6_devconf.keep_addr_on_down,
6551                 .maxlen         = sizeof(int),
6552                 .mode           = 0644,
6553                 .proc_handler   = proc_dointvec,
6554
6555         },
6556         {
6557                 .procname       = "seg6_enabled",
6558                 .data           = &ipv6_devconf.seg6_enabled,
6559                 .maxlen         = sizeof(int),
6560                 .mode           = 0644,
6561                 .proc_handler   = proc_dointvec,
6562         },
6563 #ifdef CONFIG_IPV6_SEG6_HMAC
6564         {
6565                 .procname       = "seg6_require_hmac",
6566                 .data           = &ipv6_devconf.seg6_require_hmac,
6567                 .maxlen         = sizeof(int),
6568                 .mode           = 0644,
6569                 .proc_handler   = proc_dointvec,
6570         },
6571 #endif
6572         {
6573                 .procname       = "enhanced_dad",
6574                 .data           = &ipv6_devconf.enhanced_dad,
6575                 .maxlen         = sizeof(int),
6576                 .mode           = 0644,
6577                 .proc_handler   = proc_dointvec,
6578         },
6579         {
6580                 .procname               = "addr_gen_mode",
6581                 .data                   = &ipv6_devconf.addr_gen_mode,
6582                 .maxlen                 = sizeof(int),
6583                 .mode                   = 0644,
6584                 .proc_handler   = addrconf_sysctl_addr_gen_mode,
6585         },
6586         {
6587                 .procname       = "disable_policy",
6588                 .data           = &ipv6_devconf.disable_policy,
6589                 .maxlen         = sizeof(int),
6590                 .mode           = 0644,
6591                 .proc_handler   = addrconf_sysctl_disable_policy,
6592         },
6593         {
6594                 .procname       = "ndisc_tclass",
6595                 .data           = &ipv6_devconf.ndisc_tclass,
6596                 .maxlen         = sizeof(int),
6597                 .mode           = 0644,
6598                 .proc_handler   = proc_dointvec_minmax,
6599                 .extra1         = (void *)&zero,
6600                 .extra2         = (void *)&two_five_five,
6601         },
6602         {
6603                 /* sentinel */
6604         }
6605 };
6606
6607 static int __addrconf_sysctl_register(struct net *net, char *dev_name,
6608                 struct inet6_dev *idev, struct ipv6_devconf *p)
6609 {
6610         int i, ifindex;
6611         struct ctl_table *table;
6612         char path[sizeof("net/ipv6/conf/") + IFNAMSIZ];
6613
6614         table = kmemdup(addrconf_sysctl, sizeof(addrconf_sysctl), GFP_KERNEL);
6615         if (!table)
6616                 goto out;
6617
6618         for (i = 0; table[i].data; i++) {
6619                 table[i].data += (char *)p - (char *)&ipv6_devconf;
6620                 /* If one of these is already set, then it is not safe to
6621                  * overwrite either of them: this makes proc_dointvec_minmax
6622                  * usable.
6623                  */
6624                 if (!table[i].extra1 && !table[i].extra2) {
6625                         table[i].extra1 = idev; /* embedded; no ref */
6626                         table[i].extra2 = net;
6627                 }
6628         }
6629
6630         snprintf(path, sizeof(path), "net/ipv6/conf/%s", dev_name);
6631
6632         p->sysctl_header = register_net_sysctl(net, path, table);
6633         if (!p->sysctl_header)
6634                 goto free;
6635
6636         if (!strcmp(dev_name, "all"))
6637                 ifindex = NETCONFA_IFINDEX_ALL;
6638         else if (!strcmp(dev_name, "default"))
6639                 ifindex = NETCONFA_IFINDEX_DEFAULT;
6640         else
6641                 ifindex = idev->dev->ifindex;
6642         inet6_netconf_notify_devconf(net, RTM_NEWNETCONF, NETCONFA_ALL,
6643                                      ifindex, p);
6644         return 0;
6645
6646 free:
6647         kfree(table);
6648 out:
6649         return -ENOBUFS;
6650 }
6651
6652 static void __addrconf_sysctl_unregister(struct net *net,
6653                                          struct ipv6_devconf *p, int ifindex)
6654 {
6655         struct ctl_table *table;
6656
6657         if (!p->sysctl_header)
6658                 return;
6659
6660         table = p->sysctl_header->ctl_table_arg;
6661         unregister_net_sysctl_table(p->sysctl_header);
6662         p->sysctl_header = NULL;
6663         kfree(table);
6664
6665         inet6_netconf_notify_devconf(net, RTM_DELNETCONF, 0, ifindex, NULL);
6666 }
6667
6668 static int addrconf_sysctl_register(struct inet6_dev *idev)
6669 {
6670         int err;
6671
6672         if (!sysctl_dev_name_is_allowed(idev->dev->name))
6673                 return -EINVAL;
6674
6675         err = neigh_sysctl_register(idev->dev, idev->nd_parms,
6676                                     &ndisc_ifinfo_sysctl_change);
6677         if (err)
6678                 return err;
6679         err = __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name,
6680                                          idev, &idev->cnf);
6681         if (err)
6682                 neigh_sysctl_unregister(idev->nd_parms);
6683
6684         return err;
6685 }
6686
6687 static void addrconf_sysctl_unregister(struct inet6_dev *idev)
6688 {
6689         __addrconf_sysctl_unregister(dev_net(idev->dev), &idev->cnf,
6690                                      idev->dev->ifindex);
6691         neigh_sysctl_unregister(idev->nd_parms);
6692 }
6693
6694
6695 #endif
6696
6697 static int __net_init addrconf_init_net(struct net *net)
6698 {
6699         int err = -ENOMEM;
6700         struct ipv6_devconf *all, *dflt;
6701
6702         all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL);
6703         if (!all)
6704                 goto err_alloc_all;
6705
6706         dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL);
6707         if (!dflt)
6708                 goto err_alloc_dflt;
6709
6710         /* these will be inherited by all namespaces */
6711         dflt->autoconf = ipv6_defaults.autoconf;
6712         dflt->disable_ipv6 = ipv6_defaults.disable_ipv6;
6713
6714         dflt->stable_secret.initialized = false;
6715         all->stable_secret.initialized = false;
6716
6717         net->ipv6.devconf_all = all;
6718         net->ipv6.devconf_dflt = dflt;
6719
6720 #ifdef CONFIG_SYSCTL
6721         err = __addrconf_sysctl_register(net, "all", NULL, all);
6722         if (err < 0)
6723                 goto err_reg_all;
6724
6725         err = __addrconf_sysctl_register(net, "default", NULL, dflt);
6726         if (err < 0)
6727                 goto err_reg_dflt;
6728 #endif
6729         return 0;
6730
6731 #ifdef CONFIG_SYSCTL
6732 err_reg_dflt:
6733         __addrconf_sysctl_unregister(net, all, NETCONFA_IFINDEX_ALL);
6734 err_reg_all:
6735         kfree(dflt);
6736 #endif
6737 err_alloc_dflt:
6738         kfree(all);
6739 err_alloc_all:
6740         return err;
6741 }
6742
6743 static void __net_exit addrconf_exit_net(struct net *net)
6744 {
6745 #ifdef CONFIG_SYSCTL
6746         __addrconf_sysctl_unregister(net, net->ipv6.devconf_dflt,
6747                                      NETCONFA_IFINDEX_DEFAULT);
6748         __addrconf_sysctl_unregister(net, net->ipv6.devconf_all,
6749                                      NETCONFA_IFINDEX_ALL);
6750 #endif
6751         kfree(net->ipv6.devconf_dflt);
6752         kfree(net->ipv6.devconf_all);
6753 }
6754
6755 static struct pernet_operations addrconf_ops = {
6756         .init = addrconf_init_net,
6757         .exit = addrconf_exit_net,
6758 };
6759
6760 static struct rtnl_af_ops inet6_ops __read_mostly = {
6761         .family           = AF_INET6,
6762         .fill_link_af     = inet6_fill_link_af,
6763         .get_link_af_size = inet6_get_link_af_size,
6764         .validate_link_af = inet6_validate_link_af,
6765         .set_link_af      = inet6_set_link_af,
6766 };
6767
6768 /*
6769  *      Init / cleanup code
6770  */
6771
6772 int __init addrconf_init(void)
6773 {
6774         struct inet6_dev *idev;
6775         int i, err;
6776
6777         err = ipv6_addr_label_init();
6778         if (err < 0) {
6779                 pr_crit("%s: cannot initialize default policy table: %d\n",
6780                         __func__, err);
6781                 goto out;
6782         }
6783
6784         err = register_pernet_subsys(&addrconf_ops);
6785         if (err < 0)
6786                 goto out_addrlabel;
6787
6788         addrconf_wq = create_workqueue("ipv6_addrconf");
6789         if (!addrconf_wq) {
6790                 err = -ENOMEM;
6791                 goto out_nowq;
6792         }
6793
6794         /* The addrconf netdev notifier requires that loopback_dev
6795          * has it's ipv6 private information allocated and setup
6796          * before it can bring up and give link-local addresses
6797          * to other devices which are up.
6798          *
6799          * Unfortunately, loopback_dev is not necessarily the first
6800          * entry in the global dev_base list of net devices.  In fact,
6801          * it is likely to be the very last entry on that list.
6802          * So this causes the notifier registry below to try and
6803          * give link-local addresses to all devices besides loopback_dev
6804          * first, then loopback_dev, which cases all the non-loopback_dev
6805          * devices to fail to get a link-local address.
6806          *
6807          * So, as a temporary fix, allocate the ipv6 structure for
6808          * loopback_dev first by hand.
6809          * Longer term, all of the dependencies ipv6 has upon the loopback
6810          * device and it being up should be removed.
6811          */
6812         rtnl_lock();
6813         idev = ipv6_add_dev(init_net.loopback_dev);
6814         rtnl_unlock();
6815         if (IS_ERR(idev)) {
6816                 err = PTR_ERR(idev);
6817                 goto errlo;
6818         }
6819
6820         ip6_route_init_special_entries();
6821
6822         for (i = 0; i < IN6_ADDR_HSIZE; i++)
6823                 INIT_HLIST_HEAD(&inet6_addr_lst[i]);
6824
6825         register_netdevice_notifier(&ipv6_dev_notf);
6826
6827         addrconf_verify();
6828
6829         rtnl_af_register(&inet6_ops);
6830
6831         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETLINK,
6832                                    NULL, inet6_dump_ifinfo, 0);
6833         if (err < 0)
6834                 goto errout;
6835
6836         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_NEWADDR,
6837                                    inet6_rtm_newaddr, NULL, 0);
6838         if (err < 0)
6839                 goto errout;
6840         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_DELADDR,
6841                                    inet6_rtm_deladdr, NULL, 0);
6842         if (err < 0)
6843                 goto errout;
6844         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETADDR,
6845                                    inet6_rtm_getaddr, inet6_dump_ifaddr,
6846                                    RTNL_FLAG_DOIT_UNLOCKED);
6847         if (err < 0)
6848                 goto errout;
6849         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETMULTICAST,
6850                                    NULL, inet6_dump_ifmcaddr, 0);
6851         if (err < 0)
6852                 goto errout;
6853         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETANYCAST,
6854                                    NULL, inet6_dump_ifacaddr, 0);
6855         if (err < 0)
6856                 goto errout;
6857         err = rtnl_register_module(THIS_MODULE, PF_INET6, RTM_GETNETCONF,
6858                                    inet6_netconf_get_devconf,
6859                                    inet6_netconf_dump_devconf,
6860                                    RTNL_FLAG_DOIT_UNLOCKED);
6861         if (err < 0)
6862                 goto errout;
6863         err = ipv6_addr_label_rtnl_register();
6864         if (err < 0)
6865                 goto errout;
6866
6867         return 0;
6868 errout:
6869         rtnl_unregister_all(PF_INET6);
6870         rtnl_af_unregister(&inet6_ops);
6871         unregister_netdevice_notifier(&ipv6_dev_notf);
6872 errlo:
6873         destroy_workqueue(addrconf_wq);
6874 out_nowq:
6875         unregister_pernet_subsys(&addrconf_ops);
6876 out_addrlabel:
6877         ipv6_addr_label_cleanup();
6878 out:
6879         return err;
6880 }
6881
6882 void addrconf_cleanup(void)
6883 {
6884         struct net_device *dev;
6885         int i;
6886
6887         unregister_netdevice_notifier(&ipv6_dev_notf);
6888         unregister_pernet_subsys(&addrconf_ops);
6889         ipv6_addr_label_cleanup();
6890
6891         rtnl_af_unregister(&inet6_ops);
6892
6893         rtnl_lock();
6894
6895         /* clean dev list */
6896         for_each_netdev(&init_net, dev) {
6897                 if (__in6_dev_get(dev) == NULL)
6898                         continue;
6899                 addrconf_ifdown(dev, 1);
6900         }
6901         addrconf_ifdown(init_net.loopback_dev, 2);
6902
6903         /*
6904          *      Check hash table.
6905          */
6906         spin_lock_bh(&addrconf_hash_lock);
6907         for (i = 0; i < IN6_ADDR_HSIZE; i++)
6908                 WARN_ON(!hlist_empty(&inet6_addr_lst[i]));
6909         spin_unlock_bh(&addrconf_hash_lock);
6910         cancel_delayed_work(&addr_chk_work);
6911         rtnl_unlock();
6912
6913         destroy_workqueue(addrconf_wq);
6914 }