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