File Index
Files and directories
Sign in
FILE

isotp.c

File preview with syntax highlighting.

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