]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/net/can/bcm.c
The commit aabdcb0b553b9c9547b1a506b34d55a764745870 ("can bcm: fix tx_setup
[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_start_timer(struct bcm_op *op)
464 {
465         if (op->kt_ival1.tv64 && op->count)
466                 hrtimer_start(&op->timer,
467                               ktime_add(ktime_get(), op->kt_ival1),
468                               HRTIMER_MODE_ABS);
469         else if (op->kt_ival2.tv64)
470                 hrtimer_start(&op->timer,
471                               ktime_add(ktime_get(), op->kt_ival2),
472                               HRTIMER_MODE_ABS);
473 }
474
475 static void bcm_tx_timeout_tsklet(unsigned long data)
476 {
477         struct bcm_op *op = (struct bcm_op *)data;
478         struct bcm_msg_head msg_head;
479
480         if (op->kt_ival1.tv64 && (op->count > 0)) {
481
482                 op->count--;
483                 if (!op->count && (op->flags & TX_COUNTEVT)) {
484
485                         /* create notification to user */
486                         msg_head.opcode  = TX_EXPIRED;
487                         msg_head.flags   = op->flags;
488                         msg_head.count   = op->count;
489                         msg_head.ival1   = op->ival1;
490                         msg_head.ival2   = op->ival2;
491                         msg_head.can_id  = op->can_id;
492                         msg_head.nframes = 0;
493
494                         bcm_send_to_user(op, &msg_head, NULL, 0);
495                 }
496                 bcm_can_tx(op);
497
498         } else if (op->kt_ival2.tv64)
499                 bcm_can_tx(op);
500
501         bcm_tx_start_timer(op);
502 }
503
504 /*
505  * bcm_tx_timeout_handler - performs cyclic CAN frame transmissions
506  */
507 static enum hrtimer_restart bcm_tx_timeout_handler(struct hrtimer *hrtimer)
508 {
509         struct bcm_op *op = container_of(hrtimer, struct bcm_op, timer);
510
511         tasklet_schedule(&op->tsklet);
512
513         return HRTIMER_NORESTART;
514 }
515
516 /*
517  * bcm_rx_changed - create a RX_CHANGED notification due to changed content
518  */
519 static void bcm_rx_changed(struct bcm_op *op, struct can_frame *data)
520 {
521         struct bcm_msg_head head;
522
523         /* update statistics */
524         op->frames_filtered++;
525
526         /* prevent statistics overflow */
527         if (op->frames_filtered > ULONG_MAX/100)
528                 op->frames_filtered = op->frames_abs = 0;
529
530         /* this element is not throttled anymore */
531         data->can_dlc &= (BCM_CAN_DLC_MASK|RX_RECV);
532
533         head.opcode  = RX_CHANGED;
534         head.flags   = op->flags;
535         head.count   = op->count;
536         head.ival1   = op->ival1;
537         head.ival2   = op->ival2;
538         head.can_id  = op->can_id;
539         head.nframes = 1;
540
541         bcm_send_to_user(op, &head, data, 1);
542 }
543
544 #if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,25)
545 /* is part of linux/hrtimer.h since 2.6.26 */
546 static inline int hrtimer_callback_running(struct hrtimer *timer)
547 {
548         return timer->state & HRTIMER_STATE_CALLBACK;
549 }
550 #endif
551 #if LINUX_VERSION_CODE == KERNEL_VERSION(2,6,22)
552 static inline s64 ktime_us_delta(const ktime_t later, const ktime_t earlier)
553 {
554         return ktime_to_us(ktime_sub(later, earlier));
555 }
556 #endif
557 /*
558  * bcm_rx_update_and_send - process a detected relevant receive content change
559  *                          1. update the last received data
560  *                          2. send a notification to the user (if possible)
561  */
562 static void bcm_rx_update_and_send(struct bcm_op *op,
563                                    struct can_frame *lastdata,
564                                    const struct can_frame *rxdata)
565 {
566         memcpy(lastdata, rxdata, CFSIZ);
567
568         /* mark as used and throttled by default */
569         lastdata->can_dlc |= (RX_RECV|RX_THR);
570
571         /* throtteling mode inactive ? */
572         if (!op->kt_ival2.tv64) {
573                 /* send RX_CHANGED to the user immediately */
574                 bcm_rx_changed(op, lastdata);
575                 return;
576         }
577
578         /* with active throttling timer we are just done here */
579         if (hrtimer_active(&op->thrtimer))
580                 return;
581
582         /* first receiption with enabled throttling mode */
583         if (!op->kt_lastmsg.tv64)
584                 goto rx_changed_settime;
585
586         /* got a second frame inside a potential throttle period? */
587         if (ktime_us_delta(ktime_get(), op->kt_lastmsg) <
588             ktime_to_us(op->kt_ival2)) {
589                 /* do not send the saved data - only start throttle timer */
590                 hrtimer_start(&op->thrtimer,
591                               ktime_add(op->kt_lastmsg, op->kt_ival2),
592                               HRTIMER_MODE_ABS);
593                 return;
594         }
595
596         /* the gap was that big, that throttling was not needed here */
597 rx_changed_settime:
598         bcm_rx_changed(op, lastdata);
599         op->kt_lastmsg = ktime_get();
600 }
601
602 /*
603  * bcm_rx_cmp_to_index - (bit)compares the currently received data to formerly
604  *                       received data stored in op->last_frames[]
605  */
606 static void bcm_rx_cmp_to_index(struct bcm_op *op, unsigned int index,
607                                 const struct can_frame *rxdata)
608 {
609         /*
610          * no one uses the MSBs of can_dlc for comparation,
611          * so we use it here to detect the first time of reception
612          */
613
614         if (!(op->last_frames[index].can_dlc & RX_RECV)) {
615                 /* received data for the first time => send update to user */
616                 bcm_rx_update_and_send(op, &op->last_frames[index], rxdata);
617                 return;
618         }
619
620         /* do a real check in can_frame data section */
621
622         if ((GET_U64(&op->frames[index]) & GET_U64(rxdata)) !=
623             (GET_U64(&op->frames[index]) & GET_U64(&op->last_frames[index]))) {
624                 bcm_rx_update_and_send(op, &op->last_frames[index], rxdata);
625                 return;
626         }
627
628         if (op->flags & RX_CHECK_DLC) {
629                 /* do a real check in can_frame dlc */
630                 if (rxdata->can_dlc != (op->last_frames[index].can_dlc &
631                                         BCM_CAN_DLC_MASK)) {
632                         bcm_rx_update_and_send(op, &op->last_frames[index],
633                                                rxdata);
634                         return;
635                 }
636         }
637 }
638
639 /*
640  * bcm_rx_starttimer - enable timeout monitoring for CAN frame receiption
641  */
642 static void bcm_rx_starttimer(struct bcm_op *op)
643 {
644         if (op->flags & RX_NO_AUTOTIMER)
645                 return;
646
647         if (op->kt_ival1.tv64)
648                 hrtimer_start(&op->timer, op->kt_ival1, HRTIMER_MODE_REL);
649 }
650
651 static void bcm_rx_timeout_tsklet(unsigned long data)
652 {
653         struct bcm_op *op = (struct bcm_op *)data;
654         struct bcm_msg_head msg_head;
655
656         /* create notification to user */
657         msg_head.opcode  = RX_TIMEOUT;
658         msg_head.flags   = op->flags;
659         msg_head.count   = op->count;
660         msg_head.ival1   = op->ival1;
661         msg_head.ival2   = op->ival2;
662         msg_head.can_id  = op->can_id;
663         msg_head.nframes = 0;
664
665         bcm_send_to_user(op, &msg_head, NULL, 0);
666 }
667
668 /*
669  * bcm_rx_timeout_handler - when the (cyclic) CAN frame receiption timed out
670  */
671 static enum hrtimer_restart bcm_rx_timeout_handler(struct hrtimer *hrtimer)
672 {
673         struct bcm_op *op = container_of(hrtimer, struct bcm_op, timer);
674
675         /* schedule before NET_RX_SOFTIRQ */
676         tasklet_hi_schedule(&op->tsklet);
677
678         /* no restart of the timer is done here! */
679
680         /* if user wants to be informed, when cyclic CAN-Messages come back */
681         if ((op->flags & RX_ANNOUNCE_RESUME) && op->last_frames) {
682                 /* clear received can_frames to indicate 'nothing received' */
683                 memset(op->last_frames, 0, op->nframes * CFSIZ);
684         }
685
686         return HRTIMER_NORESTART;
687 }
688
689 /*
690  * bcm_rx_do_flush - helper for bcm_rx_thr_flush
691  */
692 static inline int bcm_rx_do_flush(struct bcm_op *op, int update,
693                                   unsigned int index)
694 {
695         if ((op->last_frames) && (op->last_frames[index].can_dlc & RX_THR)) {
696                 if (update)
697                         bcm_rx_changed(op, &op->last_frames[index]);
698                 return 1;
699         }
700         return 0;
701 }
702
703 /*
704  * bcm_rx_thr_flush - Check for throttled data and send it to the userspace
705  *
706  * update == 0 : just check if throttled data is available  (any irq context)
707  * update == 1 : check and send throttled data to userspace (soft_irq context)
708  */
709 static int bcm_rx_thr_flush(struct bcm_op *op, int update)
710 {
711         int updated = 0;
712
713         if (op->nframes > 1) {
714                 unsigned int i;
715
716                 /* for MUX filter we start at index 1 */
717                 for (i = 1; i < op->nframes; i++)
718                         updated += bcm_rx_do_flush(op, update, i);
719
720         } else {
721                 /* for RX_FILTER_ID and simple filter */
722                 updated += bcm_rx_do_flush(op, update, 0);
723         }
724
725         return updated;
726 }
727
728 static void bcm_rx_thr_tsklet(unsigned long data)
729 {
730         struct bcm_op *op = (struct bcm_op *)data;
731
732         /* push the changed data to the userspace */
733         bcm_rx_thr_flush(op, 1);
734 }
735
736 /*
737  * bcm_rx_thr_handler - the time for blocked content updates is over now:
738  *                      Check for throttled data and send it to the userspace
739  */
740 static enum hrtimer_restart bcm_rx_thr_handler(struct hrtimer *hrtimer)
741 {
742         struct bcm_op *op = container_of(hrtimer, struct bcm_op, thrtimer);
743
744         tasklet_schedule(&op->thrtsklet);
745
746         if (bcm_rx_thr_flush(op, 0)) {
747                 hrtimer_forward(hrtimer, ktime_get(), op->kt_ival2);
748                 return HRTIMER_RESTART;
749         } else {
750                 /* rearm throttle handling */
751                 op->kt_lastmsg = ktime_set(0, 0);
752                 return HRTIMER_NORESTART;
753         }
754 }
755
756 /*
757  * bcm_rx_handler - handle a CAN frame receiption
758  */
759 static void bcm_rx_handler(struct sk_buff *skb, void *data)
760 {
761         struct bcm_op *op = (struct bcm_op *)data;
762         const struct can_frame *rxframe = (struct can_frame *)skb->data;
763         unsigned int i;
764
765         /* disable timeout */
766         hrtimer_cancel(&op->timer);
767
768         if (op->can_id != rxframe->can_id)
769                 return;
770
771         /* save rx timestamp */
772         op->rx_stamp = skb->tstamp;
773         /* save originator for recvfrom() */
774         op->rx_ifindex = skb->dev->ifindex;
775         /* update statistics */
776         op->frames_abs++;
777
778         if (op->flags & RX_RTR_FRAME) {
779                 /* send reply for RTR-request (placed in op->frames[0]) */
780                 bcm_can_tx(op);
781                 return;
782         }
783
784         if (op->flags & RX_FILTER_ID) {
785                 /* the easiest case */
786                 bcm_rx_update_and_send(op, &op->last_frames[0], rxframe);
787                 goto rx_starttimer;
788         }
789
790         if (op->nframes == 1) {
791                 /* simple compare with index 0 */
792                 bcm_rx_cmp_to_index(op, 0, rxframe);
793                 goto rx_starttimer;
794         }
795
796         if (op->nframes > 1) {
797                 /*
798                  * multiplex compare
799                  *
800                  * find the first multiplex mask that fits.
801                  * Remark: The MUX-mask is stored in index 0
802                  */
803
804                 for (i = 1; i < op->nframes; i++) {
805                         if ((GET_U64(&op->frames[0]) & GET_U64(rxframe)) ==
806                             (GET_U64(&op->frames[0]) &
807                              GET_U64(&op->frames[i]))) {
808                                 bcm_rx_cmp_to_index(op, i, rxframe);
809                                 break;
810                         }
811                 }
812         }
813
814 rx_starttimer:
815         bcm_rx_starttimer(op);
816 }
817
818 /*
819  * helpers for bcm_op handling: find & delete bcm [rx|tx] op elements
820  */
821 static struct bcm_op *bcm_find_op(struct list_head *ops, canid_t can_id,
822                                   int ifindex)
823 {
824         struct bcm_op *op;
825
826         list_for_each_entry(op, ops, list) {
827                 if ((op->can_id == can_id) && (op->ifindex == ifindex))
828                         return op;
829         }
830
831         return NULL;
832 }
833
834 static void bcm_remove_op(struct bcm_op *op)
835 {
836         hrtimer_cancel(&op->timer);
837         hrtimer_cancel(&op->thrtimer);
838
839         if (op->tsklet.func)
840                 tasklet_kill(&op->tsklet);
841
842         if (op->thrtsklet.func)
843                 tasklet_kill(&op->thrtsklet);
844
845         if ((op->frames) && (op->frames != &op->sframe))
846                 kfree(op->frames);
847
848         if ((op->last_frames) && (op->last_frames != &op->last_sframe))
849                 kfree(op->last_frames);
850
851         kfree(op);
852
853         return;
854 }
855
856 static void bcm_rx_unreg(struct net_device *dev, struct bcm_op *op)
857 {
858         if (op->rx_reg_dev == dev) {
859                 can_rx_unregister(dev, op->can_id, REGMASK(op->can_id),
860                                   bcm_rx_handler, op);
861
862                 /* mark as removed subscription */
863                 op->rx_reg_dev = NULL;
864         } else
865                 printk(KERN_ERR "can-bcm: bcm_rx_unreg: registered device "
866                        "mismatch %p %p\n", op->rx_reg_dev, dev);
867 }
868
869 /*
870  * bcm_delete_rx_op - find and remove a rx op (returns number of removed ops)
871  */
872 static int bcm_delete_rx_op(struct list_head *ops, canid_t can_id, int ifindex)
873 {
874         struct bcm_op *op, *n;
875
876         list_for_each_entry_safe(op, n, ops, list) {
877                 if ((op->can_id == can_id) && (op->ifindex == ifindex)) {
878
879                         /*
880                          * Don't care if we're bound or not (due to netdev
881                          * problems) can_rx_unregister() is always a save
882                          * thing to do here.
883                          */
884                         if (op->ifindex) {
885                                 /*
886                                  * Only remove subscriptions that had not
887                                  * been removed due to NETDEV_UNREGISTER
888                                  * in bcm_notifier()
889                                  */
890                                 if (op->rx_reg_dev) {
891                                         struct net_device *dev;
892
893                                         dev = dev_get_by_index(&init_net,
894                                                                op->ifindex);
895                                         if (dev) {
896                                                 bcm_rx_unreg(dev, op);
897                                                 dev_put(dev);
898                                         }
899                                 }
900                         } else
901                                 can_rx_unregister(NULL, op->can_id,
902                                                   REGMASK(op->can_id),
903                                                   bcm_rx_handler, op);
904
905                         list_del(&op->list);
906                         bcm_remove_op(op);
907                         return 1; /* done */
908                 }
909         }
910
911         return 0; /* not found */
912 }
913
914 /*
915  * bcm_delete_tx_op - find and remove a tx op (returns number of removed ops)
916  */
917 static int bcm_delete_tx_op(struct list_head *ops, canid_t can_id, int ifindex)
918 {
919         struct bcm_op *op, *n;
920
921         list_for_each_entry_safe(op, n, ops, list) {
922                 if ((op->can_id == can_id) && (op->ifindex == ifindex)) {
923                         list_del(&op->list);
924                         bcm_remove_op(op);
925                         return 1; /* done */
926                 }
927         }
928
929         return 0; /* not found */
930 }
931
932 /*
933  * bcm_read_op - read out a bcm_op and send it to the user (for bcm_sendmsg)
934  */
935 static int bcm_read_op(struct list_head *ops, struct bcm_msg_head *msg_head,
936                        int ifindex)
937 {
938         struct bcm_op *op = bcm_find_op(ops, msg_head->can_id, ifindex);
939
940         if (!op)
941                 return -EINVAL;
942
943         /* put current values into msg_head */
944         msg_head->flags   = op->flags;
945         msg_head->count   = op->count;
946         msg_head->ival1   = op->ival1;
947         msg_head->ival2   = op->ival2;
948         msg_head->nframes = op->nframes;
949
950         bcm_send_to_user(op, msg_head, op->frames, 0);
951
952         return MHSIZ;
953 }
954
955 /*
956  * bcm_tx_setup - create or update a bcm tx op (for bcm_sendmsg)
957  */
958 static int bcm_tx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
959                         int ifindex, struct sock *sk)
960 {
961         struct bcm_sock *bo = bcm_sk(sk);
962         struct bcm_op *op;
963         unsigned int i;
964         int err;
965
966         /* we need a real device to send frames */
967         if (!ifindex)
968                 return -ENODEV;
969
970         /* check nframes boundaries - we need at least one can_frame */
971         if (msg_head->nframes < 1 || msg_head->nframes > MAX_NFRAMES)
972                 return -EINVAL;
973
974         /* check the given can_id */
975         op = bcm_find_op(&bo->tx_ops, msg_head->can_id, ifindex);
976
977         if (op) {
978                 /* update existing BCM operation */
979
980                 /*
981                  * Do we need more space for the can_frames than currently
982                  * allocated? -> This is a _really_ unusual use-case and
983                  * therefore (complexity / locking) it is not supported.
984                  */
985                 if (msg_head->nframes > op->nframes)
986                         return -E2BIG;
987
988                 /* update can_frames content */
989                 for (i = 0; i < msg_head->nframes; i++) {
990                         err = memcpy_fromiovec((u8 *)&op->frames[i],
991                                                msg->msg_iov, CFSIZ);
992
993                         if (op->frames[i].can_dlc > 8)
994                                 err = -EINVAL;
995
996                         if (err < 0)
997                                 return err;
998
999                         if (msg_head->flags & TX_CP_CAN_ID) {
1000                                 /* copy can_id into frame */
1001                                 op->frames[i].can_id = msg_head->can_id;
1002                         }
1003                 }
1004
1005         } else {
1006                 /* insert new BCM operation for the given can_id */
1007
1008                 op = kzalloc(OPSIZ, GFP_KERNEL);
1009                 if (!op)
1010                         return -ENOMEM;
1011
1012                 op->can_id    = msg_head->can_id;
1013
1014                 /* create array for can_frames and copy the data */
1015                 if (msg_head->nframes > 1) {
1016                         op->frames = kmalloc(msg_head->nframes * CFSIZ,
1017                                              GFP_KERNEL);
1018                         if (!op->frames) {
1019                                 kfree(op);
1020                                 return -ENOMEM;
1021                         }
1022                 } else
1023                         op->frames = &op->sframe;
1024
1025                 for (i = 0; i < msg_head->nframes; i++) {
1026                         err = memcpy_fromiovec((u8 *)&op->frames[i],
1027                                                msg->msg_iov, CFSIZ);
1028
1029                         if (op->frames[i].can_dlc > 8)
1030                                 err = -EINVAL;
1031
1032                         if (err < 0) {
1033                                 if (op->frames != &op->sframe)
1034                                         kfree(op->frames);
1035                                 kfree(op);
1036                                 return err;
1037                         }
1038
1039                         if (msg_head->flags & TX_CP_CAN_ID) {
1040                                 /* copy can_id into frame */
1041                                 op->frames[i].can_id = msg_head->can_id;
1042                         }
1043                 }
1044
1045                 /* tx_ops never compare with previous received messages */
1046                 op->last_frames = NULL;
1047
1048                 /* bcm_can_tx / bcm_tx_timeout_handler needs this */
1049                 op->sk = sk;
1050                 op->ifindex = ifindex;
1051
1052                 /* initialize uninitialized (kzalloc) structure */
1053                 hrtimer_init(&op->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1054                 op->timer.function = bcm_tx_timeout_handler;
1055
1056                 /* initialize tasklet for tx countevent notification */
1057                 tasklet_init(&op->tsklet, bcm_tx_timeout_tsklet,
1058                              (unsigned long) op);
1059
1060                 /* currently unused in tx_ops */
1061                 hrtimer_init(&op->thrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1062
1063                 /* add this bcm_op to the list of the tx_ops */
1064                 list_add(&op->list, &bo->tx_ops);
1065
1066         } /* if ((op = bcm_find_op(&bo->tx_ops, msg_head->can_id, ifindex))) */
1067
1068         if (op->nframes != msg_head->nframes) {
1069                 op->nframes   = msg_head->nframes;
1070                 /* start multiple frame transmission with index 0 */
1071                 op->currframe = 0;
1072         }
1073
1074         /* check flags */
1075
1076         op->flags = msg_head->flags;
1077
1078         if (op->flags & TX_RESET_MULTI_IDX) {
1079                 /* start multiple frame transmission with index 0 */
1080                 op->currframe = 0;
1081         }
1082
1083         if (op->flags & SETTIMER) {
1084                 /* set timer values */
1085                 op->count = msg_head->count;
1086                 op->ival1 = msg_head->ival1;
1087                 op->ival2 = msg_head->ival2;
1088                 op->kt_ival1 = timeval_to_ktime(msg_head->ival1);
1089                 op->kt_ival2 = timeval_to_ktime(msg_head->ival2);
1090
1091                 /* disable an active timer due to zero values? */
1092                 if (!op->kt_ival1.tv64 && !op->kt_ival2.tv64)
1093                         hrtimer_cancel(&op->timer);
1094         }
1095
1096         if (op->flags & STARTTIMER) {
1097                 hrtimer_cancel(&op->timer);
1098                 /* spec: send can_frame when starting timer */
1099                 op->flags |= TX_ANNOUNCE;
1100         }
1101
1102         if (op->flags & TX_ANNOUNCE) {
1103                 bcm_can_tx(op);
1104                 if (op->count)
1105                         op->count--;
1106         }
1107
1108         if (op->flags & STARTTIMER)
1109                 bcm_tx_start_timer(op);
1110
1111         return msg_head->nframes * CFSIZ + MHSIZ;
1112 }
1113
1114 /*
1115  * bcm_rx_setup - create or update a bcm rx op (for bcm_sendmsg)
1116  */
1117 static int bcm_rx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
1118                         int ifindex, struct sock *sk)
1119 {
1120         struct bcm_sock *bo = bcm_sk(sk);
1121         struct bcm_op *op;
1122         int do_rx_register;
1123         int err = 0;
1124
1125         if ((msg_head->flags & RX_FILTER_ID) || (!(msg_head->nframes))) {
1126                 /* be robust against wrong usage ... */
1127                 msg_head->flags |= RX_FILTER_ID;
1128                 /* ignore trailing garbage */
1129                 msg_head->nframes = 0;
1130         }
1131
1132         /* the first element contains the mux-mask => MAX_NFRAMES + 1  */
1133         if (msg_head->nframes > MAX_NFRAMES + 1)
1134                 return -EINVAL;
1135
1136         if ((msg_head->flags & RX_RTR_FRAME) &&
1137             ((msg_head->nframes != 1) ||
1138              (!(msg_head->can_id & CAN_RTR_FLAG))))
1139                 return -EINVAL;
1140
1141         /* check the given can_id */
1142         op = bcm_find_op(&bo->rx_ops, msg_head->can_id, ifindex);
1143         if (op) {
1144                 /* update existing BCM operation */
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                 op = kzalloc(OPSIZ, GFP_KERNEL);
1174                 if (!op)
1175                         return -ENOMEM;
1176
1177                 op->can_id    = msg_head->can_id;
1178                 op->nframes   = msg_head->nframes;
1179
1180                 if (msg_head->nframes > 1) {
1181                         /* create array for can_frames and copy the data */
1182                         op->frames = kmalloc(msg_head->nframes * CFSIZ,
1183                                              GFP_KERNEL);
1184                         if (!op->frames) {
1185                                 kfree(op);
1186                                 return -ENOMEM;
1187                         }
1188
1189                         /* create and init array for received can_frames */
1190                         op->last_frames = kzalloc(msg_head->nframes * CFSIZ,
1191                                                   GFP_KERNEL);
1192                         if (!op->last_frames) {
1193                                 kfree(op->frames);
1194                                 kfree(op);
1195                                 return -ENOMEM;
1196                         }
1197
1198                 } else {
1199                         op->frames = &op->sframe;
1200                         op->last_frames = &op->last_sframe;
1201                 }
1202
1203                 if (msg_head->nframes) {
1204                         err = memcpy_fromiovec((u8 *)op->frames, msg->msg_iov,
1205                                                msg_head->nframes * CFSIZ);
1206                         if (err < 0) {
1207                                 if (op->frames != &op->sframe)
1208                                         kfree(op->frames);
1209                                 if (op->last_frames != &op->last_sframe)
1210                                         kfree(op->last_frames);
1211                                 kfree(op);
1212                                 return err;
1213                         }
1214                 }
1215
1216                 /* bcm_can_tx / bcm_tx_timeout_handler needs this */
1217                 op->sk = sk;
1218                 op->ifindex = ifindex;
1219
1220                 /* initialize uninitialized (kzalloc) structure */
1221                 hrtimer_init(&op->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1222                 op->timer.function = bcm_rx_timeout_handler;
1223
1224                 /* initialize tasklet for rx timeout notification */
1225                 tasklet_init(&op->tsklet, bcm_rx_timeout_tsklet,
1226                              (unsigned long) op);
1227
1228                 hrtimer_init(&op->thrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1229                 op->thrtimer.function = bcm_rx_thr_handler;
1230
1231                 /* initialize tasklet for rx throttle handling */
1232                 tasklet_init(&op->thrtsklet, bcm_rx_thr_tsklet,
1233                              (unsigned long) op);
1234
1235                 /* add this bcm_op to the list of the rx_ops */
1236                 list_add(&op->list, &bo->rx_ops);
1237
1238                 /* call can_rx_register() */
1239                 do_rx_register = 1;
1240
1241         } /* if ((op = bcm_find_op(&bo->rx_ops, msg_head->can_id, ifindex))) */
1242
1243         /* check flags */
1244         op->flags = msg_head->flags;
1245
1246         if (op->flags & RX_RTR_FRAME) {
1247
1248                 /* no timers in RTR-mode */
1249                 hrtimer_cancel(&op->thrtimer);
1250                 hrtimer_cancel(&op->timer);
1251
1252                 /*
1253                  * funny feature in RX(!)_SETUP only for RTR-mode:
1254                  * copy can_id into frame BUT without RTR-flag to
1255                  * prevent a full-load-loopback-test ... ;-]
1256                  */
1257                 if ((op->flags & TX_CP_CAN_ID) ||
1258                     (op->frames[0].can_id == op->can_id))
1259                         op->frames[0].can_id = op->can_id & ~CAN_RTR_FLAG;
1260
1261         } else {
1262                 if (op->flags & SETTIMER) {
1263
1264                         /* set timer value */
1265                         op->ival1 = msg_head->ival1;
1266                         op->ival2 = msg_head->ival2;
1267                         op->kt_ival1 = timeval_to_ktime(msg_head->ival1);
1268                         op->kt_ival2 = timeval_to_ktime(msg_head->ival2);
1269
1270                         /* disable an active timer due to zero value? */
1271                         if (!op->kt_ival1.tv64)
1272                                 hrtimer_cancel(&op->timer);
1273
1274                         /*
1275                          * In any case cancel the throttle timer, flush
1276                          * potentially blocked msgs and reset throttle handling
1277                          */
1278                         op->kt_lastmsg = ktime_set(0, 0);
1279                         hrtimer_cancel(&op->thrtimer);
1280                         bcm_rx_thr_flush(op, 1);
1281                 }
1282
1283                 if ((op->flags & STARTTIMER) && op->kt_ival1.tv64)
1284                         hrtimer_start(&op->timer, op->kt_ival1,
1285                                       HRTIMER_MODE_REL);
1286         }
1287
1288         /* now we can register for can_ids, if we added a new bcm_op */
1289         if (do_rx_register) {
1290                 if (ifindex) {
1291                         struct net_device *dev;
1292
1293                         dev = dev_get_by_index(&init_net, ifindex);
1294                         if (dev) {
1295                                 err = can_rx_register(dev, op->can_id,
1296                                                       REGMASK(op->can_id),
1297                                                       bcm_rx_handler, op,
1298                                                       "bcm");
1299
1300                                 op->rx_reg_dev = dev;
1301                                 dev_put(dev);
1302                         }
1303
1304                 } else
1305                         err = can_rx_register(NULL, op->can_id,
1306                                               REGMASK(op->can_id),
1307                                               bcm_rx_handler, op, "bcm");
1308                 if (err) {
1309                         /* this bcm rx op is broken -> remove it */
1310                         list_del(&op->list);
1311                         bcm_remove_op(op);
1312                         return err;
1313                 }
1314         }
1315
1316         return msg_head->nframes * CFSIZ + MHSIZ;
1317 }
1318
1319 /*
1320  * bcm_tx_send - send a single CAN frame to the CAN interface (for bcm_sendmsg)
1321  */
1322 static int bcm_tx_send(struct msghdr *msg, int ifindex, struct sock *sk)
1323 {
1324         struct sk_buff *skb;
1325         struct net_device *dev;
1326         int err;
1327
1328         /* we need a real device to send frames */
1329         if (!ifindex)
1330                 return -ENODEV;
1331
1332         skb = alloc_skb(CFSIZ, GFP_KERNEL);
1333
1334         if (!skb)
1335                 return -ENOMEM;
1336
1337         err = memcpy_fromiovec(skb_put(skb, CFSIZ), msg->msg_iov, CFSIZ);
1338         if (err < 0) {
1339                 kfree_skb(skb);
1340                 return err;
1341         }
1342
1343         dev = dev_get_by_index(&init_net, ifindex);
1344         if (!dev) {
1345                 kfree_skb(skb);
1346                 return -ENODEV;
1347         }
1348
1349         skb->dev = dev;
1350         skb->sk  = sk;
1351         err = can_send(skb, 1); /* send with loopback */
1352         dev_put(dev);
1353
1354         if (err)
1355                 return err;
1356
1357         return CFSIZ + MHSIZ;
1358 }
1359
1360 /*
1361  * bcm_sendmsg - process BCM commands (opcodes) from the userspace
1362  */
1363 static int bcm_sendmsg(struct kiocb *iocb, struct socket *sock,
1364                        struct msghdr *msg, size_t size)
1365 {
1366         struct sock *sk = sock->sk;
1367         struct bcm_sock *bo = bcm_sk(sk);
1368         int ifindex = bo->ifindex; /* default ifindex for this bcm_op */
1369         struct bcm_msg_head msg_head;
1370         int ret; /* read bytes or error codes as return value */
1371
1372         if (!bo->bound)
1373                 return -ENOTCONN;
1374
1375         /* check for valid message length from userspace */
1376         if (size < MHSIZ || (size - MHSIZ) % CFSIZ)
1377                 return -EINVAL;
1378
1379         /* check for alternative ifindex for this bcm_op */
1380
1381         if (!ifindex && msg->msg_name) {
1382                 /* no bound device as default => check msg_name */
1383                 struct sockaddr_can *addr =
1384                         (struct sockaddr_can *)msg->msg_name;
1385
1386                 if (msg->msg_namelen < sizeof(*addr))
1387                         return -EINVAL;
1388
1389                 if (addr->can_family != AF_CAN)
1390                         return -EINVAL;
1391
1392                 /* ifindex from sendto() */
1393                 ifindex = addr->can_ifindex;
1394
1395                 if (ifindex) {
1396                         struct net_device *dev;
1397
1398                         dev = dev_get_by_index(&init_net, ifindex);
1399                         if (!dev)
1400                                 return -ENODEV;
1401
1402                         if (dev->type != ARPHRD_CAN) {
1403                                 dev_put(dev);
1404                                 return -ENODEV;
1405                         }
1406
1407                         dev_put(dev);
1408                 }
1409         }
1410
1411         /* read message head information */
1412
1413         ret = memcpy_fromiovec((u8 *)&msg_head, msg->msg_iov, MHSIZ);
1414         if (ret < 0)
1415                 return ret;
1416
1417         lock_sock(sk);
1418
1419         switch (msg_head.opcode) {
1420
1421         case TX_SETUP:
1422                 ret = bcm_tx_setup(&msg_head, msg, ifindex, sk);
1423                 break;
1424
1425         case RX_SETUP:
1426                 ret = bcm_rx_setup(&msg_head, msg, ifindex, sk);
1427                 break;
1428
1429         case TX_DELETE:
1430                 if (bcm_delete_tx_op(&bo->tx_ops, msg_head.can_id, ifindex))
1431                         ret = MHSIZ;
1432                 else
1433                         ret = -EINVAL;
1434                 break;
1435
1436         case RX_DELETE:
1437                 if (bcm_delete_rx_op(&bo->rx_ops, msg_head.can_id, ifindex))
1438                         ret = MHSIZ;
1439                 else
1440                         ret = -EINVAL;
1441                 break;
1442
1443         case TX_READ:
1444                 /* reuse msg_head for the reply to TX_READ */
1445                 msg_head.opcode  = TX_STATUS;
1446                 ret = bcm_read_op(&bo->tx_ops, &msg_head, ifindex);
1447                 break;
1448
1449         case RX_READ:
1450                 /* reuse msg_head for the reply to RX_READ */
1451                 msg_head.opcode  = RX_STATUS;
1452                 ret = bcm_read_op(&bo->rx_ops, &msg_head, ifindex);
1453                 break;
1454
1455         case TX_SEND:
1456                 /* we need exactly one can_frame behind the msg head */
1457                 if ((msg_head.nframes != 1) || (size != CFSIZ + MHSIZ))
1458                         ret = -EINVAL;
1459                 else
1460                         ret = bcm_tx_send(msg, ifindex, sk);
1461                 break;
1462
1463         default:
1464                 ret = -EINVAL;
1465                 break;
1466         }
1467
1468         release_sock(sk);
1469
1470         return ret;
1471 }
1472
1473 /*
1474  * notification handler for netdevice status changes
1475  */
1476 static int bcm_notifier(struct notifier_block *nb, unsigned long msg,
1477                         void *data)
1478 {
1479         struct net_device *dev = (struct net_device *)data;
1480         struct bcm_sock *bo = container_of(nb, struct bcm_sock, notifier);
1481         struct sock *sk = &bo->sk;
1482         struct bcm_op *op;
1483         int notify_enodev = 0;
1484
1485 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
1486         if (!net_eq(dev_net(dev), &init_net))
1487                 return NOTIFY_DONE;
1488 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
1489         if (dev->nd_net != &init_net)
1490                 return NOTIFY_DONE;
1491 #endif
1492
1493         if (dev->type != ARPHRD_CAN)
1494                 return NOTIFY_DONE;
1495
1496         switch (msg) {
1497
1498         case NETDEV_UNREGISTER:
1499                 lock_sock(sk);
1500
1501                 /* remove device specific receive entries */
1502                 list_for_each_entry(op, &bo->rx_ops, list)
1503                         if (op->rx_reg_dev == dev)
1504                                 bcm_rx_unreg(dev, op);
1505
1506                 /* remove device reference, if this is our bound device */
1507                 if (bo->bound && bo->ifindex == dev->ifindex) {
1508                         bo->bound   = 0;
1509                         bo->ifindex = 0;
1510                         notify_enodev = 1;
1511                 }
1512
1513                 release_sock(sk);
1514
1515                 if (notify_enodev) {
1516                         sk->sk_err = ENODEV;
1517                         if (!sock_flag(sk, SOCK_DEAD))
1518                                 sk->sk_error_report(sk);
1519                 }
1520                 break;
1521
1522         case NETDEV_DOWN:
1523                 if (bo->bound && bo->ifindex == dev->ifindex) {
1524                         sk->sk_err = ENETDOWN;
1525                         if (!sock_flag(sk, SOCK_DEAD))
1526                                 sk->sk_error_report(sk);
1527                 }
1528         }
1529
1530         return NOTIFY_DONE;
1531 }
1532
1533 /*
1534  * initial settings for all BCM sockets to be set at socket creation time
1535  */
1536 static int bcm_init(struct sock *sk)
1537 {
1538         struct bcm_sock *bo = bcm_sk(sk);
1539
1540         bo->bound            = 0;
1541         bo->ifindex          = 0;
1542         bo->dropped_usr_msgs = 0;
1543         bo->bcm_proc_read    = NULL;
1544
1545         INIT_LIST_HEAD(&bo->tx_ops);
1546         INIT_LIST_HEAD(&bo->rx_ops);
1547
1548         /* set notifier */
1549         bo->notifier.notifier_call = bcm_notifier;
1550
1551         register_netdevice_notifier(&bo->notifier);
1552
1553         return 0;
1554 }
1555
1556 /*
1557  * standard socket functions
1558  */
1559 static int bcm_release(struct socket *sock)
1560 {
1561         struct sock *sk = sock->sk;
1562         struct bcm_sock *bo;
1563         struct bcm_op *op, *next;
1564
1565         if (sk == NULL)
1566                 return 0;
1567
1568         bo = bcm_sk(sk);
1569
1570         /* remove bcm_ops, timer, rx_unregister(), etc. */
1571
1572         unregister_netdevice_notifier(&bo->notifier);
1573
1574         lock_sock(sk);
1575
1576         list_for_each_entry_safe(op, next, &bo->tx_ops, list)
1577                 bcm_remove_op(op);
1578
1579         list_for_each_entry_safe(op, next, &bo->rx_ops, list) {
1580                 /*
1581                  * Don't care if we're bound or not (due to netdev problems)
1582                  * can_rx_unregister() is always a save thing to do here.
1583                  */
1584                 if (op->ifindex) {
1585                         /*
1586                          * Only remove subscriptions that had not
1587                          * been removed due to NETDEV_UNREGISTER
1588                          * in bcm_notifier()
1589                          */
1590                         if (op->rx_reg_dev) {
1591                                 struct net_device *dev;
1592
1593                                 dev = dev_get_by_index(&init_net, op->ifindex);
1594                                 if (dev) {
1595                                         bcm_rx_unreg(dev, op);
1596                                         dev_put(dev);
1597                                 }
1598                         }
1599                 } else
1600                         can_rx_unregister(NULL, op->can_id,
1601                                           REGMASK(op->can_id),
1602                                           bcm_rx_handler, op);
1603
1604                 bcm_remove_op(op);
1605         }
1606
1607         /* remove procfs entry */
1608         if (proc_dir && bo->bcm_proc_read)
1609                 remove_proc_entry(bo->procname, proc_dir);
1610
1611         /* remove device reference */
1612         if (bo->bound) {
1613                 bo->bound   = 0;
1614                 bo->ifindex = 0;
1615         }
1616
1617         sock_orphan(sk);
1618         sock->sk = NULL;
1619
1620         release_sock(sk);
1621         sock_put(sk);
1622
1623         return 0;
1624 }
1625
1626 static int bcm_connect(struct socket *sock, struct sockaddr *uaddr, int len,
1627                        int flags)
1628 {
1629         struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1630         struct sock *sk = sock->sk;
1631         struct bcm_sock *bo = bcm_sk(sk);
1632
1633         if (len < sizeof(*addr))
1634                 return -EINVAL;
1635
1636         if (bo->bound)
1637                 return -EISCONN;
1638
1639         /* bind a device to this socket */
1640         if (addr->can_ifindex) {
1641                 struct net_device *dev;
1642
1643                 dev = dev_get_by_index(&init_net, addr->can_ifindex);
1644                 if (!dev)
1645                         return -ENODEV;
1646
1647                 if (dev->type != ARPHRD_CAN) {
1648                         dev_put(dev);
1649                         return -ENODEV;
1650                 }
1651
1652                 bo->ifindex = dev->ifindex;
1653                 dev_put(dev);
1654
1655         } else {
1656                 /* no interface reference for ifindex = 0 ('any' CAN device) */
1657                 bo->ifindex = 0;
1658         }
1659
1660         bo->bound = 1;
1661
1662         if (proc_dir) {
1663                 /* unique socket address as filename */
1664                 sprintf(bo->procname, "%lu", sock_i_ino(sk));
1665 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,26)
1666                 bo->bcm_proc_read = proc_create_data(bo->procname, 0644,
1667                                                      proc_dir,
1668                                                      &bcm_proc_fops, sk);
1669 #else
1670                 bo->bcm_proc_read = create_proc_read_entry(bo->procname, 0644,
1671                                                            proc_dir,
1672                                                            bcm_read_proc, sk);
1673 #endif
1674         }
1675
1676         return 0;
1677 }
1678
1679 static int bcm_recvmsg(struct kiocb *iocb, struct socket *sock,
1680                        struct msghdr *msg, size_t size, int flags)
1681 {
1682         struct sock *sk = sock->sk;
1683         struct sk_buff *skb;
1684         int error = 0;
1685         int noblock;
1686         int err;
1687
1688         noblock =  flags & MSG_DONTWAIT;
1689         flags   &= ~MSG_DONTWAIT;
1690         skb = skb_recv_datagram(sk, flags, noblock, &error);
1691         if (!skb)
1692                 return error;
1693
1694         if (skb->len < size)
1695                 size = skb->len;
1696
1697         err = memcpy_toiovec(msg->msg_iov, skb->data, size);
1698         if (err < 0) {
1699                 skb_free_datagram(sk, skb);
1700                 return err;
1701         }
1702
1703         sock_recv_timestamp(msg, sk, skb);
1704
1705         if (msg->msg_name) {
1706                 msg->msg_namelen = sizeof(struct sockaddr_can);
1707                 memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
1708         }
1709
1710         skb_free_datagram(sk, skb);
1711
1712         return size;
1713 }
1714
1715 static const struct proto_ops bcm_ops = {
1716         .family        = PF_CAN,
1717         .release       = bcm_release,
1718         .bind          = sock_no_bind,
1719         .connect       = bcm_connect,
1720         .socketpair    = sock_no_socketpair,
1721         .accept        = sock_no_accept,
1722         .getname       = sock_no_getname,
1723         .poll          = datagram_poll,
1724         .ioctl         = can_ioctl,     /* use can_ioctl() from af_can.c */
1725         .listen        = sock_no_listen,
1726         .shutdown      = sock_no_shutdown,
1727         .setsockopt    = sock_no_setsockopt,
1728         .getsockopt    = sock_no_getsockopt,
1729         .sendmsg       = bcm_sendmsg,
1730         .recvmsg       = bcm_recvmsg,
1731         .mmap          = sock_no_mmap,
1732         .sendpage      = sock_no_sendpage,
1733 };
1734
1735 static struct proto bcm_proto __read_mostly = {
1736         .name       = "CAN_BCM",
1737         .owner      = THIS_MODULE,
1738         .obj_size   = sizeof(struct bcm_sock),
1739         .init       = bcm_init,
1740 };
1741
1742 static const struct can_proto bcm_can_proto = {
1743         .type       = SOCK_DGRAM,
1744         .protocol   = CAN_BCM,
1745 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,33)
1746         .capability = -1,
1747 #endif
1748         .ops        = &bcm_ops,
1749         .prot       = &bcm_proto,
1750 };
1751
1752 static int __init bcm_module_init(void)
1753 {
1754         int err;
1755
1756         printk(banner);
1757
1758         err = can_proto_register(&bcm_can_proto);
1759         if (err < 0) {
1760                 printk(KERN_ERR "can: registration of bcm protocol failed\n");
1761                 return err;
1762         }
1763
1764         /* create /proc/net/can-bcm directory */
1765 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
1766         proc_dir = proc_mkdir("can-bcm", init_net.proc_net);
1767 #else
1768         proc_dir = proc_mkdir("can-bcm", proc_net);
1769 #endif
1770
1771 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,30)
1772         if (proc_dir)
1773                 proc_dir->owner = THIS_MODULE;
1774 #endif
1775
1776         return 0;
1777 }
1778
1779 static void __exit bcm_module_exit(void)
1780 {
1781         can_proto_unregister(&bcm_can_proto);
1782
1783         if (proc_dir)
1784 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)
1785                 proc_net_remove(&init_net, "can-bcm");
1786 #else
1787                 proc_net_remove("can-bcm");
1788 #endif
1789 }
1790
1791 module_init(bcm_module_init);
1792 module_exit(bcm_module_exit);