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