mcp251xfd-core.c 75.0 KB
Newer Older
1 2
// SPDX-License-Identifier: GPL-2.0
//
3
// mcp251xfd - Microchip MCP251xFD Family CAN controller driver
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
//
// Copyright (c) 2019, 2020 Pengutronix,
//                          Marc Kleine-Budde <kernel@pengutronix.de>
//
// Based on:
//
// CAN bus driver for Microchip 25XXFD CAN Controller with SPI Interface
//
// Copyright (c) 2019 Martin Sperl <kernel@martin.sperl.org>
//

#include <linux/bitfield.h>
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pm_runtime.h>

#include <asm/unaligned.h>

26
#include "mcp251xfd.h"
27

28
#define DEVICE_NAME "mcp251xfd"
29

30 31 32 33 34
static const struct mcp251xfd_devtype_data mcp251xfd_devtype_data_mcp2517fd = {
	.quirks = MCP251XFD_QUIRK_MAB_NO_WARN | MCP251XFD_QUIRK_CRC_REG |
		MCP251XFD_QUIRK_CRC_RX | MCP251XFD_QUIRK_CRC_TX |
		MCP251XFD_QUIRK_ECC,
	.model = MCP251XFD_MODEL_MCP2517FD,
35 36
};

37 38 39 40
static const struct mcp251xfd_devtype_data mcp251xfd_devtype_data_mcp2518fd = {
	.quirks = MCP251XFD_QUIRK_CRC_REG | MCP251XFD_QUIRK_CRC_RX |
		MCP251XFD_QUIRK_CRC_TX | MCP251XFD_QUIRK_ECC,
	.model = MCP251XFD_MODEL_MCP2518FD,
41 42 43
};

/* Autodetect model, start with CRC enabled. */
44 45 46 47
static const struct mcp251xfd_devtype_data mcp251xfd_devtype_data_mcp251xfd = {
	.quirks = MCP251XFD_QUIRK_CRC_REG | MCP251XFD_QUIRK_CRC_RX |
		MCP251XFD_QUIRK_CRC_TX | MCP251XFD_QUIRK_ECC,
	.model = MCP251XFD_MODEL_MCP251XFD,
48 49
};

50
static const struct can_bittiming_const mcp251xfd_bittiming_const = {
51 52 53 54 55 56 57 58 59 60 61
	.name = DEVICE_NAME,
	.tseg1_min = 2,
	.tseg1_max = 256,
	.tseg2_min = 1,
	.tseg2_max = 128,
	.sjw_max = 128,
	.brp_min = 1,
	.brp_max = 256,
	.brp_inc = 1,
};

62
static const struct can_bittiming_const mcp251xfd_data_bittiming_const = {
63 64 65 66 67 68 69 70 71 72 73
	.name = DEVICE_NAME,
	.tseg1_min = 1,
	.tseg1_max = 32,
	.tseg2_min = 1,
	.tseg2_max = 16,
	.sjw_max = 16,
	.brp_min = 1,
	.brp_max = 256,
	.brp_inc = 1,
};

74
static const char *__mcp251xfd_get_model_str(enum mcp251xfd_model model)
75 76
{
	switch (model) {
77
	case MCP251XFD_MODEL_MCP2517FD:
T
Tom Rix 已提交
78
		return "MCP2517FD";
79
	case MCP251XFD_MODEL_MCP2518FD:
T
Tom Rix 已提交
80
		return "MCP2518FD";
81
	case MCP251XFD_MODEL_MCP251XFD:
T
Tom Rix 已提交
82
		return "MCP251xFD";
83 84 85 86 87 88
	}

	return "<unknown>";
}

static inline const char *
89
mcp251xfd_get_model_str(const struct mcp251xfd_priv *priv)
90
{
91
	return __mcp251xfd_get_model_str(priv->devtype_data.model);
92 93
}

94
static const char *mcp251xfd_get_mode_str(const u8 mode)
95 96
{
	switch (mode) {
97
	case MCP251XFD_REG_CON_MODE_MIXED:
T
Tom Rix 已提交
98
		return "Mixed (CAN FD/CAN 2.0)";
99
	case MCP251XFD_REG_CON_MODE_SLEEP:
T
Tom Rix 已提交
100
		return "Sleep";
101
	case MCP251XFD_REG_CON_MODE_INT_LOOPBACK:
T
Tom Rix 已提交
102
		return "Internal Loopback";
103
	case MCP251XFD_REG_CON_MODE_LISTENONLY:
T
Tom Rix 已提交
104
		return "Listen Only";
105
	case MCP251XFD_REG_CON_MODE_CONFIG:
T
Tom Rix 已提交
106
		return "Configuration";
107
	case MCP251XFD_REG_CON_MODE_EXT_LOOPBACK:
T
Tom Rix 已提交
108
		return "External Loopback";
109
	case MCP251XFD_REG_CON_MODE_CAN2_0:
T
Tom Rix 已提交
110
		return "CAN 2.0";
111
	case MCP251XFD_REG_CON_MODE_RESTRICTED:
T
Tom Rix 已提交
112
		return "Restricted Operation";
113 114 115 116 117
	}

	return "<unknown>";
}

118
static inline int mcp251xfd_vdd_enable(const struct mcp251xfd_priv *priv)
119 120 121 122 123 124 125
{
	if (!priv->reg_vdd)
		return 0;

	return regulator_enable(priv->reg_vdd);
}

126
static inline int mcp251xfd_vdd_disable(const struct mcp251xfd_priv *priv)
127 128 129 130 131 132 133 134
{
	if (!priv->reg_vdd)
		return 0;

	return regulator_disable(priv->reg_vdd);
}

static inline int
135
mcp251xfd_transceiver_enable(const struct mcp251xfd_priv *priv)
136 137 138 139 140 141 142 143
{
	if (!priv->reg_xceiver)
		return 0;

	return regulator_enable(priv->reg_xceiver);
}

static inline int
144
mcp251xfd_transceiver_disable(const struct mcp251xfd_priv *priv)
145 146 147 148 149 150 151
{
	if (!priv->reg_xceiver)
		return 0;

	return regulator_disable(priv->reg_xceiver);
}

152
static int mcp251xfd_clks_and_vdd_enable(const struct mcp251xfd_priv *priv)
153 154 155 156 157 158 159
{
	int err;

	err = clk_prepare_enable(priv->clk);
	if (err)
		return err;

160
	err = mcp251xfd_vdd_enable(priv);
161 162 163 164
	if (err)
		clk_disable_unprepare(priv->clk);

	/* Wait for oscillator stabilisation time after power up */
165 166
	usleep_range(MCP251XFD_OSC_STAB_SLEEP_US,
		     2 * MCP251XFD_OSC_STAB_SLEEP_US);
167 168 169 170

	return err;
}

171
static int mcp251xfd_clks_and_vdd_disable(const struct mcp251xfd_priv *priv)
172 173 174
{
	int err;

175
	err = mcp251xfd_vdd_disable(priv);
176 177 178 179 180 181 182 183 184
	if (err)
		return err;

	clk_disable_unprepare(priv->clk);

	return 0;
}

static inline u8
185 186
mcp251xfd_cmd_prepare_write_reg(const struct mcp251xfd_priv *priv,
				union mcp251xfd_write_reg_buf *write_reg_buf,
187 188 189 190 191 192
				const u16 reg, const u32 mask, const u32 val)
{
	u8 first_byte, last_byte, len;
	u8 *data;
	__le32 val_le32;

193 194
	first_byte = mcp251xfd_first_byte_set(mask);
	last_byte = mcp251xfd_last_byte_set(mask);
195 196
	len = last_byte - first_byte + 1;

197
	data = mcp251xfd_spi_cmd_write(priv, write_reg_buf, reg + first_byte);
198 199 200
	val_le32 = cpu_to_le32(val >> BITS_PER_BYTE * first_byte);
	memcpy(data, &val_le32, len);

201
	if (priv->devtype_data.quirks & MCP251XFD_QUIRK_CRC_REG) {
202 203
		u16 crc;

204
		mcp251xfd_spi_cmd_crc_set_len_in_reg(&write_reg_buf->crc.cmd,
205 206 207
						     len);
		/* CRC */
		len += sizeof(write_reg_buf->crc.cmd);
208
		crc = mcp251xfd_crc16_compute(&write_reg_buf->crc, len);
209 210 211 212 213 214 215 216 217 218 219 220
		put_unaligned_be16(crc, (void *)write_reg_buf + len);

		/* Total length */
		len += sizeof(write_reg_buf->crc.crc);
	} else {
		len += sizeof(write_reg_buf->nocrc.cmd);
	}

	return len;
}

static inline int
221
mcp251xfd_tef_tail_get_from_chip(const struct mcp251xfd_priv *priv,
222 223 224 225 226
				 u8 *tef_tail)
{
	u32 tef_ua;
	int err;

227
	err = regmap_read(priv->map_reg, MCP251XFD_REG_TEFUA, &tef_ua);
228 229 230
	if (err)
		return err;

231
	*tef_tail = tef_ua / sizeof(struct mcp251xfd_hw_tef_obj);
232 233 234 235 236

	return 0;
}

static inline int
237
mcp251xfd_tx_tail_get_from_chip(const struct mcp251xfd_priv *priv,
238 239 240 241 242 243
				u8 *tx_tail)
{
	u32 fifo_sta;
	int err;

	err = regmap_read(priv->map_reg,
244
			  MCP251XFD_REG_FIFOSTA(MCP251XFD_TX_FIFO),
245 246 247 248
			  &fifo_sta);
	if (err)
		return err;

249
	*tx_tail = FIELD_GET(MCP251XFD_REG_FIFOSTA_FIFOCI_MASK, fifo_sta);
250 251 252 253 254

	return 0;
}

static inline int
255 256
mcp251xfd_rx_head_get_from_chip(const struct mcp251xfd_priv *priv,
				const struct mcp251xfd_rx_ring *ring,
257 258 259 260 261
				u8 *rx_head)
{
	u32 fifo_sta;
	int err;

262
	err = regmap_read(priv->map_reg, MCP251XFD_REG_FIFOSTA(ring->fifo_nr),
263 264 265 266
			  &fifo_sta);
	if (err)
		return err;

267
	*rx_head = FIELD_GET(MCP251XFD_REG_FIFOSTA_FIFOCI_MASK, fifo_sta);
268 269 270 271 272

	return 0;
}

static inline int
273 274
mcp251xfd_rx_tail_get_from_chip(const struct mcp251xfd_priv *priv,
				const struct mcp251xfd_rx_ring *ring,
275 276 277 278 279
				u8 *rx_tail)
{
	u32 fifo_ua;
	int err;

280
	err = regmap_read(priv->map_reg, MCP251XFD_REG_FIFOUA(ring->fifo_nr),
281 282 283 284
			  &fifo_ua);
	if (err)
		return err;

285
	fifo_ua -= ring->base - MCP251XFD_RAM_START;
286 287 288 289 290 291
	*rx_tail = fifo_ua / ring->obj_size;

	return 0;
}

static void
292 293 294
mcp251xfd_tx_ring_init_tx_obj(const struct mcp251xfd_priv *priv,
			      const struct mcp251xfd_tx_ring *ring,
			      struct mcp251xfd_tx_obj *tx_obj,
295 296 297 298 299 300 301
			      const u8 rts_buf_len,
			      const u8 n)
{
	struct spi_transfer *xfer;
	u16 addr;

	/* FIFO load */
302 303 304
	addr = mcp251xfd_get_tx_obj_addr(ring, n);
	if (priv->devtype_data.quirks & MCP251XFD_QUIRK_CRC_TX)
		mcp251xfd_spi_cmd_write_crc_set_addr(&tx_obj->buf.crc.cmd,
305 306
						     addr);
	else
307
		mcp251xfd_spi_cmd_write_nocrc(&tx_obj->buf.nocrc.cmd,
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
					      addr);

	xfer = &tx_obj->xfer[0];
	xfer->tx_buf = &tx_obj->buf;
	xfer->len = 0;	/* actual len is assigned on the fly */
	xfer->cs_change = 1;
	xfer->cs_change_delay.value = 0;
	xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;

	/* FIFO request to send */
	xfer = &tx_obj->xfer[1];
	xfer->tx_buf = &ring->rts_buf;
	xfer->len = rts_buf_len;

	/* SPI message */
	spi_message_init_with_transfers(&tx_obj->msg, tx_obj->xfer,
					ARRAY_SIZE(tx_obj->xfer));
}

327
static void mcp251xfd_ring_init(struct mcp251xfd_priv *priv)
328
{
329
	struct mcp251xfd_tef_ring *tef_ring;
330 331 332
	struct mcp251xfd_tx_ring *tx_ring;
	struct mcp251xfd_rx_ring *rx_ring, *prev_rx_ring = NULL;
	struct mcp251xfd_tx_obj *tx_obj;
333 334 335
	u32 val;
	u16 addr;
	u8 len;
336
	int i, j;
337 338

	/* TEF */
339 340 341
	tef_ring = priv->tef;
	tef_ring->head = 0;
	tef_ring->tail = 0;
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
	/* FIFO increment TEF tail pointer */
	addr = MCP251XFD_REG_TEFCON;
	val = MCP251XFD_REG_TEFCON_UINC;
	len = mcp251xfd_cmd_prepare_write_reg(priv, &tef_ring->uinc_buf,
					      addr, val, val);

	for (j = 0; j < ARRAY_SIZE(tef_ring->uinc_xfer); j++) {
		struct spi_transfer *xfer;

		xfer = &tef_ring->uinc_xfer[j];
		xfer->tx_buf = &tef_ring->uinc_buf;
		xfer->len = len;
		xfer->cs_change = 1;
		xfer->cs_change_delay.value = 0;
		xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
	}

360 361 362 363
	/* TX */
	tx_ring = priv->tx;
	tx_ring->head = 0;
	tx_ring->tail = 0;
364
	tx_ring->base = mcp251xfd_get_tef_obj_addr(tx_ring->obj_num);
365 366

	/* FIFO request to send */
367 368 369
	addr = MCP251XFD_REG_FIFOCON(MCP251XFD_TX_FIFO);
	val = MCP251XFD_REG_FIFOCON_TXREQ | MCP251XFD_REG_FIFOCON_UINC;
	len = mcp251xfd_cmd_prepare_write_reg(priv, &tx_ring->rts_buf,
370 371
					      addr, val, val);

372 373
	mcp251xfd_for_each_tx_obj(tx_ring, tx_obj, i)
		mcp251xfd_tx_ring_init_tx_obj(priv, tx_ring, tx_obj, len, i);
374 375

	/* RX */
376
	mcp251xfd_for_each_rx_ring(priv, rx_ring, i) {
377 378 379
		rx_ring->head = 0;
		rx_ring->tail = 0;
		rx_ring->nr = i;
380
		rx_ring->fifo_nr = MCP251XFD_RX_FIFO(i);
381 382 383

		if (!prev_rx_ring)
			rx_ring->base =
384
				mcp251xfd_get_tx_obj_addr(tx_ring,
385 386 387 388 389 390 391
							  tx_ring->obj_num);
		else
			rx_ring->base = prev_rx_ring->base +
				prev_rx_ring->obj_size *
				prev_rx_ring->obj_num;

		prev_rx_ring = rx_ring;
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

		/* FIFO increment RX tail pointer */
		addr = MCP251XFD_REG_FIFOCON(rx_ring->fifo_nr);
		val = MCP251XFD_REG_FIFOCON_UINC;
		len = mcp251xfd_cmd_prepare_write_reg(priv, &rx_ring->uinc_buf,
						      addr, val, val);

		for (j = 0; j < ARRAY_SIZE(rx_ring->uinc_xfer); j++) {
			struct spi_transfer *xfer;

			xfer = &rx_ring->uinc_xfer[j];
			xfer->tx_buf = &rx_ring->uinc_buf;
			xfer->len = len;
			xfer->cs_change = 1;
			xfer->cs_change_delay.value = 0;
			xfer->cs_change_delay.unit = SPI_DELAY_UNIT_NSECS;
		}
409 410 411
	}
}

412
static void mcp251xfd_ring_free(struct mcp251xfd_priv *priv)
413 414 415
{
	int i;

416
	for (i = ARRAY_SIZE(priv->rx) - 1; i >= 0; i--) {
417 418 419 420 421
		kfree(priv->rx[i]);
		priv->rx[i] = NULL;
	}
}

422
static int mcp251xfd_ring_alloc(struct mcp251xfd_priv *priv)
423
{
424 425
	struct mcp251xfd_tx_ring *tx_ring;
	struct mcp251xfd_rx_ring *rx_ring;
426 427 428 429
	int tef_obj_size, tx_obj_size, rx_obj_size;
	int tx_obj_num;
	int ram_free, i;

430
	tef_obj_size = sizeof(struct mcp251xfd_hw_tef_obj);
431 432
	/* listen-only mode works like FD mode */
	if (priv->can.ctrlmode & (CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_FD)) {
433 434 435
		tx_obj_num = MCP251XFD_TX_OBJ_NUM_CANFD;
		tx_obj_size = sizeof(struct mcp251xfd_hw_tx_obj_canfd);
		rx_obj_size = sizeof(struct mcp251xfd_hw_rx_obj_canfd);
436
	} else {
437 438 439
		tx_obj_num = MCP251XFD_TX_OBJ_NUM_CAN;
		tx_obj_size = sizeof(struct mcp251xfd_hw_tx_obj_can);
		rx_obj_size = sizeof(struct mcp251xfd_hw_rx_obj_can);
440 441 442 443 444 445
	}

	tx_ring = priv->tx;
	tx_ring->obj_num = tx_obj_num;
	tx_ring->obj_size = tx_obj_size;

446
	ram_free = MCP251XFD_RAM_SIZE - tx_obj_num *
447 448 449 450 451 452 453 454
		(tef_obj_size + tx_obj_size);

	for (i = 0;
	     i < ARRAY_SIZE(priv->rx) && ram_free >= rx_obj_size;
	     i++) {
		int rx_obj_num;

		rx_obj_num = ram_free / rx_obj_size;
455 456
		rx_obj_num = min(1 << (fls(rx_obj_num) - 1),
				 MCP251XFD_RX_OBJ_NUM_MAX);
457 458 459 460

		rx_ring = kzalloc(sizeof(*rx_ring) + rx_obj_size * rx_obj_num,
				  GFP_KERNEL);
		if (!rx_ring) {
461
			mcp251xfd_ring_free(priv);
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
			return -ENOMEM;
		}
		rx_ring->obj_num = rx_obj_num;
		rx_ring->obj_size = rx_obj_size;
		priv->rx[i] = rx_ring;

		ram_free -= rx_ring->obj_num * rx_ring->obj_size;
	}
	priv->rx_ring_num = i;

	netdev_dbg(priv->ndev,
		   "FIFO setup: TEF: %d*%d bytes = %d bytes, TX: %d*%d bytes = %d bytes\n",
		   tx_obj_num, tef_obj_size, tef_obj_size * tx_obj_num,
		   tx_obj_num, tx_obj_size, tx_obj_size * tx_obj_num);

477
	mcp251xfd_for_each_rx_ring(priv, rx_ring, i) {
478 479 480 481 482 483 484 485 486 487 488 489 490 491
		netdev_dbg(priv->ndev,
			   "FIFO setup: RX-%d: %d*%d bytes = %d bytes\n",
			   i, rx_ring->obj_num, rx_ring->obj_size,
			   rx_ring->obj_size * rx_ring->obj_num);
	}

	netdev_dbg(priv->ndev,
		   "FIFO setup: free: %d bytes\n",
		   ram_free);

	return 0;
}

static inline int
492
mcp251xfd_chip_get_mode(const struct mcp251xfd_priv *priv, u8 *mode)
493 494 495 496
{
	u32 val;
	int err;

497
	err = regmap_read(priv->map_reg, MCP251XFD_REG_CON, &val);
498 499 500
	if (err)
		return err;

501
	*mode = FIELD_GET(MCP251XFD_REG_CON_OPMOD_MASK, val);
502 503 504 505 506

	return 0;
}

static int
507
__mcp251xfd_chip_set_mode(const struct mcp251xfd_priv *priv,
508 509 510 511 512
			  const u8 mode_req, bool nowait)
{
	u32 con, con_reqop;
	int err;

513 514 515
	con_reqop = FIELD_PREP(MCP251XFD_REG_CON_REQOP_MASK, mode_req);
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_CON,
				 MCP251XFD_REG_CON_REQOP_MASK, con_reqop);
516 517 518
	if (err)
		return err;

519
	if (mode_req == MCP251XFD_REG_CON_MODE_SLEEP || nowait)
520 521
		return 0;

522 523
	err = regmap_read_poll_timeout(priv->map_reg, MCP251XFD_REG_CON, con,
				       FIELD_GET(MCP251XFD_REG_CON_OPMOD_MASK,
524
						 con) == mode_req,
525 526
				       MCP251XFD_POLL_SLEEP_US,
				       MCP251XFD_POLL_TIMEOUT_US);
527
	if (err) {
528
		u8 mode = FIELD_GET(MCP251XFD_REG_CON_OPMOD_MASK, con);
529 530 531

		netdev_err(priv->ndev,
			   "Controller failed to enter mode %s Mode (%u) and stays in %s Mode (%u).\n",
532 533
			   mcp251xfd_get_mode_str(mode_req), mode_req,
			   mcp251xfd_get_mode_str(mode), mode);
534 535 536 537 538 539 540
		return err;
	}

	return 0;
}

static inline int
541
mcp251xfd_chip_set_mode(const struct mcp251xfd_priv *priv,
542 543
			const u8 mode_req)
{
544
	return __mcp251xfd_chip_set_mode(priv, mode_req, false);
545 546 547
}

static inline int
548
mcp251xfd_chip_set_mode_nowait(const struct mcp251xfd_priv *priv,
549 550
			       const u8 mode_req)
{
551
	return __mcp251xfd_chip_set_mode(priv, mode_req, true);
552 553
}

554
static inline bool mcp251xfd_osc_invalid(u32 reg)
555 556 557 558
{
	return reg == 0x0 || reg == 0xffffffff;
}

559
static int mcp251xfd_chip_clock_enable(const struct mcp251xfd_priv *priv)
560 561 562 563 564 565 566
{
	u32 osc, osc_reference, osc_mask;
	int err;

	/* Set Power On Defaults for "Clock Output Divisor" and remove
	 * "Oscillator Disable" bit.
	 */
567 568 569 570
	osc = FIELD_PREP(MCP251XFD_REG_OSC_CLKODIV_MASK,
			 MCP251XFD_REG_OSC_CLKODIV_10);
	osc_reference = MCP251XFD_REG_OSC_OSCRDY;
	osc_mask = MCP251XFD_REG_OSC_OSCRDY | MCP251XFD_REG_OSC_PLLRDY;
571 572 573 574 575 576 577

	/* Note:
	 *
	 * If the controller is in Sleep Mode the following write only
	 * removes the "Oscillator Disable" bit and powers it up. All
	 * other bits are unaffected.
	 */
578
	err = regmap_write(priv->map_reg, MCP251XFD_REG_OSC, osc);
579 580 581 582
	if (err)
		return err;

	/* Wait for "Oscillator Ready" bit */
583
	err = regmap_read_poll_timeout(priv->map_reg, MCP251XFD_REG_OSC, osc,
584
				       (osc & osc_mask) == osc_reference,
585 586 587
				       MCP251XFD_OSC_STAB_SLEEP_US,
				       MCP251XFD_OSC_STAB_TIMEOUT_US);
	if (mcp251xfd_osc_invalid(osc)) {
588 589
		netdev_err(priv->ndev,
			   "Failed to detect %s (osc=0x%08x).\n",
590
			   mcp251xfd_get_model_str(priv), osc);
591 592 593 594 595 596 597 598 599 600 601 602 603
		return -ENODEV;
	} else if (err == -ETIMEDOUT) {
		netdev_err(priv->ndev,
			   "Timeout waiting for Oscillator Ready (osc=0x%08x, osc_reference=0x%08x)\n",
			   osc, osc_reference);
		return -ETIMEDOUT;
	} else if (err) {
		return err;
	}

	return 0;
}

604
static int mcp251xfd_chip_softreset_do(const struct mcp251xfd_priv *priv)
605
{
606
	const __be16 cmd = mcp251xfd_cmd_reset();
607 608 609 610 611
	int err;

	/* The Set Mode and SPI Reset command only seems to works if
	 * the controller is not in Sleep Mode.
	 */
612
	err = mcp251xfd_chip_clock_enable(priv);
613 614 615
	if (err)
		return err;

616
	err = mcp251xfd_chip_set_mode(priv, MCP251XFD_REG_CON_MODE_CONFIG);
617 618 619 620 621 622 623
	if (err)
		return err;

	/* spi_write_then_read() works with non DMA-safe buffers */
	return spi_write_then_read(priv->spi, &cmd, sizeof(cmd), NULL, 0);
}

624
static int mcp251xfd_chip_softreset_check(const struct mcp251xfd_priv *priv)
625 626 627 628 629
{
	u32 osc, osc_reference;
	u8 mode;
	int err;

630
	err = mcp251xfd_chip_get_mode(priv, &mode);
631 632 633
	if (err)
		return err;

634
	if (mode != MCP251XFD_REG_CON_MODE_CONFIG) {
635 636
		netdev_info(priv->ndev,
			    "Controller not in Config Mode after reset, but in %s Mode (%u).\n",
637
			    mcp251xfd_get_mode_str(mode), mode);
638 639 640
		return -ETIMEDOUT;
	}

641 642 643
	osc_reference = MCP251XFD_REG_OSC_OSCRDY |
		FIELD_PREP(MCP251XFD_REG_OSC_CLKODIV_MASK,
			   MCP251XFD_REG_OSC_CLKODIV_10);
644 645

	/* check reset defaults of OSC reg */
646
	err = regmap_read(priv->map_reg, MCP251XFD_REG_OSC, &osc);
647 648 649 650 651 652 653 654 655 656 657 658 659
	if (err)
		return err;

	if (osc != osc_reference) {
		netdev_info(priv->ndev,
			    "Controller failed to reset. osc=0x%08x, reference value=0x%08x\n",
			    osc, osc_reference);
		return -ETIMEDOUT;
	}

	return 0;
}

660
static int mcp251xfd_chip_softreset(const struct mcp251xfd_priv *priv)
661 662 663
{
	int err, i;

664
	for (i = 0; i < MCP251XFD_SOFTRESET_RETRIES_MAX; i++) {
665 666 667 668
		if (i)
			netdev_info(priv->ndev,
				    "Retrying to reset Controller.\n");

669
		err = mcp251xfd_chip_softreset_do(priv);
670 671 672 673 674
		if (err == -ETIMEDOUT)
			continue;
		if (err)
			return err;

675
		err = mcp251xfd_chip_softreset_check(priv);
676 677 678 679 680 681 682 683
		if (err == -ETIMEDOUT)
			continue;
		if (err)
			return err;

		return 0;
	}

684
	return err;
685 686
}

687
static int mcp251xfd_chip_clock_init(const struct mcp251xfd_priv *priv)
688 689 690 691 692 693 694 695
{
	u32 osc;
	int err;

	/* Activate Low Power Mode on Oscillator Disable. This only
	 * works on the MCP2518FD. The MCP2517FD will go into normal
	 * Sleep Mode instead.
	 */
696 697 698 699
	osc = MCP251XFD_REG_OSC_LPMEN |
		FIELD_PREP(MCP251XFD_REG_OSC_CLKODIV_MASK,
			   MCP251XFD_REG_OSC_CLKODIV_10);
	err = regmap_write(priv->map_reg, MCP251XFD_REG_OSC, osc);
700 701 702 703 704 705 706 707
	if (err)
		return err;

	/* Set Time Base Counter Prescaler to 1.
	 *
	 * This means an overflow of the 32 bit Time Base Counter
	 * register at 40 MHz every 107 seconds.
	 */
708 709
	return regmap_write(priv->map_reg, MCP251XFD_REG_TSCON,
			    MCP251XFD_REG_TSCON_TBCEN);
710 711
}

712
static int mcp251xfd_set_bittiming(const struct mcp251xfd_priv *priv)
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
{
	const struct can_bittiming *bt = &priv->can.bittiming;
	const struct can_bittiming *dbt = &priv->can.data_bittiming;
	u32 val = 0;
	s8 tdco;
	int err;

	/* CAN Control Register
	 *
	 * - no transmit bandwidth sharing
	 * - config mode
	 * - disable transmit queue
	 * - store in transmit FIFO event
	 * - transition to restricted operation mode on system error
	 * - ESI is transmitted recessive when ESI of message is high or
	 *   CAN controller error passive
	 * - restricted retransmission attempts,
	 *   use TQXCON_TXAT and FIFOCON_TXAT
	 * - wake-up filter bits T11FILTER
	 * - use CAN bus line filter for wakeup
	 * - protocol exception is treated as a form error
	 * - Do not compare data bytes
	 */
736 737 738 739 740 741 742 743 744
	val = FIELD_PREP(MCP251XFD_REG_CON_REQOP_MASK,
			 MCP251XFD_REG_CON_MODE_CONFIG) |
		MCP251XFD_REG_CON_STEF |
		MCP251XFD_REG_CON_ESIGM |
		MCP251XFD_REG_CON_RTXAT |
		FIELD_PREP(MCP251XFD_REG_CON_WFT_MASK,
			   MCP251XFD_REG_CON_WFT_T11FILTER) |
		MCP251XFD_REG_CON_WAKFIL |
		MCP251XFD_REG_CON_PXEDIS;
745 746

	if (!(priv->can.ctrlmode & CAN_CTRLMODE_FD_NON_ISO))
747
		val |= MCP251XFD_REG_CON_ISOCRCEN;
748

749
	err = regmap_write(priv->map_reg, MCP251XFD_REG_CON, val);
750 751 752 753
	if (err)
		return err;

	/* Nominal Bit Time */
754 755
	val = FIELD_PREP(MCP251XFD_REG_NBTCFG_BRP_MASK, bt->brp - 1) |
		FIELD_PREP(MCP251XFD_REG_NBTCFG_TSEG1_MASK,
756
			   bt->prop_seg + bt->phase_seg1 - 1) |
757
		FIELD_PREP(MCP251XFD_REG_NBTCFG_TSEG2_MASK,
758
			   bt->phase_seg2 - 1) |
759
		FIELD_PREP(MCP251XFD_REG_NBTCFG_SJW_MASK, bt->sjw - 1);
760

761
	err = regmap_write(priv->map_reg, MCP251XFD_REG_NBTCFG, val);
762 763 764 765 766 767 768
	if (err)
		return err;

	if (!(priv->can.ctrlmode & CAN_CTRLMODE_FD))
		return 0;

	/* Data Bit Time */
769 770
	val = FIELD_PREP(MCP251XFD_REG_DBTCFG_BRP_MASK, dbt->brp - 1) |
		FIELD_PREP(MCP251XFD_REG_DBTCFG_TSEG1_MASK,
771
			   dbt->prop_seg + dbt->phase_seg1 - 1) |
772
		FIELD_PREP(MCP251XFD_REG_DBTCFG_TSEG2_MASK,
773
			   dbt->phase_seg2 - 1) |
774
		FIELD_PREP(MCP251XFD_REG_DBTCFG_SJW_MASK, dbt->sjw - 1);
775

776
	err = regmap_write(priv->map_reg, MCP251XFD_REG_DBTCFG, val);
777 778 779 780 781 782
	if (err)
		return err;

	/* Transmitter Delay Compensation */
	tdco = clamp_t(int, dbt->brp * (dbt->prop_seg + dbt->phase_seg1),
		       -64, 63);
783 784 785
	val = FIELD_PREP(MCP251XFD_REG_TDC_TDCMOD_MASK,
			 MCP251XFD_REG_TDC_TDCMOD_AUTO) |
		FIELD_PREP(MCP251XFD_REG_TDC_TDCO_MASK, tdco);
786

787
	return regmap_write(priv->map_reg, MCP251XFD_REG_TDC, val);
788 789
}

790
static int mcp251xfd_chip_rx_int_enable(const struct mcp251xfd_priv *priv)
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
{
	u32 val;

	if (!priv->rx_int)
		return 0;

	/* Configure GPIOs:
	 * - PIN0: GPIO Input
	 * - PIN1: GPIO Input/RX Interrupt
	 *
	 * PIN1 must be Input, otherwise there is a glitch on the
	 * rx-INT line. It happens between setting the PIN as output
	 * (in the first byte of the SPI transfer) and configuring the
	 * PIN as interrupt (in the last byte of the SPI transfer).
	 */
806 807 808
	val = MCP251XFD_REG_IOCON_PM0 | MCP251XFD_REG_IOCON_TRIS1 |
		MCP251XFD_REG_IOCON_TRIS0;
	return regmap_write(priv->map_reg, MCP251XFD_REG_IOCON, val);
809 810
}

811
static int mcp251xfd_chip_rx_int_disable(const struct mcp251xfd_priv *priv)
812 813 814 815 816 817 818 819 820 821
{
	u32 val;

	if (!priv->rx_int)
		return 0;

	/* Configure GPIOs:
	 * - PIN0: GPIO Input
	 * - PIN1: GPIO Input
	 */
822 823 824
	val = MCP251XFD_REG_IOCON_PM1 | MCP251XFD_REG_IOCON_PM0 |
		MCP251XFD_REG_IOCON_TRIS1 | MCP251XFD_REG_IOCON_TRIS0;
	return regmap_write(priv->map_reg, MCP251XFD_REG_IOCON, val);
825 826 827
}

static int
828 829
mcp251xfd_chip_rx_fifo_init_one(const struct mcp251xfd_priv *priv,
				const struct mcp251xfd_rx_ring *ring)
830 831 832 833 834 835 836 837 838
{
	u32 fifo_con;

	/* Enable RXOVIE on _all_ RX FIFOs, not just the last one.
	 *
	 * FIFOs hit by a RX MAB overflow and RXOVIE enabled will
	 * generate a RXOVIF, use this to properly detect RX MAB
	 * overflows.
	 */
839
	fifo_con = FIELD_PREP(MCP251XFD_REG_FIFOCON_FSIZE_MASK,
840
			      ring->obj_num - 1) |
841 842 843
		MCP251XFD_REG_FIFOCON_RXTSEN |
		MCP251XFD_REG_FIFOCON_RXOVIE |
		MCP251XFD_REG_FIFOCON_TFNRFNIE;
844

845
	if (priv->can.ctrlmode & (CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_FD))
846 847
		fifo_con |= FIELD_PREP(MCP251XFD_REG_FIFOCON_PLSIZE_MASK,
				       MCP251XFD_REG_FIFOCON_PLSIZE_64);
848
	else
849 850
		fifo_con |= FIELD_PREP(MCP251XFD_REG_FIFOCON_PLSIZE_MASK,
				       MCP251XFD_REG_FIFOCON_PLSIZE_8);
851 852

	return regmap_write(priv->map_reg,
853
			    MCP251XFD_REG_FIFOCON(ring->fifo_nr), fifo_con);
854 855 856
}

static int
857 858
mcp251xfd_chip_rx_filter_init_one(const struct mcp251xfd_priv *priv,
				  const struct mcp251xfd_rx_ring *ring)
859 860 861
{
	u32 fltcon;

862 863
	fltcon = MCP251XFD_REG_FLTCON_FLTEN(ring->nr) |
		MCP251XFD_REG_FLTCON_FBP(ring->nr, ring->fifo_nr);
864 865

	return regmap_update_bits(priv->map_reg,
866 867
				  MCP251XFD_REG_FLTCON(ring->nr >> 2),
				  MCP251XFD_REG_FLTCON_FLT_MASK(ring->nr),
868 869 870
				  fltcon);
}

871
static int mcp251xfd_chip_fifo_init(const struct mcp251xfd_priv *priv)
872
{
873 874
	const struct mcp251xfd_tx_ring *tx_ring = priv->tx;
	const struct mcp251xfd_rx_ring *rx_ring;
875 876 877 878
	u32 val;
	int err, n;

	/* TEF */
879
	val = FIELD_PREP(MCP251XFD_REG_TEFCON_FSIZE_MASK,
880
			 tx_ring->obj_num - 1) |
881 882 883
		MCP251XFD_REG_TEFCON_TEFTSEN |
		MCP251XFD_REG_TEFCON_TEFOVIE |
		MCP251XFD_REG_TEFCON_TEFNEIE;
884

885
	err = regmap_write(priv->map_reg, MCP251XFD_REG_TEFCON, val);
886 887 888 889
	if (err)
		return err;

	/* FIFO 1 - TX */
890
	val = FIELD_PREP(MCP251XFD_REG_FIFOCON_FSIZE_MASK,
891
			 tx_ring->obj_num - 1) |
892 893
		MCP251XFD_REG_FIFOCON_TXEN |
		MCP251XFD_REG_FIFOCON_TXATIE;
894

895
	if (priv->can.ctrlmode & (CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_FD))
896 897
		val |= FIELD_PREP(MCP251XFD_REG_FIFOCON_PLSIZE_MASK,
				  MCP251XFD_REG_FIFOCON_PLSIZE_64);
898
	else
899 900
		val |= FIELD_PREP(MCP251XFD_REG_FIFOCON_PLSIZE_MASK,
				  MCP251XFD_REG_FIFOCON_PLSIZE_8);
901 902

	if (priv->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
903 904
		val |= FIELD_PREP(MCP251XFD_REG_FIFOCON_TXAT_MASK,
				  MCP251XFD_REG_FIFOCON_TXAT_ONE_SHOT);
905
	else
906 907
		val |= FIELD_PREP(MCP251XFD_REG_FIFOCON_TXAT_MASK,
				  MCP251XFD_REG_FIFOCON_TXAT_UNLIMITED);
908 909

	err = regmap_write(priv->map_reg,
910
			   MCP251XFD_REG_FIFOCON(MCP251XFD_TX_FIFO),
911 912 913 914 915
			   val);
	if (err)
		return err;

	/* RX FIFOs */
916 917
	mcp251xfd_for_each_rx_ring(priv, rx_ring, n) {
		err = mcp251xfd_chip_rx_fifo_init_one(priv, rx_ring);
918 919 920
		if (err)
			return err;

921
		err = mcp251xfd_chip_rx_filter_init_one(priv, rx_ring);
922 923 924 925 926 927 928
		if (err)
			return err;
	}

	return 0;
}

929
static int mcp251xfd_chip_ecc_init(struct mcp251xfd_priv *priv)
930
{
931
	struct mcp251xfd_ecc *ecc = &priv->ecc;
932 933 934 935 936 937
	void *ram;
	u32 val = 0;
	int err;

	ecc->ecc_stat = 0;

938 939
	if (priv->devtype_data.quirks & MCP251XFD_QUIRK_ECC)
		val = MCP251XFD_REG_ECCCON_ECCEN;
940

941 942
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_ECCCON,
				 MCP251XFD_REG_ECCCON_ECCEN, val);
943 944 945
	if (err)
		return err;

946
	ram = kzalloc(MCP251XFD_RAM_SIZE, GFP_KERNEL);
947 948 949
	if (!ram)
		return -ENOMEM;

950 951
	err = regmap_raw_write(priv->map_reg, MCP251XFD_RAM_START, ram,
			       MCP251XFD_RAM_SIZE);
952 953 954 955 956
	kfree(ram);

	return err;
}

957
static inline void mcp251xfd_ecc_tefif_successful(struct mcp251xfd_priv *priv)
958
{
959
	struct mcp251xfd_ecc *ecc = &priv->ecc;
960 961 962 963

	ecc->ecc_stat = 0;
}

964
static u8 mcp251xfd_get_normal_mode(const struct mcp251xfd_priv *priv)
965 966 967
{
	u8 mode;

968
	if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
969
		mode = MCP251XFD_REG_CON_MODE_LISTENONLY;
970
	else if (priv->can.ctrlmode & CAN_CTRLMODE_FD)
971
		mode = MCP251XFD_REG_CON_MODE_MIXED;
972
	else
973
		mode = MCP251XFD_REG_CON_MODE_CAN2_0;
974 975 976 977 978

	return mode;
}

static int
979
__mcp251xfd_chip_set_normal_mode(const struct mcp251xfd_priv *priv,
980 981 982 983
				 bool nowait)
{
	u8 mode;

984
	mode = mcp251xfd_get_normal_mode(priv);
985

986
	return __mcp251xfd_chip_set_mode(priv, mode, nowait);
987 988 989
}

static inline int
990
mcp251xfd_chip_set_normal_mode(const struct mcp251xfd_priv *priv)
991
{
992
	return __mcp251xfd_chip_set_normal_mode(priv, false);
993 994 995
}

static inline int
996
mcp251xfd_chip_set_normal_mode_nowait(const struct mcp251xfd_priv *priv)
997
{
998
	return __mcp251xfd_chip_set_normal_mode(priv, true);
999 1000
}

1001
static int mcp251xfd_chip_interrupts_enable(const struct mcp251xfd_priv *priv)
1002 1003 1004 1005
{
	u32 val;
	int err;

1006 1007
	val = MCP251XFD_REG_CRC_FERRIE | MCP251XFD_REG_CRC_CRCERRIE;
	err = regmap_write(priv->map_reg, MCP251XFD_REG_CRC, val);
1008 1009 1010
	if (err)
		return err;

1011 1012
	val = MCP251XFD_REG_ECCCON_DEDIE | MCP251XFD_REG_ECCCON_SECIE;
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_ECCCON, val, val);
1013 1014 1015
	if (err)
		return err;

1016 1017 1018 1019 1020 1021 1022 1023 1024
	val = MCP251XFD_REG_INT_CERRIE |
		MCP251XFD_REG_INT_SERRIE |
		MCP251XFD_REG_INT_RXOVIE |
		MCP251XFD_REG_INT_TXATIE |
		MCP251XFD_REG_INT_SPICRCIE |
		MCP251XFD_REG_INT_ECCIE |
		MCP251XFD_REG_INT_TEFIE |
		MCP251XFD_REG_INT_MODIE |
		MCP251XFD_REG_INT_RXIE;
1025 1026

	if (priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING)
1027
		val |= MCP251XFD_REG_INT_IVMIE;
1028

1029
	return regmap_write(priv->map_reg, MCP251XFD_REG_INT, val);
1030 1031
}

1032
static int mcp251xfd_chip_interrupts_disable(const struct mcp251xfd_priv *priv)
1033 1034 1035 1036
{
	int err;
	u32 mask;

1037
	err = regmap_write(priv->map_reg, MCP251XFD_REG_INT, 0);
1038 1039 1040
	if (err)
		return err;

1041 1042
	mask = MCP251XFD_REG_ECCCON_DEDIE | MCP251XFD_REG_ECCCON_SECIE;
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_ECCCON,
1043 1044 1045 1046
				 mask, 0x0);
	if (err)
		return err;

1047
	return regmap_write(priv->map_reg, MCP251XFD_REG_CRC, 0);
1048 1049
}

1050
static int mcp251xfd_chip_stop(struct mcp251xfd_priv *priv,
1051 1052 1053 1054
			       const enum can_state state)
{
	priv->can.state = state;

1055 1056 1057
	mcp251xfd_chip_interrupts_disable(priv);
	mcp251xfd_chip_rx_int_disable(priv);
	return mcp251xfd_chip_set_mode(priv, MCP251XFD_REG_CON_MODE_SLEEP);
1058 1059
}

1060
static int mcp251xfd_chip_start(struct mcp251xfd_priv *priv)
1061 1062 1063
{
	int err;

1064
	err = mcp251xfd_chip_softreset(priv);
1065 1066 1067
	if (err)
		goto out_chip_stop;

1068
	err = mcp251xfd_chip_clock_init(priv);
1069 1070 1071
	if (err)
		goto out_chip_stop;

1072
	err = mcp251xfd_set_bittiming(priv);
1073 1074 1075
	if (err)
		goto out_chip_stop;

1076
	err = mcp251xfd_chip_rx_int_enable(priv);
1077 1078 1079
	if (err)
		return err;

1080
	err = mcp251xfd_chip_ecc_init(priv);
1081 1082 1083
	if (err)
		goto out_chip_stop;

1084
	mcp251xfd_ring_init(priv);
1085

1086
	err = mcp251xfd_chip_fifo_init(priv);
1087 1088 1089 1090 1091
	if (err)
		goto out_chip_stop;

	priv->can.state = CAN_STATE_ERROR_ACTIVE;

1092
	err = mcp251xfd_chip_set_normal_mode(priv);
1093 1094 1095 1096 1097 1098
	if (err)
		goto out_chip_stop;

	return 0;

 out_chip_stop:
1099
	mcp251xfd_chip_stop(priv, CAN_STATE_STOPPED);
1100 1101 1102 1103

	return err;
}

1104
static int mcp251xfd_set_mode(struct net_device *ndev, enum can_mode mode)
1105
{
1106
	struct mcp251xfd_priv *priv = netdev_priv(ndev);
1107 1108 1109 1110
	int err;

	switch (mode) {
	case CAN_MODE_START:
1111
		err = mcp251xfd_chip_start(priv);
1112 1113 1114
		if (err)
			return err;

1115
		err = mcp251xfd_chip_interrupts_enable(priv);
1116
		if (err) {
1117
			mcp251xfd_chip_stop(priv, CAN_STATE_STOPPED);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
			return err;
		}

		netif_wake_queue(ndev);
		break;

	default:
		return -EOPNOTSUPP;
	}

	return 0;
}

1131
static int __mcp251xfd_get_berr_counter(const struct net_device *ndev,
1132 1133
					struct can_berr_counter *bec)
{
1134
	const struct mcp251xfd_priv *priv = netdev_priv(ndev);
1135 1136 1137
	u32 trec;
	int err;

1138
	err = regmap_read(priv->map_reg, MCP251XFD_REG_TREC, &trec);
1139 1140 1141
	if (err)
		return err;

1142
	if (trec & MCP251XFD_REG_TREC_TXBO)
1143 1144
		bec->txerr = 256;
	else
1145 1146
		bec->txerr = FIELD_GET(MCP251XFD_REG_TREC_TEC_MASK, trec);
	bec->rxerr = FIELD_GET(MCP251XFD_REG_TREC_REC_MASK, trec);
1147 1148 1149 1150

	return 0;
}

1151
static int mcp251xfd_get_berr_counter(const struct net_device *ndev,
1152 1153
				      struct can_berr_counter *bec)
{
1154
	const struct mcp251xfd_priv *priv = netdev_priv(ndev);
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

	/* Avoid waking up the controller if the interface is down */
	if (!(ndev->flags & IFF_UP))
		return 0;

	/* The controller is powered down during Bus Off, use saved
	 * bec values.
	 */
	if (priv->can.state == CAN_STATE_BUS_OFF) {
		*bec = priv->bec;
		return 0;
	}

1168
	return __mcp251xfd_get_berr_counter(ndev, bec);
1169 1170
}

1171
static int mcp251xfd_check_tef_tail(const struct mcp251xfd_priv *priv)
1172 1173 1174 1175
{
	u8 tef_tail_chip, tef_tail;
	int err;

1176
	if (!IS_ENABLED(CONFIG_CAN_MCP251XFD_SANITY))
1177 1178
		return 0;

1179
	err = mcp251xfd_tef_tail_get_from_chip(priv, &tef_tail_chip);
1180 1181 1182
	if (err)
		return err;

1183
	tef_tail = mcp251xfd_get_tef_tail(priv);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	if (tef_tail_chip != tef_tail) {
		netdev_err(priv->ndev,
			   "TEF tail of chip (0x%02x) and ours (0x%08x) inconsistent.\n",
			   tef_tail_chip, tef_tail);
		return -EILSEQ;
	}

	return 0;
}

static int
1195 1196
mcp251xfd_check_rx_tail(const struct mcp251xfd_priv *priv,
			const struct mcp251xfd_rx_ring *ring)
1197 1198 1199 1200
{
	u8 rx_tail_chip, rx_tail;
	int err;

1201
	if (!IS_ENABLED(CONFIG_CAN_MCP251XFD_SANITY))
1202 1203
		return 0;

1204
	err = mcp251xfd_rx_tail_get_from_chip(priv, ring, &rx_tail_chip);
1205 1206 1207
	if (err)
		return err;

1208
	rx_tail = mcp251xfd_get_rx_tail(ring);
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
	if (rx_tail_chip != rx_tail) {
		netdev_err(priv->ndev,
			   "RX tail of chip (%d) and ours (%d) inconsistent.\n",
			   rx_tail_chip, rx_tail);
		return -EILSEQ;
	}

	return 0;
}

static int
1220
mcp251xfd_handle_tefif_recover(const struct mcp251xfd_priv *priv, const u32 seq)
1221
{
1222
	const struct mcp251xfd_tx_ring *tx_ring = priv->tx;
1223 1224 1225
	u32 tef_sta;
	int err;

1226
	err = regmap_read(priv->map_reg, MCP251XFD_REG_TEFSTA, &tef_sta);
1227 1228 1229
	if (err)
		return err;

1230
	if (tef_sta & MCP251XFD_REG_TEFSTA_TEFOVIF) {
1231 1232 1233 1234 1235 1236 1237
		netdev_err(priv->ndev,
			   "Transmit Event FIFO buffer overflow.\n");
		return -ENOBUFS;
	}

	netdev_info(priv->ndev,
		    "Transmit Event FIFO buffer %s. (seq=0x%08x, tef_tail=0x%08x, tef_head=0x%08x, tx_head=0x%08x)\n",
1238 1239
		    tef_sta & MCP251XFD_REG_TEFSTA_TEFFIF ?
		    "full" : tef_sta & MCP251XFD_REG_TEFSTA_TEFNEIF ?
1240
		    "not empty" : "empty",
1241
		    seq, priv->tef->tail, priv->tef->head, tx_ring->head);
1242 1243 1244 1245 1246 1247

	/* The Sequence Number in the TEF doesn't match our tef_tail. */
	return -EAGAIN;
}

static int
1248 1249
mcp251xfd_handle_tefif_one(struct mcp251xfd_priv *priv,
			   const struct mcp251xfd_hw_tef_obj *hw_tef_obj)
1250 1251 1252 1253
{
	struct net_device_stats *stats = &priv->ndev->stats;
	u32 seq, seq_masked, tef_tail_masked;

1254
	seq = FIELD_GET(MCP251XFD_OBJ_FLAGS_SEQ_MCP2518FD_MASK,
1255 1256 1257 1258 1259 1260 1261
			hw_tef_obj->flags);

	/* Use the MCP2517FD mask on the MCP2518FD, too. We only
	 * compare 7 bits, this should be enough to detect
	 * net-yet-completed, i.e. old TEF objects.
	 */
	seq_masked = seq &
1262
		field_mask(MCP251XFD_OBJ_FLAGS_SEQ_MCP2517FD_MASK);
1263
	tef_tail_masked = priv->tef->tail &
1264
		field_mask(MCP251XFD_OBJ_FLAGS_SEQ_MCP2517FD_MASK);
1265
	if (seq_masked != tef_tail_masked)
1266
		return mcp251xfd_handle_tefif_recover(priv, seq);
1267 1268 1269

	stats->tx_bytes +=
		can_rx_offload_get_echo_skb(&priv->offload,
1270
					    mcp251xfd_get_tef_tail(priv),
1271 1272
					    hw_tef_obj->ts);
	stats->tx_packets++;
1273
	priv->tef->tail++;
1274

1275
	return 0;
1276 1277
}

1278
static int mcp251xfd_tef_ring_update(struct mcp251xfd_priv *priv)
1279
{
1280
	const struct mcp251xfd_tx_ring *tx_ring = priv->tx;
1281 1282 1283 1284
	unsigned int new_head;
	u8 chip_tx_tail;
	int err;

1285
	err = mcp251xfd_tx_tail_get_from_chip(priv, &chip_tx_tail);
1286 1287 1288 1289 1290 1291
	if (err)
		return err;

	/* chip_tx_tail, is the next TX-Object send by the HW.
	 * The new TEF head must be >= the old head, ...
	 */
1292 1293
	new_head = round_down(priv->tef->head, tx_ring->obj_num) + chip_tx_tail;
	if (new_head <= priv->tef->head)
1294 1295 1296
		new_head += tx_ring->obj_num;

	/* ... but it cannot exceed the TX head. */
1297
	priv->tef->head = min(new_head, tx_ring->head);
1298

1299
	return mcp251xfd_check_tef_tail(priv);
1300 1301 1302
}

static inline int
1303 1304
mcp251xfd_tef_obj_read(const struct mcp251xfd_priv *priv,
		       struct mcp251xfd_hw_tef_obj *hw_tef_obj,
1305 1306
		       const u8 offset, const u8 len)
{
1307
	const struct mcp251xfd_tx_ring *tx_ring = priv->tx;
1308

1309
	if (IS_ENABLED(CONFIG_CAN_MCP251XFD_SANITY) &&
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
	    (offset > tx_ring->obj_num ||
	     len > tx_ring->obj_num ||
	     offset + len > tx_ring->obj_num)) {
		netdev_err(priv->ndev,
			   "Trying to read to many TEF objects (max=%d, offset=%d, len=%d).\n",
			   tx_ring->obj_num, offset, len);
		return -ERANGE;
	}

	return regmap_bulk_read(priv->map_rx,
1320
				mcp251xfd_get_tef_obj_addr(offset),
1321 1322 1323 1324
				hw_tef_obj,
				sizeof(*hw_tef_obj) / sizeof(u32) * len);
}

1325
static int mcp251xfd_handle_tefif(struct mcp251xfd_priv *priv)
1326
{
1327
	struct mcp251xfd_hw_tef_obj hw_tef_obj[MCP251XFD_TX_OBJ_NUM_MAX];
1328 1329 1330
	u8 tef_tail, len, l;
	int err, i;

1331
	err = mcp251xfd_tef_ring_update(priv);
1332 1333 1334
	if (err)
		return err;

1335 1336 1337 1338
	tef_tail = mcp251xfd_get_tef_tail(priv);
	len = mcp251xfd_get_tef_len(priv);
	l = mcp251xfd_get_tef_linear_len(priv);
	err = mcp251xfd_tef_obj_read(priv, hw_tef_obj, tef_tail, l);
1339 1340 1341 1342
	if (err)
		return err;

	if (l < len) {
1343
		err = mcp251xfd_tef_obj_read(priv, &hw_tef_obj[l], 0, len - l);
1344 1345 1346 1347 1348
		if (err)
			return err;
	}

	for (i = 0; i < len; i++) {
1349
		err = mcp251xfd_handle_tefif_one(priv, &hw_tef_obj[i]);
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
		/* -EAGAIN means the Sequence Number in the TEF
		 * doesn't match our tef_tail. This can happen if we
		 * read the TEF objects too early. Leave loop let the
		 * interrupt handler call us again.
		 */
		if (err == -EAGAIN)
			goto out_netif_wake_queue;
		if (err)
			return err;
	}

 out_netif_wake_queue:
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
	len = i;	/* number of handled goods TEFs */
	if (len) {
		struct mcp251xfd_tef_ring *ring = priv->tef;
		struct mcp251xfd_tx_ring *tx_ring = priv->tx;
		struct spi_transfer *last_xfer;

		tx_ring->tail += len;

		/* Increment the TEF FIFO tail pointer 'len' times in
		 * a single SPI message.
		 */

		/* Note:
		 *
		 * "cs_change == 1" on the last transfer results in an
		 * active chip select after the complete SPI
		 * message. This causes the controller to interpret
		 * the next register access as data. Temporary set
		 * "cs_change" of the last transfer to "0" to properly
		 * deactivate the chip select at the end of the
		 * message.
		 */
		last_xfer = &ring->uinc_xfer[len - 1];
		last_xfer->cs_change = 0;
		err = spi_sync_transfer(priv->spi, ring->uinc_xfer, len);
		last_xfer->cs_change = 1;
		if (err)
			return err;

		err = mcp251xfd_check_tef_tail(priv);
		if (err)
			return err;
	}

1396
	mcp251xfd_ecc_tefif_successful(priv);
1397

1398
	if (mcp251xfd_get_tx_free(priv->tx)) {
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
		/* Make sure that anybody stopping the queue after
		 * this sees the new tx_ring->tail.
		 */
		smp_mb();
		netif_wake_queue(priv->ndev);
	}

	return 0;
}

static int
1410 1411
mcp251xfd_rx_ring_update(const struct mcp251xfd_priv *priv,
			 struct mcp251xfd_rx_ring *ring)
1412 1413 1414 1415 1416
{
	u32 new_head;
	u8 chip_rx_head;
	int err;

1417
	err = mcp251xfd_rx_head_get_from_chip(priv, ring, &chip_rx_head);
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
	if (err)
		return err;

	/* chip_rx_head, is the next RX-Object filled by the HW.
	 * The new RX head must be >= the old head.
	 */
	new_head = round_down(ring->head, ring->obj_num) + chip_rx_head;
	if (new_head <= ring->head)
		new_head += ring->obj_num;

	ring->head = new_head;

1430
	return mcp251xfd_check_rx_tail(priv, ring);
1431 1432 1433
}

static void
1434 1435
mcp251xfd_hw_rx_obj_to_skb(const struct mcp251xfd_priv *priv,
			   const struct mcp251xfd_hw_rx_obj_canfd *hw_rx_obj,
1436 1437 1438 1439
			   struct sk_buff *skb)
{
	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;

1440
	if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_IDE) {
1441 1442
		u32 sid, eid;

1443 1444
		eid = FIELD_GET(MCP251XFD_OBJ_ID_EID_MASK, hw_rx_obj->id);
		sid = FIELD_GET(MCP251XFD_OBJ_ID_SID_MASK, hw_rx_obj->id);
1445 1446

		cfd->can_id = CAN_EFF_FLAG |
1447 1448
			FIELD_PREP(MCP251XFD_REG_FRAME_EFF_EID_MASK, eid) |
			FIELD_PREP(MCP251XFD_REG_FRAME_EFF_SID_MASK, sid);
1449
	} else {
1450
		cfd->can_id = FIELD_GET(MCP251XFD_OBJ_ID_SID_MASK,
1451 1452 1453 1454
					hw_rx_obj->id);
	}

	/* CANFD */
1455
	if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_FDF) {
1456 1457
		u8 dlc;

1458
		if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_ESI)
1459 1460
			cfd->flags |= CANFD_ESI;

1461
		if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_BRS)
1462 1463
			cfd->flags |= CANFD_BRS;

1464
		dlc = FIELD_GET(MCP251XFD_OBJ_FLAGS_DLC, hw_rx_obj->flags);
1465
		cfd->len = can_fd_dlc2len(dlc);
1466
	} else {
1467
		if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_RTR)
1468 1469
			cfd->can_id |= CAN_RTR_FLAG;

1470
		cfd->len = can_cc_dlc2len(FIELD_GET(MCP251XFD_OBJ_FLAGS_DLC,
1471 1472 1473 1474 1475 1476 1477
						 hw_rx_obj->flags));
	}

	memcpy(cfd->data, hw_rx_obj->data, cfd->len);
}

static int
1478 1479 1480
mcp251xfd_handle_rxif_one(struct mcp251xfd_priv *priv,
			  struct mcp251xfd_rx_ring *ring,
			  const struct mcp251xfd_hw_rx_obj_canfd *hw_rx_obj)
1481 1482 1483 1484 1485 1486
{
	struct net_device_stats *stats = &priv->ndev->stats;
	struct sk_buff *skb;
	struct canfd_frame *cfd;
	int err;

1487
	if (hw_rx_obj->flags & MCP251XFD_OBJ_FLAGS_FDF)
1488 1489 1490 1491 1492 1493 1494 1495 1496
		skb = alloc_canfd_skb(priv->ndev, &cfd);
	else
		skb = alloc_can_skb(priv->ndev, (struct can_frame **)&cfd);

	if (!cfd) {
		stats->rx_dropped++;
		return 0;
	}

1497
	mcp251xfd_hw_rx_obj_to_skb(priv, hw_rx_obj, skb);
1498 1499 1500 1501
	err = can_rx_offload_queue_sorted(&priv->offload, skb, hw_rx_obj->ts);
	if (err)
		stats->rx_fifo_errors++;

1502
	return 0;
1503 1504 1505
}

static inline int
1506 1507 1508
mcp251xfd_rx_obj_read(const struct mcp251xfd_priv *priv,
		      const struct mcp251xfd_rx_ring *ring,
		      struct mcp251xfd_hw_rx_obj_canfd *hw_rx_obj,
1509 1510 1511 1512 1513
		      const u8 offset, const u8 len)
{
	int err;

	err = regmap_bulk_read(priv->map_rx,
1514
			       mcp251xfd_get_rx_obj_addr(ring, offset),
1515 1516 1517 1518 1519 1520 1521
			       hw_rx_obj,
			       len * ring->obj_size / sizeof(u32));

	return err;
}

static int
1522 1523
mcp251xfd_handle_rxif_ring(struct mcp251xfd_priv *priv,
			   struct mcp251xfd_rx_ring *ring)
1524
{
1525
	struct mcp251xfd_hw_rx_obj_canfd *hw_rx_obj = ring->obj;
1526 1527 1528
	u8 rx_tail, len;
	int err, i;

1529
	err = mcp251xfd_rx_ring_update(priv, ring);
1530 1531 1532
	if (err)
		return err;

1533
	while ((len = mcp251xfd_get_rx_linear_len(ring))) {
1534 1535
		struct spi_transfer *last_xfer;

1536
		rx_tail = mcp251xfd_get_rx_tail(ring);
1537

1538
		err = mcp251xfd_rx_obj_read(priv, ring, hw_rx_obj,
1539 1540 1541 1542 1543
					    rx_tail, len);
		if (err)
			return err;

		for (i = 0; i < len; i++) {
1544
			err = mcp251xfd_handle_rxif_one(priv, ring,
1545 1546 1547 1548 1549
							(void *)hw_rx_obj +
							i * ring->obj_size);
			if (err)
				return err;
		}
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571

		/* Increment the RX FIFO tail pointer 'len' times in a
		 * single SPI message.
		 */
		ring->tail += len;

		/* Note:
		 *
		 * "cs_change == 1" on the last transfer results in an
		 * active chip select after the complete SPI
		 * message. This causes the controller to interpret
		 * the next register access as data. Temporary set
		 * "cs_change" of the last transfer to "0" to properly
		 * deactivate the chip select at the end of the
		 * message.
		 */
		last_xfer = &ring->uinc_xfer[len - 1];
		last_xfer->cs_change = 0;
		err = spi_sync_transfer(priv->spi, ring->uinc_xfer, len);
		last_xfer->cs_change = 1;
		if (err)
			return err;
1572 1573 1574 1575 1576
	}

	return 0;
}

1577
static int mcp251xfd_handle_rxif(struct mcp251xfd_priv *priv)
1578
{
1579
	struct mcp251xfd_rx_ring *ring;
1580 1581
	int err, n;

1582 1583
	mcp251xfd_for_each_rx_ring(priv, ring, n) {
		err = mcp251xfd_handle_rxif_ring(priv, ring);
1584 1585 1586 1587 1588 1589 1590
		if (err)
			return err;
	}

	return 0;
}

1591
static inline int mcp251xfd_get_timestamp(const struct mcp251xfd_priv *priv,
1592 1593
					  u32 *timestamp)
{
1594
	return regmap_read(priv->map_reg, MCP251XFD_REG_TBC, timestamp);
1595 1596 1597
}

static struct sk_buff *
1598
mcp251xfd_alloc_can_err_skb(const struct mcp251xfd_priv *priv,
1599 1600 1601 1602
			    struct can_frame **cf, u32 *timestamp)
{
	int err;

1603
	err = mcp251xfd_get_timestamp(priv, timestamp);
1604 1605 1606 1607 1608 1609
	if (err)
		return NULL;

	return alloc_can_err_skb(priv->ndev, cf);
}

1610
static int mcp251xfd_handle_rxovif(struct mcp251xfd_priv *priv)
1611 1612
{
	struct net_device_stats *stats = &priv->ndev->stats;
1613
	struct mcp251xfd_rx_ring *ring;
1614 1615 1616 1617 1618 1619 1620 1621
	struct sk_buff *skb;
	struct can_frame *cf;
	u32 timestamp, rxovif;
	int err, i;

	stats->rx_over_errors++;
	stats->rx_errors++;

1622
	err = regmap_read(priv->map_reg, MCP251XFD_REG_RXOVIF, &rxovif);
1623 1624 1625
	if (err)
		return err;

1626
	mcp251xfd_for_each_rx_ring(priv, ring, i) {
1627 1628 1629 1630
		if (!(rxovif & BIT(ring->fifo_nr)))
			continue;

		/* If SERRIF is active, there was a RX MAB overflow. */
1631
		if (priv->regs_status.intf & MCP251XFD_REG_INT_SERRIF) {
1632 1633 1634 1635 1636 1637 1638 1639 1640
			netdev_info(priv->ndev,
				    "RX-%d: MAB overflow detected.\n",
				    ring->nr);
		} else {
			netdev_info(priv->ndev,
				    "RX-%d: FIFO overflow.\n", ring->nr);
		}

		err = regmap_update_bits(priv->map_reg,
1641 1642
					 MCP251XFD_REG_FIFOSTA(ring->fifo_nr),
					 MCP251XFD_REG_FIFOSTA_RXOVIF,
1643 1644 1645 1646 1647
					 0x0);
		if (err)
			return err;
	}

1648
	skb = mcp251xfd_alloc_can_err_skb(priv, &cf, &timestamp);
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
	if (!skb)
		return 0;

	cf->can_id |= CAN_ERR_CRTL;
	cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;

	err = can_rx_offload_queue_sorted(&priv->offload, skb, timestamp);
	if (err)
		stats->rx_fifo_errors++;

	return 0;
}

1662
static int mcp251xfd_handle_txatif(struct mcp251xfd_priv *priv)
1663 1664 1665 1666 1667 1668
{
	netdev_info(priv->ndev, "%s\n", __func__);

	return 0;
}

1669
static int mcp251xfd_handle_ivmif(struct mcp251xfd_priv *priv)
1670 1671 1672 1673 1674 1675 1676
{
	struct net_device_stats *stats = &priv->ndev->stats;
	u32 bdiag1, timestamp;
	struct sk_buff *skb;
	struct can_frame *cf = NULL;
	int err;

1677
	err = mcp251xfd_get_timestamp(priv, &timestamp);
1678 1679 1680
	if (err)
		return err;

1681
	err = regmap_read(priv->map_reg, MCP251XFD_REG_BDIAG1, &bdiag1);
1682 1683 1684 1685 1686 1687
	if (err)
		return err;

	/* Write 0s to clear error bits, don't write 1s to non active
	 * bits, as they will be set.
	 */
1688
	err = regmap_write(priv->map_reg, MCP251XFD_REG_BDIAG1, 0x0);
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
	if (err)
		return err;

	priv->can.can_stats.bus_error++;

	skb = alloc_can_err_skb(priv->ndev, &cf);
	if (cf)
		cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;

	/* Controller misconfiguration */
1699
	if (WARN_ON(bdiag1 & MCP251XFD_REG_BDIAG1_DLCMM))
1700 1701 1702 1703
		netdev_err(priv->ndev,
			   "recv'd DLC is larger than PLSIZE of FIFO element.");

	/* RX errors */
1704 1705
	if (bdiag1 & (MCP251XFD_REG_BDIAG1_DCRCERR |
		      MCP251XFD_REG_BDIAG1_NCRCERR)) {
1706 1707 1708 1709 1710 1711
		netdev_dbg(priv->ndev, "CRC error\n");

		stats->rx_errors++;
		if (cf)
			cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
	}
1712 1713
	if (bdiag1 & (MCP251XFD_REG_BDIAG1_DSTUFERR |
		      MCP251XFD_REG_BDIAG1_NSTUFERR)) {
1714 1715 1716 1717 1718 1719
		netdev_dbg(priv->ndev, "Stuff error\n");

		stats->rx_errors++;
		if (cf)
			cf->data[2] |= CAN_ERR_PROT_STUFF;
	}
1720 1721
	if (bdiag1 & (MCP251XFD_REG_BDIAG1_DFORMERR |
		      MCP251XFD_REG_BDIAG1_NFORMERR)) {
1722 1723 1724 1725 1726 1727 1728 1729
		netdev_dbg(priv->ndev, "Format error\n");

		stats->rx_errors++;
		if (cf)
			cf->data[2] |= CAN_ERR_PROT_FORM;
	}

	/* TX errors */
1730
	if (bdiag1 & MCP251XFD_REG_BDIAG1_NACKERR) {
1731 1732 1733 1734 1735 1736 1737 1738
		netdev_dbg(priv->ndev, "NACK error\n");

		stats->tx_errors++;
		if (cf) {
			cf->can_id |= CAN_ERR_ACK;
			cf->data[2] |= CAN_ERR_PROT_TX;
		}
	}
1739 1740
	if (bdiag1 & (MCP251XFD_REG_BDIAG1_DBIT1ERR |
		      MCP251XFD_REG_BDIAG1_NBIT1ERR)) {
1741 1742 1743 1744 1745 1746
		netdev_dbg(priv->ndev, "Bit1 error\n");

		stats->tx_errors++;
		if (cf)
			cf->data[2] |= CAN_ERR_PROT_TX | CAN_ERR_PROT_BIT1;
	}
1747 1748
	if (bdiag1 & (MCP251XFD_REG_BDIAG1_DBIT0ERR |
		      MCP251XFD_REG_BDIAG1_NBIT0ERR)) {
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
		netdev_dbg(priv->ndev, "Bit0 error\n");

		stats->tx_errors++;
		if (cf)
			cf->data[2] |= CAN_ERR_PROT_TX | CAN_ERR_PROT_BIT0;
	}

	if (!cf)
		return 0;

	err = can_rx_offload_queue_sorted(&priv->offload, skb, timestamp);
	if (err)
		stats->rx_fifo_errors++;

	return 0;
}

1766
static int mcp251xfd_handle_cerrif(struct mcp251xfd_priv *priv)
1767 1768 1769 1770 1771 1772 1773 1774
{
	struct net_device_stats *stats = &priv->ndev->stats;
	struct sk_buff *skb;
	struct can_frame *cf = NULL;
	enum can_state new_state, rx_state, tx_state;
	u32 trec, timestamp;
	int err;

1775
	err = regmap_read(priv->map_reg, MCP251XFD_REG_TREC, &trec);
1776 1777 1778
	if (err)
		return err;

1779
	if (trec & MCP251XFD_REG_TREC_TXBO)
1780
		tx_state = CAN_STATE_BUS_OFF;
1781
	else if (trec & MCP251XFD_REG_TREC_TXBP)
1782
		tx_state = CAN_STATE_ERROR_PASSIVE;
1783
	else if (trec & MCP251XFD_REG_TREC_TXWARN)
1784 1785 1786 1787
		tx_state = CAN_STATE_ERROR_WARNING;
	else
		tx_state = CAN_STATE_ERROR_ACTIVE;

1788
	if (trec & MCP251XFD_REG_TREC_RXBP)
1789
		rx_state = CAN_STATE_ERROR_PASSIVE;
1790
	else if (trec & MCP251XFD_REG_TREC_RXWARN)
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
		rx_state = CAN_STATE_ERROR_WARNING;
	else
		rx_state = CAN_STATE_ERROR_ACTIVE;

	new_state = max(tx_state, rx_state);
	if (new_state == priv->can.state)
		return 0;

	/* The skb allocation might fail, but can_change_state()
	 * handles cf == NULL.
	 */
1802
	skb = mcp251xfd_alloc_can_err_skb(priv, &cf, &timestamp);
1803 1804 1805 1806 1807 1808 1809 1810
	can_change_state(priv->ndev, cf, tx_state, rx_state);

	if (new_state == CAN_STATE_BUS_OFF) {
		/* As we're going to switch off the chip now, let's
		 * save the error counters and return them to
		 * userspace, if do_get_berr_counter() is called while
		 * the chip is in Bus Off.
		 */
1811
		err = __mcp251xfd_get_berr_counter(priv->ndev, &priv->bec);
1812 1813 1814
		if (err)
			return err;

1815
		mcp251xfd_chip_stop(priv, CAN_STATE_BUS_OFF);
1816 1817 1818 1819 1820 1821 1822 1823 1824
		can_bus_off(priv->ndev);
	}

	if (!skb)
		return 0;

	if (new_state != CAN_STATE_BUS_OFF) {
		struct can_berr_counter bec;

1825
		err = mcp251xfd_get_berr_counter(priv->ndev, &bec);
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
		if (err)
			return err;
		cf->data[6] = bec.txerr;
		cf->data[7] = bec.rxerr;
	}

	err = can_rx_offload_queue_sorted(&priv->offload, skb, timestamp);
	if (err)
		stats->rx_fifo_errors++;

	return 0;
}

static int
1840
mcp251xfd_handle_modif(const struct mcp251xfd_priv *priv, bool *set_normal_mode)
1841
{
1842
	const u8 mode_reference = mcp251xfd_get_normal_mode(priv);
1843 1844 1845
	u8 mode;
	int err;

1846
	err = mcp251xfd_chip_get_mode(priv, &mode);
1847 1848 1849 1850 1851 1852
	if (err)
		return err;

	if (mode == mode_reference) {
		netdev_dbg(priv->ndev,
			   "Controller changed into %s Mode (%u).\n",
1853
			   mcp251xfd_get_mode_str(mode), mode);
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
		return 0;
	}

	/* According to MCP2517FD errata DS80000792B 1., during a TX
	 * MAB underflow, the controller will transition to Restricted
	 * Operation Mode or Listen Only Mode (depending on SERR2LOM).
	 *
	 * However this is not always the case. If SERR2LOM is
	 * configured for Restricted Operation Mode (SERR2LOM not set)
	 * the MCP2517FD will sometimes transition to Listen Only Mode
	 * first. When polling this bit we see that it will transition
	 * to Restricted Operation Mode shortly after.
	 */
1867 1868 1869
	if ((priv->devtype_data.quirks & MCP251XFD_QUIRK_MAB_NO_WARN) &&
	    (mode == MCP251XFD_REG_CON_MODE_RESTRICTED ||
	     mode == MCP251XFD_REG_CON_MODE_LISTENONLY))
1870 1871
		netdev_dbg(priv->ndev,
			   "Controller changed into %s Mode (%u).\n",
1872
			   mcp251xfd_get_mode_str(mode), mode);
1873 1874 1875
	else
		netdev_err(priv->ndev,
			   "Controller changed into %s Mode (%u).\n",
1876
			   mcp251xfd_get_mode_str(mode), mode);
1877 1878 1879 1880 1881 1882 1883

	/* After the application requests Normal mode, the Controller
	 * will automatically attempt to retransmit the message that
	 * caused the TX MAB underflow.
	 *
	 * However, if there is an ECC error in the TX-RAM, we first
	 * have to reload the tx-object before requesting Normal
1884
	 * mode. This is done later in mcp251xfd_handle_eccif().
1885
	 */
1886
	if (priv->regs_status.intf & MCP251XFD_REG_INT_ECCIF) {
1887 1888 1889 1890
		*set_normal_mode = true;
		return 0;
	}

1891
	return mcp251xfd_chip_set_normal_mode_nowait(priv);
1892 1893
}

1894
static int mcp251xfd_handle_serrif(struct mcp251xfd_priv *priv)
1895
{
1896
	struct mcp251xfd_ecc *ecc = &priv->ecc;
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
	struct net_device_stats *stats = &priv->ndev->stats;
	bool handled = false;

	/* TX MAB underflow
	 *
	 * According to MCP2517FD Errata DS80000792B 1. a TX MAB
	 * underflow is indicated by SERRIF and MODIF.
	 *
	 * In addition to the effects mentioned in the Errata, there
	 * are Bus Errors due to the aborted CAN frame, so a IVMIF
	 * will be seen as well.
	 *
	 * Sometimes there is an ECC error in the TX-RAM, which leads
	 * to a TX MAB underflow.
	 *
	 * However, probably due to a race condition, there is no
	 * associated MODIF pending.
	 *
	 * Further, there are situations, where the SERRIF is caused
	 * by an ECC error in the TX-RAM, but not even the ECCIF is
	 * set. This only seems to happen _after_ the first occurrence
	 * of a ECCIF (which is tracked in ecc->cnt).
	 *
	 * Treat all as a known system errors..
	 */
1922 1923 1924
	if ((priv->regs_status.intf & MCP251XFD_REG_INT_MODIF &&
	     priv->regs_status.intf & MCP251XFD_REG_INT_IVMIF) ||
	    priv->regs_status.intf & MCP251XFD_REG_INT_ECCIF ||
1925 1926 1927
	    ecc->cnt) {
		const char *msg;

1928
		if (priv->regs_status.intf & MCP251XFD_REG_INT_ECCIF ||
1929 1930 1931 1932 1933
		    ecc->cnt)
			msg = "TX MAB underflow due to ECC error detected.";
		else
			msg = "TX MAB underflow detected.";

1934
		if (priv->devtype_data.quirks & MCP251XFD_QUIRK_MAB_NO_WARN)
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
			netdev_dbg(priv->ndev, "%s\n", msg);
		else
			netdev_info(priv->ndev, "%s\n", msg);

		stats->tx_aborted_errors++;
		stats->tx_errors++;
		handled = true;
	}

	/* RX MAB overflow
	 *
	 * According to MCP2517FD Errata DS80000792B 1. a RX MAB
	 * overflow is indicated by SERRIF.
	 *
	 * In addition to the effects mentioned in the Errata, (most
	 * of the times) a RXOVIF is raised, if the FIFO that is being
	 * received into has the RXOVIE activated (and we have enabled
	 * RXOVIE on all FIFOs).
	 *
	 * Sometimes there is no RXOVIF just a RXIF is pending.
	 *
	 * Treat all as a known system errors..
	 */
1958 1959
	if (priv->regs_status.intf & MCP251XFD_REG_INT_RXOVIF ||
	    priv->regs_status.intf & MCP251XFD_REG_INT_RXIF) {
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
		stats->rx_dropped++;
		handled = true;
	}

	if (!handled)
		netdev_err(priv->ndev,
			   "Unhandled System Error Interrupt (intf=0x%08x)!\n",
			   priv->regs_status.intf);

	return 0;
}

static int
1973
mcp251xfd_handle_eccif_recover(struct mcp251xfd_priv *priv, u8 nr)
1974
{
1975 1976 1977
	struct mcp251xfd_tx_ring *tx_ring = priv->tx;
	struct mcp251xfd_ecc *ecc = &priv->ecc;
	struct mcp251xfd_tx_obj *tx_obj;
1978 1979 1980 1981
	u8 chip_tx_tail, tx_tail, offset;
	u16 addr;
	int err;

1982
	addr = FIELD_GET(MCP251XFD_REG_ECCSTAT_ERRADDR_MASK, ecc->ecc_stat);
1983

1984
	err = mcp251xfd_tx_tail_get_from_chip(priv, &chip_tx_tail);
1985 1986 1987
	if (err)
		return err;

1988
	tx_tail = mcp251xfd_get_tx_tail(tx_ring);
1989 1990 1991 1992 1993 1994 1995 1996
	offset = (nr - chip_tx_tail) & (tx_ring->obj_num - 1);

	/* Bail out if one of the following is met:
	 * - tx_tail information is inconsistent
	 * - for mcp2517fd: offset not 0
	 * - for mcp2518fd: offset not 0 or 1
	 */
	if (chip_tx_tail != tx_tail ||
1997
	    !(offset == 0 || (offset == 1 && mcp251xfd_is_2518(priv)))) {
1998 1999 2000 2001 2002 2003 2004 2005 2006
		netdev_err(priv->ndev,
			   "ECC Error information inconsistent (addr=0x%04x, nr=%d, tx_tail=0x%08x(%d), chip_tx_tail=%d, offset=%d).\n",
			   addr, nr, tx_ring->tail, tx_tail, chip_tx_tail,
			   offset);
		return -EINVAL;
	}

	netdev_info(priv->ndev,
		    "Recovering %s ECC Error at address 0x%04x (in TX-RAM, tx_obj=%d, tx_tail=0x%08x(%d), offset=%d).\n",
2007
		    ecc->ecc_stat & MCP251XFD_REG_ECCSTAT_SECIF ?
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
		    "Single" : "Double",
		    addr, nr, tx_ring->tail, tx_tail, offset);

	/* reload tx_obj into controller RAM ... */
	tx_obj = &tx_ring->obj[nr];
	err = spi_sync_transfer(priv->spi, tx_obj->xfer, 1);
	if (err)
		return err;

	/* ... and trigger retransmit */
2018
	return mcp251xfd_chip_set_normal_mode(priv);
2019 2020 2021
}

static int
2022
mcp251xfd_handle_eccif(struct mcp251xfd_priv *priv, bool set_normal_mode)
2023
{
2024
	struct mcp251xfd_ecc *ecc = &priv->ecc;
2025 2026 2027 2028 2029 2030 2031
	const char *msg;
	bool in_tx_ram;
	u32 ecc_stat;
	u16 addr;
	u8 nr;
	int err;

2032
	err = regmap_read(priv->map_reg, MCP251XFD_REG_ECCSTAT, &ecc_stat);
2033 2034 2035
	if (err)
		return err;

2036 2037
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_ECCSTAT,
				 MCP251XFD_REG_ECCSTAT_IF_MASK, ~ecc_stat);
2038 2039 2040 2041
	if (err)
		return err;

	/* Check if ECC error occurred in TX-RAM */
2042 2043
	addr = FIELD_GET(MCP251XFD_REG_ECCSTAT_ERRADDR_MASK, ecc_stat);
	err = mcp251xfd_get_tx_nr_by_addr(priv->tx, &nr, addr);
2044 2045 2046 2047 2048 2049 2050
	if (!err)
		in_tx_ram = true;
	else if (err == -ENOENT)
		in_tx_ram = false;
	else
		return err;

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
	/* Errata Reference:
	 * mcp2517fd: DS80000789B, mcp2518fd: DS80000792C 2.
	 *
	 * ECC single error correction does not work in all cases:
	 *
	 * Fix/Work Around:
	 * Enable single error correction and double error detection
	 * interrupts by setting SECIE and DEDIE. Handle SECIF as a
	 * detection interrupt and do not rely on the error
	 * correction. Instead, handle both interrupts as a
	 * notification that the RAM word at ERRADDR was corrupted.
	 */
2063
	if (ecc_stat & MCP251XFD_REG_ECCSTAT_SECIF)
2064
		msg = "Single ECC Error detected at address";
2065
	else if (ecc_stat & MCP251XFD_REG_ECCSTAT_DEDIF)
2066 2067 2068 2069 2070 2071 2072
		msg = "Double ECC Error detected at address";
	else
		return -EINVAL;

	if (!in_tx_ram) {
		ecc->ecc_stat = 0;

2073
		netdev_notice(priv->ndev, "%s 0x%04x.\n", msg, addr);
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
	} else {
		/* Re-occurring error? */
		if (ecc->ecc_stat == ecc_stat) {
			ecc->cnt++;
		} else {
			ecc->ecc_stat = ecc_stat;
			ecc->cnt = 1;
		}

		netdev_info(priv->ndev,
			    "%s 0x%04x (in TX-RAM, tx_obj=%d), occurred %d time%s.\n",
			    msg, addr, nr, ecc->cnt, ecc->cnt > 1 ? "s" : "");

2087 2088
		if (ecc->cnt >= MCP251XFD_ECC_CNT_MAX)
			return mcp251xfd_handle_eccif_recover(priv, nr);
2089 2090 2091
	}

	if (set_normal_mode)
2092
		return mcp251xfd_chip_set_normal_mode_nowait(priv);
2093 2094 2095 2096

	return 0;
}

2097
static int mcp251xfd_handle_spicrcif(struct mcp251xfd_priv *priv)
2098 2099 2100 2101
{
	int err;
	u32 crc;

2102
	err = regmap_read(priv->map_reg, MCP251XFD_REG_CRC, &crc);
2103 2104 2105
	if (err)
		return err;

2106 2107
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_CRC,
				 MCP251XFD_REG_CRC_IF_MASK,
2108 2109 2110 2111
				 ~crc);
	if (err)
		return err;

2112
	if (crc & MCP251XFD_REG_CRC_FERRIF)
2113
		netdev_notice(priv->ndev, "CRC write command format error.\n");
2114
	else if (crc & MCP251XFD_REG_CRC_CRCERRIF)
2115 2116
		netdev_notice(priv->ndev,
			      "CRC write error detected. CRC=0x%04lx.\n",
2117
			      FIELD_GET(MCP251XFD_REG_CRC_MASK, crc));
2118 2119 2120 2121

	return 0;
}

2122
#define mcp251xfd_handle(priv, irq, ...) \
2123
({ \
2124
	struct mcp251xfd_priv *_priv = (priv); \
2125 2126
	int err; \
\
2127
	err = mcp251xfd_handle_##irq(_priv, ## __VA_ARGS__); \
2128 2129
	if (err) \
		netdev_err(_priv->ndev, \
2130
			"IRQ handler mcp251xfd_handle_%s() returned %d.\n", \
2131 2132 2133 2134
			__stringify(irq), err); \
	err; \
})

2135
static irqreturn_t mcp251xfd_irq(int irq, void *dev_id)
2136
{
2137
	struct mcp251xfd_priv *priv = dev_id;
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
	irqreturn_t handled = IRQ_NONE;
	int err;

	if (priv->rx_int)
		do {
			int rx_pending;

			rx_pending = gpiod_get_value_cansleep(priv->rx_int);
			if (!rx_pending)
				break;

2149
			err = mcp251xfd_handle(priv, rxif);
2150 2151 2152 2153 2154 2155 2156 2157
			if (err)
				goto out_fail;

			handled = IRQ_HANDLED;
		} while (1);

	do {
		u32 intf_pending, intf_pending_clearable;
2158
		bool set_normal_mode = false;
2159

2160
		err = regmap_bulk_read(priv->map_reg, MCP251XFD_REG_INT,
2161 2162 2163 2164 2165 2166
				       &priv->regs_status,
				       sizeof(priv->regs_status) /
				       sizeof(u32));
		if (err)
			goto out_fail;

2167
		intf_pending = FIELD_GET(MCP251XFD_REG_INT_IF_MASK,
2168
					 priv->regs_status.intf) &
2169
			FIELD_GET(MCP251XFD_REG_INT_IE_MASK,
2170 2171 2172 2173 2174 2175
				  priv->regs_status.intf);

		if (!(intf_pending))
			return handled;

		/* Some interrupts must be ACKed in the
2176
		 * MCP251XFD_REG_INT register.
2177 2178 2179 2180
		 * - First ACK then handle, to avoid lost-IRQ race
		 *   condition on fast re-occurring interrupts.
		 * - Write "0" to clear active IRQs, "1" to all other,
		 *   to avoid r/m/w race condition on the
2181
		 *   MCP251XFD_REG_INT register.
2182 2183
		 */
		intf_pending_clearable = intf_pending &
2184
			MCP251XFD_REG_INT_IF_CLEARABLE_MASK;
2185 2186
		if (intf_pending_clearable) {
			err = regmap_update_bits(priv->map_reg,
2187 2188
						 MCP251XFD_REG_INT,
						 MCP251XFD_REG_INT_IF_MASK,
2189 2190 2191 2192 2193
						 ~intf_pending_clearable);
			if (err)
				goto out_fail;
		}

2194 2195
		if (intf_pending & MCP251XFD_REG_INT_MODIF) {
			err = mcp251xfd_handle(priv, modif, &set_normal_mode);
2196 2197 2198 2199
			if (err)
				goto out_fail;
		}

2200 2201
		if (intf_pending & MCP251XFD_REG_INT_RXIF) {
			err = mcp251xfd_handle(priv, rxif);
2202 2203 2204 2205
			if (err)
				goto out_fail;
		}

2206 2207
		if (intf_pending & MCP251XFD_REG_INT_TEFIF) {
			err = mcp251xfd_handle(priv, tefif);
2208 2209 2210 2211
			if (err)
				goto out_fail;
		}

2212 2213
		if (intf_pending & MCP251XFD_REG_INT_RXOVIF) {
			err = mcp251xfd_handle(priv, rxovif);
2214 2215 2216 2217
			if (err)
				goto out_fail;
		}

2218 2219
		if (intf_pending & MCP251XFD_REG_INT_TXATIF) {
			err = mcp251xfd_handle(priv, txatif);
2220 2221 2222 2223
			if (err)
				goto out_fail;
		}

2224 2225
		if (intf_pending & MCP251XFD_REG_INT_IVMIF) {
			err = mcp251xfd_handle(priv, ivmif);
2226 2227 2228 2229
			if (err)
				goto out_fail;
		}

2230 2231
		if (intf_pending & MCP251XFD_REG_INT_SERRIF) {
			err = mcp251xfd_handle(priv, serrif);
2232 2233 2234 2235
			if (err)
				goto out_fail;
		}

2236 2237
		if (intf_pending & MCP251XFD_REG_INT_ECCIF) {
			err = mcp251xfd_handle(priv, eccif, set_normal_mode);
2238 2239 2240 2241
			if (err)
				goto out_fail;
		}

2242 2243
		if (intf_pending & MCP251XFD_REG_INT_SPICRCIF) {
			err = mcp251xfd_handle(priv, spicrcif);
2244 2245 2246 2247 2248 2249 2250 2251
			if (err)
				goto out_fail;
		}

		/* On the MCP2527FD and MCP2518FD, we don't get a
		 * CERRIF IRQ on the transition TX ERROR_WARNING -> TX
		 * ERROR_ACTIVE.
		 */
2252
		if (intf_pending & MCP251XFD_REG_INT_CERRIF ||
2253
		    priv->can.state > CAN_STATE_ERROR_ACTIVE) {
2254
			err = mcp251xfd_handle(priv, cerrif);
2255 2256 2257 2258 2259 2260
			if (err)
				goto out_fail;

			/* In Bus Off we completely shut down the
			 * controller. Every subsequent register read
			 * will read bogus data, and if
2261
			 * MCP251XFD_QUIRK_CRC_REG is enabled the CRC
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
			 * check will fail, too. So leave IRQ handler
			 * directly.
			 */
			if (priv->can.state == CAN_STATE_BUS_OFF)
				return IRQ_HANDLED;
		}

		handled = IRQ_HANDLED;
	} while (1);

 out_fail:
	netdev_err(priv->ndev, "IRQ handler returned %d (intf=0x%08x).\n",
		   err, priv->regs_status.intf);
2275
	mcp251xfd_chip_interrupts_disable(priv);
2276 2277 2278 2279 2280

	return handled;
}

static inline struct
2281
mcp251xfd_tx_obj *mcp251xfd_get_tx_obj_next(struct mcp251xfd_tx_ring *tx_ring)
2282 2283 2284
{
	u8 tx_head;

2285
	tx_head = mcp251xfd_get_tx_head(tx_ring);
2286 2287 2288 2289 2290

	return &tx_ring->obj[tx_head];
}

static void
2291 2292
mcp251xfd_tx_obj_from_skb(const struct mcp251xfd_priv *priv,
			  struct mcp251xfd_tx_obj *tx_obj,
2293 2294 2295 2296
			  const struct sk_buff *skb,
			  unsigned int seq)
{
	const struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
2297 2298
	struct mcp251xfd_hw_tx_obj_raw *hw_tx_obj;
	union mcp251xfd_tx_obj_load_buf *load_buf;
2299 2300 2301 2302 2303 2304 2305
	u8 dlc;
	u32 id, flags;
	int offset, len;

	if (cfd->can_id & CAN_EFF_FLAG) {
		u32 sid, eid;

2306 2307
		sid = FIELD_GET(MCP251XFD_REG_FRAME_EFF_SID_MASK, cfd->can_id);
		eid = FIELD_GET(MCP251XFD_REG_FRAME_EFF_EID_MASK, cfd->can_id);
2308

2309 2310
		id = FIELD_PREP(MCP251XFD_OBJ_ID_EID_MASK, eid) |
			FIELD_PREP(MCP251XFD_OBJ_ID_SID_MASK, sid);
2311

2312
		flags = MCP251XFD_OBJ_FLAGS_IDE;
2313
	} else {
2314
		id = FIELD_PREP(MCP251XFD_OBJ_ID_SID_MASK, cfd->can_id);
2315 2316 2317 2318 2319 2320 2321
		flags = 0;
	}

	/* Use the MCP2518FD mask even on the MCP2517FD. It doesn't
	 * harm, only the lower 7 bits will be transferred into the
	 * TEF object.
	 */
2322
	dlc = can_fd_len2dlc(cfd->len);
2323 2324
	flags |= FIELD_PREP(MCP251XFD_OBJ_FLAGS_SEQ_MCP2518FD_MASK, seq) |
		FIELD_PREP(MCP251XFD_OBJ_FLAGS_DLC, dlc);
2325 2326

	if (cfd->can_id & CAN_RTR_FLAG)
2327
		flags |= MCP251XFD_OBJ_FLAGS_RTR;
2328 2329 2330 2331

	/* CANFD */
	if (can_is_canfd_skb(skb)) {
		if (cfd->flags & CANFD_ESI)
2332
			flags |= MCP251XFD_OBJ_FLAGS_ESI;
2333

2334
		flags |= MCP251XFD_OBJ_FLAGS_FDF;
2335 2336

		if (cfd->flags & CANFD_BRS)
2337
			flags |= MCP251XFD_OBJ_FLAGS_BRS;
2338 2339 2340
	}

	load_buf = &tx_obj->buf;
2341
	if (priv->devtype_data.quirks & MCP251XFD_QUIRK_CRC_TX)
2342 2343 2344 2345 2346 2347 2348 2349 2350
		hw_tx_obj = &load_buf->crc.hw_tx_obj;
	else
		hw_tx_obj = &load_buf->nocrc.hw_tx_obj;

	put_unaligned_le32(id, &hw_tx_obj->id);
	put_unaligned_le32(flags, &hw_tx_obj->flags);

	/* Clear data at end of CAN frame */
	offset = round_down(cfd->len, sizeof(u32));
2351
	len = round_up(can_fd_dlc2len(dlc), sizeof(u32)) - offset;
2352
	if (MCP251XFD_SANITIZE_CAN && len)
2353 2354 2355 2356 2357
		memset(hw_tx_obj->data + offset, 0x0, len);
	memcpy(hw_tx_obj->data, cfd->data, cfd->len);

	/* Number of bytes to be written into the RAM of the controller */
	len = sizeof(hw_tx_obj->id) + sizeof(hw_tx_obj->flags);
2358
	if (MCP251XFD_SANITIZE_CAN)
2359
		len += round_up(can_fd_dlc2len(dlc), sizeof(u32));
2360 2361 2362
	else
		len += round_up(cfd->len, sizeof(u32));

2363
	if (priv->devtype_data.quirks & MCP251XFD_QUIRK_CRC_TX) {
2364 2365
		u16 crc;

2366
		mcp251xfd_spi_cmd_crc_set_len_in_ram(&load_buf->crc.cmd,
2367 2368 2369
						     len);
		/* CRC */
		len += sizeof(load_buf->crc.cmd);
2370
		crc = mcp251xfd_crc16_compute(&load_buf->crc, len);
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
		put_unaligned_be16(crc, (void *)load_buf + len);

		/* Total length */
		len += sizeof(load_buf->crc.crc);
	} else {
		len += sizeof(load_buf->nocrc.cmd);
	}

	tx_obj->xfer[0].len = len;
}

2382 2383
static int mcp251xfd_tx_obj_write(const struct mcp251xfd_priv *priv,
				  struct mcp251xfd_tx_obj *tx_obj)
2384 2385 2386 2387
{
	return spi_async(priv->spi, &tx_obj->msg);
}

2388 2389
static bool mcp251xfd_tx_busy(const struct mcp251xfd_priv *priv,
			      struct mcp251xfd_tx_ring *tx_ring)
2390
{
2391
	if (mcp251xfd_get_tx_free(tx_ring) > 0)
2392 2393 2394 2395 2396 2397 2398
		return false;

	netif_stop_queue(priv->ndev);

	/* Memory barrier before checking tx_free (head and tail) */
	smp_mb();

2399
	if (mcp251xfd_get_tx_free(tx_ring) == 0) {
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
		netdev_dbg(priv->ndev,
			   "Stopping tx-queue (tx_head=0x%08x, tx_tail=0x%08x, len=%d).\n",
			   tx_ring->head, tx_ring->tail,
			   tx_ring->head - tx_ring->tail);

		return true;
	}

	netif_start_queue(priv->ndev);

	return false;
}

2413
static netdev_tx_t mcp251xfd_start_xmit(struct sk_buff *skb,
2414 2415
					struct net_device *ndev)
{
2416 2417 2418
	struct mcp251xfd_priv *priv = netdev_priv(ndev);
	struct mcp251xfd_tx_ring *tx_ring = priv->tx;
	struct mcp251xfd_tx_obj *tx_obj;
2419 2420 2421 2422 2423 2424
	u8 tx_head;
	int err;

	if (can_dropped_invalid_skb(ndev, skb))
		return NETDEV_TX_OK;

2425
	if (mcp251xfd_tx_busy(priv, tx_ring))
2426 2427
		return NETDEV_TX_BUSY;

2428 2429
	tx_obj = mcp251xfd_get_tx_obj_next(tx_ring);
	mcp251xfd_tx_obj_from_skb(priv, tx_obj, skb, tx_ring->head);
2430 2431

	/* Stop queue if we occupy the complete TX FIFO */
2432
	tx_head = mcp251xfd_get_tx_head(tx_ring);
2433 2434 2435 2436 2437 2438
	tx_ring->head++;
	if (tx_ring->head - tx_ring->tail >= tx_ring->obj_num)
		netif_stop_queue(ndev);

	can_put_echo_skb(skb, ndev, tx_head);

2439
	err = mcp251xfd_tx_obj_write(priv, tx_obj);
2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
	if (err)
		goto out_err;

	return NETDEV_TX_OK;

 out_err:
	netdev_err(priv->ndev, "ERROR in %s: %d\n", __func__, err);

	return NETDEV_TX_OK;
}

2451
static int mcp251xfd_open(struct net_device *ndev)
2452
{
2453
	struct mcp251xfd_priv *priv = netdev_priv(ndev);
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
	const struct spi_device *spi = priv->spi;
	int err;

	err = pm_runtime_get_sync(ndev->dev.parent);
	if (err < 0) {
		pm_runtime_put_noidle(ndev->dev.parent);
		return err;
	}

	err = open_candev(ndev);
	if (err)
		goto out_pm_runtime_put;

2467
	err = mcp251xfd_ring_alloc(priv);
2468 2469 2470
	if (err)
		goto out_close_candev;

2471
	err = mcp251xfd_transceiver_enable(priv);
2472
	if (err)
2473
		goto out_mcp251xfd_ring_free;
2474

2475
	err = mcp251xfd_chip_start(priv);
2476 2477 2478 2479 2480
	if (err)
		goto out_transceiver_disable;

	can_rx_offload_enable(&priv->offload);

2481
	err = request_threaded_irq(spi->irq, NULL, mcp251xfd_irq,
2482 2483 2484 2485 2486
				   IRQF_ONESHOT, dev_name(&spi->dev),
				   priv);
	if (err)
		goto out_can_rx_offload_disable;

2487
	err = mcp251xfd_chip_interrupts_enable(priv);
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
	if (err)
		goto out_free_irq;

	netif_start_queue(ndev);

	return 0;

 out_free_irq:
	free_irq(spi->irq, priv);
 out_can_rx_offload_disable:
	can_rx_offload_disable(&priv->offload);
 out_transceiver_disable:
2500 2501 2502
	mcp251xfd_transceiver_disable(priv);
 out_mcp251xfd_ring_free:
	mcp251xfd_ring_free(priv);
2503 2504 2505
 out_close_candev:
	close_candev(ndev);
 out_pm_runtime_put:
2506
	mcp251xfd_chip_stop(priv, CAN_STATE_STOPPED);
2507 2508 2509 2510 2511
	pm_runtime_put(ndev->dev.parent);

	return err;
}

2512
static int mcp251xfd_stop(struct net_device *ndev)
2513
{
2514
	struct mcp251xfd_priv *priv = netdev_priv(ndev);
2515 2516

	netif_stop_queue(ndev);
2517
	mcp251xfd_chip_interrupts_disable(priv);
2518 2519
	free_irq(ndev->irq, priv);
	can_rx_offload_disable(&priv->offload);
2520 2521 2522
	mcp251xfd_chip_stop(priv, CAN_STATE_STOPPED);
	mcp251xfd_transceiver_disable(priv);
	mcp251xfd_ring_free(priv);
2523 2524 2525 2526 2527 2528 2529
	close_candev(ndev);

	pm_runtime_put(ndev->dev.parent);

	return 0;
}

2530 2531 2532 2533
static const struct net_device_ops mcp251xfd_netdev_ops = {
	.ndo_open = mcp251xfd_open,
	.ndo_stop = mcp251xfd_stop,
	.ndo_start_xmit	= mcp251xfd_start_xmit,
2534 2535 2536 2537
	.ndo_change_mtu = can_change_mtu,
};

static void
2538
mcp251xfd_register_quirks(struct mcp251xfd_priv *priv)
2539 2540 2541 2542 2543
{
	const struct spi_device *spi = priv->spi;
	const struct spi_controller *ctlr = spi->controller;

	if (ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX)
2544
		priv->devtype_data.quirks |= MCP251XFD_QUIRK_HALF_DUPLEX;
2545 2546
}

2547
static int mcp251xfd_register_chip_detect(struct mcp251xfd_priv *priv)
2548 2549
{
	const struct net_device *ndev = priv->ndev;
2550
	const struct mcp251xfd_devtype_data *devtype_data;
2551 2552 2553 2554 2555 2556
	u32 osc;
	int err;

	/* The OSC_LPMEN is only supported on MCP2518FD, so use it to
	 * autodetect the model.
	 */
2557 2558 2559
	err = regmap_update_bits(priv->map_reg, MCP251XFD_REG_OSC,
				 MCP251XFD_REG_OSC_LPMEN,
				 MCP251XFD_REG_OSC_LPMEN);
2560 2561 2562
	if (err)
		return err;

2563
	err = regmap_read(priv->map_reg, MCP251XFD_REG_OSC, &osc);
2564 2565 2566
	if (err)
		return err;

2567 2568
	if (osc & MCP251XFD_REG_OSC_LPMEN)
		devtype_data = &mcp251xfd_devtype_data_mcp2518fd;
2569
	else
2570
		devtype_data = &mcp251xfd_devtype_data_mcp2517fd;
2571

2572
	if (!mcp251xfd_is_251X(priv) &&
2573 2574 2575
	    priv->devtype_data.model != devtype_data->model) {
		netdev_info(ndev,
			    "Detected %s, but firmware specifies a %s. Fixing up.",
2576 2577
			    __mcp251xfd_get_model_str(devtype_data->model),
			    mcp251xfd_get_model_str(priv));
2578 2579 2580 2581
	}
	priv->devtype_data = *devtype_data;

	/* We need to preserve the Half Duplex Quirk. */
2582
	mcp251xfd_register_quirks(priv);
2583 2584

	/* Re-init regmap with quirks of detected model. */
2585
	return mcp251xfd_regmap_init(priv);
2586 2587
}

2588
static int mcp251xfd_register_check_rx_int(struct mcp251xfd_priv *priv)
2589 2590 2591 2592 2593 2594
{
	int err, rx_pending;

	if (!priv->rx_int)
		return 0;

2595
	err = mcp251xfd_chip_rx_int_enable(priv);
2596 2597 2598 2599 2600 2601 2602 2603
	if (err)
		return err;

	/* Check if RX_INT is properly working. The RX_INT should not
	 * be active after a softreset.
	 */
	rx_pending = gpiod_get_value_cansleep(priv->rx_int);

2604
	err = mcp251xfd_chip_rx_int_disable(priv);
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
	if (err)
		return err;

	if (!rx_pending)
		return 0;

	netdev_info(priv->ndev,
		    "RX_INT active after softreset, disabling RX_INT support.");
	devm_gpiod_put(&priv->spi->dev, priv->rx_int);
	priv->rx_int = NULL;

	return 0;
}

static int
2620
mcp251xfd_register_get_dev_id(const struct mcp251xfd_priv *priv,
2621 2622
			      u32 *dev_id, u32 *effective_speed_hz)
{
2623 2624
	struct mcp251xfd_map_buf_nocrc *buf_rx;
	struct mcp251xfd_map_buf_nocrc *buf_tx;
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
	struct spi_transfer xfer[2] = { };
	int err;

	buf_rx = kzalloc(sizeof(*buf_rx), GFP_KERNEL);
	if (!buf_rx)
		return -ENOMEM;

	buf_tx = kzalloc(sizeof(*buf_tx), GFP_KERNEL);
	if (!buf_tx) {
		err = -ENOMEM;
		goto out_kfree_buf_rx;
	}

	xfer[0].tx_buf = buf_tx;
	xfer[0].len = sizeof(buf_tx->cmd);
	xfer[1].rx_buf = buf_rx->data;
	xfer[1].len = sizeof(dev_id);

2643
	mcp251xfd_spi_cmd_read_nocrc(&buf_tx->cmd, MCP251XFD_REG_DEVID);
2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
	err = spi_sync_transfer(priv->spi, xfer, ARRAY_SIZE(xfer));
	if (err)
		goto out_kfree_buf_tx;

	*dev_id = be32_to_cpup((__be32 *)buf_rx->data);
	*effective_speed_hz = xfer->effective_speed_hz;

 out_kfree_buf_tx:
	kfree(buf_tx);
 out_kfree_buf_rx:
	kfree(buf_rx);

	return 0;
}

2659 2660
#define MCP251XFD_QUIRK_ACTIVE(quirk) \
	(priv->devtype_data.quirks & MCP251XFD_QUIRK_##quirk ? '+' : '-')
2661 2662

static int
2663
mcp251xfd_register_done(const struct mcp251xfd_priv *priv)
2664 2665 2666 2667
{
	u32 dev_id, effective_speed_hz;
	int err;

2668
	err = mcp251xfd_register_get_dev_id(priv, &dev_id,
2669 2670 2671 2672 2673 2674
					    &effective_speed_hz);
	if (err)
		return err;

	netdev_info(priv->ndev,
		    "%s rev%lu.%lu (%cRX_INT %cMAB_NO_WARN %cCRC_REG %cCRC_RX %cCRC_TX %cECC %cHD c:%u.%02uMHz m:%u.%02uMHz r:%u.%02uMHz e:%u.%02uMHz) successfully initialized.\n",
2675 2676 2677
		    mcp251xfd_get_model_str(priv),
		    FIELD_GET(MCP251XFD_REG_DEVID_ID_MASK, dev_id),
		    FIELD_GET(MCP251XFD_REG_DEVID_REV_MASK, dev_id),
2678
		    priv->rx_int ? '+' : '-',
2679 2680 2681 2682 2683 2684
		    MCP251XFD_QUIRK_ACTIVE(MAB_NO_WARN),
		    MCP251XFD_QUIRK_ACTIVE(CRC_REG),
		    MCP251XFD_QUIRK_ACTIVE(CRC_RX),
		    MCP251XFD_QUIRK_ACTIVE(CRC_TX),
		    MCP251XFD_QUIRK_ACTIVE(ECC),
		    MCP251XFD_QUIRK_ACTIVE(HALF_DUPLEX),
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
		    priv->can.clock.freq / 1000000,
		    priv->can.clock.freq % 1000000 / 1000 / 10,
		    priv->spi_max_speed_hz_orig / 1000000,
		    priv->spi_max_speed_hz_orig % 1000000 / 1000 / 10,
		    priv->spi->max_speed_hz / 1000000,
		    priv->spi->max_speed_hz % 1000000 / 1000 / 10,
		    effective_speed_hz / 1000000,
		    effective_speed_hz % 1000000 / 1000 / 10);

	return 0;
}

2697
static int mcp251xfd_register(struct mcp251xfd_priv *priv)
2698 2699 2700 2701
{
	struct net_device *ndev = priv->ndev;
	int err;

2702
	err = mcp251xfd_clks_and_vdd_enable(priv);
2703 2704 2705 2706 2707 2708 2709 2710 2711
	if (err)
		return err;

	pm_runtime_get_noresume(ndev->dev.parent);
	err = pm_runtime_set_active(ndev->dev.parent);
	if (err)
		goto out_runtime_put_noidle;
	pm_runtime_enable(ndev->dev.parent);

2712
	mcp251xfd_register_quirks(priv);
2713

2714
	err = mcp251xfd_chip_softreset(priv);
2715 2716 2717 2718 2719
	if (err == -ENODEV)
		goto out_runtime_disable;
	if (err)
		goto out_chip_set_mode_sleep;

2720
	err = mcp251xfd_register_chip_detect(priv);
2721 2722 2723
	if (err)
		goto out_chip_set_mode_sleep;

2724
	err = mcp251xfd_register_check_rx_int(priv);
2725 2726 2727 2728 2729 2730 2731
	if (err)
		goto out_chip_set_mode_sleep;

	err = register_candev(ndev);
	if (err)
		goto out_chip_set_mode_sleep;

2732
	err = mcp251xfd_register_done(priv);
2733 2734 2735 2736 2737 2738 2739
	if (err)
		goto out_unregister_candev;

	/* Put controller into sleep mode and let pm_runtime_put()
	 * disable the clocks and vdd. If CONFIG_PM is not enabled,
	 * the clocks and vdd will stay powered.
	 */
2740
	err = mcp251xfd_chip_set_mode(priv, MCP251XFD_REG_CON_MODE_SLEEP);
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
	if (err)
		goto out_unregister_candev;

	pm_runtime_put(ndev->dev.parent);

	return 0;

 out_unregister_candev:
	unregister_candev(ndev);
 out_chip_set_mode_sleep:
2751
	mcp251xfd_chip_set_mode(priv, MCP251XFD_REG_CON_MODE_SLEEP);
2752 2753 2754 2755
 out_runtime_disable:
	pm_runtime_disable(ndev->dev.parent);
 out_runtime_put_noidle:
	pm_runtime_put_noidle(ndev->dev.parent);
2756
	mcp251xfd_clks_and_vdd_disable(priv);
2757 2758 2759 2760

	return err;
}

2761
static inline void mcp251xfd_unregister(struct mcp251xfd_priv *priv)
2762 2763 2764 2765 2766 2767 2768
{
	struct net_device *ndev	= priv->ndev;

	unregister_candev(ndev);

	pm_runtime_get_sync(ndev->dev.parent);
	pm_runtime_put_noidle(ndev->dev.parent);
2769
	mcp251xfd_clks_and_vdd_disable(priv);
2770 2771 2772
	pm_runtime_disable(ndev->dev.parent);
}

2773
static const struct of_device_id mcp251xfd_of_match[] = {
2774 2775
	{
		.compatible = "microchip,mcp2517fd",
2776
		.data = &mcp251xfd_devtype_data_mcp2517fd,
2777 2778
	}, {
		.compatible = "microchip,mcp2518fd",
2779
		.data = &mcp251xfd_devtype_data_mcp2518fd,
2780
	}, {
2781
		.compatible = "microchip,mcp251xfd",
2782
		.data = &mcp251xfd_devtype_data_mcp251xfd,
2783 2784 2785 2786
	}, {
		/* sentinel */
	},
};
2787
MODULE_DEVICE_TABLE(of, mcp251xfd_of_match);
2788

2789
static const struct spi_device_id mcp251xfd_id_table[] = {
2790 2791
	{
		.name = "mcp2517fd",
2792
		.driver_data = (kernel_ulong_t)&mcp251xfd_devtype_data_mcp2517fd,
2793 2794
	}, {
		.name = "mcp2518fd",
2795
		.driver_data = (kernel_ulong_t)&mcp251xfd_devtype_data_mcp2518fd,
2796
	}, {
2797
		.name = "mcp251xfd",
2798
		.driver_data = (kernel_ulong_t)&mcp251xfd_devtype_data_mcp251xfd,
2799 2800 2801 2802
	}, {
		/* sentinel */
	},
};
2803
MODULE_DEVICE_TABLE(spi, mcp251xfd_id_table);
2804

2805
static int mcp251xfd_probe(struct spi_device *spi)
2806 2807 2808
{
	const void *match;
	struct net_device *ndev;
2809
	struct mcp251xfd_priv *priv;
2810 2811 2812 2813 2814 2815
	struct gpio_desc *rx_int;
	struct regulator *reg_vdd, *reg_xceiver;
	struct clk *clk;
	u32 freq;
	int err;

2816 2817 2818 2819
	if (!spi->irq)
		return dev_err_probe(&spi->dev, -ENXIO,
				     "No IRQ specified (maybe node \"interrupts-extended\" in DT missing)!\n");

2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
	rx_int = devm_gpiod_get_optional(&spi->dev, "microchip,rx-int",
					 GPIOD_IN);
	if (PTR_ERR(rx_int) == -EPROBE_DEFER)
		return -EPROBE_DEFER;
	else if (IS_ERR(rx_int))
		return PTR_ERR(rx_int);

	reg_vdd = devm_regulator_get_optional(&spi->dev, "vdd");
	if (PTR_ERR(reg_vdd) == -EPROBE_DEFER)
		return -EPROBE_DEFER;
	else if (PTR_ERR(reg_vdd) == -ENODEV)
		reg_vdd = NULL;
	else if (IS_ERR(reg_vdd))
		return PTR_ERR(reg_vdd);

	reg_xceiver = devm_regulator_get_optional(&spi->dev, "xceiver");
	if (PTR_ERR(reg_xceiver) == -EPROBE_DEFER)
		return -EPROBE_DEFER;
	else if (PTR_ERR(reg_xceiver) == -ENODEV)
		reg_xceiver = NULL;
	else if (IS_ERR(reg_xceiver))
		return PTR_ERR(reg_xceiver);

	clk = devm_clk_get(&spi->dev, NULL);
	if (IS_ERR(clk)) {
		dev_err(&spi->dev, "No Oscillator (clock) defined.\n");
		return PTR_ERR(clk);
	}
	freq = clk_get_rate(clk);

	/* Sanity check */
2851 2852
	if (freq < MCP251XFD_SYSCLOCK_HZ_MIN ||
	    freq > MCP251XFD_SYSCLOCK_HZ_MAX) {
2853 2854 2855 2856 2857 2858
		dev_err(&spi->dev,
			"Oscillator frequency (%u Hz) is too low or high.\n",
			freq);
		return -ERANGE;
	}

2859
	if (freq <= MCP251XFD_SYSCLOCK_HZ_MAX / MCP251XFD_OSC_PLL_MULTIPLIER) {
2860 2861 2862 2863 2864 2865
		dev_err(&spi->dev,
			"Oscillator frequency (%u Hz) is too low and PLL is not supported.\n",
			freq);
		return -ERANGE;
	}

2866 2867
	ndev = alloc_candev(sizeof(struct mcp251xfd_priv),
			    MCP251XFD_TX_OBJ_NUM_MAX);
2868 2869 2870 2871 2872
	if (!ndev)
		return -ENOMEM;

	SET_NETDEV_DEV(ndev, &spi->dev);

2873
	ndev->netdev_ops = &mcp251xfd_netdev_ops;
2874 2875 2876 2877 2878 2879
	ndev->irq = spi->irq;
	ndev->flags |= IFF_ECHO;

	priv = netdev_priv(ndev);
	spi_set_drvdata(spi, priv);
	priv->can.clock.freq = freq;
2880 2881 2882 2883
	priv->can.do_set_mode = mcp251xfd_set_mode;
	priv->can.do_get_berr_counter = mcp251xfd_get_berr_counter;
	priv->can.bittiming_const = &mcp251xfd_bittiming_const;
	priv->can.data_bittiming_const = &mcp251xfd_data_bittiming_const;
2884 2885 2886
	priv->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY |
		CAN_CTRLMODE_BERR_REPORTING | CAN_CTRLMODE_FD |
		CAN_CTRLMODE_FD_NON_ISO;
2887 2888 2889 2890 2891 2892 2893 2894 2895
	priv->ndev = ndev;
	priv->spi = spi;
	priv->rx_int = rx_int;
	priv->clk = clk;
	priv->reg_vdd = reg_vdd;
	priv->reg_xceiver = reg_xceiver;

	match = device_get_match_data(&spi->dev);
	if (match)
2896
		priv->devtype_data = *(struct mcp251xfd_devtype_data *)match;
2897
	else
2898
		priv->devtype_data = *(struct mcp251xfd_devtype_data *)
2899 2900
			spi_get_device_id(spi)->driver_data;

2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
	/* Errata Reference:
	 * mcp2517fd: DS80000789B, mcp2518fd: DS80000792C 4.
	 *
	 * The SPI can write corrupted data to the RAM at fast SPI
	 * speeds:
	 *
	 * Simultaneous activity on the CAN bus while writing data to
	 * RAM via the SPI interface, with high SCK frequency, can
	 * lead to corrupted data being written to RAM.
	 *
	 * Fix/Work Around:
	 * Ensure that FSCK is less than or equal to 0.85 *
	 * (FSYSCLK/2).
2914
	 *
2915
	 * Known good and bad combinations are:
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
	 *
	 * MCP	ext-clk	SoC			SPI			SPI-clk		max-clk	parent-clk	Status	config
	 *
	 * 2518	20 MHz	allwinner,sun8i-h3	allwinner,sun8i-h3-spi	 8333333 Hz	 83.33%	600000000 Hz	good	assigned-clocks = <&ccu CLK_SPIx>
	 * 2518	20 MHz	allwinner,sun8i-h3	allwinner,sun8i-h3-spi	 9375000 Hz	 93.75%	600000000 Hz	bad	assigned-clocks = <&ccu CLK_SPIx>
	 * 2518	40 MHz	allwinner,sun8i-h3	allwinner,sun8i-h3-spi	16666667 Hz	 83.33%	600000000 Hz	good	assigned-clocks = <&ccu CLK_SPIx>
	 * 2518	40 MHz	allwinner,sun8i-h3	allwinner,sun8i-h3-spi	18750000 Hz	 93.75%	600000000 Hz	bad	assigned-clocks = <&ccu CLK_SPIx>
	 * 2517	20 MHz	fsl,imx8mm		fsl,imx51-ecspi		 8333333 Hz	 83.33%	 16666667 Hz	good	assigned-clocks = <&clk IMX8MM_CLK_ECSPIx_ROOT>
	 * 2517	20 MHz	fsl,imx8mm		fsl,imx51-ecspi		 9523809 Hz	 95.34%	 28571429 Hz	bad	assigned-clocks = <&clk IMX8MM_CLK_ECSPIx_ROOT>
	 * 2517 40 MHz	atmel,sama5d27		atmel,at91rm9200-spi	16400000 Hz	 82.00%	 82000000 Hz	good	default
	 * 2518 40 MHz	atmel,sama5d27		atmel,at91rm9200-spi	16400000 Hz	 82.00%	 82000000 Hz	good	default
	 *
	 */
	priv->spi_max_speed_hz_orig = spi->max_speed_hz;
	spi->max_speed_hz = min(spi->max_speed_hz, freq / 2 / 1000 * 850);
	spi->bits_per_word = 8;
	spi->rt = true;
	err = spi_setup(spi);
	if (err)
		goto out_free_candev;

2937
	err = mcp251xfd_regmap_init(priv);
2938 2939 2940 2941
	if (err)
		goto out_free_candev;

	err = can_rx_offload_add_manual(ndev, &priv->offload,
2942
					MCP251XFD_NAPI_WEIGHT);
2943 2944 2945
	if (err)
		goto out_free_candev;

2946
	err = mcp251xfd_register(priv);
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
	if (err)
		goto out_free_candev;

	return 0;

 out_free_candev:
	spi->max_speed_hz = priv->spi_max_speed_hz_orig;

	free_candev(ndev);

	return err;
}

2960
static int mcp251xfd_remove(struct spi_device *spi)
2961
{
2962
	struct mcp251xfd_priv *priv = spi_get_drvdata(spi);
2963 2964 2965
	struct net_device *ndev = priv->ndev;

	can_rx_offload_del(&priv->offload);
2966
	mcp251xfd_unregister(priv);
2967 2968 2969 2970 2971 2972
	spi->max_speed_hz = priv->spi_max_speed_hz_orig;
	free_candev(ndev);

	return 0;
}

2973
static int __maybe_unused mcp251xfd_runtime_suspend(struct device *device)
2974
{
2975
	const struct mcp251xfd_priv *priv = dev_get_drvdata(device);
2976

2977
	return mcp251xfd_clks_and_vdd_disable(priv);
2978 2979
}

2980
static int __maybe_unused mcp251xfd_runtime_resume(struct device *device)
2981
{
2982
	const struct mcp251xfd_priv *priv = dev_get_drvdata(device);
2983

2984
	return mcp251xfd_clks_and_vdd_enable(priv);
2985 2986
}

2987 2988 2989
static const struct dev_pm_ops mcp251xfd_pm_ops = {
	SET_RUNTIME_PM_OPS(mcp251xfd_runtime_suspend,
			   mcp251xfd_runtime_resume, NULL)
2990 2991
};

2992
static struct spi_driver mcp251xfd_driver = {
2993 2994
	.driver = {
		.name = DEVICE_NAME,
2995 2996
		.pm = &mcp251xfd_pm_ops,
		.of_match_table = mcp251xfd_of_match,
2997
	},
2998 2999 3000
	.probe = mcp251xfd_probe,
	.remove = mcp251xfd_remove,
	.id_table = mcp251xfd_id_table,
3001
};
3002
module_spi_driver(mcp251xfd_driver);
3003 3004

MODULE_AUTHOR("Marc Kleine-Budde <mkl@pengutronix.de>");
3005
MODULE_DESCRIPTION("Microchip MCP251xFD Family CAN controller driver");
3006
MODULE_LICENSE("GPL v2");