xref: /linux/net/can/bcm.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
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/can-ml.h>
58 #include <linux/can/core.h>
59 #include <linux/can/skb.h>
60 #include <linux/can/bcm.h>
61 #include <linux/slab.h>
62 #include <linux/workqueue.h>
63 #include <linux/spinlock.h>
64 #include <net/can.h>
65 #include <net/sock.h>
66 #include <net/net_namespace.h>
67 
68 /*
69  * To send multiple CAN frame content within TX_SETUP or to filter
70  * CAN messages with multiplex index within RX_SETUP, the number of
71  * different filters is limited to 256 due to the one byte index value.
72  */
73 #define MAX_NFRAMES 256
74 
75 /* limit timers to 400 days for sending/timeouts */
76 #define BCM_TIMER_SEC_MAX (400 * 24 * 60 * 60)
77 
78 /* use of last_frames[index].flags */
79 #define RX_LOCAL   0x10 /* frame was created on the local host */
80 #define RX_OWN     0x20 /* frame was sent via the socket it was received on */
81 #define RX_RECV    0x40 /* received data for this element */
82 #define RX_THR     0x80 /* element not been sent due to throttle feature */
83 #define BCM_CAN_FLAGS_MASK 0x0F /* to clean private flags after usage */
84 
85 /* get best masking value for can_rx_register() for a given single can_id */
86 #define REGMASK(id) ((id & CAN_EFF_FLAG) ? \
87 		     (CAN_EFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG) : \
88 		     (CAN_SFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG))
89 
90 MODULE_DESCRIPTION("PF_CAN broadcast manager protocol");
91 MODULE_LICENSE("Dual BSD/GPL");
92 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
93 MODULE_ALIAS("can-proto-2");
94 
95 #define BCM_MIN_NAMELEN CAN_REQUIRED_SIZE(struct sockaddr_can, can_ifindex)
96 
97 static struct workqueue_struct *bcm_wq;
98 
99 /*
100  * easy access to the first 64 bit of can(fd)_frame payload. cp->data is
101  * 64 bit aligned so the offset has to be multiples of 8 which is ensured
102  * by the only callers in bcm_rx_cmp_to_index() bcm_rx_handler().
103  */
104 static inline u64 get_u64(const struct canfd_frame *cp, int offset)
105 {
106 	return *(u64 *)(cp->data + offset);
107 }
108 
109 struct bcm_op {
110 	struct list_head list;
111 	struct rcu_head rcu;
112 	struct work_struct work;
113 	int ifindex;
114 	canid_t can_id;
115 	u32 flags;
116 	atomic_long_t frames_abs, frames_filtered;
117 	struct bcm_timeval ival1, ival2;
118 	struct hrtimer timer, thrtimer;
119 	ktime_t rx_stamp, kt_ival1, kt_ival2, kt_lastmsg;
120 	int rx_ifindex;
121 	int if_detected; /* first received ifindex in ANYDEV rx_op mode */
122 	int cfsiz;
123 	u32 count;
124 	u32 nframes;
125 	u32 currframe;
126 	/* void pointers to arrays of struct can[fd]_frame */
127 	void *frames;
128 	void *last_frames;
129 	struct canfd_frame sframe;
130 	struct canfd_frame last_sframe;
131 	struct sock *sk;
132 	struct net_device *rx_reg_dev;
133 	netdevice_tracker rx_reg_dev_tracker;
134 	spinlock_t bcm_tx_lock; /* protect tx data and timer updates */
135 	spinlock_t bcm_rx_update_lock; /* protect filter/timer data updates */
136 };
137 
138 struct bcm_sock {
139 	struct sock sk;
140 	int bound;
141 	int ifindex;
142 	struct list_head notifier;
143 	struct list_head rx_ops;
144 	struct list_head tx_ops;
145 	unsigned long dropped_usr_msgs;
146 	struct proc_dir_entry *bcm_proc_read;
147 	char procname [32]; /* inode number in decimal with \0 */
148 };
149 
150 static LIST_HEAD(bcm_notifier_list);
151 static DEFINE_SPINLOCK(bcm_notifier_lock);
152 static struct bcm_sock *bcm_busy_notifier;
153 
154 /* Return pointer to store the extra msg flags for bcm_recvmsg().
155  * We use the space of one unsigned int beyond the 'struct sockaddr_can'
156  * in skb->cb.
157  */
158 static inline unsigned int *bcm_flags(struct sk_buff *skb)
159 {
160 	/* return pointer after struct sockaddr_can */
161 	return (unsigned int *)(&((struct sockaddr_can *)skb->cb)[1]);
162 }
163 
164 static inline struct bcm_sock *bcm_sk(const struct sock *sk)
165 {
166 	return (struct bcm_sock *)sk;
167 }
168 
169 static inline ktime_t bcm_timeval_to_ktime(struct bcm_timeval tv)
170 {
171 	return ktime_set(tv.tv_sec, tv.tv_usec * NSEC_PER_USEC);
172 }
173 
174 /* check limitations for timeval provided by user */
175 static bool bcm_is_invalid_tv(struct bcm_msg_head *msg_head)
176 {
177 	if ((msg_head->ival1.tv_sec < 0) ||
178 	    (msg_head->ival1.tv_sec > BCM_TIMER_SEC_MAX) ||
179 	    (msg_head->ival1.tv_usec < 0) ||
180 	    (msg_head->ival1.tv_usec >= USEC_PER_SEC) ||
181 	    (msg_head->ival2.tv_sec < 0) ||
182 	    (msg_head->ival2.tv_sec > BCM_TIMER_SEC_MAX) ||
183 	    (msg_head->ival2.tv_usec < 0) ||
184 	    (msg_head->ival2.tv_usec >= USEC_PER_SEC))
185 		return true;
186 
187 	return false;
188 }
189 
190 #define CFSIZ(flags) ((flags & CAN_FD_FRAME) ? CANFD_MTU : CAN_MTU)
191 #define OPSIZ sizeof(struct bcm_op)
192 #define MHSIZ sizeof(struct bcm_msg_head)
193 
194 /*
195  * procfs functions
196  */
197 #if IS_ENABLED(CONFIG_PROC_FS)
198 static char *bcm_proc_getifname(struct net *net, char *result, int ifindex)
199 {
200 	struct net_device *dev;
201 
202 	if (!ifindex)
203 		return "any";
204 
205 	rcu_read_lock();
206 	dev = dev_get_by_index_rcu(net, ifindex);
207 	if (dev)
208 		strcpy(result, dev->name);
209 	else
210 		strcpy(result, "???");
211 	rcu_read_unlock();
212 
213 	return result;
214 }
215 
216 static int bcm_proc_show(struct seq_file *m, void *v)
217 {
218 	char ifname[IFNAMSIZ];
219 	struct net *net = m->private;
220 	struct sock *sk = (struct sock *)pde_data(m->file->f_inode);
221 	struct bcm_sock *bo = bcm_sk(sk);
222 	struct bcm_op *op;
223 
224 	seq_printf(m, ">>> sock inode %s", bo->procname);
225 	seq_printf(m, " / dropped %lu", bo->dropped_usr_msgs);
226 	seq_printf(m, " / bound %s", bcm_proc_getifname(net, ifname, bo->ifindex));
227 	seq_printf(m, " <<<\n");
228 
229 	rcu_read_lock();
230 
231 	list_for_each_entry_rcu(op, &bo->rx_ops, list) {
232 
233 		long reduction, frames_filtered, frames_abs;
234 
235 		frames_filtered = atomic_long_read(&op->frames_filtered);
236 		frames_abs = atomic_long_read(&op->frames_abs);
237 
238 		/* print only active entries & prevent division by zero */
239 		if (!frames_abs)
240 			continue;
241 
242 		seq_printf(m, "rx_op: %03X %-5s ", op->can_id,
243 			   bcm_proc_getifname(net, ifname, op->ifindex));
244 
245 		if (op->flags & CAN_FD_FRAME)
246 			seq_printf(m, "(%u)", op->nframes);
247 		else
248 			seq_printf(m, "[%u]", op->nframes);
249 
250 		seq_printf(m, "%c ", (op->flags & RX_CHECK_DLC) ? 'd' : ' ');
251 
252 		if (op->kt_ival1)
253 			seq_printf(m, "timeo=%lld ",
254 				   (long long)ktime_to_us(op->kt_ival1));
255 
256 		if (op->kt_ival2)
257 			seq_printf(m, "thr=%lld ",
258 				   (long long)ktime_to_us(op->kt_ival2));
259 
260 		seq_printf(m, "# recv %ld (%ld) => reduction: ",
261 			   frames_filtered, frames_abs);
262 
263 		reduction = 100 - (frames_filtered * 100) / frames_abs;
264 
265 		seq_printf(m, "%s%ld%%\n",
266 			   (reduction == 100) ? "near " : "", reduction);
267 	}
268 
269 	list_for_each_entry_rcu(op, &bo->tx_ops, list) {
270 
271 		seq_printf(m, "tx_op: %03X %s ", op->can_id,
272 			   bcm_proc_getifname(net, ifname, op->ifindex));
273 
274 		if (op->flags & CAN_FD_FRAME)
275 			seq_printf(m, "(%u) ", op->nframes);
276 		else
277 			seq_printf(m, "[%u] ", op->nframes);
278 
279 		if (op->kt_ival1)
280 			seq_printf(m, "t1=%lld ",
281 				   (long long)ktime_to_us(op->kt_ival1));
282 
283 		if (op->kt_ival2)
284 			seq_printf(m, "t2=%lld ",
285 				   (long long)ktime_to_us(op->kt_ival2));
286 
287 		seq_printf(m, "# sent %ld\n",
288 			   atomic_long_read(&op->frames_abs));
289 	}
290 	seq_putc(m, '\n');
291 
292 	rcu_read_unlock();
293 
294 	return 0;
295 }
296 #endif /* CONFIG_PROC_FS */
297 
298 static void bcm_update_rx_stats(struct bcm_op *op)
299 {
300 	/* prevent overflow of the reduction% calculation in bcm_proc_show() */
301 	if (atomic_long_inc_return(&op->frames_abs) > LONG_MAX / 100) {
302 		atomic_long_set(&op->frames_filtered, 0);
303 		atomic_long_set(&op->frames_abs, 0);
304 	}
305 }
306 
307 static void bcm_update_tx_stats(struct bcm_op *op)
308 {
309 	/* tx_op has no reduction% calculation - use the full range and
310 	 * just keep the displayed counter non-negative on overflow
311 	 */
312 	if (atomic_long_inc_return(&op->frames_abs) == LONG_MAX)
313 		atomic_long_set(&op->frames_abs, 0);
314 }
315 
316 /*
317  * bcm_can_tx - send the (next) CAN frame to the appropriate CAN interface
318  *              of the given bcm tx op
319  */
320 static void bcm_can_tx(struct bcm_op *op, struct canfd_frame *cf)
321 {
322 	struct sk_buff *skb;
323 	struct can_skb_ext *csx;
324 	struct net_device *dev;
325 	struct canfd_frame cframe;
326 	bool cyclic = !cf;
327 	unsigned int idx = 0;
328 	int err;
329 
330 	/* no target device? => exit */
331 	if (!op->ifindex)
332 		return;
333 
334 	if (cyclic) {
335 		/* read currframe under lock protection */
336 		spin_lock_bh(&op->bcm_tx_lock);
337 		idx = op->currframe;
338 		memcpy(&cframe, op->frames + op->cfsiz * idx, op->cfsiz);
339 		cf = &cframe;
340 		spin_unlock_bh(&op->bcm_tx_lock);
341 	}
342 
343 	dev = dev_get_by_index(sock_net(op->sk), op->ifindex);
344 	if (!dev) {
345 		/* RFC: should this bcm_op remove itself here? */
346 		return;
347 	}
348 
349 	skb = alloc_skb(op->cfsiz, gfp_any());
350 	if (!skb)
351 		goto out;
352 
353 	csx = can_skb_ext_add(skb);
354 	if (!csx) {
355 		kfree_skb(skb);
356 		goto out;
357 	}
358 
359 	csx->can_iif = dev->ifindex;
360 
361 	skb_put_data(skb, cf, op->cfsiz);
362 
363 	/* send with loopback */
364 	skb->dev = dev;
365 	can_skb_set_owner(skb, op->sk);
366 	err = can_send(skb, 1);
367 
368 	/* update currframe and count under lock protection */
369 	spin_lock_bh(&op->bcm_tx_lock);
370 
371 	if (!err)
372 		bcm_update_tx_stats(op);
373 
374 	/* only advance the cyclic sequence if nothing reset currframe while
375 	 * we were sending - a concurrent TX_RESET_MULTI_IDX means this
376 	 * frame's bookkeeping belongs to a sequence that no longer exists
377 	 */
378 	if (!cyclic || op->currframe == idx) {
379 		op->currframe++;
380 
381 		/* reached last frame? */
382 		if (op->currframe >= op->nframes)
383 			op->currframe = 0;
384 
385 		if (op->count > 0)
386 			op->count--;
387 	}
388 
389 	spin_unlock_bh(&op->bcm_tx_lock);
390 out:
391 	dev_put(dev);
392 }
393 
394 /*
395  * bcm_send_to_user - send a BCM message to the userspace
396  *                    (consisting of bcm_msg_head + x CAN frames)
397  */
398 static void bcm_send_to_user(struct bcm_op *op, struct bcm_msg_head *head,
399 			     struct canfd_frame *frames, int has_timestamp)
400 {
401 	struct sk_buff *skb;
402 	struct canfd_frame *firstframe;
403 	struct sockaddr_can *addr;
404 	struct sock *sk = op->sk;
405 	unsigned int datalen = head->nframes * op->cfsiz;
406 	unsigned int *pflags;
407 	enum skb_drop_reason reason;
408 
409 	skb = alloc_skb(sizeof(*head) + datalen, gfp_any());
410 	if (!skb)
411 		return;
412 
413 	skb_put_data(skb, head, sizeof(*head));
414 
415 	/* ensure space for sockaddr_can and msg flags */
416 	sock_skb_cb_check_size(sizeof(struct sockaddr_can) +
417 			       sizeof(unsigned int));
418 
419 	/* initialize msg flags */
420 	pflags = bcm_flags(skb);
421 	*pflags = 0;
422 
423 	if (head->nframes) {
424 		/* CAN frames starting here */
425 		firstframe = (struct canfd_frame *)skb_tail_pointer(skb);
426 
427 		skb_put_data(skb, frames, datalen);
428 
429 		/*
430 		 * the BCM uses the flags-element of the canfd_frame
431 		 * structure for internal purposes. This is only
432 		 * relevant for updates that are generated by the
433 		 * BCM, where nframes is 1
434 		 */
435 		if (head->nframes == 1) {
436 			if (firstframe->flags & RX_LOCAL)
437 				*pflags |= MSG_DONTROUTE;
438 			if (firstframe->flags & RX_OWN)
439 				*pflags |= MSG_CONFIRM;
440 
441 			firstframe->flags &= BCM_CAN_FLAGS_MASK;
442 		}
443 	}
444 
445 	if (has_timestamp) {
446 		/* restore rx timestamp */
447 		skb->tstamp = op->rx_stamp;
448 	}
449 
450 	/*
451 	 *  Put the datagram to the queue so that bcm_recvmsg() can
452 	 *  get it from there.  We need to pass the interface index to
453 	 *  bcm_recvmsg().  We pass a whole struct sockaddr_can in skb->cb
454 	 *  containing the interface index.
455 	 */
456 
457 	addr = (struct sockaddr_can *)skb->cb;
458 	memset(addr, 0, sizeof(*addr));
459 	addr->can_family  = AF_CAN;
460 	addr->can_ifindex = op->rx_ifindex;
461 
462 	reason = sock_queue_rcv_skb_reason(sk, skb);
463 	if (reason) {
464 		struct bcm_sock *bo = bcm_sk(sk);
465 
466 		sk_skb_reason_drop(sk, skb, reason);
467 		/* don't care about overflows in this statistic */
468 		bo->dropped_usr_msgs++;
469 	}
470 }
471 
472 static bool bcm_tx_set_expiry(struct bcm_op *op, struct hrtimer *hrt)
473 {
474 	ktime_t ival;
475 
476 	spin_lock_bh(&op->bcm_tx_lock);
477 
478 	if (op->kt_ival1 && op->count)
479 		ival = op->kt_ival1;
480 	else if (op->kt_ival2) {
481 		ival = op->kt_ival2;
482 	} else {
483 		spin_unlock_bh(&op->bcm_tx_lock);
484 		return false;
485 	}
486 
487 	spin_unlock_bh(&op->bcm_tx_lock);
488 
489 	hrtimer_set_expires(hrt, ktime_add(ktime_get(), ival));
490 	return true;
491 }
492 
493 static void bcm_tx_start_timer(struct bcm_op *op)
494 {
495 	if (bcm_tx_set_expiry(op, &op->timer))
496 		hrtimer_start_expires(&op->timer, HRTIMER_MODE_ABS_SOFT);
497 }
498 
499 /* bcm_tx_timeout_handler - performs cyclic CAN frame transmissions */
500 static enum hrtimer_restart bcm_tx_timeout_handler(struct hrtimer *hrtimer)
501 {
502 	struct bcm_op *op = container_of(hrtimer, struct bcm_op, timer);
503 	struct bcm_msg_head msg_head;
504 	bool tx_ival1, tx_ival2;
505 
506 	/* snapshot kt_ival1/kt_ival2/count under lock to avoid torn
507 	 * ktime_t reads racing with concurrent bcm_tx_setup() updates
508 	 */
509 	spin_lock_bh(&op->bcm_tx_lock);
510 	tx_ival1 = op->kt_ival1 && (op->count > 0);
511 	tx_ival2 = !!op->kt_ival2;
512 	spin_unlock_bh(&op->bcm_tx_lock);
513 
514 	if (tx_ival1) {
515 		u32 flags, count;
516 		struct bcm_timeval ival1, ival2;
517 
518 		bcm_can_tx(op, NULL);
519 
520 		/* snapshot variables under lock to avoid torn reads racing
521 		 * with concurrent bcm_tx_setup() updates
522 		 */
523 		spin_lock_bh(&op->bcm_tx_lock);
524 		flags = op->flags;
525 		count = op->count;
526 		ival1 = op->ival1;
527 		ival2 = op->ival2;
528 		spin_unlock_bh(&op->bcm_tx_lock);
529 
530 		if (!count && (flags & TX_COUNTEVT)) {
531 			/* create notification to user */
532 			memset(&msg_head, 0, sizeof(msg_head));
533 			msg_head.opcode  = TX_EXPIRED;
534 			msg_head.flags   = flags;
535 			msg_head.count   = count;
536 			msg_head.ival1   = ival1;
537 			msg_head.ival2   = ival2;
538 			msg_head.can_id  = op->can_id;
539 			msg_head.nframes = 0;
540 
541 			bcm_send_to_user(op, &msg_head, NULL, 0);
542 		}
543 
544 	} else if (tx_ival2) {
545 		bcm_can_tx(op, NULL);
546 	}
547 
548 	return bcm_tx_set_expiry(op, &op->timer) ?
549 		HRTIMER_RESTART : HRTIMER_NORESTART;
550 }
551 
552 /*
553  * bcm_rx_changed - create a RX_CHANGED notification due to changed content
554  */
555 static void bcm_rx_changed(struct bcm_op *op, struct canfd_frame *data)
556 {
557 	struct bcm_msg_head head;
558 
559 	/* update statistics (frames_filtered <= frames_abs) */
560 	if (atomic_long_read(&op->frames_abs))
561 		atomic_long_inc(&op->frames_filtered);
562 
563 	/* this element is not throttled anymore */
564 	data->flags &= ~RX_THR;
565 
566 	memset(&head, 0, sizeof(head));
567 	head.opcode  = RX_CHANGED;
568 	head.flags   = op->flags;
569 	head.count   = op->count;
570 	head.ival1   = op->ival1;
571 	head.ival2   = op->ival2;
572 	head.can_id  = op->can_id;
573 	head.nframes = 1;
574 
575 	bcm_send_to_user(op, &head, data, 1);
576 }
577 
578 /*
579  * bcm_rx_update_and_send - process a detected relevant receive content change
580  *                          1. update the last received data
581  *                          2. send a notification to the user (if possible)
582  */
583 static void bcm_rx_update_and_send(struct bcm_op *op,
584 				   struct canfd_frame *lastdata,
585 				   const struct canfd_frame *rxdata,
586 				   unsigned char traffic_flags)
587 {
588 	memcpy(lastdata, rxdata, op->cfsiz);
589 
590 	/* mark as used and throttled by default */
591 	lastdata->flags |= (RX_RECV|RX_THR);
592 
593 	/* add own/local/remote traffic flags */
594 	lastdata->flags |= traffic_flags;
595 
596 	/* throttling mode inactive ? */
597 	if (!op->kt_ival2) {
598 		/* send RX_CHANGED to the user immediately */
599 		bcm_rx_changed(op, lastdata);
600 		return;
601 	}
602 
603 	/* with active throttling timer we are just done here */
604 	if (hrtimer_active(&op->thrtimer))
605 		return;
606 
607 	/* first reception with enabled throttling mode */
608 	if (!op->kt_lastmsg)
609 		goto rx_changed_settime;
610 
611 	/* got a second frame inside a potential throttle period? */
612 	if (ktime_us_delta(ktime_get(), op->kt_lastmsg) <
613 	    ktime_to_us(op->kt_ival2)) {
614 		/* do not send the saved data - only start throttle timer */
615 		hrtimer_start(&op->thrtimer,
616 			      ktime_add(op->kt_lastmsg, op->kt_ival2),
617 			      HRTIMER_MODE_ABS_SOFT);
618 		return;
619 	}
620 
621 	/* the gap was that big, that throttling was not needed here */
622 rx_changed_settime:
623 	bcm_rx_changed(op, lastdata);
624 	op->kt_lastmsg = ktime_get();
625 }
626 
627 /*
628  * bcm_rx_cmp_to_index - (bit)compares the currently received data to formerly
629  *                       received data stored in op->last_frames[]
630  */
631 static void bcm_rx_cmp_to_index(struct bcm_op *op, unsigned int index,
632 				const struct canfd_frame *rxdata,
633 				unsigned char traffic_flags)
634 {
635 	struct canfd_frame *cf = op->frames + op->cfsiz * index;
636 	struct canfd_frame *lcf = op->last_frames + op->cfsiz * index;
637 	int i;
638 
639 	/*
640 	 * no one uses the MSBs of flags for comparison,
641 	 * so we use it here to detect the first time of reception
642 	 */
643 
644 	if (!(lcf->flags & RX_RECV)) {
645 		/* received data for the first time => send update to user */
646 		bcm_rx_update_and_send(op, lcf, rxdata, traffic_flags);
647 		return;
648 	}
649 
650 	/* do a real check in CAN frame data section */
651 	for (i = 0; i < rxdata->len; i += 8) {
652 		if ((get_u64(cf, i) & get_u64(rxdata, i)) !=
653 		    (get_u64(cf, i) & get_u64(lcf, i))) {
654 			bcm_rx_update_and_send(op, lcf, rxdata, traffic_flags);
655 			return;
656 		}
657 	}
658 
659 	if (op->flags & RX_CHECK_DLC) {
660 		/* do a real check in CAN frame length */
661 		if (rxdata->len != lcf->len) {
662 			bcm_rx_update_and_send(op, lcf, rxdata, traffic_flags);
663 			return;
664 		}
665 	}
666 }
667 
668 /*
669  * bcm_rx_starttimer - enable timeout monitoring for CAN frame reception
670  */
671 static void bcm_rx_starttimer(struct bcm_op *op)
672 {
673 	if (op->flags & RX_NO_AUTOTIMER)
674 		return;
675 
676 	if (op->kt_ival1)
677 		hrtimer_start(&op->timer, op->kt_ival1, HRTIMER_MODE_REL_SOFT);
678 }
679 
680 /* bcm_rx_timeout_handler - when the (cyclic) CAN frame reception timed out */
681 static enum hrtimer_restart bcm_rx_timeout_handler(struct hrtimer *hrtimer)
682 {
683 	struct bcm_op *op = container_of(hrtimer, struct bcm_op, timer);
684 	struct bcm_msg_head msg_head;
685 
686 	spin_lock_bh(&op->bcm_rx_update_lock);
687 
688 	/* if user wants to be informed, when cyclic CAN-Messages come back */
689 	if ((op->flags & RX_ANNOUNCE_RESUME) && op->last_frames) {
690 		/* clear received CAN frames to indicate 'nothing received' */
691 		memset(op->last_frames, 0, op->nframes * op->cfsiz);
692 	}
693 
694 	/* create notification to user */
695 	memset(&msg_head, 0, sizeof(msg_head));
696 	msg_head.opcode  = RX_TIMEOUT;
697 	msg_head.flags   = op->flags;
698 	msg_head.count   = op->count;
699 	msg_head.ival1   = op->ival1;
700 	msg_head.ival2   = op->ival2;
701 	msg_head.can_id  = op->can_id;
702 	msg_head.nframes = 0;
703 
704 	spin_unlock_bh(&op->bcm_rx_update_lock);
705 
706 	bcm_send_to_user(op, &msg_head, NULL, 0);
707 
708 	return HRTIMER_NORESTART;
709 }
710 
711 /*
712  * bcm_rx_do_flush - helper for bcm_rx_thr_flush
713  */
714 static inline int bcm_rx_do_flush(struct bcm_op *op, unsigned int index)
715 {
716 	struct canfd_frame *lcf = op->last_frames + op->cfsiz * index;
717 
718 	if ((op->last_frames) && (lcf->flags & RX_THR)) {
719 		bcm_rx_changed(op, lcf);
720 		return 1;
721 	}
722 	return 0;
723 }
724 
725 /*
726  * bcm_rx_thr_flush - Check for throttled data and send it to the userspace
727  */
728 static int bcm_rx_thr_flush(struct bcm_op *op)
729 {
730 	int updated = 0;
731 
732 	if (op->nframes > 1) {
733 		unsigned int i;
734 
735 		/* for MUX filter we start at index 1 */
736 		for (i = 1; i < op->nframes; i++)
737 			updated += bcm_rx_do_flush(op, i);
738 
739 	} else {
740 		/* for RX_FILTER_ID and simple filter */
741 		updated += bcm_rx_do_flush(op, 0);
742 	}
743 
744 	return updated;
745 }
746 
747 /*
748  * bcm_rx_thr_handler - the time for blocked content updates is over now:
749  *                      Check for throttled data and send it to the userspace
750  */
751 static enum hrtimer_restart bcm_rx_thr_handler(struct hrtimer *hrtimer)
752 {
753 	struct bcm_op *op = container_of(hrtimer, struct bcm_op, thrtimer);
754 	enum hrtimer_restart ret;
755 
756 	spin_lock_bh(&op->bcm_rx_update_lock);
757 
758 	/* kt_ival2 may have been concurrently cleared by bcm_rx_setup()
759 	 * before it cancels this timer - never forward with a zero
760 	 * interval in that case.
761 	 */
762 	if (bcm_rx_thr_flush(op) && op->kt_ival2) {
763 		hrtimer_forward_now(hrtimer, op->kt_ival2);
764 		ret = HRTIMER_RESTART;
765 	} else {
766 		/* rearm throttle handling */
767 		op->kt_lastmsg = 0;
768 		ret = HRTIMER_NORESTART;
769 	}
770 
771 	spin_unlock_bh(&op->bcm_rx_update_lock);
772 
773 	return ret;
774 }
775 
776 /*
777  * bcm_rx_handler - handle a CAN frame reception
778  */
779 static void bcm_rx_handler(struct sk_buff *skb, void *data)
780 {
781 	struct bcm_op *op = (struct bcm_op *)data;
782 	const struct canfd_frame *rxframe = (struct canfd_frame *)skb->data;
783 	struct canfd_frame rtrframe;
784 	unsigned int i;
785 	unsigned char traffic_flags;
786 	bool rtr_frame;
787 
788 	if (op->can_id != rxframe->can_id)
789 		return;
790 
791 	/* make sure to handle the correct frame type (CAN / CAN FD) */
792 	if (op->flags & CAN_FD_FRAME) {
793 		if (!can_is_canfd_skb(skb))
794 			return;
795 	} else {
796 		if (!can_is_can_skb(skb))
797 			return;
798 	}
799 
800 	/* An ANYDEV op with an active RX timeout and/or throttle timer
801 	 * tracks a single source interface: claim the first interface that
802 	 * delivers a matching frame and reject frames from any other one,
803 	 * before hrtimer_cancel() below can touch op->timer - this avoids
804 	 * racing bcm_rx_timeout_handler() across concurrent interfaces.
805 	 * RX_RTR_FRAME ops are excluded, as kt_ival1/kt_ival2 may briefly
806 	 * hold a stale value from an earlier non-RTR configuration.
807 	 */
808 	if (!op->ifindex) {
809 		spin_lock_bh(&op->bcm_rx_update_lock);
810 
811 		if (!(op->flags & RX_RTR_FRAME) &&
812 		    (op->kt_ival1 || op->kt_ival2)) {
813 			/* don't claim to vanishing interface */
814 			if (!op->if_detected &&
815 			    READ_ONCE(skb->dev->reg_state) == NETREG_REGISTERED)
816 				op->if_detected = skb->dev->ifindex;
817 
818 			if (op->if_detected != skb->dev->ifindex) {
819 				spin_unlock_bh(&op->bcm_rx_update_lock);
820 				return;
821 			}
822 		}
823 
824 		spin_unlock_bh(&op->bcm_rx_update_lock);
825 	}
826 
827 	/* disable timeout */
828 	hrtimer_cancel(&op->timer);
829 
830 	/* op->flags/op->frames may be updated concurrently by bcm_rx_setup() */
831 	spin_lock_bh(&op->bcm_rx_update_lock);
832 
833 	rtr_frame = op->flags & RX_RTR_FRAME;
834 	if (rtr_frame) {
835 		bcm_update_rx_stats(op);
836 		/* snapshot RTR content under lock */
837 		memcpy(&rtrframe, op->frames, op->cfsiz);
838 		spin_unlock_bh(&op->bcm_rx_update_lock);
839 
840 		/* send reply for RTR-request (placed in op->frames[0]) */
841 		bcm_can_tx(op, &rtrframe);
842 		return;
843 	}
844 
845 	/* update statistics in the same critical section as bcm_rx_changed()
846 	 * below: frames_filtered must never be checked/incremented against a
847 	 * frames_abs snapshot from a concurrent bcm_rx_handler() call on
848 	 * another CPU for the same (wildcard) op, or frames_filtered can end
849 	 * up larger than frames_abs.
850 	 */
851 	bcm_update_rx_stats(op);
852 
853 	/* compute flags to distinguish between own/local/remote CAN traffic */
854 	traffic_flags = 0;
855 	if (skb->sk) {
856 		traffic_flags |= RX_LOCAL;
857 		if (skb->sk == op->sk)
858 			traffic_flags |= RX_OWN;
859 	}
860 
861 	/* save rx timestamp and originator for recvfrom() under lock: an
862 	 * ANYDEV op without an active timer can still run concurrently on
863 	 * different CPUs, so content and meta data must be bundled here.
864 	 */
865 	op->rx_stamp = skb->tstamp;
866 	op->rx_ifindex = skb->dev->ifindex;
867 
868 	if (op->flags & RX_FILTER_ID) {
869 		/* the easiest case */
870 		bcm_rx_update_and_send(op, op->last_frames, rxframe,
871 				       traffic_flags);
872 		goto rx_starttimer;
873 	}
874 
875 	if (op->nframes == 1) {
876 		/* simple compare with index 0 */
877 		bcm_rx_cmp_to_index(op, 0, rxframe, traffic_flags);
878 		goto rx_starttimer;
879 	}
880 
881 	if (op->nframes > 1) {
882 		/*
883 		 * multiplex compare
884 		 *
885 		 * find the first multiplex mask that fits.
886 		 * Remark: The MUX-mask is stored in index 0 - but only the
887 		 * first 64 bits of the frame data[] are relevant (CAN FD)
888 		 */
889 
890 		for (i = 1; i < op->nframes; i++) {
891 			if ((get_u64(op->frames, 0) & get_u64(rxframe, 0)) ==
892 			    (get_u64(op->frames, 0) &
893 			     get_u64(op->frames + op->cfsiz * i, 0))) {
894 				bcm_rx_cmp_to_index(op, i, rxframe,
895 						    traffic_flags);
896 				break;
897 			}
898 		}
899 	}
900 
901 rx_starttimer:
902 	bcm_rx_starttimer(op);
903 
904 	spin_unlock_bh(&op->bcm_rx_update_lock);
905 }
906 
907 /*
908  * helpers for bcm_op handling: find & delete bcm [rx|tx] op elements
909  */
910 static struct bcm_op *bcm_find_op(struct list_head *ops,
911 				  struct bcm_msg_head *mh, int ifindex)
912 {
913 	struct bcm_op *op;
914 
915 	list_for_each_entry(op, ops, list) {
916 		if ((op->can_id == mh->can_id) && (op->ifindex == ifindex) &&
917 		    (op->flags & CAN_FD_FRAME) == (mh->flags & CAN_FD_FRAME))
918 			return op;
919 	}
920 
921 	return NULL;
922 }
923 
924 static void bcm_free_op_work(struct work_struct *work)
925 {
926 	struct bcm_op *op = container_of(work, struct bcm_op, work);
927 
928 	hrtimer_cancel(&op->timer);
929 	hrtimer_cancel(&op->thrtimer);
930 
931 	if ((op->frames) && (op->frames != &op->sframe))
932 		kfree(op->frames);
933 
934 	if ((op->last_frames) && (op->last_frames != &op->last_sframe))
935 		kfree(op->last_frames);
936 
937 	/* the last possible access to op->timer/op->thrtimer has now
938 	 * happened above via hrtimer_cancel() - op->sk is no longer
939 	 * needed by any pending timer callback, so drop our reference
940 	 */
941 	sock_put(op->sk);
942 
943 	kfree(op);
944 }
945 
946 static void bcm_free_op_rcu(struct rcu_head *rcu_head)
947 {
948 	struct bcm_op *op = container_of(rcu_head, struct bcm_op, rcu);
949 
950 	INIT_WORK(&op->work, bcm_free_op_work);
951 	queue_work(bcm_wq, &op->work);
952 }
953 
954 static void bcm_remove_op(struct bcm_op *op)
955 {
956 	hrtimer_cancel(&op->timer);
957 	hrtimer_cancel(&op->thrtimer);
958 
959 	call_rcu(&op->rcu, bcm_free_op_rcu);
960 }
961 
962 static void bcm_rx_unreg(struct net_device *dev, struct bcm_op *op)
963 {
964 	if (op->rx_reg_dev == dev) {
965 		can_rx_unregister(sock_net(op->sk), dev, op->can_id,
966 				  REGMASK(op->can_id), bcm_rx_handler, op);
967 
968 		/* mark as removed subscription */
969 		op->rx_reg_dev = NULL;
970 		netdev_put(dev, &op->rx_reg_dev_tracker);
971 	} else
972 		printk(KERN_ERR "can-bcm: bcm_rx_unreg: registered device "
973 		       "mismatch %p %p\n", op->rx_reg_dev, dev);
974 }
975 
976 /*
977  * bcm_delete_rx_op - find and remove a rx op (returns number of removed ops)
978  */
979 static int bcm_delete_rx_op(struct list_head *ops, struct bcm_msg_head *mh,
980 			    int ifindex)
981 {
982 	struct bcm_op *op, *n;
983 
984 	list_for_each_entry_safe(op, n, ops, list) {
985 		if ((op->can_id == mh->can_id) && (op->ifindex == ifindex) &&
986 		    (op->flags & CAN_FD_FRAME) == (mh->flags & CAN_FD_FRAME)) {
987 
988 			/* disable automatic timer on frame reception */
989 			op->flags |= RX_NO_AUTOTIMER;
990 
991 			if (op->ifindex) {
992 				/* Only remove subscriptions that had not been
993 				 * removed in bcm_notify(). op->rx_reg_dev keeps
994 				 * the device's receive lists accessible.
995 				 */
996 				if (op->rx_reg_dev)
997 					bcm_rx_unreg(op->rx_reg_dev, op);
998 			} else
999 				can_rx_unregister(sock_net(op->sk), NULL,
1000 						  op->can_id,
1001 						  REGMASK(op->can_id),
1002 						  bcm_rx_handler, op);
1003 
1004 			list_del_rcu(&op->list);
1005 			bcm_remove_op(op);
1006 			return 1; /* done */
1007 		}
1008 	}
1009 
1010 	return 0; /* not found */
1011 }
1012 
1013 /*
1014  * bcm_delete_tx_op - find and remove a tx op (returns number of removed ops)
1015  */
1016 static int bcm_delete_tx_op(struct list_head *ops, struct bcm_msg_head *mh,
1017 			    int ifindex)
1018 {
1019 	struct bcm_op *op, *n;
1020 
1021 	list_for_each_entry_safe(op, n, ops, list) {
1022 		if ((op->can_id == mh->can_id) && (op->ifindex == ifindex) &&
1023 		    (op->flags & CAN_FD_FRAME) == (mh->flags & CAN_FD_FRAME)) {
1024 			list_del_rcu(&op->list);
1025 			bcm_remove_op(op);
1026 			return 1; /* done */
1027 		}
1028 	}
1029 
1030 	return 0; /* not found */
1031 }
1032 
1033 /*
1034  * bcm_read_op - read out a bcm_op and send it to the user (for bcm_sendmsg)
1035  */
1036 static int bcm_read_op(struct list_head *ops, struct bcm_msg_head *msg_head,
1037 		       int ifindex)
1038 {
1039 	struct bcm_op *op = bcm_find_op(ops, msg_head, ifindex);
1040 
1041 	if (!op)
1042 		return -EINVAL;
1043 
1044 	/* put current values into msg_head */
1045 	msg_head->flags   = op->flags;
1046 	msg_head->count   = op->count;
1047 	msg_head->ival1   = op->ival1;
1048 	msg_head->ival2   = op->ival2;
1049 	msg_head->nframes = op->nframes;
1050 
1051 	bcm_send_to_user(op, msg_head, op->frames, 0);
1052 
1053 	return MHSIZ;
1054 }
1055 
1056 /*
1057  * bcm_tx_setup - create or update a bcm tx op (for bcm_sendmsg)
1058  */
1059 static int bcm_tx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
1060 			int ifindex, struct sock *sk)
1061 {
1062 	struct bcm_sock *bo = bcm_sk(sk);
1063 	struct bcm_op *op;
1064 	struct canfd_frame *cf;
1065 	bool add_op_to_list = false;
1066 	unsigned int i;
1067 	int err;
1068 
1069 	/* we need a real device to send frames */
1070 	if (!ifindex)
1071 		return -ENODEV;
1072 
1073 	/* check nframes boundaries - we need at least one CAN frame */
1074 	if (msg_head->nframes < 1 || msg_head->nframes > MAX_NFRAMES)
1075 		return -EINVAL;
1076 
1077 	/* check timeval limitations */
1078 	if ((msg_head->flags & SETTIMER) && bcm_is_invalid_tv(msg_head))
1079 		return -EINVAL;
1080 
1081 	/* check the given can_id */
1082 	op = bcm_find_op(&bo->tx_ops, msg_head, ifindex);
1083 	if (op) {
1084 		void *new_frames;
1085 
1086 		/* update existing BCM operation */
1087 
1088 		/*
1089 		 * Do we need more space for the CAN frames than currently
1090 		 * allocated? -> This is a _really_ unusual use-case and
1091 		 * therefore (complexity / locking) it is not supported.
1092 		 */
1093 		if (msg_head->nframes > op->nframes)
1094 			return -E2BIG;
1095 
1096 		/* get new CAN frames content into a staging buffer before
1097 		 * locking: validate and normalize the frames there so that
1098 		 * bcm_can_tx() / bcm_tx_timeout_handler() never observe a
1099 		 * partially updated or unvalidated frame in op->frames
1100 		 */
1101 		new_frames = kmalloc(msg_head->nframes * op->cfsiz, GFP_KERNEL);
1102 		if (!new_frames)
1103 			return -ENOMEM;
1104 
1105 		for (i = 0; i < msg_head->nframes; i++) {
1106 
1107 			cf = new_frames + op->cfsiz * i;
1108 			err = memcpy_from_msg((u8 *)cf, msg, op->cfsiz);
1109 			if (err < 0) {
1110 				kfree(new_frames);
1111 				return err;
1112 			}
1113 
1114 			if (op->flags & CAN_FD_FRAME) {
1115 				if (cf->len > 64)
1116 					err = -EINVAL;
1117 			} else {
1118 				if (cf->len > 8)
1119 					err = -EINVAL;
1120 			}
1121 
1122 			if (err < 0) {
1123 				kfree(new_frames);
1124 				return err;
1125 			}
1126 
1127 			if (msg_head->flags & TX_CP_CAN_ID) {
1128 				/* copy can_id into frame */
1129 				cf->can_id = msg_head->can_id;
1130 			}
1131 		}
1132 
1133 		spin_lock_bh(&op->bcm_tx_lock);
1134 
1135 		/* update CAN frames content */
1136 		memcpy(op->frames, new_frames, msg_head->nframes * op->cfsiz);
1137 
1138 		op->flags = msg_head->flags;
1139 
1140 		if (op->nframes != msg_head->nframes ||
1141 		    op->flags & TX_RESET_MULTI_IDX) {
1142 			/* potentially update changed nframes */
1143 			op->nframes = msg_head->nframes;
1144 			/* restart multiple frame transmission */
1145 			op->currframe = 0;
1146 		}
1147 
1148 		if (op->flags & SETTIMER)
1149 			op->count = msg_head->count;
1150 
1151 		spin_unlock_bh(&op->bcm_tx_lock);
1152 
1153 		kfree(new_frames);
1154 
1155 	} else {
1156 		/* insert new BCM operation for the given can_id */
1157 
1158 		op = kzalloc(OPSIZ, GFP_KERNEL);
1159 		if (!op)
1160 			return -ENOMEM;
1161 
1162 		spin_lock_init(&op->bcm_tx_lock);
1163 		op->can_id = msg_head->can_id;
1164 		op->cfsiz = CFSIZ(msg_head->flags);
1165 		op->flags = msg_head->flags;
1166 		op->nframes = msg_head->nframes;
1167 
1168 		if (op->flags & SETTIMER)
1169 			op->count = msg_head->count;
1170 
1171 		/* create array for CAN frames and copy the data */
1172 		if (msg_head->nframes > 1) {
1173 			op->frames = kmalloc_array(msg_head->nframes,
1174 						   op->cfsiz,
1175 						   GFP_KERNEL);
1176 			if (!op->frames) {
1177 				kfree(op);
1178 				return -ENOMEM;
1179 			}
1180 		} else
1181 			op->frames = &op->sframe;
1182 
1183 		for (i = 0; i < msg_head->nframes; i++) {
1184 
1185 			cf = op->frames + op->cfsiz * i;
1186 			err = memcpy_from_msg((u8 *)cf, msg, op->cfsiz);
1187 			if (err < 0)
1188 				goto free_op;
1189 
1190 			if (op->flags & CAN_FD_FRAME) {
1191 				if (cf->len > 64)
1192 					err = -EINVAL;
1193 			} else {
1194 				if (cf->len > 8)
1195 					err = -EINVAL;
1196 			}
1197 
1198 			if (err < 0)
1199 				goto free_op;
1200 
1201 			if (msg_head->flags & TX_CP_CAN_ID) {
1202 				/* copy can_id into frame */
1203 				cf->can_id = msg_head->can_id;
1204 			}
1205 		}
1206 
1207 		/* tx_ops never compare with previous received messages */
1208 		op->last_frames = NULL;
1209 
1210 		/* bcm_can_tx / bcm_tx_timeout_handler needs this */
1211 		op->sk = sk;
1212 		sock_hold(sk);
1213 		op->ifindex = ifindex;
1214 
1215 		/* initialize uninitialized (kzalloc) structure */
1216 		hrtimer_setup(&op->timer, bcm_tx_timeout_handler, CLOCK_MONOTONIC,
1217 			      HRTIMER_MODE_REL_SOFT);
1218 
1219 		/* currently unused in tx_ops */
1220 		hrtimer_setup(&op->thrtimer, hrtimer_dummy_timeout, CLOCK_MONOTONIC,
1221 			      HRTIMER_MODE_REL_SOFT);
1222 
1223 		add_op_to_list = true;
1224 
1225 	} /* if ((op = bcm_find_op(&bo->tx_ops, msg_head->can_id, ifindex))) */
1226 
1227 	if (op->flags & SETTIMER) {
1228 		/* set timer values */
1229 		spin_lock_bh(&op->bcm_tx_lock);
1230 		op->ival1 = msg_head->ival1;
1231 		op->ival2 = msg_head->ival2;
1232 		op->kt_ival1 = bcm_timeval_to_ktime(msg_head->ival1);
1233 		op->kt_ival2 = bcm_timeval_to_ktime(msg_head->ival2);
1234 		spin_unlock_bh(&op->bcm_tx_lock);
1235 
1236 		/* disable an active timer due to zero values? */
1237 		if (!op->kt_ival1 && !op->kt_ival2)
1238 			hrtimer_cancel(&op->timer);
1239 	}
1240 
1241 	if (op->flags & STARTTIMER) {
1242 		hrtimer_cancel(&op->timer);
1243 		/* spec: send CAN frame when starting timer */
1244 		op->flags |= TX_ANNOUNCE;
1245 	}
1246 
1247 	/* add this bcm_op to the list of the tx_ops? */
1248 	if (add_op_to_list)
1249 		list_add_rcu(&op->list, &bo->tx_ops);
1250 
1251 	if (op->flags & TX_ANNOUNCE)
1252 		bcm_can_tx(op, NULL);
1253 
1254 	if (op->flags & STARTTIMER)
1255 		bcm_tx_start_timer(op);
1256 
1257 	return msg_head->nframes * op->cfsiz + MHSIZ;
1258 
1259 free_op:
1260 	if (op->frames != &op->sframe)
1261 		kfree(op->frames);
1262 	kfree(op);
1263 	return err;
1264 }
1265 
1266 static int bcm_rx_setup_rtr_check(struct bcm_msg_head *msg_head,
1267 				  struct bcm_op *op, void *new_frames)
1268 {
1269 	struct canfd_frame *frame0 = new_frames;
1270 
1271 	if (!(msg_head->flags & RX_RTR_FRAME))
1272 		return 0;
1273 
1274 	/* this frame is sent out as-is by bcm_can_tx() whenever a matching
1275 	 * remote request is received, so validate its length the same way
1276 	 * bcm_tx_setup() validates TX_SETUP frames before installing it
1277 	 */
1278 	if (msg_head->flags & CAN_FD_FRAME) {
1279 		if (frame0->len > 64)
1280 			return -EINVAL;
1281 	} else {
1282 		if (frame0->len > 8)
1283 			return -EINVAL;
1284 	}
1285 
1286 	/* funny feature in RX(!)_SETUP only for RTR-mode:
1287 	 * copy can_id into frame BUT without RTR-flag to
1288 	 * prevent a full-load-loopback-test ... ;-]
1289 	 * normalize this on the staged buffer, before it is
1290 	 * ever installed into op->frames.
1291 	 */
1292 	if ((msg_head->flags & TX_CP_CAN_ID) ||
1293 	    frame0->can_id == op->can_id)
1294 		frame0->can_id = op->can_id & ~CAN_RTR_FLAG;
1295 
1296 	return 0;
1297 }
1298 
1299 /*
1300  * bcm_rx_setup - create or update a bcm rx op (for bcm_sendmsg)
1301  */
1302 static int bcm_rx_setup(struct bcm_msg_head *msg_head, struct msghdr *msg,
1303 			int ifindex, struct sock *sk)
1304 {
1305 	struct bcm_sock *bo = bcm_sk(sk);
1306 	struct bcm_op *op;
1307 	int do_rx_register;
1308 	int new_op = 0;
1309 	int err = 0;
1310 
1311 	if ((msg_head->flags & RX_FILTER_ID) || (!(msg_head->nframes))) {
1312 		/* be robust against wrong usage ... */
1313 		msg_head->flags |= RX_FILTER_ID;
1314 		/* ignore trailing garbage */
1315 		msg_head->nframes = 0;
1316 	}
1317 
1318 	/* the first element contains the mux-mask => MAX_NFRAMES + 1  */
1319 	if (msg_head->nframes > MAX_NFRAMES + 1)
1320 		return -EINVAL;
1321 
1322 	if ((msg_head->flags & RX_RTR_FRAME) &&
1323 	    ((msg_head->nframes != 1) ||
1324 	     (!(msg_head->can_id & CAN_RTR_FLAG))))
1325 		return -EINVAL;
1326 
1327 	/* check timeval limitations */
1328 	if ((msg_head->flags & SETTIMER) && bcm_is_invalid_tv(msg_head))
1329 		return -EINVAL;
1330 
1331 	/* check the given can_id */
1332 	op = bcm_find_op(&bo->rx_ops, msg_head, ifindex);
1333 	if (op) {
1334 		void *new_frames = NULL;
1335 
1336 		/* update existing BCM operation */
1337 
1338 		/*
1339 		 * Do we need more space for the CAN frames than currently
1340 		 * allocated? -> This is a _really_ unusual use-case and
1341 		 * therefore (complexity / locking) it is not supported.
1342 		 */
1343 		if (msg_head->nframes > op->nframes)
1344 			return -E2BIG;
1345 
1346 		if (msg_head->nframes) {
1347 			/* get new CAN frames content before locking */
1348 			new_frames = kmalloc(msg_head->nframes * op->cfsiz,
1349 					     GFP_KERNEL);
1350 			if (!new_frames)
1351 				return -ENOMEM;
1352 
1353 			err = memcpy_from_msg(new_frames, msg,
1354 					      msg_head->nframes * op->cfsiz);
1355 			if (err < 0) {
1356 				kfree(new_frames);
1357 				return err;
1358 			}
1359 
1360 			err = bcm_rx_setup_rtr_check(msg_head, op, new_frames);
1361 			if (err < 0) {
1362 				kfree(new_frames);
1363 				return err;
1364 			}
1365 		}
1366 
1367 		spin_lock_bh(&op->bcm_rx_update_lock);
1368 		op->nframes = msg_head->nframes;
1369 		op->flags = msg_head->flags;
1370 
1371 		if (msg_head->nframes) {
1372 			/* update CAN frames content */
1373 			memcpy(op->frames, new_frames,
1374 			       msg_head->nframes * op->cfsiz);
1375 
1376 			/* clear last_frames to indicate 'nothing received' */
1377 			memset(op->last_frames, 0,
1378 			       msg_head->nframes * op->cfsiz);
1379 		}
1380 
1381 		if (msg_head->flags & SETTIMER) {
1382 			op->ival1 = msg_head->ival1;
1383 			op->ival2 = msg_head->ival2;
1384 			op->kt_ival1 = bcm_timeval_to_ktime(msg_head->ival1);
1385 			op->kt_ival2 = bcm_timeval_to_ktime(msg_head->ival2);
1386 			op->kt_lastmsg = 0;
1387 			op->if_detected = 0; /* reclaim ifindex in ANYDEV mode */
1388 		}
1389 		spin_unlock_bh(&op->bcm_rx_update_lock);
1390 
1391 		/* free temporary frames / kfree(NULL) is safe */
1392 		kfree(new_frames);
1393 
1394 		/* Don't register a new CAN filter for the rx_op update unless
1395 		 * a concurrent NETDEV_UNREGISTER notifier already tore down
1396 		 * the previous registration. In this case the receiver needs
1397 		 * to be re-registered here so that this update doesn't
1398 		 * silently stop delivering frames for the given ifindex.
1399 		 * Ops with ifindex = 0 (all CAN interfaces) never carry a
1400 		 * tracked rx_reg_dev and stay registered as-is.
1401 		 */
1402 		do_rx_register = (ifindex && !op->rx_reg_dev) ? 1 : 0;
1403 
1404 	} else {
1405 		/* insert new BCM operation for the given can_id */
1406 		op = kzalloc(OPSIZ, GFP_KERNEL);
1407 		if (!op)
1408 			return -ENOMEM;
1409 
1410 		spin_lock_init(&op->bcm_tx_lock);
1411 		spin_lock_init(&op->bcm_rx_update_lock);
1412 		op->can_id = msg_head->can_id;
1413 		op->nframes = msg_head->nframes;
1414 		op->cfsiz = CFSIZ(msg_head->flags);
1415 		op->flags = msg_head->flags;
1416 
1417 		if (msg_head->nframes > 1) {
1418 			/* create array for CAN frames and copy the data */
1419 			op->frames = kmalloc_array(msg_head->nframes,
1420 						   op->cfsiz,
1421 						   GFP_KERNEL);
1422 			if (!op->frames) {
1423 				kfree(op);
1424 				return -ENOMEM;
1425 			}
1426 
1427 			/* create and init array for received CAN frames */
1428 			op->last_frames = kcalloc(msg_head->nframes,
1429 						  op->cfsiz,
1430 						  GFP_KERNEL);
1431 			if (!op->last_frames) {
1432 				kfree(op->frames);
1433 				kfree(op);
1434 				return -ENOMEM;
1435 			}
1436 
1437 		} else {
1438 			op->frames = &op->sframe;
1439 			op->last_frames = &op->last_sframe;
1440 		}
1441 
1442 		if (msg_head->nframes) {
1443 			err = memcpy_from_msg(op->frames, msg,
1444 					      msg_head->nframes * op->cfsiz);
1445 			if (err < 0)
1446 				goto free_op;
1447 
1448 			err = bcm_rx_setup_rtr_check(msg_head, op, op->frames);
1449 			if (err < 0)
1450 				goto free_op;
1451 		}
1452 
1453 		/* bcm_can_tx / bcm_tx_timeout_handler needs this */
1454 		op->sk = sk;
1455 		sock_hold(sk);
1456 		op->ifindex = ifindex;
1457 
1458 		/* ifindex for timeout events w/o previous frame reception */
1459 		op->rx_ifindex = ifindex;
1460 
1461 		/* initialize uninitialized (kzalloc) structure */
1462 		hrtimer_setup(&op->timer, bcm_rx_timeout_handler, CLOCK_MONOTONIC,
1463 			      HRTIMER_MODE_REL_SOFT);
1464 		hrtimer_setup(&op->thrtimer, bcm_rx_thr_handler, CLOCK_MONOTONIC,
1465 			      HRTIMER_MODE_REL_SOFT);
1466 
1467 		/* call can_rx_register() */
1468 		do_rx_register = 1;
1469 		new_op = 1;
1470 
1471 	} /* if ((op = bcm_find_op(&bo->rx_ops, msg_head->can_id, ifindex))) */
1472 
1473 	/* check flags */
1474 
1475 	if (op->flags & RX_RTR_FRAME) {
1476 		/* no timers in RTR-mode */
1477 		hrtimer_cancel(&op->thrtimer);
1478 		hrtimer_cancel(&op->timer);
1479 	} else {
1480 		if (op->flags & SETTIMER) {
1481 
1482 			/* set timers (locked) for newly created op */
1483 			if (new_op) {
1484 				spin_lock_bh(&op->bcm_rx_update_lock);
1485 				op->ival1 = msg_head->ival1;
1486 				op->ival2 = msg_head->ival2;
1487 				op->kt_ival1 = bcm_timeval_to_ktime(msg_head->ival1);
1488 				op->kt_ival2 = bcm_timeval_to_ktime(msg_head->ival2);
1489 				op->kt_lastmsg = 0;
1490 				spin_unlock_bh(&op->bcm_rx_update_lock);
1491 			}
1492 
1493 			/* disable an active timer due to zero value? */
1494 			if (!op->kt_ival1)
1495 				hrtimer_cancel(&op->timer);
1496 
1497 			/*
1498 			 * In any case cancel the throttle timer, flush
1499 			 * potentially blocked msgs and reset throttle handling
1500 			 */
1501 			hrtimer_cancel(&op->thrtimer);
1502 
1503 			spin_lock_bh(&op->bcm_rx_update_lock);
1504 			bcm_rx_thr_flush(op);
1505 			spin_unlock_bh(&op->bcm_rx_update_lock);
1506 		}
1507 
1508 		if ((op->flags & STARTTIMER) && op->kt_ival1)
1509 			hrtimer_start(&op->timer, op->kt_ival1,
1510 				      HRTIMER_MODE_REL_SOFT);
1511 	}
1512 
1513 	/* now we can register for can_ids, if we added a new bcm_op
1514 	 * or need to re-register after a NETDEV_UNREGISTER tore down
1515 	 * the previous registration of an existing op
1516 	 */
1517 	if (do_rx_register) {
1518 		if (ifindex) {
1519 			struct net_device *dev;
1520 
1521 			dev = dev_get_by_index(sock_net(sk), ifindex);
1522 			if (dev) {
1523 				err = can_rx_register(sock_net(sk), dev,
1524 						      op->can_id,
1525 						      REGMASK(op->can_id),
1526 						      bcm_rx_handler, op,
1527 						      sock_i_ino(sk), sk);
1528 
1529 				/* keep a tracked reference so that a later
1530 				 * unregister can safely reach the device even
1531 				 * if a concurrent NETDEV_UNREGISTER has
1532 				 * already unlisted it by ifindex
1533 				 */
1534 				if (!err) {
1535 					op->rx_reg_dev = dev;
1536 					netdev_hold(dev,
1537 						    &op->rx_reg_dev_tracker,
1538 						    GFP_KERNEL);
1539 				}
1540 				dev_put(dev);
1541 			} else {
1542 				/* the requested device is gone - do not
1543 				 * silently succeed without registering
1544 				 */
1545 				err = -ENODEV;
1546 			}
1547 
1548 		} else {
1549 			err = can_rx_register(sock_net(sk), NULL, op->can_id,
1550 					      REGMASK(op->can_id),
1551 					      bcm_rx_handler, op,
1552 					      sock_i_ino(sk), sk);
1553 		}
1554 
1555 		if (err) {
1556 			/* newly created bcm rx op is broken -> remove it */
1557 			if (new_op) {
1558 				bcm_remove_op(op);
1559 				return err;
1560 			}
1561 
1562 			/* an existing op just stays unregistered.
1563 			 * Cancel op->timer and (defensively) op->thrtimer.
1564 			 * Other settings can't be reached until the next
1565 			 * successful RX_SETUP.
1566 			 */
1567 			hrtimer_cancel(&op->timer);
1568 			hrtimer_cancel(&op->thrtimer);
1569 			return err;
1570 		}
1571 
1572 		/* add a new bcm_op to the list of the rx_ops */
1573 		if (new_op)
1574 			list_add_rcu(&op->list, &bo->rx_ops);
1575 	}
1576 
1577 	return msg_head->nframes * op->cfsiz + MHSIZ;
1578 
1579 free_op:
1580 	if (op->frames != &op->sframe)
1581 		kfree(op->frames);
1582 	if (op->last_frames != &op->last_sframe)
1583 		kfree(op->last_frames);
1584 	kfree(op);
1585 	return err;
1586 }
1587 
1588 /*
1589  * bcm_tx_send - send a single CAN frame to the CAN interface (for bcm_sendmsg)
1590  */
1591 static int bcm_tx_send(struct msghdr *msg, int ifindex, struct sock *sk,
1592 		       int cfsiz)
1593 {
1594 	struct sk_buff *skb;
1595 	struct can_skb_ext *csx;
1596 	struct net_device *dev;
1597 	int err;
1598 
1599 	/* we need a real device to send frames */
1600 	if (!ifindex)
1601 		return -ENODEV;
1602 
1603 	skb = alloc_skb(cfsiz, GFP_KERNEL);
1604 	if (!skb)
1605 		return -ENOMEM;
1606 
1607 	csx = can_skb_ext_add(skb);
1608 	if (!csx) {
1609 		kfree_skb(skb);
1610 		return -ENOMEM;
1611 	}
1612 
1613 	err = memcpy_from_msg(skb_put(skb, cfsiz), msg, cfsiz);
1614 	if (err < 0) {
1615 		kfree_skb(skb);
1616 		return err;
1617 	}
1618 
1619 	dev = dev_get_by_index(sock_net(sk), ifindex);
1620 	if (!dev) {
1621 		kfree_skb(skb);
1622 		return -ENODEV;
1623 	}
1624 
1625 	csx->can_iif = dev->ifindex;
1626 	skb->dev = dev;
1627 	can_skb_set_owner(skb, sk);
1628 	err = can_send(skb, 1); /* send with loopback */
1629 	dev_put(dev);
1630 
1631 	if (err)
1632 		return err;
1633 
1634 	return cfsiz + MHSIZ;
1635 }
1636 
1637 /*
1638  * bcm_sendmsg - process BCM commands (opcodes) from the userspace
1639  */
1640 static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
1641 {
1642 	struct sock *sk = sock->sk;
1643 	struct bcm_sock *bo = bcm_sk(sk);
1644 	int ifindex;
1645 	struct bcm_msg_head msg_head;
1646 	int cfsiz;
1647 	int ret; /* read bytes or error codes as return value */
1648 
1649 	/* Lockless fast-path check for bound socket */
1650 	if (!READ_ONCE(bo->bound))
1651 		return -ENOTCONN;
1652 
1653 	/* check for valid message length from userspace */
1654 	if (size < MHSIZ)
1655 		return -EINVAL;
1656 
1657 	/* read message head information */
1658 	ret = memcpy_from_msg((u8 *)&msg_head, msg, MHSIZ);
1659 	if (ret < 0)
1660 		return ret;
1661 
1662 	cfsiz = CFSIZ(msg_head.flags);
1663 	if ((size - MHSIZ) % cfsiz)
1664 		return -EINVAL;
1665 
1666 	lock_sock(sk);
1667 
1668 	/* Re-validate under the socket lock: a concurrent bcm_notify()
1669 	 * may have unbound this socket (device removal) after the
1670 	 * lockless fast-path check above. bo->ifindex is only ever
1671 	 * mutated under lock_sock(), so reading it here - instead of
1672 	 * before taking the lock - guarantees it can't be observed
1673 	 * torn against bo->bound.
1674 	 */
1675 	if (!bo->bound) {
1676 		ret = -ENOTCONN;
1677 		goto out_release;
1678 	}
1679 
1680 	/* default ifindex for this bcm_op */
1681 	ifindex = bo->ifindex;
1682 
1683 	/* check for alternative ifindex for this bcm_op */
1684 
1685 	if (!ifindex && msg->msg_name) {
1686 		/* no bound device as default => check msg_name */
1687 		DECLARE_SOCKADDR(struct sockaddr_can *, addr, msg->msg_name);
1688 
1689 		if (msg->msg_namelen < BCM_MIN_NAMELEN) {
1690 			ret = -EINVAL;
1691 			goto out_release;
1692 		}
1693 
1694 		if (addr->can_family != AF_CAN) {
1695 			ret = -EINVAL;
1696 			goto out_release;
1697 		}
1698 
1699 		/* ifindex from sendto() */
1700 		ifindex = addr->can_ifindex;
1701 
1702 		if (ifindex) {
1703 			struct net_device *dev;
1704 
1705 			dev = dev_get_by_index(sock_net(sk), ifindex);
1706 			if (!dev) {
1707 				ret = -ENODEV;
1708 				goto out_release;
1709 			}
1710 
1711 			if (!can_get_ml_priv(dev)) {
1712 				dev_put(dev);
1713 				ret = -ENODEV;
1714 				goto out_release;
1715 			}
1716 
1717 			dev_put(dev);
1718 		}
1719 	}
1720 
1721 	switch (msg_head.opcode) {
1722 
1723 	case TX_SETUP:
1724 		ret = bcm_tx_setup(&msg_head, msg, ifindex, sk);
1725 		break;
1726 
1727 	case RX_SETUP:
1728 		ret = bcm_rx_setup(&msg_head, msg, ifindex, sk);
1729 		break;
1730 
1731 	case TX_DELETE:
1732 		if (bcm_delete_tx_op(&bo->tx_ops, &msg_head, ifindex))
1733 			ret = MHSIZ;
1734 		else
1735 			ret = -EINVAL;
1736 		break;
1737 
1738 	case RX_DELETE:
1739 		if (bcm_delete_rx_op(&bo->rx_ops, &msg_head, ifindex))
1740 			ret = MHSIZ;
1741 		else
1742 			ret = -EINVAL;
1743 		break;
1744 
1745 	case TX_READ:
1746 		/* reuse msg_head for the reply to TX_READ */
1747 		msg_head.opcode  = TX_STATUS;
1748 		ret = bcm_read_op(&bo->tx_ops, &msg_head, ifindex);
1749 		break;
1750 
1751 	case RX_READ:
1752 		/* reuse msg_head for the reply to RX_READ */
1753 		msg_head.opcode  = RX_STATUS;
1754 		ret = bcm_read_op(&bo->rx_ops, &msg_head, ifindex);
1755 		break;
1756 
1757 	case TX_SEND:
1758 		/* we need exactly one CAN frame behind the msg head */
1759 		if ((msg_head.nframes != 1) || (size != cfsiz + MHSIZ))
1760 			ret = -EINVAL;
1761 		else
1762 			ret = bcm_tx_send(msg, ifindex, sk, cfsiz);
1763 		break;
1764 
1765 	default:
1766 		ret = -EINVAL;
1767 		break;
1768 	}
1769 
1770 out_release:
1771 	release_sock(sk);
1772 
1773 	return ret;
1774 }
1775 
1776 /*
1777  * notification handler for netdevice status changes
1778  */
1779 static void bcm_notify(struct bcm_sock *bo, unsigned long msg,
1780 		       struct net_device *dev)
1781 {
1782 	struct sock *sk = &bo->sk;
1783 	struct bcm_op *op;
1784 	int notify_enodev = 0;
1785 
1786 	if (!net_eq(dev_net(dev), sock_net(sk)))
1787 		return;
1788 
1789 	switch (msg) {
1790 
1791 	case NETDEV_UNREGISTER:
1792 		lock_sock(sk);
1793 
1794 		/* rx_ops: remove device specific receive entries */
1795 		list_for_each_entry(op, &bo->rx_ops, list) {
1796 			if (op->rx_reg_dev == dev)
1797 				bcm_rx_unreg(dev, op);
1798 
1799 			/* release an ANYDEV op's claim (see bcm_rx_handler())
1800 			 * on this now confirmed-gone interface.
1801 			 */
1802 			if (!op->ifindex) {
1803 				spin_lock_bh(&op->bcm_rx_update_lock);
1804 				if (op->if_detected == dev->ifindex)
1805 					op->if_detected = 0;
1806 				spin_unlock_bh(&op->bcm_rx_update_lock);
1807 			}
1808 		}
1809 
1810 		/* tx_ops: stop device specific cyclic transmissions on the
1811 		 * vanishing ifindex. Cancelling the timer is enough to stop
1812 		 * cyclic bcm_can_tx() calls as there is no re-arming.
1813 		 */
1814 		list_for_each_entry(op, &bo->tx_ops, list)
1815 			if (op->ifindex == dev->ifindex)
1816 				hrtimer_cancel(&op->timer);
1817 
1818 		/* remove device reference, if this is our bound device */
1819 		if (bo->bound && bo->ifindex == dev->ifindex) {
1820 #if IS_ENABLED(CONFIG_PROC_FS)
1821 			if (sock_net(sk)->can.bcmproc_dir && bo->bcm_proc_read) {
1822 				remove_proc_entry(bo->procname, sock_net(sk)->can.bcmproc_dir);
1823 				bo->bcm_proc_read = NULL;
1824 			}
1825 #endif
1826 			/* Paired with the lockless fast-path check in
1827 			 * bcm_sendmsg(); bo->ifindex itself is only ever
1828 			 * accessed under lock_sock() so it needs no
1829 			 * annotation.
1830 			 */
1831 			WRITE_ONCE(bo->bound, 0);
1832 			bo->ifindex = 0;
1833 			notify_enodev = 1;
1834 		}
1835 
1836 		release_sock(sk);
1837 
1838 		if (notify_enodev) {
1839 			sk->sk_err = ENODEV;
1840 			if (!sock_flag(sk, SOCK_DEAD))
1841 				sk_error_report(sk);
1842 		}
1843 		break;
1844 
1845 	case NETDEV_DOWN:
1846 		if (bo->bound && bo->ifindex == dev->ifindex) {
1847 			sk->sk_err = ENETDOWN;
1848 			if (!sock_flag(sk, SOCK_DEAD))
1849 				sk_error_report(sk);
1850 		}
1851 	}
1852 }
1853 
1854 static int bcm_notifier(struct notifier_block *nb, unsigned long msg,
1855 			void *ptr)
1856 {
1857 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1858 
1859 	if (!can_get_ml_priv(dev))
1860 		return NOTIFY_DONE;
1861 	if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
1862 		return NOTIFY_DONE;
1863 	if (unlikely(bcm_busy_notifier)) /* Check for reentrant bug. */
1864 		return NOTIFY_DONE;
1865 
1866 	spin_lock(&bcm_notifier_lock);
1867 	list_for_each_entry(bcm_busy_notifier, &bcm_notifier_list, notifier) {
1868 		spin_unlock(&bcm_notifier_lock);
1869 		bcm_notify(bcm_busy_notifier, msg, dev);
1870 		spin_lock(&bcm_notifier_lock);
1871 	}
1872 	bcm_busy_notifier = NULL;
1873 	spin_unlock(&bcm_notifier_lock);
1874 	return NOTIFY_DONE;
1875 }
1876 
1877 /*
1878  * initial settings for all BCM sockets to be set at socket creation time
1879  */
1880 static int bcm_init(struct sock *sk)
1881 {
1882 	struct bcm_sock *bo = bcm_sk(sk);
1883 
1884 	bo->bound            = 0;
1885 	bo->ifindex          = 0;
1886 	bo->dropped_usr_msgs = 0;
1887 	bo->bcm_proc_read    = NULL;
1888 
1889 	INIT_LIST_HEAD(&bo->tx_ops);
1890 	INIT_LIST_HEAD(&bo->rx_ops);
1891 
1892 	/* set notifier */
1893 	spin_lock(&bcm_notifier_lock);
1894 	list_add_tail(&bo->notifier, &bcm_notifier_list);
1895 	spin_unlock(&bcm_notifier_lock);
1896 
1897 	return 0;
1898 }
1899 
1900 /*
1901  * standard socket functions
1902  */
1903 static int bcm_release(struct socket *sock)
1904 {
1905 	struct sock *sk = sock->sk;
1906 	struct net *net;
1907 	struct bcm_sock *bo;
1908 	struct bcm_op *op, *next;
1909 
1910 	if (!sk)
1911 		return 0;
1912 
1913 	net = sock_net(sk);
1914 	bo = bcm_sk(sk);
1915 
1916 	/* remove bcm_ops, timer, rx_unregister(), etc. */
1917 
1918 	spin_lock(&bcm_notifier_lock);
1919 	while (bcm_busy_notifier == bo) {
1920 		spin_unlock(&bcm_notifier_lock);
1921 		schedule_timeout_uninterruptible(1);
1922 		spin_lock(&bcm_notifier_lock);
1923 	}
1924 	list_del(&bo->notifier);
1925 	spin_unlock(&bcm_notifier_lock);
1926 
1927 	/* bcm_notify() can not access this socket anymore */
1928 	lock_sock(sk);
1929 
1930 #if IS_ENABLED(CONFIG_PROC_FS)
1931 	/* remove procfs entry */
1932 	if (net->can.bcmproc_dir && bo->bcm_proc_read)
1933 		remove_proc_entry(bo->procname, net->can.bcmproc_dir);
1934 #endif /* CONFIG_PROC_FS */
1935 
1936 	list_for_each_entry_safe(op, next, &bo->tx_ops, list) {
1937 		list_del_rcu(&op->list);
1938 		bcm_remove_op(op);
1939 	}
1940 
1941 	list_for_each_entry(op, &bo->rx_ops, list) {
1942 		if (op->ifindex) {
1943 			/* Only remove subscriptions that had not been removed
1944 			 * in bcm_notify(). op->rx_reg_dev keeps the device's
1945 			 * receive lists accessible.
1946 			 */
1947 			if (op->rx_reg_dev)
1948 				bcm_rx_unreg(op->rx_reg_dev, op);
1949 		} else {
1950 			can_rx_unregister(net, NULL, op->can_id,
1951 					  REGMASK(op->can_id),
1952 					  bcm_rx_handler, op);
1953 		}
1954 		cond_resched();
1955 	}
1956 
1957 	synchronize_rcu();
1958 
1959 	list_for_each_entry_safe(op, next, &bo->rx_ops, list) {
1960 		list_del_rcu(&op->list);
1961 		bcm_remove_op(op);
1962 	}
1963 
1964 	/* remove device reference */
1965 	if (bo->bound) {
1966 		WRITE_ONCE(bo->bound, 0);
1967 		bo->ifindex = 0;
1968 	}
1969 
1970 	sock_orphan(sk);
1971 	sock->sk = NULL;
1972 
1973 	release_sock(sk);
1974 	sock_prot_inuse_add(net, sk->sk_prot, -1);
1975 	sock_put(sk);
1976 
1977 	return 0;
1978 }
1979 
1980 static int bcm_connect(struct socket *sock, struct sockaddr_unsized *uaddr, int len,
1981 		       int flags)
1982 {
1983 	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1984 	struct sock *sk = sock->sk;
1985 	struct bcm_sock *bo = bcm_sk(sk);
1986 	struct net *net = sock_net(sk);
1987 	int ret = 0;
1988 
1989 	if (len < BCM_MIN_NAMELEN)
1990 		return -EINVAL;
1991 
1992 	lock_sock(sk);
1993 
1994 	if (bo->bound) {
1995 		ret = -EISCONN;
1996 		goto fail;
1997 	}
1998 
1999 	/* bind a device to this socket */
2000 	if (addr->can_ifindex) {
2001 		struct net_device *dev;
2002 
2003 		dev = dev_get_by_index(net, addr->can_ifindex);
2004 		if (!dev) {
2005 			ret = -ENODEV;
2006 			goto fail;
2007 		}
2008 		if (!can_get_ml_priv(dev)) {
2009 			dev_put(dev);
2010 			ret = -ENODEV;
2011 			goto fail;
2012 		}
2013 
2014 		bo->ifindex = dev->ifindex;
2015 		dev_put(dev);
2016 
2017 	} else {
2018 		/* no interface reference for ifindex = 0 ('any' CAN device) */
2019 		bo->ifindex = 0;
2020 	}
2021 
2022 #if IS_ENABLED(CONFIG_PROC_FS)
2023 	if (net->can.bcmproc_dir) {
2024 		/* use unique socket inode number as filename */
2025 		snprintf(bo->procname, sizeof(bo->procname),
2026 			 "%llu", sock_i_ino(sk));
2027 		bo->bcm_proc_read = proc_create_net_single(bo->procname, 0644,
2028 						     net->can.bcmproc_dir,
2029 						     bcm_proc_show, sk);
2030 		if (!bo->bcm_proc_read) {
2031 			ret = -ENOMEM;
2032 			goto fail;
2033 		}
2034 	}
2035 #endif /* CONFIG_PROC_FS */
2036 
2037 	/* bo->ifindex above is fully assigned before this point; pairs
2038 	 * with the lockless fast-path check in bcm_sendmsg()
2039 	 */
2040 	WRITE_ONCE(bo->bound, 1);
2041 
2042 fail:
2043 	release_sock(sk);
2044 
2045 	return ret;
2046 }
2047 
2048 static int bcm_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
2049 		       int flags)
2050 {
2051 	struct sock *sk = sock->sk;
2052 	struct sk_buff *skb;
2053 	int error = 0;
2054 	int err;
2055 
2056 	skb = skb_recv_datagram(sk, flags, &error);
2057 	if (!skb)
2058 		return error;
2059 
2060 	if (skb->len < size)
2061 		size = skb->len;
2062 
2063 	err = memcpy_to_msg(msg, skb->data, size);
2064 	if (err < 0) {
2065 		skb_free_datagram(sk, skb);
2066 		return err;
2067 	}
2068 
2069 	sock_recv_cmsgs(msg, sk, skb);
2070 
2071 	if (msg->msg_name) {
2072 		__sockaddr_check_size(BCM_MIN_NAMELEN);
2073 		msg->msg_namelen = BCM_MIN_NAMELEN;
2074 		memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
2075 	}
2076 
2077 	/* assign the flags that have been recorded in bcm_send_to_user() */
2078 	msg->msg_flags |= *(bcm_flags(skb));
2079 
2080 	skb_free_datagram(sk, skb);
2081 
2082 	return size;
2083 }
2084 
2085 static int bcm_sock_no_ioctlcmd(struct socket *sock, unsigned int cmd,
2086 				unsigned long arg)
2087 {
2088 	/* no ioctls for socket layer -> hand it down to NIC layer */
2089 	return -ENOIOCTLCMD;
2090 }
2091 
2092 static const struct proto_ops bcm_ops = {
2093 	.family        = PF_CAN,
2094 	.release       = bcm_release,
2095 	.bind          = sock_no_bind,
2096 	.connect       = bcm_connect,
2097 	.socketpair    = sock_no_socketpair,
2098 	.accept        = sock_no_accept,
2099 	.getname       = sock_no_getname,
2100 	.poll          = datagram_poll,
2101 	.ioctl         = bcm_sock_no_ioctlcmd,
2102 	.gettstamp     = sock_gettstamp,
2103 	.listen        = sock_no_listen,
2104 	.shutdown      = sock_no_shutdown,
2105 	.sendmsg       = bcm_sendmsg,
2106 	.recvmsg       = bcm_recvmsg,
2107 	.mmap          = sock_no_mmap,
2108 };
2109 
2110 static struct proto bcm_proto __read_mostly = {
2111 	.name       = "CAN_BCM",
2112 	.owner      = THIS_MODULE,
2113 	.obj_size   = sizeof(struct bcm_sock),
2114 	.init       = bcm_init,
2115 };
2116 
2117 static const struct can_proto bcm_can_proto = {
2118 	.type       = SOCK_DGRAM,
2119 	.protocol   = CAN_BCM,
2120 	.ops        = &bcm_ops,
2121 	.prot       = &bcm_proto,
2122 };
2123 
2124 static int canbcm_pernet_init(struct net *net)
2125 {
2126 #if IS_ENABLED(CONFIG_PROC_FS)
2127 	/* create /proc/net/can-bcm directory */
2128 	net->can.bcmproc_dir = proc_net_mkdir(net, "can-bcm", net->proc_net);
2129 #endif /* CONFIG_PROC_FS */
2130 
2131 	return 0;
2132 }
2133 
2134 static void canbcm_pernet_exit(struct net *net)
2135 {
2136 #if IS_ENABLED(CONFIG_PROC_FS)
2137 	/* remove /proc/net/can-bcm directory */
2138 	if (net->can.bcmproc_dir)
2139 		remove_proc_entry("can-bcm", net->proc_net);
2140 #endif /* CONFIG_PROC_FS */
2141 }
2142 
2143 static struct pernet_operations canbcm_pernet_ops __read_mostly = {
2144 	.init = canbcm_pernet_init,
2145 	.exit = canbcm_pernet_exit,
2146 };
2147 
2148 static struct notifier_block canbcm_notifier = {
2149 	.notifier_call = bcm_notifier
2150 };
2151 
2152 static int __init bcm_module_init(void)
2153 {
2154 	int err;
2155 
2156 	bcm_wq = alloc_workqueue("can-bcm-wq", WQ_UNBOUND, 0);
2157 	if (!bcm_wq)
2158 		return -ENOMEM;
2159 
2160 	pr_info("can: broadcast manager protocol\n");
2161 
2162 	err = register_pernet_subsys(&canbcm_pernet_ops);
2163 	if (err)
2164 		goto register_pernet_failed;
2165 
2166 	err = register_netdevice_notifier(&canbcm_notifier);
2167 	if (err)
2168 		goto register_notifier_failed;
2169 
2170 	err = can_proto_register(&bcm_can_proto);
2171 	if (err < 0) {
2172 		printk(KERN_ERR "can: registration of bcm protocol failed\n");
2173 		goto register_proto_failed;
2174 	}
2175 
2176 	return 0;
2177 
2178 register_proto_failed:
2179 	unregister_netdevice_notifier(&canbcm_notifier);
2180 register_notifier_failed:
2181 	unregister_pernet_subsys(&canbcm_pernet_ops);
2182 register_pernet_failed:
2183 	destroy_workqueue(bcm_wq);
2184 	return err;
2185 }
2186 
2187 static void __exit bcm_module_exit(void)
2188 {
2189 	can_proto_unregister(&bcm_can_proto);
2190 	unregister_netdevice_notifier(&canbcm_notifier);
2191 	unregister_pernet_subsys(&canbcm_pernet_ops);
2192 	rcu_barrier();
2193 	destroy_workqueue(bcm_wq);
2194 }
2195 
2196 module_init(bcm_module_init);
2197 module_exit(bcm_module_exit);
2198