xref: /linux/drivers/net/can/dev/dev.c (revision c31783c2b5ae2399388b349f48fa89818b66f6d8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2005 Marc Kleine-Budde, Pengutronix
3  * Copyright (C) 2006 Andrey Volkov, Varma Electronics
4  * Copyright (C) 2008-2009 Wolfgang Grandegger <wg@grandegger.com>
5  */
6 
7 #include <linux/can.h>
8 #include <linux/can/can-ml.h>
9 #include <linux/can/dev.h>
10 #include <linux/can/skb.h>
11 #include <linux/gpio/consumer.h>
12 #include <linux/if_arp.h>
13 #include <linux/kernel.h>
14 #include <linux/netdevice.h>
15 #include <linux/of.h>
16 #include <linux/slab.h>
17 #include <linux/workqueue.h>
18 
19 static void can_update_state_error_stats(struct net_device *dev,
20 					 enum can_state new_state)
21 {
22 	struct can_priv *priv = netdev_priv(dev);
23 
24 	if (new_state <= priv->state)
25 		return;
26 
27 	switch (new_state) {
28 	case CAN_STATE_ERROR_WARNING:
29 		priv->can_stats.error_warning++;
30 		break;
31 	case CAN_STATE_ERROR_PASSIVE:
32 		priv->can_stats.error_passive++;
33 		break;
34 	case CAN_STATE_BUS_OFF:
35 		priv->can_stats.bus_off++;
36 		break;
37 	default:
38 		break;
39 	}
40 }
41 
42 static int can_tx_state_to_frame(struct net_device *dev, enum can_state state)
43 {
44 	switch (state) {
45 	case CAN_STATE_ERROR_ACTIVE:
46 		return CAN_ERR_CRTL_ACTIVE;
47 	case CAN_STATE_ERROR_WARNING:
48 		return CAN_ERR_CRTL_TX_WARNING;
49 	case CAN_STATE_ERROR_PASSIVE:
50 		return CAN_ERR_CRTL_TX_PASSIVE;
51 	default:
52 		return 0;
53 	}
54 }
55 
56 static int can_rx_state_to_frame(struct net_device *dev, enum can_state state)
57 {
58 	switch (state) {
59 	case CAN_STATE_ERROR_ACTIVE:
60 		return CAN_ERR_CRTL_ACTIVE;
61 	case CAN_STATE_ERROR_WARNING:
62 		return CAN_ERR_CRTL_RX_WARNING;
63 	case CAN_STATE_ERROR_PASSIVE:
64 		return CAN_ERR_CRTL_RX_PASSIVE;
65 	default:
66 		return 0;
67 	}
68 }
69 
70 const char *can_get_state_str(const enum can_state state)
71 {
72 	switch (state) {
73 	case CAN_STATE_ERROR_ACTIVE:
74 		return "Error Active";
75 	case CAN_STATE_ERROR_WARNING:
76 		return "Error Warning";
77 	case CAN_STATE_ERROR_PASSIVE:
78 		return "Error Passive";
79 	case CAN_STATE_BUS_OFF:
80 		return "Bus Off";
81 	case CAN_STATE_STOPPED:
82 		return "Stopped";
83 	case CAN_STATE_SLEEPING:
84 		return "Sleeping";
85 	default:
86 		return "<unknown>";
87 	}
88 }
89 EXPORT_SYMBOL_GPL(can_get_state_str);
90 
91 const char *can_get_ctrlmode_str(u32 ctrlmode)
92 {
93 	switch (ctrlmode & ~(ctrlmode - 1)) {
94 	case 0:
95 		return "none";
96 	case CAN_CTRLMODE_LOOPBACK:
97 		return "loopback";
98 	case CAN_CTRLMODE_LISTENONLY:
99 		return "listen-only";
100 	case CAN_CTRLMODE_3_SAMPLES:
101 		return "triple-sampling";
102 	case CAN_CTRLMODE_ONE_SHOT:
103 		return "one-shot";
104 	case CAN_CTRLMODE_BERR_REPORTING:
105 		return "berr-reporting";
106 	case CAN_CTRLMODE_FD:
107 		return "fd";
108 	case CAN_CTRLMODE_PRESUME_ACK:
109 		return "presume-ack";
110 	case CAN_CTRLMODE_FD_NON_ISO:
111 		return "fd-non-iso";
112 	case CAN_CTRLMODE_CC_LEN8_DLC:
113 		return "cc-len8-dlc";
114 	case CAN_CTRLMODE_TDC_AUTO:
115 		return "fd-tdc-auto";
116 	case CAN_CTRLMODE_TDC_MANUAL:
117 		return "fd-tdc-manual";
118 	default:
119 		return "<unknown>";
120 	}
121 }
122 EXPORT_SYMBOL_GPL(can_get_ctrlmode_str);
123 
124 static enum can_state can_state_err_to_state(u16 err)
125 {
126 	if (err < CAN_ERROR_WARNING_THRESHOLD)
127 		return CAN_STATE_ERROR_ACTIVE;
128 	if (err < CAN_ERROR_PASSIVE_THRESHOLD)
129 		return CAN_STATE_ERROR_WARNING;
130 	if (err < CAN_BUS_OFF_THRESHOLD)
131 		return CAN_STATE_ERROR_PASSIVE;
132 
133 	return CAN_STATE_BUS_OFF;
134 }
135 
136 void can_state_get_by_berr_counter(const struct net_device *dev,
137 				   const struct can_berr_counter *bec,
138 				   enum can_state *tx_state,
139 				   enum can_state *rx_state)
140 {
141 	*tx_state = can_state_err_to_state(bec->txerr);
142 	*rx_state = can_state_err_to_state(bec->rxerr);
143 }
144 EXPORT_SYMBOL_GPL(can_state_get_by_berr_counter);
145 
146 void can_change_state(struct net_device *dev, struct can_frame *cf,
147 		      enum can_state tx_state, enum can_state rx_state)
148 {
149 	struct can_priv *priv = netdev_priv(dev);
150 	enum can_state new_state = max(tx_state, rx_state);
151 
152 	if (unlikely(new_state == priv->state)) {
153 		netdev_warn(dev, "%s: oops, state did not change", __func__);
154 		return;
155 	}
156 
157 	netdev_dbg(dev, "Controller changed from %s State (%d) into %s State (%d).\n",
158 		   can_get_state_str(priv->state), priv->state,
159 		   can_get_state_str(new_state), new_state);
160 
161 	can_update_state_error_stats(dev, new_state);
162 	priv->state = new_state;
163 
164 	if (!cf)
165 		return;
166 
167 	if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
168 		cf->can_id |= CAN_ERR_BUSOFF;
169 		return;
170 	}
171 
172 	cf->can_id |= CAN_ERR_CRTL;
173 	cf->data[1] |= tx_state >= rx_state ?
174 		       can_tx_state_to_frame(dev, tx_state) : 0;
175 	cf->data[1] |= tx_state <= rx_state ?
176 		       can_rx_state_to_frame(dev, rx_state) : 0;
177 }
178 EXPORT_SYMBOL_GPL(can_change_state);
179 
180 /* CAN device restart for bus-off recovery */
181 static int can_restart(struct net_device *dev)
182 {
183 	struct can_priv *priv = netdev_priv(dev);
184 	struct sk_buff *skb;
185 	struct can_frame *cf;
186 	int err;
187 
188 	if (!priv->do_set_mode)
189 		return -EOPNOTSUPP;
190 
191 	if (netif_carrier_ok(dev))
192 		netdev_err(dev, "Attempt to restart for bus-off recovery, but carrier is OK?\n");
193 
194 	/* No synchronization needed because the device is bus-off and
195 	 * no messages can come in or go out.
196 	 */
197 	can_flush_echo_skb(dev);
198 
199 	/* send restart message upstream */
200 	skb = alloc_can_err_skb(dev, &cf);
201 	if (skb) {
202 		cf->can_id |= CAN_ERR_RESTARTED;
203 		netif_rx(skb);
204 	}
205 
206 	/* Now restart the device */
207 	netif_carrier_on(dev);
208 	err = priv->do_set_mode(dev, CAN_MODE_START);
209 	if (err) {
210 		netdev_err(dev, "Restart failed, error %pe\n", ERR_PTR(err));
211 		netif_carrier_off(dev);
212 
213 		return err;
214 	} else {
215 		netdev_dbg(dev, "Restarted\n");
216 		priv->can_stats.restarts++;
217 	}
218 
219 	return 0;
220 }
221 
222 static void can_restart_work(struct work_struct *work)
223 {
224 	struct delayed_work *dwork = to_delayed_work(work);
225 	struct can_priv *priv = container_of(dwork, struct can_priv,
226 					     restart_work);
227 
228 	can_restart(priv->dev);
229 }
230 
231 int can_restart_now(struct net_device *dev)
232 {
233 	struct can_priv *priv = netdev_priv(dev);
234 
235 	/* A manual restart is only permitted if automatic restart is
236 	 * disabled and the device is in the bus-off state
237 	 */
238 	if (priv->restart_ms)
239 		return -EINVAL;
240 	if (priv->state != CAN_STATE_BUS_OFF)
241 		return -EBUSY;
242 
243 	cancel_delayed_work_sync(&priv->restart_work);
244 
245 	return can_restart(dev);
246 }
247 
248 /* CAN bus-off
249  *
250  * This functions should be called when the device goes bus-off to
251  * tell the netif layer that no more packets can be sent or received.
252  * If enabled, a timer is started to trigger bus-off recovery.
253  */
254 void can_bus_off(struct net_device *dev)
255 {
256 	struct can_priv *priv = netdev_priv(dev);
257 
258 	if (priv->restart_ms)
259 		netdev_info(dev, "bus-off, scheduling restart in %d ms\n",
260 			    priv->restart_ms);
261 	else
262 		netdev_info(dev, "bus-off\n");
263 
264 	netif_carrier_off(dev);
265 
266 	if (priv->restart_ms)
267 		schedule_delayed_work(&priv->restart_work,
268 				      msecs_to_jiffies(priv->restart_ms));
269 }
270 EXPORT_SYMBOL_GPL(can_bus_off);
271 
272 void can_setup(struct net_device *dev)
273 {
274 	dev->type = ARPHRD_CAN;
275 	dev->mtu = CAN_MTU;
276 	dev->min_mtu = CAN_MTU;
277 	dev->max_mtu = CAN_MTU;
278 	dev->hard_header_len = 0;
279 	dev->addr_len = 0;
280 	dev->tx_queue_len = 10;
281 
282 	/* New-style flags. */
283 	dev->flags = IFF_NOARP;
284 	dev->features = NETIF_F_HW_CSUM;
285 }
286 
287 /* Allocate and setup space for the CAN network device */
288 struct net_device *alloc_candev_mqs(int sizeof_priv, unsigned int echo_skb_max,
289 				    unsigned int txqs, unsigned int rxqs)
290 {
291 	struct can_ml_priv *can_ml;
292 	struct net_device *dev;
293 	struct can_priv *priv;
294 	int size;
295 
296 	/* We put the driver's priv, the CAN mid layer priv and the
297 	 * echo skb into the netdevice's priv. The memory layout for
298 	 * the netdev_priv is like this:
299 	 *
300 	 * +-------------------------+
301 	 * | driver's priv           |
302 	 * +-------------------------+
303 	 * | struct can_ml_priv      |
304 	 * +-------------------------+
305 	 * | array of struct sk_buff |
306 	 * +-------------------------+
307 	 */
308 
309 	size = ALIGN(sizeof_priv, NETDEV_ALIGN) + sizeof(struct can_ml_priv);
310 
311 	if (echo_skb_max)
312 		size = ALIGN(size, sizeof(struct sk_buff *)) +
313 			echo_skb_max * sizeof(struct sk_buff *);
314 
315 	dev = alloc_netdev_mqs(size, "can%d", NET_NAME_UNKNOWN, can_setup,
316 			       txqs, rxqs);
317 	if (!dev)
318 		return NULL;
319 
320 	priv = netdev_priv(dev);
321 	priv->dev = dev;
322 
323 	can_ml = (void *)priv + ALIGN(sizeof_priv, NETDEV_ALIGN);
324 	can_set_ml_priv(dev, can_ml);
325 
326 	if (echo_skb_max) {
327 		priv->echo_skb_max = echo_skb_max;
328 		priv->echo_skb = (void *)priv +
329 			(size - echo_skb_max * sizeof(struct sk_buff *));
330 	}
331 
332 	priv->state = CAN_STATE_STOPPED;
333 
334 	INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
335 
336 	return dev;
337 }
338 EXPORT_SYMBOL_GPL(alloc_candev_mqs);
339 
340 /* Free space of the CAN network device */
341 void free_candev(struct net_device *dev)
342 {
343 	free_netdev(dev);
344 }
345 EXPORT_SYMBOL_GPL(free_candev);
346 
347 void can_set_default_mtu(struct net_device *dev)
348 {
349 	struct can_priv *priv = netdev_priv(dev);
350 
351 	if (priv->ctrlmode & CAN_CTRLMODE_FD) {
352 		dev->mtu = CANFD_MTU;
353 		dev->min_mtu = CANFD_MTU;
354 		dev->max_mtu = CANFD_MTU;
355 	} else {
356 		dev->mtu = CAN_MTU;
357 		dev->min_mtu = CAN_MTU;
358 		dev->max_mtu = CAN_MTU;
359 	}
360 }
361 
362 /* helper to define static CAN controller features at device creation time */
363 int can_set_static_ctrlmode(struct net_device *dev, u32 static_mode)
364 {
365 	struct can_priv *priv = netdev_priv(dev);
366 
367 	/* alloc_candev() succeeded => netdev_priv() is valid at this point */
368 	if (priv->ctrlmode_supported & static_mode) {
369 		netdev_warn(dev,
370 			    "Controller features can not be supported and static at the same time\n");
371 		return -EINVAL;
372 	}
373 	priv->ctrlmode = static_mode;
374 
375 	/* override MTU which was set by default in can_setup()? */
376 	can_set_default_mtu(dev);
377 
378 	return 0;
379 }
380 EXPORT_SYMBOL_GPL(can_set_static_ctrlmode);
381 
382 /* generic implementation of netdev_ops::ndo_hwtstamp_get for CAN devices
383  * supporting hardware timestamps
384  */
385 int can_hwtstamp_get(struct net_device *netdev,
386 		     struct kernel_hwtstamp_config *cfg)
387 {
388 	cfg->tx_type = HWTSTAMP_TX_ON;
389 	cfg->rx_filter = HWTSTAMP_FILTER_ALL;
390 
391 	return 0;
392 }
393 EXPORT_SYMBOL(can_hwtstamp_get);
394 
395 /* generic implementation of netdev_ops::ndo_hwtstamp_set for CAN devices
396  * supporting hardware timestamps
397  */
398 int can_hwtstamp_set(struct net_device *netdev,
399 		     struct kernel_hwtstamp_config *cfg,
400 		     struct netlink_ext_ack *extack)
401 {
402 	if (cfg->tx_type == HWTSTAMP_TX_ON &&
403 	    cfg->rx_filter == HWTSTAMP_FILTER_ALL)
404 		return 0;
405 	NL_SET_ERR_MSG_MOD(extack, "Only TX on and RX all packets filter supported");
406 	return -ERANGE;
407 }
408 EXPORT_SYMBOL(can_hwtstamp_set);
409 
410 /* generic implementation of ethtool_ops::get_ts_info for CAN devices
411  * supporting hardware timestamps
412  */
413 int can_ethtool_op_get_ts_info_hwts(struct net_device *dev,
414 				    struct kernel_ethtool_ts_info *info)
415 {
416 	info->so_timestamping =
417 		SOF_TIMESTAMPING_TX_SOFTWARE |
418 		SOF_TIMESTAMPING_TX_HARDWARE |
419 		SOF_TIMESTAMPING_RX_HARDWARE |
420 		SOF_TIMESTAMPING_RAW_HARDWARE;
421 	info->tx_types = BIT(HWTSTAMP_TX_ON);
422 	info->rx_filters = BIT(HWTSTAMP_FILTER_ALL);
423 
424 	return 0;
425 }
426 EXPORT_SYMBOL(can_ethtool_op_get_ts_info_hwts);
427 
428 /* Common open function when the device gets opened.
429  *
430  * This function should be called in the open function of the device
431  * driver.
432  */
433 int open_candev(struct net_device *dev)
434 {
435 	struct can_priv *priv = netdev_priv(dev);
436 
437 	if (!priv->bittiming.bitrate) {
438 		netdev_err(dev, "bit-timing not yet defined\n");
439 		return -EINVAL;
440 	}
441 
442 	/* For CAN FD the data bitrate has to be >= the arbitration bitrate */
443 	if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
444 	    (!priv->fd.data_bittiming.bitrate ||
445 	     priv->fd.data_bittiming.bitrate < priv->bittiming.bitrate)) {
446 		netdev_err(dev, "incorrect/missing data bit-timing\n");
447 		return -EINVAL;
448 	}
449 
450 	/* Switch carrier on if device was stopped while in bus-off state */
451 	if (!netif_carrier_ok(dev))
452 		netif_carrier_on(dev);
453 
454 	return 0;
455 }
456 EXPORT_SYMBOL_GPL(open_candev);
457 
458 #ifdef CONFIG_OF
459 /* Common function that can be used to understand the limitation of
460  * a transceiver when it provides no means to determine these limitations
461  * at runtime.
462  */
463 void of_can_transceiver(struct net_device *dev)
464 {
465 	struct device_node *dn;
466 	struct can_priv *priv = netdev_priv(dev);
467 	struct device_node *np = dev->dev.parent->of_node;
468 	int ret;
469 
470 	dn = of_get_child_by_name(np, "can-transceiver");
471 	if (!dn)
472 		return;
473 
474 	ret = of_property_read_u32(dn, "max-bitrate", &priv->bitrate_max);
475 	of_node_put(dn);
476 	if ((ret && ret != -EINVAL) || (!ret && !priv->bitrate_max))
477 		netdev_warn(dev, "Invalid value for transceiver max bitrate. Ignoring bitrate limit.\n");
478 }
479 EXPORT_SYMBOL_GPL(of_can_transceiver);
480 #endif
481 
482 /* Common close function for cleanup before the device gets closed.
483  *
484  * This function should be called in the close function of the device
485  * driver.
486  */
487 void close_candev(struct net_device *dev)
488 {
489 	struct can_priv *priv = netdev_priv(dev);
490 
491 	cancel_delayed_work_sync(&priv->restart_work);
492 	can_flush_echo_skb(dev);
493 }
494 EXPORT_SYMBOL_GPL(close_candev);
495 
496 static int can_set_termination(struct net_device *ndev, u16 term)
497 {
498 	struct can_priv *priv = netdev_priv(ndev);
499 	int set;
500 
501 	if (term == priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED])
502 		set = 1;
503 	else
504 		set = 0;
505 
506 	gpiod_set_value_cansleep(priv->termination_gpio, set);
507 
508 	return 0;
509 }
510 
511 static int can_get_termination(struct net_device *ndev)
512 {
513 	struct can_priv *priv = netdev_priv(ndev);
514 	struct device *dev = ndev->dev.parent;
515 	struct gpio_desc *gpio;
516 	u32 term;
517 	int ret;
518 
519 	/* Disabling termination by default is the safe choice: Else if many
520 	 * bus participants enable it, no communication is possible at all.
521 	 */
522 	gpio = devm_gpiod_get_optional(dev, "termination", GPIOD_OUT_LOW);
523 	if (IS_ERR(gpio))
524 		return dev_err_probe(dev, PTR_ERR(gpio),
525 				     "Cannot get termination-gpios\n");
526 
527 	if (!gpio)
528 		return 0;
529 
530 	ret = device_property_read_u32(dev, "termination-ohms", &term);
531 	if (ret) {
532 		netdev_err(ndev, "Cannot get termination-ohms: %pe\n",
533 			   ERR_PTR(ret));
534 		return ret;
535 	}
536 
537 	if (term > U16_MAX) {
538 		netdev_err(ndev, "Invalid termination-ohms value (%u > %u)\n",
539 			   term, U16_MAX);
540 		return -EINVAL;
541 	}
542 
543 	priv->termination_const_cnt = ARRAY_SIZE(priv->termination_gpio_ohms);
544 	priv->termination_const = priv->termination_gpio_ohms;
545 	priv->termination_gpio = gpio;
546 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_DISABLED] =
547 		CAN_TERMINATION_DISABLED;
548 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED] = term;
549 	priv->do_set_termination = can_set_termination;
550 
551 	return 0;
552 }
553 
554 static bool
555 can_bittiming_const_valid(const struct can_bittiming_const *btc)
556 {
557 	if (!btc)
558 		return true;
559 
560 	if (!btc->sjw_max)
561 		return false;
562 
563 	return true;
564 }
565 
566 /* Register the CAN network device */
567 int register_candev(struct net_device *dev)
568 {
569 	struct can_priv *priv = netdev_priv(dev);
570 	int err;
571 
572 	/* Ensure termination_const, termination_const_cnt and
573 	 * do_set_termination consistency. All must be either set or
574 	 * unset.
575 	 */
576 	if ((!priv->termination_const != !priv->termination_const_cnt) ||
577 	    (!priv->termination_const != !priv->do_set_termination))
578 		return -EINVAL;
579 
580 	if (!priv->bitrate_const != !priv->bitrate_const_cnt)
581 		return -EINVAL;
582 
583 	if (!priv->fd.data_bitrate_const != !priv->fd.data_bitrate_const_cnt)
584 		return -EINVAL;
585 
586 	/* We only support either fixed bit rates or bit timing const. */
587 	if ((priv->bitrate_const || priv->fd.data_bitrate_const) &&
588 	    (priv->bittiming_const || priv->fd.data_bittiming_const))
589 		return -EINVAL;
590 
591 	if (!can_bittiming_const_valid(priv->bittiming_const) ||
592 	    !can_bittiming_const_valid(priv->fd.data_bittiming_const))
593 		return -EINVAL;
594 
595 	if (!priv->termination_const) {
596 		err = can_get_termination(dev);
597 		if (err)
598 			return err;
599 	}
600 
601 	dev->rtnl_link_ops = &can_link_ops;
602 	netif_carrier_off(dev);
603 
604 	return register_netdev(dev);
605 }
606 EXPORT_SYMBOL_GPL(register_candev);
607 
608 /* Unregister the CAN network device */
609 void unregister_candev(struct net_device *dev)
610 {
611 	unregister_netdev(dev);
612 }
613 EXPORT_SYMBOL_GPL(unregister_candev);
614 
615 /* Test if a network device is a candev based device
616  * and return the can_priv* if so.
617  */
618 struct can_priv *safe_candev_priv(struct net_device *dev)
619 {
620 	if (dev->type != ARPHRD_CAN || dev->rtnl_link_ops != &can_link_ops)
621 		return NULL;
622 
623 	return netdev_priv(dev);
624 }
625 EXPORT_SYMBOL_GPL(safe_candev_priv);
626 
627 static __init int can_dev_init(void)
628 {
629 	int err;
630 
631 	err = can_netlink_register();
632 	if (!err)
633 		pr_info("CAN device driver interface\n");
634 
635 	return err;
636 }
637 module_init(can_dev_init);
638 
639 static __exit void can_dev_exit(void)
640 {
641 	can_netlink_unregister();
642 }
643 module_exit(can_dev_exit);
644 
645 MODULE_ALIAS_RTNL_LINK("can");
646