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