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