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