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