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