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