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