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