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