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