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