]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/net/can/af_can.c
Changed prototypes for CAN core exported functions to use ifindex
[socketcan-devel.git] / kernel / 2.6 / net / can / af_can.c
1 /*
2  * af_can.c - Protocol family CAN core module
3  *            (used by different CAN protocol modules)
4  *
5  * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, the following disclaimer and
13  *    the referenced file 'COPYING'.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of Volkswagen nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * Alternatively, provided that this notice is retained in full, this
22  * software may be distributed under the terms of the GNU General
23  * Public License ("GPL") version 2 as distributed in the 'COPYING'
24  * file from the main directory of the linux kernel source.
25  *
26  * The provided data structures and external interfaces from this code
27  * are not restricted to be used by modules with a GPL compatible license.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
40  * DAMAGE.
41  *
42  * Send feedback to <socketcan-users@lists.berlios.de>
43  *
44  */
45
46 #include <linux/module.h>
47 #include <linux/version.h>
48 #include <linux/slab.h>
49 #include <linux/kmod.h>
50 #include <linux/init.h>
51 #include <linux/list.h>
52 #include <linux/spinlock.h>
53 #include <linux/rcupdate.h>
54 #include <linux/socket.h>
55 #include <linux/if_ether.h>
56 #include <linux/if_arp.h>
57 #include <linux/skbuff.h>
58 #include <linux/net.h>
59 #include <linux/netdevice.h>
60 #include <linux/can.h>
61 #include <linux/can/core.h>
62 #include <net/sock.h>
63 #include <asm/uaccess.h>
64
65 #include "af_can.h"
66
67 #include <linux/can/version.h> /* for RCSID. Removed by mkpatch script */
68 RCSID("$Id$");
69
70 #define IDENT "core"
71 static __initdata const char banner[] =
72         KERN_INFO "can: controller area network core # "
73         CAN_VERSION_STRING "\n";
74
75 MODULE_DESCRIPTION("Controller Area Network PF_CAN core");
76 MODULE_LICENSE("Dual BSD/GPL");
77 MODULE_AUTHOR("Urs Thuermann <urs.thuermann@volkswagen.de>, "
78               "Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
79
80 MODULE_ALIAS_NETPROTO(PF_CAN);
81
82 int stats_timer = 1; /* default: on */
83 module_param(stats_timer, int, S_IRUGO);
84 MODULE_PARM_DESC(stats_timer, "enable timer for statistics (default:on)");
85
86 #ifdef CONFIG_CAN_DEBUG_CORE
87 static int debug = 0;
88 module_param(debug, int, S_IRUGO);
89 MODULE_PARM_DESC(debug, "debug print mask: 1:debug, 2:frames, 4:skbs");
90 #endif
91
92 struct notifier {
93         struct list_head list;
94         struct net_device *dev;
95         void (*func)(unsigned long msg, void *data);
96         void *data;
97 };
98
99 static LIST_HEAD(notifier_list);
100 static DEFINE_RWLOCK(notifier_lock);
101
102 HLIST_HEAD(rx_dev_list);
103 static struct dev_rcv_lists rx_alldev_list;
104 static DEFINE_SPINLOCK(rcv_lists_lock);
105
106 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,20)
107 static struct kmem_cache *rcv_cache __read_mostly;
108 #else
109 static kmem_cache_t *rcv_cache;
110 #endif
111
112 /* table of registered CAN protocols */
113 static struct can_proto *proto_tab[CAN_NPROTO];
114
115 struct timer_list stattimer; /* timer for statistics update */
116 struct s_stats  stats;       /* packet statistics */
117 struct s_pstats pstats;      /* receive list statistics */
118
119 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,14)
120 static void *kzalloc(size_t size, unsigned int __nocast flags)
121 {
122         void *ret = kmalloc(size, flags);
123         if (ret)
124                 memset(ret, 0, size);
125         return ret;
126 }
127 #endif
128
129 /*
130  * af_can socket functions
131  */
132
133 static int can_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
134 {
135         struct sock *sk = sock->sk;
136
137         switch (cmd) {
138
139         case SIOCGSTAMP:
140                 return sock_get_timestamp(sk, (struct timeval __user *)arg);
141
142         default:
143 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
144                 return -ENOIOCTLCMD;
145 #else
146                 return dev_ioctl(cmd, (void __user *)arg);
147 #endif
148         }
149 }
150
151 static void can_sock_destruct(struct sock *sk)
152 {
153         DBG("called for sock %p\n", sk);
154
155         skb_queue_purge(&sk->sk_receive_queue);
156         if (sk->sk_protinfo)
157                 kfree(sk->sk_protinfo);
158 }
159
160 static int can_create(struct socket *sock, int protocol)
161 {
162         struct sock *sk;
163         struct can_proto *cp;
164         char module_name[sizeof("can-proto-000")];
165         int ret = 0;
166
167         DBG("socket %p, type %d, proto %d\n", sock, sock->type, protocol);
168
169         sock->state = SS_UNCONNECTED;
170
171         if (protocol < 0 || protocol >= CAN_NPROTO)
172                 return -EINVAL;
173
174         DBG("looking up proto %d in proto_tab[]\n", protocol);
175
176         /* try to load protocol module, when CONFIG_KMOD is defined */
177         if (!proto_tab[protocol]) {
178                 sprintf(module_name, "can-proto-%d", protocol);
179                 ret = request_module(module_name);
180
181                 /* In case of error we only print a message but don't
182                  * return the error code immediately.  Below we will
183                  * return -EPROTONOSUPPORT
184                  */
185                 if (ret == -ENOSYS)
186                         printk(KERN_INFO "can: request_module(%s) not"
187                                " implemented.\n", module_name);
188                 else if (ret)
189                         printk(KERN_ERR "can: request_module(%s) failed\n",
190                                module_name);
191         }
192
193         /* check for success and correct type */
194         cp = proto_tab[protocol];
195         if (!cp || cp->type != sock->type)
196                 return -EPROTONOSUPPORT;
197
198         if (cp->capability >= 0 && !capable(cp->capability))
199                 return -EPERM;
200
201         sock->ops = cp->ops;
202
203 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
204         sk = sk_alloc(PF_CAN, GFP_KERNEL, cp->prot, 1);
205         if (!sk)
206                 return -ENOMEM;
207 #else
208         sk = sk_alloc(PF_CAN, GFP_KERNEL, 1, 0);
209         if (!sk)
210                 return -ENOMEM;
211
212         if (cp->obj_size) {
213                 sk->sk_protinfo = kmalloc(cp->obj_size, GFP_KERNEL);
214                 if (!sk->sk_protinfo) {
215                         sk_free(sk);
216                         return -ENOMEM;
217                 }
218         }
219         sk_set_owner(sk, proto_tab[protocol]->owner);
220 #endif
221
222         sock_init_data(sock, sk);
223         sk->sk_destruct = can_sock_destruct;
224
225         DBG("created sock: %p\n", sk);
226
227 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
228         if (sk->sk_prot->init)
229                 ret = sk->sk_prot->init(sk);
230 #else
231         if (cp->init)
232                 ret = cp->init(sk);
233 #endif
234
235         if (ret) {
236                 /* release sk on errors */
237                 sock_orphan(sk);
238                 sock_put(sk);
239         }
240
241         return ret;
242 }
243
244 /*
245  * af_can tx path
246  */
247
248 /**
249  * can_send - transmit a CAN frame (optional with local loopback)
250  * @skb: pointer to socket buffer with CAN frame in data section
251  * @loop: loopback for listeners on local CAN sockets (recommended default!)
252  *
253  * Return:
254  *  0 on success
255  *  -ENETDOWN when the selected interface is down
256  *  -ENOBUFS on full driver queue (see net_xmit_errno())
257  */
258 int can_send(struct sk_buff *skb, int loop)
259 {
260         int err;
261
262         if (skb->dev->type != ARPHRD_CAN) {
263                 kfree_skb(skb);
264                 return -EPERM;
265         }
266
267         skb->protocol = htons(ETH_P_CAN);
268
269         if (loop) {
270                 /* local loopback of sent CAN frames (default) */
271
272                 /* indication for the CAN driver: do loopback */
273                 skb->pkt_type = PACKET_LOOPBACK;
274
275                 /*
276                  * The reference to the originating sock may be required
277                  * by the receiving socket to indicate (and ignore) his own
278                  * sent data. Example: can_raw sockopt CAN_RAW_RECV_OWN_MSGS
279                  * Therefore we have to ensure that skb->sk remains the
280                  * reference to the originating sock by restoring skb->sk
281                  * after each skb_clone() or skb_orphan() usage.
282                  * skb->sk is usually unused and unset in the rx path.
283                  */
284
285                 /* interface not capabable to do the loopback itself? */
286                 if (!(skb->dev->flags & IFF_LOOPBACK)) {
287                         struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
288
289                         /* perform the local loopback here */
290                         newskb->sk = skb->sk;
291                         newskb->ip_summed = CHECKSUM_UNNECESSARY;
292                         newskb->pkt_type = PACKET_BROADCAST;
293                         netif_rx(newskb);
294                 }
295         } else {
296                 /* indication for the CAN driver: no loopback required */
297                 skb->pkt_type = PACKET_HOST;
298         }
299
300         if (!(skb->dev->flags & IFF_UP))
301                 return -ENETDOWN;
302
303         /* send to netdevice */
304         err = dev_queue_xmit(skb);
305         if (err > 0)
306                 err = net_xmit_errno(err);
307
308         /* update statistics */
309         stats.tx_frames++;
310         stats.tx_frames_delta++;
311
312         return err;
313 }
314 EXPORT_SYMBOL(can_send);
315
316 /*
317  * af_can rx path
318  */
319
320 static struct dev_rcv_lists *find_dev_rcv_lists(struct net_device *dev)
321 {
322         struct dev_rcv_lists *d;
323         struct hlist_node *n;
324
325         /*
326          * find receive list for this device
327          *
328          * The hlist_for_each_entry*() macros curse through the list
329          * using the pointer variable n and set d to the containing
330          * struct in each list iteration.  Therefore, after list
331          * iteration, d is unmodified when the list is empty, and it
332          * points to last list element, when the list is non-empty
333          * but no match in the loop body is found.  I.e. d is *not*
334          * NULL when no match is found.  We can, however, use the
335          * cursor variable n to decide if a match was found.
336          */
337
338         hlist_for_each_entry(d, n, &rx_dev_list, list) {
339                 if (d->dev == dev)
340                         break;
341         }
342
343         return n ? d : NULL;
344 }
345
346 static struct hlist_head *find_rcv_list(canid_t *can_id, canid_t *mask,
347                                         struct dev_rcv_lists *d)
348 {
349         canid_t inv = *can_id & CAN_INV_FILTER; /* save flag before masking */
350
351         /* filter error frames */
352         if (*mask & CAN_ERR_FLAG) {
353                 /* clear CAN_ERR_FLAG in list entry */
354                 *mask &= CAN_ERR_MASK;
355                 return &d->rx[RX_ERR];
356         }
357
358         /* ensure valid values in can_mask */
359         if (*mask & CAN_EFF_FLAG)
360                 *mask &= (CAN_EFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG);
361         else
362                 *mask &= (CAN_SFF_MASK | CAN_RTR_FLAG);
363
364         /* reduce condition testing at receive time */
365         *can_id &= *mask;
366
367         /* inverse can_id/can_mask filter */
368         if (inv)
369                 return &d->rx[RX_INV];
370
371         /* mask == 0 => no condition testing at receive time */
372         if (!(*mask))
373                 return &d->rx[RX_ALL];
374
375         /* use extra filterset for the subscription of exactly *ONE* can_id */
376         if (*can_id & CAN_EFF_FLAG) {
377                 if (*mask == (CAN_EFF_MASK | CAN_EFF_FLAG)) {
378                         /* RFC: a use-case for hash-tables in the future? */
379                         return &d->rx[RX_EFF];
380                 }
381         } else {
382                 if (*mask == CAN_SFF_MASK)
383                         return &d->rx_sff[*can_id];
384         }
385
386         /* default: filter via can_id/can_mask */
387         return &d->rx[RX_FIL];
388 }
389
390 /**
391  * can_rx_register - subscribe CAN frames from a specific interface
392  * @ifindex: device index (zero => unsubcribe from 'all' CAN devices list)
393  * @can_id: CAN identifier (see description)
394  * @mask: CAN mask (see description)
395  * @func: callback function on filter match
396  * @data: returned parameter for callback function
397  * @ident: string for calling module indentification
398  *
399  * Description:
400  *  Invokes the callback function with the received sk_buff and the given
401  *  parameter 'data' on a matching receive filter. A filter matches, when
402  *
403  *          <received_can_id> & mask == can_id & mask
404  *
405  *  The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
406  *  filter for error frames (CAN_ERR_FLAG bit set in mask).
407  *
408  * Return:
409  *  0 on success
410  *  -ENOMEM on missing cache mem to create subscription entry
411  *  -ENODEV unknown device
412  */
413 int can_rx_register(int ifindex, canid_t can_id, canid_t mask,
414                     void (*func)(struct sk_buff *, void *), void *data,
415                     char *ident)
416 {
417         struct receiver *r;
418         struct hlist_head *rl;
419         struct dev_rcv_lists *d;
420         struct net_device *dev = NULL;
421         int ret = 0;
422
423         /* insert new receiver  (dev,canid,mask) -> (func,data) */
424
425         DBG("dev %p, id %03X, mask %03X, callback %p, data %p, ident %s\n",
426             dev, can_id, mask, func, data, ident);
427
428         r = kmem_cache_alloc(rcv_cache, GFP_KERNEL);
429         if (!r)
430                 return -ENOMEM;
431
432         spin_lock_bh(&rcv_lists_lock);
433
434         if (ifindex)
435                 dev = dev_get_by_index(ifindex);
436
437         d = find_dev_rcv_lists(dev);
438         if (d) {
439                 rl = find_rcv_list(&can_id, &mask, d);
440
441                 r->can_id  = can_id;
442                 r->mask    = mask;
443                 r->matches = 0;
444                 r->func    = func;
445                 r->data    = data;
446                 r->ident   = ident;
447
448                 hlist_add_head_rcu(&r->list, rl);
449                 d->entries++;
450
451                 pstats.rcv_entries++;
452                 if (pstats.rcv_entries_max < pstats.rcv_entries)
453                         pstats.rcv_entries_max = pstats.rcv_entries;
454         } else {
455                 DBG("receive list not found for dev %s, id %03X, mask %03X\n",
456                     DNAME(dev), can_id, mask);
457                 kmem_cache_free(rcv_cache, r);
458                 ret = -ENODEV;
459         }
460
461         if (dev)
462                 dev_put(dev);
463
464         spin_unlock_bh(&rcv_lists_lock);
465
466         return ret;
467 }
468 EXPORT_SYMBOL(can_rx_register);
469
470 static void can_rx_delete_list(struct hlist_head *rl)
471 {
472         struct receiver *r;
473         struct hlist_node *n;
474
475         hlist_for_each_entry_rcu(r, n, rl, list) {
476                 hlist_del_rcu(&r->list);
477                 kmem_cache_free(rcv_cache, r);
478         }
479 }
480
481 /*
482  * can_rx_delete_device - rcu callback for dev_rcv_lists structure removal
483  */
484 static void can_rx_delete_device(struct rcu_head *rp)
485 {
486         struct dev_rcv_lists *d = container_of(rp, struct dev_rcv_lists, rcu);
487         int i;
488
489         /* remove all receivers hooked at this netdevice */
490         can_rx_delete_list(&d->rx[RX_ERR]);
491         can_rx_delete_list(&d->rx[RX_ALL]);
492         can_rx_delete_list(&d->rx[RX_FIL]);
493         can_rx_delete_list(&d->rx[RX_INV]);
494         can_rx_delete_list(&d->rx[RX_EFF]);
495
496         for (i = 0; i < 2048; i++)
497                 can_rx_delete_list(&d->rx_sff[i]);
498
499         kfree(d);
500 }
501
502 /*
503  * can_rx_delete_receiver - rcu callback for single receiver entry removal
504  */
505 static void can_rx_delete_receiver(struct rcu_head *rp)
506 {
507         struct receiver *r = container_of(rp, struct receiver, rcu);
508
509         kmem_cache_free(rcv_cache, r);
510 }
511
512 /**
513  * can_rx_unregister - unsubscribe CAN frames from a specific interface
514  * @ifindex: device index (zero => unsubcribe from 'all' CAN devices list)
515  * @can_id: CAN identifier
516  * @mask: CAN mask
517  * @func: callback function on filter match
518  * @data: returned parameter for callback function
519  *
520  * Description:
521  *  Removes subscription entry depending on given (subscription) values.
522  *
523  * Return:
524  *  0 on success
525  *  -EINVAL on missing subscription entry
526  *  -ENODEV unknown device
527  */
528 int can_rx_unregister(int ifindex, canid_t can_id, canid_t mask,
529                       void (*func)(struct sk_buff *, void *), void *data)
530 {
531         struct receiver *r = NULL;
532         struct hlist_head *rl;
533         struct hlist_node *next;
534         struct dev_rcv_lists *d;
535         struct net_device *dev = NULL;
536         int ret = 0;
537
538         DBG("dev %p, id %03X, mask %03X, callback %p, data %p\n",
539             dev, can_id, mask, func, data);
540
541         spin_lock_bh(&rcv_lists_lock);
542
543         if (ifindex)
544                 dev = dev_get_by_index(ifindex);
545
546         d = find_dev_rcv_lists(dev);
547         if (!d) {
548                 DBG("receive list not found for dev %s, id %03X, mask %03X\n",
549                     DNAME(dev), can_id, mask);
550                 ret = -ENODEV;
551                 goto out;
552         }
553
554         rl = find_rcv_list(&can_id, &mask, d);
555
556         /*
557          * Search the receiver list for the item to delete.  This should
558          * exist, since no receiver may be unregistered that hasn't
559          * been registered before.
560          */
561
562         hlist_for_each_entry(r, next, rl, list) {
563                 if (r->can_id == can_id && r->mask == mask
564                     && r->func == func && r->data == data)
565                         break;
566         }
567
568         /*
569          * Check for bug in CAN protocol implementations:
570          * If no matching list item was found, the list cursor variable next
571          * will be NULL, while r will point to the last item of the list.
572          */
573
574         if (!next) {
575                 DBG("receive list entry not found for "
576                     "dev %s, id %03X, mask %03X\n", DNAME(dev), can_id, mask);
577                 ret = -EINVAL;
578                 r = NULL;
579                 goto out;
580         }
581
582         hlist_del_rcu(&r->list);
583         d->entries--;
584
585         if (pstats.rcv_entries > 0)
586                 pstats.rcv_entries--;
587
588  out:
589         if (dev)
590                 dev_put(dev);
591
592         spin_unlock_bh(&rcv_lists_lock);
593
594         /* schedule the receiver item for deletion */
595         if (r)
596                 call_rcu(&r->rcu, can_rx_delete_receiver);
597
598         return ret;
599 }
600 EXPORT_SYMBOL(can_rx_unregister);
601
602 static inline void deliver(struct sk_buff *skb, struct receiver *r)
603 {
604         struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
605
606         DBG("skbuff %p cloned to %p\n", skb, clone);
607         if (clone) {
608                 clone->sk = skb->sk;
609                 r->func(clone, r->data);
610                 r->matches++;
611         }
612 }
613
614 static int can_rcv_filter(struct dev_rcv_lists *d, struct sk_buff *skb)
615 {
616         struct receiver *r;
617         struct hlist_node *n;
618         int matches = 0;
619         struct can_frame *cf = (struct can_frame*)skb->data;
620         canid_t can_id = cf->can_id;
621
622         if (d->entries == 0)
623                 return 0;
624
625         if (can_id & CAN_ERR_FLAG) {
626                 /* check for error frame entries only */
627                 hlist_for_each_entry_rcu(r, n, &d->rx[RX_ERR], list) {
628                         if (can_id & r->mask) {
629                                 DBG("match on rx_err skbuff %p\n", skb);
630                                 deliver(skb, r);
631                                 matches++;
632                         }
633                 }
634                 return matches;
635         }
636
637         /* check for unfiltered entries */
638         hlist_for_each_entry_rcu(r, n, &d->rx[RX_ALL], list) {
639                 DBG("match on rx_all skbuff %p\n", skb);
640                 deliver(skb, r);
641                 matches++;
642         }
643
644         /* check for can_id/mask entries */
645         hlist_for_each_entry_rcu(r, n, &d->rx[RX_FIL], list) {
646                 if ((can_id & r->mask) == r->can_id) {
647                         DBG("match on rx_fil skbuff %p\n", skb);
648                         deliver(skb, r);
649                         matches++;
650                 }
651         }
652
653         /* check for inverted can_id/mask entries */
654         hlist_for_each_entry_rcu(r, n, &d->rx[RX_INV], list) {
655                 if ((can_id & r->mask) != r->can_id) {
656                         DBG("match on rx_inv skbuff %p\n", skb);
657                         deliver(skb, r);
658                         matches++;
659                 }
660         }
661
662         /* check CAN_ID specific entries */
663         if (can_id & CAN_EFF_FLAG) {
664                 hlist_for_each_entry_rcu(r, n, &d->rx[RX_EFF], list) {
665                         if (r->can_id == can_id) {
666                                 DBG("match on rx_eff skbuff %p\n", skb);
667                                 deliver(skb, r);
668                                 matches++;
669                         }
670                 }
671         } else {
672                 can_id &= CAN_SFF_MASK;
673                 hlist_for_each_entry_rcu(r, n, &d->rx_sff[can_id], list) {
674                         DBG("match on rx_sff skbuff %p\n", skb);
675                         deliver(skb, r);
676                         matches++;
677                 }
678         }
679
680         return matches;
681 }
682
683 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
684 static int can_rcv(struct sk_buff *skb, struct net_device *dev,
685                    struct packet_type *pt, struct net_device *orig_dev)
686 #else
687 static int can_rcv(struct sk_buff *skb, struct net_device *dev,
688                    struct packet_type *pt)
689 #endif
690 {
691         struct dev_rcv_lists *d;
692         int matches;
693
694         DBG("received skbuff on device %s, ptype %04x\n",
695             dev->name, ntohs(pt->type));
696         DBG_SKB(skb);
697         DBG_FRAME("af_can: can_rcv: received CAN frame",
698                   (struct can_frame *)skb->data);
699
700         if (dev->type != ARPHRD_CAN) {
701                 kfree_skb(skb);
702                 return 0;
703         }
704
705         /* update statistics */
706         stats.rx_frames++;
707         stats.rx_frames_delta++;
708
709         rcu_read_lock();
710
711         /* deliver the packet to sockets listening on all devices */
712         matches = can_rcv_filter(&rx_alldev_list, skb);
713
714         /* find receive list for this device */
715         d = find_dev_rcv_lists(dev);
716         if (d)
717                 matches += can_rcv_filter(d, skb);
718
719         rcu_read_unlock();
720
721         /* free the skbuff allocated by the netdevice driver */
722         DBG("freeing skbuff %p\n", skb);
723         kfree_skb(skb);
724
725         if (matches > 0) {
726                 stats.matches++;
727                 stats.matches_delta++;
728         }
729
730         return 0;
731 }
732
733 /*
734  * af_can debugging stuff
735  */
736
737 #ifdef CONFIG_CAN_DEBUG_CORE
738
739 #define DBG_BSIZE 1024
740
741 /**
742  * can_debug_cframe - print CAN frame
743  * @msg: pointer to message printed before the given CAN frame
744  * @cf: pointer to CAN frame
745  */
746 void can_debug_cframe(const char *msg, struct can_frame *cf, ...)
747 {
748         va_list ap;
749         int len;
750         int dlc, i;
751         char *buf;
752
753         buf = kmalloc(DBG_BSIZE, GFP_ATOMIC);
754         if (!buf)
755                 return;
756
757         len = sprintf(buf, KERN_DEBUG);
758         va_start(ap, cf);
759         len += snprintf(buf + len, DBG_BSIZE - 64, msg, ap);
760         buf[len++] = ':';
761         buf[len++] = ' ';
762         va_end(ap);
763
764         dlc = cf->can_dlc;
765         if (dlc > 8)
766                 dlc = 8;
767
768         if (cf->can_id & CAN_EFF_FLAG)
769                 len += sprintf(buf + len, "<%08X> [%X] ",
770                                cf->can_id & CAN_EFF_MASK, dlc);
771         else
772                 len += sprintf(buf + len, "<%03X> [%X] ",
773                                cf->can_id & CAN_SFF_MASK, dlc);
774
775         for (i = 0; i < dlc; i++)
776                 len += sprintf(buf + len, "%02X ", cf->data[i]);
777
778         if (cf->can_id & CAN_RTR_FLAG)
779                 len += sprintf(buf + len, "(RTR)");
780
781         buf[len++] = '\n';
782         buf[len]   = '\0';
783         printk(buf);
784         kfree(buf);
785 }
786 EXPORT_SYMBOL(can_debug_cframe);
787
788 /**
789  * can_debug_skb - print socket buffer content to kernel log
790  * @skb: pointer to socket buffer
791  */
792 void can_debug_skb(struct sk_buff *skb)
793 {
794         int len, nbytes, i;
795         char *buf;
796
797         buf = kmalloc(DBG_BSIZE, GFP_ATOMIC);
798         if (!buf)
799                 return;
800
801         len = sprintf(buf,
802                       KERN_DEBUG "  skbuff at %p, dev: %d, proto: %04x\n"
803                       KERN_DEBUG "  users: %d, dataref: %d, nr_frags: %d, "
804                       "h,d,t,e,l: %p %+d %+d %+d, %d",
805                       skb, skb->dev ? skb->dev->ifindex : -1,
806                       ntohs(skb->protocol),
807                       atomic_read(&skb->users),
808                       atomic_read(&(skb_shinfo(skb)->dataref)),
809                       skb_shinfo(skb)->nr_frags,
810                       skb->head, skb->data - skb->head,
811                       skb->tail - skb->head, skb->end - skb->head, skb->len);
812         nbytes = skb->end - skb->head;
813         for (i = 0; i < nbytes; i++) {
814                 if (i % 16 == 0)
815                         len += sprintf(buf + len, "\n" KERN_DEBUG "  ");
816                 if (len < DBG_BSIZE - 16) {
817                         len += sprintf(buf + len, " %02x", skb->head[i]);
818                 } else {
819                         len += sprintf(buf + len, "...");
820                         break;
821                 }
822         }
823         buf[len++] = '\n';
824         buf[len]   = '\0';
825         printk(buf);
826         kfree(buf);
827 }
828 EXPORT_SYMBOL(can_debug_skb);
829
830 #endif
831
832 /*
833  * af_can protocol functions
834  */
835
836 /**
837  * can_proto_register - register CAN transport protocol
838  * @cp: pointer to CAN protocol structure
839  *
840  * Return:
841  *  0 on success
842  *  -EINVAL invalid (out of range) protocol number
843  *  -EBUSY  protocol already in use
844  *  -ENOBUF if proto_register() fails
845  */
846 int can_proto_register(struct can_proto *cp)
847 {
848         int proto = cp->protocol;
849         int err = 0;
850
851         if (proto < 0 || proto >= CAN_NPROTO) {
852                 printk(KERN_ERR "can: protocol number %d out "
853                        "of range\n", proto);
854                 return -EINVAL;
855         }
856         if (proto_tab[proto]) {
857                 printk(KERN_ERR "can: protocol %d already "
858                        "registered\n", proto);
859                 return -EBUSY;
860         }
861
862 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
863         err = proto_register(cp->prot, 0);
864         if (err < 0)
865                 return err;
866 #endif
867
868         proto_tab[proto] = cp;
869
870         /* use generic ioctl function if the module doesn't bring its own */
871         if (!cp->ops->ioctl)
872                 cp->ops->ioctl = can_ioctl;
873
874         return err;
875 }
876 EXPORT_SYMBOL(can_proto_register);
877
878 /**
879  * can_proto_unregister - unregister CAN transport protocol
880  * @cp: pointer to CAN protocol structure
881  *
882  * Return:
883  *  0 on success
884  *  -ESRCH protocol number was not registered
885  */
886 int can_proto_unregister(struct can_proto *cp)
887 {
888         int proto = cp->protocol;
889
890         if (!proto_tab[proto]) {
891                 printk(KERN_ERR "can: protocol %d is not registered\n", proto);
892                 return -ESRCH;
893         }
894 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
895         proto_unregister(cp->prot);
896 #endif
897         proto_tab[proto] = NULL;
898
899         return 0;
900 }
901 EXPORT_SYMBOL(can_proto_unregister);
902
903 /**
904  * can_dev_register - subscribe notifier for CAN device status changes
905  * @ifindex: device index
906  * @func: callback function on status change
907  * @data: returned parameter for callback function
908  *
909  * Description:
910  *  Invokes the callback function with the status 'msg' and the given
911  *  parameter 'data' on a status change of the given CAN network device.
912  *
913  * Return:
914  *  0 on success
915  *  -ENOMEM on missing mem to create subscription entry
916  *  -ENODEV unknown (CAN) device
917  *  -ENETDOWN given CAN interface is down
918  */
919 int can_dev_register(int ifindex, void (*func)(unsigned long msg, void *),
920                      void *data)
921 {
922         struct notifier *n;
923         struct net_device *dev = NULL;
924         int ret = 0;
925
926         DBG("called for %s\n", dev->name);
927
928         if (!ifindex)
929                 return -ENODEV;
930
931         dev = dev_get_by_index(ifindex);
932
933         /*
934          * TODO:
935          * put notifier list 'device dependend' into dev_rcv_lists
936          * Therefore this code should look more like the code in
937          * can_rx_register()
938          */
939
940         if (!dev || dev->type != ARPHRD_CAN) {
941                 ret = -ENODEV;
942                 goto out;
943         }
944
945         if (!(dev->flags & IFF_UP)) {
946                 ret = -ENETDOWN;
947                 goto out;
948         }
949
950         n = kmalloc(sizeof(*n), GFP_KERNEL);
951         if (!n) {
952                 ret = -ENOMEM;
953                 goto out;
954         }
955
956         n->dev  = dev;
957         n->func = func;
958         n->data = data;
959
960         write_lock(&notifier_lock);
961         list_add(&n->list, &notifier_list);
962         write_unlock(&notifier_lock);
963
964 out:
965         if (dev)
966                 dev_put(dev);
967
968         return ret;
969 }
970 EXPORT_SYMBOL(can_dev_register);
971
972 /**
973  * can_dev_unregister - unsubscribe notifier for CAN device status changes
974  * @ifindex: device index
975  * @func: callback function on filter match
976  * @data: returned parameter for callback function
977  *
978  * Description:
979  *  Removes subscription entry depending on given (subscription) values.
980  *
981  * Return:
982  *  0 on success
983  *  -EINVAL on missing subscription entry
984  *  -ENODEV unknown device
985  */
986 int can_dev_unregister(int ifindex, void (*func)(unsigned long msg, void *),
987                        void *data)
988 {
989         struct notifier *n, *next;
990         struct net_device *dev;
991         int ret = -EINVAL;
992
993         DBG("called for %s\n", dev->name);
994
995         if (!ifindex)
996                 return -ENODEV;
997
998         write_lock(&notifier_lock);
999         dev = dev_get_by_index(ifindex);
1000
1001         list_for_each_entry_safe(n, next, &notifier_list, list) {
1002                 if (n->dev == dev && n->func == func && n->data == data) {
1003                         list_del(&n->list);
1004                         kfree(n);
1005                         ret = 0;
1006                         break;
1007                 }
1008         }
1009
1010         if (dev)
1011                 dev_put(dev);
1012
1013         write_unlock(&notifier_lock);
1014
1015         return ret;
1016 }
1017 EXPORT_SYMBOL(can_dev_unregister);
1018
1019 static int can_notifier(struct notifier_block *nb,
1020                         unsigned long msg, void *data)
1021 {
1022         struct net_device *dev = (struct net_device *)data;
1023         struct notifier *n;
1024         struct dev_rcv_lists *d;
1025
1026         DBG("called for %s, msg = %lu\n", dev->name, msg);
1027
1028         if (dev->type != ARPHRD_CAN)
1029                 return NOTIFY_DONE;
1030
1031         switch (msg) {
1032
1033         case NETDEV_REGISTER:
1034
1035                 /*
1036                  * create new dev_rcv_lists for this device
1037                  *
1038                  * N.B. zeroing the struct is the correct initialization
1039                  * for the embedded hlist_head structs.
1040                  * Another list type, e.g. list_head, would require
1041                  * explicit initialization.
1042                  */
1043
1044                 DBG("creating new dev_rcv_lists for %s\n", dev->name);
1045
1046                 d = kzalloc(sizeof(*d),
1047                             in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
1048                 if (!d) {
1049                         printk(KERN_ERR "can: allocation of receive "
1050                                "list failed\n");
1051                         return NOTIFY_DONE;
1052                 }
1053                 d->dev = dev;
1054
1055                 spin_lock_bh(&rcv_lists_lock);
1056                 hlist_add_head_rcu(&d->list, &rx_dev_list);
1057                 spin_unlock_bh(&rcv_lists_lock);
1058
1059                 break;
1060
1061         case NETDEV_UNREGISTER:
1062                 spin_lock_bh(&rcv_lists_lock);
1063
1064                 d = find_dev_rcv_lists(dev);
1065                 if (d)
1066                         hlist_del_rcu(&d->list);
1067                 else
1068                         printk(KERN_ERR "can: notifier: receive list not "
1069                                "found for dev %s\n", dev->name);
1070
1071                 spin_unlock_bh(&rcv_lists_lock);
1072
1073                 if (d)
1074                         call_rcu(&d->rcu, can_rx_delete_device);
1075
1076                 break;
1077         }
1078
1079         read_lock(&notifier_lock);
1080         list_for_each_entry(n, &notifier_list, list) {
1081                 if (n->dev == dev)
1082                         n->func(msg, n->data);
1083         }
1084         read_unlock(&notifier_lock);
1085
1086         return NOTIFY_DONE;
1087 }
1088
1089 /*
1090  * af_can module init/exit functions
1091  */
1092
1093 static struct packet_type can_packet = {
1094         .type = __constant_htons(ETH_P_CAN),
1095         .dev  = NULL,
1096         .func = can_rcv,
1097 };
1098
1099 static struct net_proto_family can_family_ops = {
1100         .family = PF_CAN,
1101         .create = can_create,
1102         .owner  = THIS_MODULE,
1103 };
1104
1105 /* notifier block for netdevice event */
1106 static struct notifier_block can_netdev_notifier = {
1107         .notifier_call = can_notifier,
1108 };
1109
1110 static __init int can_init(void)
1111 {
1112         printk(banner);
1113
1114         rcv_cache = kmem_cache_create("can_receiver", sizeof(struct receiver),
1115                                       0, 0, NULL, NULL);
1116         if (!rcv_cache)
1117                 return -ENOMEM;
1118
1119         /*
1120          * Insert struct dev_rcv_lists for reception on all devices.
1121          * This struct is zero initialized which is correct for the
1122          * embedded hlist heads, the dev pointer, and the entries counter.
1123          */
1124
1125         spin_lock_bh(&rcv_lists_lock);
1126         hlist_add_head_rcu(&rx_alldev_list.list, &rx_dev_list);
1127         spin_unlock_bh(&rcv_lists_lock);
1128
1129         if (stats_timer) {
1130                 /* the statistics are updated every second (timer triggered) */
1131                 init_timer(&stattimer);
1132                 stattimer.function = can_stat_update;
1133                 stattimer.data = 0;
1134                 /* update every second */
1135                 stattimer.expires = jiffies + HZ;
1136                 /* start statistics timer */
1137                 add_timer(&stattimer);
1138         } else
1139                 stattimer.function = NULL;
1140
1141         /* procfs init */
1142         can_init_proc();
1143
1144         /* protocol register */
1145         sock_register(&can_family_ops);
1146         register_netdevice_notifier(&can_netdev_notifier);
1147         dev_add_pack(&can_packet);
1148
1149         return 0;
1150 }
1151
1152 static __exit void can_exit(void)
1153 {
1154         struct dev_rcv_lists *d;
1155         struct hlist_node *n, *next;
1156
1157         if (stats_timer)
1158                 del_timer(&stattimer);
1159
1160         /* procfs remove */
1161         can_remove_proc();
1162
1163         /* protocol unregister */
1164         dev_remove_pack(&can_packet);
1165         unregister_netdevice_notifier(&can_netdev_notifier);
1166         sock_unregister(PF_CAN);
1167
1168         /* remove rx_dev_list */
1169         spin_lock_bh(&rcv_lists_lock);
1170         hlist_del(&rx_alldev_list.list);
1171         hlist_for_each_entry_safe(d, n, next, &rx_dev_list, list) {
1172                 hlist_del(&d->list);
1173                 kfree(d);
1174         }
1175         spin_unlock_bh(&rcv_lists_lock);
1176
1177         kmem_cache_destroy(rcv_cache);
1178 }
1179
1180 module_init(can_init);
1181 module_exit(can_exit);