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