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