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