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