xref: /openbmc/linux/net/ipv4/ipmr.c (revision 17bfcd6a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	IP multicast routing support for mrouted 3.6/3.8
4  *
5  *		(c) 1995 Alan Cox, <alan@lxorguk.ukuu.org.uk>
6  *	  Linux Consultancy and Custom Driver Development
7  *
8  *	Fixes:
9  *	Michael Chastain	:	Incorrect size of copying.
10  *	Alan Cox		:	Added the cache manager code
11  *	Alan Cox		:	Fixed the clone/copy bug and device race.
12  *	Mike McLagan		:	Routing by source
13  *	Malcolm Beattie		:	Buffer handling fixes.
14  *	Alexey Kuznetsov	:	Double buffer free and other fixes.
15  *	SVR Anand		:	Fixed several multicast bugs and problems.
16  *	Alexey Kuznetsov	:	Status, optimisations and more.
17  *	Brad Parker		:	Better behaviour on mrouted upcall
18  *					overflow.
19  *      Carlos Picoto           :       PIMv1 Support
20  *	Pavlin Ivanov Radoslavov:	PIMv2 Registers must checksum only PIM header
21  *					Relax this requirement to work with older peers.
22  */
23 
24 #include <linux/uaccess.h>
25 #include <linux/types.h>
26 #include <linux/cache.h>
27 #include <linux/capability.h>
28 #include <linux/errno.h>
29 #include <linux/mm.h>
30 #include <linux/kernel.h>
31 #include <linux/fcntl.h>
32 #include <linux/stat.h>
33 #include <linux/socket.h>
34 #include <linux/in.h>
35 #include <linux/inet.h>
36 #include <linux/netdevice.h>
37 #include <linux/inetdevice.h>
38 #include <linux/igmp.h>
39 #include <linux/proc_fs.h>
40 #include <linux/seq_file.h>
41 #include <linux/mroute.h>
42 #include <linux/init.h>
43 #include <linux/if_ether.h>
44 #include <linux/slab.h>
45 #include <net/net_namespace.h>
46 #include <net/ip.h>
47 #include <net/protocol.h>
48 #include <linux/skbuff.h>
49 #include <net/route.h>
50 #include <net/icmp.h>
51 #include <net/udp.h>
52 #include <net/raw.h>
53 #include <linux/notifier.h>
54 #include <linux/if_arp.h>
55 #include <linux/netfilter_ipv4.h>
56 #include <linux/compat.h>
57 #include <linux/export.h>
58 #include <linux/rhashtable.h>
59 #include <net/ip_tunnels.h>
60 #include <net/checksum.h>
61 #include <net/netlink.h>
62 #include <net/fib_rules.h>
63 #include <linux/netconf.h>
64 #include <net/rtnh.h>
65 
66 #include <linux/nospec.h>
67 
68 struct ipmr_rule {
69 	struct fib_rule		common;
70 };
71 
72 struct ipmr_result {
73 	struct mr_table		*mrt;
74 };
75 
76 /* Big lock, protecting vif table, mrt cache and mroute socket state.
77  * Note that the changes are semaphored via rtnl_lock.
78  */
79 
80 static DEFINE_SPINLOCK(mrt_lock);
81 
82 static struct net_device *vif_dev_read(const struct vif_device *vif)
83 {
84 	return rcu_dereference(vif->dev);
85 }
86 
87 /* Multicast router control variables */
88 
89 /* Special spinlock for queue of unresolved entries */
90 static DEFINE_SPINLOCK(mfc_unres_lock);
91 
92 /* We return to original Alan's scheme. Hash table of resolved
93  * entries is changed only in process context and protected
94  * with weak lock mrt_lock. Queue of unresolved entries is protected
95  * with strong spinlock mfc_unres_lock.
96  *
97  * In this case data path is free of exclusive locks at all.
98  */
99 
100 static struct kmem_cache *mrt_cachep __ro_after_init;
101 
102 static struct mr_table *ipmr_new_table(struct net *net, u32 id);
103 static void ipmr_free_table(struct mr_table *mrt);
104 
105 static void ip_mr_forward(struct net *net, struct mr_table *mrt,
106 			  struct net_device *dev, struct sk_buff *skb,
107 			  struct mfc_cache *cache, int local);
108 static int ipmr_cache_report(const struct mr_table *mrt,
109 			     struct sk_buff *pkt, vifi_t vifi, int assert);
110 static void mroute_netlink_event(struct mr_table *mrt, struct mfc_cache *mfc,
111 				 int cmd);
112 static void igmpmsg_netlink_event(const struct mr_table *mrt, struct sk_buff *pkt);
113 static void mroute_clean_tables(struct mr_table *mrt, int flags);
114 static void ipmr_expire_process(struct timer_list *t);
115 
116 #ifdef CONFIG_IP_MROUTE_MULTIPLE_TABLES
117 #define ipmr_for_each_table(mrt, net)					\
118 	list_for_each_entry_rcu(mrt, &net->ipv4.mr_tables, list,	\
119 				lockdep_rtnl_is_held() ||		\
120 				list_empty(&net->ipv4.mr_tables))
121 
122 static struct mr_table *ipmr_mr_table_iter(struct net *net,
123 					   struct mr_table *mrt)
124 {
125 	struct mr_table *ret;
126 
127 	if (!mrt)
128 		ret = list_entry_rcu(net->ipv4.mr_tables.next,
129 				     struct mr_table, list);
130 	else
131 		ret = list_entry_rcu(mrt->list.next,
132 				     struct mr_table, list);
133 
134 	if (&ret->list == &net->ipv4.mr_tables)
135 		return NULL;
136 	return ret;
137 }
138 
139 static struct mr_table *ipmr_get_table(struct net *net, u32 id)
140 {
141 	struct mr_table *mrt;
142 
143 	ipmr_for_each_table(mrt, net) {
144 		if (mrt->id == id)
145 			return mrt;
146 	}
147 	return NULL;
148 }
149 
150 static int ipmr_fib_lookup(struct net *net, struct flowi4 *flp4,
151 			   struct mr_table **mrt)
152 {
153 	int err;
154 	struct ipmr_result res;
155 	struct fib_lookup_arg arg = {
156 		.result = &res,
157 		.flags = FIB_LOOKUP_NOREF,
158 	};
159 
160 	/* update flow if oif or iif point to device enslaved to l3mdev */
161 	l3mdev_update_flow(net, flowi4_to_flowi(flp4));
162 
163 	err = fib_rules_lookup(net->ipv4.mr_rules_ops,
164 			       flowi4_to_flowi(flp4), 0, &arg);
165 	if (err < 0)
166 		return err;
167 	*mrt = res.mrt;
168 	return 0;
169 }
170 
171 static int ipmr_rule_action(struct fib_rule *rule, struct flowi *flp,
172 			    int flags, struct fib_lookup_arg *arg)
173 {
174 	struct ipmr_result *res = arg->result;
175 	struct mr_table *mrt;
176 
177 	switch (rule->action) {
178 	case FR_ACT_TO_TBL:
179 		break;
180 	case FR_ACT_UNREACHABLE:
181 		return -ENETUNREACH;
182 	case FR_ACT_PROHIBIT:
183 		return -EACCES;
184 	case FR_ACT_BLACKHOLE:
185 	default:
186 		return -EINVAL;
187 	}
188 
189 	arg->table = fib_rule_get_table(rule, arg);
190 
191 	mrt = ipmr_get_table(rule->fr_net, arg->table);
192 	if (!mrt)
193 		return -EAGAIN;
194 	res->mrt = mrt;
195 	return 0;
196 }
197 
198 static int ipmr_rule_match(struct fib_rule *rule, struct flowi *fl, int flags)
199 {
200 	return 1;
201 }
202 
203 static int ipmr_rule_configure(struct fib_rule *rule, struct sk_buff *skb,
204 			       struct fib_rule_hdr *frh, struct nlattr **tb,
205 			       struct netlink_ext_ack *extack)
206 {
207 	return 0;
208 }
209 
210 static int ipmr_rule_compare(struct fib_rule *rule, struct fib_rule_hdr *frh,
211 			     struct nlattr **tb)
212 {
213 	return 1;
214 }
215 
216 static int ipmr_rule_fill(struct fib_rule *rule, struct sk_buff *skb,
217 			  struct fib_rule_hdr *frh)
218 {
219 	frh->dst_len = 0;
220 	frh->src_len = 0;
221 	frh->tos     = 0;
222 	return 0;
223 }
224 
225 static const struct fib_rules_ops __net_initconst ipmr_rules_ops_template = {
226 	.family		= RTNL_FAMILY_IPMR,
227 	.rule_size	= sizeof(struct ipmr_rule),
228 	.addr_size	= sizeof(u32),
229 	.action		= ipmr_rule_action,
230 	.match		= ipmr_rule_match,
231 	.configure	= ipmr_rule_configure,
232 	.compare	= ipmr_rule_compare,
233 	.fill		= ipmr_rule_fill,
234 	.nlgroup	= RTNLGRP_IPV4_RULE,
235 	.owner		= THIS_MODULE,
236 };
237 
238 static int __net_init ipmr_rules_init(struct net *net)
239 {
240 	struct fib_rules_ops *ops;
241 	struct mr_table *mrt;
242 	int err;
243 
244 	ops = fib_rules_register(&ipmr_rules_ops_template, net);
245 	if (IS_ERR(ops))
246 		return PTR_ERR(ops);
247 
248 	INIT_LIST_HEAD(&net->ipv4.mr_tables);
249 
250 	mrt = ipmr_new_table(net, RT_TABLE_DEFAULT);
251 	if (IS_ERR(mrt)) {
252 		err = PTR_ERR(mrt);
253 		goto err1;
254 	}
255 
256 	err = fib_default_rule_add(ops, 0x7fff, RT_TABLE_DEFAULT, 0);
257 	if (err < 0)
258 		goto err2;
259 
260 	net->ipv4.mr_rules_ops = ops;
261 	return 0;
262 
263 err2:
264 	rtnl_lock();
265 	ipmr_free_table(mrt);
266 	rtnl_unlock();
267 err1:
268 	fib_rules_unregister(ops);
269 	return err;
270 }
271 
272 static void __net_exit ipmr_rules_exit(struct net *net)
273 {
274 	struct mr_table *mrt, *next;
275 
276 	ASSERT_RTNL();
277 	list_for_each_entry_safe(mrt, next, &net->ipv4.mr_tables, list) {
278 		list_del(&mrt->list);
279 		ipmr_free_table(mrt);
280 	}
281 	fib_rules_unregister(net->ipv4.mr_rules_ops);
282 }
283 
284 static int ipmr_rules_dump(struct net *net, struct notifier_block *nb,
285 			   struct netlink_ext_ack *extack)
286 {
287 	return fib_rules_dump(net, nb, RTNL_FAMILY_IPMR, extack);
288 }
289 
290 static unsigned int ipmr_rules_seq_read(struct net *net)
291 {
292 	return fib_rules_seq_read(net, RTNL_FAMILY_IPMR);
293 }
294 
295 bool ipmr_rule_default(const struct fib_rule *rule)
296 {
297 	return fib_rule_matchall(rule) && rule->table == RT_TABLE_DEFAULT;
298 }
299 EXPORT_SYMBOL(ipmr_rule_default);
300 #else
301 #define ipmr_for_each_table(mrt, net) \
302 	for (mrt = net->ipv4.mrt; mrt; mrt = NULL)
303 
304 static struct mr_table *ipmr_mr_table_iter(struct net *net,
305 					   struct mr_table *mrt)
306 {
307 	if (!mrt)
308 		return net->ipv4.mrt;
309 	return NULL;
310 }
311 
312 static struct mr_table *ipmr_get_table(struct net *net, u32 id)
313 {
314 	return net->ipv4.mrt;
315 }
316 
317 static int ipmr_fib_lookup(struct net *net, struct flowi4 *flp4,
318 			   struct mr_table **mrt)
319 {
320 	*mrt = net->ipv4.mrt;
321 	return 0;
322 }
323 
324 static int __net_init ipmr_rules_init(struct net *net)
325 {
326 	struct mr_table *mrt;
327 
328 	mrt = ipmr_new_table(net, RT_TABLE_DEFAULT);
329 	if (IS_ERR(mrt))
330 		return PTR_ERR(mrt);
331 	net->ipv4.mrt = mrt;
332 	return 0;
333 }
334 
335 static void __net_exit ipmr_rules_exit(struct net *net)
336 {
337 	ASSERT_RTNL();
338 	ipmr_free_table(net->ipv4.mrt);
339 	net->ipv4.mrt = NULL;
340 }
341 
342 static int ipmr_rules_dump(struct net *net, struct notifier_block *nb,
343 			   struct netlink_ext_ack *extack)
344 {
345 	return 0;
346 }
347 
348 static unsigned int ipmr_rules_seq_read(struct net *net)
349 {
350 	return 0;
351 }
352 
353 bool ipmr_rule_default(const struct fib_rule *rule)
354 {
355 	return true;
356 }
357 EXPORT_SYMBOL(ipmr_rule_default);
358 #endif
359 
360 static inline int ipmr_hash_cmp(struct rhashtable_compare_arg *arg,
361 				const void *ptr)
362 {
363 	const struct mfc_cache_cmp_arg *cmparg = arg->key;
364 	const struct mfc_cache *c = ptr;
365 
366 	return cmparg->mfc_mcastgrp != c->mfc_mcastgrp ||
367 	       cmparg->mfc_origin != c->mfc_origin;
368 }
369 
370 static const struct rhashtable_params ipmr_rht_params = {
371 	.head_offset = offsetof(struct mr_mfc, mnode),
372 	.key_offset = offsetof(struct mfc_cache, cmparg),
373 	.key_len = sizeof(struct mfc_cache_cmp_arg),
374 	.nelem_hint = 3,
375 	.obj_cmpfn = ipmr_hash_cmp,
376 	.automatic_shrinking = true,
377 };
378 
379 static void ipmr_new_table_set(struct mr_table *mrt,
380 			       struct net *net)
381 {
382 #ifdef CONFIG_IP_MROUTE_MULTIPLE_TABLES
383 	list_add_tail_rcu(&mrt->list, &net->ipv4.mr_tables);
384 #endif
385 }
386 
387 static struct mfc_cache_cmp_arg ipmr_mr_table_ops_cmparg_any = {
388 	.mfc_mcastgrp = htonl(INADDR_ANY),
389 	.mfc_origin = htonl(INADDR_ANY),
390 };
391 
392 static struct mr_table_ops ipmr_mr_table_ops = {
393 	.rht_params = &ipmr_rht_params,
394 	.cmparg_any = &ipmr_mr_table_ops_cmparg_any,
395 };
396 
397 static struct mr_table *ipmr_new_table(struct net *net, u32 id)
398 {
399 	struct mr_table *mrt;
400 
401 	/* "pimreg%u" should not exceed 16 bytes (IFNAMSIZ) */
402 	if (id != RT_TABLE_DEFAULT && id >= 1000000000)
403 		return ERR_PTR(-EINVAL);
404 
405 	mrt = ipmr_get_table(net, id);
406 	if (mrt)
407 		return mrt;
408 
409 	return mr_table_alloc(net, id, &ipmr_mr_table_ops,
410 			      ipmr_expire_process, ipmr_new_table_set);
411 }
412 
413 static void ipmr_free_table(struct mr_table *mrt)
414 {
415 	timer_shutdown_sync(&mrt->ipmr_expire_timer);
416 	mroute_clean_tables(mrt, MRT_FLUSH_VIFS | MRT_FLUSH_VIFS_STATIC |
417 				 MRT_FLUSH_MFC | MRT_FLUSH_MFC_STATIC);
418 	rhltable_destroy(&mrt->mfc_hash);
419 	kfree(mrt);
420 }
421 
422 /* Service routines creating virtual interfaces: DVMRP tunnels and PIMREG */
423 
424 /* Initialize ipmr pimreg/tunnel in_device */
425 static bool ipmr_init_vif_indev(const struct net_device *dev)
426 {
427 	struct in_device *in_dev;
428 
429 	ASSERT_RTNL();
430 
431 	in_dev = __in_dev_get_rtnl(dev);
432 	if (!in_dev)
433 		return false;
434 	ipv4_devconf_setall(in_dev);
435 	neigh_parms_data_state_setall(in_dev->arp_parms);
436 	IPV4_DEVCONF(in_dev->cnf, RP_FILTER) = 0;
437 
438 	return true;
439 }
440 
441 static struct net_device *ipmr_new_tunnel(struct net *net, struct vifctl *v)
442 {
443 	struct net_device *tunnel_dev, *new_dev;
444 	struct ip_tunnel_parm p = { };
445 	int err;
446 
447 	tunnel_dev = __dev_get_by_name(net, "tunl0");
448 	if (!tunnel_dev)
449 		goto out;
450 
451 	p.iph.daddr = v->vifc_rmt_addr.s_addr;
452 	p.iph.saddr = v->vifc_lcl_addr.s_addr;
453 	p.iph.version = 4;
454 	p.iph.ihl = 5;
455 	p.iph.protocol = IPPROTO_IPIP;
456 	sprintf(p.name, "dvmrp%d", v->vifc_vifi);
457 
458 	if (!tunnel_dev->netdev_ops->ndo_tunnel_ctl)
459 		goto out;
460 	err = tunnel_dev->netdev_ops->ndo_tunnel_ctl(tunnel_dev, &p,
461 			SIOCADDTUNNEL);
462 	if (err)
463 		goto out;
464 
465 	new_dev = __dev_get_by_name(net, p.name);
466 	if (!new_dev)
467 		goto out;
468 
469 	new_dev->flags |= IFF_MULTICAST;
470 	if (!ipmr_init_vif_indev(new_dev))
471 		goto out_unregister;
472 	if (dev_open(new_dev, NULL))
473 		goto out_unregister;
474 	dev_hold(new_dev);
475 	err = dev_set_allmulti(new_dev, 1);
476 	if (err) {
477 		dev_close(new_dev);
478 		tunnel_dev->netdev_ops->ndo_tunnel_ctl(tunnel_dev, &p,
479 				SIOCDELTUNNEL);
480 		dev_put(new_dev);
481 		new_dev = ERR_PTR(err);
482 	}
483 	return new_dev;
484 
485 out_unregister:
486 	unregister_netdevice(new_dev);
487 out:
488 	return ERR_PTR(-ENOBUFS);
489 }
490 
491 #if defined(CONFIG_IP_PIMSM_V1) || defined(CONFIG_IP_PIMSM_V2)
492 static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev)
493 {
494 	struct net *net = dev_net(dev);
495 	struct mr_table *mrt;
496 	struct flowi4 fl4 = {
497 		.flowi4_oif	= dev->ifindex,
498 		.flowi4_iif	= skb->skb_iif ? : LOOPBACK_IFINDEX,
499 		.flowi4_mark	= skb->mark,
500 	};
501 	int err;
502 
503 	err = ipmr_fib_lookup(net, &fl4, &mrt);
504 	if (err < 0) {
505 		kfree_skb(skb);
506 		return err;
507 	}
508 
509 	DEV_STATS_ADD(dev, tx_bytes, skb->len);
510 	DEV_STATS_INC(dev, tx_packets);
511 	rcu_read_lock();
512 
513 	/* Pairs with WRITE_ONCE() in vif_add() and vif_delete() */
514 	ipmr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num),
515 			  IGMPMSG_WHOLEPKT);
516 
517 	rcu_read_unlock();
518 	kfree_skb(skb);
519 	return NETDEV_TX_OK;
520 }
521 
522 static int reg_vif_get_iflink(const struct net_device *dev)
523 {
524 	return 0;
525 }
526 
527 static const struct net_device_ops reg_vif_netdev_ops = {
528 	.ndo_start_xmit	= reg_vif_xmit,
529 	.ndo_get_iflink = reg_vif_get_iflink,
530 };
531 
532 static void reg_vif_setup(struct net_device *dev)
533 {
534 	dev->type		= ARPHRD_PIMREG;
535 	dev->mtu		= ETH_DATA_LEN - sizeof(struct iphdr) - 8;
536 	dev->flags		= IFF_NOARP;
537 	dev->netdev_ops		= &reg_vif_netdev_ops;
538 	dev->needs_free_netdev	= true;
539 	dev->features		|= NETIF_F_NETNS_LOCAL;
540 }
541 
542 static struct net_device *ipmr_reg_vif(struct net *net, struct mr_table *mrt)
543 {
544 	struct net_device *dev;
545 	char name[IFNAMSIZ];
546 
547 	if (mrt->id == RT_TABLE_DEFAULT)
548 		sprintf(name, "pimreg");
549 	else
550 		sprintf(name, "pimreg%u", mrt->id);
551 
552 	dev = alloc_netdev(0, name, NET_NAME_UNKNOWN, reg_vif_setup);
553 
554 	if (!dev)
555 		return NULL;
556 
557 	dev_net_set(dev, net);
558 
559 	if (register_netdevice(dev)) {
560 		free_netdev(dev);
561 		return NULL;
562 	}
563 
564 	if (!ipmr_init_vif_indev(dev))
565 		goto failure;
566 	if (dev_open(dev, NULL))
567 		goto failure;
568 
569 	dev_hold(dev);
570 
571 	return dev;
572 
573 failure:
574 	unregister_netdevice(dev);
575 	return NULL;
576 }
577 
578 /* called with rcu_read_lock() */
579 static int __pim_rcv(struct mr_table *mrt, struct sk_buff *skb,
580 		     unsigned int pimlen)
581 {
582 	struct net_device *reg_dev = NULL;
583 	struct iphdr *encap;
584 	int vif_num;
585 
586 	encap = (struct iphdr *)(skb_transport_header(skb) + pimlen);
587 	/* Check that:
588 	 * a. packet is really sent to a multicast group
589 	 * b. packet is not a NULL-REGISTER
590 	 * c. packet is not truncated
591 	 */
592 	if (!ipv4_is_multicast(encap->daddr) ||
593 	    encap->tot_len == 0 ||
594 	    ntohs(encap->tot_len) + pimlen > skb->len)
595 		return 1;
596 
597 	/* Pairs with WRITE_ONCE() in vif_add()/vid_delete() */
598 	vif_num = READ_ONCE(mrt->mroute_reg_vif_num);
599 	if (vif_num >= 0)
600 		reg_dev = vif_dev_read(&mrt->vif_table[vif_num]);
601 	if (!reg_dev)
602 		return 1;
603 
604 	skb->mac_header = skb->network_header;
605 	skb_pull(skb, (u8 *)encap - skb->data);
606 	skb_reset_network_header(skb);
607 	skb->protocol = htons(ETH_P_IP);
608 	skb->ip_summed = CHECKSUM_NONE;
609 
610 	skb_tunnel_rx(skb, reg_dev, dev_net(reg_dev));
611 
612 	netif_rx(skb);
613 
614 	return NET_RX_SUCCESS;
615 }
616 #else
617 static struct net_device *ipmr_reg_vif(struct net *net, struct mr_table *mrt)
618 {
619 	return NULL;
620 }
621 #endif
622 
623 static int call_ipmr_vif_entry_notifiers(struct net *net,
624 					 enum fib_event_type event_type,
625 					 struct vif_device *vif,
626 					 struct net_device *vif_dev,
627 					 vifi_t vif_index, u32 tb_id)
628 {
629 	return mr_call_vif_notifiers(net, RTNL_FAMILY_IPMR, event_type,
630 				     vif, vif_dev, vif_index, tb_id,
631 				     &net->ipv4.ipmr_seq);
632 }
633 
634 static int call_ipmr_mfc_entry_notifiers(struct net *net,
635 					 enum fib_event_type event_type,
636 					 struct mfc_cache *mfc, u32 tb_id)
637 {
638 	return mr_call_mfc_notifiers(net, RTNL_FAMILY_IPMR, event_type,
639 				     &mfc->_c, tb_id, &net->ipv4.ipmr_seq);
640 }
641 
642 /**
643  *	vif_delete - Delete a VIF entry
644  *	@mrt: Table to delete from
645  *	@vifi: VIF identifier to delete
646  *	@notify: Set to 1, if the caller is a notifier_call
647  *	@head: if unregistering the VIF, place it on this queue
648  */
649 static int vif_delete(struct mr_table *mrt, int vifi, int notify,
650 		      struct list_head *head)
651 {
652 	struct net *net = read_pnet(&mrt->net);
653 	struct vif_device *v;
654 	struct net_device *dev;
655 	struct in_device *in_dev;
656 
657 	if (vifi < 0 || vifi >= mrt->maxvif)
658 		return -EADDRNOTAVAIL;
659 
660 	v = &mrt->vif_table[vifi];
661 
662 	dev = rtnl_dereference(v->dev);
663 	if (!dev)
664 		return -EADDRNOTAVAIL;
665 
666 	spin_lock(&mrt_lock);
667 	call_ipmr_vif_entry_notifiers(net, FIB_EVENT_VIF_DEL, v, dev,
668 				      vifi, mrt->id);
669 	RCU_INIT_POINTER(v->dev, NULL);
670 
671 	if (vifi == mrt->mroute_reg_vif_num) {
672 		/* Pairs with READ_ONCE() in ipmr_cache_report() and reg_vif_xmit() */
673 		WRITE_ONCE(mrt->mroute_reg_vif_num, -1);
674 	}
675 	if (vifi + 1 == mrt->maxvif) {
676 		int tmp;
677 
678 		for (tmp = vifi - 1; tmp >= 0; tmp--) {
679 			if (VIF_EXISTS(mrt, tmp))
680 				break;
681 		}
682 		WRITE_ONCE(mrt->maxvif, tmp + 1);
683 	}
684 
685 	spin_unlock(&mrt_lock);
686 
687 	dev_set_allmulti(dev, -1);
688 
689 	in_dev = __in_dev_get_rtnl(dev);
690 	if (in_dev) {
691 		IPV4_DEVCONF(in_dev->cnf, MC_FORWARDING)--;
692 		inet_netconf_notify_devconf(dev_net(dev), RTM_NEWNETCONF,
693 					    NETCONFA_MC_FORWARDING,
694 					    dev->ifindex, &in_dev->cnf);
695 		ip_rt_multicast_event(in_dev);
696 	}
697 
698 	if (v->flags & (VIFF_TUNNEL | VIFF_REGISTER) && !notify)
699 		unregister_netdevice_queue(dev, head);
700 
701 	netdev_put(dev, &v->dev_tracker);
702 	return 0;
703 }
704 
705 static void ipmr_cache_free_rcu(struct rcu_head *head)
706 {
707 	struct mr_mfc *c = container_of(head, struct mr_mfc, rcu);
708 
709 	kmem_cache_free(mrt_cachep, (struct mfc_cache *)c);
710 }
711 
712 static void ipmr_cache_free(struct mfc_cache *c)
713 {
714 	call_rcu(&c->_c.rcu, ipmr_cache_free_rcu);
715 }
716 
717 /* Destroy an unresolved cache entry, killing queued skbs
718  * and reporting error to netlink readers.
719  */
720 static void ipmr_destroy_unres(struct mr_table *mrt, struct mfc_cache *c)
721 {
722 	struct net *net = read_pnet(&mrt->net);
723 	struct sk_buff *skb;
724 	struct nlmsgerr *e;
725 
726 	atomic_dec(&mrt->cache_resolve_queue_len);
727 
728 	while ((skb = skb_dequeue(&c->_c.mfc_un.unres.unresolved))) {
729 		if (ip_hdr(skb)->version == 0) {
730 			struct nlmsghdr *nlh = skb_pull(skb,
731 							sizeof(struct iphdr));
732 			nlh->nlmsg_type = NLMSG_ERROR;
733 			nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr));
734 			skb_trim(skb, nlh->nlmsg_len);
735 			e = nlmsg_data(nlh);
736 			e->error = -ETIMEDOUT;
737 			memset(&e->msg, 0, sizeof(e->msg));
738 
739 			rtnl_unicast(skb, net, NETLINK_CB(skb).portid);
740 		} else {
741 			kfree_skb(skb);
742 		}
743 	}
744 
745 	ipmr_cache_free(c);
746 }
747 
748 /* Timer process for the unresolved queue. */
749 static void ipmr_expire_process(struct timer_list *t)
750 {
751 	struct mr_table *mrt = from_timer(mrt, t, ipmr_expire_timer);
752 	struct mr_mfc *c, *next;
753 	unsigned long expires;
754 	unsigned long now;
755 
756 	if (!spin_trylock(&mfc_unres_lock)) {
757 		mod_timer(&mrt->ipmr_expire_timer, jiffies+HZ/10);
758 		return;
759 	}
760 
761 	if (list_empty(&mrt->mfc_unres_queue))
762 		goto out;
763 
764 	now = jiffies;
765 	expires = 10*HZ;
766 
767 	list_for_each_entry_safe(c, next, &mrt->mfc_unres_queue, list) {
768 		if (time_after(c->mfc_un.unres.expires, now)) {
769 			unsigned long interval = c->mfc_un.unres.expires - now;
770 			if (interval < expires)
771 				expires = interval;
772 			continue;
773 		}
774 
775 		list_del(&c->list);
776 		mroute_netlink_event(mrt, (struct mfc_cache *)c, RTM_DELROUTE);
777 		ipmr_destroy_unres(mrt, (struct mfc_cache *)c);
778 	}
779 
780 	if (!list_empty(&mrt->mfc_unres_queue))
781 		mod_timer(&mrt->ipmr_expire_timer, jiffies + expires);
782 
783 out:
784 	spin_unlock(&mfc_unres_lock);
785 }
786 
787 /* Fill oifs list. It is called under locked mrt_lock. */
788 static void ipmr_update_thresholds(struct mr_table *mrt, struct mr_mfc *cache,
789 				   unsigned char *ttls)
790 {
791 	int vifi;
792 
793 	cache->mfc_un.res.minvif = MAXVIFS;
794 	cache->mfc_un.res.maxvif = 0;
795 	memset(cache->mfc_un.res.ttls, 255, MAXVIFS);
796 
797 	for (vifi = 0; vifi < mrt->maxvif; vifi++) {
798 		if (VIF_EXISTS(mrt, vifi) &&
799 		    ttls[vifi] && ttls[vifi] < 255) {
800 			cache->mfc_un.res.ttls[vifi] = ttls[vifi];
801 			if (cache->mfc_un.res.minvif > vifi)
802 				cache->mfc_un.res.minvif = vifi;
803 			if (cache->mfc_un.res.maxvif <= vifi)
804 				cache->mfc_un.res.maxvif = vifi + 1;
805 		}
806 	}
807 	cache->mfc_un.res.lastuse = jiffies;
808 }
809 
810 static int vif_add(struct net *net, struct mr_table *mrt,
811 		   struct vifctl *vifc, int mrtsock)
812 {
813 	struct netdev_phys_item_id ppid = { };
814 	int vifi = vifc->vifc_vifi;
815 	struct vif_device *v = &mrt->vif_table[vifi];
816 	struct net_device *dev;
817 	struct in_device *in_dev;
818 	int err;
819 
820 	/* Is vif busy ? */
821 	if (VIF_EXISTS(mrt, vifi))
822 		return -EADDRINUSE;
823 
824 	switch (vifc->vifc_flags) {
825 	case VIFF_REGISTER:
826 		if (!ipmr_pimsm_enabled())
827 			return -EINVAL;
828 		/* Special Purpose VIF in PIM
829 		 * All the packets will be sent to the daemon
830 		 */
831 		if (mrt->mroute_reg_vif_num >= 0)
832 			return -EADDRINUSE;
833 		dev = ipmr_reg_vif(net, mrt);
834 		if (!dev)
835 			return -ENOBUFS;
836 		err = dev_set_allmulti(dev, 1);
837 		if (err) {
838 			unregister_netdevice(dev);
839 			dev_put(dev);
840 			return err;
841 		}
842 		break;
843 	case VIFF_TUNNEL:
844 		dev = ipmr_new_tunnel(net, vifc);
845 		if (IS_ERR(dev))
846 			return PTR_ERR(dev);
847 		break;
848 	case VIFF_USE_IFINDEX:
849 	case 0:
850 		if (vifc->vifc_flags == VIFF_USE_IFINDEX) {
851 			dev = dev_get_by_index(net, vifc->vifc_lcl_ifindex);
852 			if (dev && !__in_dev_get_rtnl(dev)) {
853 				dev_put(dev);
854 				return -EADDRNOTAVAIL;
855 			}
856 		} else {
857 			dev = ip_dev_find(net, vifc->vifc_lcl_addr.s_addr);
858 		}
859 		if (!dev)
860 			return -EADDRNOTAVAIL;
861 		err = dev_set_allmulti(dev, 1);
862 		if (err) {
863 			dev_put(dev);
864 			return err;
865 		}
866 		break;
867 	default:
868 		return -EINVAL;
869 	}
870 
871 	in_dev = __in_dev_get_rtnl(dev);
872 	if (!in_dev) {
873 		dev_put(dev);
874 		return -EADDRNOTAVAIL;
875 	}
876 	IPV4_DEVCONF(in_dev->cnf, MC_FORWARDING)++;
877 	inet_netconf_notify_devconf(net, RTM_NEWNETCONF, NETCONFA_MC_FORWARDING,
878 				    dev->ifindex, &in_dev->cnf);
879 	ip_rt_multicast_event(in_dev);
880 
881 	/* Fill in the VIF structures */
882 	vif_device_init(v, dev, vifc->vifc_rate_limit,
883 			vifc->vifc_threshold,
884 			vifc->vifc_flags | (!mrtsock ? VIFF_STATIC : 0),
885 			(VIFF_TUNNEL | VIFF_REGISTER));
886 
887 	err = dev_get_port_parent_id(dev, &ppid, true);
888 	if (err == 0) {
889 		memcpy(v->dev_parent_id.id, ppid.id, ppid.id_len);
890 		v->dev_parent_id.id_len = ppid.id_len;
891 	} else {
892 		v->dev_parent_id.id_len = 0;
893 	}
894 
895 	v->local = vifc->vifc_lcl_addr.s_addr;
896 	v->remote = vifc->vifc_rmt_addr.s_addr;
897 
898 	/* And finish update writing critical data */
899 	spin_lock(&mrt_lock);
900 	rcu_assign_pointer(v->dev, dev);
901 	netdev_tracker_alloc(dev, &v->dev_tracker, GFP_ATOMIC);
902 	if (v->flags & VIFF_REGISTER) {
903 		/* Pairs with READ_ONCE() in ipmr_cache_report() and reg_vif_xmit() */
904 		WRITE_ONCE(mrt->mroute_reg_vif_num, vifi);
905 	}
906 	if (vifi+1 > mrt->maxvif)
907 		WRITE_ONCE(mrt->maxvif, vifi + 1);
908 	spin_unlock(&mrt_lock);
909 	call_ipmr_vif_entry_notifiers(net, FIB_EVENT_VIF_ADD, v, dev,
910 				      vifi, mrt->id);
911 	return 0;
912 }
913 
914 /* called with rcu_read_lock() */
915 static struct mfc_cache *ipmr_cache_find(struct mr_table *mrt,
916 					 __be32 origin,
917 					 __be32 mcastgrp)
918 {
919 	struct mfc_cache_cmp_arg arg = {
920 			.mfc_mcastgrp = mcastgrp,
921 			.mfc_origin = origin
922 	};
923 
924 	return mr_mfc_find(mrt, &arg);
925 }
926 
927 /* Look for a (*,G) entry */
928 static struct mfc_cache *ipmr_cache_find_any(struct mr_table *mrt,
929 					     __be32 mcastgrp, int vifi)
930 {
931 	struct mfc_cache_cmp_arg arg = {
932 			.mfc_mcastgrp = mcastgrp,
933 			.mfc_origin = htonl(INADDR_ANY)
934 	};
935 
936 	if (mcastgrp == htonl(INADDR_ANY))
937 		return mr_mfc_find_any_parent(mrt, vifi);
938 	return mr_mfc_find_any(mrt, vifi, &arg);
939 }
940 
941 /* Look for a (S,G,iif) entry if parent != -1 */
942 static struct mfc_cache *ipmr_cache_find_parent(struct mr_table *mrt,
943 						__be32 origin, __be32 mcastgrp,
944 						int parent)
945 {
946 	struct mfc_cache_cmp_arg arg = {
947 			.mfc_mcastgrp = mcastgrp,
948 			.mfc_origin = origin,
949 	};
950 
951 	return mr_mfc_find_parent(mrt, &arg, parent);
952 }
953 
954 /* Allocate a multicast cache entry */
955 static struct mfc_cache *ipmr_cache_alloc(void)
956 {
957 	struct mfc_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_KERNEL);
958 
959 	if (c) {
960 		c->_c.mfc_un.res.last_assert = jiffies - MFC_ASSERT_THRESH - 1;
961 		c->_c.mfc_un.res.minvif = MAXVIFS;
962 		c->_c.free = ipmr_cache_free_rcu;
963 		refcount_set(&c->_c.mfc_un.res.refcount, 1);
964 	}
965 	return c;
966 }
967 
968 static struct mfc_cache *ipmr_cache_alloc_unres(void)
969 {
970 	struct mfc_cache *c = kmem_cache_zalloc(mrt_cachep, GFP_ATOMIC);
971 
972 	if (c) {
973 		skb_queue_head_init(&c->_c.mfc_un.unres.unresolved);
974 		c->_c.mfc_un.unres.expires = jiffies + 10 * HZ;
975 	}
976 	return c;
977 }
978 
979 /* A cache entry has gone into a resolved state from queued */
980 static void ipmr_cache_resolve(struct net *net, struct mr_table *mrt,
981 			       struct mfc_cache *uc, struct mfc_cache *c)
982 {
983 	struct sk_buff *skb;
984 	struct nlmsgerr *e;
985 
986 	/* Play the pending entries through our router */
987 	while ((skb = __skb_dequeue(&uc->_c.mfc_un.unres.unresolved))) {
988 		if (ip_hdr(skb)->version == 0) {
989 			struct nlmsghdr *nlh = skb_pull(skb,
990 							sizeof(struct iphdr));
991 
992 			if (mr_fill_mroute(mrt, skb, &c->_c,
993 					   nlmsg_data(nlh)) > 0) {
994 				nlh->nlmsg_len = skb_tail_pointer(skb) -
995 						 (u8 *)nlh;
996 			} else {
997 				nlh->nlmsg_type = NLMSG_ERROR;
998 				nlh->nlmsg_len = nlmsg_msg_size(sizeof(struct nlmsgerr));
999 				skb_trim(skb, nlh->nlmsg_len);
1000 				e = nlmsg_data(nlh);
1001 				e->error = -EMSGSIZE;
1002 				memset(&e->msg, 0, sizeof(e->msg));
1003 			}
1004 
1005 			rtnl_unicast(skb, net, NETLINK_CB(skb).portid);
1006 		} else {
1007 			rcu_read_lock();
1008 			ip_mr_forward(net, mrt, skb->dev, skb, c, 0);
1009 			rcu_read_unlock();
1010 		}
1011 	}
1012 }
1013 
1014 /* Bounce a cache query up to mrouted and netlink.
1015  *
1016  * Called under rcu_read_lock().
1017  */
1018 static int ipmr_cache_report(const struct mr_table *mrt,
1019 			     struct sk_buff *pkt, vifi_t vifi, int assert)
1020 {
1021 	const int ihl = ip_hdrlen(pkt);
1022 	struct sock *mroute_sk;
1023 	struct igmphdr *igmp;
1024 	struct igmpmsg *msg;
1025 	struct sk_buff *skb;
1026 	int ret;
1027 
1028 	if (assert == IGMPMSG_WHOLEPKT || assert == IGMPMSG_WRVIFWHOLE)
1029 		skb = skb_realloc_headroom(pkt, sizeof(struct iphdr));
1030 	else
1031 		skb = alloc_skb(128, GFP_ATOMIC);
1032 
1033 	if (!skb)
1034 		return -ENOBUFS;
1035 
1036 	if (assert == IGMPMSG_WHOLEPKT || assert == IGMPMSG_WRVIFWHOLE) {
1037 		/* Ugly, but we have no choice with this interface.
1038 		 * Duplicate old header, fix ihl, length etc.
1039 		 * And all this only to mangle msg->im_msgtype and
1040 		 * to set msg->im_mbz to "mbz" :-)
1041 		 */
1042 		skb_push(skb, sizeof(struct iphdr));
1043 		skb_reset_network_header(skb);
1044 		skb_reset_transport_header(skb);
1045 		msg = (struct igmpmsg *)skb_network_header(skb);
1046 		memcpy(msg, skb_network_header(pkt), sizeof(struct iphdr));
1047 		msg->im_msgtype = assert;
1048 		msg->im_mbz = 0;
1049 		if (assert == IGMPMSG_WRVIFWHOLE) {
1050 			msg->im_vif = vifi;
1051 			msg->im_vif_hi = vifi >> 8;
1052 		} else {
1053 			/* Pairs with WRITE_ONCE() in vif_add() and vif_delete() */
1054 			int vif_num = READ_ONCE(mrt->mroute_reg_vif_num);
1055 
1056 			msg->im_vif = vif_num;
1057 			msg->im_vif_hi = vif_num >> 8;
1058 		}
1059 		ip_hdr(skb)->ihl = sizeof(struct iphdr) >> 2;
1060 		ip_hdr(skb)->tot_len = htons(ntohs(ip_hdr(pkt)->tot_len) +
1061 					     sizeof(struct iphdr));
1062 	} else {
1063 		/* Copy the IP header */
1064 		skb_set_network_header(skb, skb->len);
1065 		skb_put(skb, ihl);
1066 		skb_copy_to_linear_data(skb, pkt->data, ihl);
1067 		/* Flag to the kernel this is a route add */
1068 		ip_hdr(skb)->protocol = 0;
1069 		msg = (struct igmpmsg *)skb_network_header(skb);
1070 		msg->im_vif = vifi;
1071 		msg->im_vif_hi = vifi >> 8;
1072 		skb_dst_set(skb, dst_clone(skb_dst(pkt)));
1073 		/* Add our header */
1074 		igmp = skb_put(skb, sizeof(struct igmphdr));
1075 		igmp->type = assert;
1076 		msg->im_msgtype = assert;
1077 		igmp->code = 0;
1078 		ip_hdr(skb)->tot_len = htons(skb->len);	/* Fix the length */
1079 		skb->transport_header = skb->network_header;
1080 	}
1081 
1082 	mroute_sk = rcu_dereference(mrt->mroute_sk);
1083 	if (!mroute_sk) {
1084 		kfree_skb(skb);
1085 		return -EINVAL;
1086 	}
1087 
1088 	igmpmsg_netlink_event(mrt, skb);
1089 
1090 	/* Deliver to mrouted */
1091 	ret = sock_queue_rcv_skb(mroute_sk, skb);
1092 
1093 	if (ret < 0) {
1094 		net_warn_ratelimited("mroute: pending queue full, dropping entries\n");
1095 		kfree_skb(skb);
1096 	}
1097 
1098 	return ret;
1099 }
1100 
1101 /* Queue a packet for resolution. It gets locked cache entry! */
1102 /* Called under rcu_read_lock() */
1103 static int ipmr_cache_unresolved(struct mr_table *mrt, vifi_t vifi,
1104 				 struct sk_buff *skb, struct net_device *dev)
1105 {
1106 	const struct iphdr *iph = ip_hdr(skb);
1107 	struct mfc_cache *c;
1108 	bool found = false;
1109 	int err;
1110 
1111 	spin_lock_bh(&mfc_unres_lock);
1112 	list_for_each_entry(c, &mrt->mfc_unres_queue, _c.list) {
1113 		if (c->mfc_mcastgrp == iph->daddr &&
1114 		    c->mfc_origin == iph->saddr) {
1115 			found = true;
1116 			break;
1117 		}
1118 	}
1119 
1120 	if (!found) {
1121 		/* Create a new entry if allowable */
1122 		c = ipmr_cache_alloc_unres();
1123 		if (!c) {
1124 			spin_unlock_bh(&mfc_unres_lock);
1125 
1126 			kfree_skb(skb);
1127 			return -ENOBUFS;
1128 		}
1129 
1130 		/* Fill in the new cache entry */
1131 		c->_c.mfc_parent = -1;
1132 		c->mfc_origin	= iph->saddr;
1133 		c->mfc_mcastgrp	= iph->daddr;
1134 
1135 		/* Reflect first query at mrouted. */
1136 		err = ipmr_cache_report(mrt, skb, vifi, IGMPMSG_NOCACHE);
1137 
1138 		if (err < 0) {
1139 			/* If the report failed throw the cache entry
1140 			   out - Brad Parker
1141 			 */
1142 			spin_unlock_bh(&mfc_unres_lock);
1143 
1144 			ipmr_cache_free(c);
1145 			kfree_skb(skb);
1146 			return err;
1147 		}
1148 
1149 		atomic_inc(&mrt->cache_resolve_queue_len);
1150 		list_add(&c->_c.list, &mrt->mfc_unres_queue);
1151 		mroute_netlink_event(mrt, c, RTM_NEWROUTE);
1152 
1153 		if (atomic_read(&mrt->cache_resolve_queue_len) == 1)
1154 			mod_timer(&mrt->ipmr_expire_timer,
1155 				  c->_c.mfc_un.unres.expires);
1156 	}
1157 
1158 	/* See if we can append the packet */
1159 	if (c->_c.mfc_un.unres.unresolved.qlen > 3) {
1160 		kfree_skb(skb);
1161 		err = -ENOBUFS;
1162 	} else {
1163 		if (dev) {
1164 			skb->dev = dev;
1165 			skb->skb_iif = dev->ifindex;
1166 		}
1167 		skb_queue_tail(&c->_c.mfc_un.unres.unresolved, skb);
1168 		err = 0;
1169 	}
1170 
1171 	spin_unlock_bh(&mfc_unres_lock);
1172 	return err;
1173 }
1174 
1175 /* MFC cache manipulation by user space mroute daemon */
1176 
1177 static int ipmr_mfc_delete(struct mr_table *mrt, struct mfcctl *mfc, int parent)
1178 {
1179 	struct net *net = read_pnet(&mrt->net);
1180 	struct mfc_cache *c;
1181 
1182 	/* The entries are added/deleted only under RTNL */
1183 	rcu_read_lock();
1184 	c = ipmr_cache_find_parent(mrt, mfc->mfcc_origin.s_addr,
1185 				   mfc->mfcc_mcastgrp.s_addr, parent);
1186 	rcu_read_unlock();
1187 	if (!c)
1188 		return -ENOENT;
1189 	rhltable_remove(&mrt->mfc_hash, &c->_c.mnode, ipmr_rht_params);
1190 	list_del_rcu(&c->_c.list);
1191 	call_ipmr_mfc_entry_notifiers(net, FIB_EVENT_ENTRY_DEL, c, mrt->id);
1192 	mroute_netlink_event(mrt, c, RTM_DELROUTE);
1193 	mr_cache_put(&c->_c);
1194 
1195 	return 0;
1196 }
1197 
1198 static int ipmr_mfc_add(struct net *net, struct mr_table *mrt,
1199 			struct mfcctl *mfc, int mrtsock, int parent)
1200 {
1201 	struct mfc_cache *uc, *c;
1202 	struct mr_mfc *_uc;
1203 	bool found;
1204 	int ret;
1205 
1206 	if (mfc->mfcc_parent >= MAXVIFS)
1207 		return -ENFILE;
1208 
1209 	/* The entries are added/deleted only under RTNL */
1210 	rcu_read_lock();
1211 	c = ipmr_cache_find_parent(mrt, mfc->mfcc_origin.s_addr,
1212 				   mfc->mfcc_mcastgrp.s_addr, parent);
1213 	rcu_read_unlock();
1214 	if (c) {
1215 		spin_lock(&mrt_lock);
1216 		c->_c.mfc_parent = mfc->mfcc_parent;
1217 		ipmr_update_thresholds(mrt, &c->_c, mfc->mfcc_ttls);
1218 		if (!mrtsock)
1219 			c->_c.mfc_flags |= MFC_STATIC;
1220 		spin_unlock(&mrt_lock);
1221 		call_ipmr_mfc_entry_notifiers(net, FIB_EVENT_ENTRY_REPLACE, c,
1222 					      mrt->id);
1223 		mroute_netlink_event(mrt, c, RTM_NEWROUTE);
1224 		return 0;
1225 	}
1226 
1227 	if (mfc->mfcc_mcastgrp.s_addr != htonl(INADDR_ANY) &&
1228 	    !ipv4_is_multicast(mfc->mfcc_mcastgrp.s_addr))
1229 		return -EINVAL;
1230 
1231 	c = ipmr_cache_alloc();
1232 	if (!c)
1233 		return -ENOMEM;
1234 
1235 	c->mfc_origin = mfc->mfcc_origin.s_addr;
1236 	c->mfc_mcastgrp = mfc->mfcc_mcastgrp.s_addr;
1237 	c->_c.mfc_parent = mfc->mfcc_parent;
1238 	ipmr_update_thresholds(mrt, &c->_c, mfc->mfcc_ttls);
1239 	if (!mrtsock)
1240 		c->_c.mfc_flags |= MFC_STATIC;
1241 
1242 	ret = rhltable_insert_key(&mrt->mfc_hash, &c->cmparg, &c->_c.mnode,
1243 				  ipmr_rht_params);
1244 	if (ret) {
1245 		pr_err("ipmr: rhtable insert error %d\n", ret);
1246 		ipmr_cache_free(c);
1247 		return ret;
1248 	}
1249 	list_add_tail_rcu(&c->_c.list, &mrt->mfc_cache_list);
1250 	/* Check to see if we resolved a queued list. If so we
1251 	 * need to send on the frames and tidy up.
1252 	 */
1253 	found = false;
1254 	spin_lock_bh(&mfc_unres_lock);
1255 	list_for_each_entry(_uc, &mrt->mfc_unres_queue, list) {
1256 		uc = (struct mfc_cache *)_uc;
1257 		if (uc->mfc_origin == c->mfc_origin &&
1258 		    uc->mfc_mcastgrp == c->mfc_mcastgrp) {
1259 			list_del(&_uc->list);
1260 			atomic_dec(&mrt->cache_resolve_queue_len);
1261 			found = true;
1262 			break;
1263 		}
1264 	}
1265 	if (list_empty(&mrt->mfc_unres_queue))
1266 		del_timer(&mrt->ipmr_expire_timer);
1267 	spin_unlock_bh(&mfc_unres_lock);
1268 
1269 	if (found) {
1270 		ipmr_cache_resolve(net, mrt, uc, c);
1271 		ipmr_cache_free(uc);
1272 	}
1273 	call_ipmr_mfc_entry_notifiers(net, FIB_EVENT_ENTRY_ADD, c, mrt->id);
1274 	mroute_netlink_event(mrt, c, RTM_NEWROUTE);
1275 	return 0;
1276 }
1277 
1278 /* Close the multicast socket, and clear the vif tables etc */
1279 static void mroute_clean_tables(struct mr_table *mrt, int flags)
1280 {
1281 	struct net *net = read_pnet(&mrt->net);
1282 	struct mr_mfc *c, *tmp;
1283 	struct mfc_cache *cache;
1284 	LIST_HEAD(list);
1285 	int i;
1286 
1287 	/* Shut down all active vif entries */
1288 	if (flags & (MRT_FLUSH_VIFS | MRT_FLUSH_VIFS_STATIC)) {
1289 		for (i = 0; i < mrt->maxvif; i++) {
1290 			if (((mrt->vif_table[i].flags & VIFF_STATIC) &&
1291 			     !(flags & MRT_FLUSH_VIFS_STATIC)) ||
1292 			    (!(mrt->vif_table[i].flags & VIFF_STATIC) && !(flags & MRT_FLUSH_VIFS)))
1293 				continue;
1294 			vif_delete(mrt, i, 0, &list);
1295 		}
1296 		unregister_netdevice_many(&list);
1297 	}
1298 
1299 	/* Wipe the cache */
1300 	if (flags & (MRT_FLUSH_MFC | MRT_FLUSH_MFC_STATIC)) {
1301 		list_for_each_entry_safe(c, tmp, &mrt->mfc_cache_list, list) {
1302 			if (((c->mfc_flags & MFC_STATIC) && !(flags & MRT_FLUSH_MFC_STATIC)) ||
1303 			    (!(c->mfc_flags & MFC_STATIC) && !(flags & MRT_FLUSH_MFC)))
1304 				continue;
1305 			rhltable_remove(&mrt->mfc_hash, &c->mnode, ipmr_rht_params);
1306 			list_del_rcu(&c->list);
1307 			cache = (struct mfc_cache *)c;
1308 			call_ipmr_mfc_entry_notifiers(net, FIB_EVENT_ENTRY_DEL, cache,
1309 						      mrt->id);
1310 			mroute_netlink_event(mrt, cache, RTM_DELROUTE);
1311 			mr_cache_put(c);
1312 		}
1313 	}
1314 
1315 	if (flags & MRT_FLUSH_MFC) {
1316 		if (atomic_read(&mrt->cache_resolve_queue_len) != 0) {
1317 			spin_lock_bh(&mfc_unres_lock);
1318 			list_for_each_entry_safe(c, tmp, &mrt->mfc_unres_queue, list) {
1319 				list_del(&c->list);
1320 				cache = (struct mfc_cache *)c;
1321 				mroute_netlink_event(mrt, cache, RTM_DELROUTE);
1322 				ipmr_destroy_unres(mrt, cache);
1323 			}
1324 			spin_unlock_bh(&mfc_unres_lock);
1325 		}
1326 	}
1327 }
1328 
1329 /* called from ip_ra_control(), before an RCU grace period,
1330  * we don't need to call synchronize_rcu() here
1331  */
1332 static void mrtsock_destruct(struct sock *sk)
1333 {
1334 	struct net *net = sock_net(sk);
1335 	struct mr_table *mrt;
1336 
1337 	rtnl_lock();
1338 	ipmr_for_each_table(mrt, net) {
1339 		if (sk == rtnl_dereference(mrt->mroute_sk)) {
1340 			IPV4_DEVCONF_ALL(net, MC_FORWARDING)--;
1341 			inet_netconf_notify_devconf(net, RTM_NEWNETCONF,
1342 						    NETCONFA_MC_FORWARDING,
1343 						    NETCONFA_IFINDEX_ALL,
1344 						    net->ipv4.devconf_all);
1345 			RCU_INIT_POINTER(mrt->mroute_sk, NULL);
1346 			mroute_clean_tables(mrt, MRT_FLUSH_VIFS | MRT_FLUSH_MFC);
1347 		}
1348 	}
1349 	rtnl_unlock();
1350 }
1351 
1352 /* Socket options and virtual interface manipulation. The whole
1353  * virtual interface system is a complete heap, but unfortunately
1354  * that's how BSD mrouted happens to think. Maybe one day with a proper
1355  * MOSPF/PIM router set up we can clean this up.
1356  */
1357 
1358 int ip_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval,
1359 			 unsigned int optlen)
1360 {
1361 	struct net *net = sock_net(sk);
1362 	int val, ret = 0, parent = 0;
1363 	struct mr_table *mrt;
1364 	struct vifctl vif;
1365 	struct mfcctl mfc;
1366 	bool do_wrvifwhole;
1367 	u32 uval;
1368 
1369 	/* There's one exception to the lock - MRT_DONE which needs to unlock */
1370 	rtnl_lock();
1371 	if (sk->sk_type != SOCK_RAW ||
1372 	    inet_sk(sk)->inet_num != IPPROTO_IGMP) {
1373 		ret = -EOPNOTSUPP;
1374 		goto out_unlock;
1375 	}
1376 
1377 	mrt = ipmr_get_table(net, raw_sk(sk)->ipmr_table ? : RT_TABLE_DEFAULT);
1378 	if (!mrt) {
1379 		ret = -ENOENT;
1380 		goto out_unlock;
1381 	}
1382 	if (optname != MRT_INIT) {
1383 		if (sk != rcu_access_pointer(mrt->mroute_sk) &&
1384 		    !ns_capable(net->user_ns, CAP_NET_ADMIN)) {
1385 			ret = -EACCES;
1386 			goto out_unlock;
1387 		}
1388 	}
1389 
1390 	switch (optname) {
1391 	case MRT_INIT:
1392 		if (optlen != sizeof(int)) {
1393 			ret = -EINVAL;
1394 			break;
1395 		}
1396 		if (rtnl_dereference(mrt->mroute_sk)) {
1397 			ret = -EADDRINUSE;
1398 			break;
1399 		}
1400 
1401 		ret = ip_ra_control(sk, 1, mrtsock_destruct);
1402 		if (ret == 0) {
1403 			rcu_assign_pointer(mrt->mroute_sk, sk);
1404 			IPV4_DEVCONF_ALL(net, MC_FORWARDING)++;
1405 			inet_netconf_notify_devconf(net, RTM_NEWNETCONF,
1406 						    NETCONFA_MC_FORWARDING,
1407 						    NETCONFA_IFINDEX_ALL,
1408 						    net->ipv4.devconf_all);
1409 		}
1410 		break;
1411 	case MRT_DONE:
1412 		if (sk != rcu_access_pointer(mrt->mroute_sk)) {
1413 			ret = -EACCES;
1414 		} else {
1415 			/* We need to unlock here because mrtsock_destruct takes
1416 			 * care of rtnl itself and we can't change that due to
1417 			 * the IP_ROUTER_ALERT setsockopt which runs without it.
1418 			 */
1419 			rtnl_unlock();
1420 			ret = ip_ra_control(sk, 0, NULL);
1421 			goto out;
1422 		}
1423 		break;
1424 	case MRT_ADD_VIF:
1425 	case MRT_DEL_VIF:
1426 		if (optlen != sizeof(vif)) {
1427 			ret = -EINVAL;
1428 			break;
1429 		}
1430 		if (copy_from_sockptr(&vif, optval, sizeof(vif))) {
1431 			ret = -EFAULT;
1432 			break;
1433 		}
1434 		if (vif.vifc_vifi >= MAXVIFS) {
1435 			ret = -ENFILE;
1436 			break;
1437 		}
1438 		if (optname == MRT_ADD_VIF) {
1439 			ret = vif_add(net, mrt, &vif,
1440 				      sk == rtnl_dereference(mrt->mroute_sk));
1441 		} else {
1442 			ret = vif_delete(mrt, vif.vifc_vifi, 0, NULL);
1443 		}
1444 		break;
1445 	/* Manipulate the forwarding caches. These live
1446 	 * in a sort of kernel/user symbiosis.
1447 	 */
1448 	case MRT_ADD_MFC:
1449 	case MRT_DEL_MFC:
1450 		parent = -1;
1451 		fallthrough;
1452 	case MRT_ADD_MFC_PROXY:
1453 	case MRT_DEL_MFC_PROXY:
1454 		if (optlen != sizeof(mfc)) {
1455 			ret = -EINVAL;
1456 			break;
1457 		}
1458 		if (copy_from_sockptr(&mfc, optval, sizeof(mfc))) {
1459 			ret = -EFAULT;
1460 			break;
1461 		}
1462 		if (parent == 0)
1463 			parent = mfc.mfcc_parent;
1464 		if (optname == MRT_DEL_MFC || optname == MRT_DEL_MFC_PROXY)
1465 			ret = ipmr_mfc_delete(mrt, &mfc, parent);
1466 		else
1467 			ret = ipmr_mfc_add(net, mrt, &mfc,
1468 					   sk == rtnl_dereference(mrt->mroute_sk),
1469 					   parent);
1470 		break;
1471 	case MRT_FLUSH:
1472 		if (optlen != sizeof(val)) {
1473 			ret = -EINVAL;
1474 			break;
1475 		}
1476 		if (copy_from_sockptr(&val, optval, sizeof(val))) {
1477 			ret = -EFAULT;
1478 			break;
1479 		}
1480 		mroute_clean_tables(mrt, val);
1481 		break;
1482 	/* Control PIM assert. */
1483 	case MRT_ASSERT:
1484 		if (optlen != sizeof(val)) {
1485 			ret = -EINVAL;
1486 			break;
1487 		}
1488 		if (copy_from_sockptr(&val, optval, sizeof(val))) {
1489 			ret = -EFAULT;
1490 			break;
1491 		}
1492 		mrt->mroute_do_assert = val;
1493 		break;
1494 	case MRT_PIM:
1495 		if (!ipmr_pimsm_enabled()) {
1496 			ret = -ENOPROTOOPT;
1497 			break;
1498 		}
1499 		if (optlen != sizeof(val)) {
1500 			ret = -EINVAL;
1501 			break;
1502 		}
1503 		if (copy_from_sockptr(&val, optval, sizeof(val))) {
1504 			ret = -EFAULT;
1505 			break;
1506 		}
1507 
1508 		do_wrvifwhole = (val == IGMPMSG_WRVIFWHOLE);
1509 		val = !!val;
1510 		if (val != mrt->mroute_do_pim) {
1511 			mrt->mroute_do_pim = val;
1512 			mrt->mroute_do_assert = val;
1513 			mrt->mroute_do_wrvifwhole = do_wrvifwhole;
1514 		}
1515 		break;
1516 	case MRT_TABLE:
1517 		if (!IS_BUILTIN(CONFIG_IP_MROUTE_MULTIPLE_TABLES)) {
1518 			ret = -ENOPROTOOPT;
1519 			break;
1520 		}
1521 		if (optlen != sizeof(uval)) {
1522 			ret = -EINVAL;
1523 			break;
1524 		}
1525 		if (copy_from_sockptr(&uval, optval, sizeof(uval))) {
1526 			ret = -EFAULT;
1527 			break;
1528 		}
1529 
1530 		if (sk == rtnl_dereference(mrt->mroute_sk)) {
1531 			ret = -EBUSY;
1532 		} else {
1533 			mrt = ipmr_new_table(net, uval);
1534 			if (IS_ERR(mrt))
1535 				ret = PTR_ERR(mrt);
1536 			else
1537 				raw_sk(sk)->ipmr_table = uval;
1538 		}
1539 		break;
1540 	/* Spurious command, or MRT_VERSION which you cannot set. */
1541 	default:
1542 		ret = -ENOPROTOOPT;
1543 	}
1544 out_unlock:
1545 	rtnl_unlock();
1546 out:
1547 	return ret;
1548 }
1549 
1550 /* Execute if this ioctl is a special mroute ioctl */
1551 int ipmr_sk_ioctl(struct sock *sk, unsigned int cmd, void __user *arg)
1552 {
1553 	switch (cmd) {
1554 	/* These userspace buffers will be consumed by ipmr_ioctl() */
1555 	case SIOCGETVIFCNT: {
1556 		struct sioc_vif_req buffer;
1557 
1558 		return sock_ioctl_inout(sk, cmd, arg, &buffer,
1559 				      sizeof(buffer));
1560 		}
1561 	case SIOCGETSGCNT: {
1562 		struct sioc_sg_req buffer;
1563 
1564 		return sock_ioctl_inout(sk, cmd, arg, &buffer,
1565 				      sizeof(buffer));
1566 		}
1567 	}
1568 	/* return code > 0 means that the ioctl was not executed */
1569 	return 1;
1570 }
1571 
1572 /* Getsock opt support for the multicast routing system. */
1573 int ip_mroute_getsockopt(struct sock *sk, int optname, sockptr_t optval,
1574 			 sockptr_t optlen)
1575 {
1576 	int olr;
1577 	int val;
1578 	struct net *net = sock_net(sk);
1579 	struct mr_table *mrt;
1580 
1581 	if (sk->sk_type != SOCK_RAW ||
1582 	    inet_sk(sk)->inet_num != IPPROTO_IGMP)
1583 		return -EOPNOTSUPP;
1584 
1585 	mrt = ipmr_get_table(net, raw_sk(sk)->ipmr_table ? : RT_TABLE_DEFAULT);
1586 	if (!mrt)
1587 		return -ENOENT;
1588 
1589 	switch (optname) {
1590 	case MRT_VERSION:
1591 		val = 0x0305;
1592 		break;
1593 	case MRT_PIM:
1594 		if (!ipmr_pimsm_enabled())
1595 			return -ENOPROTOOPT;
1596 		val = mrt->mroute_do_pim;
1597 		break;
1598 	case MRT_ASSERT:
1599 		val = mrt->mroute_do_assert;
1600 		break;
1601 	default:
1602 		return -ENOPROTOOPT;
1603 	}
1604 
1605 	if (copy_from_sockptr(&olr, optlen, sizeof(int)))
1606 		return -EFAULT;
1607 	olr = min_t(unsigned int, olr, sizeof(int));
1608 	if (olr < 0)
1609 		return -EINVAL;
1610 	if (copy_to_sockptr(optlen, &olr, sizeof(int)))
1611 		return -EFAULT;
1612 	if (copy_to_sockptr(optval, &val, olr))
1613 		return -EFAULT;
1614 	return 0;
1615 }
1616 
1617 /* The IP multicast ioctl support routines. */
1618 int ipmr_ioctl(struct sock *sk, int cmd, void *arg)
1619 {
1620 	struct vif_device *vif;
1621 	struct mfc_cache *c;
1622 	struct net *net = sock_net(sk);
1623 	struct sioc_vif_req *vr;
1624 	struct sioc_sg_req *sr;
1625 	struct mr_table *mrt;
1626 
1627 	mrt = ipmr_get_table(net, raw_sk(sk)->ipmr_table ? : RT_TABLE_DEFAULT);
1628 	if (!mrt)
1629 		return -ENOENT;
1630 
1631 	switch (cmd) {
1632 	case SIOCGETVIFCNT:
1633 		vr = (struct sioc_vif_req *)arg;
1634 		if (vr->vifi >= mrt->maxvif)
1635 			return -EINVAL;
1636 		vr->vifi = array_index_nospec(vr->vifi, mrt->maxvif);
1637 		rcu_read_lock();
1638 		vif = &mrt->vif_table[vr->vifi];
1639 		if (VIF_EXISTS(mrt, vr->vifi)) {
1640 			vr->icount = READ_ONCE(vif->pkt_in);
1641 			vr->ocount = READ_ONCE(vif->pkt_out);
1642 			vr->ibytes = READ_ONCE(vif->bytes_in);
1643 			vr->obytes = READ_ONCE(vif->bytes_out);
1644 			rcu_read_unlock();
1645 
1646 			return 0;
1647 		}
1648 		rcu_read_unlock();
1649 		return -EADDRNOTAVAIL;
1650 	case SIOCGETSGCNT:
1651 		sr = (struct sioc_sg_req *)arg;
1652 
1653 		rcu_read_lock();
1654 		c = ipmr_cache_find(mrt, sr->src.s_addr, sr->grp.s_addr);
1655 		if (c) {
1656 			sr->pktcnt = c->_c.mfc_un.res.pkt;
1657 			sr->bytecnt = c->_c.mfc_un.res.bytes;
1658 			sr->wrong_if = c->_c.mfc_un.res.wrong_if;
1659 			rcu_read_unlock();
1660 			return 0;
1661 		}
1662 		rcu_read_unlock();
1663 		return -EADDRNOTAVAIL;
1664 	default:
1665 		return -ENOIOCTLCMD;
1666 	}
1667 }
1668 
1669 #ifdef CONFIG_COMPAT
1670 struct compat_sioc_sg_req {
1671 	struct in_addr src;
1672 	struct in_addr grp;
1673 	compat_ulong_t pktcnt;
1674 	compat_ulong_t bytecnt;
1675 	compat_ulong_t wrong_if;
1676 };
1677 
1678 struct compat_sioc_vif_req {
1679 	vifi_t	vifi;		/* Which iface */
1680 	compat_ulong_t icount;
1681 	compat_ulong_t ocount;
1682 	compat_ulong_t ibytes;
1683 	compat_ulong_t obytes;
1684 };
1685 
1686 int ipmr_compat_ioctl(struct sock *sk, unsigned int cmd, void __user *arg)
1687 {
1688 	struct compat_sioc_sg_req sr;
1689 	struct compat_sioc_vif_req vr;
1690 	struct vif_device *vif;
1691 	struct mfc_cache *c;
1692 	struct net *net = sock_net(sk);
1693 	struct mr_table *mrt;
1694 
1695 	mrt = ipmr_get_table(net, raw_sk(sk)->ipmr_table ? : RT_TABLE_DEFAULT);
1696 	if (!mrt)
1697 		return -ENOENT;
1698 
1699 	switch (cmd) {
1700 	case SIOCGETVIFCNT:
1701 		if (copy_from_user(&vr, arg, sizeof(vr)))
1702 			return -EFAULT;
1703 		if (vr.vifi >= mrt->maxvif)
1704 			return -EINVAL;
1705 		vr.vifi = array_index_nospec(vr.vifi, mrt->maxvif);
1706 		rcu_read_lock();
1707 		vif = &mrt->vif_table[vr.vifi];
1708 		if (VIF_EXISTS(mrt, vr.vifi)) {
1709 			vr.icount = READ_ONCE(vif->pkt_in);
1710 			vr.ocount = READ_ONCE(vif->pkt_out);
1711 			vr.ibytes = READ_ONCE(vif->bytes_in);
1712 			vr.obytes = READ_ONCE(vif->bytes_out);
1713 			rcu_read_unlock();
1714 
1715 			if (copy_to_user(arg, &vr, sizeof(vr)))
1716 				return -EFAULT;
1717 			return 0;
1718 		}
1719 		rcu_read_unlock();
1720 		return -EADDRNOTAVAIL;
1721 	case SIOCGETSGCNT:
1722 		if (copy_from_user(&sr, arg, sizeof(sr)))
1723 			return -EFAULT;
1724 
1725 		rcu_read_lock();
1726 		c = ipmr_cache_find(mrt, sr.src.s_addr, sr.grp.s_addr);
1727 		if (c) {
1728 			sr.pktcnt = c->_c.mfc_un.res.pkt;
1729 			sr.bytecnt = c->_c.mfc_un.res.bytes;
1730 			sr.wrong_if = c->_c.mfc_un.res.wrong_if;
1731 			rcu_read_unlock();
1732 
1733 			if (copy_to_user(arg, &sr, sizeof(sr)))
1734 				return -EFAULT;
1735 			return 0;
1736 		}
1737 		rcu_read_unlock();
1738 		return -EADDRNOTAVAIL;
1739 	default:
1740 		return -ENOIOCTLCMD;
1741 	}
1742 }
1743 #endif
1744 
1745 static int ipmr_device_event(struct notifier_block *this, unsigned long event, void *ptr)
1746 {
1747 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1748 	struct net *net = dev_net(dev);
1749 	struct mr_table *mrt;
1750 	struct vif_device *v;
1751 	int ct;
1752 
1753 	if (event != NETDEV_UNREGISTER)
1754 		return NOTIFY_DONE;
1755 
1756 	ipmr_for_each_table(mrt, net) {
1757 		v = &mrt->vif_table[0];
1758 		for (ct = 0; ct < mrt->maxvif; ct++, v++) {
1759 			if (rcu_access_pointer(v->dev) == dev)
1760 				vif_delete(mrt, ct, 1, NULL);
1761 		}
1762 	}
1763 	return NOTIFY_DONE;
1764 }
1765 
1766 static struct notifier_block ip_mr_notifier = {
1767 	.notifier_call = ipmr_device_event,
1768 };
1769 
1770 /* Encapsulate a packet by attaching a valid IPIP header to it.
1771  * This avoids tunnel drivers and other mess and gives us the speed so
1772  * important for multicast video.
1773  */
1774 static void ip_encap(struct net *net, struct sk_buff *skb,
1775 		     __be32 saddr, __be32 daddr)
1776 {
1777 	struct iphdr *iph;
1778 	const struct iphdr *old_iph = ip_hdr(skb);
1779 
1780 	skb_push(skb, sizeof(struct iphdr));
1781 	skb->transport_header = skb->network_header;
1782 	skb_reset_network_header(skb);
1783 	iph = ip_hdr(skb);
1784 
1785 	iph->version	=	4;
1786 	iph->tos	=	old_iph->tos;
1787 	iph->ttl	=	old_iph->ttl;
1788 	iph->frag_off	=	0;
1789 	iph->daddr	=	daddr;
1790 	iph->saddr	=	saddr;
1791 	iph->protocol	=	IPPROTO_IPIP;
1792 	iph->ihl	=	5;
1793 	iph->tot_len	=	htons(skb->len);
1794 	ip_select_ident(net, skb, NULL);
1795 	ip_send_check(iph);
1796 
1797 	memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1798 	nf_reset_ct(skb);
1799 }
1800 
1801 static inline int ipmr_forward_finish(struct net *net, struct sock *sk,
1802 				      struct sk_buff *skb)
1803 {
1804 	struct ip_options *opt = &(IPCB(skb)->opt);
1805 
1806 	IP_INC_STATS(net, IPSTATS_MIB_OUTFORWDATAGRAMS);
1807 
1808 	if (unlikely(opt->optlen))
1809 		ip_forward_options(skb);
1810 
1811 	return dst_output(net, sk, skb);
1812 }
1813 
1814 #ifdef CONFIG_NET_SWITCHDEV
1815 static bool ipmr_forward_offloaded(struct sk_buff *skb, struct mr_table *mrt,
1816 				   int in_vifi, int out_vifi)
1817 {
1818 	struct vif_device *out_vif = &mrt->vif_table[out_vifi];
1819 	struct vif_device *in_vif = &mrt->vif_table[in_vifi];
1820 
1821 	if (!skb->offload_l3_fwd_mark)
1822 		return false;
1823 	if (!out_vif->dev_parent_id.id_len || !in_vif->dev_parent_id.id_len)
1824 		return false;
1825 	return netdev_phys_item_id_same(&out_vif->dev_parent_id,
1826 					&in_vif->dev_parent_id);
1827 }
1828 #else
1829 static bool ipmr_forward_offloaded(struct sk_buff *skb, struct mr_table *mrt,
1830 				   int in_vifi, int out_vifi)
1831 {
1832 	return false;
1833 }
1834 #endif
1835 
1836 /* Processing handlers for ipmr_forward, under rcu_read_lock() */
1837 
1838 static void ipmr_queue_xmit(struct net *net, struct mr_table *mrt,
1839 			    int in_vifi, struct sk_buff *skb, int vifi)
1840 {
1841 	const struct iphdr *iph = ip_hdr(skb);
1842 	struct vif_device *vif = &mrt->vif_table[vifi];
1843 	struct net_device *vif_dev;
1844 	struct net_device *dev;
1845 	struct rtable *rt;
1846 	struct flowi4 fl4;
1847 	int    encap = 0;
1848 
1849 	vif_dev = vif_dev_read(vif);
1850 	if (!vif_dev)
1851 		goto out_free;
1852 
1853 	if (vif->flags & VIFF_REGISTER) {
1854 		WRITE_ONCE(vif->pkt_out, vif->pkt_out + 1);
1855 		WRITE_ONCE(vif->bytes_out, vif->bytes_out + skb->len);
1856 		DEV_STATS_ADD(vif_dev, tx_bytes, skb->len);
1857 		DEV_STATS_INC(vif_dev, tx_packets);
1858 		ipmr_cache_report(mrt, skb, vifi, IGMPMSG_WHOLEPKT);
1859 		goto out_free;
1860 	}
1861 
1862 	if (ipmr_forward_offloaded(skb, mrt, in_vifi, vifi))
1863 		goto out_free;
1864 
1865 	if (vif->flags & VIFF_TUNNEL) {
1866 		rt = ip_route_output_ports(net, &fl4, NULL,
1867 					   vif->remote, vif->local,
1868 					   0, 0,
1869 					   IPPROTO_IPIP,
1870 					   RT_TOS(iph->tos), vif->link);
1871 		if (IS_ERR(rt))
1872 			goto out_free;
1873 		encap = sizeof(struct iphdr);
1874 	} else {
1875 		rt = ip_route_output_ports(net, &fl4, NULL, iph->daddr, 0,
1876 					   0, 0,
1877 					   IPPROTO_IPIP,
1878 					   RT_TOS(iph->tos), vif->link);
1879 		if (IS_ERR(rt))
1880 			goto out_free;
1881 	}
1882 
1883 	dev = rt->dst.dev;
1884 
1885 	if (skb->len+encap > dst_mtu(&rt->dst) && (ntohs(iph->frag_off) & IP_DF)) {
1886 		/* Do not fragment multicasts. Alas, IPv4 does not
1887 		 * allow to send ICMP, so that packets will disappear
1888 		 * to blackhole.
1889 		 */
1890 		IP_INC_STATS(net, IPSTATS_MIB_FRAGFAILS);
1891 		ip_rt_put(rt);
1892 		goto out_free;
1893 	}
1894 
1895 	encap += LL_RESERVED_SPACE(dev) + rt->dst.header_len;
1896 
1897 	if (skb_cow(skb, encap)) {
1898 		ip_rt_put(rt);
1899 		goto out_free;
1900 	}
1901 
1902 	WRITE_ONCE(vif->pkt_out, vif->pkt_out + 1);
1903 	WRITE_ONCE(vif->bytes_out, vif->bytes_out + skb->len);
1904 
1905 	skb_dst_drop(skb);
1906 	skb_dst_set(skb, &rt->dst);
1907 	ip_decrease_ttl(ip_hdr(skb));
1908 
1909 	/* FIXME: forward and output firewalls used to be called here.
1910 	 * What do we do with netfilter? -- RR
1911 	 */
1912 	if (vif->flags & VIFF_TUNNEL) {
1913 		ip_encap(net, skb, vif->local, vif->remote);
1914 		/* FIXME: extra output firewall step used to be here. --RR */
1915 		DEV_STATS_INC(vif_dev, tx_packets);
1916 		DEV_STATS_ADD(vif_dev, tx_bytes, skb->len);
1917 	}
1918 
1919 	IPCB(skb)->flags |= IPSKB_FORWARDED;
1920 
1921 	/* RFC1584 teaches, that DVMRP/PIM router must deliver packets locally
1922 	 * not only before forwarding, but after forwarding on all output
1923 	 * interfaces. It is clear, if mrouter runs a multicasting
1924 	 * program, it should receive packets not depending to what interface
1925 	 * program is joined.
1926 	 * If we will not make it, the program will have to join on all
1927 	 * interfaces. On the other hand, multihoming host (or router, but
1928 	 * not mrouter) cannot join to more than one interface - it will
1929 	 * result in receiving multiple packets.
1930 	 */
1931 	NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD,
1932 		net, NULL, skb, skb->dev, dev,
1933 		ipmr_forward_finish);
1934 	return;
1935 
1936 out_free:
1937 	kfree_skb(skb);
1938 }
1939 
1940 /* Called with mrt_lock or rcu_read_lock() */
1941 static int ipmr_find_vif(const struct mr_table *mrt, struct net_device *dev)
1942 {
1943 	int ct;
1944 	/* Pairs with WRITE_ONCE() in vif_delete()/vif_add() */
1945 	for (ct = READ_ONCE(mrt->maxvif) - 1; ct >= 0; ct--) {
1946 		if (rcu_access_pointer(mrt->vif_table[ct].dev) == dev)
1947 			break;
1948 	}
1949 	return ct;
1950 }
1951 
1952 /* "local" means that we should preserve one skb (for local delivery) */
1953 /* Called uner rcu_read_lock() */
1954 static void ip_mr_forward(struct net *net, struct mr_table *mrt,
1955 			  struct net_device *dev, struct sk_buff *skb,
1956 			  struct mfc_cache *c, int local)
1957 {
1958 	int true_vifi = ipmr_find_vif(mrt, dev);
1959 	int psend = -1;
1960 	int vif, ct;
1961 
1962 	vif = c->_c.mfc_parent;
1963 	c->_c.mfc_un.res.pkt++;
1964 	c->_c.mfc_un.res.bytes += skb->len;
1965 	c->_c.mfc_un.res.lastuse = jiffies;
1966 
1967 	if (c->mfc_origin == htonl(INADDR_ANY) && true_vifi >= 0) {
1968 		struct mfc_cache *cache_proxy;
1969 
1970 		/* For an (*,G) entry, we only check that the incoming
1971 		 * interface is part of the static tree.
1972 		 */
1973 		cache_proxy = mr_mfc_find_any_parent(mrt, vif);
1974 		if (cache_proxy &&
1975 		    cache_proxy->_c.mfc_un.res.ttls[true_vifi] < 255)
1976 			goto forward;
1977 	}
1978 
1979 	/* Wrong interface: drop packet and (maybe) send PIM assert. */
1980 	if (rcu_access_pointer(mrt->vif_table[vif].dev) != dev) {
1981 		if (rt_is_output_route(skb_rtable(skb))) {
1982 			/* It is our own packet, looped back.
1983 			 * Very complicated situation...
1984 			 *
1985 			 * The best workaround until routing daemons will be
1986 			 * fixed is not to redistribute packet, if it was
1987 			 * send through wrong interface. It means, that
1988 			 * multicast applications WILL NOT work for
1989 			 * (S,G), which have default multicast route pointing
1990 			 * to wrong oif. In any case, it is not a good
1991 			 * idea to use multicasting applications on router.
1992 			 */
1993 			goto dont_forward;
1994 		}
1995 
1996 		c->_c.mfc_un.res.wrong_if++;
1997 
1998 		if (true_vifi >= 0 && mrt->mroute_do_assert &&
1999 		    /* pimsm uses asserts, when switching from RPT to SPT,
2000 		     * so that we cannot check that packet arrived on an oif.
2001 		     * It is bad, but otherwise we would need to move pretty
2002 		     * large chunk of pimd to kernel. Ough... --ANK
2003 		     */
2004 		    (mrt->mroute_do_pim ||
2005 		     c->_c.mfc_un.res.ttls[true_vifi] < 255) &&
2006 		    time_after(jiffies,
2007 			       c->_c.mfc_un.res.last_assert +
2008 			       MFC_ASSERT_THRESH)) {
2009 			c->_c.mfc_un.res.last_assert = jiffies;
2010 			ipmr_cache_report(mrt, skb, true_vifi, IGMPMSG_WRONGVIF);
2011 			if (mrt->mroute_do_wrvifwhole)
2012 				ipmr_cache_report(mrt, skb, true_vifi,
2013 						  IGMPMSG_WRVIFWHOLE);
2014 		}
2015 		goto dont_forward;
2016 	}
2017 
2018 forward:
2019 	WRITE_ONCE(mrt->vif_table[vif].pkt_in,
2020 		   mrt->vif_table[vif].pkt_in + 1);
2021 	WRITE_ONCE(mrt->vif_table[vif].bytes_in,
2022 		   mrt->vif_table[vif].bytes_in + skb->len);
2023 
2024 	/* Forward the frame */
2025 	if (c->mfc_origin == htonl(INADDR_ANY) &&
2026 	    c->mfc_mcastgrp == htonl(INADDR_ANY)) {
2027 		if (true_vifi >= 0 &&
2028 		    true_vifi != c->_c.mfc_parent &&
2029 		    ip_hdr(skb)->ttl >
2030 				c->_c.mfc_un.res.ttls[c->_c.mfc_parent]) {
2031 			/* It's an (*,*) entry and the packet is not coming from
2032 			 * the upstream: forward the packet to the upstream
2033 			 * only.
2034 			 */
2035 			psend = c->_c.mfc_parent;
2036 			goto last_forward;
2037 		}
2038 		goto dont_forward;
2039 	}
2040 	for (ct = c->_c.mfc_un.res.maxvif - 1;
2041 	     ct >= c->_c.mfc_un.res.minvif; ct--) {
2042 		/* For (*,G) entry, don't forward to the incoming interface */
2043 		if ((c->mfc_origin != htonl(INADDR_ANY) ||
2044 		     ct != true_vifi) &&
2045 		    ip_hdr(skb)->ttl > c->_c.mfc_un.res.ttls[ct]) {
2046 			if (psend != -1) {
2047 				struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
2048 
2049 				if (skb2)
2050 					ipmr_queue_xmit(net, mrt, true_vifi,
2051 							skb2, psend);
2052 			}
2053 			psend = ct;
2054 		}
2055 	}
2056 last_forward:
2057 	if (psend != -1) {
2058 		if (local) {
2059 			struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
2060 
2061 			if (skb2)
2062 				ipmr_queue_xmit(net, mrt, true_vifi, skb2,
2063 						psend);
2064 		} else {
2065 			ipmr_queue_xmit(net, mrt, true_vifi, skb, psend);
2066 			return;
2067 		}
2068 	}
2069 
2070 dont_forward:
2071 	if (!local)
2072 		kfree_skb(skb);
2073 }
2074 
2075 static struct mr_table *ipmr_rt_fib_lookup(struct net *net, struct sk_buff *skb)
2076 {
2077 	struct rtable *rt = skb_rtable(skb);
2078 	struct iphdr *iph = ip_hdr(skb);
2079 	struct flowi4 fl4 = {
2080 		.daddr = iph->daddr,
2081 		.saddr = iph->saddr,
2082 		.flowi4_tos = RT_TOS(iph->tos),
2083 		.flowi4_oif = (rt_is_output_route(rt) ?
2084 			       skb->dev->ifindex : 0),
2085 		.flowi4_iif = (rt_is_output_route(rt) ?
2086 			       LOOPBACK_IFINDEX :
2087 			       skb->dev->ifindex),
2088 		.flowi4_mark = skb->mark,
2089 	};
2090 	struct mr_table *mrt;
2091 	int err;
2092 
2093 	err = ipmr_fib_lookup(net, &fl4, &mrt);
2094 	if (err)
2095 		return ERR_PTR(err);
2096 	return mrt;
2097 }
2098 
2099 /* Multicast packets for forwarding arrive here
2100  * Called with rcu_read_lock();
2101  */
2102 int ip_mr_input(struct sk_buff *skb)
2103 {
2104 	struct mfc_cache *cache;
2105 	struct net *net = dev_net(skb->dev);
2106 	int local = skb_rtable(skb)->rt_flags & RTCF_LOCAL;
2107 	struct mr_table *mrt;
2108 	struct net_device *dev;
2109 
2110 	/* skb->dev passed in is the loX master dev for vrfs.
2111 	 * As there are no vifs associated with loopback devices,
2112 	 * get the proper interface that does have a vif associated with it.
2113 	 */
2114 	dev = skb->dev;
2115 	if (netif_is_l3_master(skb->dev)) {
2116 		dev = dev_get_by_index_rcu(net, IPCB(skb)->iif);
2117 		if (!dev) {
2118 			kfree_skb(skb);
2119 			return -ENODEV;
2120 		}
2121 	}
2122 
2123 	/* Packet is looped back after forward, it should not be
2124 	 * forwarded second time, but still can be delivered locally.
2125 	 */
2126 	if (IPCB(skb)->flags & IPSKB_FORWARDED)
2127 		goto dont_forward;
2128 
2129 	mrt = ipmr_rt_fib_lookup(net, skb);
2130 	if (IS_ERR(mrt)) {
2131 		kfree_skb(skb);
2132 		return PTR_ERR(mrt);
2133 	}
2134 	if (!local) {
2135 		if (IPCB(skb)->opt.router_alert) {
2136 			if (ip_call_ra_chain(skb))
2137 				return 0;
2138 		} else if (ip_hdr(skb)->protocol == IPPROTO_IGMP) {
2139 			/* IGMPv1 (and broken IGMPv2 implementations sort of
2140 			 * Cisco IOS <= 11.2(8)) do not put router alert
2141 			 * option to IGMP packets destined to routable
2142 			 * groups. It is very bad, because it means
2143 			 * that we can forward NO IGMP messages.
2144 			 */
2145 			struct sock *mroute_sk;
2146 
2147 			mroute_sk = rcu_dereference(mrt->mroute_sk);
2148 			if (mroute_sk) {
2149 				nf_reset_ct(skb);
2150 				raw_rcv(mroute_sk, skb);
2151 				return 0;
2152 			}
2153 		}
2154 	}
2155 
2156 	/* already under rcu_read_lock() */
2157 	cache = ipmr_cache_find(mrt, ip_hdr(skb)->saddr, ip_hdr(skb)->daddr);
2158 	if (!cache) {
2159 		int vif = ipmr_find_vif(mrt, dev);
2160 
2161 		if (vif >= 0)
2162 			cache = ipmr_cache_find_any(mrt, ip_hdr(skb)->daddr,
2163 						    vif);
2164 	}
2165 
2166 	/* No usable cache entry */
2167 	if (!cache) {
2168 		int vif;
2169 
2170 		if (local) {
2171 			struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
2172 			ip_local_deliver(skb);
2173 			if (!skb2)
2174 				return -ENOBUFS;
2175 			skb = skb2;
2176 		}
2177 
2178 		vif = ipmr_find_vif(mrt, dev);
2179 		if (vif >= 0)
2180 			return ipmr_cache_unresolved(mrt, vif, skb, dev);
2181 		kfree_skb(skb);
2182 		return -ENODEV;
2183 	}
2184 
2185 	ip_mr_forward(net, mrt, dev, skb, cache, local);
2186 
2187 	if (local)
2188 		return ip_local_deliver(skb);
2189 
2190 	return 0;
2191 
2192 dont_forward:
2193 	if (local)
2194 		return ip_local_deliver(skb);
2195 	kfree_skb(skb);
2196 	return 0;
2197 }
2198 
2199 #ifdef CONFIG_IP_PIMSM_V1
2200 /* Handle IGMP messages of PIMv1 */
2201 int pim_rcv_v1(struct sk_buff *skb)
2202 {
2203 	struct igmphdr *pim;
2204 	struct net *net = dev_net(skb->dev);
2205 	struct mr_table *mrt;
2206 
2207 	if (!pskb_may_pull(skb, sizeof(*pim) + sizeof(struct iphdr)))
2208 		goto drop;
2209 
2210 	pim = igmp_hdr(skb);
2211 
2212 	mrt = ipmr_rt_fib_lookup(net, skb);
2213 	if (IS_ERR(mrt))
2214 		goto drop;
2215 	if (!mrt->mroute_do_pim ||
2216 	    pim->group != PIM_V1_VERSION || pim->code != PIM_V1_REGISTER)
2217 		goto drop;
2218 
2219 	if (__pim_rcv(mrt, skb, sizeof(*pim))) {
2220 drop:
2221 		kfree_skb(skb);
2222 	}
2223 	return 0;
2224 }
2225 #endif
2226 
2227 #ifdef CONFIG_IP_PIMSM_V2
2228 static int pim_rcv(struct sk_buff *skb)
2229 {
2230 	struct pimreghdr *pim;
2231 	struct net *net = dev_net(skb->dev);
2232 	struct mr_table *mrt;
2233 
2234 	if (!pskb_may_pull(skb, sizeof(*pim) + sizeof(struct iphdr)))
2235 		goto drop;
2236 
2237 	pim = (struct pimreghdr *)skb_transport_header(skb);
2238 	if (pim->type != ((PIM_VERSION << 4) | (PIM_TYPE_REGISTER)) ||
2239 	    (pim->flags & PIM_NULL_REGISTER) ||
2240 	    (ip_compute_csum((void *)pim, sizeof(*pim)) != 0 &&
2241 	     csum_fold(skb_checksum(skb, 0, skb->len, 0))))
2242 		goto drop;
2243 
2244 	mrt = ipmr_rt_fib_lookup(net, skb);
2245 	if (IS_ERR(mrt))
2246 		goto drop;
2247 	if (__pim_rcv(mrt, skb, sizeof(*pim))) {
2248 drop:
2249 		kfree_skb(skb);
2250 	}
2251 	return 0;
2252 }
2253 #endif
2254 
2255 int ipmr_get_route(struct net *net, struct sk_buff *skb,
2256 		   __be32 saddr, __be32 daddr,
2257 		   struct rtmsg *rtm, u32 portid)
2258 {
2259 	struct mfc_cache *cache;
2260 	struct mr_table *mrt;
2261 	int err;
2262 
2263 	mrt = ipmr_get_table(net, RT_TABLE_DEFAULT);
2264 	if (!mrt)
2265 		return -ENOENT;
2266 
2267 	rcu_read_lock();
2268 	cache = ipmr_cache_find(mrt, saddr, daddr);
2269 	if (!cache && skb->dev) {
2270 		int vif = ipmr_find_vif(mrt, skb->dev);
2271 
2272 		if (vif >= 0)
2273 			cache = ipmr_cache_find_any(mrt, daddr, vif);
2274 	}
2275 	if (!cache) {
2276 		struct sk_buff *skb2;
2277 		struct iphdr *iph;
2278 		struct net_device *dev;
2279 		int vif = -1;
2280 
2281 		dev = skb->dev;
2282 		if (dev)
2283 			vif = ipmr_find_vif(mrt, dev);
2284 		if (vif < 0) {
2285 			rcu_read_unlock();
2286 			return -ENODEV;
2287 		}
2288 
2289 		skb2 = skb_realloc_headroom(skb, sizeof(struct iphdr));
2290 		if (!skb2) {
2291 			rcu_read_unlock();
2292 			return -ENOMEM;
2293 		}
2294 
2295 		NETLINK_CB(skb2).portid = portid;
2296 		skb_push(skb2, sizeof(struct iphdr));
2297 		skb_reset_network_header(skb2);
2298 		iph = ip_hdr(skb2);
2299 		iph->ihl = sizeof(struct iphdr) >> 2;
2300 		iph->saddr = saddr;
2301 		iph->daddr = daddr;
2302 		iph->version = 0;
2303 		err = ipmr_cache_unresolved(mrt, vif, skb2, dev);
2304 		rcu_read_unlock();
2305 		return err;
2306 	}
2307 
2308 	err = mr_fill_mroute(mrt, skb, &cache->_c, rtm);
2309 	rcu_read_unlock();
2310 	return err;
2311 }
2312 
2313 static int ipmr_fill_mroute(struct mr_table *mrt, struct sk_buff *skb,
2314 			    u32 portid, u32 seq, struct mfc_cache *c, int cmd,
2315 			    int flags)
2316 {
2317 	struct nlmsghdr *nlh;
2318 	struct rtmsg *rtm;
2319 	int err;
2320 
2321 	nlh = nlmsg_put(skb, portid, seq, cmd, sizeof(*rtm), flags);
2322 	if (!nlh)
2323 		return -EMSGSIZE;
2324 
2325 	rtm = nlmsg_data(nlh);
2326 	rtm->rtm_family   = RTNL_FAMILY_IPMR;
2327 	rtm->rtm_dst_len  = 32;
2328 	rtm->rtm_src_len  = 32;
2329 	rtm->rtm_tos      = 0;
2330 	rtm->rtm_table    = mrt->id;
2331 	if (nla_put_u32(skb, RTA_TABLE, mrt->id))
2332 		goto nla_put_failure;
2333 	rtm->rtm_type     = RTN_MULTICAST;
2334 	rtm->rtm_scope    = RT_SCOPE_UNIVERSE;
2335 	if (c->_c.mfc_flags & MFC_STATIC)
2336 		rtm->rtm_protocol = RTPROT_STATIC;
2337 	else
2338 		rtm->rtm_protocol = RTPROT_MROUTED;
2339 	rtm->rtm_flags    = 0;
2340 
2341 	if (nla_put_in_addr(skb, RTA_SRC, c->mfc_origin) ||
2342 	    nla_put_in_addr(skb, RTA_DST, c->mfc_mcastgrp))
2343 		goto nla_put_failure;
2344 	err = mr_fill_mroute(mrt, skb, &c->_c, rtm);
2345 	/* do not break the dump if cache is unresolved */
2346 	if (err < 0 && err != -ENOENT)
2347 		goto nla_put_failure;
2348 
2349 	nlmsg_end(skb, nlh);
2350 	return 0;
2351 
2352 nla_put_failure:
2353 	nlmsg_cancel(skb, nlh);
2354 	return -EMSGSIZE;
2355 }
2356 
2357 static int _ipmr_fill_mroute(struct mr_table *mrt, struct sk_buff *skb,
2358 			     u32 portid, u32 seq, struct mr_mfc *c, int cmd,
2359 			     int flags)
2360 {
2361 	return ipmr_fill_mroute(mrt, skb, portid, seq, (struct mfc_cache *)c,
2362 				cmd, flags);
2363 }
2364 
2365 static size_t mroute_msgsize(bool unresolved, int maxvif)
2366 {
2367 	size_t len =
2368 		NLMSG_ALIGN(sizeof(struct rtmsg))
2369 		+ nla_total_size(4)	/* RTA_TABLE */
2370 		+ nla_total_size(4)	/* RTA_SRC */
2371 		+ nla_total_size(4)	/* RTA_DST */
2372 		;
2373 
2374 	if (!unresolved)
2375 		len = len
2376 		      + nla_total_size(4)	/* RTA_IIF */
2377 		      + nla_total_size(0)	/* RTA_MULTIPATH */
2378 		      + maxvif * NLA_ALIGN(sizeof(struct rtnexthop))
2379 						/* RTA_MFC_STATS */
2380 		      + nla_total_size_64bit(sizeof(struct rta_mfc_stats))
2381 		;
2382 
2383 	return len;
2384 }
2385 
2386 static void mroute_netlink_event(struct mr_table *mrt, struct mfc_cache *mfc,
2387 				 int cmd)
2388 {
2389 	struct net *net = read_pnet(&mrt->net);
2390 	struct sk_buff *skb;
2391 	int err = -ENOBUFS;
2392 
2393 	skb = nlmsg_new(mroute_msgsize(mfc->_c.mfc_parent >= MAXVIFS,
2394 				       mrt->maxvif),
2395 			GFP_ATOMIC);
2396 	if (!skb)
2397 		goto errout;
2398 
2399 	err = ipmr_fill_mroute(mrt, skb, 0, 0, mfc, cmd, 0);
2400 	if (err < 0)
2401 		goto errout;
2402 
2403 	rtnl_notify(skb, net, 0, RTNLGRP_IPV4_MROUTE, NULL, GFP_ATOMIC);
2404 	return;
2405 
2406 errout:
2407 	kfree_skb(skb);
2408 	if (err < 0)
2409 		rtnl_set_sk_err(net, RTNLGRP_IPV4_MROUTE, err);
2410 }
2411 
2412 static size_t igmpmsg_netlink_msgsize(size_t payloadlen)
2413 {
2414 	size_t len =
2415 		NLMSG_ALIGN(sizeof(struct rtgenmsg))
2416 		+ nla_total_size(1)	/* IPMRA_CREPORT_MSGTYPE */
2417 		+ nla_total_size(4)	/* IPMRA_CREPORT_VIF_ID */
2418 		+ nla_total_size(4)	/* IPMRA_CREPORT_SRC_ADDR */
2419 		+ nla_total_size(4)	/* IPMRA_CREPORT_DST_ADDR */
2420 		+ nla_total_size(4)	/* IPMRA_CREPORT_TABLE */
2421 					/* IPMRA_CREPORT_PKT */
2422 		+ nla_total_size(payloadlen)
2423 		;
2424 
2425 	return len;
2426 }
2427 
2428 static void igmpmsg_netlink_event(const struct mr_table *mrt, struct sk_buff *pkt)
2429 {
2430 	struct net *net = read_pnet(&mrt->net);
2431 	struct nlmsghdr *nlh;
2432 	struct rtgenmsg *rtgenm;
2433 	struct igmpmsg *msg;
2434 	struct sk_buff *skb;
2435 	struct nlattr *nla;
2436 	int payloadlen;
2437 
2438 	payloadlen = pkt->len - sizeof(struct igmpmsg);
2439 	msg = (struct igmpmsg *)skb_network_header(pkt);
2440 
2441 	skb = nlmsg_new(igmpmsg_netlink_msgsize(payloadlen), GFP_ATOMIC);
2442 	if (!skb)
2443 		goto errout;
2444 
2445 	nlh = nlmsg_put(skb, 0, 0, RTM_NEWCACHEREPORT,
2446 			sizeof(struct rtgenmsg), 0);
2447 	if (!nlh)
2448 		goto errout;
2449 	rtgenm = nlmsg_data(nlh);
2450 	rtgenm->rtgen_family = RTNL_FAMILY_IPMR;
2451 	if (nla_put_u8(skb, IPMRA_CREPORT_MSGTYPE, msg->im_msgtype) ||
2452 	    nla_put_u32(skb, IPMRA_CREPORT_VIF_ID, msg->im_vif | (msg->im_vif_hi << 8)) ||
2453 	    nla_put_in_addr(skb, IPMRA_CREPORT_SRC_ADDR,
2454 			    msg->im_src.s_addr) ||
2455 	    nla_put_in_addr(skb, IPMRA_CREPORT_DST_ADDR,
2456 			    msg->im_dst.s_addr) ||
2457 	    nla_put_u32(skb, IPMRA_CREPORT_TABLE, mrt->id))
2458 		goto nla_put_failure;
2459 
2460 	nla = nla_reserve(skb, IPMRA_CREPORT_PKT, payloadlen);
2461 	if (!nla || skb_copy_bits(pkt, sizeof(struct igmpmsg),
2462 				  nla_data(nla), payloadlen))
2463 		goto nla_put_failure;
2464 
2465 	nlmsg_end(skb, nlh);
2466 
2467 	rtnl_notify(skb, net, 0, RTNLGRP_IPV4_MROUTE_R, NULL, GFP_ATOMIC);
2468 	return;
2469 
2470 nla_put_failure:
2471 	nlmsg_cancel(skb, nlh);
2472 errout:
2473 	kfree_skb(skb);
2474 	rtnl_set_sk_err(net, RTNLGRP_IPV4_MROUTE_R, -ENOBUFS);
2475 }
2476 
2477 static int ipmr_rtm_valid_getroute_req(struct sk_buff *skb,
2478 				       const struct nlmsghdr *nlh,
2479 				       struct nlattr **tb,
2480 				       struct netlink_ext_ack *extack)
2481 {
2482 	struct rtmsg *rtm;
2483 	int i, err;
2484 
2485 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) {
2486 		NL_SET_ERR_MSG(extack, "ipv4: Invalid header for multicast route get request");
2487 		return -EINVAL;
2488 	}
2489 
2490 	if (!netlink_strict_get_check(skb))
2491 		return nlmsg_parse_deprecated(nlh, sizeof(*rtm), tb, RTA_MAX,
2492 					      rtm_ipv4_policy, extack);
2493 
2494 	rtm = nlmsg_data(nlh);
2495 	if ((rtm->rtm_src_len && rtm->rtm_src_len != 32) ||
2496 	    (rtm->rtm_dst_len && rtm->rtm_dst_len != 32) ||
2497 	    rtm->rtm_tos || rtm->rtm_table || rtm->rtm_protocol ||
2498 	    rtm->rtm_scope || rtm->rtm_type || rtm->rtm_flags) {
2499 		NL_SET_ERR_MSG(extack, "ipv4: Invalid values in header for multicast route get request");
2500 		return -EINVAL;
2501 	}
2502 
2503 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(*rtm), tb, RTA_MAX,
2504 					    rtm_ipv4_policy, extack);
2505 	if (err)
2506 		return err;
2507 
2508 	if ((tb[RTA_SRC] && !rtm->rtm_src_len) ||
2509 	    (tb[RTA_DST] && !rtm->rtm_dst_len)) {
2510 		NL_SET_ERR_MSG(extack, "ipv4: rtm_src_len and rtm_dst_len must be 32 for IPv4");
2511 		return -EINVAL;
2512 	}
2513 
2514 	for (i = 0; i <= RTA_MAX; i++) {
2515 		if (!tb[i])
2516 			continue;
2517 
2518 		switch (i) {
2519 		case RTA_SRC:
2520 		case RTA_DST:
2521 		case RTA_TABLE:
2522 			break;
2523 		default:
2524 			NL_SET_ERR_MSG(extack, "ipv4: Unsupported attribute in multicast route get request");
2525 			return -EINVAL;
2526 		}
2527 	}
2528 
2529 	return 0;
2530 }
2531 
2532 static int ipmr_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
2533 			     struct netlink_ext_ack *extack)
2534 {
2535 	struct net *net = sock_net(in_skb->sk);
2536 	struct nlattr *tb[RTA_MAX + 1];
2537 	struct sk_buff *skb = NULL;
2538 	struct mfc_cache *cache;
2539 	struct mr_table *mrt;
2540 	__be32 src, grp;
2541 	u32 tableid;
2542 	int err;
2543 
2544 	err = ipmr_rtm_valid_getroute_req(in_skb, nlh, tb, extack);
2545 	if (err < 0)
2546 		goto errout;
2547 
2548 	src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
2549 	grp = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
2550 	tableid = tb[RTA_TABLE] ? nla_get_u32(tb[RTA_TABLE]) : 0;
2551 
2552 	mrt = ipmr_get_table(net, tableid ? tableid : RT_TABLE_DEFAULT);
2553 	if (!mrt) {
2554 		err = -ENOENT;
2555 		goto errout_free;
2556 	}
2557 
2558 	/* entries are added/deleted only under RTNL */
2559 	rcu_read_lock();
2560 	cache = ipmr_cache_find(mrt, src, grp);
2561 	rcu_read_unlock();
2562 	if (!cache) {
2563 		err = -ENOENT;
2564 		goto errout_free;
2565 	}
2566 
2567 	skb = nlmsg_new(mroute_msgsize(false, mrt->maxvif), GFP_KERNEL);
2568 	if (!skb) {
2569 		err = -ENOBUFS;
2570 		goto errout_free;
2571 	}
2572 
2573 	err = ipmr_fill_mroute(mrt, skb, NETLINK_CB(in_skb).portid,
2574 			       nlh->nlmsg_seq, cache,
2575 			       RTM_NEWROUTE, 0);
2576 	if (err < 0)
2577 		goto errout_free;
2578 
2579 	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
2580 
2581 errout:
2582 	return err;
2583 
2584 errout_free:
2585 	kfree_skb(skb);
2586 	goto errout;
2587 }
2588 
2589 static int ipmr_rtm_dumproute(struct sk_buff *skb, struct netlink_callback *cb)
2590 {
2591 	struct fib_dump_filter filter = {};
2592 	int err;
2593 
2594 	if (cb->strict_check) {
2595 		err = ip_valid_fib_dump_req(sock_net(skb->sk), cb->nlh,
2596 					    &filter, cb);
2597 		if (err < 0)
2598 			return err;
2599 	}
2600 
2601 	if (filter.table_id) {
2602 		struct mr_table *mrt;
2603 
2604 		mrt = ipmr_get_table(sock_net(skb->sk), filter.table_id);
2605 		if (!mrt) {
2606 			if (rtnl_msg_family(cb->nlh) != RTNL_FAMILY_IPMR)
2607 				return skb->len;
2608 
2609 			NL_SET_ERR_MSG(cb->extack, "ipv4: MR table does not exist");
2610 			return -ENOENT;
2611 		}
2612 		err = mr_table_dump(mrt, skb, cb, _ipmr_fill_mroute,
2613 				    &mfc_unres_lock, &filter);
2614 		return skb->len ? : err;
2615 	}
2616 
2617 	return mr_rtm_dumproute(skb, cb, ipmr_mr_table_iter,
2618 				_ipmr_fill_mroute, &mfc_unres_lock, &filter);
2619 }
2620 
2621 static const struct nla_policy rtm_ipmr_policy[RTA_MAX + 1] = {
2622 	[RTA_SRC]	= { .type = NLA_U32 },
2623 	[RTA_DST]	= { .type = NLA_U32 },
2624 	[RTA_IIF]	= { .type = NLA_U32 },
2625 	[RTA_TABLE]	= { .type = NLA_U32 },
2626 	[RTA_MULTIPATH]	= { .len = sizeof(struct rtnexthop) },
2627 };
2628 
2629 static bool ipmr_rtm_validate_proto(unsigned char rtm_protocol)
2630 {
2631 	switch (rtm_protocol) {
2632 	case RTPROT_STATIC:
2633 	case RTPROT_MROUTED:
2634 		return true;
2635 	}
2636 	return false;
2637 }
2638 
2639 static int ipmr_nla_get_ttls(const struct nlattr *nla, struct mfcctl *mfcc)
2640 {
2641 	struct rtnexthop *rtnh = nla_data(nla);
2642 	int remaining = nla_len(nla), vifi = 0;
2643 
2644 	while (rtnh_ok(rtnh, remaining)) {
2645 		mfcc->mfcc_ttls[vifi] = rtnh->rtnh_hops;
2646 		if (++vifi == MAXVIFS)
2647 			break;
2648 		rtnh = rtnh_next(rtnh, &remaining);
2649 	}
2650 
2651 	return remaining > 0 ? -EINVAL : vifi;
2652 }
2653 
2654 /* returns < 0 on error, 0 for ADD_MFC and 1 for ADD_MFC_PROXY */
2655 static int rtm_to_ipmr_mfcc(struct net *net, struct nlmsghdr *nlh,
2656 			    struct mfcctl *mfcc, int *mrtsock,
2657 			    struct mr_table **mrtret,
2658 			    struct netlink_ext_ack *extack)
2659 {
2660 	struct net_device *dev = NULL;
2661 	u32 tblid = RT_TABLE_DEFAULT;
2662 	struct mr_table *mrt;
2663 	struct nlattr *attr;
2664 	struct rtmsg *rtm;
2665 	int ret, rem;
2666 
2667 	ret = nlmsg_validate_deprecated(nlh, sizeof(*rtm), RTA_MAX,
2668 					rtm_ipmr_policy, extack);
2669 	if (ret < 0)
2670 		goto out;
2671 	rtm = nlmsg_data(nlh);
2672 
2673 	ret = -EINVAL;
2674 	if (rtm->rtm_family != RTNL_FAMILY_IPMR || rtm->rtm_dst_len != 32 ||
2675 	    rtm->rtm_type != RTN_MULTICAST ||
2676 	    rtm->rtm_scope != RT_SCOPE_UNIVERSE ||
2677 	    !ipmr_rtm_validate_proto(rtm->rtm_protocol))
2678 		goto out;
2679 
2680 	memset(mfcc, 0, sizeof(*mfcc));
2681 	mfcc->mfcc_parent = -1;
2682 	ret = 0;
2683 	nlmsg_for_each_attr(attr, nlh, sizeof(struct rtmsg), rem) {
2684 		switch (nla_type(attr)) {
2685 		case RTA_SRC:
2686 			mfcc->mfcc_origin.s_addr = nla_get_be32(attr);
2687 			break;
2688 		case RTA_DST:
2689 			mfcc->mfcc_mcastgrp.s_addr = nla_get_be32(attr);
2690 			break;
2691 		case RTA_IIF:
2692 			dev = __dev_get_by_index(net, nla_get_u32(attr));
2693 			if (!dev) {
2694 				ret = -ENODEV;
2695 				goto out;
2696 			}
2697 			break;
2698 		case RTA_MULTIPATH:
2699 			if (ipmr_nla_get_ttls(attr, mfcc) < 0) {
2700 				ret = -EINVAL;
2701 				goto out;
2702 			}
2703 			break;
2704 		case RTA_PREFSRC:
2705 			ret = 1;
2706 			break;
2707 		case RTA_TABLE:
2708 			tblid = nla_get_u32(attr);
2709 			break;
2710 		}
2711 	}
2712 	mrt = ipmr_get_table(net, tblid);
2713 	if (!mrt) {
2714 		ret = -ENOENT;
2715 		goto out;
2716 	}
2717 	*mrtret = mrt;
2718 	*mrtsock = rtm->rtm_protocol == RTPROT_MROUTED ? 1 : 0;
2719 	if (dev)
2720 		mfcc->mfcc_parent = ipmr_find_vif(mrt, dev);
2721 
2722 out:
2723 	return ret;
2724 }
2725 
2726 /* takes care of both newroute and delroute */
2727 static int ipmr_rtm_route(struct sk_buff *skb, struct nlmsghdr *nlh,
2728 			  struct netlink_ext_ack *extack)
2729 {
2730 	struct net *net = sock_net(skb->sk);
2731 	int ret, mrtsock, parent;
2732 	struct mr_table *tbl;
2733 	struct mfcctl mfcc;
2734 
2735 	mrtsock = 0;
2736 	tbl = NULL;
2737 	ret = rtm_to_ipmr_mfcc(net, nlh, &mfcc, &mrtsock, &tbl, extack);
2738 	if (ret < 0)
2739 		return ret;
2740 
2741 	parent = ret ? mfcc.mfcc_parent : -1;
2742 	if (nlh->nlmsg_type == RTM_NEWROUTE)
2743 		return ipmr_mfc_add(net, tbl, &mfcc, mrtsock, parent);
2744 	else
2745 		return ipmr_mfc_delete(tbl, &mfcc, parent);
2746 }
2747 
2748 static bool ipmr_fill_table(struct mr_table *mrt, struct sk_buff *skb)
2749 {
2750 	u32 queue_len = atomic_read(&mrt->cache_resolve_queue_len);
2751 
2752 	if (nla_put_u32(skb, IPMRA_TABLE_ID, mrt->id) ||
2753 	    nla_put_u32(skb, IPMRA_TABLE_CACHE_RES_QUEUE_LEN, queue_len) ||
2754 	    nla_put_s32(skb, IPMRA_TABLE_MROUTE_REG_VIF_NUM,
2755 			mrt->mroute_reg_vif_num) ||
2756 	    nla_put_u8(skb, IPMRA_TABLE_MROUTE_DO_ASSERT,
2757 		       mrt->mroute_do_assert) ||
2758 	    nla_put_u8(skb, IPMRA_TABLE_MROUTE_DO_PIM, mrt->mroute_do_pim) ||
2759 	    nla_put_u8(skb, IPMRA_TABLE_MROUTE_DO_WRVIFWHOLE,
2760 		       mrt->mroute_do_wrvifwhole))
2761 		return false;
2762 
2763 	return true;
2764 }
2765 
2766 static bool ipmr_fill_vif(struct mr_table *mrt, u32 vifid, struct sk_buff *skb)
2767 {
2768 	struct net_device *vif_dev;
2769 	struct nlattr *vif_nest;
2770 	struct vif_device *vif;
2771 
2772 	vif = &mrt->vif_table[vifid];
2773 	vif_dev = rtnl_dereference(vif->dev);
2774 	/* if the VIF doesn't exist just continue */
2775 	if (!vif_dev)
2776 		return true;
2777 
2778 	vif_nest = nla_nest_start_noflag(skb, IPMRA_VIF);
2779 	if (!vif_nest)
2780 		return false;
2781 
2782 	if (nla_put_u32(skb, IPMRA_VIFA_IFINDEX, vif_dev->ifindex) ||
2783 	    nla_put_u32(skb, IPMRA_VIFA_VIF_ID, vifid) ||
2784 	    nla_put_u16(skb, IPMRA_VIFA_FLAGS, vif->flags) ||
2785 	    nla_put_u64_64bit(skb, IPMRA_VIFA_BYTES_IN, vif->bytes_in,
2786 			      IPMRA_VIFA_PAD) ||
2787 	    nla_put_u64_64bit(skb, IPMRA_VIFA_BYTES_OUT, vif->bytes_out,
2788 			      IPMRA_VIFA_PAD) ||
2789 	    nla_put_u64_64bit(skb, IPMRA_VIFA_PACKETS_IN, vif->pkt_in,
2790 			      IPMRA_VIFA_PAD) ||
2791 	    nla_put_u64_64bit(skb, IPMRA_VIFA_PACKETS_OUT, vif->pkt_out,
2792 			      IPMRA_VIFA_PAD) ||
2793 	    nla_put_be32(skb, IPMRA_VIFA_LOCAL_ADDR, vif->local) ||
2794 	    nla_put_be32(skb, IPMRA_VIFA_REMOTE_ADDR, vif->remote)) {
2795 		nla_nest_cancel(skb, vif_nest);
2796 		return false;
2797 	}
2798 	nla_nest_end(skb, vif_nest);
2799 
2800 	return true;
2801 }
2802 
2803 static int ipmr_valid_dumplink(const struct nlmsghdr *nlh,
2804 			       struct netlink_ext_ack *extack)
2805 {
2806 	struct ifinfomsg *ifm;
2807 
2808 	if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*ifm))) {
2809 		NL_SET_ERR_MSG(extack, "ipv4: Invalid header for ipmr link dump");
2810 		return -EINVAL;
2811 	}
2812 
2813 	if (nlmsg_attrlen(nlh, sizeof(*ifm))) {
2814 		NL_SET_ERR_MSG(extack, "Invalid data after header in ipmr link dump");
2815 		return -EINVAL;
2816 	}
2817 
2818 	ifm = nlmsg_data(nlh);
2819 	if (ifm->__ifi_pad || ifm->ifi_type || ifm->ifi_flags ||
2820 	    ifm->ifi_change || ifm->ifi_index) {
2821 		NL_SET_ERR_MSG(extack, "Invalid values in header for ipmr link dump request");
2822 		return -EINVAL;
2823 	}
2824 
2825 	return 0;
2826 }
2827 
2828 static int ipmr_rtm_dumplink(struct sk_buff *skb, struct netlink_callback *cb)
2829 {
2830 	struct net *net = sock_net(skb->sk);
2831 	struct nlmsghdr *nlh = NULL;
2832 	unsigned int t = 0, s_t;
2833 	unsigned int e = 0, s_e;
2834 	struct mr_table *mrt;
2835 
2836 	if (cb->strict_check) {
2837 		int err = ipmr_valid_dumplink(cb->nlh, cb->extack);
2838 
2839 		if (err < 0)
2840 			return err;
2841 	}
2842 
2843 	s_t = cb->args[0];
2844 	s_e = cb->args[1];
2845 
2846 	ipmr_for_each_table(mrt, net) {
2847 		struct nlattr *vifs, *af;
2848 		struct ifinfomsg *hdr;
2849 		u32 i;
2850 
2851 		if (t < s_t)
2852 			goto skip_table;
2853 		nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
2854 				cb->nlh->nlmsg_seq, RTM_NEWLINK,
2855 				sizeof(*hdr), NLM_F_MULTI);
2856 		if (!nlh)
2857 			break;
2858 
2859 		hdr = nlmsg_data(nlh);
2860 		memset(hdr, 0, sizeof(*hdr));
2861 		hdr->ifi_family = RTNL_FAMILY_IPMR;
2862 
2863 		af = nla_nest_start_noflag(skb, IFLA_AF_SPEC);
2864 		if (!af) {
2865 			nlmsg_cancel(skb, nlh);
2866 			goto out;
2867 		}
2868 
2869 		if (!ipmr_fill_table(mrt, skb)) {
2870 			nlmsg_cancel(skb, nlh);
2871 			goto out;
2872 		}
2873 
2874 		vifs = nla_nest_start_noflag(skb, IPMRA_TABLE_VIFS);
2875 		if (!vifs) {
2876 			nla_nest_end(skb, af);
2877 			nlmsg_end(skb, nlh);
2878 			goto out;
2879 		}
2880 		for (i = 0; i < mrt->maxvif; i++) {
2881 			if (e < s_e)
2882 				goto skip_entry;
2883 			if (!ipmr_fill_vif(mrt, i, skb)) {
2884 				nla_nest_end(skb, vifs);
2885 				nla_nest_end(skb, af);
2886 				nlmsg_end(skb, nlh);
2887 				goto out;
2888 			}
2889 skip_entry:
2890 			e++;
2891 		}
2892 		s_e = 0;
2893 		e = 0;
2894 		nla_nest_end(skb, vifs);
2895 		nla_nest_end(skb, af);
2896 		nlmsg_end(skb, nlh);
2897 skip_table:
2898 		t++;
2899 	}
2900 
2901 out:
2902 	cb->args[1] = e;
2903 	cb->args[0] = t;
2904 
2905 	return skb->len;
2906 }
2907 
2908 #ifdef CONFIG_PROC_FS
2909 /* The /proc interfaces to multicast routing :
2910  * /proc/net/ip_mr_cache & /proc/net/ip_mr_vif
2911  */
2912 
2913 static void *ipmr_vif_seq_start(struct seq_file *seq, loff_t *pos)
2914 	__acquires(RCU)
2915 {
2916 	struct mr_vif_iter *iter = seq->private;
2917 	struct net *net = seq_file_net(seq);
2918 	struct mr_table *mrt;
2919 
2920 	mrt = ipmr_get_table(net, RT_TABLE_DEFAULT);
2921 	if (!mrt)
2922 		return ERR_PTR(-ENOENT);
2923 
2924 	iter->mrt = mrt;
2925 
2926 	rcu_read_lock();
2927 	return mr_vif_seq_start(seq, pos);
2928 }
2929 
2930 static void ipmr_vif_seq_stop(struct seq_file *seq, void *v)
2931 	__releases(RCU)
2932 {
2933 	rcu_read_unlock();
2934 }
2935 
2936 static int ipmr_vif_seq_show(struct seq_file *seq, void *v)
2937 {
2938 	struct mr_vif_iter *iter = seq->private;
2939 	struct mr_table *mrt = iter->mrt;
2940 
2941 	if (v == SEQ_START_TOKEN) {
2942 		seq_puts(seq,
2943 			 "Interface      BytesIn  PktsIn  BytesOut PktsOut Flags Local    Remote\n");
2944 	} else {
2945 		const struct vif_device *vif = v;
2946 		const struct net_device *vif_dev;
2947 		const char *name;
2948 
2949 		vif_dev = vif_dev_read(vif);
2950 		name = vif_dev ? vif_dev->name : "none";
2951 		seq_printf(seq,
2952 			   "%2td %-10s %8ld %7ld  %8ld %7ld %05X %08X %08X\n",
2953 			   vif - mrt->vif_table,
2954 			   name, vif->bytes_in, vif->pkt_in,
2955 			   vif->bytes_out, vif->pkt_out,
2956 			   vif->flags, vif->local, vif->remote);
2957 	}
2958 	return 0;
2959 }
2960 
2961 static const struct seq_operations ipmr_vif_seq_ops = {
2962 	.start = ipmr_vif_seq_start,
2963 	.next  = mr_vif_seq_next,
2964 	.stop  = ipmr_vif_seq_stop,
2965 	.show  = ipmr_vif_seq_show,
2966 };
2967 
2968 static void *ipmr_mfc_seq_start(struct seq_file *seq, loff_t *pos)
2969 {
2970 	struct net *net = seq_file_net(seq);
2971 	struct mr_table *mrt;
2972 
2973 	mrt = ipmr_get_table(net, RT_TABLE_DEFAULT);
2974 	if (!mrt)
2975 		return ERR_PTR(-ENOENT);
2976 
2977 	return mr_mfc_seq_start(seq, pos, mrt, &mfc_unres_lock);
2978 }
2979 
2980 static int ipmr_mfc_seq_show(struct seq_file *seq, void *v)
2981 {
2982 	int n;
2983 
2984 	if (v == SEQ_START_TOKEN) {
2985 		seq_puts(seq,
2986 		 "Group    Origin   Iif     Pkts    Bytes    Wrong Oifs\n");
2987 	} else {
2988 		const struct mfc_cache *mfc = v;
2989 		const struct mr_mfc_iter *it = seq->private;
2990 		const struct mr_table *mrt = it->mrt;
2991 
2992 		seq_printf(seq, "%08X %08X %-3hd",
2993 			   (__force u32) mfc->mfc_mcastgrp,
2994 			   (__force u32) mfc->mfc_origin,
2995 			   mfc->_c.mfc_parent);
2996 
2997 		if (it->cache != &mrt->mfc_unres_queue) {
2998 			seq_printf(seq, " %8lu %8lu %8lu",
2999 				   mfc->_c.mfc_un.res.pkt,
3000 				   mfc->_c.mfc_un.res.bytes,
3001 				   mfc->_c.mfc_un.res.wrong_if);
3002 			for (n = mfc->_c.mfc_un.res.minvif;
3003 			     n < mfc->_c.mfc_un.res.maxvif; n++) {
3004 				if (VIF_EXISTS(mrt, n) &&
3005 				    mfc->_c.mfc_un.res.ttls[n] < 255)
3006 					seq_printf(seq,
3007 					   " %2d:%-3d",
3008 					   n, mfc->_c.mfc_un.res.ttls[n]);
3009 			}
3010 		} else {
3011 			/* unresolved mfc_caches don't contain
3012 			 * pkt, bytes and wrong_if values
3013 			 */
3014 			seq_printf(seq, " %8lu %8lu %8lu", 0ul, 0ul, 0ul);
3015 		}
3016 		seq_putc(seq, '\n');
3017 	}
3018 	return 0;
3019 }
3020 
3021 static const struct seq_operations ipmr_mfc_seq_ops = {
3022 	.start = ipmr_mfc_seq_start,
3023 	.next  = mr_mfc_seq_next,
3024 	.stop  = mr_mfc_seq_stop,
3025 	.show  = ipmr_mfc_seq_show,
3026 };
3027 #endif
3028 
3029 #ifdef CONFIG_IP_PIMSM_V2
3030 static const struct net_protocol pim_protocol = {
3031 	.handler	=	pim_rcv,
3032 };
3033 #endif
3034 
3035 static unsigned int ipmr_seq_read(struct net *net)
3036 {
3037 	ASSERT_RTNL();
3038 
3039 	return net->ipv4.ipmr_seq + ipmr_rules_seq_read(net);
3040 }
3041 
3042 static int ipmr_dump(struct net *net, struct notifier_block *nb,
3043 		     struct netlink_ext_ack *extack)
3044 {
3045 	return mr_dump(net, nb, RTNL_FAMILY_IPMR, ipmr_rules_dump,
3046 		       ipmr_mr_table_iter, extack);
3047 }
3048 
3049 static const struct fib_notifier_ops ipmr_notifier_ops_template = {
3050 	.family		= RTNL_FAMILY_IPMR,
3051 	.fib_seq_read	= ipmr_seq_read,
3052 	.fib_dump	= ipmr_dump,
3053 	.owner		= THIS_MODULE,
3054 };
3055 
3056 static int __net_init ipmr_notifier_init(struct net *net)
3057 {
3058 	struct fib_notifier_ops *ops;
3059 
3060 	net->ipv4.ipmr_seq = 0;
3061 
3062 	ops = fib_notifier_ops_register(&ipmr_notifier_ops_template, net);
3063 	if (IS_ERR(ops))
3064 		return PTR_ERR(ops);
3065 	net->ipv4.ipmr_notifier_ops = ops;
3066 
3067 	return 0;
3068 }
3069 
3070 static void __net_exit ipmr_notifier_exit(struct net *net)
3071 {
3072 	fib_notifier_ops_unregister(net->ipv4.ipmr_notifier_ops);
3073 	net->ipv4.ipmr_notifier_ops = NULL;
3074 }
3075 
3076 /* Setup for IP multicast routing */
3077 static int __net_init ipmr_net_init(struct net *net)
3078 {
3079 	int err;
3080 
3081 	err = ipmr_notifier_init(net);
3082 	if (err)
3083 		goto ipmr_notifier_fail;
3084 
3085 	err = ipmr_rules_init(net);
3086 	if (err < 0)
3087 		goto ipmr_rules_fail;
3088 
3089 #ifdef CONFIG_PROC_FS
3090 	err = -ENOMEM;
3091 	if (!proc_create_net("ip_mr_vif", 0, net->proc_net, &ipmr_vif_seq_ops,
3092 			sizeof(struct mr_vif_iter)))
3093 		goto proc_vif_fail;
3094 	if (!proc_create_net("ip_mr_cache", 0, net->proc_net, &ipmr_mfc_seq_ops,
3095 			sizeof(struct mr_mfc_iter)))
3096 		goto proc_cache_fail;
3097 #endif
3098 	return 0;
3099 
3100 #ifdef CONFIG_PROC_FS
3101 proc_cache_fail:
3102 	remove_proc_entry("ip_mr_vif", net->proc_net);
3103 proc_vif_fail:
3104 	rtnl_lock();
3105 	ipmr_rules_exit(net);
3106 	rtnl_unlock();
3107 #endif
3108 ipmr_rules_fail:
3109 	ipmr_notifier_exit(net);
3110 ipmr_notifier_fail:
3111 	return err;
3112 }
3113 
3114 static void __net_exit ipmr_net_exit(struct net *net)
3115 {
3116 #ifdef CONFIG_PROC_FS
3117 	remove_proc_entry("ip_mr_cache", net->proc_net);
3118 	remove_proc_entry("ip_mr_vif", net->proc_net);
3119 #endif
3120 	ipmr_notifier_exit(net);
3121 }
3122 
3123 static void __net_exit ipmr_net_exit_batch(struct list_head *net_list)
3124 {
3125 	struct net *net;
3126 
3127 	rtnl_lock();
3128 	list_for_each_entry(net, net_list, exit_list)
3129 		ipmr_rules_exit(net);
3130 	rtnl_unlock();
3131 }
3132 
3133 static struct pernet_operations ipmr_net_ops = {
3134 	.init = ipmr_net_init,
3135 	.exit = ipmr_net_exit,
3136 	.exit_batch = ipmr_net_exit_batch,
3137 };
3138 
3139 int __init ip_mr_init(void)
3140 {
3141 	int err;
3142 
3143 	mrt_cachep = kmem_cache_create("ip_mrt_cache",
3144 				       sizeof(struct mfc_cache),
3145 				       0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
3146 				       NULL);
3147 
3148 	err = register_pernet_subsys(&ipmr_net_ops);
3149 	if (err)
3150 		goto reg_pernet_fail;
3151 
3152 	err = register_netdevice_notifier(&ip_mr_notifier);
3153 	if (err)
3154 		goto reg_notif_fail;
3155 #ifdef CONFIG_IP_PIMSM_V2
3156 	if (inet_add_protocol(&pim_protocol, IPPROTO_PIM) < 0) {
3157 		pr_err("%s: can't add PIM protocol\n", __func__);
3158 		err = -EAGAIN;
3159 		goto add_proto_fail;
3160 	}
3161 #endif
3162 	rtnl_register(RTNL_FAMILY_IPMR, RTM_GETROUTE,
3163 		      ipmr_rtm_getroute, ipmr_rtm_dumproute, 0);
3164 	rtnl_register(RTNL_FAMILY_IPMR, RTM_NEWROUTE,
3165 		      ipmr_rtm_route, NULL, 0);
3166 	rtnl_register(RTNL_FAMILY_IPMR, RTM_DELROUTE,
3167 		      ipmr_rtm_route, NULL, 0);
3168 
3169 	rtnl_register(RTNL_FAMILY_IPMR, RTM_GETLINK,
3170 		      NULL, ipmr_rtm_dumplink, 0);
3171 	return 0;
3172 
3173 #ifdef CONFIG_IP_PIMSM_V2
3174 add_proto_fail:
3175 	unregister_netdevice_notifier(&ip_mr_notifier);
3176 #endif
3177 reg_notif_fail:
3178 	unregister_pernet_subsys(&ipmr_net_ops);
3179 reg_pernet_fail:
3180 	kmem_cache_destroy(mrt_cachep);
3181 	return err;
3182 }
3183