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