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