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