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