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