xref: /linux-6.15/drivers/net/can/dev/dev.c (revision fe5c9940)
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 <[email protected]>
5  */
6 
7 #include <linux/kernel.h>
8 #include <linux/slab.h>
9 #include <linux/netdevice.h>
10 #include <linux/if_arp.h>
11 #include <linux/workqueue.h>
12 #include <linux/can.h>
13 #include <linux/can/can-ml.h>
14 #include <linux/can/dev.h>
15 #include <linux/can/skb.h>
16 #include <linux/gpio/consumer.h>
17 #include <linux/of.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 	return "<unknown>";
90 }
91 EXPORT_SYMBOL_GPL(can_get_state_str);
92 
93 void can_change_state(struct net_device *dev, struct can_frame *cf,
94 		      enum can_state tx_state, enum can_state rx_state)
95 {
96 	struct can_priv *priv = netdev_priv(dev);
97 	enum can_state new_state = max(tx_state, rx_state);
98 
99 	if (unlikely(new_state == priv->state)) {
100 		netdev_warn(dev, "%s: oops, state did not change", __func__);
101 		return;
102 	}
103 
104 	netdev_dbg(dev, "Controller changed from %s State (%d) into %s State (%d).\n",
105 		   can_get_state_str(priv->state), priv->state,
106 		   can_get_state_str(new_state), new_state);
107 
108 	can_update_state_error_stats(dev, new_state);
109 	priv->state = new_state;
110 
111 	if (!cf)
112 		return;
113 
114 	if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
115 		cf->can_id |= CAN_ERR_BUSOFF;
116 		return;
117 	}
118 
119 	cf->can_id |= CAN_ERR_CRTL;
120 	cf->data[1] |= tx_state >= rx_state ?
121 		       can_tx_state_to_frame(dev, tx_state) : 0;
122 	cf->data[1] |= tx_state <= rx_state ?
123 		       can_rx_state_to_frame(dev, rx_state) : 0;
124 }
125 EXPORT_SYMBOL_GPL(can_change_state);
126 
127 /* CAN device restart for bus-off recovery */
128 static void can_restart(struct net_device *dev)
129 {
130 	struct can_priv *priv = netdev_priv(dev);
131 	struct sk_buff *skb;
132 	struct can_frame *cf;
133 	int err;
134 
135 	if (netif_carrier_ok(dev))
136 		netdev_err(dev, "Attempt to restart for bus-off recovery, but carrier is OK?\n");
137 
138 	/* No synchronization needed because the device is bus-off and
139 	 * no messages can come in or go out.
140 	 */
141 	can_flush_echo_skb(dev);
142 
143 	/* send restart message upstream */
144 	skb = alloc_can_err_skb(dev, &cf);
145 	if (!skb)
146 		goto restart;
147 
148 	cf->can_id |= CAN_ERR_RESTARTED;
149 
150 	netif_rx(skb);
151 
152 restart:
153 	netdev_dbg(dev, "restarted\n");
154 	priv->can_stats.restarts++;
155 
156 	/* Now restart the device */
157 	err = priv->do_set_mode(dev, CAN_MODE_START);
158 
159 	netif_carrier_on(dev);
160 	if (err)
161 		netdev_err(dev, "Error %d during restart", err);
162 }
163 
164 static void can_restart_work(struct work_struct *work)
165 {
166 	struct delayed_work *dwork = to_delayed_work(work);
167 	struct can_priv *priv = container_of(dwork, struct can_priv,
168 					     restart_work);
169 
170 	can_restart(priv->dev);
171 }
172 
173 int can_restart_now(struct net_device *dev)
174 {
175 	struct can_priv *priv = netdev_priv(dev);
176 
177 	/* A manual restart is only permitted if automatic restart is
178 	 * disabled and the device is in the bus-off state
179 	 */
180 	if (priv->restart_ms)
181 		return -EINVAL;
182 	if (priv->state != CAN_STATE_BUS_OFF)
183 		return -EBUSY;
184 
185 	cancel_delayed_work_sync(&priv->restart_work);
186 	can_restart(dev);
187 
188 	return 0;
189 }
190 
191 /* CAN bus-off
192  *
193  * This functions should be called when the device goes bus-off to
194  * tell the netif layer that no more packets can be sent or received.
195  * If enabled, a timer is started to trigger bus-off recovery.
196  */
197 void can_bus_off(struct net_device *dev)
198 {
199 	struct can_priv *priv = netdev_priv(dev);
200 
201 	if (priv->restart_ms)
202 		netdev_info(dev, "bus-off, scheduling restart in %d ms\n",
203 			    priv->restart_ms);
204 	else
205 		netdev_info(dev, "bus-off\n");
206 
207 	netif_carrier_off(dev);
208 
209 	if (priv->restart_ms)
210 		schedule_delayed_work(&priv->restart_work,
211 				      msecs_to_jiffies(priv->restart_ms));
212 }
213 EXPORT_SYMBOL_GPL(can_bus_off);
214 
215 void can_setup(struct net_device *dev)
216 {
217 	dev->type = ARPHRD_CAN;
218 	dev->mtu = CAN_MTU;
219 	dev->hard_header_len = 0;
220 	dev->addr_len = 0;
221 	dev->tx_queue_len = 10;
222 
223 	/* New-style flags. */
224 	dev->flags = IFF_NOARP;
225 	dev->features = NETIF_F_HW_CSUM;
226 }
227 
228 /* Allocate and setup space for the CAN network device */
229 struct net_device *alloc_candev_mqs(int sizeof_priv, unsigned int echo_skb_max,
230 				    unsigned int txqs, unsigned int rxqs)
231 {
232 	struct can_ml_priv *can_ml;
233 	struct net_device *dev;
234 	struct can_priv *priv;
235 	int size;
236 
237 	/* We put the driver's priv, the CAN mid layer priv and the
238 	 * echo skb into the netdevice's priv. The memory layout for
239 	 * the netdev_priv is like this:
240 	 *
241 	 * +-------------------------+
242 	 * | driver's priv           |
243 	 * +-------------------------+
244 	 * | struct can_ml_priv      |
245 	 * +-------------------------+
246 	 * | array of struct sk_buff |
247 	 * +-------------------------+
248 	 */
249 
250 	size = ALIGN(sizeof_priv, NETDEV_ALIGN) + sizeof(struct can_ml_priv);
251 
252 	if (echo_skb_max)
253 		size = ALIGN(size, sizeof(struct sk_buff *)) +
254 			echo_skb_max * sizeof(struct sk_buff *);
255 
256 	dev = alloc_netdev_mqs(size, "can%d", NET_NAME_UNKNOWN, can_setup,
257 			       txqs, rxqs);
258 	if (!dev)
259 		return NULL;
260 
261 	priv = netdev_priv(dev);
262 	priv->dev = dev;
263 
264 	can_ml = (void *)priv + ALIGN(sizeof_priv, NETDEV_ALIGN);
265 	can_set_ml_priv(dev, can_ml);
266 
267 	if (echo_skb_max) {
268 		priv->echo_skb_max = echo_skb_max;
269 		priv->echo_skb = (void *)priv +
270 			(size - echo_skb_max * sizeof(struct sk_buff *));
271 	}
272 
273 	priv->state = CAN_STATE_STOPPED;
274 
275 	INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
276 
277 	return dev;
278 }
279 EXPORT_SYMBOL_GPL(alloc_candev_mqs);
280 
281 /* Free space of the CAN network device */
282 void free_candev(struct net_device *dev)
283 {
284 	free_netdev(dev);
285 }
286 EXPORT_SYMBOL_GPL(free_candev);
287 
288 /* changing MTU and control mode for CAN/CANFD devices */
289 int can_change_mtu(struct net_device *dev, int new_mtu)
290 {
291 	struct can_priv *priv = netdev_priv(dev);
292 	u32 ctrlmode_static = can_get_static_ctrlmode(priv);
293 
294 	/* Do not allow changing the MTU while running */
295 	if (dev->flags & IFF_UP)
296 		return -EBUSY;
297 
298 	/* allow change of MTU according to the CANFD ability of the device */
299 	switch (new_mtu) {
300 	case CAN_MTU:
301 		/* 'CANFD-only' controllers can not switch to CAN_MTU */
302 		if (ctrlmode_static & CAN_CTRLMODE_FD)
303 			return -EINVAL;
304 
305 		priv->ctrlmode &= ~CAN_CTRLMODE_FD;
306 		break;
307 
308 	case CANFD_MTU:
309 		/* check for potential CANFD ability */
310 		if (!(priv->ctrlmode_supported & CAN_CTRLMODE_FD) &&
311 		    !(ctrlmode_static & CAN_CTRLMODE_FD))
312 			return -EINVAL;
313 
314 		priv->ctrlmode |= CAN_CTRLMODE_FD;
315 		break;
316 
317 	default:
318 		return -EINVAL;
319 	}
320 
321 	dev->mtu = new_mtu;
322 	return 0;
323 }
324 EXPORT_SYMBOL_GPL(can_change_mtu);
325 
326 /* generic implementation of netdev_ops::ndo_eth_ioctl for CAN devices
327  * supporting hardware timestamps
328  */
329 int can_eth_ioctl_hwts(struct net_device *netdev, struct ifreq *ifr, int cmd)
330 {
331 	struct hwtstamp_config hwts_cfg = { 0 };
332 
333 	switch (cmd) {
334 	case SIOCSHWTSTAMP: /* set */
335 		if (copy_from_user(&hwts_cfg, ifr->ifr_data, sizeof(hwts_cfg)))
336 			return -EFAULT;
337 		if (hwts_cfg.tx_type == HWTSTAMP_TX_ON &&
338 		    hwts_cfg.rx_filter == HWTSTAMP_FILTER_ALL)
339 			return 0;
340 		return -ERANGE;
341 
342 	case SIOCGHWTSTAMP: /* get */
343 		hwts_cfg.tx_type = HWTSTAMP_TX_ON;
344 		hwts_cfg.rx_filter = HWTSTAMP_FILTER_ALL;
345 		if (copy_to_user(ifr->ifr_data, &hwts_cfg, sizeof(hwts_cfg)))
346 			return -EFAULT;
347 		return 0;
348 
349 	default:
350 		return -EOPNOTSUPP;
351 	}
352 }
353 EXPORT_SYMBOL(can_eth_ioctl_hwts);
354 
355 /* generic implementation of ethtool_ops::get_ts_info for CAN devices
356  * supporting hardware timestamps
357  */
358 int can_ethtool_op_get_ts_info_hwts(struct net_device *dev,
359 				    struct ethtool_ts_info *info)
360 {
361 	info->so_timestamping =
362 		SOF_TIMESTAMPING_TX_SOFTWARE |
363 		SOF_TIMESTAMPING_RX_SOFTWARE |
364 		SOF_TIMESTAMPING_SOFTWARE |
365 		SOF_TIMESTAMPING_TX_HARDWARE |
366 		SOF_TIMESTAMPING_RX_HARDWARE |
367 		SOF_TIMESTAMPING_RAW_HARDWARE;
368 	info->phc_index = -1;
369 	info->tx_types = BIT(HWTSTAMP_TX_ON);
370 	info->rx_filters = BIT(HWTSTAMP_FILTER_ALL);
371 
372 	return 0;
373 }
374 EXPORT_SYMBOL(can_ethtool_op_get_ts_info_hwts);
375 
376 /* Common open function when the device gets opened.
377  *
378  * This function should be called in the open function of the device
379  * driver.
380  */
381 int open_candev(struct net_device *dev)
382 {
383 	struct can_priv *priv = netdev_priv(dev);
384 
385 	if (!priv->bittiming.bitrate) {
386 		netdev_err(dev, "bit-timing not yet defined\n");
387 		return -EINVAL;
388 	}
389 
390 	/* For CAN FD the data bitrate has to be >= the arbitration bitrate */
391 	if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
392 	    (!priv->data_bittiming.bitrate ||
393 	     priv->data_bittiming.bitrate < priv->bittiming.bitrate)) {
394 		netdev_err(dev, "incorrect/missing data bit-timing\n");
395 		return -EINVAL;
396 	}
397 
398 	/* Switch carrier on if device was stopped while in bus-off state */
399 	if (!netif_carrier_ok(dev))
400 		netif_carrier_on(dev);
401 
402 	return 0;
403 }
404 EXPORT_SYMBOL_GPL(open_candev);
405 
406 #ifdef CONFIG_OF
407 /* Common function that can be used to understand the limitation of
408  * a transceiver when it provides no means to determine these limitations
409  * at runtime.
410  */
411 void of_can_transceiver(struct net_device *dev)
412 {
413 	struct device_node *dn;
414 	struct can_priv *priv = netdev_priv(dev);
415 	struct device_node *np = dev->dev.parent->of_node;
416 	int ret;
417 
418 	dn = of_get_child_by_name(np, "can-transceiver");
419 	if (!dn)
420 		return;
421 
422 	ret = of_property_read_u32(dn, "max-bitrate", &priv->bitrate_max);
423 	of_node_put(dn);
424 	if ((ret && ret != -EINVAL) || (!ret && !priv->bitrate_max))
425 		netdev_warn(dev, "Invalid value for transceiver max bitrate. Ignoring bitrate limit.\n");
426 }
427 EXPORT_SYMBOL_GPL(of_can_transceiver);
428 #endif
429 
430 /* Common close function for cleanup before the device gets closed.
431  *
432  * This function should be called in the close function of the device
433  * driver.
434  */
435 void close_candev(struct net_device *dev)
436 {
437 	struct can_priv *priv = netdev_priv(dev);
438 
439 	cancel_delayed_work_sync(&priv->restart_work);
440 	can_flush_echo_skb(dev);
441 }
442 EXPORT_SYMBOL_GPL(close_candev);
443 
444 static int can_set_termination(struct net_device *ndev, u16 term)
445 {
446 	struct can_priv *priv = netdev_priv(ndev);
447 	int set;
448 
449 	if (term == priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED])
450 		set = 1;
451 	else
452 		set = 0;
453 
454 	gpiod_set_value(priv->termination_gpio, set);
455 
456 	return 0;
457 }
458 
459 static int can_get_termination(struct net_device *ndev)
460 {
461 	struct can_priv *priv = netdev_priv(ndev);
462 	struct device *dev = ndev->dev.parent;
463 	struct gpio_desc *gpio;
464 	u32 term;
465 	int ret;
466 
467 	/* Disabling termination by default is the safe choice: Else if many
468 	 * bus participants enable it, no communication is possible at all.
469 	 */
470 	gpio = devm_gpiod_get_optional(dev, "termination", GPIOD_OUT_LOW);
471 	if (IS_ERR(gpio))
472 		return dev_err_probe(dev, PTR_ERR(gpio),
473 				     "Cannot get termination-gpios\n");
474 
475 	if (!gpio)
476 		return 0;
477 
478 	ret = device_property_read_u32(dev, "termination-ohms", &term);
479 	if (ret) {
480 		netdev_err(ndev, "Cannot get termination-ohms: %pe\n",
481 			   ERR_PTR(ret));
482 		return ret;
483 	}
484 
485 	if (term > U16_MAX) {
486 		netdev_err(ndev, "Invalid termination-ohms value (%u > %u)\n",
487 			   term, U16_MAX);
488 		return -EINVAL;
489 	}
490 
491 	priv->termination_const_cnt = ARRAY_SIZE(priv->termination_gpio_ohms);
492 	priv->termination_const = priv->termination_gpio_ohms;
493 	priv->termination_gpio = gpio;
494 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_DISABLED] =
495 		CAN_TERMINATION_DISABLED;
496 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED] = term;
497 	priv->do_set_termination = can_set_termination;
498 
499 	return 0;
500 }
501 
502 static bool
503 can_bittiming_const_valid(const struct can_bittiming_const *btc)
504 {
505 	if (!btc)
506 		return true;
507 
508 	if (!btc->sjw_max)
509 		return false;
510 
511 	return true;
512 }
513 
514 /* Register the CAN network device */
515 int register_candev(struct net_device *dev)
516 {
517 	struct can_priv *priv = netdev_priv(dev);
518 	int err;
519 
520 	/* Ensure termination_const, termination_const_cnt and
521 	 * do_set_termination consistency. All must be either set or
522 	 * unset.
523 	 */
524 	if ((!priv->termination_const != !priv->termination_const_cnt) ||
525 	    (!priv->termination_const != !priv->do_set_termination))
526 		return -EINVAL;
527 
528 	if (!priv->bitrate_const != !priv->bitrate_const_cnt)
529 		return -EINVAL;
530 
531 	if (!priv->data_bitrate_const != !priv->data_bitrate_const_cnt)
532 		return -EINVAL;
533 
534 	/* We only support either fixed bit rates or bit timing const. */
535 	if ((priv->bitrate_const || priv->data_bitrate_const) &&
536 	    (priv->bittiming_const || priv->data_bittiming_const))
537 		return -EINVAL;
538 
539 	if (!can_bittiming_const_valid(priv->bittiming_const) ||
540 	    !can_bittiming_const_valid(priv->data_bittiming_const))
541 		return -EINVAL;
542 
543 	if (!priv->termination_const) {
544 		err = can_get_termination(dev);
545 		if (err)
546 			return err;
547 	}
548 
549 	dev->rtnl_link_ops = &can_link_ops;
550 	netif_carrier_off(dev);
551 
552 	return register_netdev(dev);
553 }
554 EXPORT_SYMBOL_GPL(register_candev);
555 
556 /* Unregister the CAN network device */
557 void unregister_candev(struct net_device *dev)
558 {
559 	unregister_netdev(dev);
560 }
561 EXPORT_SYMBOL_GPL(unregister_candev);
562 
563 /* Test if a network device is a candev based device
564  * and return the can_priv* if so.
565  */
566 struct can_priv *safe_candev_priv(struct net_device *dev)
567 {
568 	if (dev->type != ARPHRD_CAN || dev->rtnl_link_ops != &can_link_ops)
569 		return NULL;
570 
571 	return netdev_priv(dev);
572 }
573 EXPORT_SYMBOL_GPL(safe_candev_priv);
574 
575 static __init int can_dev_init(void)
576 {
577 	int err;
578 
579 	err = can_netlink_register();
580 	if (!err)
581 		pr_info("CAN device driver interface\n");
582 
583 	return err;
584 }
585 module_init(can_dev_init);
586 
587 static __exit void can_dev_exit(void)
588 {
589 	can_netlink_unregister();
590 }
591 module_exit(can_dev_exit);
592 
593 MODULE_ALIAS_RTNL_LINK("can");
594