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