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