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