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