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