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