]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/net/can/bcm.c
Updated to version 20070619.
[socketcan-devel.git] / kernel / 2.6 / net / can / bcm.c
1 /*
2  * bcm.c - Broadcast Manager to filter/send (cyclic) CAN content
3  *
4  * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions, the following disclaimer and
12  *    the referenced file 'COPYING'.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of Volkswagen nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * Alternatively, provided that this notice is retained in full, this
21  * software may be distributed under the terms of the GNU General
22  * Public License ("GPL") version 2 as distributed in the 'COPYING'
23  * file from the main directory of the linux kernel source.
24  *
25  * The provided data structures and external interfaces from this code
26  * are not restricted to be used by modules with a GPL compatible license.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
39  * DAMAGE.
40  *
41  * Send feedback to <socketcan-users@lists.berlios.de>
42  *
43  */
44
45 #include <linux/module.h>
46 #include <linux/init.h>
47 #include <linux/version.h>
48 #include <linux/net.h>
49 #include <linux/netdevice.h>
50 #include <linux/proc_fs.h>
51 #include <linux/poll.h>
52 #include <linux/can.h>
53 #include <linux/can/core.h>
54 #include <linux/can/bcm.h>
55 #include <net/sock.h>
56
57 #include <linux/can/version.h> /* for RCSID. Removed by mkpatch script */
58 RCSID("$Id$");
59
60 /* use of last_frames[index].can_dlc */
61 #define RX_RECV    0x40 /* received data for this element */
62 #define RX_THR     0x80 /* element not been sent due to throttle feature */
63 #define BCM_CAN_DLC_MASK 0x0F /* clean private flags in can_dlc by masking */
64
65 /* get best masking value for can_rx_register() for a given single can_id */
66 #define REGMASK(id) ((id & CAN_RTR_FLAG) | ((id & CAN_EFF_FLAG) ? \
67                         (CAN_EFF_MASK | CAN_EFF_FLAG) : CAN_SFF_MASK))
68
69 #define IDENT "bcm"
70 #define CAN_BCM_VERSION CAN_VERSION
71 static __initdata const char banner[] = KERN_INFO
72         "can: broadcast manager protocol (rev " CAN_BCM_VERSION ")\n";
73
74 MODULE_DESCRIPTION("PF_CAN broadcast manager protocol");
75 MODULE_LICENSE("Dual BSD/GPL");
76 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
77
78 #ifdef CONFIG_CAN_DEBUG_CORE
79 static int debug = 0;
80 module_param(debug, int, S_IRUGO);
81 MODULE_PARM_DESC(debug, "debug print mask: 1:debug, 2:frames, 4:skbs");
82 #endif
83
84 /* easy access to can_frame payload */
85 static inline u64 GET_U64(const struct can_frame *cp)
86 {
87         return *(u64*)cp->data;
88 }
89
90 struct bcm_op {
91         struct list_head list;
92         int ifindex;
93         canid_t can_id;
94         int flags;
95         unsigned long j_ival1, j_ival2, j_lastmsg;
96         unsigned long frames_abs, frames_filtered;
97         struct timer_list timer, thrtimer;
98         struct timeval ival1, ival2;
99 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
100         ktime_t rx_stamp;
101 #else
102         struct timeval rx_stamp;
103 #endif
104         int rx_ifindex;
105         int count;
106         int nframes;
107         int currframe;
108         struct can_frame *frames;
109         struct can_frame *last_frames;
110         struct can_frame sframe;
111         struct can_frame last_sframe;
112         struct sock *sk;
113         struct net_device *rx_reg_dev;
114 };
115
116 struct bcm_opt {
117         int bound;
118         int ifindex;
119         struct notifier_block notifier;
120         struct list_head rx_ops;
121         struct list_head tx_ops;
122         unsigned long dropped_usr_msgs;
123         struct proc_dir_entry *bcm_proc_read;
124         char procname [9]; /* pointer printed in ASCII with \0 */
125 };
126
127 static struct proc_dir_entry *proc_dir = NULL;
128
129 #ifdef CONFIG_CAN_BCM_USER
130 #define BCM_CAP (-1)
131 #else
132 #define BCM_CAP CAP_NET_RAW
133 #endif
134
135 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
136 struct bcm_sock {
137         struct sock    sk;
138         struct bcm_opt opt;
139 };
140
141 static inline struct bcm_opt *bcm_sk(const struct sock *sk)
142 {
143         return &((struct bcm_sock *)sk)->opt;
144 }
145 #else
146 static inline struct bcm_opt *bcm_sk(const struct sock *sk)
147 {
148         return (struct bcm_opt *)sk->sk_protinfo;
149 }
150 #endif
151
152 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,14)
153 static void *kzalloc(size_t size, unsigned int __nocast flags)
154 {
155         void *ret = kmalloc(size, flags);
156
157         if (ret)
158                 memset(ret, 0, size);
159
160         return ret;
161 }
162
163 static inline void skb_get_timestamp(const struct sk_buff *skb,
164                                      struct timeval *stamp)
165 {
166         stamp->tv_sec  = skb->stamp.tv_sec;
167         stamp->tv_usec = skb->stamp.tv_usec;
168 }
169
170 static inline void skb_set_timestamp(struct sk_buff *skb,
171                                      const struct timeval *stamp)
172 {
173         skb->stamp.tv_sec  = stamp->tv_sec;
174         skb->stamp.tv_usec = stamp->tv_usec;
175 }
176 #endif
177
178 #define CFSIZ sizeof(struct can_frame)
179 #define OPSIZ sizeof(struct bcm_op)
180 #define MHSIZ sizeof(struct bcm_msg_head)
181
182 /*
183  * rounded_tv2jif - calculate jiffies from timeval including optional up
184  * @tv: pointer to timeval
185  *
186  * Description:
187  * In opposite to timeval_to_jiffies() provided in include/linux/jiffies.h this
188  * function is intentionally more relaxed on precise timer ticks to get exact
189  * one jiffy for requested 1000us on a 1000HZ machine.
190  * This code is to be removed when upgrading to kernel hrtimer.
191  *
192  * Return:
193  *  calculated jiffies (max: ULONG_MAX)
194  */
195 static unsigned long rounded_tv2jif(const struct timeval *tv)
196 {
197         unsigned long sec  = tv->tv_sec;
198         unsigned long usec = tv->tv_usec;
199         unsigned long jif;
200
201         if (sec > ULONG_MAX / HZ)
202                 return ULONG_MAX;
203
204         /* round up to get at least the requested time */
205         usec += 1000000 / HZ - 1;
206
207         jif  = usec / (1000000 / HZ);
208
209         if (sec * HZ > ULONG_MAX - jif)
210                 return ULONG_MAX;
211
212         return jif + sec * HZ;
213 }
214
215 /*
216  * procfs functions
217  */
218 static char *bcm_proc_getifname(int ifindex)
219 {
220         struct net_device *dev;
221
222         if (!ifindex)
223                 return "any";
224
225         dev = __dev_get_by_index(ifindex); /* no usage counting */
226         if (dev)
227                 return dev->name;
228
229         return "???";
230 }
231
232 static int bcm_read_proc(char *page, char **start, off_t off,
233                          int count, int *eof, void *data)
234 {
235         int len = 0;
236         struct sock *sk = (struct sock *)data;
237         struct bcm_opt *bo = bcm_sk(sk);
238         struct bcm_op *op;
239
240         len += snprintf(page + len, PAGE_SIZE - len, ">>> socket %p",
241                         sk->sk_socket);
242         len += snprintf(page + len, PAGE_SIZE - len, " / sk %p", sk);
243         len += snprintf(page + len, PAGE_SIZE - len, " / bo %p", bo);
244         len += snprintf(page + len, PAGE_SIZE - len, " / dropped %lu",
245                         bo->dropped_usr_msgs);
246         len += snprintf(page + len, PAGE_SIZE - len, " / bound %s",
247                         bcm_proc_getifname(bo->ifindex));
248         len += snprintf(page + len, PAGE_SIZE - len, " <<<\n");
249
250         list_for_each_entry(op, &bo->rx_ops, list) {
251
252                 unsigned long reduction;
253
254                 /* print only active entries & prevent division by zero */
255                 if (!op->frames_abs)
256                         continue;
257
258                 len += snprintf(page + len, PAGE_SIZE - len,
259                                 "rx_op: %03X %-5s ",
260                                 op->can_id, bcm_proc_getifname(op->ifindex));
261                 len += snprintf(page + len, PAGE_SIZE - len, "[%d]%c ",
262                                 op->nframes,
263                                 (op->flags & RX_CHECK_DLC)?'d':' ');
264                 if (op->j_ival1)
265                         len += snprintf(page + len, PAGE_SIZE - len,
266                                         "timeo=%ld ", op->j_ival1);
267
268                 if (op->j_ival2)
269                         len += snprintf(page + len, PAGE_SIZE - len,
270                                         "thr=%ld ", op->j_ival2);
271
272                 len += snprintf(page + len, PAGE_SIZE - len,
273                                 "# recv %ld (%ld) => reduction: ",
274                                 op->frames_filtered, op->frames_abs);
275
276                 reduction = 100 - (op->frames_filtered * 100) / op->frames_abs;
277
278                 len += snprintf(page + len, PAGE_SIZE - len, "%s%ld%%\n",
279                                 (reduction == 100)?"near ":"", reduction);
280
281                 if (len > PAGE_SIZE - 200) {
282                         /* mark output cut off */
283                         len += snprintf(page + len, PAGE_SIZE - len, "(..)\n");
284                         break;
285                 }
286         }
287
288         list_for_each_entry(op, &bo->tx_ops, list) {
289
290                 len += snprintf(page + len, PAGE_SIZE - len,
291                                 "tx_op: %03X %s [%d] ",
292                                 op->can_id, bcm_proc_getifname(op->ifindex),
293                                 op->nframes);
294                 if (op->j_ival1)
295                         len += snprintf(page + len, PAGE_SIZE - len, "t1=%ld ",
296                                         op->j_ival1);
297
298                 if (op->j_ival2)
299                         len += snprintf(page + len, PAGE_SIZE - len, "t2=%ld ",
300                                         op->j_ival2);
301
302                 len += snprintf(page + len, PAGE_SIZE - len, "# sent %ld\n",
303                                 op->frames_abs);
304
305                 if (len > PAGE_SIZE - 100) {
306                         /* mark output cut off */
307                         len += snprintf(page + len, PAGE_SIZE - len, "(..)\n");
308                         break;
309                 }
310         }
311
312         len += snprintf(page + len, PAGE_SIZE - len, "\n");
313
314         *eof = 1;
315         return len;
316 }
317
318 /*
319  * bcm_can_tx - send the (next) CAN frame to the appropriate CAN interface
320  *              of the given bcm tx op
321  */
322 static void bcm_can_tx(struct bcm_op *op)
323 {
324         struct sk_buff *skb;
325         struct net_device *dev;
326         struct can_frame *cf = &op->frames[op->currframe];
327
328         DBG_FRAME("BCM: bcm_can_tx: sending frame", cf);
329
330         /* no target device? => exit */
331         if (!op->ifindex)
332                 return;
333
334         dev = dev_get_by_index(op->ifindex);
335
336         if (!dev) {
337                 /* RFC: should this bcm_op remove itself here? */
338                 return;
339         }
340
341         skb = alloc_skb(CFSIZ,
342                         in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
343
344         if (!skb)
345                 goto out;
346
347         memcpy(skb_put(skb, CFSIZ), cf, CFSIZ);
348
349         /* send with loopback */
350         skb->dev = dev;
351         skb->sk = op->sk;
352         can_send(skb, 1);
353
354         /* update statistics */
355         op->currframe++;
356         op->frames_abs++;
357
358         /* reached last frame? */
359         if (op->currframe >= op->nframes)
360                 op->currframe = 0;
361  out:
362         dev_put(dev);
363 }
364
365 /*
366  * bcm_send_to_user - send a BCM message to the userspace
367  *                    (consisting of bcm_msg_head + x CAN frames)
368  */
369 static void bcm_send_to_user(struct bcm_op *op, struct bcm_msg_head *head,
370                              struct can_frame *frames, int has_timestamp)
371 {
372         struct sk_buff *skb;
373         struct can_frame *firstframe;
374         struct sock *sk = op->sk;
375         int datalen = head->nframes * CFSIZ;
376         struct sockaddr_can *addr;
377         int err;
378
379         skb = alloc_skb(sizeof(*head) + datalen,
380                         in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
381         if (!skb)
382                 return;
383
384         memcpy(skb_put(skb, sizeof(*head)), head, sizeof(*head));
385
386         /* can_frames starting here */
387         firstframe = (struct can_frame *) skb->tail;
388
389
390         if (has_timestamp) {
391                 /* restore rx timestamp */
392 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
393                 skb->tstamp = op->rx_stamp;
394 #else
395                 skb_set_timestamp(skb, &op->rx_stamp);
396 #endif
397         }
398
399         addr = (struct sockaddr_can *)skb->cb;
400         memset(addr, 0, sizeof(*addr));
401         addr->can_family  = AF_CAN;
402         /* restore originator for recvfrom() */
403         addr->can_ifindex = op->rx_ifindex;
404
405         if (head->nframes) {
406                 memcpy(skb_put(skb, datalen), frames, datalen);
407
408                 /*
409                  * the BCM uses the can_dlc-element of the can_frame
410                  * structure for internal purposes. This is only
411                  * relevant for updates that are generated by the
412                  * BCM, where nframes is 1
413                  */
414                 if (head->nframes == 1)
415                         firstframe->can_dlc &= BCM_CAN_DLC_MASK;
416         }
417
418         err = sock_queue_rcv_skb(sk, skb);
419         if (err < 0) {
420                 struct bcm_opt *bo = bcm_sk(sk);
421
422                 DBG("sock_queue_rcv_skb failed: %d\n", err);
423                 kfree_skb(skb);
424                 /* don't care about overflows in this statistic */
425                 bo->dropped_usr_msgs++;
426         }
427 }
428
429 /*
430  * bcm_tx_timeout_handler - performes cyclic CAN frame transmissions
431  */
432 static void bcm_tx_timeout_handler(unsigned long data)
433 {
434         struct bcm_op *op = (struct bcm_op*)data;
435
436         DBG("Called with bcm_op %p\n", op);
437
438         if (op->j_ival1 && (op->count > 0)) {
439
440                 op->count--;
441                 if (!op->count && (op->flags & TX_COUNTEVT)) {
442                         struct bcm_msg_head msg_head;
443
444                         /* create notification to user */
445                         DBG("sending TX_EXPIRED for can_id %03X\n",
446                             op->can_id);
447
448                         msg_head.opcode  = TX_EXPIRED;
449                         msg_head.flags   = op->flags;
450                         msg_head.count   = op->count;
451                         msg_head.ival1   = op->ival1;
452                         msg_head.ival2   = op->ival2;
453                         msg_head.can_id  = op->can_id;
454                         msg_head.nframes = 0;
455
456                         bcm_send_to_user(op, &msg_head, NULL, 0);
457                 }
458         }
459
460         DBG("count=%d j_ival1=%ld j_ival2=%ld\n",
461             op->count, op->j_ival1, op->j_ival2);
462
463         if (op->j_ival1 && (op->count > 0)) {
464
465                 op->timer.expires = jiffies + op->j_ival1;
466                 add_timer(&op->timer);
467
468                 DBG("adding timer ival1. func=%p data=%p exp=0x%08X\n",
469                     op->timer.function,
470                     (char*) op->timer.data,
471                     (unsigned int) op->timer.expires);
472
473                 /* send (next) frame */
474                 bcm_can_tx(op);
475
476         } else {
477                 if (op->j_ival2) {
478                         op->timer.expires = jiffies + op->j_ival2;
479                         add_timer(&op->timer);
480
481                         DBG("adding timer ival2. func=%p data=%p exp=0x%08X\n",
482                             op->timer.function,
483                             (char*) op->timer.data,
484                             (unsigned int) op->timer.expires);
485
486                         /* send (next) frame */
487                         bcm_can_tx(op);
488
489                 } else
490                         DBG("no timer restart\n");
491         }
492
493         return;
494 }
495
496 /*
497  * bcm_rx_changed - create a RX_CHANGED notification due to changed content
498  */
499 static void bcm_rx_changed(struct bcm_op *op, struct can_frame *data)
500 {
501         struct bcm_msg_head head;
502
503         op->j_lastmsg = jiffies;
504
505         /* update statistics */
506         op->frames_filtered++;
507
508         /* prevent statistics overflow */
509         if (op->frames_filtered > ULONG_MAX/100)
510                 op->frames_filtered = op->frames_abs = 0;
511
512         DBG("setting j_lastmsg to 0x%08X for rx_op %p\n",
513             (unsigned int) op->j_lastmsg, op);
514         DBG("sending notification\n");
515
516         head.opcode  = RX_CHANGED;
517         head.flags   = op->flags;
518         head.count   = op->count;
519         head.ival1   = op->ival1;
520         head.ival2   = op->ival2;
521         head.can_id  = op->can_id;
522         head.nframes = 1;
523
524         bcm_send_to_user(op, &head, data, 1);
525 }
526
527 /*
528  * bcm_rx_update_and_send - process a detected relevant receive content change
529  *                          1. update the last received data
530  *                          2. send a notification to the user (if possible)
531  */
532 static void bcm_rx_update_and_send(struct bcm_op *op,
533                                    struct can_frame *lastdata,
534                                    struct can_frame *rxdata)
535 {
536         unsigned long nexttx = op->j_lastmsg + op->j_ival2;
537
538         memcpy(lastdata, rxdata, CFSIZ);
539
540         /* mark as used */
541         lastdata->can_dlc |= RX_RECV;
542
543         /* throttle bcm_rx_changed ? */
544         if ((op->thrtimer.expires) ||
545             ((op->j_ival2) && (nexttx > jiffies))) {
546                 /* we are already waiting OR we have to start waiting */
547
548                 /* mark as 'throttled' */
549                 lastdata->can_dlc |= RX_THR;
550
551                 if (!(op->thrtimer.expires)) {
552                         /* start the timer only the first time */
553                         op->thrtimer.expires = nexttx;
554                         add_timer(&op->thrtimer);
555
556                         DBG("adding thrtimer. func=%p data=%p exp=0x%08X\n",
557                             op->thrtimer.function,
558                             (char*) op->thrtimer.data,
559                             (unsigned int) op->thrtimer.expires);
560                 }
561
562         } else {
563                 /* send RX_CHANGED to the user immediately */
564                 bcm_rx_changed(op, rxdata);
565         }
566 }
567
568 /*
569  * bcm_rx_cmp_to_index - (bit)compares the currently received data to formerly
570  *                       received data stored in op->last_frames[]
571  */
572 static void bcm_rx_cmp_to_index(struct bcm_op *op, int index,
573                                 struct can_frame *rxdata)
574 {
575         /*
576          * no one uses the MSBs of can_dlc for comparation,
577          * so we use it here to detect the first time of reception
578          */
579
580         if (!(op->last_frames[index].can_dlc & RX_RECV)) {
581                 /* received data for the first time => send update to user */
582                 DBG("first time :)\n");
583                 bcm_rx_update_and_send(op, &op->last_frames[index], rxdata);
584                 return;
585         }
586
587         /* do a real check in can_frame data section */
588
589         DBG("op->frames[index].data = 0x%016llx\n",
590             GET_U64(&op->frames[index]));
591         DBG("op->last_frames[index].data = 0x%016llx\n",
592             GET_U64(&op->last_frames[index]));
593         DBG("rxdata->data = 0x%016llx\n", GET_U64(rxdata));
594
595         if ((GET_U64(&op->frames[index]) & GET_U64(rxdata)) !=
596             (GET_U64(&op->frames[index]) & GET_U64(&op->last_frames[index]))) {
597                 DBG("relevant data change :)\n");
598                 bcm_rx_update_and_send(op, &op->last_frames[index], rxdata);
599                 return;
600         }
601
602         if (op->flags & RX_CHECK_DLC) {
603                 /* do a real check in can_frame dlc */
604                 if (rxdata->can_dlc != (op->last_frames[index].can_dlc &
605                                         BCM_CAN_DLC_MASK)) {
606                         DBG("dlc change :)\n");
607                         bcm_rx_update_and_send(op, &op->last_frames[index],
608                                                rxdata);
609                         return;
610                 }
611         }
612         DBG("no relevant change :(\n");
613 }
614
615 /*
616  * bcm_rx_starttimer - enable timeout monitoring for CAN frame receiption
617  */
618 static void bcm_rx_starttimer(struct bcm_op *op)
619 {
620         if (op->flags & RX_NO_AUTOTIMER)
621                 return;
622
623         if (op->j_ival1) {
624                 op->timer.expires = jiffies + op->j_ival1;
625
626                 DBG("adding rx timeout timer ival1. func=%p data=%p "
627                     "exp=0x%08X\n",
628                     op->timer.function,
629                     (char*) op->timer.data,
630                     (unsigned int) op->timer.expires);
631
632                 add_timer(&op->timer);
633         }
634 }
635
636 /*
637  * bcm_rx_timeout_handler - when the (cyclic) CAN frame receiption timed out
638  */
639 static void bcm_rx_timeout_handler(unsigned long data)
640 {
641         struct bcm_op *op = (struct bcm_op*)data;
642         struct bcm_msg_head msg_head;
643
644         DBG("sending RX_TIMEOUT for can_id %03X. op is %p\n", op->can_id, op);
645
646         msg_head.opcode  = RX_TIMEOUT;
647         msg_head.flags   = op->flags;
648         msg_head.count   = op->count;
649         msg_head.ival1   = op->ival1;
650         msg_head.ival2   = op->ival2;
651         msg_head.can_id  = op->can_id;
652         msg_head.nframes = 0;
653
654         bcm_send_to_user(op, &msg_head, NULL, 0);
655
656         /* no restart of the timer is done here! */
657
658         /* if user wants to be informed, when cyclic CAN-Messages come back */
659         if ((op->flags & RX_ANNOUNCE_RESUME) && op->last_frames) {
660                 /* clear received can_frames to indicate 'nothing received' */
661                 memset(op->last_frames, 0, op->nframes * CFSIZ);
662                 DBG("RX_ANNOUNCE_RESTART\n");
663         }
664 }
665
666 /*
667  * bcm_rx_thr_handler - the time for blocked content updates is over now:
668  *                      Check for throttled data and send it to the userspace
669  */
670 static void bcm_rx_thr_handler(unsigned long data)
671 {
672         struct bcm_op *op = (struct bcm_op*)data;
673         int i = 0;
674
675         /* mark disabled / consumed timer */
676         op->thrtimer.expires = 0;
677
678         if (op->nframes > 1) {
679                 DBG("sending MUX RX_CHANGED for can_id %03X. op is %p\n",
680                     op->can_id, op);
681                 /* for MUX filter we start at index 1 */
682                 for (i=1; i<op->nframes; i++) {
683                         if ((op->last_frames) &&
684                             (op->last_frames[i].can_dlc & RX_THR)) {
685                                 op->last_frames[i].can_dlc &= ~RX_THR;
686                                 bcm_rx_changed(op, &op->last_frames[i]);
687                         }
688                 }
689
690         } else {
691                 DBG("sending simple RX_CHANGED for can_id %03X. op is %p\n",
692                     op->can_id, op);
693                 /* for RX_FILTER_ID and simple filter */
694                 if (op->last_frames && (op->last_frames[0].can_dlc & RX_THR)) {
695                         op->last_frames[0].can_dlc &= ~RX_THR;
696                         bcm_rx_changed(op, &op->last_frames[0]);
697                 }
698         }
699 }
700
701 /*
702  * bcm_rx_handler - handle a CAN frame receiption
703  */
704 static void bcm_rx_handler(struct sk_buff *skb, void *data)
705 {
706         struct bcm_op *op = (struct bcm_op*)data;
707         struct can_frame rxframe;
708         int i;
709
710         /* disable timeout */
711         del_timer(&op->timer);
712
713         DBG("Called with bcm_op %p\n", op);
714
715         if (skb->len == sizeof(rxframe)) {
716                 memcpy(&rxframe, skb->data, sizeof(rxframe));
717                 /* save rx timestamp */
718 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
719                 op->rx_stamp = skb->tstamp;
720 #else
721                 skb_get_timestamp(skb, &op->rx_stamp);
722 #endif
723                 /* save originator for recvfrom() */
724                 op->rx_ifindex = skb->dev->ifindex;
725                 /* update statistics */
726                 op->frames_abs++;
727                 kfree_skb(skb);
728                 DBG("got can_frame with can_id %03X\n", rxframe.can_id);
729
730         } else {
731                 DBG("Wrong skb->len = %d\n", skb->len);
732                 kfree_skb(skb);
733                 return;
734         }
735
736         DBG_FRAME("BCM: bcm_rx_handler: CAN frame", &rxframe);
737
738         if (op->can_id != rxframe.can_id) {
739                 DBG("ERROR! Got wrong can_id %03X! Expected %03X.\n",
740                     rxframe.can_id, op->can_id);
741                 return;
742         }
743
744         if (op->flags & RX_RTR_FRAME) {
745                 /* send reply for RTR-request */
746                 DBG("RTR-request\n");
747
748                 /* send op->frames[0] to CAN device */
749                 bcm_can_tx(op);
750                 return;
751         }
752
753         if (op->flags & RX_FILTER_ID) {
754                 /* the easiest case */
755                 DBG("Easy does it with RX_FILTER_ID\n");
756
757                 bcm_rx_update_and_send(op, &op->last_frames[0], &rxframe);
758                 bcm_rx_starttimer(op);
759                 return;
760         }
761
762         if (op->nframes == 1) {
763                 /* simple compare with index 0 */
764                 DBG("Simple compare\n");
765
766                 bcm_rx_cmp_to_index(op, 0, &rxframe);
767                 bcm_rx_starttimer(op);
768                 return;
769         }
770
771         if (op->nframes > 1) {
772                 /* multiplex compare */
773                 DBG("Multiplex compare\n");
774
775                 /*
776                  * find the first multiplex mask that fits.
777                  * Remark: The MUX-mask is stored in index 0
778                  */
779
780                 for (i=1; i < op->nframes; i++) {
781                         if ((GET_U64(&op->frames[0]) & GET_U64(&rxframe)) ==
782                             (GET_U64(&op->frames[0]) &
783                              GET_U64(&op->frames[i]))) {
784                                 DBG("found MUX index %d\n", i);
785                                 bcm_rx_cmp_to_index(op, i, &rxframe);
786                                 break;
787                         }
788                 }
789                 bcm_rx_starttimer(op);
790         }
791 }
792
793 /*
794  * helpers for bcm_op handling: find & delete bcm [rx|tx] op elements
795  */
796 static struct bcm_op *bcm_find_op(struct list_head *ops, canid_t can_id,
797                                   int ifindex)
798 {
799         struct bcm_op *op;
800
801         list_for_each_entry(op, ops, list) {
802                 if ((op->can_id == can_id) && (op->ifindex == ifindex))
803                         return op;
804         }
805
806         return NULL;
807 }
808
809 static void bcm_remove_op(struct bcm_op *op)
810 {
811         del_timer(&op->timer);
812         del_timer(&op->thrtimer);
813
814         if ((op->frames) && (op->frames != &op->sframe))
815                 kfree(op->frames);
816
817         if ((op->last_frames) && (op->last_frames != &op->last_sframe))
818                 kfree(op->last_frames);
819
820         kfree(op);
821
822         return;
823 }
824
825 static void bcm_rx_unreg(struct net_device *dev, struct bcm_op *op)
826 {
827         if (op->rx_reg_dev == dev) {
828                 can_rx_unregister(dev, op->can_id, REGMASK(op->can_id),
829                                   bcm_rx_handler, op);
830
831                 /* mark as removed subscription */
832                 op->rx_reg_dev = NULL;
833         } else
834                 printk(KERN_ERR "can-bcm: bcm_rx_unreg: registered device "
835                        "mismatch %p %p\n", op->rx_reg_dev, dev);
836 }
837
838 /*
839  * bcm_delete_rx_op - find and remove a rx op (returns number of removed ops)
840  */
841 static int bcm_delete_rx_op(struct list_head *ops, canid_t can_id, int ifindex)
842 {
843         struct bcm_op *op, *n;
844
845         list_for_each_entry_safe(op, n, ops, list) {
846                 if ((op->can_id == can_id) && (op->ifindex == ifindex)) {
847                         DBG("removing rx_op %p for can_id %03X\n",
848                             op, op->can_id);
849
850                         /*
851                          * Don't care if we're bound or not (due to netdev
852                          * problems) can_rx_unregister() is always a save
853                          * thing to do here.
854                          */
855                         if (op->ifindex) {
856                                 /*
857                                  * Only remove subscriptions that had not
858                                  * been removed due to NETDEV_UNREGISTER
859                                  * in bcm_notifier()
860                                  */
861                                 if (op->rx_reg_dev) {
862                                         struct net_device *dev;
863
864                                         dev = dev_get_by_index(op->ifindex);
865                                         if (dev) {
866                                                 bcm_rx_unreg(dev, op);
867                                                 dev_put(dev);
868                                         }
869                                 }
870                         } else
871                                 can_rx_unregister(NULL, op->can_id,
872                                                   REGMASK(op->can_id),
873                                                   bcm_rx_handler, op);
874
875                         list_del(&op->list);
876                         bcm_remove_op(op);
877                         return 1; /* done */
878                 }
879         }
880
881         return 0; /* not found */
882 }
883
884 /*
885  * bcm_delete_tx_op - find and remove a tx op (returns number of removed ops)
886  */
887 static int bcm_delete_tx_op(struct list_head *ops, canid_t can_id, int ifindex)
888 {
889         struct bcm_op *op, *n;
890
891         list_for_each_entry_safe(op, n, ops, list) {
892                 if ((op->can_id == can_id) && (op->ifindex == ifindex)) {
893                         DBG("removing rx_op %p for can_id %03X\n",
894                             op, op->can_id);
895                         list_del(&op->list);
896                         bcm_remove_op(op);
897                         return 1; /* done */
898                 }
899         }
900
901         return 0; /* not found */
902 }
903
904 /*
905  * bcm_read_op - read out a bcm_op and send it to the user (for bcm_sendmsg)
906  */
907 static int bcm_read_op(struct list_head *ops, struct bcm_msg_head *msg_head,
908                        int ifindex)
909 {
910         struct bcm_op *op = bcm_find_op(ops, msg_head->can_id, ifindex);
911
912         if (!op) {
913                 DBG("TRX_READ: did not find op for can_id %03X\n",
914                     msg_head->can_id);
915                 return -EINVAL;
916         }
917
918         DBG("TRX_READ: sending status for can_id %03X\n",
919             msg_head->can_id);
920         /* put current values into msg_head */
921         msg_head->flags   = op->flags;
922         msg_head->count   = op->count;
923         msg_head->ival1   = op->ival1;
924         msg_head->ival2   = op->ival2;
925         msg_head->nframes = op->nframes;
926
927         bcm_send_to_user(op, msg_head, op->frames, 0);
928
929         return MHSIZ;
930 }
931
932 /*
933  * bcm_tx_setup - create or update a bcm tx op (for bcm_sendmsg)
934  */
935 static int bcm_tx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
936                         int ifindex, struct sock *sk)
937 {
938         struct bcm_opt *bo = bcm_sk(sk);
939         struct bcm_op *op;
940         int i, err;
941
942         /* we need a real device to send frames */
943         if (!ifindex)
944                 return -ENODEV;
945
946         /* we need at least one can_frame */
947         if (msg_head->nframes < 1)
948                 return -EINVAL;
949
950         /* check the given can_id */
951         op = bcm_find_op(&bo->tx_ops, msg_head->can_id, ifindex);
952
953         if (op) {
954                 /* update existing BCM operation */
955
956                 DBG("TX_SETUP: modifying existing tx_op %p for can_id %03X\n",
957                     op, msg_head->can_id);
958
959                 /*
960                  * Do we need more space for the can_frames than currently
961                  * allocated? -> This is a _really_ unusual use-case and
962                  * therefore (complexity / locking) it is not supported.
963                  */
964                 if (msg_head->nframes > op->nframes)
965                         return -E2BIG;
966
967                 /* update can_frames content */
968                 for (i = 0; i < msg_head->nframes; i++) {
969                         err = memcpy_fromiovec((u8*)&op->frames[i],
970                                                msg->msg_iov, CFSIZ);
971                         if (err < 0)
972                                 return err;
973
974                         if (msg_head->flags & TX_CP_CAN_ID) {
975                                 /* copy can_id into frame */
976                                 op->frames[i].can_id = msg_head->can_id;
977                         }
978                 }
979
980         } else {
981                 /* insert new BCM operation for the given can_id */
982
983                 op = kzalloc(OPSIZ, GFP_KERNEL);
984                 if (!op)
985                         return -ENOMEM;
986
987                 DBG("TX_SETUP: creating new tx_op %p for can_id %03X\n",
988                     op, msg_head->can_id);
989
990                 op->can_id    = msg_head->can_id;
991
992                 /* create array for can_frames and copy the data */
993                 if (msg_head->nframes > 1) {
994                         op->frames = kmalloc(msg_head->nframes * CFSIZ,
995                                              GFP_KERNEL);
996                         if (!op->frames) {
997                                 kfree(op);
998                                 return -ENOMEM;
999                         }
1000                 } else
1001                         op->frames = &op->sframe;
1002
1003                 for (i = 0; i < msg_head->nframes; i++) {
1004                         err = memcpy_fromiovec((u8*)&op->frames[i],
1005                                                msg->msg_iov, CFSIZ);
1006                         if (err < 0) {
1007                                 if (op->frames != &op->sframe)
1008                                         kfree(op->frames);
1009                                 kfree(op);
1010                                 return err;
1011                         }
1012
1013                         if (msg_head->flags & TX_CP_CAN_ID) {
1014                                 /* copy can_id into frame */
1015                                 op->frames[i].can_id = msg_head->can_id;
1016                         }
1017                 }
1018
1019                 /* tx_ops never compare with previous received messages */
1020                 op->last_frames = NULL;
1021
1022                 /* bcm_can_tx / bcm_tx_timeout_handler needs this */
1023                 op->sk = sk;
1024
1025                 op->ifindex = ifindex;
1026
1027                 /* initialize uninitialized (kmalloc) structure */
1028                 init_timer(&op->timer);
1029
1030                 /* currently unused in tx_ops */
1031                 init_timer(&op->thrtimer);
1032
1033                 /* handler for tx_ops */
1034                 op->timer.function = bcm_tx_timeout_handler;
1035
1036                 /* timer.data points to this op-structure */
1037                 op->timer.data = (unsigned long)op;
1038
1039                 /* add this bcm_op to the list of the tx_ops */
1040                 list_add(&op->list, &bo->tx_ops);
1041
1042         } /* if ((op = bcm_find_op(&bo->tx_ops, msg_head->can_id, ifindex))) */
1043
1044         if (op->nframes != msg_head->nframes) {
1045                 op->nframes   = msg_head->nframes;
1046                 /* start multiple frame transmission with index 0 */
1047                 op->currframe = 0;
1048         }
1049
1050         /* check flags */
1051
1052         op->flags = msg_head->flags;
1053
1054         if (op->flags & TX_RESET_MULTI_IDX) {
1055                 /* start multiple frame transmission with index 0 */
1056                 op->currframe = 0;
1057         }
1058
1059         if (op->flags & SETTIMER) {
1060                 /* set timer values */
1061
1062                 op->count = msg_head->count;
1063                 op->ival1 = msg_head->ival1;
1064                 op->ival2 = msg_head->ival2;
1065                 op->j_ival1 = rounded_tv2jif(&msg_head->ival1);
1066                 op->j_ival2 = rounded_tv2jif(&msg_head->ival2);
1067
1068                 DBG("TX_SETUP: SETTIMER count=%d j_ival1=%ld j_ival2=%ld\n",
1069                     op->count, op->j_ival1, op->j_ival2);
1070
1071                 /* disable an active timer due to zero values? */
1072                 if (!op->j_ival1 && !op->j_ival2) {
1073                         del_timer(&op->timer);
1074                         DBG("TX_SETUP: SETTIMER disabled timer.\n");
1075                 }
1076         }
1077
1078         if ((op->flags & STARTTIMER) &&
1079             ((op->j_ival1 && op->count) || op->j_ival2)) {
1080
1081                 del_timer(&op->timer);
1082
1083                 /* spec: send can_frame when starting timer */
1084                 op->flags |= TX_ANNOUNCE;
1085
1086                 if (op->j_ival1 && (op->count > 0)) {
1087                         op->timer.expires = jiffies + op->j_ival1;
1088                         /* op->count-- is done in bcm_tx_timeout_handler */
1089                         DBG("TX_SETUP: adding timer ival1. func=%p data=%p "
1090                             "exp=0x%08X\n",
1091                             op->timer.function,
1092                             (char*) op->timer.data,
1093                             (unsigned int) op->timer.expires);
1094
1095                 } else {
1096                         op->timer.expires = jiffies + op->j_ival2;
1097                         DBG("TX_SETUP: adding timer ival2. func=%p data=%p "
1098                             "exp=0x%08X\n",
1099                             op->timer.function,
1100                             (char*) op->timer.data,
1101                             (unsigned int) op->timer.expires);
1102                 }
1103
1104                 add_timer(&op->timer);
1105         }
1106
1107         if (op->flags & TX_ANNOUNCE)
1108                 bcm_can_tx(op);
1109
1110         return msg_head->nframes * CFSIZ + MHSIZ;
1111 }
1112
1113 /*
1114  * bcm_rx_setup - create or update a bcm rx op (for bcm_sendmsg)
1115  */
1116 static int bcm_rx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
1117                         int ifindex, struct sock *sk)
1118 {
1119         struct bcm_opt *bo = bcm_sk(sk);
1120         struct bcm_op *op;
1121         int do_rx_register;
1122         int err;
1123
1124         if ((msg_head->flags & RX_FILTER_ID) || (!(msg_head->nframes))) {
1125                 /* be robust against wrong usage ... */
1126                 msg_head->flags |= RX_FILTER_ID;
1127                 msg_head->nframes = 0; /* ignore trailing garbage */
1128         }
1129
1130         if ((msg_head->flags & RX_RTR_FRAME) &&
1131             ((msg_head->nframes != 1) ||
1132              (!(msg_head->can_id & CAN_RTR_FLAG)))) {
1133
1134                 DBG("RX_SETUP: bad RX_RTR_FRAME setup!\n");
1135                 return -EINVAL;
1136         }
1137
1138         /* check the given can_id */
1139         op = bcm_find_op(&bo->rx_ops, msg_head->can_id, ifindex);
1140         if (op) {
1141                 /* update existing BCM operation */
1142
1143                 DBG("RX_SETUP: modifying existing rx_op %p for can_id %03X\n",
1144                     op, msg_head->can_id);
1145
1146                 /*
1147                  * Do we need more space for the can_frames than currently
1148                  * allocated? -> This is a _really_ unusual use-case and
1149                  * therefore (complexity / locking) it is not supported.
1150                  */
1151                 if (msg_head->nframes > op->nframes)
1152                         return -E2BIG;
1153
1154                 if (msg_head->nframes) {
1155                         /* update can_frames content */
1156                         err = memcpy_fromiovec((u8*)op->frames,
1157                                                msg->msg_iov,
1158                                                msg_head->nframes * CFSIZ);
1159                         if (err < 0)
1160                                 return err;
1161
1162                         /* clear last_frames to indicate 'nothing received' */
1163                         memset(op->last_frames, 0, msg_head->nframes * CFSIZ);
1164                 }
1165
1166                 op->nframes = msg_head->nframes;
1167
1168                 /* Only an update -> do not call can_rx_register() */
1169                 do_rx_register = 0;
1170
1171         } else {
1172                 /* insert new BCM operation for the given can_id */
1173
1174                 op = kzalloc(OPSIZ, GFP_KERNEL);
1175                 if (!op)
1176                         return -ENOMEM;
1177
1178                 DBG("RX_SETUP: creating new rx_op %p for can_id %03X\n",
1179                     op, msg_head->can_id);
1180
1181                 op->can_id    = msg_head->can_id;
1182                 op->nframes   = msg_head->nframes;
1183
1184                 if (msg_head->nframes > 1) {
1185                         /* create array for can_frames and copy the data */
1186                         op->frames = kmalloc(msg_head->nframes * CFSIZ,
1187                                              GFP_KERNEL);
1188                         if (!op->frames) {
1189                                 kfree(op);
1190                                 return -ENOMEM;
1191                         }
1192
1193                         /* create and init array for received can_frames */
1194                         op->last_frames = kzalloc(msg_head->nframes * CFSIZ,
1195                                                   GFP_KERNEL);
1196                         if (!op->last_frames) {
1197                                 kfree(op->frames);
1198                                 kfree(op);
1199                                 return -ENOMEM;
1200                         }
1201
1202                 } else {
1203                         op->frames = &op->sframe;
1204                         op->last_frames = &op->last_sframe;
1205                 }
1206
1207                 if (msg_head->nframes) {
1208                         err = memcpy_fromiovec((u8*)op->frames, msg->msg_iov,
1209                                                msg_head->nframes * CFSIZ);
1210                         if (err < 0) {
1211                                 if (op->frames != &op->sframe)
1212                                         kfree(op->frames);
1213                                 if (op->last_frames != &op->last_sframe)
1214                                         kfree(op->last_frames);
1215                                 kfree(op);
1216                                 return err;
1217                         }
1218                 }
1219
1220                 op->sk = sk;
1221                 op->ifindex = ifindex;
1222
1223                 /* initialize uninitialized (kzalloc) structure */
1224                 init_timer(&op->timer);
1225
1226                 /* init throttle timer for RX_CHANGED */
1227                 init_timer(&op->thrtimer);
1228
1229                 /* handler for rx timeouts */
1230                 op->timer.function = bcm_rx_timeout_handler;
1231
1232                 /* timer.data points to this op-structure */
1233                 op->timer.data = (unsigned long)op;
1234
1235                 /* handler for RX_CHANGED throttle timeouts */
1236                 op->thrtimer.function = bcm_rx_thr_handler;
1237
1238                 /* timer.data points to this op-structure */
1239                 op->thrtimer.data = (unsigned long)op;
1240
1241                 /* mark disabled timer */
1242                 op->thrtimer.expires = 0;
1243
1244                 /* add this bcm_op to the list of the tx_ops */
1245                 list_add(&op->list, &bo->rx_ops);
1246
1247                 /* call can_rx_register() */
1248                 do_rx_register = 1;
1249
1250         } /* if ((op = bcm_find_op(&bo->rx_ops, msg_head->can_id, ifindex))) */
1251
1252         /* check flags */
1253         op->flags = msg_head->flags;
1254
1255         if (op->flags & RX_RTR_FRAME) {
1256
1257                 /* no timers in RTR-mode */
1258                 del_timer(&op->thrtimer);
1259                 del_timer(&op->timer);
1260
1261                 /*
1262                  * funny feature in RX(!)_SETUP only for RTR-mode:
1263                  * copy can_id into frame BUT without RTR-flag to
1264                  * prevent a full-load-loopback-test ... ;-]
1265                  */
1266                 if ((op->flags & TX_CP_CAN_ID) ||
1267                     (op->frames[0].can_id == op->can_id))
1268                         op->frames[0].can_id = op->can_id & ~CAN_RTR_FLAG;
1269
1270         } else {
1271                 if (op->flags & SETTIMER) {
1272
1273                         /* set timer value */
1274                         op->ival1 = msg_head->ival1;
1275                         op->ival2 = msg_head->ival2;
1276                         op->j_ival1 = rounded_tv2jif(&msg_head->ival1);
1277                         op->j_ival2 = rounded_tv2jif(&msg_head->ival2);
1278
1279                         DBG("RX_SETUP: SETTIMER j_ival1=%ld j_ival2=%ld\n",
1280                             op->j_ival1, op->j_ival2);
1281
1282                         /* disable an active timer due to zero value? */
1283                         if (!op->j_ival1) {
1284                                 del_timer(&op->timer);
1285                                 DBG("RX_SETUP: disabled timer rx timeouts.\n");
1286                         }
1287
1288                         /* free currently blocked msgs ? */
1289                         if (op->thrtimer.expires) {
1290                                 DBG("RX_SETUP: unblocking throttled msgs.\n");
1291                                 del_timer(&op->thrtimer);
1292                                 /* send blocked msgs hereafter */
1293                                 op->thrtimer.expires = jiffies + 2;
1294                                 add_timer(&op->thrtimer);
1295                         }
1296                         /*
1297                          * if (op->j_ival2) is zero, no (new) throttling
1298                          * will happen. For details see functions
1299                          * bcm_rx_update_and_send() and bcm_rx_thr_handler()
1300                          */
1301                 }
1302
1303                 if ((op->flags & STARTTIMER) && op->j_ival1) {
1304
1305                         del_timer(&op->timer);
1306                         op->timer.expires = jiffies + op->j_ival1;
1307
1308                         DBG("RX_SETUP: adding timer ival1. func=%p data=%p"
1309                             " exp=0x%08X\n",
1310                             (char *) op->timer.function,
1311                             (char *) op->timer.data,
1312                             (unsigned int) op->timer.expires);
1313
1314                         add_timer(&op->timer);
1315                 }
1316         }
1317
1318         /* now we can register for can_ids, if we added a new bcm_op */
1319         if (do_rx_register) {
1320                 DBG("RX_SETUP: can_rx_register() for can_id %03X. "
1321                     "rx_op is %p\n", op->can_id, op);
1322
1323                 if (ifindex) {
1324                         struct net_device *dev = dev_get_by_index(ifindex);
1325
1326                         if (dev) {
1327                                 can_rx_register(dev, op->can_id,
1328                                                 REGMASK(op->can_id),
1329                                                 bcm_rx_handler, op, IDENT);
1330                                 op->rx_reg_dev = dev;
1331                                 dev_put(dev);
1332                         }
1333
1334                 } else
1335                         can_rx_register(NULL, op->can_id, REGMASK(op->can_id),
1336                                         bcm_rx_handler, op, IDENT);
1337         }
1338
1339         return msg_head->nframes * CFSIZ + MHSIZ;
1340 }
1341
1342 /*
1343  * bcm_tx_send - send a single CAN frame to the CAN interface (for bcm_sendmsg)
1344  */
1345 static int bcm_tx_send(struct msghdr *msg, int ifindex, struct sock *sk)
1346 {
1347         struct sk_buff *skb;
1348         struct net_device *dev;
1349         int err;
1350
1351         /* just copy and send one can_frame */
1352
1353         if (!ifindex) /* we need a real device to send frames */
1354                 return -ENODEV;
1355
1356         skb = alloc_skb(CFSIZ, GFP_KERNEL);
1357
1358         if (!skb)
1359                 return -ENOMEM;
1360
1361         err = memcpy_fromiovec(skb_put(skb, CFSIZ), msg->msg_iov, CFSIZ);
1362         if (err < 0) {
1363                 kfree_skb(skb);
1364                 return err;
1365         }
1366
1367         DBG_FRAME("BCM: TX_SEND: sending frame",
1368                   (struct can_frame *)skb->data);
1369
1370         dev = dev_get_by_index(ifindex);
1371         if (!dev) {
1372                 kfree_skb(skb);
1373                 return -ENODEV;
1374         }
1375
1376         skb->dev = dev;
1377         skb->sk  = sk;
1378         can_send(skb, 1); /* send with loopback */
1379         dev_put(dev);
1380
1381         return CFSIZ + MHSIZ;
1382 }
1383
1384 /*
1385  * bcm_sendmsg - process BCM commands (opcodes) from the userspace
1386  */
1387 static int bcm_sendmsg(struct kiocb *iocb, struct socket *sock,
1388                        struct msghdr *msg, size_t size)
1389 {
1390         struct sock *sk = sock->sk;
1391         struct bcm_opt *bo = bcm_sk(sk);
1392         int ifindex = bo->ifindex; /* default ifindex for this bcm_op */
1393         struct bcm_msg_head msg_head;
1394         int ret; /* read bytes or error codes as return value */
1395
1396         if (!bo->bound) {
1397                 DBG("sock %p not bound\n", sk);
1398                 return -ENOTCONN;
1399         }
1400
1401         /* check for alternative ifindex for this bcm_op */
1402
1403         if (!ifindex && msg->msg_name) {
1404                 /* no bound device as default => check msg_name */
1405                 struct sockaddr_can *addr =
1406                         (struct sockaddr_can *)msg->msg_name;
1407
1408                 if (addr->can_family != AF_CAN)
1409                         return -EINVAL;
1410
1411                 ifindex = addr->can_ifindex; /* ifindex from sendto() */
1412
1413                 if (ifindex) {
1414                         struct net_device *dev = dev_get_by_index(ifindex);
1415
1416                         if (!dev) {
1417                                 DBG("device %d not found\n", ifindex);
1418                                 return -ENODEV;
1419                         }
1420
1421                         if (dev->type != ARPHRD_CAN) {
1422                                 DBG("device %d no CAN device\n", ifindex);
1423                                 dev_put(dev);
1424                                 return -ENODEV;
1425                         }
1426
1427                         dev_put(dev);
1428                 }
1429         }
1430
1431         /* read message head information */
1432
1433         ret = memcpy_fromiovec((u8*)&msg_head, msg->msg_iov, MHSIZ);
1434         if (ret < 0)
1435                 return ret;
1436
1437         DBG("opcode %d for can_id %03X\n", msg_head.opcode, msg_head.can_id);
1438
1439         lock_sock(sk);
1440
1441         switch (msg_head.opcode) {
1442
1443         case TX_SETUP:
1444                 ret = bcm_tx_setup(&msg_head, msg, ifindex, sk);
1445                 break;
1446
1447         case RX_SETUP:
1448                 ret = bcm_rx_setup(&msg_head, msg, ifindex, sk);
1449                 break;
1450
1451         case TX_DELETE:
1452                 if (bcm_delete_tx_op(&bo->tx_ops, msg_head.can_id, ifindex))
1453                         ret = MHSIZ;
1454                 else
1455                         ret = -EINVAL;
1456                 break;
1457
1458         case RX_DELETE:
1459                 if (bcm_delete_rx_op(&bo->rx_ops, msg_head.can_id, ifindex))
1460                         ret = MHSIZ;
1461                 else
1462                         ret = -EINVAL;
1463                 break;
1464
1465         case TX_READ:
1466                 /* reuse msg_head for the reply to TX_READ */
1467                 msg_head.opcode  = TX_STATUS;
1468                 ret = bcm_read_op(&bo->tx_ops, &msg_head, ifindex);
1469                 break;
1470
1471         case RX_READ:
1472                 /* reuse msg_head for the reply to RX_READ */
1473                 msg_head.opcode  = RX_STATUS;
1474                 ret = bcm_read_op(&bo->rx_ops, &msg_head, ifindex);
1475                 break;
1476
1477         case TX_SEND:
1478                 /* we need at least one can_frame */
1479                 if (msg_head.nframes < 1)
1480                         ret = -EINVAL;
1481                 else
1482                         ret = bcm_tx_send(msg, ifindex, sk);
1483                 break;
1484
1485         default:
1486                 DBG("Unknown opcode %d\n", msg_head.opcode);
1487                 ret = -EINVAL;
1488                 break;
1489         }
1490
1491         release_sock(sk);
1492
1493         return ret;
1494 }
1495
1496 /*
1497  * notification handler for netdevice status changes
1498  */
1499 static int bcm_notifier(struct notifier_block *nb, unsigned long msg,
1500                         void *data)
1501 {
1502         struct net_device *dev = (struct net_device *)data;
1503         struct bcm_opt *bo = container_of(nb, struct bcm_opt, notifier);
1504 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
1505         struct bcm_sock *bs = container_of(bo, struct bcm_sock, opt);
1506         struct sock *sk = &bs->sk;
1507 #else
1508 #error TODO (if needed): Notifier support for Kernel Versions < 2.6.12
1509 #endif
1510         struct bcm_op *op;
1511         int notify_enodev = 0;
1512
1513         DBG("msg %ld for dev %p (%s idx %d) sk %p bo->ifindex %d\n",
1514             msg, dev, dev->name, dev->ifindex, sk, bo->ifindex);
1515
1516         if (dev->type != ARPHRD_CAN)
1517                 return NOTIFY_DONE;
1518
1519         switch (msg) {
1520
1521         case NETDEV_UNREGISTER:
1522                 lock_sock(sk);
1523
1524                 /* remove device specific receive entries */
1525                 list_for_each_entry(op, &bo->rx_ops, list)
1526                         if (op->rx_reg_dev == dev)
1527                                 bcm_rx_unreg(dev, op);
1528
1529                 /* remove device reference, if this is our bound device */
1530                 if (bo->bound && bo->ifindex == dev->ifindex) {
1531                         bo->bound   = 0;
1532                         bo->ifindex = 0;
1533                         notify_enodev = 1;
1534                 }
1535
1536                 release_sock(sk);
1537
1538                 if (notify_enodev) {
1539                         sk->sk_err = ENODEV;
1540                         if (!sock_flag(sk, SOCK_DEAD))
1541                                 sk->sk_error_report(sk);
1542                 }
1543                 break;
1544
1545         case NETDEV_DOWN:
1546                 if (bo->bound && bo->ifindex == dev->ifindex) {
1547                         sk->sk_err = ENETDOWN;
1548                         if (!sock_flag(sk, SOCK_DEAD))
1549                                 sk->sk_error_report(sk);
1550                 }
1551         }
1552
1553         return NOTIFY_DONE;
1554 }
1555
1556 /*
1557  * initial settings for all BCM sockets to be set at socket creation time
1558  */
1559 static int bcm_init(struct sock *sk)
1560 {
1561         struct bcm_opt *bo = bcm_sk(sk);
1562
1563         bo->bound            = 0;
1564         bo->ifindex          = 0;
1565         bo->dropped_usr_msgs = 0;
1566         bo->bcm_proc_read    = NULL;
1567
1568         INIT_LIST_HEAD(&bo->tx_ops);
1569         INIT_LIST_HEAD(&bo->rx_ops);
1570
1571         /* set notifier */
1572         bo->notifier.notifier_call = bcm_notifier;
1573
1574         register_netdevice_notifier(&bo->notifier);
1575
1576         return 0;
1577 }
1578
1579 /*
1580  * standard socket functions
1581  */
1582 static int bcm_release(struct socket *sock)
1583 {
1584         struct sock *sk = sock->sk;
1585         struct bcm_opt *bo = bcm_sk(sk);
1586         struct bcm_op *op, *next;
1587
1588         DBG("socket %p, sk %p\n", sock, sk);
1589
1590         /* remove bcm_ops, timer, rx_unregister(), etc. */
1591
1592         unregister_netdevice_notifier(&bo->notifier);
1593
1594         lock_sock(sk);
1595
1596         list_for_each_entry_safe(op, next, &bo->tx_ops, list) {
1597                 DBG("removing tx_op %p for can_id %03X\n", op, op->can_id);
1598                 bcm_remove_op(op);
1599         }
1600
1601         list_for_each_entry_safe(op, next, &bo->rx_ops, list) {
1602                 DBG("removing rx_op %p for can_id %03X\n", op, op->can_id);
1603
1604                 /*
1605                  * Don't care if we're bound or not (due to netdev problems)
1606                  * can_rx_unregister() is always a save thing to do here.
1607                  */
1608                 if (op->ifindex) {
1609                         /*
1610                          * Only remove subscriptions that had not
1611                          * been removed due to NETDEV_UNREGISTER
1612                          * in bcm_notifier()
1613                          */
1614                         if (op->rx_reg_dev) {
1615                                 struct net_device *dev;
1616
1617                                 dev = dev_get_by_index(op->ifindex);
1618                                 if (dev) {
1619                                         bcm_rx_unreg(dev, op);
1620                                         dev_put(dev);
1621                                 }
1622                         }
1623                 } else
1624                         can_rx_unregister(NULL, op->can_id,
1625                                           REGMASK(op->can_id),
1626                                           bcm_rx_handler, op);
1627
1628                 bcm_remove_op(op);
1629         }
1630
1631         /* remove procfs entry */
1632         if (proc_dir && bo->bcm_proc_read)
1633                 remove_proc_entry(bo->procname, proc_dir);
1634
1635         /* remove device reference */
1636         if (bo->bound) {
1637                 bo->bound   = 0;
1638                 bo->ifindex = 0;
1639         }
1640
1641         release_sock(sk);
1642         sock_put(sk);
1643
1644         return 0;
1645 }
1646
1647 static int bcm_connect(struct socket *sock, struct sockaddr *uaddr, int len,
1648                        int flags)
1649 {
1650         struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1651         struct sock *sk = sock->sk;
1652         struct bcm_opt *bo = bcm_sk(sk);
1653
1654         if (bo->bound)
1655                 return -EISCONN;
1656
1657         /* bind a device to this socket */
1658         if (addr->can_ifindex) {
1659                 struct net_device *dev = dev_get_by_index(addr->can_ifindex);
1660
1661                 if (!dev) {
1662                         DBG("could not find device index %d\n",
1663                             addr->can_ifindex);
1664                         return -ENODEV;
1665                 }
1666
1667                 if (dev->type != ARPHRD_CAN) {
1668                         DBG("device %d no CAN device\n", addr->can_ifindex);
1669                         dev_put(dev);
1670                         return -ENODEV;
1671                 }
1672
1673                 bo->ifindex = dev->ifindex;
1674                 dev_put(dev);
1675
1676                 DBG("socket %p bound to device %s (idx %d)\n",
1677                     sock, dev->name, dev->ifindex);
1678
1679         } else {
1680                 /* no interface reference for ifindex = 0 ('any' CAN device) */
1681                 bo->ifindex = 0;
1682         }
1683
1684         bo->bound = 1;
1685
1686         if (proc_dir) {
1687                 /* unique socket address as filename */
1688                 sprintf(bo->procname, "%p", sock);
1689                 bo->bcm_proc_read = create_proc_read_entry(bo->procname, 0644,
1690                                                            proc_dir,
1691                                                            bcm_read_proc, sk);
1692         }
1693
1694         return 0;
1695 }
1696
1697 static int bcm_recvmsg(struct kiocb *iocb, struct socket *sock,
1698                        struct msghdr *msg, size_t size, int flags)
1699 {
1700         struct sock *sk = sock->sk;
1701         struct sk_buff *skb;
1702         int error = 0;
1703         int noblock;
1704         int err;
1705
1706         DBG("socket %p, sk %p\n", sock, sk);
1707
1708         noblock =  flags & MSG_DONTWAIT;
1709         flags   &= ~MSG_DONTWAIT;
1710         skb = skb_recv_datagram(sk, flags, noblock, &error);
1711         if (!skb)
1712                 return error;
1713
1714         DBG("delivering skbuff %p\n", skb);
1715         DBG_SKB(skb);
1716
1717         if (skb->len < size)
1718                 size = skb->len;
1719
1720         err = memcpy_toiovec(msg->msg_iov, skb->data, size);
1721         if (err < 0) {
1722                 skb_free_datagram(sk, skb);
1723                 return err;
1724         }
1725
1726         sock_recv_timestamp(msg, sk, skb);
1727
1728         if (msg->msg_name) {
1729                 msg->msg_namelen = sizeof(struct sockaddr_can);
1730                 memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
1731         }
1732
1733         DBG("freeing sock %p, skbuff %p\n", sk, skb);
1734         skb_free_datagram(sk, skb);
1735
1736         return size;
1737 }
1738
1739 static unsigned int bcm_poll(struct file *file, struct socket *sock,
1740                              poll_table *wait)
1741 {
1742         unsigned int mask = 0;
1743
1744         DBG("socket %p\n", sock);
1745
1746         mask = datagram_poll(file, sock, wait);
1747         return mask;
1748 }
1749
1750 static struct proto_ops bcm_ops = {
1751         .family        = PF_CAN,
1752         .release       = bcm_release,
1753         .bind          = sock_no_bind,
1754         .connect       = bcm_connect,
1755         .socketpair    = sock_no_socketpair,
1756         .accept        = sock_no_accept,
1757         .getname       = sock_no_getname,
1758         .poll          = bcm_poll,
1759         .ioctl         = NULL,          /* use can_ioctl() from af_can.c */
1760         .listen        = sock_no_listen,
1761         .shutdown      = sock_no_shutdown,
1762         .setsockopt    = sock_no_setsockopt,
1763         .getsockopt    = sock_no_getsockopt,
1764         .sendmsg       = bcm_sendmsg,
1765         .recvmsg       = bcm_recvmsg,
1766         .mmap          = sock_no_mmap,
1767         .sendpage      = sock_no_sendpage,
1768 };
1769
1770 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
1771 static struct proto bcm_proto = {
1772         .name       = "CAN_BCM",
1773         .owner      = THIS_MODULE,
1774         .obj_size   = sizeof(struct bcm_sock),
1775         .init       = bcm_init,
1776 };
1777
1778 static struct can_proto bcm_can_proto = {
1779         .type       = SOCK_DGRAM,
1780         .protocol   = CAN_BCM,
1781         .capability = BCM_CAP,
1782         .ops        = &bcm_ops,
1783         .prot       = &bcm_proto,
1784 };
1785 #else
1786 static struct can_proto bcm_can_proto = {
1787         .type       = SOCK_DGRAM,
1788         .protocol   = CAN_BCM,
1789         .capability = BCM_CAP,
1790         .ops        = &bcm_ops,
1791         .owner      = THIS_MODULE,
1792         .obj_size   = sizeof(struct bcm_opt),
1793         .init       = bcm_init,
1794 };
1795 #endif
1796
1797 static int __init bcm_module_init(void)
1798 {
1799         printk(banner);
1800
1801         can_proto_register(&bcm_can_proto);
1802
1803         /* create /proc/net/can/bcm directory */
1804         proc_dir = proc_mkdir(CAN_PROC_DIR"/"IDENT, NULL);
1805
1806         if (proc_dir)
1807                 proc_dir->owner = THIS_MODULE;
1808
1809         return 0;
1810 }
1811
1812 static void __exit bcm_module_exit(void)
1813 {
1814         can_proto_unregister(&bcm_can_proto);
1815
1816         if (proc_dir)
1817                 remove_proc_entry(CAN_PROC_DIR"/"IDENT, NULL);
1818 }
1819
1820 module_init(bcm_module_init);
1821 module_exit(bcm_module_exit);