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