xref: /linux/net/can/isotp.c (revision 900f27fb797c7eaf0b84b7a6516613e19746bc4e)
1 // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
2 /* isotp.c - ISO 15765-2 CAN transport protocol for protocol family CAN
3  *
4  * This implementation does not provide ISO-TP specific return values to the
5  * userspace.
6  *
7  * - RX path timeout of data reception leads to -ETIMEDOUT
8  * - RX path SN mismatch leads to -EILSEQ
9  * - RX path data reception with wrong padding leads to -EBADMSG
10  * - TX path flowcontrol reception timeout leads to -ECOMM
11  * - TX path flowcontrol reception overflow leads to -EMSGSIZE
12  * - TX path flowcontrol reception with wrong layout/padding leads to -EBADMSG
13  * - when a transfer (tx) is on the run the next write() blocks until it's done
14  * - use CAN_ISOTP_WAIT_TX_DONE flag to block the caller until the PDU is sent
15  * - as we have static buffers the check whether the PDU fits into the buffer
16  *   is done at FF reception time (no support for sending 'wait frames')
17  *
18  * Copyright (c) 2020 Volkswagen Group Electronic Research
19  * All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  * 3. Neither the name of Volkswagen nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * Alternatively, provided that this notice is retained in full, this
34  * software may be distributed under the terms of the GNU General
35  * Public License ("GPL") version 2, in which case the provisions of the
36  * GPL apply INSTEAD OF those given above.
37  *
38  * The provided data structures and external interfaces from this code
39  * are not restricted to be used by modules with a GPL compatible license.
40  *
41  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
42  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
43  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
44  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
45  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
46  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
47  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
48  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
49  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
50  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
51  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
52  * DAMAGE.
53  */
54 
55 #include <linux/module.h>
56 #include <linux/init.h>
57 #include <linux/interrupt.h>
58 #include <linux/spinlock.h>
59 #include <linux/hrtimer.h>
60 #include <linux/wait.h>
61 #include <linux/uio.h>
62 #include <linux/net.h>
63 #include <linux/netdevice.h>
64 #include <linux/socket.h>
65 #include <linux/if_arp.h>
66 #include <linux/skbuff.h>
67 #include <linux/can.h>
68 #include <linux/can/core.h>
69 #include <linux/can/skb.h>
70 #include <linux/can/isotp.h>
71 #include <linux/slab.h>
72 #include <net/can.h>
73 #include <net/sock.h>
74 #include <net/net_namespace.h>
75 
76 MODULE_DESCRIPTION("PF_CAN ISO 15765-2 transport protocol");
77 MODULE_LICENSE("Dual BSD/GPL");
78 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
79 MODULE_ALIAS("can-proto-6");
80 
81 #define ISOTP_MIN_NAMELEN CAN_REQUIRED_SIZE(struct sockaddr_can, can_addr.tp)
82 
83 #define SINGLE_MASK(id) (((id) & CAN_EFF_FLAG) ? \
84 			 (CAN_EFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG) : \
85 			 (CAN_SFF_MASK | CAN_EFF_FLAG | CAN_RTR_FLAG))
86 
87 /* Since ISO 15765-2:2016 the CAN isotp protocol supports more than 4095
88  * byte per ISO PDU as the FF_DL can take full 32 bit values (4 Gbyte).
89  * We would need some good concept to handle this between user space and
90  * kernel space. For now set the static buffer to something about 8 kbyte
91  * to be able to test this new functionality.
92  */
93 #define DEFAULT_MAX_PDU_SIZE 8300
94 
95 /* maximum PDU size before ISO 15765-2:2016 extension was 4095 */
96 #define MAX_12BIT_PDU_SIZE 4095
97 
98 /* limit the isotp pdu size from the optional module parameter to 1MByte */
99 #define MAX_PDU_SIZE (1025 * 1024U)
100 
101 static unsigned int max_pdu_size __read_mostly = DEFAULT_MAX_PDU_SIZE;
102 module_param(max_pdu_size, uint, 0444);
103 MODULE_PARM_DESC(max_pdu_size, "maximum isotp pdu size (default "
104 		 __stringify(DEFAULT_MAX_PDU_SIZE) ")");
105 
106 /* N_PCI type values in bits 7-4 of N_PCI bytes */
107 #define N_PCI_SF 0x00	/* single frame */
108 #define N_PCI_FF 0x10	/* first frame */
109 #define N_PCI_CF 0x20	/* consecutive frame */
110 #define N_PCI_FC 0x30	/* flow control */
111 
112 #define N_PCI_SZ 1	/* size of the PCI byte #1 */
113 #define SF_PCI_SZ4 1	/* size of SingleFrame PCI including 4 bit SF_DL */
114 #define SF_PCI_SZ8 2	/* size of SingleFrame PCI including 8 bit SF_DL */
115 #define FF_PCI_SZ12 2	/* size of FirstFrame PCI including 12 bit FF_DL */
116 #define FF_PCI_SZ32 6	/* size of FirstFrame PCI including 32 bit FF_DL */
117 #define FC_CONTENT_SZ 3	/* flow control content size in byte (FS/BS/STmin) */
118 
119 #define ISOTP_CHECK_PADDING (CAN_ISOTP_CHK_PAD_LEN | CAN_ISOTP_CHK_PAD_DATA)
120 #define ISOTP_ALL_BC_FLAGS (CAN_ISOTP_SF_BROADCAST | CAN_ISOTP_CF_BROADCAST)
121 
122 /* Flow Status given in FC frame */
123 #define ISOTP_FC_CTS 0		/* clear to send */
124 #define ISOTP_FC_WT 1		/* wait */
125 #define ISOTP_FC_OVFLW 2	/* overflow */
126 
127 #define ISOTP_FC_TIMEOUT 1	/* 1 sec */
128 #define ISOTP_ECHO_TIMEOUT 2	/* 2 secs */
129 
130 enum {
131 	ISOTP_IDLE = 0,
132 	ISOTP_WAIT_FIRST_FC,
133 	ISOTP_WAIT_FC,
134 	ISOTP_WAIT_DATA,
135 	ISOTP_SENDING,
136 	ISOTP_SHUTDOWN,
137 };
138 
139 struct tpcon {
140 	u8 *buf;
141 	unsigned int buflen;
142 	unsigned int len;
143 	unsigned int idx;
144 	u32 state;
145 	u8 bs;
146 	u8 sn;
147 	u8 ll_dl;
148 	u8 sbuf[DEFAULT_MAX_PDU_SIZE];
149 };
150 
151 struct isotp_sock {
152 	struct sock sk;
153 	int bound;
154 	int ifindex;
155 	canid_t txid;
156 	canid_t rxid;
157 	ktime_t tx_gap;
158 	ktime_t lastrxcf_tstamp;
159 	struct hrtimer rxtimer, txtimer, txfrtimer;
160 	struct can_isotp_options opt;
161 	struct can_isotp_fc_options rxfc, txfc;
162 	struct can_isotp_ll_options ll;
163 	u32 frame_txtime;
164 	u32 force_tx_stmin;
165 	u32 force_rx_stmin;
166 	u32 cfecho; /* consecutive frame echo tag */
167 	struct tpcon rx, tx;
168 	struct list_head notifier;
169 	wait_queue_head_t wait;
170 	spinlock_t rx_lock; /* protect single thread state machine */
171 };
172 
173 static LIST_HEAD(isotp_notifier_list);
174 static DEFINE_SPINLOCK(isotp_notifier_lock);
175 static struct isotp_sock *isotp_busy_notifier;
176 
177 static inline struct isotp_sock *isotp_sk(const struct sock *sk)
178 {
179 	return (struct isotp_sock *)sk;
180 }
181 
182 static u32 isotp_bc_flags(struct isotp_sock *so)
183 {
184 	return so->opt.flags & ISOTP_ALL_BC_FLAGS;
185 }
186 
187 static bool isotp_register_rxid(struct isotp_sock *so)
188 {
189 	/* no broadcast modes => register rx_id for FC frame reception */
190 	return (isotp_bc_flags(so) == 0);
191 }
192 
193 static enum hrtimer_restart isotp_rx_timer_handler(struct hrtimer *hrtimer)
194 {
195 	struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
196 					     rxtimer);
197 	struct sock *sk = &so->sk;
198 
199 	if (so->rx.state == ISOTP_WAIT_DATA) {
200 		/* we did not get new data frames in time */
201 
202 		/* report 'connection timed out' */
203 		sk->sk_err = ETIMEDOUT;
204 		if (!sock_flag(sk, SOCK_DEAD))
205 			sk_error_report(sk);
206 
207 		/* reset rx state */
208 		so->rx.state = ISOTP_IDLE;
209 	}
210 
211 	return HRTIMER_NORESTART;
212 }
213 
214 static int isotp_send_fc(struct sock *sk, int ae, u8 flowstatus)
215 {
216 	struct net_device *dev;
217 	struct sk_buff *nskb;
218 	struct can_skb_ext *csx;
219 	struct canfd_frame *ncf;
220 	struct isotp_sock *so = isotp_sk(sk);
221 	int can_send_ret;
222 
223 	nskb = alloc_skb(so->ll.mtu, gfp_any());
224 	if (!nskb)
225 		return 1;
226 
227 	csx = can_skb_ext_add(nskb);
228 	if (!csx) {
229 		kfree_skb(nskb);
230 		return 1;
231 	}
232 
233 	dev = dev_get_by_index(sock_net(sk), so->ifindex);
234 	if (!dev) {
235 		kfree_skb(nskb);
236 		return 1;
237 	}
238 
239 	csx->can_iif = dev->ifindex;
240 	nskb->dev = dev;
241 	can_skb_set_owner(nskb, sk);
242 	ncf = (struct canfd_frame *)nskb->data;
243 	skb_put_zero(nskb, so->ll.mtu);
244 
245 	/* create & send flow control reply */
246 	ncf->can_id = so->txid;
247 
248 	if (so->opt.flags & CAN_ISOTP_TX_PADDING) {
249 		memset(ncf->data, so->opt.txpad_content, CAN_MAX_DLEN);
250 		ncf->len = CAN_MAX_DLEN;
251 	} else {
252 		ncf->len = ae + FC_CONTENT_SZ;
253 	}
254 
255 	ncf->data[ae] = N_PCI_FC | flowstatus;
256 	ncf->data[ae + 1] = so->rxfc.bs;
257 	ncf->data[ae + 2] = so->rxfc.stmin;
258 
259 	if (ae)
260 		ncf->data[0] = so->opt.ext_address;
261 
262 	ncf->flags = so->ll.tx_flags;
263 
264 	can_send_ret = can_send(nskb, 1);
265 	if (can_send_ret)
266 		pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
267 			       __func__, ERR_PTR(can_send_ret));
268 
269 	dev_put(dev);
270 
271 	/* reset blocksize counter */
272 	so->rx.bs = 0;
273 
274 	/* reset last CF frame rx timestamp for rx stmin enforcement */
275 	so->lastrxcf_tstamp = ktime_set(0, 0);
276 
277 	/* start rx timeout watchdog */
278 	hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
279 		      HRTIMER_MODE_REL_SOFT);
280 	return 0;
281 }
282 
283 static void isotp_rcv_skb(struct sk_buff *skb, struct sock *sk)
284 {
285 	struct sockaddr_can *addr = (struct sockaddr_can *)skb->cb;
286 	enum skb_drop_reason reason;
287 
288 	BUILD_BUG_ON(sizeof(skb->cb) < sizeof(struct sockaddr_can));
289 
290 	memset(addr, 0, sizeof(*addr));
291 	addr->can_family = AF_CAN;
292 	addr->can_ifindex = skb->dev->ifindex;
293 
294 	reason = sock_queue_rcv_skb_reason(sk, skb);
295 	if (reason)
296 		sk_skb_reason_drop(sk, skb, reason);
297 }
298 
299 static u8 padlen(u8 datalen)
300 {
301 	static const u8 plen[] = {
302 		8, 8, 8, 8, 8, 8, 8, 8, 8,	/* 0 - 8 */
303 		12, 12, 12, 12,			/* 9 - 12 */
304 		16, 16, 16, 16,			/* 13 - 16 */
305 		20, 20, 20, 20,			/* 17 - 20 */
306 		24, 24, 24, 24,			/* 21 - 24 */
307 		32, 32, 32, 32, 32, 32, 32, 32,	/* 25 - 32 */
308 		48, 48, 48, 48, 48, 48, 48, 48,	/* 33 - 40 */
309 		48, 48, 48, 48, 48, 48, 48, 48	/* 41 - 48 */
310 	};
311 
312 	if (datalen > 48)
313 		return 64;
314 
315 	return plen[datalen];
316 }
317 
318 /* check for length optimization and return 1/true when the check fails */
319 static int check_optimized(struct canfd_frame *cf, int start_index)
320 {
321 	/* for CAN_DL <= 8 the start_index is equal to the CAN_DL as the
322 	 * padding would start at this point. E.g. if the padding would
323 	 * start at cf.data[7] cf->len has to be 7 to be optimal.
324 	 * Note: The data[] index starts with zero.
325 	 */
326 	if (cf->len <= CAN_MAX_DLEN)
327 		return (cf->len != start_index);
328 
329 	/* This relation is also valid in the non-linear DLC range, where
330 	 * we need to take care of the minimal next possible CAN_DL.
331 	 * The correct check would be (padlen(cf->len) != padlen(start_index)).
332 	 * But as cf->len can only take discrete values from 12, .., 64 at this
333 	 * point the padlen(cf->len) is always equal to cf->len.
334 	 */
335 	return (cf->len != padlen(start_index));
336 }
337 
338 /* check padding and return 1/true when the check fails */
339 static int check_pad(struct isotp_sock *so, struct canfd_frame *cf,
340 		     int start_index, u8 content)
341 {
342 	int i;
343 
344 	/* no RX_PADDING value => check length of optimized frame length */
345 	if (!(so->opt.flags & CAN_ISOTP_RX_PADDING)) {
346 		if (so->opt.flags & CAN_ISOTP_CHK_PAD_LEN)
347 			return check_optimized(cf, start_index);
348 
349 		/* no valid test against empty value => ignore frame */
350 		return 1;
351 	}
352 
353 	/* check datalength of correctly padded CAN frame */
354 	if ((so->opt.flags & CAN_ISOTP_CHK_PAD_LEN) &&
355 	    cf->len != padlen(cf->len))
356 		return 1;
357 
358 	/* check padding content */
359 	if (so->opt.flags & CAN_ISOTP_CHK_PAD_DATA) {
360 		for (i = start_index; i < cf->len; i++)
361 			if (cf->data[i] != content)
362 				return 1;
363 	}
364 	return 0;
365 }
366 
367 static void isotp_send_cframe(struct isotp_sock *so);
368 
369 static int isotp_rcv_fc(struct isotp_sock *so, struct canfd_frame *cf, int ae)
370 {
371 	struct sock *sk = &so->sk;
372 
373 	if (so->tx.state != ISOTP_WAIT_FC &&
374 	    so->tx.state != ISOTP_WAIT_FIRST_FC)
375 		return 0;
376 
377 	hrtimer_cancel(&so->txtimer);
378 
379 	if ((cf->len < ae + FC_CONTENT_SZ) ||
380 	    ((so->opt.flags & ISOTP_CHECK_PADDING) &&
381 	     check_pad(so, cf, ae + FC_CONTENT_SZ, so->opt.rxpad_content))) {
382 		/* malformed PDU - report 'not a data message' */
383 		sk->sk_err = EBADMSG;
384 		if (!sock_flag(sk, SOCK_DEAD))
385 			sk_error_report(sk);
386 
387 		so->tx.state = ISOTP_IDLE;
388 		wake_up_interruptible(&so->wait);
389 		return 1;
390 	}
391 
392 	/* get static/dynamic communication params from first/every FC frame */
393 	if (so->tx.state == ISOTP_WAIT_FIRST_FC ||
394 	    so->opt.flags & CAN_ISOTP_DYN_FC_PARMS) {
395 		so->txfc.bs = cf->data[ae + 1];
396 		so->txfc.stmin = cf->data[ae + 2];
397 
398 		/* fix wrong STmin values according spec */
399 		if (so->txfc.stmin > 0x7F &&
400 		    (so->txfc.stmin < 0xF1 || so->txfc.stmin > 0xF9))
401 			so->txfc.stmin = 0x7F;
402 
403 		so->tx_gap = ktime_set(0, 0);
404 		/* add transmission time for CAN frame N_As */
405 		so->tx_gap = ktime_add_ns(so->tx_gap, so->frame_txtime);
406 		/* add waiting time for consecutive frames N_Cs */
407 		if (so->opt.flags & CAN_ISOTP_FORCE_TXSTMIN)
408 			so->tx_gap = ktime_add_ns(so->tx_gap,
409 						  so->force_tx_stmin);
410 		else if (so->txfc.stmin < 0x80)
411 			so->tx_gap = ktime_add_ns(so->tx_gap,
412 						  so->txfc.stmin * 1000000);
413 		else
414 			so->tx_gap = ktime_add_ns(so->tx_gap,
415 						  (so->txfc.stmin - 0xF0)
416 						  * 100000);
417 		so->tx.state = ISOTP_WAIT_FC;
418 	}
419 
420 	switch (cf->data[ae] & 0x0F) {
421 	case ISOTP_FC_CTS:
422 		so->tx.bs = 0;
423 		so->tx.state = ISOTP_SENDING;
424 		/* send CF frame and enable echo timeout handling */
425 		hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
426 			      HRTIMER_MODE_REL_SOFT);
427 		isotp_send_cframe(so);
428 		break;
429 
430 	case ISOTP_FC_WT:
431 		/* start timer to wait for next FC frame */
432 		hrtimer_start(&so->txtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
433 			      HRTIMER_MODE_REL_SOFT);
434 		break;
435 
436 	case ISOTP_FC_OVFLW:
437 		/* overflow on receiver side - report 'message too long' */
438 		sk->sk_err = EMSGSIZE;
439 		if (!sock_flag(sk, SOCK_DEAD))
440 			sk_error_report(sk);
441 		fallthrough;
442 
443 	default:
444 		/* stop this tx job */
445 		so->tx.state = ISOTP_IDLE;
446 		wake_up_interruptible(&so->wait);
447 	}
448 	return 0;
449 }
450 
451 static int isotp_rcv_sf(struct sock *sk, struct canfd_frame *cf, int pcilen,
452 			struct sk_buff *skb, int len)
453 {
454 	struct isotp_sock *so = isotp_sk(sk);
455 	struct sk_buff *nskb;
456 
457 	hrtimer_cancel(&so->rxtimer);
458 	so->rx.state = ISOTP_IDLE;
459 
460 	if (!len || len > cf->len - pcilen)
461 		return 1;
462 
463 	if ((so->opt.flags & ISOTP_CHECK_PADDING) &&
464 	    check_pad(so, cf, pcilen + len, so->opt.rxpad_content)) {
465 		/* malformed PDU - report 'not a data message' */
466 		sk->sk_err = EBADMSG;
467 		if (!sock_flag(sk, SOCK_DEAD))
468 			sk_error_report(sk);
469 		return 1;
470 	}
471 
472 	nskb = alloc_skb(len, gfp_any());
473 	if (!nskb)
474 		return 1;
475 
476 	memcpy(skb_put(nskb, len), &cf->data[pcilen], len);
477 
478 	nskb->tstamp = skb->tstamp;
479 	nskb->dev = skb->dev;
480 	isotp_rcv_skb(nskb, sk);
481 	return 0;
482 }
483 
484 static int isotp_rcv_ff(struct sock *sk, struct canfd_frame *cf, int ae)
485 {
486 	struct isotp_sock *so = isotp_sk(sk);
487 	int i;
488 	int off;
489 	int ff_pci_sz;
490 
491 	hrtimer_cancel(&so->rxtimer);
492 	so->rx.state = ISOTP_IDLE;
493 
494 	/* get the used sender LL_DL from the (first) CAN frame data length */
495 	so->rx.ll_dl = padlen(cf->len);
496 
497 	/* the first frame has to use the entire frame up to LL_DL length */
498 	if (cf->len != so->rx.ll_dl)
499 		return 1;
500 
501 	/* get the FF_DL */
502 	so->rx.len = (cf->data[ae] & 0x0F) << 8;
503 	so->rx.len += cf->data[ae + 1];
504 
505 	/* Check for FF_DL escape sequence supporting 32 bit PDU length */
506 	if (so->rx.len) {
507 		ff_pci_sz = FF_PCI_SZ12;
508 	} else {
509 		/* FF_DL = 0 => get real length from next 4 bytes */
510 		so->rx.len = cf->data[ae + 2] << 24;
511 		so->rx.len += cf->data[ae + 3] << 16;
512 		so->rx.len += cf->data[ae + 4] << 8;
513 		so->rx.len += cf->data[ae + 5];
514 		ff_pci_sz = FF_PCI_SZ32;
515 	}
516 
517 	/* take care of a potential SF_DL ESC offset for TX_DL > 8 */
518 	off = (so->rx.ll_dl > CAN_MAX_DLEN) ? 1 : 0;
519 
520 	if (so->rx.len + ae + off + ff_pci_sz < so->rx.ll_dl)
521 		return 1;
522 
523 	/* PDU size > default => try max_pdu_size */
524 	if (so->rx.len > so->rx.buflen && so->rx.buflen < max_pdu_size) {
525 		u8 *newbuf = kmalloc(max_pdu_size, GFP_ATOMIC);
526 
527 		if (newbuf) {
528 			so->rx.buf = newbuf;
529 			so->rx.buflen = max_pdu_size;
530 		}
531 	}
532 
533 	if (so->rx.len > so->rx.buflen) {
534 		/* send FC frame with overflow status */
535 		isotp_send_fc(sk, ae, ISOTP_FC_OVFLW);
536 		return 1;
537 	}
538 
539 	/* copy the first received data bytes */
540 	so->rx.idx = 0;
541 	for (i = ae + ff_pci_sz; i < so->rx.ll_dl; i++)
542 		so->rx.buf[so->rx.idx++] = cf->data[i];
543 
544 	/* initial setup for this pdu reception */
545 	so->rx.sn = 1;
546 	so->rx.state = ISOTP_WAIT_DATA;
547 
548 	/* no creation of flow control frames */
549 	if (so->opt.flags & CAN_ISOTP_LISTEN_MODE)
550 		return 0;
551 
552 	/* send our first FC frame */
553 	isotp_send_fc(sk, ae, ISOTP_FC_CTS);
554 	return 0;
555 }
556 
557 static int isotp_rcv_cf(struct sock *sk, struct canfd_frame *cf, int ae,
558 			struct sk_buff *skb)
559 {
560 	struct isotp_sock *so = isotp_sk(sk);
561 	struct sk_buff *nskb;
562 	int i;
563 
564 	if (so->rx.state != ISOTP_WAIT_DATA)
565 		return 0;
566 
567 	/* drop if timestamp gap is less than force_rx_stmin nano secs */
568 	if (so->opt.flags & CAN_ISOTP_FORCE_RXSTMIN) {
569 		if (ktime_to_ns(ktime_sub(skb->tstamp, so->lastrxcf_tstamp)) <
570 		    so->force_rx_stmin)
571 			return 0;
572 
573 		so->lastrxcf_tstamp = skb->tstamp;
574 	}
575 
576 	hrtimer_cancel(&so->rxtimer);
577 
578 	/* CFs are never longer than the FF */
579 	if (cf->len > so->rx.ll_dl)
580 		return 1;
581 
582 	/* CFs have usually the LL_DL length */
583 	if (cf->len < so->rx.ll_dl) {
584 		/* this is only allowed for the last CF */
585 		if (so->rx.len - so->rx.idx > so->rx.ll_dl - ae - N_PCI_SZ)
586 			return 1;
587 	}
588 
589 	if ((cf->data[ae] & 0x0F) != so->rx.sn) {
590 		/* wrong sn detected - report 'illegal byte sequence' */
591 		sk->sk_err = EILSEQ;
592 		if (!sock_flag(sk, SOCK_DEAD))
593 			sk_error_report(sk);
594 
595 		/* reset rx state */
596 		so->rx.state = ISOTP_IDLE;
597 		return 1;
598 	}
599 	so->rx.sn++;
600 	so->rx.sn %= 16;
601 
602 	for (i = ae + N_PCI_SZ; i < cf->len; i++) {
603 		so->rx.buf[so->rx.idx++] = cf->data[i];
604 		if (so->rx.idx >= so->rx.len)
605 			break;
606 	}
607 
608 	if (so->rx.idx >= so->rx.len) {
609 		/* we are done */
610 		so->rx.state = ISOTP_IDLE;
611 
612 		if ((so->opt.flags & ISOTP_CHECK_PADDING) &&
613 		    check_pad(so, cf, i + 1, so->opt.rxpad_content)) {
614 			/* malformed PDU - report 'not a data message' */
615 			sk->sk_err = EBADMSG;
616 			if (!sock_flag(sk, SOCK_DEAD))
617 				sk_error_report(sk);
618 			return 1;
619 		}
620 
621 		nskb = alloc_skb(so->rx.len, gfp_any());
622 		if (!nskb)
623 			return 1;
624 
625 		memcpy(skb_put(nskb, so->rx.len), so->rx.buf,
626 		       so->rx.len);
627 
628 		nskb->tstamp = skb->tstamp;
629 		nskb->dev = skb->dev;
630 		isotp_rcv_skb(nskb, sk);
631 		return 0;
632 	}
633 
634 	/* perform blocksize handling, if enabled */
635 	if (!so->rxfc.bs || ++so->rx.bs < so->rxfc.bs) {
636 		/* start rx timeout watchdog */
637 		hrtimer_start(&so->rxtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
638 			      HRTIMER_MODE_REL_SOFT);
639 		return 0;
640 	}
641 
642 	/* no creation of flow control frames */
643 	if (so->opt.flags & CAN_ISOTP_LISTEN_MODE)
644 		return 0;
645 
646 	/* we reached the specified blocksize so->rxfc.bs */
647 	isotp_send_fc(sk, ae, ISOTP_FC_CTS);
648 	return 0;
649 }
650 
651 static void isotp_rcv(struct sk_buff *skb, void *data)
652 {
653 	struct sock *sk = (struct sock *)data;
654 	struct isotp_sock *so = isotp_sk(sk);
655 	struct canfd_frame *cf;
656 	int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
657 	u8 n_pci_type, sf_dl;
658 
659 	/* Strictly receive only frames with the configured MTU size
660 	 * => clear separation of CAN2.0 / CAN FD transport channels
661 	 */
662 	if (skb->len != so->ll.mtu)
663 		return;
664 
665 	cf = (struct canfd_frame *)skb->data;
666 
667 	/* if enabled: check reception of my configured extended address */
668 	if (ae && cf->data[0] != so->opt.rx_ext_address)
669 		return;
670 
671 	n_pci_type = cf->data[ae] & 0xF0;
672 
673 	/* Make sure the state changes and data structures stay consistent at
674 	 * CAN frame reception time. This locking is not needed in real world
675 	 * use cases but the inconsistency can be triggered with syzkaller.
676 	 */
677 	spin_lock(&so->rx_lock);
678 
679 	if (so->opt.flags & CAN_ISOTP_HALF_DUPLEX) {
680 		/* check rx/tx path half duplex expectations */
681 		if ((so->tx.state != ISOTP_IDLE && n_pci_type != N_PCI_FC) ||
682 		    (so->rx.state != ISOTP_IDLE && n_pci_type == N_PCI_FC))
683 			goto out_unlock;
684 	}
685 
686 	switch (n_pci_type) {
687 	case N_PCI_FC:
688 		/* tx path: flow control frame containing the FC parameters */
689 		isotp_rcv_fc(so, cf, ae);
690 		break;
691 
692 	case N_PCI_SF:
693 		/* rx path: single frame
694 		 *
695 		 * As we do not have a rx.ll_dl configuration, we can only test
696 		 * if the CAN frames payload length matches the LL_DL == 8
697 		 * requirements - no matter if it's CAN 2.0 or CAN FD
698 		 */
699 
700 		/* get the SF_DL from the N_PCI byte */
701 		sf_dl = cf->data[ae] & 0x0F;
702 
703 		if (cf->len <= CAN_MAX_DLEN) {
704 			isotp_rcv_sf(sk, cf, SF_PCI_SZ4 + ae, skb, sf_dl);
705 		} else {
706 			if (can_is_canfd_skb(skb)) {
707 				/* We have a CAN FD frame and CAN_DL is greater than 8:
708 				 * Only frames with the SF_DL == 0 ESC value are valid.
709 				 *
710 				 * If so take care of the increased SF PCI size
711 				 * (SF_PCI_SZ8) to point to the message content behind
712 				 * the extended SF PCI info and get the real SF_DL
713 				 * length value from the formerly first data byte.
714 				 */
715 				if (sf_dl == 0)
716 					isotp_rcv_sf(sk, cf, SF_PCI_SZ8 + ae, skb,
717 						     cf->data[SF_PCI_SZ4 + ae]);
718 			}
719 		}
720 		break;
721 
722 	case N_PCI_FF:
723 		/* rx path: first frame */
724 		isotp_rcv_ff(sk, cf, ae);
725 		break;
726 
727 	case N_PCI_CF:
728 		/* rx path: consecutive frame */
729 		isotp_rcv_cf(sk, cf, ae, skb);
730 		break;
731 	}
732 
733 out_unlock:
734 	spin_unlock(&so->rx_lock);
735 }
736 
737 static void isotp_fill_dataframe(struct canfd_frame *cf, struct isotp_sock *so,
738 				 int ae, int off)
739 {
740 	int pcilen = N_PCI_SZ + ae + off;
741 	int space = so->tx.ll_dl - pcilen;
742 	int num = min_t(int, so->tx.len - so->tx.idx, space);
743 	int i;
744 
745 	cf->can_id = so->txid;
746 	cf->len = num + pcilen;
747 
748 	if (num < space) {
749 		if (so->opt.flags & CAN_ISOTP_TX_PADDING) {
750 			/* user requested padding */
751 			cf->len = padlen(cf->len);
752 			memset(cf->data, so->opt.txpad_content, cf->len);
753 		} else if (cf->len > CAN_MAX_DLEN) {
754 			/* mandatory padding for CAN FD frames */
755 			cf->len = padlen(cf->len);
756 			memset(cf->data, CAN_ISOTP_DEFAULT_PAD_CONTENT,
757 			       cf->len);
758 		}
759 	}
760 
761 	for (i = 0; i < num; i++)
762 		cf->data[pcilen + i] = so->tx.buf[so->tx.idx++];
763 
764 	if (ae)
765 		cf->data[0] = so->opt.ext_address;
766 }
767 
768 static void isotp_send_cframe(struct isotp_sock *so)
769 {
770 	struct sock *sk = &so->sk;
771 	struct sk_buff *skb;
772 	struct can_skb_ext *csx;
773 	struct net_device *dev;
774 	struct canfd_frame *cf;
775 	int can_send_ret;
776 	int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
777 
778 	dev = dev_get_by_index(sock_net(sk), so->ifindex);
779 	if (!dev)
780 		return;
781 
782 	skb = alloc_skb(so->ll.mtu, GFP_ATOMIC);
783 	if (!skb) {
784 		dev_put(dev);
785 		return;
786 	}
787 
788 	csx = can_skb_ext_add(skb);
789 	if (!csx) {
790 		kfree_skb(skb);
791 		netdev_put(dev, NULL);
792 		return;
793 	}
794 
795 	csx->can_iif = dev->ifindex;
796 
797 	cf = (struct canfd_frame *)skb->data;
798 	skb_put_zero(skb, so->ll.mtu);
799 
800 	/* create consecutive frame */
801 	isotp_fill_dataframe(cf, so, ae, 0);
802 
803 	/* place consecutive frame N_PCI in appropriate index */
804 	cf->data[ae] = N_PCI_CF | so->tx.sn++;
805 	so->tx.sn %= 16;
806 	so->tx.bs++;
807 
808 	cf->flags = so->ll.tx_flags;
809 
810 	skb->dev = dev;
811 	can_skb_set_owner(skb, sk);
812 
813 	/* cfecho should have been zero'ed by init/isotp_rcv_echo() */
814 	if (so->cfecho)
815 		pr_notice_once("can-isotp: cfecho is %08X != 0\n", so->cfecho);
816 
817 	/* set consecutive frame echo tag */
818 	so->cfecho = *(u32 *)cf->data;
819 
820 	/* send frame with local echo enabled */
821 	can_send_ret = can_send(skb, 1);
822 	if (can_send_ret) {
823 		pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
824 			       __func__, ERR_PTR(can_send_ret));
825 		if (can_send_ret == -ENOBUFS)
826 			pr_notice_once("can-isotp: tx queue is full\n");
827 	}
828 	dev_put(dev);
829 }
830 
831 static void isotp_create_fframe(struct canfd_frame *cf, struct isotp_sock *so,
832 				int ae)
833 {
834 	int i;
835 	int ff_pci_sz;
836 
837 	cf->can_id = so->txid;
838 	cf->len = so->tx.ll_dl;
839 	if (ae)
840 		cf->data[0] = so->opt.ext_address;
841 
842 	/* create N_PCI bytes with 12/32 bit FF_DL data length */
843 	if (so->tx.len > MAX_12BIT_PDU_SIZE) {
844 		/* use 32 bit FF_DL notation */
845 		cf->data[ae] = N_PCI_FF;
846 		cf->data[ae + 1] = 0;
847 		cf->data[ae + 2] = (u8)(so->tx.len >> 24) & 0xFFU;
848 		cf->data[ae + 3] = (u8)(so->tx.len >> 16) & 0xFFU;
849 		cf->data[ae + 4] = (u8)(so->tx.len >> 8) & 0xFFU;
850 		cf->data[ae + 5] = (u8)so->tx.len & 0xFFU;
851 		ff_pci_sz = FF_PCI_SZ32;
852 	} else {
853 		/* use 12 bit FF_DL notation */
854 		cf->data[ae] = (u8)(so->tx.len >> 8) | N_PCI_FF;
855 		cf->data[ae + 1] = (u8)so->tx.len & 0xFFU;
856 		ff_pci_sz = FF_PCI_SZ12;
857 	}
858 
859 	/* add first data bytes depending on ae */
860 	for (i = ae + ff_pci_sz; i < so->tx.ll_dl; i++)
861 		cf->data[i] = so->tx.buf[so->tx.idx++];
862 
863 	so->tx.sn = 1;
864 }
865 
866 static void isotp_rcv_echo(struct sk_buff *skb, void *data)
867 {
868 	struct sock *sk = (struct sock *)data;
869 	struct isotp_sock *so = isotp_sk(sk);
870 	struct canfd_frame *cf = (struct canfd_frame *)skb->data;
871 
872 	/* only handle my own local echo CF/SF skb's (no FF!) */
873 	if (skb->sk != sk || so->cfecho != *(u32 *)cf->data)
874 		return;
875 
876 	/* cancel local echo timeout */
877 	hrtimer_cancel(&so->txtimer);
878 
879 	/* local echo skb with consecutive frame has been consumed */
880 	so->cfecho = 0;
881 
882 	if (so->tx.idx >= so->tx.len) {
883 		/* we are done */
884 		so->tx.state = ISOTP_IDLE;
885 		wake_up_interruptible(&so->wait);
886 		return;
887 	}
888 
889 	if (so->txfc.bs && so->tx.bs >= so->txfc.bs) {
890 		/* stop and wait for FC with timeout */
891 		so->tx.state = ISOTP_WAIT_FC;
892 		hrtimer_start(&so->txtimer, ktime_set(ISOTP_FC_TIMEOUT, 0),
893 			      HRTIMER_MODE_REL_SOFT);
894 		return;
895 	}
896 
897 	/* no gap between data frames needed => use burst mode */
898 	if (!so->tx_gap) {
899 		/* enable echo timeout handling */
900 		hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
901 			      HRTIMER_MODE_REL_SOFT);
902 		isotp_send_cframe(so);
903 		return;
904 	}
905 
906 	/* start timer to send next consecutive frame with correct delay */
907 	hrtimer_start(&so->txfrtimer, so->tx_gap, HRTIMER_MODE_REL_SOFT);
908 }
909 
910 static enum hrtimer_restart isotp_tx_timer_handler(struct hrtimer *hrtimer)
911 {
912 	struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
913 					     txtimer);
914 	struct sock *sk = &so->sk;
915 
916 	/* don't handle timeouts in IDLE or SHUTDOWN state */
917 	if (so->tx.state == ISOTP_IDLE || so->tx.state == ISOTP_SHUTDOWN)
918 		return HRTIMER_NORESTART;
919 
920 	/* we did not get any flow control or echo frame in time */
921 
922 	/* report 'communication error on send' */
923 	sk->sk_err = ECOMM;
924 	if (!sock_flag(sk, SOCK_DEAD))
925 		sk_error_report(sk);
926 
927 	/* reset tx state */
928 	so->tx.state = ISOTP_IDLE;
929 	wake_up_interruptible(&so->wait);
930 
931 	return HRTIMER_NORESTART;
932 }
933 
934 static enum hrtimer_restart isotp_txfr_timer_handler(struct hrtimer *hrtimer)
935 {
936 	struct isotp_sock *so = container_of(hrtimer, struct isotp_sock,
937 					     txfrtimer);
938 
939 	/* start echo timeout handling and cover below protocol error */
940 	hrtimer_start(&so->txtimer, ktime_set(ISOTP_ECHO_TIMEOUT, 0),
941 		      HRTIMER_MODE_REL_SOFT);
942 
943 	/* cfecho should be consumed by isotp_rcv_echo() here */
944 	if (so->tx.state == ISOTP_SENDING && !so->cfecho)
945 		isotp_send_cframe(so);
946 
947 	return HRTIMER_NORESTART;
948 }
949 
950 static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
951 {
952 	struct sock *sk = sock->sk;
953 	struct isotp_sock *so = isotp_sk(sk);
954 	struct sk_buff *skb;
955 	struct can_skb_ext *csx;
956 	struct net_device *dev;
957 	struct canfd_frame *cf;
958 	int ae = (so->opt.flags & CAN_ISOTP_EXTEND_ADDR) ? 1 : 0;
959 	int wait_tx_done = (so->opt.flags & CAN_ISOTP_WAIT_TX_DONE) ? 1 : 0;
960 	s64 hrtimer_sec = ISOTP_ECHO_TIMEOUT;
961 	int off;
962 	int err;
963 
964 	if (!so->bound || so->tx.state == ISOTP_SHUTDOWN)
965 		return -EADDRNOTAVAIL;
966 
967 	while (cmpxchg(&so->tx.state, ISOTP_IDLE, ISOTP_SENDING) != ISOTP_IDLE) {
968 		/* we do not support multiple buffers - for now */
969 		if (msg->msg_flags & MSG_DONTWAIT)
970 			return -EAGAIN;
971 
972 		if (so->tx.state == ISOTP_SHUTDOWN)
973 			return -EADDRNOTAVAIL;
974 
975 		/* wait for complete transmission of current pdu */
976 		err = wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE);
977 		if (err)
978 			goto err_event_drop;
979 	}
980 
981 	/* PDU size > default => try max_pdu_size */
982 	if (size > so->tx.buflen && so->tx.buflen < max_pdu_size) {
983 		u8 *newbuf = kmalloc(max_pdu_size, GFP_KERNEL);
984 
985 		if (newbuf) {
986 			so->tx.buf = newbuf;
987 			so->tx.buflen = max_pdu_size;
988 		}
989 	}
990 
991 	if (!size || size > so->tx.buflen) {
992 		err = -EINVAL;
993 		goto err_out_drop;
994 	}
995 
996 	/* take care of a potential SF_DL ESC offset for TX_DL > 8 */
997 	off = (so->tx.ll_dl > CAN_MAX_DLEN) ? 1 : 0;
998 
999 	/* does the given data fit into a single frame for SF_BROADCAST? */
1000 	if ((isotp_bc_flags(so) == CAN_ISOTP_SF_BROADCAST) &&
1001 	    (size > so->tx.ll_dl - SF_PCI_SZ4 - ae - off)) {
1002 		err = -EINVAL;
1003 		goto err_out_drop;
1004 	}
1005 
1006 	err = memcpy_from_msg(so->tx.buf, msg, size);
1007 	if (err < 0)
1008 		goto err_out_drop;
1009 
1010 	dev = dev_get_by_index(sock_net(sk), so->ifindex);
1011 	if (!dev) {
1012 		err = -ENXIO;
1013 		goto err_out_drop;
1014 	}
1015 
1016 	skb = sock_alloc_send_skb(sk, so->ll.mtu, msg->msg_flags & MSG_DONTWAIT,
1017 				  &err);
1018 	if (!skb) {
1019 		dev_put(dev);
1020 		goto err_out_drop;
1021 	}
1022 
1023 	csx = can_skb_ext_add(skb);
1024 	if (!csx) {
1025 		kfree_skb(skb);
1026 		netdev_put(dev, NULL);
1027 		err = -ENOMEM;
1028 		goto err_out_drop;
1029 	}
1030 
1031 	csx->can_iif = dev->ifindex;
1032 
1033 	so->tx.len = size;
1034 	so->tx.idx = 0;
1035 
1036 	cf = (struct canfd_frame *)skb->data;
1037 	skb_put_zero(skb, so->ll.mtu);
1038 
1039 	/* cfecho should have been zero'ed by init / former isotp_rcv_echo() */
1040 	if (so->cfecho)
1041 		pr_notice_once("can-isotp: uninit cfecho %08X\n", so->cfecho);
1042 
1043 	/* check for single frame transmission depending on TX_DL */
1044 	if (size <= so->tx.ll_dl - SF_PCI_SZ4 - ae - off) {
1045 		/* The message size generally fits into a SingleFrame - good.
1046 		 *
1047 		 * SF_DL ESC offset optimization:
1048 		 *
1049 		 * When TX_DL is greater 8 but the message would still fit
1050 		 * into a 8 byte CAN frame, we can omit the offset.
1051 		 * This prevents a protocol caused length extension from
1052 		 * CAN_DL = 8 to CAN_DL = 12 due to the SF_SL ESC handling.
1053 		 */
1054 		if (size <= CAN_MAX_DLEN - SF_PCI_SZ4 - ae)
1055 			off = 0;
1056 
1057 		isotp_fill_dataframe(cf, so, ae, off);
1058 
1059 		/* place single frame N_PCI w/o length in appropriate index */
1060 		cf->data[ae] = N_PCI_SF;
1061 
1062 		/* place SF_DL size value depending on the SF_DL ESC offset */
1063 		if (off)
1064 			cf->data[SF_PCI_SZ4 + ae] = size;
1065 		else
1066 			cf->data[ae] |= size;
1067 
1068 		/* set CF echo tag for isotp_rcv_echo() (SF-mode) */
1069 		so->cfecho = *(u32 *)cf->data;
1070 	} else {
1071 		/* send first frame */
1072 
1073 		isotp_create_fframe(cf, so, ae);
1074 
1075 		if (isotp_bc_flags(so) == CAN_ISOTP_CF_BROADCAST) {
1076 			/* set timer for FC-less operation (STmin = 0) */
1077 			if (so->opt.flags & CAN_ISOTP_FORCE_TXSTMIN)
1078 				so->tx_gap = ktime_set(0, so->force_tx_stmin);
1079 			else
1080 				so->tx_gap = ktime_set(0, so->frame_txtime);
1081 
1082 			/* disable wait for FCs due to activated block size */
1083 			so->txfc.bs = 0;
1084 
1085 			/* set CF echo tag for isotp_rcv_echo() (CF-mode) */
1086 			so->cfecho = *(u32 *)cf->data;
1087 		} else {
1088 			/* standard flow control check */
1089 			so->tx.state = ISOTP_WAIT_FIRST_FC;
1090 
1091 			/* start timeout for FC */
1092 			hrtimer_sec = ISOTP_FC_TIMEOUT;
1093 
1094 			/* no CF echo tag for isotp_rcv_echo() (FF-mode) */
1095 			so->cfecho = 0;
1096 		}
1097 	}
1098 
1099 	hrtimer_start(&so->txtimer, ktime_set(hrtimer_sec, 0),
1100 		      HRTIMER_MODE_REL_SOFT);
1101 
1102 	/* send the first or only CAN frame */
1103 	cf->flags = so->ll.tx_flags;
1104 
1105 	skb->dev = dev;
1106 	skb->sk = sk;
1107 	err = can_send(skb, 1);
1108 	dev_put(dev);
1109 	if (err) {
1110 		pr_notice_once("can-isotp: %s: can_send_ret %pe\n",
1111 			       __func__, ERR_PTR(err));
1112 
1113 		/* no transmission -> no timeout monitoring */
1114 		hrtimer_cancel(&so->txtimer);
1115 
1116 		/* reset consecutive frame echo tag */
1117 		so->cfecho = 0;
1118 
1119 		goto err_out_drop;
1120 	}
1121 
1122 	if (wait_tx_done) {
1123 		/* wait for complete transmission of current pdu */
1124 		err = wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE);
1125 		if (err)
1126 			goto err_event_drop;
1127 
1128 		err = sock_error(sk);
1129 		if (err)
1130 			return err;
1131 	}
1132 
1133 	return size;
1134 
1135 err_event_drop:
1136 	/* got signal: force tx state machine to be idle */
1137 	so->tx.state = ISOTP_IDLE;
1138 	hrtimer_cancel(&so->txfrtimer);
1139 	hrtimer_cancel(&so->txtimer);
1140 err_out_drop:
1141 	/* drop this PDU and unlock a potential wait queue */
1142 	so->tx.state = ISOTP_IDLE;
1143 	wake_up_interruptible(&so->wait);
1144 
1145 	return err;
1146 }
1147 
1148 static int isotp_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
1149 			 int flags)
1150 {
1151 	struct sock *sk = sock->sk;
1152 	struct sk_buff *skb;
1153 	struct isotp_sock *so = isotp_sk(sk);
1154 	int ret = 0;
1155 
1156 	if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT))
1157 		return -EINVAL;
1158 
1159 	if (!so->bound)
1160 		return -EADDRNOTAVAIL;
1161 
1162 	skb = skb_recv_datagram(sk, flags, &ret);
1163 	if (!skb)
1164 		return ret;
1165 
1166 	if (size < skb->len)
1167 		msg->msg_flags |= MSG_TRUNC;
1168 	else
1169 		size = skb->len;
1170 
1171 	ret = memcpy_to_msg(msg, skb->data, size);
1172 	if (ret < 0)
1173 		goto out_err;
1174 
1175 	sock_recv_cmsgs(msg, sk, skb);
1176 
1177 	if (msg->msg_name) {
1178 		__sockaddr_check_size(ISOTP_MIN_NAMELEN);
1179 		msg->msg_namelen = ISOTP_MIN_NAMELEN;
1180 		memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
1181 	}
1182 
1183 	/* set length of return value */
1184 	ret = (flags & MSG_TRUNC) ? skb->len : size;
1185 
1186 out_err:
1187 	skb_free_datagram(sk, skb);
1188 
1189 	return ret;
1190 }
1191 
1192 static int isotp_release(struct socket *sock)
1193 {
1194 	struct sock *sk = sock->sk;
1195 	struct isotp_sock *so;
1196 	struct net *net;
1197 
1198 	if (!sk)
1199 		return 0;
1200 
1201 	so = isotp_sk(sk);
1202 	net = sock_net(sk);
1203 
1204 	/* wait for complete transmission of current pdu */
1205 	while (wait_event_interruptible(so->wait, so->tx.state == ISOTP_IDLE) == 0 &&
1206 	       cmpxchg(&so->tx.state, ISOTP_IDLE, ISOTP_SHUTDOWN) != ISOTP_IDLE)
1207 		;
1208 
1209 	/* force state machines to be idle also when a signal occurred */
1210 	so->tx.state = ISOTP_SHUTDOWN;
1211 	so->rx.state = ISOTP_IDLE;
1212 
1213 	spin_lock(&isotp_notifier_lock);
1214 	while (isotp_busy_notifier == so) {
1215 		spin_unlock(&isotp_notifier_lock);
1216 		schedule_timeout_uninterruptible(1);
1217 		spin_lock(&isotp_notifier_lock);
1218 	}
1219 	list_del(&so->notifier);
1220 	spin_unlock(&isotp_notifier_lock);
1221 
1222 	lock_sock(sk);
1223 
1224 	/* remove current filters & unregister */
1225 	if (so->bound) {
1226 		if (so->ifindex) {
1227 			struct net_device *dev;
1228 
1229 			dev = dev_get_by_index(net, so->ifindex);
1230 			if (dev) {
1231 				if (isotp_register_rxid(so))
1232 					can_rx_unregister(net, dev, so->rxid,
1233 							  SINGLE_MASK(so->rxid),
1234 							  isotp_rcv, sk);
1235 
1236 				can_rx_unregister(net, dev, so->txid,
1237 						  SINGLE_MASK(so->txid),
1238 						  isotp_rcv_echo, sk);
1239 				dev_put(dev);
1240 				synchronize_rcu();
1241 			}
1242 		}
1243 	}
1244 
1245 	hrtimer_cancel(&so->txfrtimer);
1246 	hrtimer_cancel(&so->txtimer);
1247 	hrtimer_cancel(&so->rxtimer);
1248 
1249 	so->ifindex = 0;
1250 	so->bound = 0;
1251 
1252 	sock_orphan(sk);
1253 	sock->sk = NULL;
1254 
1255 	release_sock(sk);
1256 	sock_prot_inuse_add(net, sk->sk_prot, -1);
1257 	sock_put(sk);
1258 
1259 	return 0;
1260 }
1261 
1262 static int isotp_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int len)
1263 {
1264 	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1265 	struct sock *sk = sock->sk;
1266 	struct isotp_sock *so = isotp_sk(sk);
1267 	struct net *net = sock_net(sk);
1268 	int ifindex;
1269 	struct net_device *dev;
1270 	canid_t tx_id = addr->can_addr.tp.tx_id;
1271 	canid_t rx_id = addr->can_addr.tp.rx_id;
1272 	int err = 0;
1273 	int notify_enetdown = 0;
1274 
1275 	if (len < ISOTP_MIN_NAMELEN)
1276 		return -EINVAL;
1277 
1278 	if (addr->can_family != AF_CAN)
1279 		return -EINVAL;
1280 
1281 	/* sanitize tx CAN identifier */
1282 	if (tx_id & CAN_EFF_FLAG)
1283 		tx_id &= (CAN_EFF_FLAG | CAN_EFF_MASK);
1284 	else
1285 		tx_id &= CAN_SFF_MASK;
1286 
1287 	/* give feedback on wrong CAN-ID value */
1288 	if (tx_id != addr->can_addr.tp.tx_id)
1289 		return -EINVAL;
1290 
1291 	/* sanitize rx CAN identifier (if needed) */
1292 	if (isotp_register_rxid(so)) {
1293 		if (rx_id & CAN_EFF_FLAG)
1294 			rx_id &= (CAN_EFF_FLAG | CAN_EFF_MASK);
1295 		else
1296 			rx_id &= CAN_SFF_MASK;
1297 
1298 		/* give feedback on wrong CAN-ID value */
1299 		if (rx_id != addr->can_addr.tp.rx_id)
1300 			return -EINVAL;
1301 	}
1302 
1303 	if (!addr->can_ifindex)
1304 		return -ENODEV;
1305 
1306 	lock_sock(sk);
1307 
1308 	if (so->bound) {
1309 		err = -EINVAL;
1310 		goto out;
1311 	}
1312 
1313 	/* ensure different CAN IDs when the rx_id is to be registered */
1314 	if (isotp_register_rxid(so) && rx_id == tx_id) {
1315 		err = -EADDRNOTAVAIL;
1316 		goto out;
1317 	}
1318 
1319 	dev = dev_get_by_index(net, addr->can_ifindex);
1320 	if (!dev) {
1321 		err = -ENODEV;
1322 		goto out;
1323 	}
1324 	if (dev->type != ARPHRD_CAN) {
1325 		dev_put(dev);
1326 		err = -ENODEV;
1327 		goto out;
1328 	}
1329 	if (READ_ONCE(dev->mtu) < so->ll.mtu) {
1330 		dev_put(dev);
1331 		err = -EINVAL;
1332 		goto out;
1333 	}
1334 	if (!(dev->flags & IFF_UP))
1335 		notify_enetdown = 1;
1336 
1337 	ifindex = dev->ifindex;
1338 
1339 	if (isotp_register_rxid(so))
1340 		can_rx_register(net, dev, rx_id, SINGLE_MASK(rx_id),
1341 				isotp_rcv, sk, "isotp", sk);
1342 
1343 	/* no consecutive frame echo skb in flight */
1344 	so->cfecho = 0;
1345 
1346 	/* register for echo skb's */
1347 	can_rx_register(net, dev, tx_id, SINGLE_MASK(tx_id),
1348 			isotp_rcv_echo, sk, "isotpe", sk);
1349 
1350 	dev_put(dev);
1351 
1352 	/* switch to new settings */
1353 	so->ifindex = ifindex;
1354 	so->rxid = rx_id;
1355 	so->txid = tx_id;
1356 	so->bound = 1;
1357 
1358 out:
1359 	release_sock(sk);
1360 
1361 	if (notify_enetdown) {
1362 		sk->sk_err = ENETDOWN;
1363 		if (!sock_flag(sk, SOCK_DEAD))
1364 			sk_error_report(sk);
1365 	}
1366 
1367 	return err;
1368 }
1369 
1370 static int isotp_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
1371 {
1372 	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
1373 	struct sock *sk = sock->sk;
1374 	struct isotp_sock *so = isotp_sk(sk);
1375 
1376 	if (peer)
1377 		return -EOPNOTSUPP;
1378 
1379 	memset(addr, 0, ISOTP_MIN_NAMELEN);
1380 	addr->can_family = AF_CAN;
1381 	addr->can_ifindex = so->ifindex;
1382 	addr->can_addr.tp.rx_id = so->rxid;
1383 	addr->can_addr.tp.tx_id = so->txid;
1384 
1385 	return ISOTP_MIN_NAMELEN;
1386 }
1387 
1388 static int isotp_setsockopt_locked(struct socket *sock, int level, int optname,
1389 			    sockptr_t optval, unsigned int optlen)
1390 {
1391 	struct sock *sk = sock->sk;
1392 	struct isotp_sock *so = isotp_sk(sk);
1393 	int ret = 0;
1394 
1395 	if (so->bound)
1396 		return -EISCONN;
1397 
1398 	switch (optname) {
1399 	case CAN_ISOTP_OPTS:
1400 		if (optlen != sizeof(struct can_isotp_options))
1401 			return -EINVAL;
1402 
1403 		if (copy_from_sockptr(&so->opt, optval, optlen))
1404 			return -EFAULT;
1405 
1406 		/* no separate rx_ext_address is given => use ext_address */
1407 		if (!(so->opt.flags & CAN_ISOTP_RX_EXT_ADDR))
1408 			so->opt.rx_ext_address = so->opt.ext_address;
1409 
1410 		/* these broadcast flags are not allowed together */
1411 		if (isotp_bc_flags(so) == ISOTP_ALL_BC_FLAGS) {
1412 			/* CAN_ISOTP_SF_BROADCAST is prioritized */
1413 			so->opt.flags &= ~CAN_ISOTP_CF_BROADCAST;
1414 
1415 			/* give user feedback on wrong config attempt */
1416 			ret = -EINVAL;
1417 		}
1418 
1419 		/* check for frame_txtime changes (0 => no changes) */
1420 		if (so->opt.frame_txtime) {
1421 			if (so->opt.frame_txtime == CAN_ISOTP_FRAME_TXTIME_ZERO)
1422 				so->frame_txtime = 0;
1423 			else
1424 				so->frame_txtime = so->opt.frame_txtime;
1425 		}
1426 		break;
1427 
1428 	case CAN_ISOTP_RECV_FC:
1429 		if (optlen != sizeof(struct can_isotp_fc_options))
1430 			return -EINVAL;
1431 
1432 		if (copy_from_sockptr(&so->rxfc, optval, optlen))
1433 			return -EFAULT;
1434 		break;
1435 
1436 	case CAN_ISOTP_TX_STMIN:
1437 		if (optlen != sizeof(u32))
1438 			return -EINVAL;
1439 
1440 		if (copy_from_sockptr(&so->force_tx_stmin, optval, optlen))
1441 			return -EFAULT;
1442 		break;
1443 
1444 	case CAN_ISOTP_RX_STMIN:
1445 		if (optlen != sizeof(u32))
1446 			return -EINVAL;
1447 
1448 		if (copy_from_sockptr(&so->force_rx_stmin, optval, optlen))
1449 			return -EFAULT;
1450 		break;
1451 
1452 	case CAN_ISOTP_LL_OPTS:
1453 		if (optlen == sizeof(struct can_isotp_ll_options)) {
1454 			struct can_isotp_ll_options ll;
1455 
1456 			if (copy_from_sockptr(&ll, optval, optlen))
1457 				return -EFAULT;
1458 
1459 			/* check for correct ISO 11898-1 DLC data length */
1460 			if (ll.tx_dl != padlen(ll.tx_dl))
1461 				return -EINVAL;
1462 
1463 			if (ll.mtu != CAN_MTU && ll.mtu != CANFD_MTU)
1464 				return -EINVAL;
1465 
1466 			if (ll.mtu == CAN_MTU &&
1467 			    (ll.tx_dl > CAN_MAX_DLEN || ll.tx_flags != 0))
1468 				return -EINVAL;
1469 
1470 			memcpy(&so->ll, &ll, sizeof(ll));
1471 
1472 			/* set ll_dl for tx path to similar place as for rx */
1473 			so->tx.ll_dl = ll.tx_dl;
1474 		} else {
1475 			return -EINVAL;
1476 		}
1477 		break;
1478 
1479 	default:
1480 		ret = -ENOPROTOOPT;
1481 	}
1482 
1483 	return ret;
1484 }
1485 
1486 static int isotp_setsockopt(struct socket *sock, int level, int optname,
1487 			    sockptr_t optval, unsigned int optlen)
1488 
1489 {
1490 	struct sock *sk = sock->sk;
1491 	int ret;
1492 
1493 	if (level != SOL_CAN_ISOTP)
1494 		return -EINVAL;
1495 
1496 	lock_sock(sk);
1497 	ret = isotp_setsockopt_locked(sock, level, optname, optval, optlen);
1498 	release_sock(sk);
1499 	return ret;
1500 }
1501 
1502 static int isotp_getsockopt(struct socket *sock, int level, int optname,
1503 			    char __user *optval, int __user *optlen)
1504 {
1505 	struct sock *sk = sock->sk;
1506 	struct isotp_sock *so = isotp_sk(sk);
1507 	int len;
1508 	void *val;
1509 
1510 	if (level != SOL_CAN_ISOTP)
1511 		return -EINVAL;
1512 	if (get_user(len, optlen))
1513 		return -EFAULT;
1514 	if (len < 0)
1515 		return -EINVAL;
1516 
1517 	switch (optname) {
1518 	case CAN_ISOTP_OPTS:
1519 		len = min_t(int, len, sizeof(struct can_isotp_options));
1520 		val = &so->opt;
1521 		break;
1522 
1523 	case CAN_ISOTP_RECV_FC:
1524 		len = min_t(int, len, sizeof(struct can_isotp_fc_options));
1525 		val = &so->rxfc;
1526 		break;
1527 
1528 	case CAN_ISOTP_TX_STMIN:
1529 		len = min_t(int, len, sizeof(u32));
1530 		val = &so->force_tx_stmin;
1531 		break;
1532 
1533 	case CAN_ISOTP_RX_STMIN:
1534 		len = min_t(int, len, sizeof(u32));
1535 		val = &so->force_rx_stmin;
1536 		break;
1537 
1538 	case CAN_ISOTP_LL_OPTS:
1539 		len = min_t(int, len, sizeof(struct can_isotp_ll_options));
1540 		val = &so->ll;
1541 		break;
1542 
1543 	default:
1544 		return -ENOPROTOOPT;
1545 	}
1546 
1547 	if (put_user(len, optlen))
1548 		return -EFAULT;
1549 	if (copy_to_user(optval, val, len))
1550 		return -EFAULT;
1551 	return 0;
1552 }
1553 
1554 static void isotp_notify(struct isotp_sock *so, unsigned long msg,
1555 			 struct net_device *dev)
1556 {
1557 	struct sock *sk = &so->sk;
1558 
1559 	if (!net_eq(dev_net(dev), sock_net(sk)))
1560 		return;
1561 
1562 	if (so->ifindex != dev->ifindex)
1563 		return;
1564 
1565 	switch (msg) {
1566 	case NETDEV_UNREGISTER:
1567 		lock_sock(sk);
1568 		/* remove current filters & unregister */
1569 		if (so->bound) {
1570 			if (isotp_register_rxid(so))
1571 				can_rx_unregister(dev_net(dev), dev, so->rxid,
1572 						  SINGLE_MASK(so->rxid),
1573 						  isotp_rcv, sk);
1574 
1575 			can_rx_unregister(dev_net(dev), dev, so->txid,
1576 					  SINGLE_MASK(so->txid),
1577 					  isotp_rcv_echo, sk);
1578 		}
1579 
1580 		so->ifindex = 0;
1581 		so->bound  = 0;
1582 		release_sock(sk);
1583 
1584 		sk->sk_err = ENODEV;
1585 		if (!sock_flag(sk, SOCK_DEAD))
1586 			sk_error_report(sk);
1587 		break;
1588 
1589 	case NETDEV_DOWN:
1590 		sk->sk_err = ENETDOWN;
1591 		if (!sock_flag(sk, SOCK_DEAD))
1592 			sk_error_report(sk);
1593 		break;
1594 	}
1595 }
1596 
1597 static int isotp_notifier(struct notifier_block *nb, unsigned long msg,
1598 			  void *ptr)
1599 {
1600 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1601 
1602 	if (dev->type != ARPHRD_CAN)
1603 		return NOTIFY_DONE;
1604 	if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
1605 		return NOTIFY_DONE;
1606 	if (unlikely(isotp_busy_notifier)) /* Check for reentrant bug. */
1607 		return NOTIFY_DONE;
1608 
1609 	spin_lock(&isotp_notifier_lock);
1610 	list_for_each_entry(isotp_busy_notifier, &isotp_notifier_list, notifier) {
1611 		spin_unlock(&isotp_notifier_lock);
1612 		isotp_notify(isotp_busy_notifier, msg, dev);
1613 		spin_lock(&isotp_notifier_lock);
1614 	}
1615 	isotp_busy_notifier = NULL;
1616 	spin_unlock(&isotp_notifier_lock);
1617 	return NOTIFY_DONE;
1618 }
1619 
1620 static void isotp_sock_destruct(struct sock *sk)
1621 {
1622 	struct isotp_sock *so = isotp_sk(sk);
1623 
1624 	/* do the standard CAN sock destruct work */
1625 	can_sock_destruct(sk);
1626 
1627 	/* free potential extended PDU buffers */
1628 	if (so->rx.buf != so->rx.sbuf)
1629 		kfree(so->rx.buf);
1630 
1631 	if (so->tx.buf != so->tx.sbuf)
1632 		kfree(so->tx.buf);
1633 }
1634 
1635 static int isotp_init(struct sock *sk)
1636 {
1637 	struct isotp_sock *so = isotp_sk(sk);
1638 
1639 	so->ifindex = 0;
1640 	so->bound = 0;
1641 
1642 	so->opt.flags = CAN_ISOTP_DEFAULT_FLAGS;
1643 	so->opt.ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS;
1644 	so->opt.rx_ext_address = CAN_ISOTP_DEFAULT_EXT_ADDRESS;
1645 	so->opt.rxpad_content = CAN_ISOTP_DEFAULT_PAD_CONTENT;
1646 	so->opt.txpad_content = CAN_ISOTP_DEFAULT_PAD_CONTENT;
1647 	so->opt.frame_txtime = CAN_ISOTP_DEFAULT_FRAME_TXTIME;
1648 	so->frame_txtime = CAN_ISOTP_DEFAULT_FRAME_TXTIME;
1649 	so->rxfc.bs = CAN_ISOTP_DEFAULT_RECV_BS;
1650 	so->rxfc.stmin = CAN_ISOTP_DEFAULT_RECV_STMIN;
1651 	so->rxfc.wftmax = CAN_ISOTP_DEFAULT_RECV_WFTMAX;
1652 	so->ll.mtu = CAN_ISOTP_DEFAULT_LL_MTU;
1653 	so->ll.tx_dl = CAN_ISOTP_DEFAULT_LL_TX_DL;
1654 	so->ll.tx_flags = CAN_ISOTP_DEFAULT_LL_TX_FLAGS;
1655 
1656 	/* set ll_dl for tx path to similar place as for rx */
1657 	so->tx.ll_dl = so->ll.tx_dl;
1658 
1659 	so->rx.state = ISOTP_IDLE;
1660 	so->tx.state = ISOTP_IDLE;
1661 
1662 	so->rx.buf = so->rx.sbuf;
1663 	so->tx.buf = so->tx.sbuf;
1664 	so->rx.buflen = ARRAY_SIZE(so->rx.sbuf);
1665 	so->tx.buflen = ARRAY_SIZE(so->tx.sbuf);
1666 
1667 	hrtimer_setup(&so->rxtimer, isotp_rx_timer_handler, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1668 	hrtimer_setup(&so->txtimer, isotp_tx_timer_handler, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1669 	hrtimer_setup(&so->txfrtimer, isotp_txfr_timer_handler, CLOCK_MONOTONIC,
1670 		      HRTIMER_MODE_REL_SOFT);
1671 
1672 	init_waitqueue_head(&so->wait);
1673 	spin_lock_init(&so->rx_lock);
1674 
1675 	spin_lock(&isotp_notifier_lock);
1676 	list_add_tail(&so->notifier, &isotp_notifier_list);
1677 	spin_unlock(&isotp_notifier_lock);
1678 
1679 	/* re-assign default can_sock_destruct() reference */
1680 	sk->sk_destruct = isotp_sock_destruct;
1681 
1682 	return 0;
1683 }
1684 
1685 static __poll_t isotp_poll(struct file *file, struct socket *sock, poll_table *wait)
1686 {
1687 	struct sock *sk = sock->sk;
1688 	struct isotp_sock *so = isotp_sk(sk);
1689 
1690 	__poll_t mask = datagram_poll(file, sock, wait);
1691 	poll_wait(file, &so->wait, wait);
1692 
1693 	/* Check for false positives due to TX state */
1694 	if ((mask & EPOLLWRNORM) && (so->tx.state != ISOTP_IDLE))
1695 		mask &= ~(EPOLLOUT | EPOLLWRNORM);
1696 
1697 	return mask;
1698 }
1699 
1700 static int isotp_sock_no_ioctlcmd(struct socket *sock, unsigned int cmd,
1701 				  unsigned long arg)
1702 {
1703 	/* no ioctls for socket layer -> hand it down to NIC layer */
1704 	return -ENOIOCTLCMD;
1705 }
1706 
1707 static const struct proto_ops isotp_ops = {
1708 	.family = PF_CAN,
1709 	.release = isotp_release,
1710 	.bind = isotp_bind,
1711 	.connect = sock_no_connect,
1712 	.socketpair = sock_no_socketpair,
1713 	.accept = sock_no_accept,
1714 	.getname = isotp_getname,
1715 	.poll = isotp_poll,
1716 	.ioctl = isotp_sock_no_ioctlcmd,
1717 	.gettstamp = sock_gettstamp,
1718 	.listen = sock_no_listen,
1719 	.shutdown = sock_no_shutdown,
1720 	.setsockopt = isotp_setsockopt,
1721 	.getsockopt = isotp_getsockopt,
1722 	.sendmsg = isotp_sendmsg,
1723 	.recvmsg = isotp_recvmsg,
1724 	.mmap = sock_no_mmap,
1725 };
1726 
1727 static struct proto isotp_proto __read_mostly = {
1728 	.name = "CAN_ISOTP",
1729 	.owner = THIS_MODULE,
1730 	.obj_size = sizeof(struct isotp_sock),
1731 	.init = isotp_init,
1732 };
1733 
1734 static const struct can_proto isotp_can_proto = {
1735 	.type = SOCK_DGRAM,
1736 	.protocol = CAN_ISOTP,
1737 	.ops = &isotp_ops,
1738 	.prot = &isotp_proto,
1739 };
1740 
1741 static struct notifier_block canisotp_notifier = {
1742 	.notifier_call = isotp_notifier
1743 };
1744 
1745 static __init int isotp_module_init(void)
1746 {
1747 	int err;
1748 
1749 	max_pdu_size = max_t(unsigned int, max_pdu_size, MAX_12BIT_PDU_SIZE);
1750 	max_pdu_size = min_t(unsigned int, max_pdu_size, MAX_PDU_SIZE);
1751 
1752 	pr_info("can: isotp protocol (max_pdu_size %d)\n", max_pdu_size);
1753 
1754 	err = can_proto_register(&isotp_can_proto);
1755 	if (err < 0)
1756 		pr_err("can: registration of isotp protocol failed %pe\n", ERR_PTR(err));
1757 	else
1758 		register_netdevice_notifier(&canisotp_notifier);
1759 
1760 	return err;
1761 }
1762 
1763 static __exit void isotp_module_exit(void)
1764 {
1765 	can_proto_unregister(&isotp_can_proto);
1766 	unregister_netdevice_notifier(&canisotp_notifier);
1767 }
1768 
1769 module_init(isotp_module_init);
1770 module_exit(isotp_module_exit);
1771