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