]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/net/can/bcm.c
Added missing include if_arp.h for the use of ARPHRD_CAN in notifier.
[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/if_arp.h>
53 #include <linux/can.h>
54 #include <linux/can/core.h>
55 #include <linux/can/bcm.h>
56 #include <net/sock.h>
57
58 #include <linux/can/version.h> /* for RCSID. Removed by mkpatch script */
59 RCSID("$Id$");
60
61 /* use of last_frames[index].can_dlc */
62 #define RX_RECV    0x40 /* received data for this element */
63 #define RX_THR     0x80 /* element not been sent due to throttle feature */
64 #define BCM_CAN_DLC_MASK 0x0F /* clean private flags in can_dlc by masking */
65
66 /* get best masking value for can_rx_register() for a given single can_id */
67 #define REGMASK(id) ((id & CAN_RTR_FLAG) | ((id & CAN_EFF_FLAG) ? \
68                         (CAN_EFF_MASK | CAN_EFF_FLAG) : CAN_SFF_MASK))
69
70 #define IDENT "bcm"
71 #define CAN_BCM_VERSION CAN_VERSION
72 static __initdata const char banner[] = KERN_INFO
73         "can: broadcast manager protocol (rev " CAN_BCM_VERSION ")\n";
74
75 MODULE_DESCRIPTION("PF_CAN broadcast manager protocol");
76 MODULE_LICENSE("Dual BSD/GPL");
77 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
78
79 #ifdef CONFIG_CAN_DEBUG_CORE
80 static int debug = 0;
81 module_param(debug, int, S_IRUGO);
82 MODULE_PARM_DESC(debug, "debug print mask: 1:debug, 2:frames, 4:skbs");
83 #endif
84
85 /* easy access to can_frame payload */
86 static inline u64 GET_U64(const struct can_frame *cp)
87 {
88         return *(u64*)cp->data;
89 }
90
91 struct bcm_op {
92         struct list_head list;
93         int ifindex;
94         canid_t can_id;
95         int flags;
96         unsigned long j_ival1, j_ival2, j_lastmsg;
97         unsigned long frames_abs, frames_filtered;
98         struct timer_list timer, thrtimer;
99         struct timeval ival1, ival2;
100 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
101         ktime_t rx_stamp;
102 #else
103         struct timeval rx_stamp;
104 #endif
105         int rx_ifindex;
106         int count;
107         int nframes;
108         int currframe;
109         struct can_frame *frames;
110         struct can_frame *last_frames;
111         struct can_frame sframe;
112         struct can_frame last_sframe;
113         struct sock *sk;
114         struct net_device *rx_reg_dev;
115 };
116
117 static struct proc_dir_entry *proc_dir = NULL;
118
119 #ifdef CONFIG_CAN_BCM_USER
120 #define BCM_CAP (-1)
121 #else
122 #define BCM_CAP CAP_NET_RAW
123 #endif
124
125 struct bcm_sock {
126 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
127         struct sock sk;
128 #else
129         struct sock *sk;
130 #endif
131         int bound;
132         int ifindex;
133         struct notifier_block notifier;
134         struct list_head rx_ops;
135         struct list_head tx_ops;
136         unsigned long dropped_usr_msgs;
137         struct proc_dir_entry *bcm_proc_read;
138         char procname [9]; /* pointer printed in ASCII with \0 */
139 };
140
141 static inline struct bcm_sock *bcm_sk(const struct sock *sk)
142 {
143 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
144         return (struct bcm_sock *)sk;
145 #else
146         return (struct bcm_sock *)sk->sk_protinfo;
147 #endif
148 }
149
150 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,14)
151 static void *kzalloc(size_t size, unsigned int __nocast flags)
152 {
153         void *ret = kmalloc(size, flags);
154
155         if (ret)
156                 memset(ret, 0, size);
157
158         return ret;
159 }
160
161 static inline void skb_get_timestamp(const struct sk_buff *skb,
162                                      struct timeval *stamp)
163 {
164         stamp->tv_sec  = skb->stamp.tv_sec;
165         stamp->tv_usec = skb->stamp.tv_usec;
166 }
167
168 static inline void skb_set_timestamp(struct sk_buff *skb,
169                                      const struct timeval *stamp)
170 {
171         skb->stamp.tv_sec  = stamp->tv_sec;
172         skb->stamp.tv_usec = stamp->tv_usec;
173 }
174 #endif
175
176 #define CFSIZ sizeof(struct can_frame)
177 #define OPSIZ sizeof(struct bcm_op)
178 #define MHSIZ sizeof(struct bcm_msg_head)
179
180 /*
181  * rounded_tv2jif - calculate jiffies from timeval including optional up
182  * @tv: pointer to timeval
183  *
184  * Description:
185  * In opposite to timeval_to_jiffies() provided in include/linux/jiffies.h this
186  * function is intentionally more relaxed on precise timer ticks to get exact
187  * one jiffy for requested 1000us on a 1000HZ machine.
188  * This code is to be removed when upgrading to kernel hrtimer.
189  *
190  * Return:
191  *  calculated jiffies (max: ULONG_MAX)
192  */
193 static unsigned long rounded_tv2jif(const struct timeval *tv)
194 {
195         unsigned long sec  = tv->tv_sec;
196         unsigned long usec = tv->tv_usec;
197         unsigned long jif;
198
199         if (sec > ULONG_MAX / HZ)
200                 return ULONG_MAX;
201
202         /* round up to get at least the requested time */
203         usec += 1000000 / HZ - 1;
204
205         jif  = usec / (1000000 / HZ);
206
207         if (sec * HZ > ULONG_MAX - jif)
208                 return ULONG_MAX;
209
210         return jif + sec * HZ;
211 }
212
213 /*
214  * procfs functions
215  */
216 static char *bcm_proc_getifname(int ifindex)
217 {
218         struct net_device *dev;
219
220         if (!ifindex)
221                 return "any";
222
223         dev = __dev_get_by_index(ifindex); /* no usage counting */
224         if (dev)
225                 return dev->name;
226
227         return "???";
228 }
229
230 static int bcm_read_proc(char *page, char **start, off_t off,
231                          int count, int *eof, void *data)
232 {
233         int len = 0;
234         struct sock *sk = (struct sock *)data;
235         struct bcm_sock *bo = bcm_sk(sk);
236         struct bcm_op *op;
237
238         len += snprintf(page + len, PAGE_SIZE - len, ">>> socket %p",
239                         sk->sk_socket);
240         len += snprintf(page + len, PAGE_SIZE - len, " / sk %p", sk);
241         len += snprintf(page + len, PAGE_SIZE - len, " / bo %p", bo);
242         len += snprintf(page + len, PAGE_SIZE - len, " / dropped %lu",
243                         bo->dropped_usr_msgs);
244         len += snprintf(page + len, PAGE_SIZE - len, " / bound %s",
245                         bcm_proc_getifname(bo->ifindex));
246         len += snprintf(page + len, PAGE_SIZE - len, " <<<\n");
247
248         list_for_each_entry(op, &bo->rx_ops, list) {
249
250                 unsigned long reduction;
251
252                 /* print only active entries & prevent division by zero */
253                 if (!op->frames_abs)
254                         continue;
255
256                 len += snprintf(page + len, PAGE_SIZE - len,
257                                 "rx_op: %03X %-5s ",
258                                 op->can_id, bcm_proc_getifname(op->ifindex));
259                 len += snprintf(page + len, PAGE_SIZE - len, "[%d]%c ",
260                                 op->nframes,
261                                 (op->flags & RX_CHECK_DLC)?'d':' ');
262                 if (op->j_ival1)
263                         len += snprintf(page + len, PAGE_SIZE - len,
264                                         "timeo=%ld ", op->j_ival1);
265
266                 if (op->j_ival2)
267                         len += snprintf(page + len, PAGE_SIZE - len,
268                                         "thr=%ld ", op->j_ival2);
269
270                 len += snprintf(page + len, PAGE_SIZE - len,
271                                 "# recv %ld (%ld) => reduction: ",
272                                 op->frames_filtered, op->frames_abs);
273
274                 reduction = 100 - (op->frames_filtered * 100) / op->frames_abs;
275
276                 len += snprintf(page + len, PAGE_SIZE - len, "%s%ld%%\n",
277                                 (reduction == 100)?"near ":"", reduction);
278
279                 if (len > PAGE_SIZE - 200) {
280                         /* mark output cut off */
281                         len += snprintf(page + len, PAGE_SIZE - len, "(..)\n");
282                         break;
283                 }
284         }
285
286         list_for_each_entry(op, &bo->tx_ops, list) {
287
288                 len += snprintf(page + len, PAGE_SIZE - len,
289                                 "tx_op: %03X %s [%d] ",
290                                 op->can_id, bcm_proc_getifname(op->ifindex),
291                                 op->nframes);
292                 if (op->j_ival1)
293                         len += snprintf(page + len, PAGE_SIZE - len, "t1=%ld ",
294                                         op->j_ival1);
295
296                 if (op->j_ival2)
297                         len += snprintf(page + len, PAGE_SIZE - len, "t2=%ld ",
298                                         op->j_ival2);
299
300                 len += snprintf(page + len, PAGE_SIZE - len, "# sent %ld\n",
301                                 op->frames_abs);
302
303                 if (len > PAGE_SIZE - 100) {
304                         /* mark output cut off */
305                         len += snprintf(page + len, PAGE_SIZE - len, "(..)\n");
306                         break;
307                 }
308         }
309
310         len += snprintf(page + len, PAGE_SIZE - len, "\n");
311
312         *eof = 1;
313         return len;
314 }
315
316 /*
317  * bcm_can_tx - send the (next) CAN frame to the appropriate CAN interface
318  *              of the given bcm tx op
319  */
320 static void bcm_can_tx(struct bcm_op *op)
321 {
322         struct sk_buff *skb;
323         struct net_device *dev;
324         struct can_frame *cf = &op->frames[op->currframe];
325
326         DBG_FRAME("BCM: bcm_can_tx: sending frame", cf);
327
328         /* no target device? => exit */
329         if (!op->ifindex)
330                 return;
331
332         dev = dev_get_by_index(op->ifindex);
333
334         if (!dev) {
335                 /* RFC: should this bcm_op remove itself here? */
336                 return;
337         }
338
339         skb = alloc_skb(CFSIZ,
340                         in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
341
342         if (!skb)
343                 goto out;
344
345         memcpy(skb_put(skb, CFSIZ), cf, CFSIZ);
346
347         /* send with loopback */
348         skb->dev = dev;
349         skb->sk = op->sk;
350         can_send(skb, 1);
351
352         /* update statistics */
353         op->currframe++;
354         op->frames_abs++;
355
356         /* reached last frame? */
357         if (op->currframe >= op->nframes)
358                 op->currframe = 0;
359  out:
360         dev_put(dev);
361 }
362
363 /*
364  * bcm_send_to_user - send a BCM message to the userspace
365  *                    (consisting of bcm_msg_head + x CAN frames)
366  */
367 static void bcm_send_to_user(struct bcm_op *op, struct bcm_msg_head *head,
368                              struct can_frame *frames, int has_timestamp)
369 {
370         struct sk_buff *skb;
371         struct can_frame *firstframe;
372         struct sock *sk = op->sk;
373         int datalen = head->nframes * CFSIZ;
374         int err;
375
376         skb = alloc_skb(sizeof(*head) + datalen,
377                         in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
378         if (!skb)
379                 return;
380
381         memcpy(skb_put(skb, sizeof(*head)), head, sizeof(*head));
382
383         /* can_frames starting here */
384         firstframe = (struct can_frame *) skb->tail;
385
386
387         if (has_timestamp) {
388                 /* restore rx timestamp */
389 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22)
390                 skb->tstamp = op->rx_stamp;
391 #else
392                 skb_set_timestamp(skb, &op->rx_stamp);
393 #endif
394         }
395
396         /* restore originator for recvfrom() */
397 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
398         skb->iif = op->rx_ifindex;
399 #else
400         skb->input_dev = dev_get_by_index(op->rx_ifindex);
401         if (skb->input_dev)
402                 dev_put(skb->input_dev);
403 #endif
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_sock *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_sock *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_sock *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_sock *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_sock *bo = container_of(nb, struct bcm_sock, notifier);
1504 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
1505         struct sock *sk = &bo->sk;
1506 #else
1507         struct sock *sk = bo->sk;
1508 #endif
1509         struct bcm_op *op;
1510         int notify_enodev = 0;
1511
1512         DBG("msg %ld for dev %p (%s idx %d) sk %p bo->ifindex %d\n",
1513             msg, dev, dev->name, dev->ifindex, sk, bo->ifindex);
1514
1515         if (dev->type != ARPHRD_CAN)
1516                 return NOTIFY_DONE;
1517
1518         switch (msg) {
1519
1520         case NETDEV_UNREGISTER:
1521                 lock_sock(sk);
1522
1523                 /* remove device specific receive entries */
1524                 list_for_each_entry(op, &bo->rx_ops, list)
1525                         if (op->rx_reg_dev == dev)
1526                                 bcm_rx_unreg(dev, op);
1527
1528                 /* remove device reference, if this is our bound device */
1529                 if (bo->bound && bo->ifindex == dev->ifindex) {
1530                         bo->bound   = 0;
1531                         bo->ifindex = 0;
1532                         notify_enodev = 1;
1533                 }
1534
1535                 release_sock(sk);
1536
1537                 if (notify_enodev) {
1538                         sk->sk_err = ENODEV;
1539                         if (!sock_flag(sk, SOCK_DEAD))
1540                                 sk->sk_error_report(sk);
1541                 }
1542                 break;
1543
1544         case NETDEV_DOWN:
1545                 if (bo->bound && bo->ifindex == dev->ifindex) {
1546                         sk->sk_err = ENETDOWN;
1547                         if (!sock_flag(sk, SOCK_DEAD))
1548                                 sk->sk_error_report(sk);
1549                 }
1550         }
1551
1552         return NOTIFY_DONE;
1553 }
1554
1555 /*
1556  * initial settings for all BCM sockets to be set at socket creation time
1557  */
1558 static int bcm_init(struct sock *sk)
1559 {
1560         struct bcm_sock *bo = bcm_sk(sk);
1561
1562 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,12)
1563         bo->sk               = sk;
1564 #endif
1565         bo->bound            = 0;
1566         bo->ifindex          = 0;
1567         bo->dropped_usr_msgs = 0;
1568         bo->bcm_proc_read    = NULL;
1569
1570         INIT_LIST_HEAD(&bo->tx_ops);
1571         INIT_LIST_HEAD(&bo->rx_ops);
1572
1573         /* set notifier */
1574         bo->notifier.notifier_call = bcm_notifier;
1575
1576         register_netdevice_notifier(&bo->notifier);
1577
1578         return 0;
1579 }
1580
1581 /*
1582  * standard socket functions
1583  */
1584 static int bcm_release(struct socket *sock)
1585 {
1586         struct sock *sk = sock->sk;
1587         struct bcm_sock *bo = bcm_sk(sk);
1588         struct bcm_op *op, *next;
1589
1590         DBG("socket %p, sk %p\n", sock, sk);
1591
1592         /* remove bcm_ops, timer, rx_unregister(), etc. */
1593
1594         unregister_netdevice_notifier(&bo->notifier);
1595
1596         lock_sock(sk);
1597
1598         list_for_each_entry_safe(op, next, &bo->tx_ops, list) {
1599                 DBG("removing tx_op %p for can_id %03X\n", op, op->can_id);
1600                 bcm_remove_op(op);
1601         }
1602
1603         list_for_each_entry_safe(op, next, &bo->rx_ops, list) {
1604                 DBG("removing rx_op %p for can_id %03X\n", op, op->can_id);
1605
1606                 /*
1607                  * Don't care if we're bound or not (due to netdev problems)
1608                  * can_rx_unregister() is always a save thing to do here.
1609                  */
1610                 if (op->ifindex) {
1611                         /*
1612                          * Only remove subscriptions that had not
1613                          * been removed due to NETDEV_UNREGISTER
1614                          * in bcm_notifier()
1615                          */
1616                         if (op->rx_reg_dev) {
1617                                 struct net_device *dev;
1618
1619                                 dev = dev_get_by_index(op->ifindex);
1620                                 if (dev) {
1621                                         bcm_rx_unreg(dev, op);
1622                                         dev_put(dev);
1623                                 }
1624                         }
1625                 } else
1626                         can_rx_unregister(NULL, op->can_id,
1627                                           REGMASK(op->can_id),
1628                                           bcm_rx_handler, op);
1629
1630                 bcm_remove_op(op);
1631         }
1632
1633         /* remove procfs entry */
1634         if (proc_dir && bo->bcm_proc_read)
1635                 remove_proc_entry(bo->procname, proc_dir);
1636
1637         /* remove device reference */
1638         if (bo->bound) {
1639                 bo->bound   = 0;
1640                 bo->ifindex = 0;
1641         }
1642
1643         release_sock(sk);
1644         sock_put(sk);
1645
1646         return 0;
1647 }
1648
1649 static int bcm_connect(struct socket *sock, struct sockaddr *uaddr, int len,
1650                        int flags)
1651 {
1652         struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1653         struct sock *sk = sock->sk;
1654         struct bcm_sock *bo = bcm_sk(sk);
1655
1656         if (bo->bound)
1657                 return -EISCONN;
1658
1659         /* bind a device to this socket */
1660         if (addr->can_ifindex) {
1661                 struct net_device *dev = dev_get_by_index(addr->can_ifindex);
1662
1663                 if (!dev) {
1664                         DBG("could not find device index %d\n",
1665                             addr->can_ifindex);
1666                         return -ENODEV;
1667                 }
1668
1669                 if (dev->type != ARPHRD_CAN) {
1670                         DBG("device %d no CAN device\n", addr->can_ifindex);
1671                         dev_put(dev);
1672                         return -ENODEV;
1673                 }
1674
1675                 bo->ifindex = dev->ifindex;
1676                 dev_put(dev);
1677
1678                 DBG("socket %p bound to device %s (idx %d)\n",
1679                     sock, dev->name, dev->ifindex);
1680
1681         } else {
1682                 /* no interface reference for ifindex = 0 ('any' CAN device) */
1683                 bo->ifindex = 0;
1684         }
1685
1686         bo->bound = 1;
1687
1688         if (proc_dir) {
1689                 /* unique socket address as filename */
1690                 sprintf(bo->procname, "%p", sock);
1691                 bo->bcm_proc_read = create_proc_read_entry(bo->procname, 0644,
1692                                                            proc_dir,
1693                                                            bcm_read_proc, sk);
1694         }
1695
1696         return 0;
1697 }
1698
1699 static int bcm_recvmsg(struct kiocb *iocb, struct socket *sock,
1700                        struct msghdr *msg, size_t size, int flags)
1701 {
1702         struct sock *sk = sock->sk;
1703         struct sk_buff *skb;
1704         int error = 0;
1705         int noblock;
1706         int err;
1707
1708         DBG("socket %p, sk %p\n", sock, sk);
1709
1710         noblock =  flags & MSG_DONTWAIT;
1711         flags   &= ~MSG_DONTWAIT;
1712         skb = skb_recv_datagram(sk, flags, noblock, &error);
1713         if (!skb)
1714                 return error;
1715
1716         DBG("delivering skbuff %p\n", skb);
1717         DBG_SKB(skb);
1718
1719         if (skb->len < size)
1720                 size = skb->len;
1721
1722         err = memcpy_toiovec(msg->msg_iov, skb->data, size);
1723         if (err < 0) {
1724                 skb_free_datagram(sk, skb);
1725                 return err;
1726         }
1727
1728         sock_recv_timestamp(msg, sk, skb);
1729
1730         if (msg->msg_name) {
1731                 struct sockaddr_can *addr = msg->msg_name;
1732                 msg->msg_namelen = sizeof(*addr);
1733                 memset(addr, 0, sizeof(*addr));
1734                 addr->can_family  = AF_CAN;
1735 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,21)
1736                 addr->can_ifindex = skb->iif;
1737 #else
1738                 /*
1739                  * FIXME: Race condition, skb->input_dev might disappear
1740                  *        while skb is waiting on the queue.
1741                  */
1742                 if (skb->input_dev)
1743                         addr->can_ifindex = skb->input_dev->ifindex;
1744                 else
1745                         addr->can_ifindex = 0;
1746 #endif
1747         }
1748
1749         DBG("freeing sock %p, skbuff %p\n", sk, skb);
1750         skb_free_datagram(sk, skb);
1751
1752         return size;
1753 }
1754
1755 static unsigned int bcm_poll(struct file *file, struct socket *sock,
1756                              poll_table *wait)
1757 {
1758         unsigned int mask = 0;
1759
1760         DBG("socket %p\n", sock);
1761
1762         mask = datagram_poll(file, sock, wait);
1763         return mask;
1764 }
1765
1766 static struct proto_ops bcm_ops = {
1767         .family        = PF_CAN,
1768         .release       = bcm_release,
1769         .bind          = sock_no_bind,
1770         .connect       = bcm_connect,
1771         .socketpair    = sock_no_socketpair,
1772         .accept        = sock_no_accept,
1773         .getname       = sock_no_getname,
1774         .poll          = bcm_poll,
1775         .ioctl         = NULL,          /* use can_ioctl() from af_can.c */
1776         .listen        = sock_no_listen,
1777         .shutdown      = sock_no_shutdown,
1778         .setsockopt    = sock_no_setsockopt,
1779         .getsockopt    = sock_no_getsockopt,
1780         .sendmsg       = bcm_sendmsg,
1781         .recvmsg       = bcm_recvmsg,
1782         .mmap          = sock_no_mmap,
1783         .sendpage      = sock_no_sendpage,
1784 };
1785
1786 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)
1787 static struct proto bcm_proto = {
1788         .name       = "CAN_BCM",
1789         .owner      = THIS_MODULE,
1790         .obj_size   = sizeof(struct bcm_sock),
1791         .init       = bcm_init,
1792 };
1793
1794 static struct can_proto bcm_can_proto = {
1795         .type       = SOCK_DGRAM,
1796         .protocol   = CAN_BCM,
1797         .capability = BCM_CAP,
1798         .ops        = &bcm_ops,
1799         .prot       = &bcm_proto,
1800 };
1801 #else
1802 static struct can_proto bcm_can_proto = {
1803         .type       = SOCK_DGRAM,
1804         .protocol   = CAN_BCM,
1805         .capability = BCM_CAP,
1806         .ops        = &bcm_ops,
1807         .owner      = THIS_MODULE,
1808         .obj_size   = sizeof(struct bcm_sock),
1809         .init       = bcm_init,
1810 };
1811 #endif
1812
1813 static int __init bcm_module_init(void)
1814 {
1815         printk(banner);
1816
1817         can_proto_register(&bcm_can_proto);
1818
1819         /* create /proc/net/can/bcm directory */
1820         proc_dir = proc_mkdir(CAN_PROC_DIR"/"IDENT, NULL);
1821
1822         if (proc_dir)
1823                 proc_dir->owner = THIS_MODULE;
1824
1825         return 0;
1826 }
1827
1828 static void __exit bcm_module_exit(void)
1829 {
1830         can_proto_unregister(&bcm_can_proto);
1831
1832         if (proc_dir)
1833                 remove_proc_entry(CAN_PROC_DIR"/"IDENT, NULL);
1834 }
1835
1836 module_init(bcm_module_init);
1837 module_exit(bcm_module_exit);