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