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